|
| 1 | +"""Automatic duration metrics for the HTTP requests an application makes. |
| 2 | +
|
| 3 | +Enabled with the ``metrics={"network": ...}`` client option. Wraps |
| 4 | +``requests.Session.send`` and, when httpx is installed, ``httpx.Client.send`` |
| 5 | +and ``httpx.AsyncClient.send``. The wrappers only observe: they call the |
| 6 | +original with the same arguments, return its result or re-raise its error, |
| 7 | +and never let a recording failure reach the caller. The SDK marks its own |
| 8 | +sessions with ``_mark_internal`` so PostHog's uploads are not recorded. |
| 9 | +""" |
| 10 | + |
| 11 | +import contextvars |
| 12 | +import functools |
| 13 | +import logging |
| 14 | +import re |
| 15 | +import time |
| 16 | +from typing import Any, Callable, List, Optional, Tuple |
| 17 | +from urllib.parse import urlsplit |
| 18 | + |
| 19 | +import requests |
| 20 | + |
| 21 | +try: |
| 22 | + import httpx |
| 23 | +except ImportError: # pragma: no cover |
| 24 | + httpx = None |
| 25 | + |
| 26 | +log = logging.getLogger("posthog") |
| 27 | + |
| 28 | +DEFAULT_METRIC_NAME = "http.client.request.duration" |
| 29 | + |
| 30 | +_INTERNAL_MARKER = "_posthog_internal" |
| 31 | + |
| 32 | +# ``requests`` sends each redirect hop through ``Session.send`` again. Only the |
| 33 | +# outermost send in a thread or task is recorded, so a redirected request counts once. |
| 34 | +_in_flight: contextvars.ContextVar[bool] = contextvars.ContextVar( |
| 35 | + "posthog_network_metrics_in_flight", default=False |
| 36 | +) |
| 37 | + |
| 38 | +_ALL_DIGITS = re.compile(r"^\d+$") |
| 39 | +_HEX_WITH_A_DIGIT = re.compile(r"^[0-9a-f-]*\d[0-9a-f-]*$", re.IGNORECASE) |
| 40 | + |
| 41 | + |
| 42 | +def _mark_internal(http_client): |
| 43 | + """Marks a ``requests.Session`` or httpx client as the SDK's own. |
| 44 | +
|
| 45 | + Its requests are never recorded as network metrics. |
| 46 | + """ |
| 47 | + setattr(http_client, _INTERNAL_MARKER, True) |
| 48 | + return http_client |
| 49 | + |
| 50 | + |
| 51 | +def _is_internal(http_client) -> bool: |
| 52 | + return getattr(http_client, _INTERNAL_MARKER, False) is True |
| 53 | + |
| 54 | + |
| 55 | +def _is_id_like(segment: str) -> bool: |
| 56 | + return bool(_ALL_DIGITS.match(segment)) or ( |
| 57 | + len(segment) >= 8 and bool(_HEX_WITH_A_DIGIT.match(segment)) |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +def _template_path(path: str) -> str: |
| 62 | + """Replaces each all-digit or uuid-like path segment with ``:id``.""" |
| 63 | + return "/".join( |
| 64 | + ":id" if _is_id_like(segment) else segment for segment in path.split("/") |
| 65 | + ) |
| 66 | + |
| 67 | + |
| 68 | +def _status_class(status: Optional[int]) -> str: |
| 69 | + return "{}xx".format(status // 100) if status else "missing" |
| 70 | + |
| 71 | + |
| 72 | +def _parse_config(config: Any) -> Tuple[Any, Optional[Callable]]: |
| 73 | + if config is True: |
| 74 | + config = {} |
| 75 | + if not isinstance(config, dict): |
| 76 | + log.warning( |
| 77 | + "Ignoring metrics network config: expected True or a dict, got %s", |
| 78 | + type(config).__name__, |
| 79 | + ) |
| 80 | + config = {} |
| 81 | + name = config.get("name", DEFAULT_METRIC_NAME) |
| 82 | + if not (isinstance(name, str) or callable(name)): |
| 83 | + log.warning("Ignoring metrics network name: expected a string or a callable") |
| 84 | + name = DEFAULT_METRIC_NAME |
| 85 | + attributes = config.get("attributes") |
| 86 | + if attributes is not None and not callable(attributes): |
| 87 | + log.warning("Ignoring metrics network attributes: expected a callable") |
| 88 | + attributes = None |
| 89 | + return name, attributes |
| 90 | + |
| 91 | + |
| 92 | +def _patch(target, attribute: str, make_wrapper: Callable) -> Callable[[], None]: |
| 93 | + original = getattr(target, attribute) |
| 94 | + wrapper = make_wrapper(original) |
| 95 | + setattr(target, attribute, wrapper) |
| 96 | + |
| 97 | + def restore() -> None: |
| 98 | + # Another wrapper layered on top keeps ours in place as a pass-through. |
| 99 | + if getattr(target, attribute) is wrapper: |
| 100 | + setattr(target, attribute, original) |
| 101 | + |
| 102 | + return restore |
| 103 | + |
| 104 | + |
| 105 | +class _NetworkMetrics: |
| 106 | + """Installs the request wrappers for one metrics client; ``stop()`` removes them.""" |
| 107 | + |
| 108 | + def __init__(self, metrics, config: Any): |
| 109 | + self._metrics = metrics |
| 110 | + self._name, self._attributes = _parse_config(config) |
| 111 | + self._active = True |
| 112 | + self._record_error_warned = False |
| 113 | + self._restores: List[Callable[[], None]] = [ |
| 114 | + _patch(requests.Session, "send", self._wrap_sync) |
| 115 | + ] |
| 116 | + if httpx is not None: |
| 117 | + self._restores.append(_patch(httpx.Client, "send", self._wrap_sync)) |
| 118 | + self._restores.append(_patch(httpx.AsyncClient, "send", self._wrap_async)) |
| 119 | + |
| 120 | + def stop(self) -> None: |
| 121 | + self._active = False |
| 122 | + for restore in self._restores: |
| 123 | + restore() |
| 124 | + |
| 125 | + def _observes(self, http_client) -> bool: |
| 126 | + return self._active and not _in_flight.get() and not _is_internal(http_client) |
| 127 | + |
| 128 | + def _wrap_sync(self, original: Callable) -> Callable: |
| 129 | + @functools.wraps(original) |
| 130 | + def send(http_client, request, *args, **kwargs): |
| 131 | + if not self._observes(http_client): |
| 132 | + return original(http_client, request, *args, **kwargs) |
| 133 | + token = _in_flight.set(True) |
| 134 | + start = time.perf_counter() |
| 135 | + try: |
| 136 | + response = original(http_client, request, *args, **kwargs) |
| 137 | + except Exception: |
| 138 | + self._record(request, None, start) |
| 139 | + raise |
| 140 | + finally: |
| 141 | + _in_flight.reset(token) |
| 142 | + self._record(request, response, start) |
| 143 | + return response |
| 144 | + |
| 145 | + return send |
| 146 | + |
| 147 | + def _wrap_async(self, original: Callable) -> Callable: |
| 148 | + @functools.wraps(original) |
| 149 | + async def send(http_client, request, *args, **kwargs): |
| 150 | + if not self._observes(http_client): |
| 151 | + return await original(http_client, request, *args, **kwargs) |
| 152 | + token = _in_flight.set(True) |
| 153 | + start = time.perf_counter() |
| 154 | + try: |
| 155 | + response = await original(http_client, request, *args, **kwargs) |
| 156 | + except Exception: |
| 157 | + self._record(request, None, start) |
| 158 | + raise |
| 159 | + finally: |
| 160 | + _in_flight.reset(token) |
| 161 | + self._record(request, response, start) |
| 162 | + return response |
| 163 | + |
| 164 | + return send |
| 165 | + |
| 166 | + def _record(self, request, response, start: float) -> None: |
| 167 | + try: |
| 168 | + duration_ms = (time.perf_counter() - start) * 1000 |
| 169 | + url = str(request.url) |
| 170 | + parts = urlsplit(url) |
| 171 | + if parts.scheme not in ("http", "https"): |
| 172 | + return |
| 173 | + observed = {"url": url, "method": str(request.method).upper()} |
| 174 | + name = self._name(observed) if callable(self._name) else self._name |
| 175 | + if not name: |
| 176 | + return |
| 177 | + status = getattr(response, "status_code", None) |
| 178 | + attributes = { |
| 179 | + "method": observed["method"], |
| 180 | + "host": parts.hostname or "", |
| 181 | + "path": _template_path(parts.path), |
| 182 | + "status_class": _status_class(status), |
| 183 | + } |
| 184 | + if self._attributes is not None: |
| 185 | + extra = self._attributes( |
| 186 | + observed, {"status": status, "duration_ms": duration_ms} |
| 187 | + ) |
| 188 | + attributes.update(extra or {}) |
| 189 | + self._metrics.histogram(name, duration_ms, unit="ms", attributes=attributes) |
| 190 | + except Exception as e: |
| 191 | + if not self._record_error_warned: |
| 192 | + self._record_error_warned = True |
| 193 | + log.warning("Failed to record network metric: %s", e) |
0 commit comments