macss-modular-api-postgres 0.5.0__py3-none-any.whl → 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: macss-modular-api-postgres
3
- Version: 0.5.0
3
+ Version: 0.7.0
4
4
  Summary: Official MACSS Postgres integration package for Python.
5
5
  Author: ccisne.dev
6
6
  License-Expression: MIT
@@ -19,7 +19,10 @@ Classifier: Topic :: Database
19
19
  Classifier: Typing :: Typed
20
20
  Requires-Python: >=3.11
21
21
  Description-Content-Type: text/markdown
22
+ Requires-Dist: opentelemetry-api<2,>=1.44
22
23
  Provides-Extra: dev
24
+ Requires-Dist: opentelemetry-sdk<2,>=1.44; extra == "dev"
25
+ Requires-Dist: pyright>=1.1.400; extra == "dev"
23
26
  Requires-Dist: pytest>=8.0; extra == "dev"
24
27
 
25
28
  # macss-modular-api-postgres
@@ -56,10 +59,12 @@ else:
56
59
 
57
60
  See [example/example.py](example/example.py) for a complete in-memory wiring sample.
58
61
 
59
- ## Current slice
62
+ ## What this package provides
60
63
 
61
64
  - normalized Postgres connection defaults and redacted summaries
62
65
  - engine-agnostic `DbClient`, `DbRepository`, and transaction contracts
63
66
  - explicit lease ownership semantics for package-owned and application-owned sessions
64
67
  - health contributor and GraphQL support bundle for higher-level integrations
65
- - real driver bindings intentionally remain outside this first slice
68
+ - the application supplies the driver binding (adapter) for its chosen engine and driver
69
+
70
+ This package is **contracts-only by design** and will never ship a driver binding; you choose your engine and driver and provide the adapter. See [ADR-0004](../../../docs/adr/0004-contracts-only-database-packages.md).
@@ -0,0 +1,8 @@
1
+ modular_api_postgres/__init__.py,sha256=Api4zr2ITzwymhtfKju9rNS7ABuUihvpnmDbKYRxdgk,1335
2
+ modular_api_postgres/db_client.py,sha256=zfwhk_SWnvMeOsps0mXMyIvkjFatVR00wQ2Mkk_tHfk,14355
3
+ modular_api_postgres/db_tracing.py,sha256=Flb3vPzhw4i3oplrzpXOznazqG7jYG0-bFw1HUrJZc0,11839
4
+ modular_api_postgres/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ macss_modular_api_postgres-0.7.0.dist-info/METADATA,sha256=-TB6cRdHfOlk-e0BgYb2K-MzrsqXo8502cDf4QD9mfA,2596
6
+ macss_modular_api_postgres-0.7.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
7
+ macss_modular_api_postgres-0.7.0.dist-info/top_level.txt,sha256=256SRpi7HI1fM37vDEnZVT6An9ivmo9YcA7TJN1Dmuk,21
8
+ macss_modular_api_postgres-0.7.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: setuptools (83.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -14,6 +14,9 @@ from .db_client import (
14
14
  DbHealthContributor,
15
15
  DbHealthReport,
16
16
  DbHealthStatus,
17
+ DbParameter,
18
+ DbParameterDirection,
19
+ DbProcedureOutcome,
17
20
  DbProviderDescription,
18
21
  DbRepository,
19
22
  DbRepositoryContext,
@@ -25,8 +28,10 @@ from .db_client import (
25
28
  DbTransactionContext,
26
29
  DbTransactionRunner,
27
30
  )
31
+ from .db_tracing import DbTracingOptions, trace_db_client
28
32
 
29
33
  __all__ = [
34
+ "DbTracingOptions",
30
35
  "DbClient",
31
36
  "DbCommand",
32
37
  "DbCommandExecutor",
@@ -40,6 +45,9 @@ __all__ = [
40
45
  "DbHealthContributor",
41
46
  "DbHealthReport",
42
47
  "DbHealthStatus",
48
+ "DbParameter",
49
+ "DbParameterDirection",
50
+ "DbProcedureOutcome",
43
51
  "DbProviderDescription",
44
52
  "DbRepository",
45
53
  "DbRepositoryContext",
@@ -50,4 +58,5 @@ __all__ = [
50
58
  "DbSessionProvider",
51
59
  "DbTransactionContext",
52
60
  "DbTransactionRunner",
53
- ]
61
+ "trace_db_client",
62
+ ]
@@ -7,6 +7,8 @@ from enum import Enum
7
7
  from typing import Callable, Generic, Mapping, Protocol, TypeVar, cast
8
8
 
9
9
  S = TypeVar("S")
10
+ #: Contravariant because the protocols below only ever *accept* a session, never return one.
11
+ S_contra = TypeVar("S_contra", contravariant=True)
10
12
  T = TypeVar("T")
11
13
  R = TypeVar("R")
12
14
  _MISSING = object()
@@ -17,6 +19,13 @@ class DbCommandKind(str, Enum):
17
19
  EXECUTE = "execute"
18
20
  BATCH = "batch"
19
21
  SCALAR = "scalar"
22
+ PROCEDURE = "procedure"
23
+
24
+
25
+ class DbParameterDirection(str, Enum):
26
+ INPUT = "input"
27
+ OUTPUT = "output"
28
+ INPUT_OUTPUT = "inputOutput"
20
29
 
21
30
 
22
31
  class DbFailureKind(str, Enum):
@@ -45,7 +54,7 @@ class DbConnectionSettings:
45
54
  username: str
46
55
  password: str
47
56
  ssl_mode: str
48
- options: Mapping[str, object] = field(default_factory=dict)
57
+ options: Mapping[str, object] = field(default_factory=dict[str, object])
49
58
 
50
59
  @classmethod
51
60
  def from_environment(
@@ -81,6 +90,39 @@ class DbConnectionSettings:
81
90
  )
82
91
 
83
92
 
93
+ @dataclass(frozen=True, slots=True)
94
+ class DbParameter:
95
+ name: str
96
+ value: object | None = None
97
+ direction: DbParameterDirection = DbParameterDirection.INPUT
98
+ type_hint: str | None = None
99
+
100
+ @classmethod
101
+ def input(cls, name: str, value: object | None, type_hint: str | None = None) -> DbParameter:
102
+ return cls(name=name, value=value, direction=DbParameterDirection.INPUT, type_hint=type_hint)
103
+
104
+ @classmethod
105
+ def output(cls, name: str, type_hint: str | None = None) -> DbParameter:
106
+ return cls(name=name, direction=DbParameterDirection.OUTPUT, type_hint=type_hint)
107
+
108
+ @classmethod
109
+ def input_output(
110
+ cls, name: str, value: object | None, type_hint: str | None = None
111
+ ) -> DbParameter:
112
+ return cls(
113
+ name=name,
114
+ value=value,
115
+ direction=DbParameterDirection.INPUT_OUTPUT,
116
+ type_hint=type_hint,
117
+ )
118
+
119
+
120
+ @dataclass(frozen=True, slots=True)
121
+ class DbProcedureOutcome:
122
+ return_value: object | None = None
123
+ output_parameters: Mapping[str, object] | None = None
124
+
125
+
84
126
  @dataclass(frozen=True, slots=True)
85
127
  class DbCommand:
86
128
  kind: DbCommandKind
@@ -101,12 +143,14 @@ class DbExecutionMetadata:
101
143
  class DbRowSet:
102
144
  rows: list[Mapping[str, object]]
103
145
  metadata: DbExecutionMetadata
146
+ procedure: DbProcedureOutcome | None = None
104
147
 
105
148
 
106
149
  @dataclass(frozen=True, slots=True)
107
150
  class DbExecutionSummary:
108
151
  affected_count: int
109
152
  metadata: DbExecutionMetadata
153
+ procedure: DbProcedureOutcome | None = None
110
154
 
111
155
 
112
156
  @dataclass(frozen=True, slots=True)
@@ -161,18 +205,18 @@ class DbResult(Generic[T]):
161
205
 
162
206
  def map(self, transform: Callable[[T], R]) -> DbResult[R]:
163
207
  if self.is_failure:
164
- return DbResult.from_failure(self.failure)
165
- return DbResult.success(transform(self.value))
208
+ return DbResult[R].from_failure(self.failure)
209
+ return DbResult[R].success(transform(self.value))
166
210
 
167
211
  def flat_map(self, transform: Callable[[T], DbResult[R]]) -> DbResult[R]:
168
212
  if self.is_failure:
169
- return DbResult.from_failure(self.failure)
213
+ return DbResult[R].from_failure(self.failure)
170
214
  return transform(self.value)
171
215
 
172
216
  def map_failure(self, transform: Callable[[DbFailure], DbFailure]) -> DbResult[T]:
173
217
  if self.is_success:
174
- return DbResult.success(self.value)
175
- return DbResult.from_failure(transform(self.failure))
218
+ return DbResult[T].success(self.value)
219
+ return DbResult[T].from_failure(transform(self.failure))
176
220
 
177
221
  def get_or_throw(self, message: str | None = None) -> T:
178
222
  if self.is_failure:
@@ -202,7 +246,7 @@ class DbSessionLease(Generic[S]):
202
246
 
203
247
  def release(self) -> DbResult[None]:
204
248
  if not self.owned_by_package:
205
- return DbResult.success(None)
249
+ return DbResult[None].success(None)
206
250
  return self._releaser()
207
251
 
208
252
 
@@ -214,12 +258,16 @@ class DbSessionProvider(Protocol[S]):
214
258
  def describe(self) -> DbProviderDescription: ...
215
259
 
216
260
 
217
- class DbCommandExecutor(Protocol[S]):
218
- def query(self, session: S, command: DbCommand) -> DbResult[DbRowSet]: ...
261
+ class DbCommandExecutor(Protocol[S_contra]):
262
+ def query(self, session: S_contra, command: DbCommand) -> DbResult[DbRowSet]: ...
219
263
 
220
- def execute(self, session: S, command: DbCommand) -> DbResult[DbExecutionSummary]: ...
264
+ def execute(
265
+ self, session: S_contra, command: DbCommand
266
+ ) -> DbResult[DbExecutionSummary]: ...
221
267
 
222
- def scalar(self, session: S, command: DbCommand) -> DbResult[DbScalar[object]]: ...
268
+ def scalar(
269
+ self, session: S_contra, command: DbCommand
270
+ ) -> DbResult[DbScalar[object]]: ...
223
271
 
224
272
 
225
273
  @dataclass(frozen=True, slots=True)
@@ -234,8 +282,8 @@ class DbTransactionContext(Generic[S]):
234
282
  def execute(self, command: DbCommand) -> DbResult[DbExecutionSummary]:
235
283
  return self.command_executor.execute(self.session, command)
236
284
 
237
- def scalar(self, command: DbCommand) -> DbResult[DbScalar[T]]:
238
- return cast(DbResult[DbScalar[T]], self.command_executor.scalar(self.session, command))
285
+ def scalar(self, command: DbCommand) -> DbResult[DbScalar[object]]:
286
+ return self.command_executor.scalar(self.session, command)
239
287
 
240
288
 
241
289
  class DbTransactionRunner(Protocol[S]):
@@ -270,13 +318,10 @@ class DbRepository(Generic[S]):
270
318
  lambda lease: self.context.command_executor.execute(lease.session, command),
271
319
  )
272
320
 
273
- def scalar(self, command: DbCommand) -> DbResult[DbScalar[T]]:
274
- return cast(
275
- DbResult[DbScalar[T]],
276
- _with_lease(
277
- self.context.session_provider,
278
- lambda lease: self.context.command_executor.scalar(lease.session, command),
279
- ),
321
+ def scalar(self, command: DbCommand) -> DbResult[DbScalar[object]]:
322
+ return _with_lease(
323
+ self.context.session_provider,
324
+ lambda lease: self.context.command_executor.scalar(lease.session, command),
280
325
  )
281
326
 
282
327
  def transaction(self, body: Callable[[DbTransactionContext[S]], DbResult[T]]) -> DbResult[T]:
@@ -315,19 +360,16 @@ class DbClient(Generic[S]):
315
360
  lambda lease: self.command_executor.execute(lease.session, command),
316
361
  )
317
362
 
318
- def scalar(self, command: DbCommand) -> DbResult[DbScalar[T]]:
319
- return cast(
320
- DbResult[DbScalar[T]],
321
- _with_lease(
322
- self.session_provider,
323
- lambda lease: self.command_executor.scalar(lease.session, command),
324
- ),
363
+ def scalar(self, command: DbCommand) -> DbResult[DbScalar[object]]:
364
+ return _with_lease(
365
+ self.session_provider,
366
+ lambda lease: self.command_executor.scalar(lease.session, command),
325
367
  )
326
368
 
327
369
  def transaction(self, body: Callable[[DbTransactionContext[S]], DbResult[T]]) -> DbResult[T]:
328
370
  lease_result = self.session_provider.acquire()
329
371
  if lease_result.is_failure:
330
- return DbResult.from_failure(lease_result.failure)
372
+ return DbResult[T].from_failure(lease_result.failure)
331
373
 
332
374
  lease = lease_result.value
333
375
  context = DbTransactionContext(
@@ -339,9 +381,9 @@ class DbClient(Generic[S]):
339
381
  release_result = lease.release()
340
382
 
341
383
  if result.is_failure:
342
- return DbResult.from_failure(result.failure)
384
+ return DbResult[T].from_failure(result.failure)
343
385
  if release_result.is_failure:
344
- return DbResult.from_failure(release_result.failure)
386
+ return DbResult[T].from_failure(release_result.failure)
345
387
  return result
346
388
 
347
389
  def repository_context(self) -> DbRepositoryContext[S]:
@@ -412,14 +454,14 @@ def _with_lease(
412
454
  ) -> DbResult[T]:
413
455
  lease_result = session_provider.acquire()
414
456
  if lease_result.is_failure:
415
- return DbResult.from_failure(lease_result.failure)
457
+ return DbResult[T].from_failure(lease_result.failure)
416
458
 
417
459
  lease = lease_result.value
418
460
  operation_result = operation(lease)
419
461
  release_result = lease.release()
420
462
 
421
463
  if operation_result.is_failure:
422
- return DbResult.from_failure(operation_result.failure)
464
+ return DbResult[T].from_failure(operation_result.failure)
423
465
  if release_result.is_failure:
424
- return DbResult.from_failure(release_result.failure)
466
+ return DbResult[T].from_failure(release_result.failure)
425
467
  return operation_result
@@ -0,0 +1,341 @@
1
+ """Database spans for the contracts this package ships.
2
+
3
+ **Instrumentation is a decorator over the contract, not a change to ``DbClient``.** ADR-0004 makes
4
+ this package contracts-only, and ``DbClient``, ``DbRepository`` and ``DbTransactionContext`` all
5
+ delegate to the same application-supplied ``DbCommandExecutor``. Wrapping that one collaborator
6
+ instruments every call path at once — including commands issued inside a transaction body, which
7
+ ``DbClient.transaction`` routes through a freshly built ``DbTransactionContext`` carrying the same
8
+ executor.
9
+
10
+ It follows that **not wrapping is how you turn tracing off**, so the cost of not using it is zero
11
+ rather than a branch per call (gate G3).
12
+
13
+ The Dart and TypeScript counterparts are ``lib/src/db_tracing.dart`` and ``src/dbTracing.ts``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from dataclasses import dataclass
20
+ from typing import Any, Callable, Generic, TypeVar
21
+
22
+ from opentelemetry import trace
23
+ from opentelemetry.trace import Span, SpanKind, Status, StatusCode, Tracer
24
+ from opentelemetry.util.types import AttributeValue
25
+
26
+ from modular_api_postgres.db_client import (
27
+ DbClient,
28
+ DbCommand,
29
+ DbCommandExecutor,
30
+ DbCommandKind,
31
+ DbConnectionSettings,
32
+ DbExecutionSummary,
33
+ DbProviderDescription,
34
+ DbResult,
35
+ DbRowSet,
36
+ DbScalar,
37
+ DbSessionLease,
38
+ DbSessionProvider,
39
+ DbTransactionContext,
40
+ DbTransactionRunner,
41
+ )
42
+
43
+ S = TypeVar("S")
44
+ T = TypeVar("T")
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class DbTracingOptions:
49
+ """How much a database span is allowed to say.
50
+
51
+ ``include_query_text`` is **off by default** (runbook D9). SQL can carry personal or financial
52
+ data in a literal, and a span is not a place that is reviewed for that. Parameter *values* are
53
+ never recorded regardless of this setting: the text is a template, the parameters are the data.
54
+ """
55
+
56
+ include_query_text: bool = False
57
+ instrumentation_name: str = "modular_api_postgres"
58
+
59
+
60
+ def trace_db_client(
61
+ client: DbClient[S],
62
+ options: DbTracingOptions | None = None,
63
+ ) -> DbClient[S]:
64
+ """Wrap ``client`` so its commands, transactions and session acquisitions produce spans.
65
+
66
+ The wrapped client is a drop-in replacement: same settings, same ``DbProviderDescription``, so
67
+ ``DbHealthContributor`` and GraphQL support keep working unchanged. A repository built from the
68
+ wrapped client is instrumented too — call ``repository_context()`` on the result rather than on
69
+ the original.
70
+ """
71
+ resolved = options or DbTracingOptions()
72
+ tracer = trace.get_tracer(resolved.instrumentation_name)
73
+ target = _DbTarget(client.settings)
74
+
75
+ return DbClient(
76
+ settings=client.settings,
77
+ session_provider=_TracedSessionProvider(client.session_provider, tracer, target),
78
+ command_executor=_TracedCommandExecutor(
79
+ client.command_executor, tracer, target, resolved
80
+ ),
81
+ transaction_runner=_TracedTransactionRunner(client.transaction_runner, tracer, target),
82
+ )
83
+
84
+
85
+ class _DbTarget:
86
+ """The attributes that describe *where* the database is, computed once per client."""
87
+
88
+ #: The value the semantic conventions register for Postgres.
89
+ #:
90
+ #: Deliberately not ``settings.engine_id``, which is ``postgres``: a backend keying its Postgres
91
+ #: dashboards off ``db.system.name`` would not match on that.
92
+ SYSTEM_NAME = "postgresql"
93
+
94
+ __slots__ = ("host", "namespace", "port")
95
+
96
+ def __init__(self, settings: DbConnectionSettings) -> None:
97
+ self.namespace = settings.database
98
+ self.host = settings.host
99
+ self.port = settings.port
100
+
101
+
102
+ #: The SQL verbs an operation name may take.
103
+ #:
104
+ #: An allowlist rather than "the first word", so an unusual leading token — a comment, a driver
105
+ #: directive — is dropped instead of emitted. That keeps the attribute low-cardinality and makes it
106
+ #: impossible for a fragment of a query to arrive as an operation name.
107
+ _SQL_OPERATIONS = frozenset(
108
+ {
109
+ "SELECT",
110
+ "INSERT",
111
+ "UPDATE",
112
+ "DELETE",
113
+ "MERGE",
114
+ "UPSERT",
115
+ "CALL",
116
+ "WITH",
117
+ "CREATE",
118
+ "ALTER",
119
+ "DROP",
120
+ "TRUNCATE",
121
+ "GRANT",
122
+ "REVOKE",
123
+ "EXPLAIN",
124
+ "ANALYZE",
125
+ "VACUUM",
126
+ "COPY",
127
+ "BEGIN",
128
+ "COMMIT",
129
+ "ROLLBACK",
130
+ "SET",
131
+ "SHOW",
132
+ "LISTEN",
133
+ "NOTIFY",
134
+ "REFRESH",
135
+ }
136
+ )
137
+
138
+ _LEADING_WORD = re.compile(r"^\s*([A-Za-z_]+)")
139
+
140
+
141
+ def _operation_name(command: DbCommand) -> str | None:
142
+ match = _LEADING_WORD.match(command.text)
143
+ if match is None:
144
+ return None
145
+
146
+ candidate = match.group(1).upper()
147
+ return candidate if candidate in _SQL_OPERATIONS else None
148
+
149
+
150
+ def _start_db_span(
151
+ tracer: Tracer,
152
+ *,
153
+ target: _DbTarget,
154
+ operation: str | None = None,
155
+ summary: str | None = None,
156
+ query_text: str | None = None,
157
+ batch_size: int | None = None,
158
+ ) -> Span | None:
159
+ """Start a span for one database operation, or return ``None`` when tracing is off.
160
+
161
+ ``None`` rather than a non-recording span: with no recording parent there is nothing to attach
162
+ to, and a span nobody will read is cost with no benefit.
163
+ """
164
+ parent = trace.get_current_span()
165
+ if not parent.is_recording():
166
+ return None
167
+
168
+ # `AttributeValue`, not `object`: OpenTelemetry accepts only primitives and sequences of
169
+ # primitives, and silently drops an attribute whose value is anything else. Naming the type
170
+ # turns a dropped attribute — invisible at runtime, and exactly the kind of gap that makes an
171
+ # instrumentation look broken — into an error here.
172
+ attributes: dict[str, AttributeValue] = {
173
+ "db.system.name": _DbTarget.SYSTEM_NAME,
174
+ "db.namespace": target.namespace,
175
+ "server.address": target.host,
176
+ "server.port": target.port,
177
+ }
178
+ if operation is not None:
179
+ attributes["db.operation.name"] = operation
180
+ if summary is not None:
181
+ attributes["db.query.summary"] = summary
182
+ if query_text is not None:
183
+ attributes["db.query.text"] = query_text
184
+ if batch_size is not None:
185
+ attributes["db.operation.batch.size"] = batch_size
186
+
187
+ return tracer.start_span(
188
+ # The conventions ask for ``{operation} {target}``, and prefer ``db.query.summary`` when one
189
+ # exists. ``DbCommand.label`` is exactly that — application-supplied and stable — so it wins
190
+ # over anything derived from the SQL. Never the SQL text itself: unbounded cardinality, and
191
+ # possibly personal data.
192
+ summary or f"{operation or 'QUERY'} {target.namespace}",
193
+ kind=SpanKind.CLIENT, # A database call leaves the process.
194
+ attributes=attributes,
195
+ )
196
+
197
+
198
+ def _end_db_span(
199
+ span: Span | None,
200
+ # `DbResult[Any]`, not `DbResult[object]`: this helper never touches the value, only `is_failure`
201
+ # and `failure` — but `DbResult` is invariant, so `DbResult[object]` accepts none of the concrete
202
+ # results its five call sites hold.
203
+ result: DbResult[Any],
204
+ returned_rows: int | None = None,
205
+ ) -> None:
206
+ """Record the outcome on ``span`` and end it.
207
+
208
+ Failures arrive as a ``DbResult``, never as a raised exception, so this inspects the result. A
209
+ decorator that only wrapped a ``try``/``except`` would report every timeout as a success.
210
+
211
+ The failure *message* is deliberately not copied: a driver message can quote the offending row.
212
+ The code and the kind are what diagnose the problem.
213
+ """
214
+ if span is None:
215
+ return
216
+
217
+ if result.is_failure:
218
+ failure = result.failure
219
+ span.set_attribute("db.response.status_code", failure.code)
220
+ span.set_attribute("modular_api.db.failure_kind", failure.kind.value)
221
+ span.set_status(Status(StatusCode.ERROR))
222
+ elif returned_rows is not None:
223
+ span.set_attribute("db.response.returned_rows", returned_rows)
224
+
225
+ span.end()
226
+
227
+
228
+ class _TracedCommandExecutor(Generic[S]):
229
+ __slots__ = ("_inner", "_options", "_target", "_tracer")
230
+
231
+ def __init__(
232
+ self,
233
+ inner: DbCommandExecutor[S],
234
+ tracer: Tracer,
235
+ target: _DbTarget,
236
+ options: DbTracingOptions,
237
+ ) -> None:
238
+ self._inner = inner
239
+ self._tracer = tracer
240
+ self._target = target
241
+ self._options = options
242
+
243
+ def _start(self, command: DbCommand) -> Span | None:
244
+ return _start_db_span(
245
+ self._tracer,
246
+ target=self._target,
247
+ operation=_operation_name(command),
248
+ summary=command.label,
249
+ query_text=command.text if self._options.include_query_text else None,
250
+ batch_size=(
251
+ len(command.parameters) if command.kind is DbCommandKind.BATCH else None
252
+ ),
253
+ )
254
+
255
+ def query(self, session: S, command: DbCommand) -> DbResult[DbRowSet]:
256
+ span = self._start(command)
257
+ result = self._inner.query(session, command)
258
+ rows = None
259
+ if result.is_success:
260
+ rows = result.value.metadata.row_count
261
+ if rows is None:
262
+ rows = len(result.value.rows)
263
+ _end_db_span(span, result, rows)
264
+ return result
265
+
266
+ def execute(self, session: S, command: DbCommand) -> DbResult[DbExecutionSummary]:
267
+ span = self._start(command)
268
+ result = self._inner.execute(session, command)
269
+ _end_db_span(span, result)
270
+ return result
271
+
272
+ def scalar(self, session: S, command: DbCommand) -> DbResult[DbScalar[object]]:
273
+ span = self._start(command)
274
+ result = self._inner.scalar(session, command)
275
+ _end_db_span(span, result)
276
+ return result
277
+
278
+
279
+ class _TracedTransactionRunner(Generic[S]):
280
+ __slots__ = ("_inner", "_target", "_tracer")
281
+
282
+ def __init__(
283
+ self,
284
+ inner: DbTransactionRunner[S],
285
+ tracer: Tracer,
286
+ target: _DbTarget,
287
+ ) -> None:
288
+ self._inner = inner
289
+ self._tracer = tracer
290
+ self._target = target
291
+
292
+ def run(
293
+ self,
294
+ context: DbTransactionContext[S],
295
+ body: Callable[[DbTransactionContext[S]], DbResult[T]],
296
+ ) -> DbResult[T]:
297
+ span = _start_db_span(self._tracer, target=self._target, operation="TRANSACTION")
298
+ if span is None:
299
+ return self._inner.run(context, body)
300
+
301
+ # Made ambient so commands issued through the transaction context become its children
302
+ # rather than siblings — the nesting is what makes a transaction readable in a waterfall.
303
+ # ``end_on_exit=False`` because ``_end_db_span`` records the outcome first.
304
+ with trace.use_span(span, end_on_exit=False):
305
+ result = self._inner.run(context, body)
306
+
307
+ _end_db_span(span, result)
308
+ return result
309
+
310
+
311
+ class _TracedSessionProvider(Generic[S]):
312
+ __slots__ = ("_inner", "_target", "_tracer")
313
+
314
+ def __init__(
315
+ self,
316
+ inner: DbSessionProvider[S],
317
+ tracer: Tracer,
318
+ target: _DbTarget,
319
+ ) -> None:
320
+ self._inner = inner
321
+ self._tracer = tracer
322
+ self._target = target
323
+
324
+ def acquire(self) -> DbResult[DbSessionLease[S]]:
325
+ """Acquisition gets its own span (runbook D28).
326
+
327
+ Without it, time spent waiting for a connection lands in no span at all — an unattributed
328
+ gap that reads as nothing having happened rather than as queueing for the pool. Pool
329
+ exhaustion is a live hypothesis for ``socia``, so this is the number that confirms or kills
330
+ it.
331
+ """
332
+ span = _start_db_span(self._tracer, target=self._target, operation="CONNECT")
333
+ result = self._inner.acquire()
334
+ _end_db_span(span, result)
335
+ return result
336
+
337
+ def close(self) -> DbResult[None]:
338
+ return self._inner.close()
339
+
340
+ def describe(self) -> DbProviderDescription:
341
+ return self._inner.describe()
File without changes
@@ -1,6 +0,0 @@
1
- modular_api_postgres/__init__.py,sha256=URrLgEvTQBn48LkyY7aJsz5vzwC38lEo_AMgF1JY0a4,1089
2
- modular_api_postgres/db_client.py,sha256=ixskWFwjikbIV_OsHCncYTjbKZTR4ZQdtbLD1ErmN0A,12959
3
- macss_modular_api_postgres-0.5.0.dist-info/METADATA,sha256=MNLXC_3ETdjNIbQCawjng1QypOi1OqcL-EL-IwJIiGU,2196
4
- macss_modular_api_postgres-0.5.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
5
- macss_modular_api_postgres-0.5.0.dist-info/top_level.txt,sha256=256SRpi7HI1fM37vDEnZVT6An9ivmo9YcA7TJN1Dmuk,21
6
- macss_modular_api_postgres-0.5.0.dist-info/RECORD,,