Skip to content

Commit

Permalink
Make OpenTelemetry transport respect Httpx context managers
Browse files Browse the repository at this point in the history
  • Loading branch information
sam-mosleh committed Feb 26, 2023
1 parent 0417141 commit 2703611
Showing 1 changed file with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ def response_hook(span, request, response):
"""
import logging
import typing
from types import TracebackType

import httpx

Expand Down Expand Up @@ -293,6 +294,18 @@ def __init__(
self._request_hook = request_hook
self._response_hook = response_hook

def __enter__(self) -> "SyncOpenTelemetryTransport":
self._transport.__enter__()
return self

def __exit__(
self,
exc_type: typing.Optional[typing.Type[BaseException]] = None,
exc_value: typing.Optional[BaseException] = None,
traceback: typing.Optional[TracebackType] = None,
) -> None:
self._transport.__exit__(exc_type, exc_value, traceback)

def handle_request(
self,
*args,
Expand Down Expand Up @@ -343,6 +356,9 @@ def handle_request(

return response

def close(self) -> None:
self._transport.close()


class AsyncOpenTelemetryTransport(httpx.AsyncBaseTransport):
"""Async transport class that will trace all requests made with a client.
Expand Down Expand Up @@ -372,6 +388,18 @@ def __init__(
self._request_hook = request_hook
self._response_hook = response_hook

async def __aenter__(self: A) -> A: # Use generics for subclass support.
await self._transport.__aenter__()
return self

async def __aexit__(
self,
exc_type: typing.Optional[typing.Type[BaseException]] = None,
exc_value: typing.Optional[BaseException] = None,
traceback: typing.Optional[TracebackType] = None,
) -> None:
await self._transport.__aexit__(exc_type, exc_value, traceback)

async def handle_async_request(
self, *args, **kwargs
) -> typing.Union[
Expand Down Expand Up @@ -423,6 +451,9 @@ async def handle_async_request(

return response

async def aclose(self) -> None:
await self._transport.aclose()


class _InstrumentedClient(httpx.Client):
_tracer_provider = None
Expand Down

0 comments on commit 2703611

Please sign in to comment.