clientx 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clientx/_decoding.py ADDED
@@ -0,0 +1,240 @@
1
+ """Decode an endpoint's response as its return annotation says.
2
+
3
+ The return annotation decides how a response becomes the value an endpoint
4
+ returns, so most endpoints need no ``decoder=``:
5
+
6
+ -> None nothing
7
+ -> Response the response, read (unread with ``stream=True``)
8
+ -> str / -> bytes the body as text / as bytes
9
+ -> Iterator[str] the body streamed as lines
10
+ -> Iterator[bytes] the body streamed as chunks
11
+ -> anything else the JSON body, validated by a ``TypeAdapter``
12
+
13
+ An ``async def`` endpoint streams with ``AsyncIterator[str]`` and
14
+ ``AsyncIterator[bytes]`` instead.
15
+
16
+ An endpoint's own ``decoder=``, any callable that takes an ``httpx2.Response``,
17
+ replaces the decoder the annotation implies. An ``Iterator`` or
18
+ ``AsyncIterator`` annotation streams the response either way, and ``decode`` /
19
+ ``adecode`` close it when iteration ends.
20
+
21
+ A 4xx or 5xx response isn't decoded when the endpoint checks the status: the
22
+ wrapper calls ``raise_status_error`` (``araise_status_error`` for ``async def``)
23
+ instead, which raises ``httpx2.HTTPStatusError``.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Iterable, Iterator
29
+ from contextlib import AsyncExitStack
30
+ from types import NoneType
31
+ from typing import TYPE_CHECKING, Any, cast, get_args, get_origin
32
+
33
+ from httpx2 import Response
34
+ from pydantic import PydanticSchemaGenerationError, TypeAdapter
35
+
36
+ from clientx.exceptions import DefinitionError
37
+
38
+ if TYPE_CHECKING:
39
+ from clientx._signature import ReturnInfo
40
+ from clientx._types import Decoder
41
+
42
+
43
+ # --- Choosing a decoder -------------------------------------------------------
44
+ def is_stream(returns: ReturnInfo, *, is_async: bool) -> bool:
45
+ """Return whether an endpoint's return annotation makes it stream.
46
+
47
+ A ``def`` endpoint streams with ``-> Iterator[T]``, an ``async def`` one
48
+ with ``-> AsyncIterator[T]``.
49
+
50
+ Raises:
51
+ DefinitionError: If the annotation is the other kind of endpoint's
52
+ iterator.
53
+ """
54
+ origin = get_origin(returns.base_type)
55
+ if is_async and origin is Iterator:
56
+ raise DefinitionError("An `async def` endpoint streams an AsyncIterator: annotate it -> AsyncIterator[...].")
57
+ if not is_async and origin is AsyncIterator:
58
+ raise DefinitionError("A plain `def` endpoint streams an Iterator: annotate it -> Iterator[...].")
59
+ return origin is (AsyncIterator if is_async else Iterator)
60
+
61
+
62
+ def default_decoder(returns: ReturnInfo, *, is_async: bool) -> Decoder | None:
63
+ """Return the decoder ``returns`` implies, or ``None`` for ``-> None``.
64
+
65
+ It's for an endpoint without ``decoder=``, and dispatches on
66
+ ``returns.base_type``, so ``Annotated`` and ``type`` aliases don't hide the
67
+ type. The ``TypeAdapter`` gets the full ``returns.annotation``, so
68
+ ``Annotated`` constraints are validated too. It's built here, once, so a
69
+ type Pydantic can't validate fails now rather than on the first call.
70
+
71
+ Raises:
72
+ DefinitionError: If the annotation needs a ``decoder=``: it streams
73
+ items other than ``str`` or ``bytes``, or names a type Pydantic
74
+ can't validate. Also if it's the other kind of endpoint's iterator.
75
+ """
76
+ return_type = returns.base_type
77
+ if return_type is None or return_type is NoneType:
78
+ return None
79
+ if return_type is Response:
80
+ return _response
81
+ if return_type is str:
82
+ return _text
83
+ if return_type is bytes:
84
+ return _content
85
+ if is_stream(returns, is_async=is_async):
86
+ item = get_args(return_type)[0]
87
+ if item is str:
88
+ return _alines if is_async else _lines
89
+ if item is bytes:
90
+ return _achunks if is_async else _chunks
91
+ raise DefinitionError(
92
+ f"Streaming {_type_name(item)} items needs a decoder=: ClientX streams str (lines) and bytes "
93
+ "(chunks) by itself."
94
+ )
95
+ try:
96
+ adapter = TypeAdapter[Any](returns.annotation)
97
+ except PydanticSchemaGenerationError as error:
98
+ raise DefinitionError(
99
+ f"Pydantic can't validate {_type_name(returns.annotation)}: annotate a type it supports, "
100
+ "or pass a decoder=."
101
+ ) from error
102
+ return lambda response: adapter.validate_json(response.content)
103
+
104
+
105
+ def _type_name(annotation: Any) -> str:
106
+ return annotation.__qualname__ if isinstance(annotation, type) else repr(annotation)
107
+
108
+
109
+ # --- The default decoders -----------------------------------------------------
110
+ def _response(response: Response) -> Response:
111
+ return response
112
+
113
+
114
+ def _text(response: Response) -> str:
115
+ return response.text
116
+
117
+
118
+ def _content(response: Response) -> bytes:
119
+ return response.content
120
+
121
+
122
+ def _lines(response: Response) -> Iterator[str]:
123
+ return response.iter_lines()
124
+
125
+
126
+ def _chunks(response: Response) -> Iterator[bytes]:
127
+ return response.iter_bytes()
128
+
129
+
130
+ def _alines(response: Response) -> AsyncIterator[str]:
131
+ return response.aiter_lines()
132
+
133
+
134
+ def _achunks(response: Response) -> AsyncIterator[bytes]:
135
+ return response.aiter_bytes()
136
+
137
+
138
+ # --- Errors for 4xx and 5xx ---------------------------------------------------
139
+ def raise_status_error(response: Response) -> None:
140
+ """Raise ``httpx2.HTTPStatusError`` for a 4xx or 5xx ``response``.
141
+
142
+ The caller checks ``response.is_error`` first: called on a 3xx this would
143
+ raise, and on a successful streamed response it would read the body the
144
+ decoder should stream. The body is read, so the error keeps it, and the
145
+ response is closed, so a streamed one frees its connection. For a response
146
+ that isn't streamed, httpx2 has already done both, and they do nothing.
147
+ """
148
+ try:
149
+ response.read()
150
+ finally:
151
+ response.close()
152
+ response.raise_for_status()
153
+
154
+
155
+ async def araise_status_error(response: Response) -> None:
156
+ """Raise ``httpx2.HTTPStatusError`` for a 4xx or 5xx async ``response``.
157
+
158
+ See ``raise_status_error``.
159
+ """
160
+ try:
161
+ await response.aread()
162
+ finally:
163
+ await response.aclose()
164
+ response.raise_for_status()
165
+
166
+
167
+ # --- Decoding a response ------------------------------------------------------
168
+ def decode(decoder: Decoder | None, response: Response, *, stream: bool) -> object:
169
+ """Return a ``def`` endpoint's result: ``decoder``'s output, or ``None``.
170
+
171
+ For a streamed response, ``decoder`` returns an iterator. The response is
172
+ closed if the decoder raises, and otherwise when iteration finishes, stops
173
+ early, or fails.
174
+
175
+ Args:
176
+ decoder: The endpoint's decoder, or ``None`` for an endpoint that
177
+ returns nothing.
178
+ response: The response, read already unless ``stream`` is true.
179
+ stream: Whether the response was sent in streaming mode.
180
+ """
181
+ if decoder is None:
182
+ return None
183
+ if not stream:
184
+ return decoder(response)
185
+ try:
186
+ items = cast("Iterable[object]", decoder(response))
187
+ except BaseException:
188
+ response.close()
189
+ raise
190
+ return _close_when_done(items, response)
191
+
192
+
193
+ def _close_when_done(items: Iterable[object], response: Response) -> Iterator[object]:
194
+ """Yield from ``items``, then close ``response`` however iteration ends.
195
+
196
+ The ``finally`` block runs on exhaustion, on an exception, and when the
197
+ generator is closed (explicitly, or by a ``for`` loop that breaks early). An
198
+ iterator that's never started, or is kept alive, stays open until it's
199
+ closed or garbage-collected.
200
+ """
201
+ try:
202
+ yield from items
203
+ finally:
204
+ response.close()
205
+
206
+
207
+ async def adecode(decoder: Decoder | None, response: Response, *, stream: bool) -> object:
208
+ """Return an ``async def`` endpoint's result, as ``decode`` does.
209
+
210
+ A stream is an async iterator.
211
+ """
212
+ if decoder is None:
213
+ return None
214
+ if not stream:
215
+ return decoder(response)
216
+ try:
217
+ items = cast("AsyncIterable[object]", decoder(response))
218
+ except BaseException:
219
+ await response.aclose()
220
+ raise
221
+ return _aclose_when_done(items, response)
222
+
223
+
224
+ async def _aclose_when_done(items: AsyncIterable[object], response: Response) -> AsyncIterator[object]:
225
+ """Yield from ``items``, then close them and ``response``.
226
+
227
+ The exit stack closes them on exhaustion, on an exception, and when the
228
+ iterator is closed with ``aclose()``. If the caller stops iterating without
229
+ closing it, the event loop closes it when it's garbage-collected (the async
230
+ generator finalizer hook).
231
+ """
232
+ async with AsyncExitStack() as stack:
233
+ stack.push_async_callback(response.aclose)
234
+ # What `yield from` does for the sync version: close the decoder's own
235
+ # generator too. Callbacks run last in, first out: the generator, then
236
+ # the response.
237
+ if isinstance(items, AsyncGenerator):
238
+ stack.push_async_callback(items.aclose)
239
+ async for item in items:
240
+ yield item
clientx/_endpoint.py ADDED
@@ -0,0 +1,276 @@
1
+ """The ``Endpoint`` the verb decorators build for each endpoint method.
2
+
3
+ The decorator in ``_method.py`` creates one ``Endpoint`` per decorated method
4
+ when the class body runs, and registers it in ``_registry.py``. It holds the
5
+ decorator's options and the analysed signature, and works out how the response
6
+ is decoded, so the function isn't inspected again at call time. When the client
7
+ or resource class is defined, ``_class_setup.py`` sets its ``owner``, joins a
8
+ resource's prefix and tags onto ``raw_path`` and ``tags``, and calls
9
+ ``set_up_request``.
10
+ """
11
+
12
+ import functools
13
+ import inspect
14
+ from collections.abc import AsyncIterator, Iterator
15
+ from dataclasses import dataclass, field
16
+ from types import NoneType
17
+ from typing import Any, get_origin
18
+
19
+ from httpx2 import USE_CLIENT_DEFAULT, Response, Timeout
20
+
21
+ from clientx._builder import build_request
22
+ from clientx._decoding import default_decoder, is_stream
23
+ from clientx._planner import RequestPlan, plan_request
24
+ from clientx._signature import NO_VALUE, BoundCall, ParameterInfo, ParameterKind, SignatureInfo
25
+ from clientx._types import BuildRequestKwargs, Decoder, MethodType, UseClientDefault
26
+ from clientx.exceptions import DefinitionError
27
+
28
+
29
+ @dataclass(slots=True)
30
+ class Endpoint:
31
+ """An endpoint's HTTP method and path, its function, and its options.
32
+
33
+ Attributes:
34
+ method: The HTTP method, such as ``"GET"``.
35
+ signature: The function's analysed signature, with every parameter as
36
+ written. The first one receives the client or resource;
37
+ ``parameters()`` returns the rest.
38
+ tags: Labels that group endpoints, each tag once, in order. A resource
39
+ puts its own tags in front when its class is defined. ClientX
40
+ doesn't read them itself yet: they're for tooling.
41
+ raw_path: The path template, such as ``"/users/{user_id}"``. A resource
42
+ joins its prefix onto it when its class is defined.
43
+ decoder: Turns the ``httpx2.Response`` into the endpoint's return value.
44
+ It's the decorator's ``decoder=``, or else ``__post_init__`` sets
45
+ the one the return annotation implies. It stays ``None`` for
46
+ ``-> None``: the endpoint returns nothing.
47
+ deprecated: The message of the ``DeprecationWarning`` each call emits,
48
+ such as ``"Use new() instead."``; ``None`` if the endpoint isn't
49
+ deprecated.
50
+ timeout: The request timeout for this endpoint, passed to httpx2 as it
51
+ is, so it means what it does there: ``USE_CLIENT_DEFAULT`` (the
52
+ default) uses the client's, and ``None`` turns the timeout off.
53
+ raise_for_status: Whether a 4xx or 5xx response raises
54
+ ``httpx2.HTTPStatusError``; ``None`` uses the client's setting.
55
+ stream_response: The decorator's ``stream=True``: the endpoint returns
56
+ the open, unread response, which the caller reads and closes. Only
57
+ with ``-> Response``, and without a ``decoder=``.
58
+ owner: The client or resource class whose body declares the endpoint, or
59
+ ``None`` until that class is defined. An endpoint has one owner, so
60
+ a resource joins its prefix once.
61
+ request: How a call's arguments become the request, or ``None`` until
62
+ the owner class is defined and calls ``set_up_request``.
63
+ stream: Whether requests are sent in streaming mode: with
64
+ ``stream_response``, or because the return annotation is an
65
+ ``Iterator`` (``AsyncIterator`` for ``async def``).
66
+ ``__post_init__`` sets it.
67
+ """
68
+
69
+ method: MethodType
70
+ signature: SignatureInfo
71
+ tags: list[str] = field(default_factory=list[str])
72
+ raw_path: str = field(default="")
73
+ decoder: Decoder | None = field(default=None)
74
+ deprecated: str | None = field(default=None)
75
+ timeout: Timeout | float | None | UseClientDefault = field(default=USE_CLIENT_DEFAULT)
76
+ raise_for_status: bool | None = field(default=None)
77
+ stream_response: bool = field(default=False)
78
+ owner: type | None = field(default=None)
79
+ request: RequestPlan | None = field(default=None, init=False)
80
+ stream: bool = field(init=False)
81
+
82
+ def __post_init__(self) -> None:
83
+ """Check the signature and work out how to decode the response, once.
84
+
85
+ It runs when the method is decorated, before its class exists.
86
+
87
+ Raises:
88
+ DefinitionError: If the parameters, the return annotation,
89
+ ``stream=True`` or the ``decoder=`` can't work; see the
90
+ ``_check_*`` methods and ``default_decoder``.
91
+ """
92
+ self.tags = list(dict.fromkeys(self.tags)) # Each tag once, in order.
93
+ self._check_parameters()
94
+ self._check_return_annotation()
95
+ self._check_stream_response()
96
+ self._check_decoder()
97
+
98
+ name = self.signature.qualname
99
+ returns = self.signature.returns
100
+ is_async = self.signature.is_async
101
+ try:
102
+ self.stream = self.stream_response or is_stream(returns, is_async=is_async)
103
+ if self.decoder is None:
104
+ self.decoder = default_decoder(returns, is_async=is_async)
105
+ except DefinitionError as error:
106
+ raise DefinitionError(f"Endpoint '{name}': {error}") from error
107
+
108
+ def _check_parameters(self) -> None:
109
+ """Raise ``DefinitionError`` unless the parameters fit an endpoint.
110
+
111
+ The first parameter receives the client or resource, so a call must be
112
+ able to pass it positionally. Every other parameter sends one value,
113
+ which its annotation places in the request, so a ``*args`` or
114
+ ``**kwargs`` parameter has nowhere to go.
115
+ """
116
+ name = self.signature.qualname
117
+ first = self.signature.parameters[0] if self.signature.parameters else None
118
+ if first is None or first.kind not in (ParameterKind.POSITIONAL_ONLY, ParameterKind.POSITIONAL_OR_KEYWORD):
119
+ raise DefinitionError(
120
+ f"Endpoint '{name}' needs a positional first parameter, such as `self`, "
121
+ "for the client or resource it's called on."
122
+ )
123
+ for parameter in self.parameters():
124
+ if parameter.kind in (ParameterKind.VAR_POSITIONAL, ParameterKind.VAR_KEYWORD):
125
+ star = "*" if parameter.kind is ParameterKind.VAR_POSITIONAL else "**"
126
+ raise DefinitionError(
127
+ f"Endpoint '{name}' can't take `{star}{parameter.name}`: each value it sends needs a "
128
+ "parameter of its own, which decides where the value goes in the request."
129
+ )
130
+
131
+ def _check_return_annotation(self) -> None:
132
+ """Raise ``DefinitionError`` if the return annotation is missing."""
133
+ if self.signature.returns.annotation is NO_VALUE:
134
+ raise DefinitionError(
135
+ f"Endpoint '{self.signature.qualname}' needs a return annotation, such as `-> None` or "
136
+ "`-> User`: it decides what the endpoint returns."
137
+ )
138
+
139
+ def _check_stream_response(self) -> None:
140
+ """Raise ``DefinitionError`` if ``stream=True`` is misused.
141
+
142
+ It needs ``-> Response`` and no ``decoder=``: the endpoint then returns
143
+ the open response itself, so another return type has nothing to say, and
144
+ a decoder would leave nobody sure who closes the response.
145
+ """
146
+ if not self.stream_response:
147
+ return
148
+ name = self.signature.qualname
149
+ if self.signature.returns.base_type is not Response:
150
+ raise DefinitionError(
151
+ f"Endpoint '{name}' has stream=True, which returns the open response, so annotate it "
152
+ "-> Response. An Iterator annotation, such as -> Iterator[bytes], streams the body by itself."
153
+ )
154
+ if self.decoder is not None:
155
+ raise DefinitionError(
156
+ f"Endpoint '{name}' has stream=True, which returns the open response, so it can't also take a decoder=."
157
+ )
158
+
159
+ def _check_decoder(self) -> None:
160
+ """Raise ``DefinitionError`` if ``decoder=`` can't fit the annotation.
161
+
162
+ An endpoint annotated ``-> None`` returns nothing, so it takes no
163
+ decoder. A decoder is a plain function that gets the response: the body
164
+ is already read, or, for an endpoint annotated as a stream, the decoder
165
+ returns the iterator. So it can't be ``async def``, and a generator
166
+ decoder streams: a plain generator for a ``def`` endpoint annotated
167
+ ``-> Iterator[...]``, an async generator for an ``async def`` one
168
+ annotated ``-> AsyncIterator[...]``. A decoder that returns an iterator
169
+ without being a generator can't be told apart here; type checkers check
170
+ it against the annotation.
171
+ """
172
+ if self.decoder is None:
173
+ return
174
+ name = self.signature.qualname
175
+ returns = self.signature.returns.base_type
176
+ if returns is None or returns is NoneType:
177
+ raise DefinitionError(
178
+ f"Endpoint '{name}' is annotated -> None, so it returns nothing and can't take a decoder=. "
179
+ "Annotate what the decoder returns."
180
+ )
181
+ function = _function_of(self.decoder)
182
+ if inspect.iscoroutinefunction(function):
183
+ raise DefinitionError(
184
+ f"Endpoint '{name}': decoder= must be a plain function, not `async def`: the response is read "
185
+ "before the decoder runs. To stream an `async def` endpoint, use an async generator, an "
186
+ "`async def` with `yield`."
187
+ )
188
+ is_async = self.signature.is_async
189
+ if inspect.isasyncgenfunction(function) and not is_async:
190
+ raise DefinitionError(
191
+ f"Endpoint '{name}' is a plain `def`, so its decoder can't be an async generator: use a "
192
+ "generator, a `def` with `yield`."
193
+ )
194
+ if inspect.isgeneratorfunction(function) and is_async:
195
+ raise DefinitionError(
196
+ f"Endpoint '{name}' is `async def`, so its stream decoder must be an async generator, an "
197
+ "`async def` with `yield`, not a plain generator."
198
+ )
199
+ streams = get_origin(returns) is (AsyncIterator if is_async else Iterator)
200
+ if (inspect.isgeneratorfunction(function) or inspect.isasyncgenfunction(function)) and not streams:
201
+ iterator = "AsyncIterator" if is_async else "Iterator"
202
+ raise DefinitionError(
203
+ f"Endpoint '{name}': a generator decoder streams the response, so annotate the endpoint "
204
+ f"-> {iterator}[...]."
205
+ )
206
+
207
+ def bind(self, owner: object, *args: Any, **kwargs: Any) -> BoundCall:
208
+ """Return a call's arguments by name, in order, with defaults filled in.
209
+
210
+ ``owner``, the client or resource the endpoint was called on, fills the
211
+ first parameter and is left out of the result.
212
+
213
+ Raises:
214
+ TypeError: If the arguments don't fit the signature, as in a normal
215
+ call.
216
+ """
217
+ bound = self.signature.bind(owner, *args, **kwargs)
218
+ owner_name = self.signature.parameters[0].name
219
+ del bound.arguments[owner_name]
220
+ return BoundCall(bound.arguments, bound.passed - {owner_name})
221
+
222
+ def parameters(self) -> tuple[ParameterInfo, ...]:
223
+ """Return all parameters but the first: the client or resource."""
224
+ return self.signature.parameters[1:]
225
+
226
+ def set_up_request(self) -> None:
227
+ """Work out how a call's arguments become the request, once.
228
+
229
+ It also checks the path against the parameters. ``_class_setup`` calls
230
+ it when the owner class is defined, after joining a resource's prefix
231
+ onto ``raw_path``: the prefix can add placeholders.
232
+
233
+ Raises:
234
+ DefinitionError: If the path template and the parameters don't fit
235
+ together; see ``plan_request``.
236
+ """
237
+ try:
238
+ self.request = plan_request(self.raw_path, self.parameters(), is_async=self.signature.is_async)
239
+ except DefinitionError as error:
240
+ raise DefinitionError(f"Endpoint '{self.signature.qualname}': {error}") from error
241
+
242
+ def request_arguments(self, bound: BoundCall) -> tuple[str, BuildRequestKwargs]:
243
+ """Return a call's URL path and its other ``build_request`` arguments.
244
+
245
+ The plan supplies the parts that carry the call's arguments; the
246
+ endpoint adds its ``timeout``.
247
+
248
+ Args:
249
+ bound: The call's arguments, as ``bind`` returns them.
250
+
251
+ Raises:
252
+ DefinitionError: If the endpoint isn't declared in the body of a
253
+ client or resource class, so it has no ``request`` plan.
254
+ ArgumentError: If an argument's value can't be sent.
255
+ """
256
+ if self.request is None:
257
+ raise DefinitionError(
258
+ f"Endpoint '{self.signature.qualname}' can't be called: it isn't declared in the body of a "
259
+ "ClientX, AsyncClientX, Resource or AsyncResource subclass."
260
+ )
261
+ url, request_arguments = build_request(self.request, bound.arguments, bound.passed)
262
+ request_arguments["timeout"] = self.timeout
263
+ return url, request_arguments
264
+
265
+
266
+ def _function_of(decoder: Decoder) -> object:
267
+ """Return the function a decoder runs: itself, or its class's ``__call__``.
268
+
269
+ ``inspect`` sees through functions, methods and ``functools.partial``, but
270
+ not through a callable instance, so a decoder class with an
271
+ ``async def __call__`` is checked by its method.
272
+ """
273
+ function: object = decoder
274
+ if not (inspect.isroutine(decoder) or isinstance(decoder, functools.partial)):
275
+ function = type(decoder).__call__
276
+ return function