|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from enum import Enum |
| 5 | +from dataclasses import dataclass |
| 6 | + |
| 7 | +from agentex.types.span import Span |
| 8 | +from agentex.lib.utils.logging import make_logger |
| 9 | +from agentex.lib.core.tracing.processors.tracing_processor_interface import ( |
| 10 | + AsyncTracingProcessor, |
| 11 | +) |
| 12 | + |
| 13 | +logger = make_logger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +class SpanEventType(str, Enum): |
| 17 | + START = "start" |
| 18 | + END = "end" |
| 19 | + |
| 20 | + |
| 21 | +@dataclass |
| 22 | +class _SpanQueueItem: |
| 23 | + event_type: SpanEventType |
| 24 | + span: Span |
| 25 | + processors: list[AsyncTracingProcessor] |
| 26 | + |
| 27 | + |
| 28 | +class AsyncSpanQueue: |
| 29 | + """Background FIFO queue for async span processing. |
| 30 | +
|
| 31 | + Span events are enqueued synchronously (non-blocking) and processed |
| 32 | + sequentially by a background drain task. This keeps tracing HTTP calls |
| 33 | + off the critical request path while preserving start-before-end ordering. |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__(self) -> None: |
| 37 | + self._queue: asyncio.Queue[_SpanQueueItem] = asyncio.Queue() |
| 38 | + self._drain_task: asyncio.Task[None] | None = None |
| 39 | + self._stopping = False |
| 40 | + |
| 41 | + def enqueue( |
| 42 | + self, |
| 43 | + event_type: SpanEventType, |
| 44 | + span: Span, |
| 45 | + processors: list[AsyncTracingProcessor], |
| 46 | + ) -> None: |
| 47 | + if self._stopping: |
| 48 | + logger.warning("Span queue is shutting down, dropping %s event for span %s", event_type.value, span.id) |
| 49 | + return |
| 50 | + self._ensure_drain_running() |
| 51 | + self._queue.put_nowait(_SpanQueueItem(event_type=event_type, span=span, processors=processors)) |
| 52 | + |
| 53 | + def _ensure_drain_running(self) -> None: |
| 54 | + if self._drain_task is None or self._drain_task.done(): |
| 55 | + self._drain_task = asyncio.create_task(self._drain_loop()) |
| 56 | + |
| 57 | + async def _drain_loop(self) -> None: |
| 58 | + while True: |
| 59 | + item = await self._queue.get() |
| 60 | + try: |
| 61 | + if item.event_type == SpanEventType.START: |
| 62 | + coros = [p.on_span_start(item.span) for p in item.processors] |
| 63 | + else: |
| 64 | + coros = [p.on_span_end(item.span) for p in item.processors] |
| 65 | + results = await asyncio.gather(*coros, return_exceptions=True) |
| 66 | + for result in results: |
| 67 | + if isinstance(result, Exception): |
| 68 | + logger.error( |
| 69 | + "Tracing processor error during %s for span %s", |
| 70 | + item.event_type.value, |
| 71 | + item.span.id, |
| 72 | + exc_info=result, |
| 73 | + ) |
| 74 | + except Exception: |
| 75 | + logger.exception("Unexpected error in span queue drain loop for span %s", item.span.id) |
| 76 | + finally: |
| 77 | + self._queue.task_done() |
| 78 | + |
| 79 | + async def shutdown(self, timeout: float = 30.0) -> None: |
| 80 | + self._stopping = True |
| 81 | + if self._queue.empty() and (self._drain_task is None or self._drain_task.done()): |
| 82 | + return |
| 83 | + try: |
| 84 | + await asyncio.wait_for(self._queue.join(), timeout=timeout) |
| 85 | + except asyncio.TimeoutError: |
| 86 | + logger.warning( |
| 87 | + "Span queue shutdown timed out after %.1fs with %d items remaining", timeout, self._queue.qsize() |
| 88 | + ) |
| 89 | + if self._drain_task is not None and not self._drain_task.done(): |
| 90 | + self._drain_task.cancel() |
| 91 | + try: |
| 92 | + await self._drain_task |
| 93 | + except asyncio.CancelledError: |
| 94 | + pass |
| 95 | + |
| 96 | + |
| 97 | +_default_span_queue: AsyncSpanQueue | None = None |
| 98 | + |
| 99 | + |
| 100 | +def get_default_span_queue() -> AsyncSpanQueue: |
| 101 | + global _default_span_queue |
| 102 | + if _default_span_queue is None: |
| 103 | + _default_span_queue = AsyncSpanQueue() |
| 104 | + return _default_span_queue |
| 105 | + |
| 106 | + |
| 107 | +async def shutdown_default_span_queue(timeout: float = 30.0) -> None: |
| 108 | + global _default_span_queue |
| 109 | + if _default_span_queue is not None: |
| 110 | + await _default_span_queue.shutdown(timeout=timeout) |
| 111 | + _default_span_queue = None |
0 commit comments