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.
@@ -0,0 +1,252 @@
1
+ """Set up client and resource subclasses when they're defined.
2
+
3
+ ``__init_subclass__`` on the bases in ``_client.py`` calls into this module, so
4
+ the rules that run once per class live here, apart from the classes themselves.
5
+ This module imports nothing from ``_client.py`` at runtime, so ``_client.py``
6
+ can import it without a circular import.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import inspect
12
+ from collections.abc import Sequence
13
+ from functools import cache
14
+ from typing import TYPE_CHECKING
15
+
16
+ from httpx2 import URL, InvalidURL
17
+
18
+ from clientx._registry import endpoint_for
19
+ from clientx.exceptions import DefinitionError
20
+
21
+ if TYPE_CHECKING:
22
+ from clientx._client import AsyncClientX, AsyncResource, ClientX, Resource
23
+ from clientx._endpoint import Endpoint
24
+
25
+
26
+ # --- Setting up a class -------------------------------------------------------
27
+ # The sync and the async base of each kind of class, by `__clientx_is_async__`,
28
+ # for error messages.
29
+ _CLIENT_BASES = ("ClientX", "AsyncClientX")
30
+ _RESOURCE_BASES = ("Resource", "AsyncResource")
31
+
32
+
33
+ def set_up_client(
34
+ cls: type[ClientX | AsyncClientX],
35
+ *,
36
+ base: type[ClientX | AsyncClientX],
37
+ base_url: URL | str | None,
38
+ user_agent: str | None,
39
+ ) -> None:
40
+ """Set up a new client subclass: check its body and claim its endpoints.
41
+
42
+ ``base`` is ``ClientX`` or ``AsyncClientX``, whose names the endpoints can't
43
+ use. A subclass without its own ``base_url`` or ``user_agent`` keeps its
44
+ parent's. Claiming the endpoints stops a resource from taking one and
45
+ joining its prefix onto the client's path. Each endpoint's request plan is
46
+ worked out once its path is final.
47
+ """
48
+ _check_one_kind(cls, _CLIENT_BASES)
49
+ _check_member_names(cls, base, fix="Rename it, or put it on a Resource mounted on the client.")
50
+ _check_resource_classes(cls)
51
+ _check_endpoint_kinds(cls, _CLIENT_BASES)
52
+ if base_url is not None:
53
+ try:
54
+ cls.__clientx_base_url__ = parse_base_url(base_url)
55
+ except ValueError as error:
56
+ raise DefinitionError(f"'{cls.__qualname__}' can't have this class argument: {error}") from error
57
+ if user_agent is not None:
58
+ cls.__clientx_user_agent__ = user_agent
59
+ for endpoint in _claim_endpoints(cls):
60
+ endpoint.set_up_request()
61
+
62
+
63
+ def set_up_resource(
64
+ cls: type[Resource | AsyncResource],
65
+ *,
66
+ base: type[Resource | AsyncResource],
67
+ prefix: str | None,
68
+ tags: Sequence[str] | None,
69
+ ) -> None:
70
+ """Set up a new resource subclass: check it, and apply its prefix and tags.
71
+
72
+ ``base`` is ``Resource`` or ``AsyncResource``, whose names the endpoints
73
+ can't use. A subclass without its own ``prefix`` keeps its parent's, and its
74
+ ``tags`` are added to its parent's, each tag once. The prefix is joined to
75
+ each endpoint's path now, so it's absolute: it doesn't depend on where the
76
+ resource is mounted. Each endpoint's request plan is worked out after the
77
+ join, because the prefix can add placeholders.
78
+ """
79
+ _check_one_kind(cls, _RESOURCE_BASES)
80
+ _check_member_names(cls, base, fix="Rename it.")
81
+ _check_resource_classes(cls)
82
+ _check_endpoint_kinds(cls, _RESOURCE_BASES)
83
+ if prefix is not None:
84
+ cls.__clientx_prefix__ = prefix
85
+ if tags is not None:
86
+ # Until now, `cls` inherits its parent's tags: add its own after them.
87
+ cls.__clientx_tags__ = tuple(dict.fromkeys([*cls.__clientx_tags__, *tags]))
88
+ for endpoint in _claim_endpoints(cls):
89
+ endpoint.raw_path = _join_path(cls.__clientx_prefix__, endpoint.raw_path)
90
+ endpoint.tags = list(dict.fromkeys([*cls.__clientx_tags__, *endpoint.tags]))
91
+ endpoint.set_up_request()
92
+
93
+
94
+ def check_mount(resource_name: str, *, is_async: bool, owner: type) -> None:
95
+ """Raise ``DefinitionError`` unless a resource's owner is its own kind.
96
+
97
+ A resource's ``__set_name__`` calls it when an instance is assigned in
98
+ ``owner``'s body. A ``Resource``'s ``def`` endpoints need a ``ClientX`` to
99
+ send through, and an ``AsyncResource``'s ``async def`` endpoints an
100
+ ``AsyncClientX``.
101
+ """
102
+ owner_kind = getattr(owner, "__clientx_is_async__", None)
103
+ if owner_kind is is_async:
104
+ return
105
+ client, resource = _CLIENT_BASES[is_async], _RESOURCE_BASES[is_async]
106
+ message = (
107
+ f"{resource} '{resource_name}' can only be mounted on a{'n' if is_async else ''} {client} or "
108
+ f"{resource} subclass, not on '{owner.__qualname__}'."
109
+ )
110
+ if owner_kind is not None:
111
+ other_client, other_resource = _CLIENT_BASES[not is_async], _RESOURCE_BASES[not is_async]
112
+ message += f" For {'a' if is_async else 'an'} {other_client}, subclass {other_resource} instead."
113
+ raise DefinitionError(message)
114
+
115
+
116
+ def parse_base_url(base_url: URL | str) -> URL:
117
+ """Return a base URL as a URL, or raise ``ValueError`` if it isn't absolute.
118
+
119
+ It needs a scheme and a host: httpx2 would take ``"api.example.com"`` as a
120
+ relative path, and fail only on the first request. A client's ``__init__``
121
+ checks the one it's given; ``set_up_client`` checks a class's, and raises
122
+ ``DefinitionError`` instead.
123
+ """
124
+ try:
125
+ url = URL(base_url)
126
+ except InvalidURL as error:
127
+ raise ValueError(f"base_url={base_url!r} isn't a URL: {error}.") from error
128
+ if not url.is_absolute_url:
129
+ raise ValueError(f'base_url={base_url!r} needs a scheme and a host, as in "https://api.example.com".')
130
+ return url
131
+
132
+
133
+ # --- Checks on a class body ---------------------------------------------------
134
+ def _check_one_kind(cls: type, bases: tuple[str, str]) -> None:
135
+ """Raise ``DefinitionError`` if ``cls`` has both a sync and an async base.
136
+
137
+ Each base, such as ``ClientX`` or ``AsyncClientX``, sets
138
+ ``__clientx_is_async__`` in its own body, so a class that inherits both has
139
+ both values among the classes in its MRO.
140
+ """
141
+ kinds = {vars(class_)["__clientx_is_async__"] for class_ in cls.__mro__ if "__clientx_is_async__" in vars(class_)}
142
+ if len(kinds) > 1:
143
+ raise DefinitionError(f"'{cls.__qualname__}' can't subclass both {bases[0]} and {bases[1]}: choose one.")
144
+
145
+
146
+ def _check_endpoint_kinds(cls: type[ClientX | AsyncClientX | Resource | AsyncResource], bases: tuple[str, str]) -> None:
147
+ """Raise ``DefinitionError`` if an endpoint is the wrong kind for ``cls``.
148
+
149
+ ``ClientX`` and ``Resource`` send with a sync ``httpx2.Client``, so their
150
+ endpoints are ``def`` methods; ``AsyncClientX`` and ``AsyncResource``
151
+ endpoints are ``async def`` methods. Endpoints inherited from a parent class
152
+ were checked when it was defined.
153
+ """
154
+ is_async = cls.__clientx_is_async__
155
+ for value in vars(cls).values():
156
+ endpoint = endpoint_for(value)
157
+ if endpoint is not None and endpoint.signature.is_async != is_async:
158
+ kind, fix = ("`async def`", "`def`") if endpoint.signature.is_async else ("a plain `def`", "`async def`")
159
+ raise DefinitionError(
160
+ f"Endpoint '{endpoint.signature.qualname}' is {kind}, so it can't be an endpoint of "
161
+ f"'{cls.__qualname__}', a{'n' if is_async else ''} {bases[is_async]} subclass. "
162
+ f"Define it with {fix}, or subclass {bases[not is_async]} instead."
163
+ )
164
+
165
+
166
+ def _check_member_names(cls: type, base: type, *, fix: str) -> None:
167
+ """Raise ``DefinitionError`` if an endpoint or resource has a reserved name.
168
+
169
+ Overriding one breaks the client: an endpoint named ``send`` would replace
170
+ the ``httpx2.Client.send`` that every request goes through. Other members,
171
+ such as the subclass's own ``__init__``, may override ``base``'s names as
172
+ usual.
173
+ """
174
+ reserved = _reserved_names(base)
175
+ for name, value in vars(cls).items():
176
+ if name in reserved and (endpoint_for(value) is not None or _is_resource(value)):
177
+ raise DefinitionError(
178
+ f"'{cls.__qualname__}.{name}' (defined in {cls.__module__}) can't be named '{name}': "
179
+ f"{base.__name__} already uses that name, and overriding it breaks the client. {fix}"
180
+ )
181
+
182
+
183
+ @cache
184
+ def _reserved_names(base: type) -> frozenset[str]:
185
+ """Return the names endpoints and mounted resources can't use on ``base``.
186
+
187
+ That's everything it defines: ``dir(base)``, which for a client includes all
188
+ of ``httpx2.Client``'s names, plus the instance attributes ``base`` and its
189
+ parents declare.
190
+ """
191
+ return frozenset(dir(base)).union(*(inspect.get_annotations(cls) for cls in base.__mro__))
192
+
193
+
194
+ def _check_resource_classes(cls: type) -> None:
195
+ """Raise ``DefinitionError`` for a resource class in ``cls``'s body.
196
+
197
+ ``users = Users`` instead of ``users = Users()`` isn't mounted: each call
198
+ would fail on its endpoint's ``self``, far from the mistake. A resource
199
+ class defined in the body itself, to be mounted there, is fine: its
200
+ qualified name is ``cls``'s plus its own.
201
+ """
202
+ for name, value in vars(cls).items():
203
+ is_resource_class = isinstance(value, type) and hasattr(value, "__clientx_prefix__")
204
+ if is_resource_class and value.__qualname__ != f"{cls.__qualname__}.{name}":
205
+ raise DefinitionError(
206
+ f"'{cls.__qualname__}.{name}' is the resource class {value.__qualname__}, not an instance, so it "
207
+ f"isn't mounted. Mount an instance: {name} = {value.__name__}()."
208
+ )
209
+
210
+
211
+ def _is_resource(value: object) -> bool:
212
+ """Return whether ``value`` is a mounted resource.
213
+
214
+ Only resource classes define ``__clientx_prefix__``, so this module needn't
215
+ import them. It's looked up on the type, so an object whose ``__getattr__``
216
+ answers any name doesn't count.
217
+ """
218
+ return hasattr(type(value), "__clientx_prefix__")
219
+
220
+
221
+ # --- Claiming endpoints -------------------------------------------------------
222
+ def _claim_endpoints(cls: type) -> list[Endpoint]:
223
+ """Make ``cls`` the owner of the endpoints in its body, and return them.
224
+
225
+ A second name for an endpoint in the same body (an alias,
226
+ ``QueryDevices = query_devices``) is the same endpoint, so a resource joins
227
+ its prefix once. An endpoint that another class's body already has raises
228
+ ``DefinitionError``: a resource would join its prefix onto that endpoint's
229
+ path too, and an endpoint has one path.
230
+ """
231
+ claimed: list[Endpoint] = []
232
+ for value in vars(cls).values():
233
+ endpoint = endpoint_for(value)
234
+ if endpoint is None or endpoint.owner is cls:
235
+ continue
236
+ if endpoint.owner is not None:
237
+ raise DefinitionError(
238
+ f"Endpoint '{endpoint.signature.qualname}' belongs to '{endpoint.owner.__qualname__}', so it can't "
239
+ f"also be an endpoint of '{cls.__qualname__}': an endpoint has one path. Declare it in "
240
+ f"'{cls.__qualname__}' too."
241
+ )
242
+ endpoint.owner = cls
243
+ claimed.append(endpoint)
244
+ return claimed
245
+
246
+
247
+ def _join_path(prefix: str, path: str) -> str:
248
+ if not prefix:
249
+ return path
250
+ if not path:
251
+ return prefix
252
+ return prefix.rstrip("/") + "/" + path.lstrip("/")
clientx/_client.py ADDED
@@ -0,0 +1,300 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from copy import copy
5
+ from typing import Any, ClassVar, Self, Unpack, cast
6
+
7
+ from httpx2 import URL, AsyncClient, Client, Headers
8
+
9
+ from clientx._class_setup import check_mount, parse_base_url, set_up_client, set_up_resource
10
+ from clientx._types import AsyncHttpxClientOptions, HeaderTypes, HttpxClientOptions
11
+ from clientx._version import __version__
12
+ from clientx.exceptions import DefinitionError
13
+
14
+ type EndpointOwner = ClientX | AsyncClientX | Resource | AsyncResource
15
+
16
+
17
+ # --- Clients ------------------------------------------------------------------
18
+ class _BaseClientX:
19
+ # The class arguments: what a client uses when its caller doesn't say.
20
+ __clientx_base_url__: ClassVar[URL | None] = None
21
+ __clientx_user_agent__: ClassVar[str] = f"ClientX/{__version__}"
22
+ __clientx_raise_for_status__: bool = True
23
+
24
+ def __repr__(self) -> str:
25
+ client = cast("ClientX | AsyncClientX", self)
26
+ return (
27
+ f"{type(self).__qualname__}(base_url={_masked(client.base_url)!r}, "
28
+ f"user_agent={client.headers.get('User-Agent')!r})"
29
+ )
30
+
31
+
32
+ def _masked(url: URL) -> str:
33
+ """Return ``url`` as text with any password masked, for a repr."""
34
+ text = str(url)
35
+ if not url.password:
36
+ return text
37
+ userinfo = url.userinfo.decode("ascii")
38
+ username = userinfo.split(":", 1)[0]
39
+ return text.replace(f"//{userinfo}@", f"//{username}:[redacted]@", 1)
40
+
41
+
42
+ class ClientX(_BaseClientX, Client):
43
+ """Base class for an HTTP API client: subclass it and declare endpoints.
44
+
45
+ An endpoint is a ``def`` method with an empty body and a ``clientx.method``
46
+ decorator. Its signature and annotations say how to build the request and
47
+ decode the response. A ``ClientX`` is an ``httpx2.Client``, so it's
48
+ configured, used and closed like one::
49
+
50
+ class UsersAPI(ClientX, base_url="https://api.example.com"):
51
+ @method.get("/users/{user_id}")
52
+ def get_user(self, user_id: int) -> User: ...
53
+
54
+ with UsersAPI() as api:
55
+ user = api.get_user(1)
56
+ """
57
+
58
+ # Which kind of class this is: `def` endpoints and resources. `_class_setup`
59
+ # reads it.
60
+ __clientx_is_async__: ClassVar[bool] = False
61
+
62
+ def __init__(
63
+ self,
64
+ base_url: URL | str | None = None,
65
+ *,
66
+ user_agent: str | None = None,
67
+ raise_for_status: bool | None = None,
68
+ **kwargs: Unpack[HttpxClientOptions],
69
+ ) -> None:
70
+ """Initialize with a base URL and ``httpx2.Client`` options.
71
+
72
+ Args:
73
+ base_url: Base URL used for all relative request paths. When
74
+ ``None``, the class's ``base_url=`` class argument.
75
+ user_agent: The ``User-Agent`` header to send. When ``None``, a
76
+ ``User-Agent`` given in ``headers=`` is kept, or else the
77
+ class's default: its ``user_agent=`` class argument, or
78
+ ``ClientX/<version>``.
79
+ raise_for_status: Raise ``httpx2.HTTPStatusError`` when an endpoint
80
+ gets a 4xx or 5xx response, before any decoder runs. On when
81
+ ``None``. An endpoint's own ``raise_for_status=`` overrides it.
82
+ **kwargs: Additional keyword arguments passed directly to
83
+ ``httpx2.Client``.
84
+
85
+ Raises:
86
+ TypeError: If there's no base URL, here or on the class.
87
+ ValueError: If ``base_url`` isn't an absolute URL, with a scheme and
88
+ a host.
89
+ """
90
+ super().__init__(base_url=_base_url(type(self), base_url), **kwargs)
91
+ _configure(
92
+ self,
93
+ user_agent=user_agent,
94
+ headers=kwargs.get("headers"),
95
+ raise_for_status=raise_for_status,
96
+ )
97
+
98
+ def __init_subclass__(
99
+ cls, *, base_url: URL | str | None = None, user_agent: str | None = None, **kwargs: Any
100
+ ) -> None:
101
+ """Check the class, store its class arguments, and set up its endpoints.
102
+
103
+ An endpoint or mounted resource can't use a name ``ClientX`` already
104
+ uses, which includes all of ``httpx2.Client``'s, such as ``get`` or
105
+ ``send``. Those names are free on a ``Resource``. The ``base_url=`` and
106
+ ``user_agent=`` class arguments are used unless the caller gives its
107
+ own. A subclass without one keeps its parent's, and a direct subclass
108
+ has no base URL and sends ``ClientX/<version>``.
109
+
110
+ Raises:
111
+ DefinitionError: If ``base_url`` isn't an absolute URL, with a
112
+ scheme and a host, or the class breaks a rule for endpoints or
113
+ resources.
114
+ """
115
+ super().__init_subclass__(**kwargs)
116
+ set_up_client(cls, base=ClientX, base_url=base_url, user_agent=user_agent)
117
+
118
+
119
+ class AsyncClientX(_BaseClientX, AsyncClient):
120
+ """Base class for an async HTTP API client, with ``async def`` endpoints.
121
+
122
+ It works like ``ClientX``, but an ``AsyncClientX`` is an
123
+ ``httpx2.AsyncClient``, so it's used with ``async with`` and closed with
124
+ ``aclose()``.
125
+ """
126
+
127
+ # Which kind of class this is: `async def` endpoints and resources.
128
+ # `_class_setup` reads it.
129
+ __clientx_is_async__: ClassVar[bool] = True
130
+
131
+ def __init__(
132
+ self,
133
+ base_url: URL | str | None = None,
134
+ *,
135
+ user_agent: str | None = None,
136
+ raise_for_status: bool | None = None,
137
+ **kwargs: Unpack[AsyncHttpxClientOptions],
138
+ ) -> None:
139
+ """Initialize with a base URL and ``httpx2.AsyncClient`` options.
140
+
141
+ Takes the same arguments as ``ClientX``, except that ``transport`` and
142
+ ``mounts`` take async transports, and event hooks must be ``async``
143
+ functions.
144
+ """
145
+ super().__init__(base_url=_base_url(type(self), base_url), **kwargs)
146
+ _configure(
147
+ self,
148
+ user_agent=user_agent,
149
+ headers=kwargs.get("headers"),
150
+ raise_for_status=raise_for_status,
151
+ )
152
+
153
+ def __init_subclass__(
154
+ cls, *, base_url: URL | str | None = None, user_agent: str | None = None, **kwargs: Any
155
+ ) -> None:
156
+ """Check the class and set up its endpoints, like ``ClientX``."""
157
+ super().__init_subclass__(**kwargs)
158
+ set_up_client(cls, base=AsyncClientX, base_url=base_url, user_agent=user_agent)
159
+
160
+
161
+ def _base_url(cls: type[ClientX | AsyncClientX], base_url: URL | str | None) -> URL:
162
+ """Return the base URL given, or else the class's.
163
+
164
+ Raises:
165
+ TypeError: If there's neither, as for a missing argument.
166
+ ValueError: If the one given isn't an absolute URL.
167
+ """
168
+ if base_url is not None:
169
+ return parse_base_url(base_url)
170
+ if cls.__clientx_base_url__ is not None:
171
+ return cls.__clientx_base_url__
172
+ name, base = cls.__qualname__, ("AsyncClientX" if cls.__clientx_is_async__ else "ClientX")
173
+ raise TypeError(
174
+ f'{name} needs a base URL: pass one, as in {name}("https://api.example.com"), or set it in the class '
175
+ f'statement, as in class {name}({base}, base_url="https://api.example.com").'
176
+ )
177
+
178
+
179
+ def _configure(
180
+ client: ClientX | AsyncClientX,
181
+ *,
182
+ user_agent: str | None,
183
+ headers: HeaderTypes | None,
184
+ raise_for_status: bool | None,
185
+ ) -> None:
186
+ # httpx2 always sets its own User-Agent, so read the caller's from
187
+ # `headers=`, not from `client.headers`.
188
+ client.headers["User-Agent"] = (
189
+ user_agent or Headers(headers).get("User-Agent") or type(client).__clientx_user_agent__
190
+ )
191
+ if raise_for_status is not None:
192
+ client.__clientx_raise_for_status__ = raise_for_status
193
+
194
+
195
+ # --- Resources ----------------------------------------------------------------
196
+ class _BaseResource:
197
+ """Shared base of ``Resource`` and ``AsyncResource``: prefix, tags, parent.
198
+
199
+ Internal state uses ``__clientx_*__`` names, so names ``ClientX`` uses, such
200
+ as ``close``, are free for endpoints on a resource.
201
+ """
202
+
203
+ __clientx_prefix__: ClassVar[str] = ""
204
+ __clientx_tags__: ClassVar[tuple[str, ...]] = ()
205
+ __clientx_parent__: ClientX | AsyncClientX | _BaseResource | None = None
206
+ # Set by `Resource` and `AsyncResource`, as on the clients.
207
+ __clientx_is_async__: ClassVar[bool]
208
+
209
+ def __set_name__(self, owner: type[Any], name: str) -> None:
210
+ """Check that the resource is mounted on its own kind of class."""
211
+ check_mount(type(self).__qualname__, is_async=self.__clientx_is_async__, owner=owner)
212
+
213
+ def __get__(self, instance: ClientX | AsyncClientX | _BaseResource | None, owner: type[Any] | None = None) -> Self:
214
+ """Return a copy bound to ``instance``, or ``self`` on class access."""
215
+ if instance is None:
216
+ return self
217
+ bound = copy(self)
218
+ bound.__clientx_parent__ = instance
219
+ return bound
220
+
221
+ def __repr__(self) -> str:
222
+ return f"{type(self).__qualname__}(prefix={type(self).__clientx_prefix__!r})"
223
+
224
+
225
+ class Resource(_BaseResource):
226
+ """Base class for a group of endpoints under a path prefix.
227
+
228
+ Declare endpoints as on a ``ClientX``, and mount an instance as a class
229
+ attribute of a client::
230
+
231
+ class Users(Resource, prefix="/users"):
232
+ @method.get("/{user_id}")
233
+ def get(self, user_id: int) -> User: ...
234
+
235
+ class UsersAPI(ClientX):
236
+ users = Users()
237
+
238
+ ``api.users.get(1)`` then calls ``/users/1``. A resource can be mounted on
239
+ another resource, but prefixes don't add up: each is the full prefix.
240
+ ``ClientX``'s names, such as ``get``, are free for a resource's endpoints.
241
+ """
242
+
243
+ __clientx_is_async__: ClassVar[bool] = False
244
+
245
+ def __init_subclass__(cls, *, prefix: str | None = None, tags: Sequence[str] | None = None, **kwargs: Any) -> None:
246
+ """Check the class, and apply its prefix and tags to its endpoints.
247
+
248
+ The ``prefix=`` class argument, such as ``"/users"``, is joined onto
249
+ each endpoint's path; a subclass without one keeps its parent's.
250
+ ``tags=`` are added to the parent class's tags, then go before each
251
+ endpoint's own, each tag once.
252
+ """
253
+ super().__init_subclass__(**kwargs)
254
+ set_up_resource(cls, base=Resource, prefix=prefix, tags=tags)
255
+
256
+
257
+ class AsyncResource(_BaseResource):
258
+ """Base class for a group of ``async def`` endpoints, like ``Resource``.
259
+
260
+ Mount it on an ``AsyncClientX`` or another ``AsyncResource``.
261
+ """
262
+
263
+ __clientx_is_async__: ClassVar[bool] = True
264
+
265
+ def __init_subclass__(cls, *, prefix: str | None = None, tags: Sequence[str] | None = None, **kwargs: Any) -> None:
266
+ """Check the class and apply its prefix and tags, like ``Resource``."""
267
+ super().__init_subclass__(**kwargs)
268
+ set_up_resource(cls, base=AsyncResource, prefix=prefix, tags=tags)
269
+
270
+
271
+ # --- Finding a call's client --------------------------------------------------
272
+ def client_of[C: ClientX | AsyncClientX](owner: object, kind: type[C]) -> C:
273
+ """Return the client an endpoint call on ``owner`` goes through.
274
+
275
+ Args:
276
+ owner: The object the endpoint was called on: a client, or a resource
277
+ mounted on one (possibly through other resources).
278
+ kind: The client class the endpoint needs: ``ClientX`` for a ``def``
279
+ endpoint, ``AsyncClientX`` for an ``async def`` one.
280
+
281
+ Raises:
282
+ DefinitionError: If ``owner`` is a resource that isn't mounted on a
283
+ client, or isn't a ``kind`` instance or a resource mounted on one.
284
+ """
285
+ current = owner
286
+ while isinstance(current, _BaseResource):
287
+ if current.__clientx_parent__ is None:
288
+ name = type(current).__qualname__
289
+ raise DefinitionError(
290
+ f"Resource '{name}' isn't mounted on a client. Mount an instance as a class "
291
+ f"attribute of a ClientX subclass (for example, `items = {name}()`) and call "
292
+ "its endpoints through a client instance (`client.items.<endpoint>(...)`)."
293
+ )
294
+ current = current.__clientx_parent__
295
+ if isinstance(current, kind):
296
+ return current
297
+ raise DefinitionError(
298
+ f"The endpoint must be called on an instance of {kind.__name__} or a resource mounted on one, "
299
+ f"not on {type(owner).__qualname__!r}."
300
+ )