onecli-sdk 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.
onecli/_async/_http.py ADDED
@@ -0,0 +1,330 @@
1
+ """The transport both parts share: one call, tried again when that is safe."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import uuid
7
+ from dataclasses import dataclass
8
+ from http.cookiejar import CookieJar, DefaultCookiePolicy
9
+ from typing import TYPE_CHECKING, Final, cast
10
+
11
+ import httpx2
12
+
13
+ from onecli._async._io import (
14
+ REAL_CLOCK,
15
+ Clock,
16
+ checkpoint,
17
+ new_client,
18
+ read_chunks,
19
+ try_deadline,
20
+ )
21
+ from onecli._errors import OneCLIError
22
+ from onecli._retry import NoAnswer, Outcome, StatusAnswer, check_max_retries, should_retry, wait_ms
23
+ from onecli._wire import (
24
+ CLIENT_HEADER,
25
+ CLIENT_VALUE,
26
+ IDEMPOTENCY_HEADER,
27
+ MAX_BODY,
28
+ Method,
29
+ Query,
30
+ ResponseHook,
31
+ ResponseInfo,
32
+ Secret,
33
+ api_error,
34
+ check_idempotency_key,
35
+ check_timeout,
36
+ json_body,
37
+ normalize_base_url,
38
+ not_json,
39
+ parse_json,
40
+ retry_after_of,
41
+ safe_origin,
42
+ url_with_query,
43
+ )
44
+
45
+ if TYPE_CHECKING:
46
+ from collections.abc import Mapping
47
+
48
+ __all__ = ["AsyncHttp"]
49
+
50
+ # Set by the server on the stored answer of an earlier try.
51
+ _REPLAYED_HEADER: Final = "idempotent-replayed"
52
+ # Fetch's `redirect: "error"`: an answer that sends the call elsewhere is no answer.
53
+ _REDIRECTS: Final = frozenset({301, 302, 303, 307, 308})
54
+ _NO_CONTENT: Final = 204
55
+ _OK_LOW: Final = 200
56
+ _OK_HIGH: Final = 299
57
+
58
+
59
+ class _TooLargeError(Exception):
60
+ pass
61
+
62
+
63
+ class _ReadTimeoutError(Exception):
64
+ pass
65
+
66
+
67
+ @dataclass(frozen=True, slots=True)
68
+ class _Answer:
69
+ status: int
70
+ headers: httpx2.Headers
71
+ text: str
72
+
73
+
74
+ @dataclass(frozen=True, slots=True)
75
+ class _Failed:
76
+ """No answer came, or none the SDK can use. ``final``: no later try can change it."""
77
+
78
+ message: str
79
+ final: bool = False
80
+
81
+
82
+ def _no_cookies() -> CookieJar:
83
+ # Like fetch, the client keeps no cookie from one call to the next.
84
+ return CookieJar(policy=DefaultCookiePolicy(allowed_domains=[]))
85
+
86
+
87
+ class AsyncHttp:
88
+ """The transport shared by both parts.
89
+
90
+ It holds the bearer in a private slot, so the credential never shows in
91
+ repr, vars or an error message.
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ base_url: str,
97
+ bearer: str,
98
+ *,
99
+ timeout: float,
100
+ max_retries: int,
101
+ on_response: ResponseHook | None = None,
102
+ http_client: httpx2.AsyncClient | None = None,
103
+ clock: Clock = REAL_CLOCK,
104
+ ) -> None:
105
+ self.base_url: Final = normalize_base_url(base_url)
106
+ self.timeout: Final = check_timeout(timeout)
107
+ self.max_retries: Final = check_max_retries(max_retries)
108
+ if on_response is not None and not callable(on_response):
109
+ msg = "on_response must be callable."
110
+ raise OneCLIError(msg)
111
+ # A client of the old httpx package, or one of the other kind, is a common slip.
112
+ if http_client is not None and not isinstance(
113
+ cast("object", http_client), httpx2.AsyncClient
114
+ ):
115
+ msg = "http_client must be an httpx2.AsyncClient."
116
+ raise OneCLIError(msg)
117
+ self._bearer: Final = Secret(bearer)
118
+ self._on_response: Final = on_response
119
+ self._clock: Final = clock
120
+ self._owns_client: Final = http_client is None
121
+ self._client: Final = new_client(_no_cookies()) if http_client is None else http_client
122
+
123
+ @property
124
+ def has_bearer(self) -> bool:
125
+ """Whether a bearer is set."""
126
+ return bool(self._bearer)
127
+
128
+ async def aclose(self) -> None:
129
+ """Close the connection pool, unless the caller gave it."""
130
+ if self._owns_client:
131
+ await self._client.aclose()
132
+
133
+ def __repr__(self) -> str:
134
+ return f"AsyncHttp({self.base_url!r})"
135
+
136
+ def __reduce__(self) -> tuple[object, ...]:
137
+ msg = "A OneCLI client cannot be pickled: it holds a key."
138
+ raise TypeError(msg)
139
+
140
+ def _headers(
141
+ self, extra: Mapping[str, str] | None, *, anonymous: bool, has_body: bool
142
+ ) -> dict[str, str]:
143
+ headers = {"Accept": "application/json", CLIENT_HEADER: CLIENT_VALUE, **(extra or {})}
144
+ if has_body:
145
+ headers["Content-Type"] = "application/json"
146
+ if not anonymous and self._bearer:
147
+ headers["Authorization"] = f"Bearer {self._bearer.reveal()}"
148
+ return headers
149
+
150
+ async def json(
151
+ self,
152
+ method: Method,
153
+ path: str,
154
+ *,
155
+ query: Query | None = None,
156
+ body: object = None,
157
+ headers: Mapping[str, str] | None = None,
158
+ anonymous: bool = False,
159
+ keyed: bool = False,
160
+ idempotency_key: str | None = None,
161
+ timeout: float | None = None,
162
+ max_retries: int | None = None,
163
+ ) -> object:
164
+ """A /v2 call: JSON in, JSON out, the v2 error shape on failure.
165
+
166
+ Tried again when that is safe. ``body`` None sends no body. ``keyed``:
167
+ the route takes an Idempotency-Key, so the SDK sends one and the call
168
+ can be tried again without doing its work twice. Returns the parsed
169
+ answer, or None for an empty one.
170
+ """
171
+ status, url, text = await self._send(
172
+ method,
173
+ path,
174
+ query=query,
175
+ body=body,
176
+ headers=headers,
177
+ anonymous=anonymous,
178
+ keyed=keyed,
179
+ idempotency_key=idempotency_key,
180
+ timeout=timeout,
181
+ max_retries=max_retries,
182
+ )
183
+ if status == _NO_CONTENT or text == "":
184
+ return None
185
+ try:
186
+ return parse_json(text)
187
+ except ValueError:
188
+ error = not_json(url, status)
189
+ raise error
190
+
191
+ async def _send(
192
+ self,
193
+ method: Method,
194
+ path: str,
195
+ *,
196
+ query: Query | None,
197
+ body: object,
198
+ headers: Mapping[str, str] | None,
199
+ anonymous: bool,
200
+ keyed: bool,
201
+ idempotency_key: str | None,
202
+ timeout: float | None,
203
+ max_retries: int | None,
204
+ ) -> tuple[int, str, str]:
205
+ """The retry loop.
206
+
207
+ One deadline is set at the start, ``timeout`` for each try the call may
208
+ make, and the waits between tries come out of it: a call never takes
209
+ longer than ``timeout x (max_retries + 1)``.
210
+ """
211
+ try_ms = check_timeout(self.timeout if timeout is None else timeout) * 1000
212
+ retries = check_max_retries(self.max_retries if max_retries is None else max_retries)
213
+ extra = dict(headers or {})
214
+ if idempotency_key is not None:
215
+ extra[IDEMPOTENCY_HEADER] = check_idempotency_key(idempotency_key)
216
+ # One key for every try of this call. A key the caller gave wins.
217
+ if keyed and method == "POST" and retries > 0 and IDEMPOTENCY_HEADER not in extra:
218
+ extra[IDEMPOTENCY_HEADER] = str(uuid.uuid4())
219
+ is_keyed = method == "POST" and IDEMPOTENCY_HEADER in extra
220
+ url = url_with_query(self.base_url, path, query)
221
+ content = None if body is None else json_body(body)
222
+ sent = self._headers(extra, anonymous=anonymous, has_body=content is not None)
223
+
224
+ deadline = self._clock.now() + try_ms * (retries + 1)
225
+ attempt = 1
226
+ while True:
227
+ started = self._clock.now()
228
+ limit = max(1.0, min(try_ms, deadline - started))
229
+ result = await self._once(method, url, sent, content, limit)
230
+ if isinstance(result, _Failed) and result.final:
231
+ raise OneCLIError(result.message)
232
+ if isinstance(result, _Answer):
233
+ self._tell(method, path, result, attempt, started)
234
+ outcome: Outcome = StatusAnswer(
235
+ result.status, result.headers.get(_REPLAYED_HEADER) == "true"
236
+ )
237
+ retry_after = retry_after_of(result.headers.get("retry-after"))
238
+ else:
239
+ outcome = NoAnswer()
240
+ retry_after = None
241
+ if attempt <= retries and should_retry(
242
+ method=method, keyed=is_keyed, attempt=attempt, outcome=outcome
243
+ ):
244
+ wait = wait_ms(attempt, retry_after, self._clock.random)
245
+ if self._clock.now() + wait < deadline:
246
+ await self._clock.sleep(wait)
247
+ attempt += 1
248
+ continue
249
+ if isinstance(result, _Failed):
250
+ raise OneCLIError(result.message)
251
+ if not _OK_LOW <= result.status <= _OK_HIGH:
252
+ raise api_error(
253
+ status=result.status,
254
+ url=url,
255
+ text=result.text,
256
+ request_id=result.headers.get("x-request-id"),
257
+ retry_after=result.headers.get("retry-after"),
258
+ )
259
+ return result.status, url, result.text
260
+
261
+ async def _once(
262
+ self,
263
+ method: Method,
264
+ url: str,
265
+ headers: dict[str, str],
266
+ content: bytes | None,
267
+ limit_ms: float,
268
+ ) -> _Answer | _Failed:
269
+ """One try: send, and read the whole body within ``limit_ms``."""
270
+ await checkpoint()
271
+ host = safe_origin(url)
272
+ ends = self._clock.now() + limit_ms
273
+ request = self._client.build_request(
274
+ method, url, headers=headers, content=content, timeout=limit_ms / 1000
275
+ )
276
+ reading = False
277
+ try:
278
+ with try_deadline(limit_ms / 1000):
279
+ response = await self._client.send(
280
+ request, stream=True, auth=None, follow_redirects=False
281
+ )
282
+ try:
283
+ if response.status_code in _REDIRECTS:
284
+ return _Failed(f"Could not reach {host}.")
285
+ reading = True
286
+ text = await self._read(response, ends)
287
+ return _Answer(response.status_code, response.headers, text)
288
+ finally:
289
+ await response.aclose()
290
+ except _TooLargeError:
291
+ return _Failed("OneCLI answered with a body that is too large.", final=True)
292
+ except (TimeoutError, httpx2.TimeoutException, _ReadTimeoutError):
293
+ return _Failed(f"The request to {host} timed out.")
294
+ except httpx2.RequestError:
295
+ if reading:
296
+ return _Failed(f"Reading the answer from {host} failed.")
297
+ return _Failed(f"Could not reach {host}.")
298
+
299
+ async def _read(self, response: httpx2.Response, ends: float) -> str:
300
+ """The whole body, at most MAX_BODY bytes, read before the try's time ends."""
301
+ chunks: list[bytes] = []
302
+ size = 0
303
+ async with read_chunks(response) as body:
304
+ async for chunk in body:
305
+ size += len(chunk)
306
+ if size > MAX_BODY:
307
+ raise _TooLargeError
308
+ chunks.append(chunk)
309
+ # Without an event loop no timer stops a slow read: the clock does.
310
+ if self._clock.now() > ends:
311
+ raise _ReadTimeoutError
312
+ # As TextDecoder reads it: a BOM is dropped, broken bytes become U+FFFD.
313
+ return b"".join(chunks).decode("utf-8-sig", errors="replace")
314
+
315
+ def _tell(
316
+ self, method: Method, path: str, answer: _Answer, attempt: int, started: float
317
+ ) -> None:
318
+ """Tell ``on_response`` about one answer. What it raises is dropped."""
319
+ if self._on_response is None:
320
+ return
321
+ info = ResponseInfo(
322
+ method=method,
323
+ path=path,
324
+ status=answer.status,
325
+ request_id=answer.headers.get("x-request-id"),
326
+ attempt=attempt,
327
+ duration_ms=max(0, round(self._clock.now() - started)),
328
+ )
329
+ with contextlib.suppress(Exception): # A logger must not fail a call.
330
+ self._on_response(info)
onecli/_async/_io.py ADDED
@@ -0,0 +1,118 @@
1
+ """The async side of the one seam between the async and the sync client.
2
+
3
+ Everything else in ``_async`` is turned into ``_sync`` by scripts/gen_sync.py.
4
+ This file is not: ``_sync/_io.py`` is its hand-written twin, with the same
5
+ names doing the same things without an event loop.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import random
12
+ import time
13
+ from collections.abc import Awaitable, Callable
14
+ from typing import TYPE_CHECKING, Protocol, TypeVar
15
+
16
+ import anyio
17
+ import anyio.lowlevel
18
+ import httpx2
19
+
20
+ if TYPE_CHECKING:
21
+ from collections.abc import AsyncGenerator, AsyncIterator
22
+ from contextlib import AbstractContextManager
23
+ from http.cookiejar import CookieJar
24
+
25
+ __all__ = [
26
+ "REAL_CLOCK",
27
+ "Clock",
28
+ "Lock",
29
+ "PageLoader",
30
+ "checkpoint",
31
+ "new_client",
32
+ "read_chunks",
33
+ "shielded",
34
+ "try_deadline",
35
+ ]
36
+
37
+ _P = TypeVar("_P")
38
+
39
+ PageLoader = Callable[[str | None], Awaitable[_P]]
40
+ """Loads one page of a list for a cursor (None for the first page)."""
41
+
42
+ Lock = anyio.Lock
43
+ """A lock for a task to hold across an await."""
44
+
45
+
46
+ class Clock(Protocol):
47
+ """What the retry loop needs from the world. Tests pass their own."""
48
+
49
+ def now(self) -> float:
50
+ """Milliseconds on a clock that only goes forward."""
51
+ ...
52
+
53
+ async def sleep(self, ms: float) -> None:
54
+ """Wait ``ms`` milliseconds. Cancelling the call stops the wait at once."""
55
+ ...
56
+
57
+ def random(self) -> float:
58
+ """A number from 0 up to 1, for the spread of the waits."""
59
+ ...
60
+
61
+
62
+ class _RealClock:
63
+ def now(self) -> float:
64
+ return time.monotonic() * 1000
65
+
66
+ async def sleep(self, ms: float) -> None:
67
+ await anyio.sleep(ms / 1000)
68
+
69
+ def random(self) -> float:
70
+ return random.random() # noqa: S311 - spreads retries, not a secret
71
+
72
+
73
+ REAL_CLOCK: Clock = _RealClock()
74
+
75
+
76
+ async def checkpoint() -> None:
77
+ """Let a cancelled call stop here, before anything is sent."""
78
+ await anyio.lowlevel.checkpoint()
79
+
80
+
81
+ def shielded() -> AbstractContextManager[object]:
82
+ """Run a cleanup to its end even when the task around it is being cancelled.
83
+
84
+ Only for a call that has its own deadline, so it cannot hang.
85
+ """
86
+ return anyio.CancelScope(shield=True)
87
+
88
+
89
+ def try_deadline(seconds: float) -> AbstractContextManager[object]:
90
+ """Stop one try after ``seconds``, whatever it is waiting on. Raises TimeoutError."""
91
+ return anyio.fail_after(seconds)
92
+
93
+
94
+ def new_client(cookies: CookieJar) -> httpx2.AsyncClient:
95
+ """The connection pool a client makes for itself, and closes with itself."""
96
+ return httpx2.AsyncClient(cookies=cookies, follow_redirects=False)
97
+
98
+
99
+ @contextlib.asynccontextmanager
100
+ async def read_chunks(response: httpx2.Response) -> AsyncGenerator[AsyncIterator[bytes]]:
101
+ """The body in pieces. Every layer under it has ended when the block ends.
102
+
103
+ httpx2 closes its own generators when a read stops early, but not the
104
+ transport's one under them, which the event loop then finalizes later
105
+ (trio warns that it was not exhausted). So on leaving the block, the
106
+ response is closed first, which closes the connection under a body not
107
+ read to its end, and the pieces are then read on: the next read from the
108
+ closed connection fails inside the lowest layer, which ends every layer
109
+ on its way up. Pieces already received are dropped.
110
+ """
111
+ body = response.aiter_bytes()
112
+ try:
113
+ yield body
114
+ finally:
115
+ await response.aclose()
116
+ with contextlib.suppress(httpx2.HTTPError):
117
+ async for _ in body:
118
+ pass