| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import inspect |
| 4 |
from typing import TYPE_CHECKING, Any, Union, Callable, Iterable, Awaitable |
| 5 |
from typing_extensions import TypeAlias |
| 6 |
|
| 7 |
from ._request import APIRequest |
| 8 |
|
| 9 |
if TYPE_CHECKING: |
| 10 |
from ._response import APIResponse, AsyncAPIResponse |
| 11 |
|
| 12 |
__all__ = [ |
| 13 |
"Middleware", |
| 14 |
"CallNext", |
| 15 |
"AsyncCallNext", |
| 16 |
"MiddlewareCallable", |
| 17 |
"AsyncMiddlewareCallable", |
| 18 |
"MiddlewareInput", |
| 19 |
] |
| 20 |
|
| 21 |
CallNext: TypeAlias = Callable[[APIRequest], "APIResponse[Any]"] |
| 22 |
"""Invokes the rest of the middleware chain and, ultimately, a single HTTP attempt. |
| 23 |
|
| 24 |
The middleware chain runs inside the SDK's retry loop, once per attempt, and |
| 25 |
returns the `APIResponse` for every HTTP response, including 4xx/5xx — inspect |
| 26 |
`response.status_code` to react to API errors; the SDK raises its typed errors |
| 27 |
for the original caller after the chain. Connection failures have no response to |
| 28 |
return, so they raise (`APITimeoutError`, `APIConnectionError`). |
| 29 |
|
| 30 |
Returns the `APIResponse` wrapper; call `.parse()` on it to get the typed model. |
| 31 |
""" |
| 32 |
|
| 33 |
AsyncCallNext: TypeAlias = Callable[[APIRequest], Awaitable["AsyncAPIResponse[Any]"]] |
| 34 |
"""Invokes the rest of the middleware chain and, ultimately, a single HTTP attempt. |
| 35 |
|
| 36 |
The middleware chain runs inside the SDK's retry loop, once per attempt, and |
| 37 |
returns the `AsyncAPIResponse` for every HTTP response, including 4xx/5xx — inspect |
| 38 |
`response.status_code` to react to API errors; the SDK raises its typed errors |
| 39 |
for the original caller after the chain. Connection failures have no response to |
| 40 |
return, so they raise (`APITimeoutError`, `APIConnectionError`). |
| 41 |
|
| 42 |
Returns the `AsyncAPIResponse` wrapper; call `await .parse()` on it to get the typed model. |
| 43 |
""" |
| 44 |
|
| 45 |
|
| 46 |
class Middleware: |
| 47 |
"""Base class for client-level middleware. |
| 48 |
|
| 49 |
Subclass and override `handle` (used by the sync client) and/or `handle_async` |
| 50 |
(used by the async client). The default implementations delegate straight to |
| 51 |
the rest of the chain. |
| 52 |
""" |
| 53 |
|
| 54 |
def handle(self, request: APIRequest, call_next: CallNext) -> APIResponse[Any]: |
| 55 |
return call_next(request) |
| 56 |
|
| 57 |
async def handle_async(self, request: APIRequest, call_next: AsyncCallNext) -> AsyncAPIResponse[Any]: |
| 58 |
return await call_next(request) |
| 59 |
|
| 60 |
|
| 61 |
MiddlewareCallable: TypeAlias = Callable[[APIRequest, CallNext], "APIResponse[Any]"] |
| 62 |
AsyncMiddlewareCallable: TypeAlias = Callable[[APIRequest, AsyncCallNext], Awaitable["AsyncAPIResponse[Any]"]] |
| 63 |
MiddlewareInput: TypeAlias = Union[Middleware, MiddlewareCallable, AsyncMiddlewareCallable] |
| 64 |
|
| 65 |
|
| 66 |
def _middleware_name(middleware: object) -> str: |
| 67 |
if isinstance(middleware, Middleware): |
| 68 |
return type(middleware).__name__ |
| 69 |
name = getattr(middleware, "__name__", None) |
| 70 |
return name if isinstance(name, str) else repr(middleware) |
| 71 |
|
| 72 |
|
| 73 |
def _is_async_callable(obj: object) -> bool: |
| 74 |
"""Whether calling the given object returns a coroutine. |
| 75 |
|
| 76 |
Unlike `inspect.iscoroutinefunction(obj)` this also handles class instances |
| 77 |
that define an async `__call__` method. |
| 78 |
""" |
| 79 |
if inspect.iscoroutinefunction(obj): |
| 80 |
return True |
| 81 |
call = getattr(obj, "__call__", None) # noqa: B004 |
| 82 |
return call is not None and inspect.iscoroutinefunction(call) |
| 83 |
|
| 84 |
|
| 85 |
def validate_sync_middleware(middleware: Iterable[MiddlewareInput]) -> None: |
| 86 |
for entry in middleware: |
| 87 |
if isinstance(entry, Middleware): |
| 88 |
if type(entry).handle is Middleware.handle: |
| 89 |
raise TypeError( |
| 90 |
f"middleware {_middleware_name(entry)} does not implement `handle()`; " |
| 91 |
"the synchronous client requires sync-capable middleware" |
| 92 |
) |
| 93 |
if inspect.iscoroutinefunction(type(entry).handle): |
| 94 |
raise TypeError( |
| 95 |
f"middleware {_middleware_name(entry)} defines `handle()` as an async function; " |
| 96 |
"the synchronous client requires `handle()` to be a sync function" |
| 97 |
) |
| 98 |
elif not callable(entry): |
| 99 |
raise TypeError(f"middleware {_middleware_name(entry)} is not callable") |
| 100 |
elif _is_async_callable(entry): |
| 101 |
raise TypeError( |
| 102 |
f"middleware {_middleware_name(entry)} is an async function; " |
| 103 |
"the synchronous client requires sync middleware functions" |
| 104 |
) |
| 105 |
|
| 106 |
|
| 107 |
def validate_async_middleware(middleware: Iterable[MiddlewareInput]) -> None: |
| 108 |
for entry in middleware: |
| 109 |
if isinstance(entry, Middleware): |
| 110 |
if type(entry).handle_async is Middleware.handle_async: |
| 111 |
raise TypeError( |
| 112 |
f"middleware {_middleware_name(entry)} does not implement `handle_async()`; " |
| 113 |
"the asynchronous client requires async-capable middleware" |
| 114 |
) |
| 115 |
if not inspect.iscoroutinefunction(type(entry).handle_async): |
| 116 |
raise TypeError( |
| 117 |
f"middleware {_middleware_name(entry)} defines `handle_async()` as a sync function; " |
| 118 |
"the asynchronous client requires `handle_async()` to be an async function" |
| 119 |
) |
| 120 |
elif not callable(entry): |
| 121 |
raise TypeError(f"middleware {_middleware_name(entry)} is not callable") |
| 122 |
elif not _is_async_callable(entry): |
| 123 |
raise TypeError( |
| 124 |
f"middleware {_middleware_name(entry)} is not an async function; " |
| 125 |
"the asynchronous client requires async middleware functions" |
| 126 |
) |