chickinfry 0.5.0.dev1__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.
- chickinfry/__init__.py +18 -0
- chickinfry/_auth_database.py +765 -0
- chickinfry/_conformance.py +208 -0
- chickinfry/_device.py +1405 -0
- chickinfry/_device_windows.py +250 -0
- chickinfry/_error_details.py +76 -0
- chickinfry/_http_common.py +165 -0
- chickinfry/_input.py +129 -0
- chickinfry/_origin.py +60 -0
- chickinfry/_password.py +38 -0
- chickinfry/_request_logs.py +66 -0
- chickinfry/_request_state.py +32 -0
- chickinfry/_sync_http.py +546 -0
- chickinfry/_sync_network.py +288 -0
- chickinfry/_workerd.py +731 -0
- chickinfry/auth.py +1227 -0
- chickinfry/errors.py +101 -0
- chickinfry/http.py +427 -0
- chickinfry/orm.py +506 -0
- chickinfry/postgres.py +281 -0
- chickinfry/py.typed +0 -0
- chickinfry/realtime.py +522 -0
- chickinfry/server.py +540 -0
- chickinfry/session.py +465 -0
- chickinfry/signup.py +134 -0
- chickinfry/wire.py +23 -0
- chickinfry-0.5.0.dev1.dist-info/METADATA +375 -0
- chickinfry-0.5.0.dev1.dist-info/RECORD +30 -0
- chickinfry-0.5.0.dev1.dist-info/WHEEL +4 -0
- chickinfry-0.5.0.dev1.dist-info/licenses/LICENSE +202 -0
chickinfry/_password.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Internal password KDF boundary; the Pyodide implementation is not selected yet."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import re
|
|
6
|
+
import secrets
|
|
7
|
+
from typing import Protocol
|
|
8
|
+
|
|
9
|
+
_FORMAT = re.compile(r"scrypt\$32768\$8\$3\$([a-f0-9]{32})\$([a-f0-9]{64})")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PasswordKDF(Protocol):
|
|
13
|
+
def derive(self, password: bytes, salt: bytes) -> bytes: ...
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CPythonScrypt:
|
|
17
|
+
# shortcut: CPython/OpenSSL only; Pyodide needs a separately measured implementation.
|
|
18
|
+
def derive(self, password: bytes, salt: bytes) -> bytes:
|
|
19
|
+
return hashlib.scrypt(
|
|
20
|
+
password, salt=salt, n=32768, r=8, p=3, maxmem=64 << 20, dklen=32
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def hash_password(password: str, kdf: PasswordKDF) -> str:
|
|
25
|
+
salt = secrets.token_bytes(16)
|
|
26
|
+
key = kdf.derive(password.encode("utf-8"), salt)
|
|
27
|
+
if len(key) != 32:
|
|
28
|
+
raise ValueError("Password hashing failed.")
|
|
29
|
+
return f"scrypt$32768$8$3${salt.hex()}${key.hex()}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def verify_password(password: str, stored: str | None, kdf: PasswordKDF) -> bool:
|
|
33
|
+
parts = _FORMAT.fullmatch(stored) if isinstance(stored, str) else None
|
|
34
|
+
salt = bytes.fromhex(parts[1]) if parts else bytes(16)
|
|
35
|
+
expected = bytes.fromhex(parts[2]) if parts else bytes(32)
|
|
36
|
+
actual = kdf.derive(password.encode("utf-8"), salt)
|
|
37
|
+
matched = hmac.compare_digest(actual, expected)
|
|
38
|
+
return parts is not None and matched and len(actual) == 32
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import threading
|
|
3
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from contextvars import ContextVar
|
|
6
|
+
from types import TracebackType
|
|
7
|
+
|
|
8
|
+
_active: ContextVar[bool] = ContextVar("chickinfry_request_logs", default=False)
|
|
9
|
+
_lock = threading.Lock()
|
|
10
|
+
_installed: Callable[..., logging.LogRecord] | None = None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _install() -> None:
|
|
14
|
+
global _installed
|
|
15
|
+
with _lock:
|
|
16
|
+
previous = logging.getLogRecordFactory()
|
|
17
|
+
if previous is _installed:
|
|
18
|
+
return
|
|
19
|
+
|
|
20
|
+
def factory(
|
|
21
|
+
name: str,
|
|
22
|
+
level: int,
|
|
23
|
+
pathname: str,
|
|
24
|
+
lineno: int,
|
|
25
|
+
msg: object,
|
|
26
|
+
args: tuple[object, ...] | Mapping[str, object] | None,
|
|
27
|
+
exc_info: tuple[type[BaseException], BaseException, TracebackType | None]
|
|
28
|
+
| tuple[None, None, None]
|
|
29
|
+
| None,
|
|
30
|
+
func: str | None = None,
|
|
31
|
+
sinfo: str | None = None,
|
|
32
|
+
**kwargs: object,
|
|
33
|
+
) -> logging.LogRecord:
|
|
34
|
+
if _active.get() and name.split(".", 1)[0] in {"httpx", "httpcore", "h11"}:
|
|
35
|
+
# Sanitize contextual logs before outer factories or handlers see the raw exception.
|
|
36
|
+
msg, args, exc_info, sinfo = (
|
|
37
|
+
"Chickinfry request transport event",
|
|
38
|
+
(),
|
|
39
|
+
None,
|
|
40
|
+
None,
|
|
41
|
+
)
|
|
42
|
+
return previous(
|
|
43
|
+
name,
|
|
44
|
+
level,
|
|
45
|
+
pathname,
|
|
46
|
+
lineno,
|
|
47
|
+
msg,
|
|
48
|
+
args,
|
|
49
|
+
exc_info,
|
|
50
|
+
func,
|
|
51
|
+
sinfo,
|
|
52
|
+
**kwargs,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
logging.setLogRecordFactory(factory)
|
|
56
|
+
_installed = factory
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@contextmanager
|
|
60
|
+
def _request_logs() -> Iterator[None]:
|
|
61
|
+
_install()
|
|
62
|
+
token = _active.set(True)
|
|
63
|
+
try:
|
|
64
|
+
yield
|
|
65
|
+
finally:
|
|
66
|
+
_active.reset(token)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import threading
|
|
2
|
+
from contextvars import ContextVar
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class _RequestState:
|
|
6
|
+
def __init__(self) -> None:
|
|
7
|
+
self._lock = threading.Lock()
|
|
8
|
+
self._sending = False
|
|
9
|
+
self._finished = False
|
|
10
|
+
|
|
11
|
+
def trace(self, event: str, info: dict[str, object]) -> None:
|
|
12
|
+
if event.endswith(".send_request_headers.started"):
|
|
13
|
+
with self._lock:
|
|
14
|
+
self._sending = True
|
|
15
|
+
|
|
16
|
+
async def atrace(self, event: str, info: dict[str, object]) -> None:
|
|
17
|
+
self.trace(event, info)
|
|
18
|
+
|
|
19
|
+
def finish(self) -> None:
|
|
20
|
+
with self._lock:
|
|
21
|
+
self._finished = True
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def outcome_unknown(self) -> bool:
|
|
25
|
+
# Failures after header writes begin may have sent partial output; only completion is certain.
|
|
26
|
+
with self._lock:
|
|
27
|
+
return self._sending and not self._finished
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
_state: ContextVar[_RequestState | None] = ContextVar(
|
|
31
|
+
"chickinfry_request_state", default=None
|
|
32
|
+
)
|
chickinfry/_sync_http.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import threading
|
|
3
|
+
import time
|
|
4
|
+
from collections.abc import Iterator, Mapping
|
|
5
|
+
from contextlib import contextmanager
|
|
6
|
+
from http.cookiejar import CookieJar
|
|
7
|
+
from typing import TYPE_CHECKING, Protocol, Self, cast
|
|
8
|
+
|
|
9
|
+
from ._conformance import _HookError, _Observation, _observer
|
|
10
|
+
from ._device import _device_store, _DeviceStore, _persist_settings
|
|
11
|
+
from ._http_common import (
|
|
12
|
+
_HEADERS,
|
|
13
|
+
_Body,
|
|
14
|
+
_check_environment,
|
|
15
|
+
_NoCookies,
|
|
16
|
+
_operation,
|
|
17
|
+
_response,
|
|
18
|
+
_serialize,
|
|
19
|
+
_timeout,
|
|
20
|
+
)
|
|
21
|
+
from ._origin import canonical_origin
|
|
22
|
+
from ._request_logs import _request_logs
|
|
23
|
+
from ._request_state import _RequestState, _state
|
|
24
|
+
from .errors import ClientError, OperationError, _local_error
|
|
25
|
+
from .session import (
|
|
26
|
+
SessionCredentials,
|
|
27
|
+
_Failure,
|
|
28
|
+
_finish_auth,
|
|
29
|
+
_read_credentials,
|
|
30
|
+
_refresh_candidate,
|
|
31
|
+
_SessionStore,
|
|
32
|
+
_SyncFlight,
|
|
33
|
+
_valid_token,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
if TYPE_CHECKING:
|
|
37
|
+
import httpx
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _check_deadline(deadline: float) -> None:
|
|
41
|
+
if time.monotonic() >= deadline:
|
|
42
|
+
raise ClientError("deadline_exceeded")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Transport(Protocol):
|
|
46
|
+
"""The synchronous operation contract consumed by generated clients."""
|
|
47
|
+
|
|
48
|
+
def invoke(self, operation: str, payload: bytes | Mapping[str, object]) -> object:
|
|
49
|
+
"""Invoke one operation and return its parsed JSON value."""
|
|
50
|
+
...
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class HttpTransport:
|
|
54
|
+
"""An origin-bound synchronous transport with a pool shared safely by threads."""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
origin: str,
|
|
59
|
+
*,
|
|
60
|
+
timeout: float = 30.0,
|
|
61
|
+
persist: bool | Mapping[str, object] = True,
|
|
62
|
+
) -> None:
|
|
63
|
+
_check_environment()
|
|
64
|
+
self._origin = canonical_origin(origin)
|
|
65
|
+
self._timeout = _timeout(timeout)
|
|
66
|
+
self._persist = _persist_settings(persist)
|
|
67
|
+
self._lock = threading.RLock()
|
|
68
|
+
self._closed = False
|
|
69
|
+
self._client: httpx.Client | None = None
|
|
70
|
+
|
|
71
|
+
@contextmanager
|
|
72
|
+
def _locked(self, deadline: float | None = None) -> Iterator[None]:
|
|
73
|
+
if deadline is None:
|
|
74
|
+
self._lock.acquire()
|
|
75
|
+
else:
|
|
76
|
+
remaining = deadline - time.monotonic()
|
|
77
|
+
if remaining <= 0 or not self._lock.acquire(timeout=remaining):
|
|
78
|
+
raise ClientError("deadline_exceeded")
|
|
79
|
+
try:
|
|
80
|
+
if self._closed:
|
|
81
|
+
raise _local_error("failed_precondition", "transport_closed")
|
|
82
|
+
if deadline is not None:
|
|
83
|
+
_check_deadline(deadline)
|
|
84
|
+
yield
|
|
85
|
+
finally:
|
|
86
|
+
self._lock.release()
|
|
87
|
+
|
|
88
|
+
def _http_client(self, deadline: float | None = None) -> "httpx.Client":
|
|
89
|
+
_check_environment()
|
|
90
|
+
with self._locked(deadline):
|
|
91
|
+
if self._client is None:
|
|
92
|
+
import httpx
|
|
93
|
+
|
|
94
|
+
from ._sync_network import _Transport
|
|
95
|
+
|
|
96
|
+
self._client = httpx.Client(
|
|
97
|
+
transport=_Transport(),
|
|
98
|
+
follow_redirects=False,
|
|
99
|
+
trust_env=False,
|
|
100
|
+
verify=True,
|
|
101
|
+
timeout=self._timeout,
|
|
102
|
+
cookies=CookieJar(policy=_NoCookies()),
|
|
103
|
+
headers=_HEADERS,
|
|
104
|
+
)
|
|
105
|
+
return self._client
|
|
106
|
+
|
|
107
|
+
def __enter__(self) -> Self:
|
|
108
|
+
self._http_client()
|
|
109
|
+
return self
|
|
110
|
+
|
|
111
|
+
def __exit__(self, *args: object) -> None:
|
|
112
|
+
self.close()
|
|
113
|
+
|
|
114
|
+
def close(self) -> None:
|
|
115
|
+
with self._lock:
|
|
116
|
+
if self._closed:
|
|
117
|
+
return
|
|
118
|
+
self._closed = True
|
|
119
|
+
client = self._client
|
|
120
|
+
if client is not None:
|
|
121
|
+
client.close()
|
|
122
|
+
|
|
123
|
+
def _device_store(
|
|
124
|
+
self, *, app: str, project: str, environment: str
|
|
125
|
+
) -> _DeviceStore:
|
|
126
|
+
return _device_store(
|
|
127
|
+
self._origin,
|
|
128
|
+
app=app,
|
|
129
|
+
project=project,
|
|
130
|
+
environment=environment,
|
|
131
|
+
persist=self._persist,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def with_bearer(self, token: str) -> Transport:
|
|
135
|
+
with self._locked():
|
|
136
|
+
if not _valid_token(token):
|
|
137
|
+
raise _local_error("invalid_argument", "invalid_token")
|
|
138
|
+
return _Authenticated(self, token=token)
|
|
139
|
+
|
|
140
|
+
def with_session(self, store: _SessionStore) -> Transport:
|
|
141
|
+
with self._locked():
|
|
142
|
+
if not isinstance(store, _SessionStore):
|
|
143
|
+
raise ClientError("failed_precondition")
|
|
144
|
+
store._attach("sync", self._origin)
|
|
145
|
+
return _Authenticated(self, store=store)
|
|
146
|
+
|
|
147
|
+
def invoke(self, operation: str, payload: bytes | Mapping[str, object]) -> object:
|
|
148
|
+
return self._invoke(operation, payload, None, None)
|
|
149
|
+
|
|
150
|
+
def invoke_public(
|
|
151
|
+
self, operation: str, payload: bytes | Mapping[str, object]
|
|
152
|
+
) -> object:
|
|
153
|
+
"""Invoke an operation declared public by the generated SDK."""
|
|
154
|
+
return self._invoke(operation, payload, None, None, public=True)
|
|
155
|
+
|
|
156
|
+
def _invoke(
|
|
157
|
+
self,
|
|
158
|
+
operation: str,
|
|
159
|
+
payload: bytes | Mapping[str, object],
|
|
160
|
+
token: str | None,
|
|
161
|
+
store: _SessionStore | None,
|
|
162
|
+
*,
|
|
163
|
+
public: bool = False,
|
|
164
|
+
) -> object:
|
|
165
|
+
observation = _observer.get()
|
|
166
|
+
if observation is not None:
|
|
167
|
+
observation.notify("entered")
|
|
168
|
+
observation.arrive("sdk-entered", {"entered": True})
|
|
169
|
+
deadline = time.monotonic() + 3 * self._timeout
|
|
170
|
+
_check_environment()
|
|
171
|
+
with self._locked(deadline):
|
|
172
|
+
pass
|
|
173
|
+
_operation(operation)
|
|
174
|
+
body = _serialize(payload)
|
|
175
|
+
_check_deadline(deadline)
|
|
176
|
+
snapshot: SessionCredentials | None = None
|
|
177
|
+
generation = 0
|
|
178
|
+
refresh_allowed = True
|
|
179
|
+
if store is not None:
|
|
180
|
+
with store._locked(deadline):
|
|
181
|
+
snapshot, generation = store._register(deadline, allow_empty=public)
|
|
182
|
+
refresh_allowed = store._blocked_generation != generation
|
|
183
|
+
token = snapshot.access_token if snapshot is not None else None
|
|
184
|
+
try:
|
|
185
|
+
try:
|
|
186
|
+
result = self._attempt(
|
|
187
|
+
operation,
|
|
188
|
+
body,
|
|
189
|
+
None if operation == "auth.refresh" else token,
|
|
190
|
+
deadline,
|
|
191
|
+
)
|
|
192
|
+
except OperationError as failure:
|
|
193
|
+
if (
|
|
194
|
+
store is None
|
|
195
|
+
or snapshot is None
|
|
196
|
+
or not refresh_allowed
|
|
197
|
+
or not _refresh_candidate(operation, failure)
|
|
198
|
+
):
|
|
199
|
+
raise
|
|
200
|
+
if observation is not None:
|
|
201
|
+
observation.arrive("both-originals-rejected", {"httpStatus": 401})
|
|
202
|
+
self._refresh(store, snapshot, generation, deadline)
|
|
203
|
+
with store._locked(deadline):
|
|
204
|
+
latest = store._new_credentials(generation)
|
|
205
|
+
if latest is None:
|
|
206
|
+
raise failure
|
|
207
|
+
result = self._attempt(operation, body, latest.access_token, deadline)
|
|
208
|
+
if store is not None:
|
|
209
|
+
_finish_auth(store, operation, result, snapshot, generation, deadline)
|
|
210
|
+
return result
|
|
211
|
+
finally:
|
|
212
|
+
if store is not None:
|
|
213
|
+
store._release(generation)
|
|
214
|
+
|
|
215
|
+
def _refresh(
|
|
216
|
+
self,
|
|
217
|
+
store: _SessionStore,
|
|
218
|
+
snapshot: SessionCredentials,
|
|
219
|
+
generation: int,
|
|
220
|
+
deadline: float,
|
|
221
|
+
) -> None:
|
|
222
|
+
elected = False
|
|
223
|
+
with store._locked(deadline):
|
|
224
|
+
if store._new_credentials(generation):
|
|
225
|
+
return
|
|
226
|
+
flight = store._sync_flights.get(generation)
|
|
227
|
+
if flight is None:
|
|
228
|
+
if not store._current(snapshot, generation):
|
|
229
|
+
return
|
|
230
|
+
flight = _SyncFlight(time.monotonic() + self._timeout)
|
|
231
|
+
store._sync_flights[generation] = flight
|
|
232
|
+
elected = True
|
|
233
|
+
observation = _observer.get()
|
|
234
|
+
if observation is not None:
|
|
235
|
+
observation.flight = flight
|
|
236
|
+
if elected:
|
|
237
|
+
thread: threading.Thread | None = None
|
|
238
|
+
try:
|
|
239
|
+
thread = threading.Thread(
|
|
240
|
+
target=self._produce,
|
|
241
|
+
args=(store, snapshot, generation, flight, observation)
|
|
242
|
+
if observation is not None
|
|
243
|
+
else (store, snapshot, generation, flight),
|
|
244
|
+
daemon=False,
|
|
245
|
+
)
|
|
246
|
+
with store._locked():
|
|
247
|
+
flight.thread = thread
|
|
248
|
+
thread.start()
|
|
249
|
+
except BaseException as error:
|
|
250
|
+
if isinstance(error, RuntimeError) and (
|
|
251
|
+
thread is None or thread.ident is None
|
|
252
|
+
):
|
|
253
|
+
self._publish(
|
|
254
|
+
store,
|
|
255
|
+
snapshot,
|
|
256
|
+
generation,
|
|
257
|
+
flight,
|
|
258
|
+
None,
|
|
259
|
+
_Failure("unavailable", retryable=True),
|
|
260
|
+
)
|
|
261
|
+
else:
|
|
262
|
+
self._watch_start(store, snapshot, generation, flight)
|
|
263
|
+
if not isinstance(error, Exception):
|
|
264
|
+
raise
|
|
265
|
+
elif (
|
|
266
|
+
observation is not None
|
|
267
|
+
and observation.flight_ref is not None
|
|
268
|
+
and not flight.settled
|
|
269
|
+
):
|
|
270
|
+
observation.arrive(
|
|
271
|
+
"refresh-joined", {"refreshRef": observation.flight_ref(flight)}
|
|
272
|
+
)
|
|
273
|
+
with store._locked(deadline):
|
|
274
|
+
while not flight.settled:
|
|
275
|
+
now = time.monotonic()
|
|
276
|
+
if now >= flight.deadline:
|
|
277
|
+
flight.result = _Failure(
|
|
278
|
+
"deadline_exceeded",
|
|
279
|
+
outcome_unknown=flight.request_state.outcome_unknown,
|
|
280
|
+
)
|
|
281
|
+
store._apply_refresh(snapshot, generation, None, flight.result)
|
|
282
|
+
flight.settled = True
|
|
283
|
+
store._condition.notify_all()
|
|
284
|
+
break
|
|
285
|
+
remaining = min(deadline, flight.deadline) - now
|
|
286
|
+
if remaining <= 0:
|
|
287
|
+
raise ClientError("deadline_exceeded")
|
|
288
|
+
store._condition.wait(remaining)
|
|
289
|
+
_check_deadline(deadline)
|
|
290
|
+
result = flight.result
|
|
291
|
+
if result is not None:
|
|
292
|
+
raise result.error()
|
|
293
|
+
|
|
294
|
+
def _watch_start(
|
|
295
|
+
self,
|
|
296
|
+
store: _SessionStore,
|
|
297
|
+
snapshot: SessionCredentials,
|
|
298
|
+
generation: int,
|
|
299
|
+
flight: _SyncFlight,
|
|
300
|
+
) -> None:
|
|
301
|
+
watch = threading.Timer(
|
|
302
|
+
max(0.0, flight.deadline - time.monotonic()),
|
|
303
|
+
self._expire_start,
|
|
304
|
+
args=(store, snapshot, generation, flight),
|
|
305
|
+
)
|
|
306
|
+
watch.daemon = False
|
|
307
|
+
with store._locked():
|
|
308
|
+
flight.start_uncertain = True
|
|
309
|
+
if flight.producer_done:
|
|
310
|
+
return
|
|
311
|
+
flight.start_watch = watch
|
|
312
|
+
try:
|
|
313
|
+
watch.start()
|
|
314
|
+
except RuntimeError:
|
|
315
|
+
# Even without thread-creation resources, the next store sweep enforces the deadline.
|
|
316
|
+
pass
|
|
317
|
+
|
|
318
|
+
def _expire_start(
|
|
319
|
+
self,
|
|
320
|
+
store: _SessionStore,
|
|
321
|
+
snapshot: SessionCredentials,
|
|
322
|
+
generation: int,
|
|
323
|
+
flight: _SyncFlight,
|
|
324
|
+
) -> None:
|
|
325
|
+
with store._locked():
|
|
326
|
+
if not flight.settled:
|
|
327
|
+
flight.result = _Failure(
|
|
328
|
+
"deadline_exceeded",
|
|
329
|
+
outcome_unknown=flight.request_state.outcome_unknown,
|
|
330
|
+
)
|
|
331
|
+
store._apply_refresh(snapshot, generation, None, flight.result)
|
|
332
|
+
flight.settled = True
|
|
333
|
+
store._condition.notify_all()
|
|
334
|
+
store._reclaim(generation)
|
|
335
|
+
|
|
336
|
+
def _produce(
|
|
337
|
+
self,
|
|
338
|
+
store: _SessionStore,
|
|
339
|
+
snapshot: SessionCredentials,
|
|
340
|
+
generation: int,
|
|
341
|
+
flight: _SyncFlight,
|
|
342
|
+
hook: _Observation | None = None,
|
|
343
|
+
) -> None:
|
|
344
|
+
credentials: SessionCredentials | None = None
|
|
345
|
+
failure: _Failure | None = _Failure("unavailable")
|
|
346
|
+
observation = _state.set(flight.request_state)
|
|
347
|
+
registration = _observer.set(hook) if hook is not None else None
|
|
348
|
+
try:
|
|
349
|
+
store._begin_refresh(snapshot, generation)
|
|
350
|
+
credentials = cast(
|
|
351
|
+
SessionCredentials,
|
|
352
|
+
self._attempt(
|
|
353
|
+
"auth.refresh",
|
|
354
|
+
_serialize({"refresh_token": snapshot.refresh_token}),
|
|
355
|
+
None,
|
|
356
|
+
flight.deadline,
|
|
357
|
+
credentials=True,
|
|
358
|
+
),
|
|
359
|
+
)
|
|
360
|
+
failure = None
|
|
361
|
+
except ClientError as error:
|
|
362
|
+
failure = _Failure.from_error(error)
|
|
363
|
+
except _HookError:
|
|
364
|
+
failure = _Failure("unavailable", retryable=True, hook_failed=True)
|
|
365
|
+
except BaseException:
|
|
366
|
+
failure = _Failure("unavailable")
|
|
367
|
+
finally:
|
|
368
|
+
_state.reset(observation)
|
|
369
|
+
self._publish(store, snapshot, generation, flight, credentials, failure)
|
|
370
|
+
if registration is not None:
|
|
371
|
+
_observer.reset(registration)
|
|
372
|
+
|
|
373
|
+
def _publish(
|
|
374
|
+
self,
|
|
375
|
+
store: _SessionStore,
|
|
376
|
+
snapshot: SessionCredentials,
|
|
377
|
+
generation: int,
|
|
378
|
+
flight: _SyncFlight,
|
|
379
|
+
credentials: SessionCredentials | None,
|
|
380
|
+
failure: _Failure | None,
|
|
381
|
+
) -> None:
|
|
382
|
+
with store._locked():
|
|
383
|
+
if not flight.settled:
|
|
384
|
+
if time.monotonic() >= flight.deadline:
|
|
385
|
+
failure = _Failure(
|
|
386
|
+
"deadline_exceeded",
|
|
387
|
+
failure.status if failure is not None else None,
|
|
388
|
+
outcome_unknown=flight.request_state.outcome_unknown,
|
|
389
|
+
hook_failed=failure.hook_failed
|
|
390
|
+
if failure is not None
|
|
391
|
+
else False,
|
|
392
|
+
)
|
|
393
|
+
credentials = None
|
|
394
|
+
try:
|
|
395
|
+
store._apply_refresh(snapshot, generation, credentials, failure)
|
|
396
|
+
except ClientError as error:
|
|
397
|
+
failure = _Failure.from_error(error)
|
|
398
|
+
flight.result = failure
|
|
399
|
+
flight.settled = True
|
|
400
|
+
flight.producer_done = True
|
|
401
|
+
store._condition.notify_all()
|
|
402
|
+
store._reclaim(generation)
|
|
403
|
+
if flight.start_watch is not None:
|
|
404
|
+
flight.start_watch.cancel()
|
|
405
|
+
|
|
406
|
+
def _attempt(
|
|
407
|
+
self,
|
|
408
|
+
operation: str,
|
|
409
|
+
body: bytes,
|
|
410
|
+
token: str | None,
|
|
411
|
+
deadline: float,
|
|
412
|
+
*,
|
|
413
|
+
credentials: bool = False,
|
|
414
|
+
) -> object:
|
|
415
|
+
refresh = operation == "auth.refresh"
|
|
416
|
+
state = _state.get() or _RequestState()
|
|
417
|
+
observation = _observer.get()
|
|
418
|
+
if observation is not None:
|
|
419
|
+
deadline = min(deadline, observation.deadline)
|
|
420
|
+
with _request_logs():
|
|
421
|
+
deadline = min(deadline, time.monotonic() + self._timeout)
|
|
422
|
+
client = self._http_client(deadline)
|
|
423
|
+
import httpcore
|
|
424
|
+
import httpx
|
|
425
|
+
|
|
426
|
+
from ._sync_network import _deadline, _remaining
|
|
427
|
+
|
|
428
|
+
context = _deadline.set(deadline)
|
|
429
|
+
status: int | None = None
|
|
430
|
+
reason: str | None = None
|
|
431
|
+
failure: ClientError | None = None
|
|
432
|
+
headers = {"Content-Type": "application/json"}
|
|
433
|
+
if token is not None:
|
|
434
|
+
headers["Authorization"] = "Bearer " + token
|
|
435
|
+
try:
|
|
436
|
+
try:
|
|
437
|
+
_remaining()
|
|
438
|
+
with client.stream(
|
|
439
|
+
"POST",
|
|
440
|
+
self._origin + "/" + operation,
|
|
441
|
+
content=body,
|
|
442
|
+
headers=headers,
|
|
443
|
+
extensions={
|
|
444
|
+
"trace": functools.partial(
|
|
445
|
+
observation.trace, state, refresh=credentials
|
|
446
|
+
)
|
|
447
|
+
if observation is not None
|
|
448
|
+
else state.trace
|
|
449
|
+
},
|
|
450
|
+
) as response:
|
|
451
|
+
status = response.status_code
|
|
452
|
+
if observation is not None:
|
|
453
|
+
observation.notify("headers", response)
|
|
454
|
+
observation.record_headers(
|
|
455
|
+
status, response.headers.values()
|
|
456
|
+
)
|
|
457
|
+
if 300 <= status < 400:
|
|
458
|
+
if observation is not None:
|
|
459
|
+
observation.notify("redirect", response)
|
|
460
|
+
if not refresh:
|
|
461
|
+
state.finish()
|
|
462
|
+
raise _local_error("internal", "operation_failed", status)
|
|
463
|
+
decoder = _Body(
|
|
464
|
+
response.headers.get("content-encoding", "identity"), status
|
|
465
|
+
)
|
|
466
|
+
for chunk in response.iter_raw():
|
|
467
|
+
_remaining()
|
|
468
|
+
decoder.feed(chunk)
|
|
469
|
+
_remaining()
|
|
470
|
+
data = decoder.finish()
|
|
471
|
+
if observation is not None:
|
|
472
|
+
observation.record_body(data)
|
|
473
|
+
if not refresh:
|
|
474
|
+
state.finish()
|
|
475
|
+
value = _response(data, status)
|
|
476
|
+
if refresh:
|
|
477
|
+
try:
|
|
478
|
+
decoded = _read_credentials(value)
|
|
479
|
+
except ClientError:
|
|
480
|
+
reason = "internal"
|
|
481
|
+
else:
|
|
482
|
+
_remaining()
|
|
483
|
+
state.finish()
|
|
484
|
+
return decoded if credentials else value
|
|
485
|
+
else:
|
|
486
|
+
_remaining()
|
|
487
|
+
return value
|
|
488
|
+
except (
|
|
489
|
+
TimeoutError,
|
|
490
|
+
httpcore.TimeoutException,
|
|
491
|
+
httpx.TimeoutException,
|
|
492
|
+
) as error:
|
|
493
|
+
if observation is not None:
|
|
494
|
+
observation.details.extend((type(error).__name__, str(error)))
|
|
495
|
+
reason = "deadline_exceeded"
|
|
496
|
+
except (
|
|
497
|
+
httpcore.NetworkError,
|
|
498
|
+
httpcore.ProtocolError,
|
|
499
|
+
httpx.HTTPError,
|
|
500
|
+
OSError,
|
|
501
|
+
RuntimeError,
|
|
502
|
+
ValueError,
|
|
503
|
+
) as error:
|
|
504
|
+
if observation is not None:
|
|
505
|
+
observation.details.extend((type(error).__name__, str(error)))
|
|
506
|
+
reason = "unavailable"
|
|
507
|
+
except ClientError as error:
|
|
508
|
+
if (
|
|
509
|
+
refresh
|
|
510
|
+
and isinstance(error, OperationError)
|
|
511
|
+
and error._valid_error_envelope
|
|
512
|
+
and error.status == 401
|
|
513
|
+
):
|
|
514
|
+
state.finish()
|
|
515
|
+
failure = error
|
|
516
|
+
finally:
|
|
517
|
+
_deadline.reset(context)
|
|
518
|
+
if reason is not None:
|
|
519
|
+
failure = ClientError(reason, status)
|
|
520
|
+
if failure is not None:
|
|
521
|
+
failure._outcome_unknown = state.outcome_unknown
|
|
522
|
+
raise failure
|
|
523
|
+
raise AssertionError
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
class _Authenticated:
|
|
527
|
+
def __init__(
|
|
528
|
+
self,
|
|
529
|
+
owner: HttpTransport,
|
|
530
|
+
*,
|
|
531
|
+
token: str | None = None,
|
|
532
|
+
store: _SessionStore | None = None,
|
|
533
|
+
) -> None:
|
|
534
|
+
self._owner = owner
|
|
535
|
+
self._token = token
|
|
536
|
+
self._store = store
|
|
537
|
+
|
|
538
|
+
def invoke(self, operation: str, payload: bytes | Mapping[str, object]) -> object:
|
|
539
|
+
return self._owner._invoke(operation, payload, self._token, self._store)
|
|
540
|
+
|
|
541
|
+
def invoke_public(
|
|
542
|
+
self, operation: str, payload: bytes | Mapping[str, object]
|
|
543
|
+
) -> object:
|
|
544
|
+
return self._owner._invoke(
|
|
545
|
+
operation, payload, self._token, self._store, public=True
|
|
546
|
+
)
|