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/errors.py ADDED
@@ -0,0 +1,101 @@
1
+ import re
2
+
3
+ from ._error_details import FieldError as FieldError
4
+ from ._error_details import _fields, _message
5
+
6
+ _MESSAGES = {
7
+ "invalid_argument": "The request data is invalid; provide JSON-compatible values or valid UTF-8 JSON bytes.",
8
+ "failed_precondition": "The session cannot be used by this client; use valid credentials in a separate session store for the selected transport and event loop.",
9
+ "resource_exhausted": "The request exceeds the 4 MiB limit; reduce the request size before making another call.",
10
+ "deadline_exceeded": "The request exceeded its time limit; check the server's state before making another call.",
11
+ "canceled": "The request was canceled; check the server's state before making another call.",
12
+ "unavailable": "The request could not complete because of a network failure; check your connection and the server's state before making another call.",
13
+ "data_loss": "Stored session data could not be read; sign out to clear it, then sign in again.",
14
+ "unimplemented": "This client does not support Python Workers yet (support is planned); make calls from a regular Python process for now.",
15
+ "internal": "The server response is invalid; check that the server and generated client use the same API contract.",
16
+ "permission_denied": "The session is not authorized for this channel; check the channel permission before subscribing again.",
17
+ "unknown": "The client failed for an unknown reason; check the client's configuration and the server's state before making another call.",
18
+ "unauthenticated": "The request has no eligible session; use an active session for this operation.",
19
+ "operation_failed": "The operation failed; check the error code and HTTP status, then resolve the reported problem before making another call.",
20
+ }
21
+ _CODES = frozenset(_MESSAGES) - {"operation_failed"}
22
+
23
+ # Internal diagnostic keys are not accepted as public error codes.
24
+ _MESSAGES.update(
25
+ {
26
+ "device_storage_unavailable": "Could not use device storage for the session. Check that the storage location is writable, or set persist to another directory or turn it off.",
27
+ "device_storage_corrupt": "Stored session data could not be read. Sign out to clear it, then sign in again.",
28
+ "device_storage_full": "Device storage for sign-in is full. Finish or cancel pending sign-ups, then try again.",
29
+ "device_storage_version_unsupported": "Stored session data was written by a newer SDK. Update the SDK, or sign out and sign in again.",
30
+ "invalid_origin": "The server address is invalid; use an HTTPS origin or an explicit IP loopback HTTP origin without a path, query, or fragment.",
31
+ "invalid_operation": "The operation name is invalid; use the operation name defined by your generated client.",
32
+ "invalid_input": "The request data is invalid; provide JSON-compatible values or valid UTF-8 JSON bytes.",
33
+ "invalid_token": "The authentication token is invalid; sign in again and use the newly issued credentials.",
34
+ "invalid_session": "The session cannot be used by this client; use valid credentials in a separate session store for the selected transport and event loop.",
35
+ "origin_mismatch": "The session belongs to a different server origin; use a session store created for the same origin as this client.",
36
+ "invalid_timeout": "The timeout is invalid; set it to a positive finite number of seconds.",
37
+ "invalid_response": "The server response is invalid; check that the server and generated client use the same API contract.",
38
+ "request_too_large": "The request exceeds the 4 MiB limit; reduce the request size before making another call.",
39
+ "response_too_large": "The response exceeds the 1 MiB limit; request less data or reduce the server's response size.",
40
+ "timeout": "The request exceeded its time limit; check the server's state before making another call.",
41
+ "network_error": "The request could not complete because of a network failure; check your connection and the server's state before making another call.",
42
+ "unsupported_environment": "This client does not support Python Workers yet (support is planned); make calls from a regular Python process for now.",
43
+ "wrong_event_loop": "The async client belongs to a different event loop; create and use the client on the same event loop.",
44
+ "transport_closed": "The client is closed; create a new client before making another call.",
45
+ "operation_failed": "The operation failed; check the error code and HTTP status, then resolve the reported problem before making another call.",
46
+ }
47
+ )
48
+
49
+ _STORAGE_REASONS = {
50
+ "failed_precondition": "device_storage_unavailable",
51
+ "resource_exhausted": "device_storage_full",
52
+ "data_loss": "device_storage_corrupt",
53
+ "unimplemented": "device_storage_version_unsupported",
54
+ }
55
+
56
+
57
+ class ClientError(Exception):
58
+ """A local failure with a common code and optional received HTTP status."""
59
+
60
+ def __init__(self, code: str, status: int | None = None) -> None:
61
+ self.code = code if code in _CODES else "unknown"
62
+ self._reason = self.code
63
+ self.status = status
64
+ self._outcome_unknown = False
65
+ self._storage_failure = False
66
+ super().__init__(_MESSAGES[self.code])
67
+
68
+
69
+ class OperationError(ClientError):
70
+ """A server operation failure retaining its wire code and HTTP status."""
71
+
72
+ def __init__(
73
+ self,
74
+ code: str,
75
+ status: int,
76
+ message: str | None = None,
77
+ fields: tuple[FieldError, ...] = (),
78
+ ) -> None:
79
+ self.code = code if re.fullmatch(r"[a-z_]+", code) else "operation_failed"
80
+ self._reason = "operation_failed"
81
+ self.status = status
82
+ self.response_message = _message(message)
83
+ self.fields = _fields(fields) if self.code == "invalid_input" else ()
84
+ self._outcome_unknown = False
85
+ self._storage_failure = False
86
+ self._valid_error_envelope = True
87
+ Exception.__init__(self, _MESSAGES["operation_failed"])
88
+
89
+
90
+ def _local_error(code: str, reason: str, status: int | None = None) -> ClientError:
91
+ error = ClientError(code, status)
92
+ error._reason = reason if reason in _MESSAGES else error.code
93
+ Exception.__init__(error, _MESSAGES[error._reason])
94
+ return error
95
+
96
+
97
+ def _storage_error(code: str) -> ClientError:
98
+ # Storage fallback must not consume a session failure with the same public code.
99
+ error = _local_error(code, _STORAGE_REASONS.get(code, code))
100
+ error._storage_failure = True
101
+ return error
chickinfry/http.py ADDED
@@ -0,0 +1,427 @@
1
+ import asyncio
2
+ import functools
3
+ from collections.abc import Mapping
4
+ from http.cookiejar import CookieJar
5
+ from typing import TYPE_CHECKING, Protocol, Self, cast
6
+
7
+ from ._conformance import _HookError, _observer
8
+ from ._device import _device_store, _DeviceStore, _persist_settings
9
+ from ._http_common import (
10
+ _HEADERS,
11
+ _Body,
12
+ _check_environment,
13
+ _NoCookies,
14
+ _operation,
15
+ _response,
16
+ _serialize,
17
+ _timeout,
18
+ )
19
+ from ._origin import canonical_origin
20
+ from ._request_logs import _request_logs
21
+ from ._request_state import _RequestState
22
+ from .errors import ClientError, OperationError, _local_error
23
+ from .session import (
24
+ SessionCredentials,
25
+ _Failure,
26
+ _finish_auth,
27
+ _read_credentials,
28
+ _refresh_candidate,
29
+ _SessionStore,
30
+ _valid_token,
31
+ )
32
+
33
+ if TYPE_CHECKING:
34
+ import httpx
35
+
36
+
37
+ def _check_deadline(deadline: float) -> None:
38
+ if asyncio.get_running_loop().time() >= deadline:
39
+ raise ClientError("deadline_exceeded")
40
+
41
+
42
+ class AsyncTransport(Protocol):
43
+ """The shared async operation contract consumed by generated clients."""
44
+
45
+ async def invoke(
46
+ self, operation: str, payload: bytes | Mapping[str, object]
47
+ ) -> object:
48
+ """Invoke one operation and return its parsed JSON value."""
49
+ ...
50
+
51
+
52
+ class AsyncHttpTransport:
53
+ """An anonymous origin-bound transport owning the lifetime of its HTTP pool."""
54
+
55
+ def __init__(
56
+ self,
57
+ origin: str,
58
+ *,
59
+ timeout: float = 30.0,
60
+ persist: bool | Mapping[str, object] = True,
61
+ ) -> None:
62
+ _check_environment()
63
+ self._origin = canonical_origin(origin)
64
+ self._timeout = _timeout(timeout)
65
+ self._persist = _persist_settings(persist)
66
+ self._loop: asyncio.AbstractEventLoop | None = None
67
+ self._client: httpx.AsyncClient | None = None
68
+ self._closed = False
69
+
70
+ def _check_loop(self) -> None:
71
+ _check_environment()
72
+ try:
73
+ loop = asyncio.get_running_loop()
74
+ except RuntimeError:
75
+ loop = None
76
+ if loop is None or (self._loop is not None and self._loop is not loop):
77
+ raise _local_error("failed_precondition", "wrong_event_loop")
78
+ self._loop = loop
79
+ if self._closed:
80
+ raise _local_error("failed_precondition", "transport_closed")
81
+
82
+ def _http_client(self) -> "httpx.AsyncClient":
83
+ self._check_loop()
84
+ if self._client is None:
85
+ import httpx
86
+
87
+ self._client = httpx.AsyncClient(
88
+ transport=httpx.AsyncHTTPTransport(
89
+ retries=0, verify=True, trust_env=False
90
+ ),
91
+ follow_redirects=False,
92
+ trust_env=False,
93
+ verify=True,
94
+ timeout=self._timeout,
95
+ cookies=CookieJar(policy=_NoCookies()),
96
+ headers=_HEADERS,
97
+ )
98
+ return self._client
99
+
100
+ async def __aenter__(self) -> Self:
101
+ self._http_client()
102
+ return self
103
+
104
+ async def __aexit__(self, *args: object) -> None:
105
+ await self.aclose()
106
+
107
+ async def aclose(self) -> None:
108
+ if self._closed:
109
+ return
110
+ self._check_loop()
111
+ self._closed = True
112
+ if self._client is not None:
113
+ await self._client.aclose()
114
+
115
+ def _device_store(
116
+ self, *, app: str, project: str, environment: str
117
+ ) -> _DeviceStore:
118
+ return _device_store(
119
+ self._origin,
120
+ app=app,
121
+ project=project,
122
+ environment=environment,
123
+ persist=self._persist,
124
+ )
125
+
126
+ def with_bearer(self, token: str) -> AsyncTransport:
127
+ if not _valid_token(token):
128
+ raise _local_error("invalid_argument", "invalid_token")
129
+ return _Authenticated(self, token=token)
130
+
131
+ def with_session(self, store: _SessionStore) -> AsyncTransport:
132
+ if not isinstance(store, _SessionStore):
133
+ raise ClientError("failed_precondition")
134
+ store._attach("async", self._origin)
135
+ return _Authenticated(self, store=store)
136
+
137
+ async def invoke(
138
+ self, operation: str, payload: bytes | Mapping[str, object]
139
+ ) -> object:
140
+ return await self._invoke(operation, payload, None, None)
141
+
142
+ async def invoke_public(
143
+ self, operation: str, payload: bytes | Mapping[str, object]
144
+ ) -> object:
145
+ """Invoke an operation declared public by the generated SDK."""
146
+ return await self._invoke(operation, payload, None, None, public=True)
147
+
148
+ async def _invoke(
149
+ self,
150
+ operation: str,
151
+ payload: bytes | Mapping[str, object],
152
+ token: str | None,
153
+ store: _SessionStore | None,
154
+ *,
155
+ public: bool = False,
156
+ ) -> object:
157
+ observation = _observer.get()
158
+ if observation is not None:
159
+ observation.notify("entered")
160
+ await observation.aarrive("sdk-entered", {"entered": True})
161
+ self._check_loop()
162
+ deadline = asyncio.get_running_loop().time() + 3 * self._timeout
163
+ _operation(operation)
164
+ body = _serialize(payload)
165
+ _check_deadline(deadline)
166
+ snapshot: SessionCredentials | None = None
167
+ generation = 0
168
+ refresh_allowed = True
169
+ if store is not None:
170
+ with store._locked():
171
+ snapshot, generation = store._register(allow_empty=public)
172
+ refresh_allowed = store._blocked_generation != generation
173
+ token = snapshot.access_token if snapshot is not None else None
174
+ timed_out = False
175
+ try:
176
+ try:
177
+ async with asyncio.timeout_at(deadline):
178
+ try:
179
+ result = await self._attempt(
180
+ operation,
181
+ body,
182
+ None if operation == "auth.refresh" else token,
183
+ deadline=deadline,
184
+ )
185
+ except OperationError as failure:
186
+ if (
187
+ store is None
188
+ or snapshot is None
189
+ or not refresh_allowed
190
+ or not _refresh_candidate(operation, failure)
191
+ ):
192
+ raise
193
+ if observation is not None:
194
+ await observation.aarrive(
195
+ "both-originals-rejected", {"httpStatus": 401}
196
+ )
197
+ await self._refresh(store, snapshot, generation)
198
+ with store._locked():
199
+ latest = store._new_credentials(generation)
200
+ if latest is None:
201
+ raise failure
202
+ result = await self._attempt(
203
+ operation, body, latest.access_token, deadline=deadline
204
+ )
205
+ if store is not None:
206
+ _finish_auth(store, operation, result, snapshot, generation)
207
+ return result
208
+ except TimeoutError:
209
+ timed_out = True
210
+ finally:
211
+ if store is not None:
212
+ store._release(generation)
213
+ if timed_out:
214
+ raise ClientError("deadline_exceeded")
215
+ raise AssertionError
216
+
217
+ async def _refresh(
218
+ self,
219
+ store: _SessionStore,
220
+ snapshot: SessionCredentials,
221
+ generation: int,
222
+ ) -> None:
223
+ with store._locked():
224
+ if store._new_credentials(generation):
225
+ return
226
+ flight = store._flights.get(generation)
227
+ if flight is None:
228
+ if not store._current(snapshot, generation):
229
+ return
230
+ if store._blocked_generation == generation:
231
+ raise ClientError("unauthenticated")
232
+ elected = flight is None
233
+ if flight is None:
234
+ flight = asyncio.create_task(
235
+ self._rotate(
236
+ store,
237
+ snapshot,
238
+ generation,
239
+ asyncio.get_running_loop().time() + self._timeout,
240
+ )
241
+ )
242
+ with store._locked():
243
+ store._flights[generation] = flight
244
+ flight.add_done_callback(functools.partial(store._settled, generation))
245
+ observation = _observer.get()
246
+ if observation is not None:
247
+ observation.flight = flight
248
+ if not elected and observation.flight_ref is not None and not flight.done():
249
+ await observation.aarrive(
250
+ "refresh-joined", {"refreshRef": observation.flight_ref(flight)}
251
+ )
252
+ failure = await asyncio.shield(flight)
253
+ if failure is not None:
254
+ raise failure.error()
255
+
256
+ async def _rotate(
257
+ self,
258
+ store: _SessionStore,
259
+ snapshot: SessionCredentials,
260
+ generation: int,
261
+ deadline: float,
262
+ ) -> _Failure | None:
263
+ failure: _Failure | None = None
264
+ credentials: SessionCredentials | None = None
265
+ try:
266
+ store._begin_refresh(snapshot, generation)
267
+ value = await self._attempt(
268
+ "auth.refresh",
269
+ _serialize({"refresh_token": snapshot.refresh_token}),
270
+ None,
271
+ credentials=True,
272
+ deadline=deadline,
273
+ )
274
+ credentials = cast(SessionCredentials, value)
275
+ except ClientError as error:
276
+ failure = _Failure.from_error(error)
277
+ except _HookError:
278
+ failure = _Failure("unavailable", retryable=True, hook_failed=True)
279
+ with store._locked():
280
+ if asyncio.get_running_loop().time() >= deadline:
281
+ failure = _Failure(
282
+ "deadline_exceeded",
283
+ failure.status if failure is not None else None,
284
+ outcome_unknown=failure.outcome_unknown
285
+ if failure is not None
286
+ else False,
287
+ hook_failed=failure.hook_failed if failure is not None else False,
288
+ )
289
+ credentials = None
290
+ store._apply_refresh(snapshot, generation, credentials, failure)
291
+ # Python 3.14's shield logs the inner exception after cancellation, so share the failure.
292
+ return failure
293
+
294
+ async def _attempt(
295
+ self,
296
+ operation: str,
297
+ body: bytes,
298
+ token: str | None,
299
+ *,
300
+ credentials: bool = False,
301
+ deadline: float | None = None,
302
+ ) -> object:
303
+ now = asyncio.get_running_loop().time()
304
+ deadline = min(
305
+ deadline if deadline is not None else now + self._timeout,
306
+ now + self._timeout,
307
+ )
308
+ observation = _observer.get()
309
+ if observation is not None:
310
+ deadline = min(deadline, observation.deadline)
311
+ refresh = operation == "auth.refresh"
312
+ state = _RequestState()
313
+ with _request_logs():
314
+ import httpx
315
+
316
+ headers = {"Content-Type": "application/json"}
317
+ if token is not None:
318
+ headers["Authorization"] = "Bearer " + token
319
+ status: int | None = None
320
+ failure: ClientError | None = None
321
+ value: object = None
322
+ try:
323
+ async with asyncio.timeout_at(deadline):
324
+ _check_deadline(deadline)
325
+ client = self._http_client()
326
+ _check_deadline(deadline)
327
+ async with client.stream(
328
+ "POST",
329
+ self._origin + "/" + operation,
330
+ content=body,
331
+ headers=headers,
332
+ extensions={
333
+ "trace": functools.partial(
334
+ observation.atrace, state, refresh=credentials
335
+ )
336
+ if observation is not None
337
+ else state.atrace
338
+ },
339
+ ) as response:
340
+ status = response.status_code
341
+ if observation is not None:
342
+ observation.notify("headers", response)
343
+ observation.record_headers(
344
+ status, response.headers.values()
345
+ )
346
+ if 300 <= status < 400:
347
+ if observation is not None:
348
+ observation.notify("redirect", response)
349
+ if not refresh:
350
+ state.finish()
351
+ raise _local_error("internal", "operation_failed", status)
352
+ data = await _read_body(response)
353
+ if observation is not None:
354
+ observation.record_body(data)
355
+ if not refresh:
356
+ state.finish()
357
+ _check_deadline(deadline)
358
+ value = _response(data, status)
359
+ if refresh:
360
+ try:
361
+ decoded = _read_credentials(value)
362
+ except ClientError:
363
+ failure = ClientError("internal", status)
364
+ else:
365
+ if credentials:
366
+ value = decoded
367
+ _check_deadline(deadline)
368
+ _check_deadline(deadline)
369
+ if refresh and failure is None:
370
+ state.finish()
371
+ except (TimeoutError, httpx.TimeoutException) as error:
372
+ if observation is not None:
373
+ observation.details.extend((type(error).__name__, str(error)))
374
+ failure = ClientError("deadline_exceeded", status)
375
+ except (httpx.HTTPError, OSError, RuntimeError) as error:
376
+ if observation is not None:
377
+ observation.details.extend((type(error).__name__, str(error)))
378
+ failure = ClientError("unavailable", status)
379
+ except ClientError as error:
380
+ if (
381
+ refresh
382
+ and isinstance(error, OperationError)
383
+ and error._valid_error_envelope
384
+ and error.status == 401
385
+ ):
386
+ state.finish()
387
+ failure = error
388
+ if asyncio.get_running_loop().time() >= deadline:
389
+ failure = ClientError("deadline_exceeded", status)
390
+ if failure is not None:
391
+ failure._outcome_unknown = state.outcome_unknown
392
+ raise failure
393
+ return value
394
+
395
+
396
+ class _Authenticated:
397
+ def __init__(
398
+ self,
399
+ owner: AsyncHttpTransport,
400
+ *,
401
+ token: str | None = None,
402
+ store: _SessionStore | None = None,
403
+ ) -> None:
404
+ self._owner = owner
405
+ self._token = token
406
+ self._store = store
407
+
408
+ async def invoke(
409
+ self, operation: str, payload: bytes | Mapping[str, object]
410
+ ) -> object:
411
+ return await self._owner._invoke(operation, payload, self._token, self._store)
412
+
413
+ async def invoke_public(
414
+ self, operation: str, payload: bytes | Mapping[str, object]
415
+ ) -> object:
416
+ return await self._owner._invoke(
417
+ operation, payload, self._token, self._store, public=True
418
+ )
419
+
420
+
421
+ async def _read_body(response: "httpx.Response") -> bytes:
422
+ body = _Body(
423
+ response.headers.get("content-encoding", "identity"), response.status_code
424
+ )
425
+ async for chunk in response.aiter_raw():
426
+ body.feed(chunk)
427
+ return body.finish()