|
| 1 | +from .types import ( |
| 2 | + AfterErrorContext, |
| 3 | + AfterErrorHook, |
| 4 | + AfterSuccessContext, |
| 5 | + AfterSuccessHook, |
| 6 | + BeforeRequestContext, |
| 7 | + BeforeRequestHook, |
| 8 | +) |
| 9 | +from ..extra.observability.otel import ( |
| 10 | + get_traced_request_and_span, |
| 11 | + get_traced_response, |
| 12 | + get_response_and_error, |
| 13 | + get_or_create_otel_tracer, |
| 14 | +) |
| 15 | + |
| 16 | +from opentelemetry.trace import Span |
| 17 | +from typing import Optional, Tuple, Union |
| 18 | + |
| 19 | +import httpx |
| 20 | +import logging |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | + |
| 25 | +class TracingHook(BeforeRequestHook, AfterSuccessHook, AfterErrorHook): |
| 26 | + def __init__(self) -> None: |
| 27 | + self.tracing_enabled, self.tracer = get_or_create_otel_tracer() |
| 28 | + self.request_span: Optional[Span] = None |
| 29 | + |
| 30 | + def before_request( |
| 31 | + self, hook_ctx: BeforeRequestContext, request: httpx.Request |
| 32 | + ) -> Union[httpx.Request, Exception]: |
| 33 | + request, self.request_span = get_traced_request_and_span(tracing_enabled=self.tracing_enabled, tracer=self.tracer, span=self.request_span, operation_id=hook_ctx.operation_id, request=request) |
| 34 | + return request |
| 35 | + |
| 36 | + def after_success( |
| 37 | + self, hook_ctx: AfterSuccessContext, response: httpx.Response |
| 38 | + ) -> Union[httpx.Response, Exception]: |
| 39 | + response = get_traced_response(tracing_enabled=self.tracing_enabled, tracer=self.tracer, span=self.request_span, operation_id=hook_ctx.operation_id, response=response) |
| 40 | + return response |
| 41 | + |
| 42 | + def after_error( |
| 43 | + self, |
| 44 | + hook_ctx: AfterErrorContext, |
| 45 | + response: Optional[httpx.Response], |
| 46 | + error: Optional[Exception], |
| 47 | + ) -> Union[Tuple[Optional[httpx.Response], Optional[Exception]], Exception]: |
| 48 | + if response: |
| 49 | + response, error = get_response_and_error(tracing_enabled=self.tracing_enabled, tracer=self.tracer, span=self.request_span, operation_id=hook_ctx.operation_id, response=response, error=error) |
| 50 | + return response, error |
0 commit comments