cap-sdk-python 2.17.0__py3-none-any.whl → 2.19.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.
cap/telemetry.py ADDED
@@ -0,0 +1,366 @@
1
+ """W3C trace context and OpenTelemetry messaging spans for CAP over NATS.
2
+
3
+ This module implements ``spec/interop/trace-context.md`` with the
4
+ OpenTelemetry API only. It imports without OpenTelemetry installed; a
5
+ non-None :class:`TelemetryConfig` needs it
6
+ (``pip install 'cap-sdk-python[otel]'``).
7
+
8
+ Rules this module enforces:
9
+
10
+ - Header values are untrusted correlation hints outside the signed bytes.
11
+ They never select tenant, principal, key, policy or approval.
12
+ - Only the lowercase ``traceparent`` and ``tracestate`` headers are written
13
+ or read. ``baggage`` is never written or read, whatever propagator is
14
+ configured.
15
+ - Call :func:`extract` only after CAP-PRODUCTION admission or legacy
16
+ validation has accepted the packet. There is no span for rejected packets.
17
+ - A ``None`` config is the off switch: it writes no headers, extracts
18
+ nothing and starts no spans.
19
+ - A legacy packet's ``trace_id`` and message ID are never recorded.
20
+ """
21
+
22
+ import enum
23
+ from dataclasses import dataclass
24
+ from typing import TYPE_CHECKING, Dict, FrozenSet, List, Mapping, Optional, Tuple, Union, cast
25
+
26
+ from . import subjects
27
+
28
+ if TYPE_CHECKING:
29
+ from opentelemetry.context import Context
30
+ from opentelemetry.propagators.textmap import Getter, Setter, TextMapPropagator
31
+ from opentelemetry.trace import Span, SpanContext, SpanKind, Tracer, TracerProvider
32
+
33
+ __all__ = [
34
+ "ErrorType",
35
+ "FIXED_SUBJECTS",
36
+ "MessagingSpan",
37
+ "Process",
38
+ "Publish",
39
+ "TelemetryConfig",
40
+ "extract",
41
+ "from_opentelemetry",
42
+ "inject_headers",
43
+ "start_process",
44
+ "start_publish",
45
+ ]
46
+
47
+ _INSTALL_HINT = "cap.telemetry needs OpenTelemetry: pip install 'cap-sdk-python[otel]'"
48
+ _TRACE_KEYS = ("traceparent", "tracestate")
49
+ _POOL_FORBIDDEN = frozenset("*> \t\r\n")
50
+ _Attributes = Dict[str, Union[str, bool]]
51
+
52
+
53
+ class ErrorType(str, enum.Enum):
54
+ """The closed ``error.type`` values of the trace-context contract."""
55
+
56
+ PROTOCOL_VERSION_MISMATCH = "PROTOCOL_VERSION_MISMATCH"
57
+ PROTOCOL_MALFORMED_PACKET = "PROTOCOL_MALFORMED_PACKET"
58
+ PROTOCOL_UNKNOWN_PAYLOAD = "PROTOCOL_UNKNOWN_PAYLOAD"
59
+ PROTOCOL_SIGNATURE_INVALID = "PROTOCOL_SIGNATURE_INVALID"
60
+ PROTOCOL_SIGNATURE_MISSING = "PROTOCOL_SIGNATURE_MISSING"
61
+ ADMISSION_REJECTED = "ADMISSION_REJECTED"
62
+ HANDLER_FAILED = "HANDLER_FAILED"
63
+ TRANSPORT_PUBLISH_FAILED = "TRANSPORT_PUBLISH_FAILED"
64
+ OTHER = "_OTHER"
65
+
66
+
67
+ _PUBLISH_ERRORS = frozenset({ErrorType.TRANSPORT_PUBLISH_FAILED.value, ErrorType.OTHER.value})
68
+ _PROCESS_ERRORS = frozenset(member.value for member in ErrorType) - {ErrorType.TRANSPORT_PUBLISH_FAILED.value}
69
+
70
+ FIXED_SUBJECTS: FrozenSet[str] = frozenset(
71
+ {
72
+ subjects.SUBJECT_SUBMIT,
73
+ subjects.SUBJECT_RESULT,
74
+ subjects.SUBJECT_HEARTBEAT,
75
+ subjects.SUBJECT_ALERT,
76
+ subjects.SUBJECT_PROGRESS,
77
+ subjects.SUBJECT_CANCEL,
78
+ subjects.SUBJECT_DLQ,
79
+ subjects.SUBJECT_WORKFLOW_EVENT,
80
+ subjects.SUBJECT_HANDSHAKE,
81
+ subjects.SUBJECT_WORKER_HANDSHAKE_CHALLENGE,
82
+ subjects.SUBJECT_WORKER_HANDSHAKE_AUTHENTICATE,
83
+ }
84
+ )
85
+ """The fixed ``sys.*`` subjects of the spec/09 subject table."""
86
+
87
+
88
+ def _require_opentelemetry() -> None:
89
+ try:
90
+ import opentelemetry.trace # noqa: F401
91
+ except ImportError as exc:
92
+ raise ImportError(_INSTALL_HINT) from exc
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class TelemetryConfig:
97
+ """An OpenTelemetry tracer plus an optional trace-context propagator.
98
+
99
+ ``propagator`` defaults to the W3C trace-context propagator, never the
100
+ global textmap. Whatever propagator is set, only ``traceparent`` and
101
+ ``tracestate`` reach the headers.
102
+ """
103
+
104
+ tracer: "Tracer"
105
+ propagator: "Optional[TextMapPropagator]" = None
106
+
107
+ def __post_init__(self) -> None:
108
+ _require_opentelemetry()
109
+ from opentelemetry.propagators.textmap import TextMapPropagator
110
+ from opentelemetry.trace import Tracer
111
+
112
+ if not isinstance(self.tracer, Tracer):
113
+ raise TypeError("tracer must be an opentelemetry.trace.Tracer")
114
+ if self.propagator is not None and not isinstance(self.propagator, TextMapPropagator):
115
+ raise TypeError("propagator must be None or an opentelemetry TextMapPropagator")
116
+
117
+
118
+ @dataclass(frozen=True)
119
+ class Publish:
120
+ """What a publish span describes.
121
+
122
+ ``pool`` is the ``job.<pool>`` subject the participant is configured to
123
+ publish to; the span names the destination only when it equals
124
+ ``subject``. Leave ``conversation_id`` empty when the packet's
125
+ ``trace_id`` was copied from an unauthenticated packet (spec/10 Safe
126
+ Observability).
127
+ """
128
+
129
+ subject: str
130
+ pool: str = ""
131
+ reply_inbox: bool = False
132
+ conversation_id: str = ""
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class Process:
137
+ """What a process span describes, for an admitted packet only.
138
+
139
+ ``production_verified`` is True only when the packet passed
140
+ CAP-PRODUCTION admission; only then are ``message_id`` (16 bytes) and
141
+ ``conversation_id`` recorded. ``creation`` is the result of
142
+ :func:`extract`.
143
+ """
144
+
145
+ subject: str
146
+ pool: str = ""
147
+ reply_inbox: bool = False
148
+ queue_group: str = ""
149
+ durable: str = ""
150
+ production_verified: bool = False
151
+ message_id: bytes = b""
152
+ conversation_id: str = ""
153
+ creation: "Optional[SpanContext]" = None
154
+
155
+
156
+ class MessagingSpan:
157
+ """A started publish or process span that accepts only contract data."""
158
+
159
+ __slots__ = ("_span", "_allowed")
160
+
161
+ def __init__(self, span: "Optional[Span]" = None, allowed: FrozenSet[str] = frozenset()) -> None:
162
+ self._span = span
163
+ self._allowed = allowed
164
+
165
+ def fail(self, error_type: Union[ErrorType, str]) -> None:
166
+ """Mark the span failed with a closed ``error.type`` value.
167
+
168
+ A value outside the span's closed set is recorded as ``_OTHER``. No
169
+ exception, message or event is recorded.
170
+ """
171
+ if self._span is None:
172
+ return
173
+ from opentelemetry.trace import Status, StatusCode
174
+
175
+ value = error_type.value if isinstance(error_type, ErrorType) else error_type
176
+ if not isinstance(value, str) or value not in self._allowed:
177
+ value = ErrorType.OTHER.value
178
+ self._span.set_attribute("error.type", value)
179
+ self._span.set_status(Status(StatusCode.ERROR, value))
180
+
181
+ def end(self) -> None:
182
+ """End the span."""
183
+ if self._span is not None:
184
+ self._span.end()
185
+
186
+
187
+ _NOOP_SPAN = MessagingSpan()
188
+
189
+
190
+ class _TraceHeaders:
191
+ """Getter and setter for exactly the lowercase trace-context header keys."""
192
+
193
+ def get(self, carrier: Mapping[str, str], key: str) -> Optional[List[str]]:
194
+ value = carrier.get(key) if key in _TRACE_KEYS else None
195
+ return [value] if isinstance(value, str) else None
196
+
197
+ def keys(self, carrier: Mapping[str, str]) -> List[str]:
198
+ return [key for key in _TRACE_KEYS if key in carrier]
199
+
200
+ def set(self, carrier: Dict[str, str], key: str, value: str) -> None:
201
+ if key in _TRACE_KEYS:
202
+ carrier[key] = value
203
+
204
+
205
+ _CARRIER = _TraceHeaders()
206
+
207
+
208
+ def _propagator(config: TelemetryConfig) -> "TextMapPropagator":
209
+ if config.propagator is not None:
210
+ return config.propagator
211
+ from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
212
+
213
+ return TraceContextTextMapPropagator()
214
+
215
+
216
+ def from_opentelemetry(
217
+ tracer_provider: "Optional[TracerProvider]" = None,
218
+ propagator: "Optional[TextMapPropagator]" = None,
219
+ ) -> TelemetryConfig:
220
+ """Build a config whose tracer comes from ``tracer_provider``.
221
+
222
+ A ``None`` provider resolves the global tracer provider at call time.
223
+ """
224
+ _require_opentelemetry()
225
+ import opentelemetry.trace
226
+
227
+ return TelemetryConfig(opentelemetry.trace.get_tracer("cap.telemetry", tracer_provider=tracer_provider), propagator)
228
+
229
+
230
+ def inject_headers(
231
+ config: Optional[TelemetryConfig],
232
+ headers: Optional[Dict[str, str]],
233
+ context: "Optional[Context]" = None,
234
+ ) -> Optional[Dict[str, str]]:
235
+ """Write the trace context of ``context`` into ``headers``.
236
+
237
+ ``context`` ``None`` means the current OpenTelemetry context. Existing
238
+ ``traceparent`` and ``tracestate`` values are replaced or removed; other
239
+ keys are kept. ``headers`` is updated in place and returned; when it is
240
+ ``None``, a new dict is returned, or ``None`` if nothing was written.
241
+ """
242
+ if config is None:
243
+ return headers
244
+ carrier: Dict[str, str] = {} if headers is None else headers
245
+ for key in _TRACE_KEYS:
246
+ carrier.pop(key, None)
247
+ _propagator(config).inject(carrier, context=context, setter=cast("Setter[Dict[str, str]]", _CARRIER))
248
+ if headers is None and not carrier:
249
+ return None
250
+ return carrier
251
+
252
+
253
+ def extract(
254
+ config: Optional[TelemetryConfig],
255
+ headers: Optional[Mapping[str, str]],
256
+ ) -> "Optional[SpanContext]":
257
+ """Return the valid remote creation context in ``headers``, else None.
258
+
259
+ Call it only for a packet that admission or validation accepted. The
260
+ result is a correlation hint, never authority.
261
+ """
262
+ if config is None or headers is None:
263
+ return None
264
+ from opentelemetry import trace
265
+ from opentelemetry.context import Context
266
+
267
+ getter = cast("Getter[Mapping[str, str]]", _CARRIER)
268
+ extracted = _propagator(config).extract(headers, context=Context(), getter=getter)
269
+ span_context = trace.get_current_span(extracted).get_span_context()
270
+ return span_context if span_context.is_valid and span_context.is_remote else None
271
+
272
+
273
+ def _attributes(op: str, op_type: str, subject: str, pool: str, reply_inbox: bool) -> Tuple[str, _Attributes]:
274
+ attributes: _Attributes = {
275
+ "messaging.system": "nats",
276
+ "messaging.operation.name": op,
277
+ "messaging.operation.type": op_type,
278
+ }
279
+ if reply_inbox:
280
+ attributes["messaging.destination.temporary"] = True
281
+ attributes["messaging.destination.anonymous"] = True
282
+ return op, attributes
283
+ is_pool = pool.startswith("job.") and len(pool) > len("job.") and not _POOL_FORBIDDEN.intersection(pool)
284
+ if subject in FIXED_SUBJECTS or (subject == pool and is_pool):
285
+ attributes["messaging.destination.name"] = subject
286
+ return op + " " + subject, attributes
287
+ return op, attributes
288
+
289
+
290
+ def _start(
291
+ config: TelemetryConfig,
292
+ name: str,
293
+ kind: "SpanKind",
294
+ attributes: _Attributes,
295
+ context: "Optional[Context]",
296
+ creation: "Optional[SpanContext]",
297
+ allowed: FrozenSet[str],
298
+ ) -> "Tuple[Optional[Context], MessagingSpan]":
299
+ from opentelemetry import trace
300
+
301
+ links = None
302
+ if creation is not None and creation.is_valid:
303
+ links = [trace.Link(creation)]
304
+ if not trace.get_current_span(context).get_span_context().is_valid:
305
+ context = trace.set_span_in_context(trace.NonRecordingSpan(creation), context)
306
+ span = config.tracer.start_span(
307
+ name,
308
+ context=context,
309
+ kind=kind,
310
+ attributes=attributes,
311
+ links=links,
312
+ record_exception=False,
313
+ set_status_on_exception=False,
314
+ )
315
+ return trace.set_span_in_context(span, context), MessagingSpan(span, allowed)
316
+
317
+
318
+ def start_publish(
319
+ config: Optional[TelemetryConfig],
320
+ publish: Publish,
321
+ context: "Optional[Context]" = None,
322
+ ) -> "Tuple[Optional[Context], MessagingSpan]":
323
+ """Start the PRODUCER ``publish`` span.
324
+
325
+ Inject the returned context into the message headers: the publish span
326
+ is the creation context. ``context`` ``None`` means the current context.
327
+ A caller leaves ``publish.conversation_id`` empty when the packet's
328
+ ``trace_id`` was copied from an unauthenticated packet (spec/10 Safe
329
+ Observability).
330
+ """
331
+ if config is None:
332
+ return context, _NOOP_SPAN
333
+ from opentelemetry.trace import SpanKind
334
+
335
+ name, attributes = _attributes("publish", "send", publish.subject, publish.pool, publish.reply_inbox)
336
+ if publish.conversation_id:
337
+ attributes["messaging.message.conversation_id"] = publish.conversation_id
338
+ return _start(config, name, SpanKind.PRODUCER, attributes, context, None, _PUBLISH_ERRORS)
339
+
340
+
341
+ def start_process(
342
+ config: Optional[TelemetryConfig],
343
+ process: Process,
344
+ context: "Optional[Context]" = None,
345
+ ) -> "Tuple[Optional[Context], MessagingSpan]":
346
+ """Start the CONSUMER ``process`` span for an admitted packet.
347
+
348
+ A valid ``process.creation`` becomes a link, and also the parent when
349
+ ``context`` has no active span. ``context`` ``None`` means the current
350
+ context.
351
+ """
352
+ if config is None:
353
+ return context, _NOOP_SPAN
354
+ from opentelemetry.trace import SpanKind
355
+
356
+ name, attributes = _attributes("process", "process", process.subject, process.pool, process.reply_inbox)
357
+ if process.queue_group:
358
+ attributes["messaging.consumer.group.name"] = process.queue_group
359
+ if process.durable:
360
+ attributes["messaging.destination.subscription.name"] = process.durable
361
+ if process.production_verified:
362
+ if len(process.message_id) == 16:
363
+ attributes["messaging.message.id"] = process.message_id.hex()
364
+ if process.conversation_id:
365
+ attributes["messaging.message.conversation_id"] = process.conversation_id
366
+ return _start(config, name, SpanKind.CONSUMER, attributes, context, process.creation, _PROCESS_ERRORS)
cap/testing.py CHANGED
@@ -18,6 +18,10 @@ class MockNATS:
18
18
  def __init__(self) -> None:
19
19
  self.subscriptions: Dict[str, Any] = {}
20
20
  self._published: 'Optional["asyncio.Queue[Tuple[str, bytes]]"]' = None
21
+ self.requests: List[Tuple[str, bytes]] = []
22
+ self.published_headers: List[Tuple[str, Optional[Dict[str, str]]]] = []
23
+ self.reconnected_cb: Optional[Callable[[], Awaitable[None]]] = None
24
+ self.disconnected_cb: Optional[Callable[[], Awaitable[None]]] = None
21
25
 
22
26
  @property
23
27
  def published(self) -> "asyncio.Queue[Tuple[str, bytes]]":
@@ -26,15 +30,45 @@ class MockNATS:
26
30
  self._published = asyncio.Queue()
27
31
  return self._published
28
32
 
29
- async def publish(self, subject: str, data: bytes) -> None:
33
+ async def publish(
34
+ self, subject: str, data: bytes, headers: Optional[Dict[str, str]] = None,
35
+ ) -> None:
36
+ """Accept telemetry-enabled Agent/client headers and record a copy in order.
37
+
38
+ ``published`` still yields ``(subject, data)``; ``published_headers``
39
+ records the optional headers separately in the same publish order.
40
+ """
41
+ self.published_headers.append((subject, None if headers is None else dict(headers)))
30
42
  await self.published.put((subject, data))
31
43
 
32
44
  async def subscribe(self, subject: str, queue: str = "", cb: Any = None) -> None:
33
45
  self.subscriptions[subject] = cb
34
46
 
35
- async def connect(self, servers: str, name: str) -> "MockNATS":
47
+ async def connect(
48
+ self,
49
+ servers: str,
50
+ name: str,
51
+ *,
52
+ reconnected_cb: Optional[Callable[[], Awaitable[None]]] = None,
53
+ disconnected_cb: Optional[Callable[[], Awaitable[None]]] = None,
54
+ ) -> "MockNATS":
55
+ """Accept the options Agent passes when worker trust is warn or enforce.
56
+
57
+ The callbacks are stored so tests can await them to simulate reconnects.
58
+ """
59
+ self.reconnected_cb = reconnected_cb
60
+ self.disconnected_cb = disconnected_cb
36
61
  return self
37
62
 
63
+ async def request(self, subject: str, data: bytes = b"", timeout: float = 0.5) -> Any:
64
+ """Record the request, then time out: the in-memory bus has no responders.
65
+
66
+ A timeout is an operational transport failure, so worker trust in warn
67
+ mode continues without a session and enforce mode fails closed.
68
+ """
69
+ self.requests.append((subject, data))
70
+ raise asyncio.TimeoutError(f"MockNATS has no responder for {subject}")
71
+
38
72
  async def drain(self) -> None:
39
73
  return None
40
74