from __future__ import annotations import asyncio import contextvars import functools import logging import time import uuid from contextlib import asynccontextmanager from typing import Any, Callable, TypeVar logger = logging.getLogger("simple_call_center.telemetry") _current_trace_id: contextvars.ContextVar[str | None] = contextvars.ContextVar("trace_id", default=None) _current_parent_span: contextvars.ContextVar[str | None] = contextvars.ContextVar("parent_span", default=None) _current_depth: contextvars.ContextVar[int] = contextvars.ContextVar("depth", default=0) F = TypeVar("F", bound=Callable[..., Any]) def trace_span(name: str | None = None): """Decorator for tracing sync/async functions in a waterfall hierarchy.""" def decorator(func: F) -> F: span_name = name or func.__qualname__ @functools.wraps(func) async def async_wrapper(*args: Any, **kwargs: Any) -> Any: async with time_span(span_name): return await func(*args, **kwargs) @functools.wraps(func) def sync_wrapper(*args: Any, **kwargs: Any) -> Any: return _run_sync_span(span_name, func, *args, **kwargs) return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper # type: ignore return decorator @asynccontextmanager async def time_span(span_name: str, **attributes: Any): """Context manager for tracing code blocks.""" trace_id = _current_trace_id.get() is_root = trace_id is None if is_root: trace_id = f"tr-{uuid.uuid4().hex[:8]}" _current_trace_id.set(trace_id) parent_span = _current_parent_span.get() or "ROOT" span_id = f"sp-{uuid.uuid4().hex[:6]}" depth = _current_depth.get() t_parent = _current_parent_span.set(span_id) t_depth = _current_depth.set(depth + 1) indent = " │ " * depth + " ├─ " if depth > 0 else "┌─ " attrs_str = f" | {attributes}" if attributes else "" logger.info( "WATERFALL | %s %s [START] [trace_id=%s span_id=%s parent=%s]%s", indent, span_name, trace_id, span_id, parent_span, attrs_str, extra={ "trace_id": trace_id, "span_id": span_id, "parent_span": parent_span, "span_name": span_name, "event": "start", }, ) start_time = time.perf_counter() try: yield span_id finally: duration_ms = (time.perf_counter() - start_time) * 1000 end_indent = " │ " * depth + " └─ " if depth > 0 else "└─ " logger.info( "WATERFALL | %s %s [END SUCCESS] duration=%.2fms [trace_id=%s span_id=%s parent=%s]", end_indent, span_name, duration_ms, trace_id, span_id, parent_span, extra={ "trace_id": trace_id, "span_id": span_id, "parent_span": parent_span, "span_name": span_name, "duration_ms": round(duration_ms, 2), "event": "end", }, ) _current_parent_span.reset(t_parent) _current_depth.reset(t_depth) if is_root: _current_trace_id.set(None) def _run_sync_span(span_name: str, func: Callable, *args: Any, **kwargs: Any) -> Any: trace_id = _current_trace_id.get() is_root = trace_id is None if is_root: trace_id = f"tr-{uuid.uuid4().hex[:8]}" _current_trace_id.set(trace_id) parent_span = _current_parent_span.get() or "ROOT" span_id = f"sp-{uuid.uuid4().hex[:6]}" depth = _current_depth.get() t_parent = _current_parent_span.set(span_id) t_depth = _current_depth.set(depth + 1) indent = " │ " * depth + " ├─ " if depth > 0 else "┌─ " logger.info( "WATERFALL | %s %s [START] [trace_id=%s span_id=%s parent=%s]", indent, span_name, trace_id, span_id, parent_span, ) start_time = time.perf_counter() try: return func(*args, **kwargs) finally: duration_ms = (time.perf_counter() - start_time) * 1000 end_indent = " │ " * depth + " └─ " if depth > 0 else "└─ " logger.info( "WATERFALL | %s %s [END SUCCESS] duration=%.2fms [trace_id=%s span_id=%s parent=%s]", end_indent, span_name, duration_ms, trace_id, span_id, parent_span, ) _current_parent_span.reset(t_parent) _current_depth.reset(t_depth) if is_root: _current_trace_id.set(None)