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/__init__.py +97 -0
- onecli/_agent_env.py +238 -0
- onecli/_async/__init__.py +1 -0
- onecli/_async/_client.py +431 -0
- onecli/_async/_connected_agent.py +184 -0
- onecli/_async/_http.py +330 -0
- onecli/_async/_io.py +118 -0
- onecli/_async/_resources.py +1293 -0
- onecli/_errors.py +106 -0
- onecli/_js.py +122 -0
- onecli/_keys.py +101 -0
- onecli/_lifetime.py +110 -0
- onecli/_retry.py +116 -0
- onecli/_sync/__init__.py +1 -0
- onecli/_sync/_client.py +426 -0
- onecli/_sync/_connected_agent.py +185 -0
- onecli/_sync/_http.py +329 -0
- onecli/_sync/_io.py +110 -0
- onecli/_sync/_resources.py +1286 -0
- onecli/_url.py +264 -0
- onecli/_version.py +19 -0
- onecli/_wire.py +469 -0
- onecli/gateway.py +454 -0
- onecli/py.typed +0 -0
- onecli/types/__init__.py +229 -0
- onecli/types/_base.py +42 -0
- onecli/types/_openapi.py +1590 -0
- onecli_sdk-0.1.0.dist-info/METADATA +354 -0
- onecli_sdk-0.1.0.dist-info/RECORD +31 -0
- onecli_sdk-0.1.0.dist-info/WHEEL +4 -0
- onecli_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
onecli/_errors.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""The errors the SDK raises, and the redaction every message goes through."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from onecli._js import JS_SPACE_CLASS
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from onecli.types import ApiErrorDetail
|
|
12
|
+
|
|
13
|
+
__all__ = ["OneCLIApiError", "OneCLIError", "OneCLIRequestError", "redact"]
|
|
14
|
+
|
|
15
|
+
# Every token family the server issues, and any user:password in a URL, is
|
|
16
|
+
# replaced before a message is stored on an error. The families: managing key
|
|
17
|
+
# `oc_key_`, agent credential `oc_agent_`, connect token `oc_connect_`, sign-up
|
|
18
|
+
# poll token `oc_poll_`, directory-sync token `oc_scim_`, old keys `oc_` /
|
|
19
|
+
# `oc_org_`, and old agent tokens `aoc_` / `oat_`. `oc_` covers the `oc_*_`
|
|
20
|
+
# families. Six characters at least, so a hint like `oc_key_...` stays readable.
|
|
21
|
+
_SECRET_RE = re.compile(r"(?<![A-Za-z0-9])(?:a?oc|oat)_[A-Za-z0-9_-]{6,}")
|
|
22
|
+
# A scheme starts after a character that is not an ASCII letter, digit or
|
|
23
|
+
# underscore, as JavaScript's \b sees it.
|
|
24
|
+
_URL_USERINFO_RE = re.compile(
|
|
25
|
+
rf"((?<![A-Za-z0-9_])[A-Za-z][A-Za-z0-9+.-]*://)[^{JS_SPACE_CLASS}/@]*@"
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def redact(text: str) -> str:
|
|
30
|
+
"""Replace every token and every user:password in a URL with ``[redacted]``."""
|
|
31
|
+
return _SECRET_RE.sub("[redacted]", _URL_USERINFO_RE.sub(r"\1[redacted]@", text))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class OneCLIError(Exception):
|
|
35
|
+
"""Anything the SDK raises: a refused input, no answer, or a failed call.
|
|
36
|
+
|
|
37
|
+
The message never holds a key, a credential or a token.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
message: str
|
|
41
|
+
"""The message, redacted."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, message: str) -> None:
|
|
44
|
+
self.message = redact(message)
|
|
45
|
+
super().__init__(self.message)
|
|
46
|
+
|
|
47
|
+
def __reduce__(self) -> tuple[Any, ...]:
|
|
48
|
+
return (_rebuild, (type(self), self.__dict__.copy()))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _rebuild(cls: type[OneCLIError], state: dict[str, Any]) -> OneCLIError:
|
|
52
|
+
error = cls.__new__(cls)
|
|
53
|
+
error.__dict__.update(state)
|
|
54
|
+
Exception.__init__(error, state.get("message", ""))
|
|
55
|
+
return error
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class OneCLIRequestError(OneCLIError):
|
|
59
|
+
"""A call that got an answer the SDK could not use: a failed status or a body it cannot read.
|
|
60
|
+
|
|
61
|
+
The message starts with ``[URL=...] [StatusCode=...]``.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
url: str
|
|
65
|
+
"""The URL of the call, redacted."""
|
|
66
|
+
status_code: int
|
|
67
|
+
"""The HTTP status of the answer."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, message: str, *, url: str, status_code: int) -> None:
|
|
70
|
+
safe_url = redact(url)
|
|
71
|
+
super().__init__(f"[URL={safe_url}] [StatusCode={status_code}] {redact(message)}")
|
|
72
|
+
self.url = safe_url
|
|
73
|
+
self.status_code = status_code
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class OneCLIApiError(OneCLIRequestError):
|
|
77
|
+
"""A failed /v2 call, with the server's error shape."""
|
|
78
|
+
|
|
79
|
+
code: str
|
|
80
|
+
"""The server's error code, for example ``not_found`` or ``forbidden``."""
|
|
81
|
+
reason: str
|
|
82
|
+
"""The server's message alone, without the URL and status prefix."""
|
|
83
|
+
details: list[ApiErrorDetail]
|
|
84
|
+
"""What was wrong with each field, when the server said."""
|
|
85
|
+
request_id: str | None
|
|
86
|
+
"""The X-Request-Id of the call, to quote when asking for help."""
|
|
87
|
+
retry_after: float | None
|
|
88
|
+
"""Seconds to wait before trying again, from Retry-After."""
|
|
89
|
+
|
|
90
|
+
def __init__(
|
|
91
|
+
self,
|
|
92
|
+
message: str,
|
|
93
|
+
*,
|
|
94
|
+
url: str,
|
|
95
|
+
status_code: int,
|
|
96
|
+
code: str,
|
|
97
|
+
details: list[ApiErrorDetail],
|
|
98
|
+
request_id: str | None,
|
|
99
|
+
retry_after: float | None,
|
|
100
|
+
) -> None:
|
|
101
|
+
super().__init__(message, url=url, status_code=status_code)
|
|
102
|
+
self.code = code
|
|
103
|
+
self.reason = redact(message)
|
|
104
|
+
self.details = [d.model_copy(update={"message": redact(d.message)}) for d in details]
|
|
105
|
+
self.request_id = request_id
|
|
106
|
+
self.retry_after = retry_after
|
onecli/_js.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
r"""JavaScript's string rules, where Node's SDK leans on them and Python's differ.
|
|
2
|
+
|
|
3
|
+
Python's ``str.strip()`` and the ``\s`` of ``re`` take a few characters
|
|
4
|
+
JavaScript does not (``\x1c`` to ``\x1f``, ``\x85``) and miss one it takes
|
|
5
|
+
(``\ufeff``). ``float()`` reads ``1_0`` and full-width digits, which
|
|
6
|
+
JavaScript's ``Number()`` refuses, and refuses ``0x10``, which it reads.
|
|
7
|
+
``len()`` and slices count code points, JavaScript counts UTF-16 units.
|
|
8
|
+
A Python string can hold a surrogate pair as two code points, where
|
|
9
|
+
JavaScript reads the one character they stand for.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from typing import Final
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"JS_SPACE_CLASS",
|
|
19
|
+
"js_integer",
|
|
20
|
+
"js_length",
|
|
21
|
+
"js_number",
|
|
22
|
+
"js_pairs",
|
|
23
|
+
"js_prefix",
|
|
24
|
+
"js_trim",
|
|
25
|
+
"js_usv",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
# WhiteSpace and LineTerminator of ECMA-262: what `trim()`, `\s` and `Number()` skip.
|
|
29
|
+
_JS_SPACE: Final = (
|
|
30
|
+
"\t\n\v\f\r \xa0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009"
|
|
31
|
+
"\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
|
|
32
|
+
)
|
|
33
|
+
JS_SPACE_CLASS: Final = "".join(f"\\u{ord(c):04x}" for c in _JS_SPACE)
|
|
34
|
+
r"""The characters of JavaScript's ``\s``, written for a ``re`` character class."""
|
|
35
|
+
|
|
36
|
+
# StringNumericLiteral, the text Number() reads once the spaces around it are gone.
|
|
37
|
+
_DECIMAL: Final = re.compile(r"[+-]?(?:Infinity|(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)")
|
|
38
|
+
_RADIX: Final = {"x": 16, "o": 8, "b": 2}
|
|
39
|
+
_RADIX_RE: Final = re.compile(r"0(?:[xX][0-9A-Fa-f]+|[oO][0-7]+|[bB][01]+)")
|
|
40
|
+
_MAX_UTF16: Final = 0xFFFF
|
|
41
|
+
_SURROGATE: Final = re.compile("[\ud800-\udfff]")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def js_trim(text: str) -> str:
|
|
45
|
+
"""``text.trim()`` as JavaScript does it."""
|
|
46
|
+
return text.strip(_JS_SPACE)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def js_number(text: str) -> float:
|
|
50
|
+
"""``Number(text)`` as JavaScript reads a string: NaN when it is not a number."""
|
|
51
|
+
body = js_trim(text)
|
|
52
|
+
if body == "":
|
|
53
|
+
return 0.0
|
|
54
|
+
if _RADIX_RE.fullmatch(body):
|
|
55
|
+
whole = int(body[2:], _RADIX[body[1].lower()])
|
|
56
|
+
try:
|
|
57
|
+
return float(whole)
|
|
58
|
+
except OverflowError: # Past the largest double: JavaScript says Infinity.
|
|
59
|
+
return float("inf")
|
|
60
|
+
if _DECIMAL.fullmatch(body):
|
|
61
|
+
return float(body.replace("Infinity", "inf"))
|
|
62
|
+
return float("nan")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def js_prefix(text: str, units: int) -> str:
|
|
66
|
+
"""``text.slice(0, units)``: the first ``units`` UTF-16 code units.
|
|
67
|
+
|
|
68
|
+
A pair cut in half leaves U+FFFD, which is what ``URLSearchParams`` sends
|
|
69
|
+
for the lone half JavaScript would keep.
|
|
70
|
+
"""
|
|
71
|
+
kept: list[str] = []
|
|
72
|
+
used = 0
|
|
73
|
+
for char in text:
|
|
74
|
+
width = 2 if ord(char) > _MAX_UTF16 else 1
|
|
75
|
+
if used + width > units:
|
|
76
|
+
if used < units:
|
|
77
|
+
kept.append("\ufffd")
|
|
78
|
+
break
|
|
79
|
+
kept.append(char)
|
|
80
|
+
used += width
|
|
81
|
+
return "".join(kept)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def js_length(text: str) -> int:
|
|
85
|
+
"""``text.length``: the number of UTF-16 code units."""
|
|
86
|
+
return len(text) + sum(1 for char in text if ord(char) > _MAX_UTF16)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def js_pairs(text: str) -> str:
|
|
90
|
+
"""``text`` with each surrogate pair joined into its character, as JavaScript reads it.
|
|
91
|
+
|
|
92
|
+
A lone surrogate is kept, for the caller to refuse.
|
|
93
|
+
"""
|
|
94
|
+
if not _SURROGATE.search(text):
|
|
95
|
+
return text
|
|
96
|
+
return text.encode("utf-16-le", "surrogatepass").decode("utf-16-le", "surrogatepass")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def js_usv(text: str) -> str:
|
|
100
|
+
"""``text`` as JavaScript's USVString conversion gives it (``URLSearchParams``).
|
|
101
|
+
|
|
102
|
+
Each surrogate pair is joined into its character, and a lone surrogate
|
|
103
|
+
becomes U+FFFD.
|
|
104
|
+
"""
|
|
105
|
+
if not _SURROGATE.search(text):
|
|
106
|
+
return text
|
|
107
|
+
return text.encode("utf-16-le", "surrogatepass").decode("utf-16-le", "replace")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def js_integer(value: object) -> int | None:
|
|
111
|
+
"""``value`` as an int when ``Number.isInteger(value)`` would be true, else None.
|
|
112
|
+
|
|
113
|
+
A whole float such as ``2.0`` counts. A bool does not: JavaScript's
|
|
114
|
+
``true`` is not a number.
|
|
115
|
+
"""
|
|
116
|
+
if isinstance(value, bool):
|
|
117
|
+
return None
|
|
118
|
+
if isinstance(value, int):
|
|
119
|
+
return value
|
|
120
|
+
if isinstance(value, float) and value.is_integer():
|
|
121
|
+
return int(value)
|
|
122
|
+
return None
|
onecli/_keys.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Which kind of token a string is, and the checks each part makes before any call."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Final, Literal
|
|
7
|
+
|
|
8
|
+
from onecli._errors import OneCLIError
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"AGENT_PREFIX",
|
|
12
|
+
"CONNECT_PREFIX",
|
|
13
|
+
"MANAGING_PREFIX",
|
|
14
|
+
"OLD_AGENT_PREFIXES",
|
|
15
|
+
"KeyKind",
|
|
16
|
+
"assert_agent_credential",
|
|
17
|
+
"assert_connect_token",
|
|
18
|
+
"assert_owner_key",
|
|
19
|
+
"key_kind",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
AGENT_PREFIX: Final = "oc_agent_"
|
|
23
|
+
"""An agent credential starts with this."""
|
|
24
|
+
CONNECT_PREFIX: Final = "oc_connect_"
|
|
25
|
+
"""A vault's connect token starts with this."""
|
|
26
|
+
MANAGING_PREFIX: Final = "oc_key_"
|
|
27
|
+
"""A managing key starts with this."""
|
|
28
|
+
OLD_AGENT_PREFIXES: Final = ("aoc_", "oat_")
|
|
29
|
+
"""The old agent tokens from before 3.0. OneCLI 3.0 no longer accepts them."""
|
|
30
|
+
# One-purpose tokens that are never a key: a sign-up poll and directory sync.
|
|
31
|
+
_OTHER_PREFIXES: Final = ("oc_poll_", "oc_scim_")
|
|
32
|
+
_TOKEN_RE: Final = re.compile(r"[A-Za-z0-9_\-.]+")
|
|
33
|
+
|
|
34
|
+
KeyKind = Literal["managing", "agent", "connect", "old-agent", "other", "none"]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def key_kind(key: str) -> KeyKind:
|
|
38
|
+
"""Which kind of token ``key`` is, from its prefix."""
|
|
39
|
+
if key == "":
|
|
40
|
+
return "none"
|
|
41
|
+
if key.startswith(AGENT_PREFIX):
|
|
42
|
+
return "agent"
|
|
43
|
+
if key.startswith(CONNECT_PREFIX):
|
|
44
|
+
return "connect"
|
|
45
|
+
if key.startswith(OLD_AGENT_PREFIXES):
|
|
46
|
+
return "old-agent"
|
|
47
|
+
if key.startswith(_OTHER_PREFIXES):
|
|
48
|
+
return "other"
|
|
49
|
+
return "managing"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def assert_owner_key(key: str) -> None:
|
|
53
|
+
"""The owner part takes a managing key (or an older API key). Fails before any call."""
|
|
54
|
+
kind = key_kind(key)
|
|
55
|
+
if kind == "agent":
|
|
56
|
+
msg = (
|
|
57
|
+
"This is an agent credential. Use OneCLI.agent() for the agent part. "
|
|
58
|
+
"OneCLI(key=...) needs a managing key (oc_key_...)."
|
|
59
|
+
)
|
|
60
|
+
raise OneCLIError(msg)
|
|
61
|
+
if kind == "connect":
|
|
62
|
+
msg = (
|
|
63
|
+
"This is a vault's connect token. It is for the connect command in a sandbox. "
|
|
64
|
+
"OneCLI(key=...) needs a managing key (oc_key_...)."
|
|
65
|
+
)
|
|
66
|
+
raise OneCLIError(msg)
|
|
67
|
+
if kind == "old-agent":
|
|
68
|
+
msg = (
|
|
69
|
+
"This is an old agent token. OneCLI 3.0 no longer accepts it. "
|
|
70
|
+
"OneCLI(key=...) needs a managing key (oc_key_...)."
|
|
71
|
+
)
|
|
72
|
+
raise OneCLIError(msg)
|
|
73
|
+
if kind == "other":
|
|
74
|
+
msg = "This token is not a key. OneCLI(key=...) needs a managing key (oc_key_...)."
|
|
75
|
+
raise OneCLIError(msg)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def assert_connect_token(token: str) -> None:
|
|
79
|
+
"""OneCLI.connect takes a vault's connect token only. Fails before any call."""
|
|
80
|
+
if key_kind(token) != "connect" or not _TOKEN_RE.fullmatch(token):
|
|
81
|
+
msg = "OneCLI.connect needs a vault's connect token (oc_connect_...)."
|
|
82
|
+
raise OneCLIError(msg)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def assert_agent_credential(credential: str) -> None:
|
|
86
|
+
"""The agent part takes an agent credential only. Fails before any call."""
|
|
87
|
+
if credential == "":
|
|
88
|
+
msg = (
|
|
89
|
+
"No agent credential: pass one to OneCLI.agent(credential=...) "
|
|
90
|
+
"or set ONECLI_AGENT_CREDENTIAL."
|
|
91
|
+
)
|
|
92
|
+
raise OneCLIError(msg)
|
|
93
|
+
if key_kind(credential) != "agent":
|
|
94
|
+
msg = (
|
|
95
|
+
"OneCLI.agent() needs an agent credential (oc_agent_...). "
|
|
96
|
+
"For a managing key use OneCLI(key=...)."
|
|
97
|
+
)
|
|
98
|
+
raise OneCLIError(msg)
|
|
99
|
+
if not _TOKEN_RE.fullmatch(credential):
|
|
100
|
+
msg = "The agent credential has characters a credential never has."
|
|
101
|
+
raise OneCLIError(msg)
|
onecli/_lifetime.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""How long an agent made by ``agents.create`` lives.
|
|
2
|
+
|
|
3
|
+
One hour unless the caller says otherwise, and forever only when
|
|
4
|
+
``no_expiry=True`` is written.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from datetime import UTC, datetime
|
|
11
|
+
from typing import Final
|
|
12
|
+
|
|
13
|
+
from onecli._errors import OneCLIError
|
|
14
|
+
from onecli._js import js_integer, js_trim
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"DEFAULT_TTL_SECONDS",
|
|
18
|
+
"MAX_TTL_SECONDS",
|
|
19
|
+
"MIN_TTL_SECONDS",
|
|
20
|
+
"iso_datetime",
|
|
21
|
+
"iso_ms",
|
|
22
|
+
"now_ms",
|
|
23
|
+
"resolve_expiry",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
DEFAULT_TTL_SECONDS: Final = 60 * 60
|
|
27
|
+
"""The lifetime of an agent when none is given."""
|
|
28
|
+
MIN_TTL_SECONDS: Final = 5 * 60
|
|
29
|
+
"""The shortest lifetime the server takes: 5 minutes ahead."""
|
|
30
|
+
MAX_TTL_SECONDS: Final = 90 * 24 * 60 * 60
|
|
31
|
+
"""The longest lifetime the server takes: 90 days ahead."""
|
|
32
|
+
|
|
33
|
+
# The server has no `ttlSeconds`: it takes a moment in time and refuses one
|
|
34
|
+
# that is under 5 minutes or over 90 days ahead of its own clock. The request
|
|
35
|
+
# takes a moment to arrive, so a short lifetime is sent a little long and the
|
|
36
|
+
# longest one a little short.
|
|
37
|
+
_CUSHION_MS: Final = 15_000
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def now_ms() -> int:
|
|
41
|
+
"""The time now, in whole milliseconds since 1970 (JavaScript's ``Date.now()``)."""
|
|
42
|
+
return time.time_ns() // 1_000_000
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _iso(moment: datetime) -> str:
|
|
46
|
+
"""ISO 8601 in UTC with milliseconds, as JavaScript's ``toISOString()`` writes it."""
|
|
47
|
+
return (
|
|
48
|
+
f"{moment.year:04d}-{moment.month:02d}-{moment.day:02d}"
|
|
49
|
+
f"T{moment.hour:02d}:{moment.minute:02d}:{moment.second:02d}"
|
|
50
|
+
f".{moment.microsecond // 1000:03d}Z"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def iso_ms(ms: int) -> str:
|
|
55
|
+
"""A moment in milliseconds since 1970, in ISO 8601 (UTC, with milliseconds)."""
|
|
56
|
+
seconds, millis = divmod(ms, 1000)
|
|
57
|
+
return _iso(datetime.fromtimestamp(seconds, tz=UTC).replace(microsecond=millis * 1000))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def iso_datetime(value: datetime, name: str) -> str:
|
|
61
|
+
"""An aware datetime in ISO 8601 (UTC, with milliseconds).
|
|
62
|
+
|
|
63
|
+
A datetime with no timezone is refused: it could be any of 24 moments.
|
|
64
|
+
"""
|
|
65
|
+
if value.utcoffset() is None:
|
|
66
|
+
msg = f"{name} has no timezone. Give one, like datetime.now(UTC)."
|
|
67
|
+
raise OneCLIError(msg)
|
|
68
|
+
return _iso(value.astimezone(UTC))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def resolve_expiry(
|
|
72
|
+
*,
|
|
73
|
+
ttl_seconds: object = None,
|
|
74
|
+
expires_at: object = None,
|
|
75
|
+
no_expiry: object = False,
|
|
76
|
+
now: int | None = None,
|
|
77
|
+
) -> str | None:
|
|
78
|
+
"""The ``expiresAt`` to send, or None for an agent that never expires.
|
|
79
|
+
|
|
80
|
+
Raises on a bad value, before any call is made. ``now`` is in milliseconds.
|
|
81
|
+
"""
|
|
82
|
+
if not isinstance(no_expiry, bool):
|
|
83
|
+
msg = "no_expiry must be True, or left out."
|
|
84
|
+
raise OneCLIError(msg)
|
|
85
|
+
given = [ttl_seconds is not None, expires_at is not None, no_expiry]
|
|
86
|
+
if sum(given) > 1:
|
|
87
|
+
msg = "Give only one of ttl_seconds, expires_at and no_expiry."
|
|
88
|
+
raise OneCLIError(msg)
|
|
89
|
+
if no_expiry:
|
|
90
|
+
return None
|
|
91
|
+
if isinstance(expires_at, str):
|
|
92
|
+
if js_trim(expires_at) == "":
|
|
93
|
+
msg = "expires_at is empty."
|
|
94
|
+
raise OneCLIError(msg)
|
|
95
|
+
return expires_at
|
|
96
|
+
if isinstance(expires_at, datetime):
|
|
97
|
+
return iso_datetime(expires_at, "expires_at")
|
|
98
|
+
if expires_at is not None:
|
|
99
|
+
msg = "expires_at is not a valid date."
|
|
100
|
+
raise OneCLIError(msg)
|
|
101
|
+
|
|
102
|
+
ttl = js_integer(DEFAULT_TTL_SECONDS if ttl_seconds is None else ttl_seconds)
|
|
103
|
+
if ttl is None or not MIN_TTL_SECONDS <= ttl <= MAX_TTL_SECONDS:
|
|
104
|
+
msg = (
|
|
105
|
+
f"ttl_seconds must be a whole number from {MIN_TTL_SECONDS} (5 minutes) to "
|
|
106
|
+
f"{MAX_TTL_SECONDS} (90 days). For an agent that never expires, write no_expiry=True."
|
|
107
|
+
)
|
|
108
|
+
raise OneCLIError(msg)
|
|
109
|
+
ahead = min(ttl * 1000 + _CUSHION_MS, MAX_TTL_SECONDS * 1000 - _CUSHION_MS)
|
|
110
|
+
return iso_ms((now_ms() if now is None else now) + ahead)
|
onecli/_retry.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""When a failed call is tried again. These are the rules only, with no I/O.
|
|
2
|
+
|
|
3
|
+
The transport runs the loop. A call is tried again only when sending it twice
|
|
4
|
+
cannot do the work twice:
|
|
5
|
+
|
|
6
|
+
- GET, PUT and DELETE, and a POST that carries an Idempotency-Key, are tried
|
|
7
|
+
again when no answer came or the server said "not now".
|
|
8
|
+
- Every other call is tried again only on 429: the limiter answered before
|
|
9
|
+
the call ran.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import math
|
|
15
|
+
import random as _random
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import TYPE_CHECKING, Final, Literal
|
|
18
|
+
|
|
19
|
+
from onecli._errors import OneCLIError
|
|
20
|
+
from onecli._js import js_integer
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from collections.abc import Callable
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"DEFAULT_MAX_RETRIES",
|
|
27
|
+
"MAX_RETRIES_LIMIT",
|
|
28
|
+
"NoAnswer",
|
|
29
|
+
"Outcome",
|
|
30
|
+
"RetryMethod",
|
|
31
|
+
"StatusAnswer",
|
|
32
|
+
"backoff_ms",
|
|
33
|
+
"check_max_retries",
|
|
34
|
+
"is_repeatable",
|
|
35
|
+
"should_retry",
|
|
36
|
+
"wait_ms",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
DEFAULT_MAX_RETRIES: Final = 2
|
|
40
|
+
"""Tries after the first one, unless the client or the call says otherwise."""
|
|
41
|
+
MAX_RETRIES_LIMIT: Final = 10
|
|
42
|
+
"""The most ``max_retries`` may be. More than this hammers a server that is already down."""
|
|
43
|
+
|
|
44
|
+
_BASE_MS: Final = 500
|
|
45
|
+
_CAP_MS: Final = 8_000
|
|
46
|
+
# A little spread on top of the server's Retry-After, so many clients do not come back at once.
|
|
47
|
+
_RETRY_AFTER_SPREAD_MS: Final = 250
|
|
48
|
+
_TOO_MANY: Final = 429
|
|
49
|
+
_CONFLICT: Final = 409
|
|
50
|
+
# Answers that mean "not now" and say nothing about the call itself.
|
|
51
|
+
_NOT_NOW: Final = frozenset({502, 503, 504})
|
|
52
|
+
|
|
53
|
+
RetryMethod = Literal["GET", "POST", "PUT", "PATCH", "DELETE"]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True, slots=True)
|
|
57
|
+
class NoAnswer:
|
|
58
|
+
"""The network failed or the try timed out, so the call may have run."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True, slots=True)
|
|
62
|
+
class StatusAnswer:
|
|
63
|
+
"""The server answered with ``status``. ``replayed``: the stored answer of an earlier try."""
|
|
64
|
+
|
|
65
|
+
status: int
|
|
66
|
+
replayed: bool = False
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
Outcome = NoAnswer | StatusAnswer
|
|
70
|
+
"""How one try ended."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def is_repeatable(method: RetryMethod, *, keyed: bool) -> bool:
|
|
74
|
+
"""Whether the server does the work once however often the call is sent."""
|
|
75
|
+
return method in {"GET", "PUT", "DELETE"} or (method == "POST" and keyed)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def should_retry(*, method: RetryMethod, keyed: bool, attempt: int, outcome: Outcome) -> bool:
|
|
79
|
+
"""Whether to try again after try number ``attempt`` (1 after the first) ended so."""
|
|
80
|
+
repeatable = is_repeatable(method, keyed=keyed)
|
|
81
|
+
if isinstance(outcome, NoAnswer):
|
|
82
|
+
return repeatable
|
|
83
|
+
if outcome.status == _TOO_MANY:
|
|
84
|
+
return True
|
|
85
|
+
if outcome.status in _NOT_NOW:
|
|
86
|
+
return repeatable
|
|
87
|
+
# A keyed POST that is sent again while its first try still runs gets a
|
|
88
|
+
# 409. A 409 marked as a replay is the first try's own answer.
|
|
89
|
+
if outcome.status == _CONFLICT:
|
|
90
|
+
return method == "POST" and keyed and attempt > 1 and not outcome.replayed
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def backoff_ms(attempt: int, random: Callable[[], float] = _random.random) -> int:
|
|
95
|
+
"""Full jitter: a random wait from 0 up to 0.5 s, 1 s, 2 s, ... and 8 s at most."""
|
|
96
|
+
return math.floor(random() * min(_CAP_MS, _BASE_MS * 2 ** (attempt - 1)))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def wait_ms(
|
|
100
|
+
attempt: int,
|
|
101
|
+
retry_after_seconds: float | None,
|
|
102
|
+
random: Callable[[], float] = _random.random,
|
|
103
|
+
) -> int:
|
|
104
|
+
"""The wait before the next try: the server's Retry-After when it sent one, else the backoff."""
|
|
105
|
+
if retry_after_seconds is None:
|
|
106
|
+
return backoff_ms(attempt, random)
|
|
107
|
+
return math.ceil(retry_after_seconds * 1000) + math.floor(random() * _RETRY_AFTER_SPREAD_MS)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def check_max_retries(value: object) -> int:
|
|
111
|
+
"""Refuse a ``max_retries`` that is not a whole number from 0 to 10."""
|
|
112
|
+
whole = js_integer(value)
|
|
113
|
+
if whole is None or not 0 <= whole <= MAX_RETRIES_LIMIT:
|
|
114
|
+
msg = f"max_retries must be a whole number from 0 to {MAX_RETRIES_LIMIT}."
|
|
115
|
+
raise OneCLIError(msg)
|
|
116
|
+
return whole
|
onecli/_sync/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The sync client, made from ``_async`` by scripts/gen_sync.py. Do not edit, but ``_io.py``."""
|