|
| 1 | +from __future__ import annotations |
| 2 | +import contextlib |
| 3 | +from typing import Any, TypeVar, Callable, Awaitable, Iterator |
| 4 | + |
| 5 | +from asyncpg.cursor import BaseCursor # type: ignore |
| 6 | + |
| 7 | +from sentry_sdk import Hub |
| 8 | +from sentry_sdk.consts import OP, SPANDATA |
| 9 | +from sentry_sdk.integrations import Integration, DidNotEnable |
| 10 | +from sentry_sdk.tracing import Span |
| 11 | +from sentry_sdk.tracing_utils import record_sql_queries |
| 12 | +from sentry_sdk.utils import parse_version, capture_internal_exceptions |
| 13 | + |
| 14 | +try: |
| 15 | + import asyncpg # type: ignore[import] |
| 16 | + |
| 17 | +except ImportError: |
| 18 | + raise DidNotEnable("asyncpg not installed.") |
| 19 | + |
| 20 | +# asyncpg.__version__ is a string containing the semantic version in the form of "<major>.<minor>.<patch>" |
| 21 | +asyncpg_version = parse_version(asyncpg.__version__) |
| 22 | + |
| 23 | +if asyncpg_version is not None and asyncpg_version < (0, 23, 0): |
| 24 | + raise DidNotEnable("asyncpg >= 0.23.0 required") |
| 25 | + |
| 26 | + |
| 27 | +class AsyncPGIntegration(Integration): |
| 28 | + identifier = "asyncpg" |
| 29 | + _record_params = False |
| 30 | + |
| 31 | + def __init__(self, *, record_params: bool = False): |
| 32 | + AsyncPGIntegration._record_params = record_params |
| 33 | + |
| 34 | + @staticmethod |
| 35 | + def setup_once() -> None: |
| 36 | + asyncpg.Connection.execute = _wrap_execute( |
| 37 | + asyncpg.Connection.execute, |
| 38 | + ) |
| 39 | + |
| 40 | + asyncpg.Connection._execute = _wrap_connection_method( |
| 41 | + asyncpg.Connection._execute |
| 42 | + ) |
| 43 | + asyncpg.Connection._executemany = _wrap_connection_method( |
| 44 | + asyncpg.Connection._executemany, executemany=True |
| 45 | + ) |
| 46 | + asyncpg.Connection.cursor = _wrap_cursor_creation(asyncpg.Connection.cursor) |
| 47 | + asyncpg.Connection.prepare = _wrap_connection_method(asyncpg.Connection.prepare) |
| 48 | + asyncpg.connect_utils._connect_addr = _wrap_connect_addr( |
| 49 | + asyncpg.connect_utils._connect_addr |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +T = TypeVar("T") |
| 54 | + |
| 55 | + |
| 56 | +def _wrap_execute(f: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]: |
| 57 | + async def _inner(*args: Any, **kwargs: Any) -> T: |
| 58 | + hub = Hub.current |
| 59 | + integration = hub.get_integration(AsyncPGIntegration) |
| 60 | + |
| 61 | + # Avoid recording calls to _execute twice. |
| 62 | + # Calls to Connection.execute with args also call |
| 63 | + # Connection._execute, which is recorded separately |
| 64 | + # args[0] = the connection object, args[1] is the query |
| 65 | + if integration is None or len(args) > 2: |
| 66 | + return await f(*args, **kwargs) |
| 67 | + |
| 68 | + query = args[1] |
| 69 | + with record_sql_queries(hub, None, query, None, None, executemany=False): |
| 70 | + res = await f(*args, **kwargs) |
| 71 | + return res |
| 72 | + |
| 73 | + return _inner |
| 74 | + |
| 75 | + |
| 76 | +SubCursor = TypeVar("SubCursor", bound=BaseCursor) |
| 77 | + |
| 78 | + |
| 79 | +@contextlib.contextmanager |
| 80 | +def _record( |
| 81 | + hub: Hub, |
| 82 | + cursor: SubCursor | None, |
| 83 | + query: str, |
| 84 | + params_list: tuple[Any, ...] | None, |
| 85 | + *, |
| 86 | + executemany: bool = False, |
| 87 | +) -> Iterator[Span]: |
| 88 | + integration = hub.get_integration(AsyncPGIntegration) |
| 89 | + if not integration._record_params: |
| 90 | + params_list = None |
| 91 | + |
| 92 | + param_style = "pyformat" if params_list else None |
| 93 | + |
| 94 | + with record_sql_queries( |
| 95 | + hub, |
| 96 | + cursor, |
| 97 | + query, |
| 98 | + params_list, |
| 99 | + param_style, |
| 100 | + executemany=executemany, |
| 101 | + record_cursor_repr=cursor is not None, |
| 102 | + ) as span: |
| 103 | + yield span |
| 104 | + |
| 105 | + |
| 106 | +def _wrap_connection_method( |
| 107 | + f: Callable[..., Awaitable[T]], *, executemany: bool = False |
| 108 | +) -> Callable[..., Awaitable[T]]: |
| 109 | + async def _inner(*args: Any, **kwargs: Any) -> T: |
| 110 | + hub = Hub.current |
| 111 | + integration = hub.get_integration(AsyncPGIntegration) |
| 112 | + |
| 113 | + if integration is None: |
| 114 | + return await f(*args, **kwargs) |
| 115 | + |
| 116 | + query = args[1] |
| 117 | + params_list = args[2] if len(args) > 2 else None |
| 118 | + with _record(hub, None, query, params_list, executemany=executemany) as span: |
| 119 | + _set_db_data(span, args[0]) |
| 120 | + res = await f(*args, **kwargs) |
| 121 | + return res |
| 122 | + |
| 123 | + return _inner |
| 124 | + |
| 125 | + |
| 126 | +def _wrap_cursor_creation(f: Callable[..., T]) -> Callable[..., T]: |
| 127 | + def _inner(*args: Any, **kwargs: Any) -> T: # noqa: N807 |
| 128 | + hub = Hub.current |
| 129 | + integration = hub.get_integration(AsyncPGIntegration) |
| 130 | + |
| 131 | + if integration is None: |
| 132 | + return f(*args, **kwargs) |
| 133 | + |
| 134 | + query = args[1] |
| 135 | + params_list = args[2] if len(args) > 2 else None |
| 136 | + |
| 137 | + with _record( |
| 138 | + hub, |
| 139 | + None, |
| 140 | + query, |
| 141 | + params_list, |
| 142 | + executemany=False, |
| 143 | + ) as span: |
| 144 | + _set_db_data(span, args[0]) |
| 145 | + res = f(*args, **kwargs) |
| 146 | + span.set_data("db.cursor", res) |
| 147 | + |
| 148 | + return res |
| 149 | + |
| 150 | + return _inner |
| 151 | + |
| 152 | + |
| 153 | +def _wrap_connect_addr(f: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]: |
| 154 | + async def _inner(*args: Any, **kwargs: Any) -> T: |
| 155 | + hub = Hub.current |
| 156 | + integration = hub.get_integration(AsyncPGIntegration) |
| 157 | + |
| 158 | + if integration is None: |
| 159 | + return await f(*args, **kwargs) |
| 160 | + |
| 161 | + user = kwargs["params"].user |
| 162 | + database = kwargs["params"].database |
| 163 | + |
| 164 | + with hub.start_span(op=OP.DB, description="connect") as span: |
| 165 | + span.set_data(SPANDATA.DB_SYSTEM, "postgresql") |
| 166 | + addr = kwargs.get("addr") |
| 167 | + if addr: |
| 168 | + try: |
| 169 | + span.set_data(SPANDATA.SERVER_ADDRESS, addr[0]) |
| 170 | + span.set_data(SPANDATA.SERVER_PORT, addr[1]) |
| 171 | + except IndexError: |
| 172 | + pass |
| 173 | + span.set_data(SPANDATA.DB_NAME, database) |
| 174 | + span.set_data(SPANDATA.DB_USER, user) |
| 175 | + |
| 176 | + with capture_internal_exceptions(): |
| 177 | + hub.add_breadcrumb(message="connect", category="query", data=span._data) |
| 178 | + res = await f(*args, **kwargs) |
| 179 | + |
| 180 | + return res |
| 181 | + |
| 182 | + return _inner |
| 183 | + |
| 184 | + |
| 185 | +def _set_db_data(span: Span, conn: Any) -> None: |
| 186 | + span.set_data(SPANDATA.DB_SYSTEM, "postgresql") |
| 187 | + |
| 188 | + addr = conn._addr |
| 189 | + if addr: |
| 190 | + try: |
| 191 | + span.set_data(SPANDATA.SERVER_ADDRESS, addr[0]) |
| 192 | + span.set_data(SPANDATA.SERVER_PORT, addr[1]) |
| 193 | + except IndexError: |
| 194 | + pass |
| 195 | + |
| 196 | + database = conn._params.database |
| 197 | + if database: |
| 198 | + span.set_data(SPANDATA.DB_NAME, database) |
| 199 | + |
| 200 | + user = conn._params.user |
| 201 | + if user: |
| 202 | + span.set_data(SPANDATA.DB_USER, user) |
0 commit comments