|
| 1 | +""" |
| 2 | +An ASGI middleware. |
| 3 | +
|
| 4 | +Based on Tom Christie's `sentry-asgi <https://github.com/encode/sentry-asgi>`_. |
| 5 | +""" |
| 6 | + |
| 7 | +import functools |
| 8 | +import urllib |
| 9 | + |
| 10 | +from sentry_sdk._types import MYPY |
| 11 | +from sentry_sdk.hub import Hub, _should_send_default_pii |
| 12 | +from sentry_sdk.integrations._wsgi_common import _filter_headers |
| 13 | +from sentry_sdk.utils import transaction_from_function |
| 14 | + |
| 15 | +if MYPY: |
| 16 | + from typing import Dict |
| 17 | + |
| 18 | + |
| 19 | +class SentryAsgiMiddleware: |
| 20 | + __slots__ = ("app",) |
| 21 | + |
| 22 | + def __init__(self, app): |
| 23 | + self.app = app |
| 24 | + |
| 25 | + def __call__(self, scope, receive=None, send=None): |
| 26 | + if receive is None or send is None: |
| 27 | + |
| 28 | + async def run_asgi2(receive, send): |
| 29 | + return await self._run_app( |
| 30 | + scope, lambda: self.app(scope)(receive, send) |
| 31 | + ) |
| 32 | + |
| 33 | + return run_asgi2 |
| 34 | + else: |
| 35 | + return self._run_app(scope, lambda: self.app(scope, receive, send)) |
| 36 | + |
| 37 | + async def _run_app(self, scope, callback): |
| 38 | + hub = Hub.current |
| 39 | + with Hub(hub) as hub: |
| 40 | + with hub.configure_scope() as sentry_scope: |
| 41 | + sentry_scope._name = "asgi" |
| 42 | + sentry_scope.transaction = scope.get("path") or "unknown asgi request" |
| 43 | + |
| 44 | + processor = functools.partial(self.event_processor, asgi_scope=scope) |
| 45 | + sentry_scope.add_event_processor(processor) |
| 46 | + |
| 47 | + try: |
| 48 | + await callback() |
| 49 | + except Exception as exc: |
| 50 | + hub.capture_exception(exc) |
| 51 | + raise exc from None |
| 52 | + |
| 53 | + def event_processor(self, event, hint, asgi_scope): |
| 54 | + request_info = event.setdefault("request", {}) |
| 55 | + |
| 56 | + if asgi_scope["type"] in ("http", "websocket"): |
| 57 | + request_info["url"] = self.get_url(asgi_scope) |
| 58 | + request_info["method"] = asgi_scope["method"] |
| 59 | + request_info["headers"] = _filter_headers(self.get_headers(asgi_scope)) |
| 60 | + request_info["query_string"] = self.get_query(asgi_scope) |
| 61 | + |
| 62 | + if asgi_scope.get("client") and _should_send_default_pii(): |
| 63 | + request_info["env"] = {"REMOTE_ADDR": asgi_scope["client"][0]} |
| 64 | + |
| 65 | + if asgi_scope.get("endpoint"): |
| 66 | + # Webframeworks like Starlette mutate the ASGI env once routing is |
| 67 | + # done, which is sometime after the request has started. If we have |
| 68 | + # an endpoint, overwrite our path-based transaction name. |
| 69 | + event["transaction"] = self.get_transaction(asgi_scope) |
| 70 | + return event |
| 71 | + |
| 72 | + def get_url(self, scope): |
| 73 | + """ |
| 74 | + Extract URL from the ASGI scope, without also including the querystring. |
| 75 | + """ |
| 76 | + scheme = scope.get("scheme", "http") |
| 77 | + server = scope.get("server", None) |
| 78 | + path = scope.get("root_path", "") + scope["path"] |
| 79 | + |
| 80 | + for key, value in scope["headers"]: |
| 81 | + if key == b"host": |
| 82 | + host_header = value.decode("latin-1") |
| 83 | + return "%s://%s%s" % (scheme, host_header, path) |
| 84 | + |
| 85 | + if server is not None: |
| 86 | + host, port = server |
| 87 | + default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme] |
| 88 | + if port != default_port: |
| 89 | + return "%s://%s:%s%s" % (scheme, host, port, path) |
| 90 | + return "%s://%s%s" % (scheme, host, path) |
| 91 | + return path |
| 92 | + |
| 93 | + def get_query(self, scope): |
| 94 | + """ |
| 95 | + Extract querystring from the ASGI scope, in the format that the Sentry protocol expects. |
| 96 | + """ |
| 97 | + return urllib.parse.unquote(scope["query_string"].decode("latin-1")) |
| 98 | + |
| 99 | + def get_headers(self, scope): |
| 100 | + """ |
| 101 | + Extract headers from the ASGI scope, in the format that the Sentry protocol expects. |
| 102 | + """ |
| 103 | + headers = {} # type: Dict[str, str] |
| 104 | + for raw_key, raw_value in scope["headers"]: |
| 105 | + key = raw_key.decode("latin-1") |
| 106 | + value = raw_value.decode("latin-1") |
| 107 | + if key in headers: |
| 108 | + headers[key] = headers[key] + ", " + value |
| 109 | + else: |
| 110 | + headers[key] = value |
| 111 | + return headers |
| 112 | + |
| 113 | + def get_transaction(self, scope): |
| 114 | + """ |
| 115 | + Return a transaction string to identify the routed endpoint. |
| 116 | + """ |
| 117 | + return transaction_from_function(scope["endpoint"]) |
0 commit comments