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/_wire.py ADDED
@@ -0,0 +1,469 @@
1
+ """What both clients share for the wire: paths, URLs, queries, bodies and errors.
2
+
3
+ No I/O here. The transport (``_async/_http.py``, and the sync copy made from
4
+ it) sends and reads; this module builds what it sends and reads what it got.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ import json
11
+ import types
12
+ import typing
13
+ from collections.abc import Callable, Mapping, Sequence
14
+ from dataclasses import dataclass
15
+ from typing import Any, Final, Literal, NoReturn, TypeVar, cast, get_args, get_origin
16
+ from urllib.parse import quote, quote_plus
17
+
18
+ from pydantic import BaseModel, TypeAdapter, ValidationError
19
+
20
+ from onecli._errors import OneCLIApiError, OneCLIError, OneCLIRequestError
21
+ from onecli._js import js_number, js_pairs, js_usv
22
+ from onecli._url import parse_http_url, scheme_of
23
+ from onecli._version import SDK_VERSION
24
+ from onecli.types._openapi import ErrorDetail
25
+
26
+ __all__ = [
27
+ "CLIENT_HEADER",
28
+ "CLIENT_VALUE",
29
+ "DEFAULT_TIMEOUT",
30
+ "DEFAULT_URL",
31
+ "IDEMPOTENCY_HEADER",
32
+ "MAX_BODY",
33
+ "NOT_GIVEN",
34
+ "Method",
35
+ "NotGiven",
36
+ "Query",
37
+ "ResponseHook",
38
+ "ResponseInfo",
39
+ "Secret",
40
+ "api_error",
41
+ "check_idempotency_key",
42
+ "check_timeout",
43
+ "decode",
44
+ "json_body",
45
+ "normalize_base_url",
46
+ "parse_json",
47
+ "retry_after_of",
48
+ "safe_origin",
49
+ "seg",
50
+ "to_wire",
51
+ "url_with_query",
52
+ ]
53
+
54
+ CLIENT_HEADER: Final = "OneCLI-Client"
55
+ """The header that names this client on every call."""
56
+ CLIENT_VALUE: Final = f"python-sdk/{SDK_VERSION}"
57
+
58
+ DEFAULT_URL: Final = "https://api.onecli.sh"
59
+ DEFAULT_TIMEOUT: Final = 10.0
60
+ """Seconds one try of a call may take."""
61
+
62
+ IDEMPOTENCY_HEADER: Final = "Idempotency-Key"
63
+ """The header that lets the server run a POST once however often it is sent."""
64
+ # The server's rule for a key: 1 to 255 visible characters, no space.
65
+ _IDEMPOTENCY_KEY_CHARS: Final = frozenset(chr(c) for c in range(0x21, 0x7F))
66
+ _IDEMPOTENCY_KEY_MAX: Final = 255
67
+
68
+ MAX_BODY: Final = 4 << 20
69
+ """The largest answer body the SDK reads, so a broken server cannot exhaust memory."""
70
+
71
+ Method = Literal["GET", "POST", "PUT", "PATCH", "DELETE"]
72
+ Query = Mapping[str, str | int | bool | None]
73
+
74
+
75
+ @dataclass(frozen=True, slots=True)
76
+ class ResponseInfo:
77
+ """What ``on_response`` is told about one answer. Never a header, a body or a query."""
78
+
79
+ method: Method
80
+ path: str
81
+ """The path of the call, without its query."""
82
+ status: int
83
+ request_id: str | None
84
+ """The X-Request-Id of the answer, to quote when asking for help."""
85
+ attempt: int
86
+ """1 for the first try."""
87
+ duration_ms: int
88
+ """How long the try took, in milliseconds."""
89
+
90
+
91
+ ResponseHook = Callable[[ResponseInfo], object]
92
+ """Called after every answer with a :class:`ResponseInfo`. What it raises is ignored."""
93
+
94
+
95
+ @typing.final
96
+ class NotGiven:
97
+ """The default of an argument where ``None`` means something: it sends JSON ``null``.
98
+
99
+ Left at ``NOT_GIVEN``, the field is not sent at all.
100
+ """
101
+
102
+ __slots__ = ()
103
+
104
+ def __bool__(self) -> typing.Literal[False]:
105
+ return False
106
+
107
+ def __repr__(self) -> str:
108
+ return "NOT_GIVEN"
109
+
110
+ def __reduce__(self) -> str:
111
+ return "NOT_GIVEN"
112
+
113
+
114
+ NOT_GIVEN: Final = NotGiven()
115
+ """Leave a field out of the body. See :class:`NotGiven`."""
116
+
117
+
118
+ class Secret:
119
+ """A key or credential that never shows in repr, str or a pickle."""
120
+
121
+ __slots__ = ("_value",)
122
+
123
+ def __init__(self, value: str) -> None:
124
+ self._value = value
125
+
126
+ def reveal(self) -> str:
127
+ """The value itself. Do not log it."""
128
+ return self._value
129
+
130
+ def __bool__(self) -> bool:
131
+ return self._value != ""
132
+
133
+ def __repr__(self) -> str:
134
+ return "[redacted]"
135
+
136
+ def __reduce__(self) -> NoReturn:
137
+ msg = "A OneCLI secret cannot be pickled."
138
+ raise TypeError(msg)
139
+
140
+
141
+ _T = TypeVar("_T")
142
+
143
+
144
+ def check_timeout(timeout: object) -> float:
145
+ """Refuse a timeout that is not a number of seconds above 0."""
146
+ if (
147
+ isinstance(timeout, bool)
148
+ or not isinstance(timeout, int | float)
149
+ or not 0 < timeout < float("inf")
150
+ ):
151
+ msg = "The timeout must be a number of seconds above 0."
152
+ raise OneCLIError(msg)
153
+ return float(timeout)
154
+
155
+
156
+ def check_idempotency_key(key: object) -> str:
157
+ """Refuse a key the server would refuse.
158
+
159
+ An empty or broken key is refused here: sent as it is, the call would fail
160
+ in a way that says nothing about the key, and left out, two calls the
161
+ caller meant as one would both run.
162
+ """
163
+ if (
164
+ not isinstance(key, str)
165
+ or not 0 < len(key) <= _IDEMPOTENCY_KEY_MAX
166
+ or not set(key) <= _IDEMPOTENCY_KEY_CHARS
167
+ ):
168
+ msg = "idempotency_key must be 1 to 255 letters, digits or signs, with no space."
169
+ raise OneCLIError(msg)
170
+ return key
171
+
172
+
173
+ def normalize_base_url(raw: object) -> str:
174
+ """Remove a trailing slash and refuse a URL that is not plain http(s)."""
175
+ if not isinstance(raw, str) or scheme_of(raw) is None:
176
+ msg = "The OneCLI url is not a valid URL."
177
+ raise OneCLIError(msg)
178
+ if scheme_of(raw) not in {"http", "https"}:
179
+ msg = "The OneCLI url must start with http:// or https://."
180
+ raise OneCLIError(msg)
181
+ url = parse_http_url(raw)
182
+ if url is None:
183
+ msg = "The OneCLI url is not a valid URL."
184
+ raise OneCLIError(msg)
185
+ if url.has_userinfo:
186
+ msg = "The OneCLI url must not carry a user or password."
187
+ raise OneCLIError(msg)
188
+ if url.has_query or url.has_fragment or "?" in raw or "#" in raw:
189
+ msg = "The OneCLI url must not carry a query or a fragment."
190
+ raise OneCLIError(msg)
191
+ return raw.rstrip("/")
192
+
193
+
194
+ def safe_origin(url: str) -> str:
195
+ """The host of a URL, with its port when not the scheme's own. Never a path or a query."""
196
+ parsed = parse_http_url(url)
197
+ return parsed.authority if parsed else "the OneCLI API"
198
+
199
+
200
+ def seg(value: object) -> str:
201
+ """Encode an id for one path segment.
202
+
203
+ ``.`` and ``..`` are refused: a URL parser would collapse them and send the
204
+ call to another route.
205
+ """
206
+ if not isinstance(value, str) or value == "":
207
+ msg = "An id is required."
208
+ raise OneCLIError(msg)
209
+ if value in {".", ".."}:
210
+ msg = "An id cannot be . or .."
211
+ raise OneCLIError(msg)
212
+ try:
213
+ # The characters JavaScript's encodeURIComponent leaves as they are. It
214
+ # throws on a lone surrogate, and so does this.
215
+ return quote(js_pairs(value), safe="!'()*-._~", encoding="utf-8", errors="strict")
216
+ except UnicodeEncodeError:
217
+ msg = "An id must be text that UTF-8 can carry."
218
+ raise OneCLIError(msg) from None
219
+
220
+
221
+ def _form(value: str) -> str:
222
+ # application/x-www-form-urlencoded, as URLSearchParams writes it: a lone
223
+ # surrogate goes as U+FFFD.
224
+ return quote_plus(js_usv(value), safe="*").replace("~", "%7E")
225
+
226
+
227
+ def _query_value(value: str | int | bool) -> str: # noqa: FBT001 - a query value, not a flag
228
+ if isinstance(value, bool):
229
+ return "true" if value else "false"
230
+ return str(value)
231
+
232
+
233
+ def url_with_query(base: str, path: str, query: Query | None = None) -> str:
234
+ """The full URL of a call. A query value of None is left out."""
235
+ pairs = [
236
+ f"{_form(name)}={_form(_query_value(value))}"
237
+ for name, value in (query or {}).items()
238
+ if value is not None
239
+ ]
240
+ return f"{base}{path}?{'&'.join(pairs)}" if pairs else f"{base}{path}"
241
+
242
+
243
+ def form_query(pairs: Sequence[tuple[str, str]]) -> str:
244
+ """A query string, written the way URLSearchParams writes one."""
245
+ return "&".join(f"{_form(name)}={_form(value)}" for name, value in pairs)
246
+
247
+
248
+ def _reject_constant(name: str) -> object:
249
+ msg = f"{name} is not JSON"
250
+ raise ValueError(msg)
251
+
252
+
253
+ def parse_json(text: str) -> object:
254
+ """Parse JSON the way JavaScript's JSON.parse does: NaN and Infinity are not JSON."""
255
+ return json.loads(text, parse_constant=_reject_constant)
256
+
257
+
258
+ def json_body(body: object) -> bytes:
259
+ r"""A request body, written as JSON.stringify writes it: compact, in UTF-8.
260
+
261
+ UTF-8 cannot carry a lone surrogate (text decoded with ``surrogateescape``
262
+ holds them), so such a body is written with every non-ASCII character
263
+ escaped: the same JSON, and a lone surrogate comes out as JSON.stringify
264
+ writes it, ``"\ud800"``.
265
+ """
266
+ try:
267
+ return json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode()
268
+ except UnicodeEncodeError:
269
+ return json.dumps(body, separators=(",", ":")).encode()
270
+
271
+
272
+ def retry_after_of(value: str | None) -> float | None:
273
+ """Seconds from a Retry-After header, or None when it names no wait in seconds."""
274
+ if value is None:
275
+ return None
276
+ # Number() as Node reads the header: "0x10" is 16, "1_0" is no number.
277
+ seconds = js_number(value)
278
+ return seconds if 0 < seconds < float("inf") else None
279
+
280
+
281
+ def api_error(
282
+ *,
283
+ status: int,
284
+ url: str,
285
+ text: str,
286
+ request_id: str | None,
287
+ retry_after: str | None,
288
+ ) -> OneCLIApiError:
289
+ """The error for a failed answer: the v2 shape first, then the old flat shapes."""
290
+ code = "unknown"
291
+ message = f"OneCLI returned {status}"
292
+ details: list[ErrorDetail] = []
293
+ try:
294
+ parsed = parse_json(text)
295
+ except ValueError:
296
+ parsed = None # Not JSON: keep the status line.
297
+ error = _field(parsed, "error")
298
+ given_message = _field(error, "message")
299
+ if isinstance(given_message, str):
300
+ message = given_message
301
+ given_code = _field(error, "code")
302
+ if isinstance(given_code, str):
303
+ code = given_code
304
+ given_details = _field(error, "details")
305
+ if isinstance(given_details, list):
306
+ details = [
307
+ ErrorDetail.model_validate(d)
308
+ for d in cast("list[object]", given_details)
309
+ if _is_detail(d)
310
+ ]
311
+ given_id = _field(error, "requestId")
312
+ if isinstance(given_id, str):
313
+ request_id = given_id
314
+ elif isinstance(error, str):
315
+ message = error
316
+ return OneCLIApiError(
317
+ message,
318
+ url=url,
319
+ status_code=status,
320
+ code=code,
321
+ details=details,
322
+ request_id=request_id,
323
+ retry_after=retry_after_of(retry_after),
324
+ )
325
+
326
+
327
+ def _as_dict(value: object) -> dict[str, object] | None:
328
+ return cast("dict[str, object]", value) if isinstance(value, dict) else None
329
+
330
+
331
+ def _field(value: object, name: str) -> object:
332
+ """A key of a JSON object, or None when the value is not an object."""
333
+ mapping = _as_dict(value)
334
+ return None if mapping is None else mapping.get(name)
335
+
336
+
337
+ def _is_detail(value: object) -> bool:
338
+ return all(isinstance(_field(value, k), str) for k in ("field", "issue", "message"))
339
+
340
+
341
+ def not_json(url: str, status: int) -> OneCLIRequestError:
342
+ """The error for an answer whose body is not JSON."""
343
+ return OneCLIRequestError(
344
+ "OneCLI answered with a body that is not JSON.", url=url, status_code=status
345
+ )
346
+
347
+
348
+ # Reading answers ------------------------------------------------------------
349
+
350
+
351
+ @functools.cache
352
+ def _adapter(tp: Any) -> TypeAdapter[Any]: # noqa: ANN401 - any model type
353
+ return TypeAdapter(tp)
354
+
355
+
356
+ def decode(tp: type[_T] | Any, data: object) -> _T: # noqa: ANN401 - a type form
357
+ """Read an answer into ``tp``, never failing on a shape the SDK does not know.
358
+
359
+ A server newer or older than this SDK may add a field, add a value to an
360
+ enum, or leave a field out. The answer is read the strict way first; when
361
+ that fails, it is read loosely: what fits is typed, the rest is kept as the
362
+ server sent it, and a field the server left out is not set. Node's SDK
363
+ never refuses an answer either.
364
+ """
365
+ try:
366
+ return cast("_T", _adapter(tp).validate_python(data))
367
+ except ValidationError:
368
+ return cast("_T", _loose(tp, data))
369
+
370
+
371
+ def _loose(tp: Any, value: object) -> object: # noqa: ANN401, PLR0911 - walks a type form
372
+ origin = get_origin(tp)
373
+ if origin is typing.Annotated:
374
+ return _loose(get_args(tp)[0], value)
375
+ if isinstance(tp, type) and issubclass(tp, BaseModel):
376
+ return _loose_model(tp, value)
377
+ if origin in {types.UnionType, typing.Union}:
378
+ return _loose_union(get_args(tp), value)
379
+ if origin is list and isinstance(value, list):
380
+ item: Any = get_args(tp)[0]
381
+ return [_loose(item, v) for v in cast("list[object]", value)]
382
+ if origin is dict and isinstance(value, dict):
383
+ item = get_args(tp)[1]
384
+ return {k: _loose(item, v) for k, v in cast("dict[str, object]", value).items()}
385
+ if tp is Any or origin is Literal:
386
+ return value
387
+ try:
388
+ return _adapter(cast("Any", tp)).validate_python(value)
389
+ except ValidationError:
390
+ return value
391
+
392
+
393
+ def _loose_union(members: tuple[Any, ...], value: object) -> object:
394
+ if value is None and type(None) in members:
395
+ return None
396
+ for member in members:
397
+ try:
398
+ return _adapter(member).validate_python(value)
399
+ except ValidationError:
400
+ continue
401
+ mapping = _as_dict(value)
402
+ if mapping is not None:
403
+ for member in members:
404
+ if isinstance(member, type) and issubclass(member, BaseModel):
405
+ return _loose_model(member, mapping)
406
+ return value
407
+
408
+
409
+ def _loose_model(model: type[BaseModel], value: object) -> object:
410
+ if not isinstance(value, dict):
411
+ return value
412
+ given = cast("dict[str, object]", value)
413
+ fields: dict[str, object] = {}
414
+ used: set[str] = set()
415
+ for name, info in model.model_fields.items():
416
+ key = info.alias or name
417
+ if key in given:
418
+ fields[name] = _loose(info.annotation, given[key])
419
+ used.add(key)
420
+ elif name in given:
421
+ fields[name] = _loose(info.annotation, given[name])
422
+ used.add(name)
423
+ # Keys the model does not know are kept, as a strict read keeps them.
424
+ values = {k: v for k, v in given.items() if k not in used}
425
+ values.update(fields)
426
+ return model.model_construct(_fields_set=set(fields), **values)
427
+
428
+
429
+ # Building bodies -------------------------------------------------------------
430
+
431
+
432
+ def _always_sent(model: type[BaseModel]) -> dict[str, object]:
433
+ """Fields fixed to one value, such as ``kind="network"``: sent even when left as they are."""
434
+ fixed: dict[str, object] = {}
435
+ for name, info in model.model_fields.items():
436
+ args = get_args(info.annotation) if get_origin(info.annotation) is Literal else ()
437
+ if len(args) == 1 and info.default == args[0]:
438
+ fixed[info.alias or name] = args[0]
439
+ return fixed
440
+
441
+
442
+ def _dump(model: BaseModel) -> dict[str, object]:
443
+ sent = _always_sent(type(model))
444
+ sent.update(model.model_dump(mode="json", by_alias=True, exclude_unset=True))
445
+ return sent
446
+
447
+
448
+ def to_wire(value: object, shape: Any = None) -> object: # noqa: ANN401 - a type form
449
+ """One input value, as the API's JSON.
450
+
451
+ A model is sent by its aliases, with only the fields that were set. A
452
+ mapping is read into ``shape`` (a model or a union of models) so its
453
+ Python names become the API's names; a mapping that fits no shape is sent
454
+ as written, and the server judges it. Lists and nested values are walked.
455
+ """
456
+ if isinstance(value, BaseModel):
457
+ return _dump(value)
458
+ if isinstance(value, Mapping):
459
+ mapping = cast("Mapping[str, object]", value)
460
+ if shape is not None:
461
+ try:
462
+ return to_wire(_adapter(shape).validate_python(dict(mapping)))
463
+ except ValidationError:
464
+ pass
465
+ return {str(k): to_wire(v) for k, v in mapping.items()}
466
+ if isinstance(value, list | tuple):
467
+ items = cast("Sequence[object]", value)
468
+ return [to_wire(v, shape) for v in items]
469
+ return value