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