btx-otel 0.0.1__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.
btx_otel/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Export OpenTelemetry spans through the application's existing provider."""
2
+
3
+ from ._processor import BtxExportObservation, BtxSpanProcessor
4
+
5
+ __all__ = ["BtxExportObservation", "BtxSpanProcessor"]
btx_otel/_policy.py ADDED
@@ -0,0 +1,129 @@
1
+ """Builds an isolated span-attribute copy for BTX export."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping, Sequence
6
+ from dataclasses import dataclass, field
7
+ from types import MappingProxyType
8
+ from typing import TypeAlias
9
+
10
+ from opentelemetry.sdk.trace import ReadableSpan
11
+
12
+ AttributeValue: TypeAlias = (
13
+ str
14
+ | bool
15
+ | int
16
+ | float
17
+ | bytes
18
+ | Sequence["AttributeValue"]
19
+ | Mapping[str, "AttributeValue"]
20
+ | None
21
+ )
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class _SpanPatch:
26
+ """Changes span attributes on BTX's export copy.
27
+
28
+ ``delete_attributes`` removes keys first, then ``set_attributes`` adds or
29
+ replaces values. Unmentioned attributes stay unchanged. Inputs are copied
30
+ into immutable mappings and sequences. Invalid keys or values raise
31
+ ``ValueError`` or ``TypeError``.
32
+ """
33
+
34
+ set_attributes: Mapping[str, AttributeValue] = field(default_factory=dict)
35
+ delete_attributes: Sequence[str] = ()
36
+
37
+ def __post_init__(self) -> None:
38
+ if isinstance(self.delete_attributes, (str, bytes)) or not isinstance(
39
+ self.delete_attributes, Sequence
40
+ ):
41
+ raise ValueError("Deleted attributes must be a sequence of keys")
42
+ deleted = tuple(self.delete_attributes)
43
+ for key in deleted:
44
+ if not isinstance(key, str):
45
+ raise ValueError("Attribute keys must be strings")
46
+ key.encode("utf-8")
47
+ object.__setattr__(self, "set_attributes", _freeze_attributes(self.set_attributes))
48
+ object.__setattr__(self, "delete_attributes", deleted)
49
+
50
+
51
+ def _freeze_attributes(
52
+ attributes: Mapping[str, AttributeValue],
53
+ ) -> Mapping[str, AttributeValue]:
54
+ if not isinstance(attributes, Mapping):
55
+ raise ValueError("Attribute replacements must be a mapping")
56
+ frozen = {}
57
+ for key, value in attributes.items():
58
+ if not isinstance(key, str):
59
+ raise ValueError("Attribute keys must be strings")
60
+ key.encode("utf-8")
61
+ frozen[key] = _freeze_value(value)
62
+ return MappingProxyType(frozen)
63
+
64
+
65
+ def _freeze_value(value: AttributeValue) -> AttributeValue:
66
+ if type(value) is str:
67
+ value.encode("utf-8")
68
+ return value
69
+ if value is None or type(value) in (bool, float, bytes):
70
+ return value
71
+ if type(value) is int:
72
+ if not -(2**63) <= value < 2**63:
73
+ raise ValueError("Integer attribute exceeds the OTLP range")
74
+ return value
75
+ if isinstance(value, Mapping):
76
+ return _freeze_attributes(value)
77
+ if isinstance(value, Sequence):
78
+ return tuple(_freeze_value(item) for item in value)
79
+ raise ValueError("Unsupported attribute value")
80
+
81
+
82
+ def apply_mask(
83
+ span: ReadableSpan,
84
+ mask: Callable[[ReadableSpan], _SpanPatch | None],
85
+ ) -> ReadableSpan:
86
+ snapshot = _ExportSpan(span, _freeze_attributes(span.attributes or {}))
87
+ patch = mask(snapshot)
88
+ if patch is None:
89
+ return snapshot
90
+ if not isinstance(patch, _SpanPatch):
91
+ raise ValueError("Masking must return _SpanPatch or None")
92
+ attributes = dict(snapshot.attributes or {})
93
+ for key in patch.delete_attributes:
94
+ attributes.pop(key, None)
95
+ attributes.update(patch.set_attributes)
96
+ return _ExportSpan(span, MappingProxyType(attributes))
97
+
98
+
99
+ class _ExportSpan(ReadableSpan):
100
+ def __init__(self, span: ReadableSpan, attributes: Mapping[str, AttributeValue]) -> None:
101
+ super().__init__(
102
+ name=span.name,
103
+ context=span.get_span_context(),
104
+ parent=span.parent,
105
+ resource=span.resource,
106
+ attributes=attributes,
107
+ events=span.events,
108
+ links=span.links,
109
+ kind=span.kind,
110
+ status=span.status,
111
+ start_time=span.start_time,
112
+ end_time=span.end_time,
113
+ instrumentation_scope=span.instrumentation_scope,
114
+ )
115
+ self._dropped_attribute_count = span.dropped_attributes
116
+ self._dropped_event_count = span.dropped_events
117
+ self._dropped_link_count = span.dropped_links
118
+
119
+ @property
120
+ def dropped_attributes(self) -> int:
121
+ return self._dropped_attribute_count
122
+
123
+ @property
124
+ def dropped_events(self) -> int:
125
+ return self._dropped_event_count
126
+
127
+ @property
128
+ def dropped_links(self) -> int:
129
+ return self._dropped_link_count
btx_otel/_processor.py ADDED
@@ -0,0 +1,457 @@
1
+ """BTX delivery defaults composed with the official OTel batching and transport APIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import re
7
+ from collections.abc import Callable, Sequence
8
+ from dataclasses import dataclass, field
9
+ from threading import Event, Lock, Thread, local
10
+ from typing import Any, Literal
11
+
12
+ from opentelemetry.context import Context
13
+ from opentelemetry.exporter.otlp.proto.common.trace_encoder import encode_spans
14
+ from opentelemetry.exporter.otlp.proto.http import Compression
15
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
16
+ from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceResponse
17
+ from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor
18
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExporter, SpanExportResult
19
+ from requests import PreparedRequest, Response, Session
20
+ from requests.exceptions import ConnectionError as RequestsConnectionError
21
+ from requests.exceptions import RequestException, Timeout
22
+ from urllib3.exceptions import HTTPError, ReadTimeoutError
23
+
24
+ from ._policy import _SpanPatch, apply_mask
25
+ from ._response import ResponseLimitError, read_response
26
+
27
+ _ENDPOINT = "https://btx.so/api/otel/v1/traces"
28
+ _QUEUE_BYTES = 4 * 1024 * 1024
29
+ _REQUEST_BYTES = 4 * 1024 * 1024
30
+ _SPAN_BYTES = 128 * 1024
31
+ _logger = logging.getLogger("btx_otel")
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class BtxExportObservation:
36
+ """Reports delivery metadata without credentials or span content."""
37
+
38
+ outcome: Literal["accepted", "failed", "partial_success", "overflow"]
39
+ spans: int
40
+ reason: str | None = None
41
+ http_status: int | None = None
42
+ rejected_spans: int = 0
43
+
44
+
45
+ @dataclass
46
+ class _Drain:
47
+ event: Event = field(default_factory=Event)
48
+ ok: bool = False
49
+
50
+
51
+ class _Session(Session):
52
+ """Own headers and observe OTLP responses through requests' public session API."""
53
+
54
+ def __init__(self, api_key: str) -> None:
55
+ super().__init__()
56
+ self._api_key = api_key
57
+ self.status: int | None = None
58
+ self.rejected = 0
59
+ self.warning = False
60
+ self.reason: str | None = None
61
+
62
+ def send(self, request: PreparedRequest, **kwargs: Any) -> Response:
63
+ if request.url != _ENDPOINT:
64
+ raise ValueError("BTX export destination changed")
65
+ # Do not inherit global OTel headers, session credentials, or redirect credentials.
66
+ length = request.headers.get("Content-Length")
67
+ request.headers.clear()
68
+ request.headers.update(
69
+ {
70
+ "Authorization": f"Bearer {self._api_key}",
71
+ "Content-Type": "application/x-protobuf",
72
+ "Accept-Encoding": "gzip",
73
+ }
74
+ )
75
+ if length is not None:
76
+ request.headers["Content-Length"] = length
77
+ kwargs.pop("allow_redirects", None)
78
+ kwargs["stream"] = True
79
+ self.reason = None
80
+ self.rejected = 0
81
+ self.warning = False
82
+ response: Response | None = None
83
+ try:
84
+ # Session.send prepares redirects by reading their bodies, even with
85
+ # redirects disabled. The public adapter API leaves every body streamed.
86
+ response = self.get_adapter(_ENDPOINT).send(request, **kwargs)
87
+ self.status = response.status_code
88
+ body = read_response(response)
89
+ if response.status_code == 200:
90
+ message = ExportTraceServiceResponse.FromString(body)
91
+ self.rejected = message.partial_success.rejected_spans
92
+ self.warning = bool(message.partial_success.error_message)
93
+ if self.rejected < 0:
94
+ raise ValueError("Invalid rejected span count")
95
+ return self._safe_response(response)
96
+ except ResponseLimitError:
97
+ self.reason = "response_too_large"
98
+ # A permanent local rejection prevents upstream retrying the batch.
99
+ return self._safe_response(response, status=400)
100
+ except (Timeout, ReadTimeoutError):
101
+ self.reason = "timeout"
102
+ raise Timeout("BTX export timed out") from None
103
+ except RequestsConnectionError:
104
+ self.reason = "network_error"
105
+ raise RequestsConnectionError("BTX export transport failed") from None
106
+ except HTTPError:
107
+ # Reading a streamed response bypasses requests' exception mapping.
108
+ # Preserve connection-error classification for the official retry policy.
109
+ self.reason = "network_error"
110
+ raise RequestsConnectionError("BTX export transport failed") from None
111
+ except RequestException:
112
+ self.reason = "network_error"
113
+ raise RequestException("BTX export transport failed") from None
114
+ except Exception:
115
+ self.reason = "invalid_acknowledgment"
116
+ return self._safe_response(response, status=400)
117
+ finally:
118
+ if response is not None:
119
+ response.close()
120
+
121
+ @staticmethod
122
+ def _safe_response(original: Response | None, *, status: int | None = None) -> Response:
123
+ # Preserve only transport metadata; upstream logging never sees server text.
124
+ safe = Response()
125
+ safe.status_code = (
126
+ status
127
+ if status is not None
128
+ else (original.status_code if original is not None else 400)
129
+ )
130
+ if original is not None:
131
+ safe.headers.update(original.headers)
132
+ safe._content = b""
133
+ _ = safe.content
134
+ safe.reason = "BTX export rejected" if safe.status_code != 200 else "OK"
135
+ return safe
136
+
137
+
138
+ class _Exporter(SpanExporter):
139
+ def __init__(self, owner: BtxSpanProcessor, api_key: str, timeout: float) -> None:
140
+ self.owner = owner
141
+ self.session = _Session(api_key)
142
+ self.transport = OTLPSpanExporter(
143
+ endpoint=_ENDPOINT,
144
+ headers={"Authorization": f"Bearer {api_key}"},
145
+ timeout=timeout,
146
+ compression=Compression.NoCompression,
147
+ session=self.session,
148
+ max_request_size=_REQUEST_BYTES,
149
+ )
150
+
151
+ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
152
+ result = SpanExportResult.SUCCESS
153
+ batch: list[ReadableSpan] = []
154
+ batch_bytes = 0
155
+ try:
156
+ for span in spans:
157
+ masked = self.owner._mask(span)
158
+ if masked is None:
159
+ result = SpanExportResult.FAILURE
160
+ continue
161
+ try:
162
+ size = encode_spans((masked,)).ByteSize()
163
+ except Exception:
164
+ self.owner._observe(BtxExportObservation("failed", 1, "projection_failed"))
165
+ result = SpanExportResult.FAILURE
166
+ continue
167
+ if size > min(_SPAN_BYTES, _REQUEST_BYTES):
168
+ self.owner._observe(BtxExportObservation("overflow", 1, "span_too_large"))
169
+ result = SpanExportResult.FAILURE
170
+ continue
171
+ if batch and batch_bytes + size > _REQUEST_BYTES:
172
+ if self._deliver(batch) is SpanExportResult.FAILURE:
173
+ result = SpanExportResult.FAILURE
174
+ batch = []
175
+ batch_bytes = 0
176
+ batch.append(masked)
177
+ batch_bytes += size
178
+ if batch and self._deliver(batch) is SpanExportResult.FAILURE:
179
+ result = SpanExportResult.FAILURE
180
+ return result
181
+ except Exception:
182
+ self.owner._observe(BtxExportObservation("failed", len(spans), "export_failed"))
183
+ return SpanExportResult.FAILURE
184
+ finally:
185
+ # Account for the original queued spans until masking and all sends finish.
186
+ self.owner._release(spans)
187
+
188
+ def _deliver(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
189
+ self.session.status = None
190
+ self.session.rejected = 0
191
+ self.session.warning = False
192
+ self.session.reason = None
193
+ try:
194
+ result = self.transport.export(spans)
195
+ status = self.session.status
196
+ rejected = self.session.rejected
197
+ # requests treats redirects as OK; OTLP acceptance requires HTTP 200.
198
+ if status is not None and status != 200:
199
+ result = SpanExportResult.FAILURE
200
+ if rejected > len(spans):
201
+ self.owner._observe(
202
+ BtxExportObservation(
203
+ "failed",
204
+ len(spans),
205
+ "invalid_acknowledgment",
206
+ status,
207
+ )
208
+ )
209
+ return SpanExportResult.FAILURE
210
+ if result is SpanExportResult.SUCCESS and rejected:
211
+ self.owner._observe(
212
+ BtxExportObservation(
213
+ "partial_success",
214
+ len(spans),
215
+ "rejected",
216
+ status,
217
+ rejected,
218
+ )
219
+ )
220
+ elif result is SpanExportResult.SUCCESS:
221
+ self.owner._observe(
222
+ BtxExportObservation(
223
+ "accepted",
224
+ len(spans),
225
+ "server_warning" if self.session.warning else None,
226
+ status,
227
+ )
228
+ )
229
+ else:
230
+ reason = self.session.reason or {
231
+ 401: "invalid_api_key",
232
+ 429: "rate_limited",
233
+ }.get(status or 0)
234
+ reason = reason or (
235
+ "unavailable"
236
+ if status and status >= 500
237
+ else "rejected"
238
+ if status
239
+ else "export_failed"
240
+ )
241
+ self.owner._observe(BtxExportObservation("failed", len(spans), reason, status))
242
+ return result
243
+ except Exception:
244
+ self.owner._observe(BtxExportObservation("failed", len(spans), "export_failed"))
245
+ return SpanExportResult.FAILURE
246
+
247
+ def shutdown(self) -> None:
248
+ self.transport.shutdown() # type: ignore[no-untyped-call] # Upstream method is untyped.
249
+
250
+
251
+ class BtxSpanProcessor(SpanProcessor):
252
+ """Adds bounded BTX export to an existing provider without changing its spans.
253
+
254
+ ``on_export`` receives delivery metadata on the submitting or export thread;
255
+ keep it fast. Callback exceptions never escape into application work.
256
+ ``force_flush`` reports queue-drain completion, not successful storage; inspect
257
+ export observations for acceptance, failure, and partial rejection.
258
+
259
+ ``should_export_span`` selects ended, sampled spans for BTX on the
260
+ span-ending thread. Treat its ``ReadableSpan`` argument as read-only.
261
+ Keep the callback fast and free of instrumented work. Invalid results or
262
+ exceptions drop only that BTX span with a safe diagnostic. Other destinations
263
+ are unchanged. The bounded queue retains the original spans.
264
+ """
265
+
266
+ def __init__(
267
+ self,
268
+ *,
269
+ api_key: str,
270
+ on_export: Callable[[BtxExportObservation], None] | None = None,
271
+ should_export_span: Callable[[ReadableSpan], bool] | None = None,
272
+ max_queue_size: int = 512,
273
+ max_export_batch_size: int = 128,
274
+ schedule_delay_millis: int = 30_000,
275
+ export_timeout_millis: int = 15_000,
276
+ _mask_span: Callable[[ReadableSpan], _SpanPatch | None] | None = None,
277
+ ) -> None:
278
+ if not isinstance(api_key, str) or not re.fullmatch(r"btx_[A-Za-z0-9_-]{43}", api_key):
279
+ raise ValueError("A valid BTX project API key is required")
280
+ for value in (
281
+ max_queue_size,
282
+ max_export_batch_size,
283
+ schedule_delay_millis,
284
+ export_timeout_millis,
285
+ ):
286
+ if type(value) is not int or value <= 0:
287
+ raise ValueError("BTX delivery limits must be positive integers")
288
+ if max_export_batch_size > max_queue_size:
289
+ raise ValueError("Export batch size exceeds queue size")
290
+ for hook in (should_export_span, _mask_span):
291
+ if hook is not None and not callable(hook):
292
+ raise ValueError("BTX export policy hooks must be callable")
293
+ self._on_export = on_export
294
+ self._should_export_span = should_export_span
295
+ self._mask_span = _mask_span
296
+ self._notifying = local()
297
+ self._lock = Lock()
298
+ self._pending: dict[int, int] = {}
299
+ self._warned: set[str] = set()
300
+ self._pending_bytes = 0
301
+ self._max_queue_size = max_queue_size
302
+ self._stopped = False
303
+ self._flush_wait: _Drain | None = None
304
+ self._shutdown_wait: _Drain | None = None
305
+ self._exporter = _Exporter(self, api_key, export_timeout_millis / 1000)
306
+ self._batch = BatchSpanProcessor(
307
+ self._exporter,
308
+ max_queue_size=max_queue_size,
309
+ max_export_batch_size=max_export_batch_size,
310
+ schedule_delay_millis=schedule_delay_millis,
311
+ export_timeout_millis=export_timeout_millis,
312
+ )
313
+
314
+ def on_start(self, span: Span, parent_context: Context | None = None) -> None:
315
+ """Leaves span creation and sampling with the host provider."""
316
+
317
+ def on_end(self, span: ReadableSpan) -> None:
318
+ """Enqueues sampled spans without network I/O or mutation."""
319
+ try:
320
+ if getattr(self._notifying, "active", False):
321
+ return
322
+ if not span.context or not span.context.trace_flags.sampled:
323
+ return
324
+ with self._lock:
325
+ if self._stopped:
326
+ return
327
+ if not self._select(span):
328
+ return
329
+ size = encode_spans((span,)).ByteSize()
330
+ reason: str | None = None
331
+ with self._lock:
332
+ if self._stopped:
333
+ return
334
+ if (
335
+ len(self._pending) >= self._max_queue_size
336
+ or self._pending_bytes + size > _QUEUE_BYTES
337
+ ):
338
+ reason = "queue_full"
339
+ elif id(span) in self._pending:
340
+ return
341
+ else:
342
+ self._pending[id(span)] = size
343
+ self._pending_bytes += size
344
+ self._batch.on_end(span)
345
+ if reason:
346
+ self._observe(BtxExportObservation("overflow", 1, reason))
347
+ except Exception:
348
+ self._release((span,))
349
+ self._observe(BtxExportObservation("failed", 1, "projection_failed"))
350
+
351
+ def _select(self, span: ReadableSpan) -> bool:
352
+ try:
353
+ self._notifying.active = True
354
+ if self._should_export_span is not None:
355
+ selected = self._should_export_span(span)
356
+ if type(selected) is not bool:
357
+ raise ValueError("Span selection must return a boolean")
358
+ return selected
359
+ return True
360
+ except Exception:
361
+ self._notifying.active = False
362
+ self._observe(BtxExportObservation("failed", 1, "filter_failed"))
363
+ return False
364
+ finally:
365
+ self._notifying.active = False
366
+
367
+ def _mask(self, span: ReadableSpan) -> ReadableSpan | None:
368
+ try:
369
+ self._notifying.active = True
370
+ if self._mask_span is not None:
371
+ return apply_mask(span, self._mask_span)
372
+ return span
373
+ except Exception:
374
+ # Never export the original span when a configured policy fails.
375
+ self._notifying.active = False
376
+ self._observe(BtxExportObservation("failed", 1, "mask_failed"))
377
+ return None
378
+ finally:
379
+ self._notifying.active = False
380
+
381
+ def _release(self, spans: Sequence[ReadableSpan]) -> None:
382
+ with self._lock:
383
+ for span in spans:
384
+ self._pending_bytes -= self._pending.pop(id(span), 0)
385
+
386
+ def _observe(self, observation: BtxExportObservation) -> None:
387
+ if getattr(self._notifying, "active", False):
388
+ return
389
+ try:
390
+ self._notifying.active = True
391
+ if self._on_export:
392
+ self._on_export(observation)
393
+ else:
394
+ with self._lock:
395
+ if observation.outcome == "accepted":
396
+ if observation.reason is None:
397
+ self._warned.clear()
398
+ return
399
+ self._warned.intersection_update({observation.reason})
400
+ reason = observation.reason or "export_failed"
401
+ if reason in self._warned:
402
+ return
403
+ self._warned.add(reason)
404
+ _logger.warning(
405
+ "BTX export %s: %s (%d spans)", observation.outcome, reason, observation.spans
406
+ )
407
+ except Exception:
408
+ pass
409
+ finally:
410
+ self._notifying.active = False
411
+
412
+ def force_flush(self, timeout_millis: int = 20_000) -> bool:
413
+ """Waits at most the given duration for queued export work to finish."""
414
+ if type(timeout_millis) is not int or timeout_millis <= 0:
415
+ return False
416
+ with self._lock:
417
+ if self._shutdown_wait:
418
+ drain = self._shutdown_wait
419
+ elif self._flush_wait and not self._flush_wait.event.is_set():
420
+ drain = self._flush_wait
421
+ else:
422
+ drain = _Drain()
423
+ self._flush_wait = drain
424
+ Thread(target=self._flush, args=(drain,), daemon=True).start()
425
+ return drain.event.wait(timeout_millis / 1000) and drain.ok
426
+
427
+ def _flush(self, drain: _Drain) -> None:
428
+ try:
429
+ ok = self._batch.force_flush()
430
+ with self._lock:
431
+ drain.ok = ok and not self._pending
432
+ except Exception:
433
+ self._observe(BtxExportObservation("failed", 0, "flush_failed"))
434
+ finally:
435
+ drain.event.set()
436
+
437
+ def shutdown(self) -> None:
438
+ """Stops intake and waits up to 20 seconds for final delivery and cleanup."""
439
+ with self._lock:
440
+ if self._shutdown_wait is None:
441
+ self._stopped = True
442
+ self._shutdown_wait = _Drain()
443
+ Thread(target=self._shutdown, args=(self._shutdown_wait,), daemon=True).start()
444
+ drain = self._shutdown_wait
445
+ drain.event.wait(20)
446
+
447
+ def _shutdown(self, drain: _Drain) -> None:
448
+ try:
449
+ if self._flush_wait:
450
+ self._flush_wait.event.wait()
451
+ self._batch.shutdown() # type: ignore[no-untyped-call] # Upstream method is untyped.
452
+ with self._lock:
453
+ drain.ok = not self._pending
454
+ except Exception:
455
+ self._observe(BtxExportObservation("failed", 0, "shutdown_failed"))
456
+ finally:
457
+ drain.event.set()
btx_otel/_response.py ADDED
@@ -0,0 +1,61 @@
1
+ """Reads OTLP acknowledgments within wire and decompressed byte limits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ from io import RawIOBase
7
+ from typing import Any
8
+
9
+ from requests import Response
10
+
11
+ _RESPONSE_BYTES = 4 * 1024 * 1024
12
+ _READ_BYTES = 64 * 1024
13
+
14
+
15
+ class ResponseLimitError(Exception):
16
+ """Indicates a response exceeded the supported byte budget."""
17
+
18
+
19
+ class _WireReader(RawIOBase):
20
+ def __init__(self, raw: Any) -> None:
21
+ self._raw = raw
22
+ self._received = 0
23
+
24
+ def read(self, size: int = -1) -> bytes:
25
+ size = min(size if size >= 0 else _READ_BYTES, _READ_BYTES)
26
+ # Read at most one byte beyond the budget to distinguish EOF from overflow.
27
+ chunk: bytes = self._raw.read(
28
+ min(size, _RESPONSE_BYTES - self._received + 1), decode_content=False
29
+ )
30
+ self._received += len(chunk)
31
+ if self._received > _RESPONSE_BYTES:
32
+ raise ResponseLimitError
33
+ return chunk
34
+
35
+
36
+ def read_response(response: Response) -> bytes:
37
+ """Returns a bounded response body, decoding gzip when advertised."""
38
+ length = response.headers.get("Content-Length", "")
39
+ try:
40
+ declared = int(length)
41
+ except ValueError:
42
+ declared = 0
43
+ if declared > _RESPONSE_BYTES:
44
+ raise ResponseLimitError
45
+
46
+ wire = _WireReader(response.raw)
47
+ encoding = response.headers.get("Content-Encoding", "identity").strip().lower()
48
+ if encoding == "gzip":
49
+ # GzipFile bounds decompressor output and handles concatenated members.
50
+ with gzip.GzipFile(fileobj=wire, mode="rb") as stream:
51
+ body = stream.read(_RESPONSE_BYTES + 1)
52
+ elif encoding in ("", "identity"):
53
+ buffer = bytearray()
54
+ while chunk := wire.read():
55
+ buffer.extend(chunk)
56
+ body = bytes(buffer)
57
+ else:
58
+ raise ValueError("Unsupported BTX response encoding")
59
+ if len(body) > _RESPONSE_BYTES:
60
+ raise ResponseLimitError
61
+ return body
btx_otel/py.typed ADDED
File without changes
@@ -0,0 +1,249 @@
1
+ Metadata-Version: 2.5
2
+ Name: btx-otel
3
+ Version: 0.0.1
4
+ Summary: Export existing OpenTelemetry traces to BTX
5
+ Project-URL: Documentation, https://btx.so/docs/otel/python
6
+ Project-URL: Source, https://github.com/dataporto/btx
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http<1.46,>=1.45.1
9
+ Requires-Dist: opentelemetry-sdk<1.46,>=1.45.1
10
+ Requires-Dist: requests<3,>=2.33.0
11
+ Requires-Dist: urllib3<3,>=2.8.0
12
+ Provides-Extra: test
13
+ Requires-Dist: fastapi<1,>=0.115; extra == 'test'
14
+ Requires-Dist: httpx<1,>=0.27; extra == 'test'
15
+ Requires-Dist: langfuse<6,>=5.0.4; (python_version >= '3.11') and extra == 'test'
16
+ Requires-Dist: mypy<3,>=1.18; extra == 'test'
17
+ Requires-Dist: opentelemetry-instrumentation-fastapi<0.67,>=0.66b0; extra == 'test'
18
+ Requires-Dist: pip-audit<3,>=2.10.1; extra == 'test'
19
+ Requires-Dist: psutil<8,>=6; extra == 'test'
20
+ Requires-Dist: pytest<10,>=8; extra == 'test'
21
+ Requires-Dist: ruff<1,>=0.14; extra == 'test'
22
+ Requires-Dist: types-requests<3,>=2.32; extra == 'test'
23
+ Requires-Dist: uvicorn<1,>=0.30; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # btx-otel
27
+
28
+ Export spans from an existing Python OpenTelemetry provider to BTX.
29
+ This package is an export-only integration.
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pip install btx-otel
35
+ ```
36
+
37
+ For setup instructions, see the [Python guide](https://btx.so/docs/otel/python).
38
+
39
+ ## Scope and ownership
40
+
41
+ The host application creates spans through OpenTelemetry or existing
42
+ instrumentation, including Langfuse. It owns the `TracerProvider`, sampling,
43
+ resource and service metadata, context propagation, and application startup
44
+ and shutdown.
45
+
46
+ BTX attaches a `BtxSpanProcessor` to that provider. The processor owns BTX export
47
+ selection, bounded batching, transport, and delivery diagnostics.
48
+ The official OTel exporter handles bounded HTTP retries. Existing processors and
49
+ export destinations remain registered with the host provider.
50
+
51
+ Span creation APIs, tracing decorators, framework instrumentation, and a
52
+ provider-managing `init()` API are deferred to a separately scoped iteration.
53
+ The current integration uses `BtxSpanProcessor`; host applications continue
54
+ using their existing tracing APIs.
55
+
56
+ ## Requirements
57
+
58
+ - Python 3.10 or later.
59
+ - OpenTelemetry SDK and OTLP HTTP exporter `>=1.45.1,<1.46`.
60
+ - Requests `>=2.33.0,<3` and urllib3 `>=2.8.0,<3`.
61
+ - A server-side BTX project API key.
62
+
63
+ The supported OTel range is intentionally narrow for this first version. Keep
64
+ your application's OTel dependencies within that range; package installation
65
+ must resolve one compatible SDK, including dependencies used by Langfuse.
66
+ Langfuse is optional. Installed-wheel compatibility tests cover OTel 1.45.2
67
+ across Python 3.10–3.14, including Langfuse 5.0.4 and 5.2.0 coexistence and the
68
+ minimum Requests version on Python 3.10 and 3.14. Core BTX export supports Python
69
+ 3.10 independently. OTel 1.44 and
70
+ earlier lack the exporter's request-size option used by this package; newer
71
+ minor versions require validation before expanding the supported range.
72
+
73
+ Use OTel 1.45.2 or later in the 1.45 series. OTel 1.45.1 is temporarily accepted
74
+ for existing hosts, with separate functional compatibility coverage on Python
75
+ 3.13 and Langfuse 5.0.4. It has a known propagation denial-of-service advisory
76
+ and fails the vulnerability audit. This compatibility exception does not make
77
+ that dependency set security-qualified. Remove the older version when the host
78
+ can upgrade its shared OTel dependencies. OTel 1.45.0 remains unsupported.
79
+
80
+ The HTTP dependency minimums exclude known Requests credential/temp-file issues
81
+ and urllib3 proxy TLS issues.
82
+
83
+ ## Add BTX export
84
+
85
+ ```python
86
+ import os
87
+ from btx_otel import BtxSpanProcessor
88
+
89
+ btx_processor = BtxSpanProcessor(api_key=os.environ["BTX_API_KEY"])
90
+ provider.add_span_processor(btx_processor)
91
+ ```
92
+
93
+ `provider` is your application's existing `TracerProvider`. Initialize this
94
+ processor once per provider, after any worker forks. Keep existing processors,
95
+ including Langfuse's, registered. Creating, configuring, and shutting down the
96
+ provider remain the host application's responsibility.
97
+
98
+ ## Filter spans
99
+
100
+ To skip selected spans, replace the processor construction in the setup example
101
+ with:
102
+
103
+ ```python
104
+ btx_processor = BtxSpanProcessor(
105
+ api_key=os.environ["BTX_API_KEY"],
106
+ should_export_span=lambda span: span.name != "healthcheck",
107
+ )
108
+ provider.add_span_processor(btx_processor)
109
+ ```
110
+
111
+ `should_export_span` receives an ended, sampled `ReadableSpan` on the span-ending
112
+ thread, before queue admission. Return `True` to export to BTX or `False` to skip
113
+ it. Selection applies to each span independently; excluding a parent does not
114
+ exclude its children or change their parent IDs. Other destinations are unchanged.
115
+
116
+ Treat the span as read-only. Keep the callback fast and thread-safe, and avoid
117
+ network calls and instrumented work. An exception or invalid return value drops
118
+ that BTX span and reports `failed` with reason `filter_failed`; exception details
119
+ stay out of diagnostics. Without a callback, BTX exports sampled spans.
120
+
121
+ ### Control sensitive data
122
+
123
+ Sanitize data in your instrumentation before spans end. Review names, attributes,
124
+ exception events and stack traces, status descriptions, resources, and links.
125
+ Policies configured in another exporter, including Langfuse, do not sanitize
126
+ BTX exports. The queue retains original span data in memory until export finishes.
127
+ Keep the project API key server-side in your secret manager and rotate it if
128
+ exposed.
129
+
130
+ ## Verify delivery
131
+
132
+ Run an existing instrumented request or job. After its spans finish, flush the
133
+ BTX processor and find the trace in BTX. With Langfuse export enabled, check the
134
+ same trace ID in both destinations.
135
+
136
+ The standalone [first-export example](examples/first_trace.py) uses the host
137
+ application's standard OTel APIs to create one root and three child spans. With
138
+ `BTX_API_KEY` set, it prints the trace ID and requires an `accepted` acknowledgment
139
+ for all four spans. Auth rejection, incomplete acknowledgment, and flush timeout
140
+ fail the verification instead of reporting success. Search for the printed trace
141
+ ID in your BTX project to verify visibility; an acknowledgment alone does not
142
+ establish storage or viewer visibility. The example owns and shuts down its
143
+ provider; an existing host app retains its own provider lifecycle.
144
+
145
+ ```python
146
+ drained = btx_processor.force_flush(timeout_millis=20_000)
147
+ ```
148
+
149
+ `force_flush()` returns `False` if its deadline expires. `True` means the queued
150
+ export attempts finished; it does not guarantee storage. A failed attempt can
151
+ finish draining the queue. Flush after traced work finishes and before a
152
+ short-lived runtime pauses. The method blocks the caller; use your framework's
153
+ thread offloading when calling it from async code.
154
+
155
+ During application shutdown, call `provider.shutdown()`. The BTX processor stops
156
+ accepting new spans and waits up to 20 seconds. Cleanup can continue in a daemon
157
+ thread after a timeout. Buffered data does not survive process termination.
158
+
159
+ ## Observe delivery
160
+
161
+ ```python
162
+ from btx_otel import BtxExportObservation, BtxSpanProcessor
163
+
164
+
165
+ def observe_export(result: BtxExportObservation) -> None:
166
+ print(result.outcome, result.spans, result.reason)
167
+
168
+
169
+ btx_processor = BtxSpanProcessor(
170
+ api_key=os.environ["BTX_API_KEY"],
171
+ on_export=observe_export,
172
+ )
173
+ ```
174
+
175
+ Register one processor from these examples. Observations contain `outcome`,
176
+ `spans`, `reason`, `http_status`, and `rejected_spans`. Outcomes are `accepted`,
177
+ `failed`, `partial_success`, and `overflow`. The counts describe the attempted
178
+ batch; `rejected_spans` identifies the rejected portion of a partial acknowledgment.
179
+ Partial-success responses are not replayed. Failed batches are not durably queued
180
+ for later recovery; the official exporter owns its bounded transport retries.
181
+
182
+ A warning-only acknowledgment reports `accepted` with reason `server_warning`
183
+ and zero rejected spans. Server warning text is never included in diagnostics.
184
+ Without a callback, these warnings use the same bounded logger as failures.
185
+
186
+ `on_export` can run on the application or exporter thread. Keep it fast and avoid
187
+ instrumented work inside it. Exceptions raised by this callback are ignored.
188
+ Without a callback, failures use the `btx_otel` logger. Diagnostics contain no
189
+ credentials, response bodies, or span content.
190
+ Repeated warnings for the same failure reason are suppressed until an export succeeds.
191
+
192
+ ## Advanced: Configure delivery
193
+
194
+ Delivery tuning is optional. Start with the defaults and override only the
195
+ settings your workload needs. For example, to shorten the export interval from
196
+ 30 seconds to 5 seconds, replace the basic processor configuration:
197
+
198
+ ```python
199
+ btx_processor = BtxSpanProcessor(
200
+ api_key=os.environ["BTX_API_KEY"],
201
+ schedule_delay_millis=5_000,
202
+ )
203
+ provider.add_span_processor(btx_processor)
204
+ ```
205
+
206
+ Register only one BTX processor. The supported delivery options are:
207
+
208
+ | Option | Default |
209
+ | --- | --- |
210
+ | `max_queue_size` | 512 pending spans, including export in progress |
211
+ | `max_export_batch_size` | 128 spans |
212
+ | `schedule_delay_millis` | 30,000 ms |
213
+ | `export_timeout_millis` | 15,000 ms per HTTP export |
214
+
215
+ Values must be positive integers, and `max_export_batch_size` must not exceed
216
+ `max_queue_size`. The export timeout applies to the HTTP exporter. The
217
+ `force_flush(timeout_millis=...)` deadline separately bounds the caller's wait.
218
+
219
+ The queue holds original spans within a 4 MiB encoded-size budget, including
220
+ export in progress. Size calculation runs synchronously when a span ends. A span
221
+ that exceeds the remaining queue budget is dropped.
222
+
223
+ The queue budget is not a total process-memory limit. Calculating encoded size
224
+ allocates a temporary representation before admission, and hooks can allocate
225
+ additional memory. Limit captured string lengths, attribute counts, events, and
226
+ links in the host's instrumentation and OTel span limits. Do not capture entire
227
+ request bodies or unbounded model output and rely on the queue to make it safe.
228
+
229
+ A single exported span must fit 128 KiB, and export batches split into requests
230
+ within a separate 4 MiB budget. Overhead is counted conservatively for each span.
231
+ Overflow drops the affected span and emits a diagnostic. Queue accounting is
232
+ released after all HTTP attempts for its batch finish. The receiver separately
233
+ enforces its projected JSON size limit; a span can fit its Protobuf budget and
234
+ still be rejected by the receiver. Accepted span content is not rewritten or
235
+ truncated.
236
+
237
+ HTTP response bodies have separate 4 MiB wire and decompressed limits. BTX reads
238
+ them incrementally and supports identity and gzip encoding. An oversized response
239
+ stops reading, closes the connection, and reports `failed` with reason
240
+ `response_too_large`; the batch is not retried. Invalid or unsupported response
241
+ encoding and malformed acknowledgments report `invalid_acknowledgment` without
242
+ retrying. These failures do not establish whether the server stored the batch.
243
+
244
+ BTX uses OTLP HTTP Protobuf and owns the endpoint and authorization headers.
245
+ Global OTel endpoint, header, and compression settings do not redirect BTX
246
+ exports. Trace IDs, parent relationships, resource/scope metadata, attributes,
247
+ events, links, and host sampling remain with the application.
248
+
249
+ See [connection details and troubleshooting](https://btx.so/docs/otel).
@@ -0,0 +1,8 @@
1
+ btx_otel/__init__.py,sha256=A4uP52XNjRyVQG-5QtKw1oZanB5pWpgA0Zkl_Zw6dQ4,198
2
+ btx_otel/_policy.py,sha256=gxBtzzSWZBY44pN5x2GQmTSNO_fvgWnCy0SH9SEh3gM,4345
3
+ btx_otel/_processor.py,sha256=Vv0E3XuxG0r68SLoiVyyEO7L3J75UAJpJNcXqDmf5Vg,19048
4
+ btx_otel/_response.py,sha256=iSbm00mxLeipnj0ZpZgBUj1-JvU2kX21qLuQ99P8Pqw,1961
5
+ btx_otel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ btx_otel-0.0.1.dist-info/METADATA,sha256=UB8Sxgmc3y94kfucXcuCxPP5kak7q-RXYBxF_lPQodI,11270
7
+ btx_otel-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ btx_otel-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any