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/server.py ADDED
@@ -0,0 +1,540 @@
1
+ """Generated dispatch wires Operation codecs with public context factories.
2
+
3
+ Application serves size-limited HTTP requests, and create_worker_entrypoint
4
+ connects to the host-provided workers module without adding a host dependency
5
+ to the CPython installation.
6
+ """
7
+
8
+ import asyncio
9
+ import json
10
+ import re
11
+ import sys
12
+ from collections.abc import (
13
+ AsyncIterator,
14
+ Awaitable,
15
+ Callable,
16
+ Iterator,
17
+ Mapping,
18
+ Sequence,
19
+ )
20
+ from dataclasses import dataclass, field
21
+ from importlib import import_module
22
+ from types import MappingProxyType
23
+ from typing import TYPE_CHECKING, Generic, Protocol, TypeVar, cast, overload
24
+ from urllib.parse import urlsplit
25
+
26
+ from ._error_details import FieldError as FieldError
27
+ from ._error_details import _fields, _message, _string
28
+
29
+ if TYPE_CHECKING:
30
+ from .auth import AuthHooks, IdentityProvider
31
+
32
+ Input = TypeVar("Input")
33
+ Output = TypeVar("Output")
34
+ C = TypeVar("C")
35
+ S = TypeVar("S")
36
+ Options = TypeVar("Options")
37
+ _C = TypeVar("_C", contravariant=True)
38
+ MAX_REQUEST_BYTES = 4 * 1024 * 1024
39
+
40
+
41
+ class OperationError(Exception):
42
+ """An explicitly trusted business error; received SDK errors are not trusted automatically."""
43
+
44
+ def __init__(
45
+ self,
46
+ code: str,
47
+ status: int,
48
+ message: str | None = None,
49
+ fields: tuple[FieldError, ...] = (),
50
+ ) -> None:
51
+ self.code, self.status = code, status
52
+ self.message, self.fields = message, fields
53
+ super().__init__("Operation failed.")
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class User:
58
+ id: str
59
+ email: str
60
+
61
+
62
+ @dataclass(frozen=True, slots=True)
63
+ class Session:
64
+ id: str
65
+ user: User
66
+
67
+
68
+ @dataclass(frozen=True, slots=True)
69
+ class AuthContext(Generic[S]):
70
+ session: S
71
+
72
+
73
+ class Request(Protocol):
74
+ @property
75
+ def method(self) -> str: ...
76
+ @property
77
+ def url(self) -> str: ...
78
+ @property
79
+ def headers(self) -> Mapping[str, str]: ...
80
+ def chunks(self) -> AsyncIterator[bytes]: ...
81
+ async def cancel(self) -> None: ...
82
+
83
+
84
+ @dataclass(frozen=True, slots=True, repr=False)
85
+ class RequestInfo:
86
+ """Immutable request metadata, without a body reader or host references."""
87
+
88
+ method: str
89
+ path: str
90
+ headers: Mapping[str, str]
91
+
92
+ def __post_init__(self) -> None:
93
+ object.__setattr__(
94
+ self,
95
+ "headers",
96
+ MappingProxyType(
97
+ {
98
+ key.lower(): value
99
+ for key, value in self.headers.items()
100
+ if key.lower() != "proxy-authorization"
101
+ }
102
+ ),
103
+ )
104
+
105
+ @classmethod
106
+ def from_request(cls, request: Request, *, uses_auth: bool) -> "RequestInfo":
107
+ return cls(
108
+ request.method,
109
+ urlsplit(request.url).path or "/",
110
+ {
111
+ key: value
112
+ for key, value in request.headers.items()
113
+ if not uses_auth or key.lower() not in {"authorization", "cookie"}
114
+ },
115
+ )
116
+
117
+
118
+ @dataclass(frozen=True, slots=True)
119
+ class Response:
120
+ status: int
121
+ body: bytes
122
+ headers: Mapping[str, str]
123
+
124
+
125
+ class DispatchOperation(Protocol[_C]):
126
+ """Receives raw JSON so authorization wrappers can defer input decoding."""
127
+
128
+ @property
129
+ def input_fields(self) -> frozenset[str]: ...
130
+ def prepare(self, value: object) -> Callable[[_C], Awaitable[object]]: ...
131
+
132
+
133
+ @dataclass(frozen=True, slots=True)
134
+ class Operation(Generic[Input, Output, C]):
135
+ """Connects the generated input decoder, exact async method, and output encoder."""
136
+
137
+ decode: Callable[[Mapping[str, object]], Input]
138
+ invoke: Callable[[C, Input], Awaitable[Output]]
139
+ encode: Callable[[Output], object]
140
+ input_fields: frozenset[str] = frozenset()
141
+
142
+ def prepare(self, value: object) -> Callable[[C], Awaitable[object]]:
143
+ try:
144
+ decoded = self.decode(_input_record(value))
145
+ except OperationError as error:
146
+ if error.code == "request_too_large" and error.status == 413:
147
+ raise
148
+ raise OperationError("invalid_input", 400) from None
149
+ except Exception:
150
+ raise OperationError("invalid_input", 400) from None
151
+
152
+ async def run(context: C) -> object:
153
+ result = await self.invoke(context, decoded)
154
+ try:
155
+ return self.encode(result)
156
+ except Exception:
157
+ raise OperationError("operation_failed", 500) from None
158
+
159
+ return run
160
+
161
+
162
+ @dataclass(frozen=True, slots=True)
163
+ class RequestScope(Generic[C]):
164
+ """The factory exposes only the public context; close ends the request's DB connection."""
165
+
166
+ context: C
167
+ close: Callable[[], Awaitable[None]]
168
+
169
+
170
+ def _invalid_constant(value: str) -> object:
171
+ raise ValueError("Non-standard JSON number.")
172
+
173
+
174
+ def _input_record(value: object) -> Mapping[str, object]:
175
+ if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
176
+ raise OperationError("invalid_input", 400)
177
+ return cast(Mapping[str, object], value)
178
+
179
+
180
+ def _error_response(
181
+ error: Exception, headers: Mapping[str, str], declared: object
182
+ ) -> Response:
183
+ try:
184
+ if isinstance(error, OperationError):
185
+ code, status = _string(error.code), error.status
186
+ if (
187
+ code is not None
188
+ and re.fullmatch(r"[a-z_]{1,64}", code)
189
+ and type(status) is int
190
+ and 400 <= status <= 599
191
+ ):
192
+ body: dict[str, object] = {"error": code}
193
+ try:
194
+ message = _message(error.message)
195
+ except Exception:
196
+ message = None
197
+ if message is not None:
198
+ body["message"] = message
199
+ try:
200
+ fields = (
201
+ _fields(
202
+ error.fields,
203
+ declared
204
+ if isinstance(declared, frozenset)
205
+ else frozenset(),
206
+ )
207
+ if code == "invalid_input"
208
+ else ()
209
+ )
210
+ except Exception:
211
+ fields = ()
212
+ if fields:
213
+ body["fields"] = [
214
+ {"path": item.path, "code": item.code} for item in fields
215
+ ]
216
+ return Response(
217
+ status, json.dumps(body, separators=(",", ":")).encode(), headers
218
+ )
219
+ except Exception:
220
+ pass
221
+ return Response(500, b'{"error":"operation_failed"}', headers)
222
+
223
+
224
+ class Application(Generic[C]):
225
+ """Operation preparation controls validation before the request scope opens."""
226
+
227
+ def __init__(
228
+ self,
229
+ operations: Mapping[str, DispatchOperation[C]],
230
+ open_scope: Callable[[Request], Awaitable[RequestScope[C]]],
231
+ *,
232
+ origins: frozenset[str] = frozenset(),
233
+ no_store: bool = False,
234
+ ) -> None:
235
+ if any(
236
+ not re.fullmatch(r"[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*", key)
237
+ for key in operations
238
+ ):
239
+ raise ValueError("Invalid operation name.")
240
+ self.operations = dict(operations)
241
+ self.open_scope = open_scope
242
+ self.origins, self.no_store = origins, no_store
243
+
244
+ async def fetch(self, request: Request) -> Response:
245
+ headers = {"Content-Type": "application/json"}
246
+ if self.no_store:
247
+ headers["Cache-Control"] = "no-store"
248
+ scope: RequestScope[C] | None = None
249
+ input_fields: frozenset[str] = frozenset()
250
+ try:
251
+ origin = request.headers.get("origin")
252
+ if origin is not None:
253
+ if origin not in self.origins:
254
+ raise OperationError("origin_denied", 403)
255
+ headers.update(
256
+ {"Access-Control-Allow-Origin": origin, "Vary": "Origin"}
257
+ )
258
+ if request.method == "OPTIONS":
259
+ headers.update(
260
+ {
261
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
262
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
263
+ }
264
+ )
265
+ return Response(204, b"", headers)
266
+ url = urlsplit(request.url)
267
+ if (
268
+ request.method != "POST"
269
+ or url.query
270
+ or "?" in request.url
271
+ or url.fragment
272
+ ):
273
+ raise OperationError("not_found", 404)
274
+ operation = (
275
+ self.operations.get(url.path[1:]) if url.path.startswith("/") else None
276
+ )
277
+ if operation is None:
278
+ raise OperationError("not_found", 404)
279
+ if (
280
+ request.headers.get("content-type", "").split(";", 1)[0]
281
+ != "application/json"
282
+ ):
283
+ raise OperationError("unsupported_media_type", 415)
284
+ body = bytearray()
285
+ try:
286
+ async for chunk in request.chunks():
287
+ if len(body) + len(chunk) > MAX_REQUEST_BYTES:
288
+ raise OperationError("request_too_large", 413)
289
+ body.extend(chunk)
290
+ except BaseException:
291
+ try:
292
+ await request.cancel()
293
+ except Exception:
294
+ pass
295
+ raise
296
+ try:
297
+ value: object = json.loads(
298
+ body.decode("utf-8"), parse_constant=_invalid_constant
299
+ )
300
+ except (ValueError, UnicodeError, RecursionError):
301
+ raise OperationError("invalid_json", 400) from None
302
+ input_fields = operation.input_fields
303
+ prepared = operation.prepare(value)
304
+ scope = await self.open_scope(request)
305
+ output = await prepared(scope.context)
306
+ encoded = json.dumps(
307
+ output, ensure_ascii=False, allow_nan=False, separators=(",", ":")
308
+ ).encode("utf-8")
309
+ return Response(200, encoded, headers)
310
+ except Exception as error:
311
+ return _error_response(error, headers, input_fields)
312
+ finally:
313
+ if scope is not None:
314
+ try:
315
+ await scope.close()
316
+ except Exception:
317
+ pass
318
+
319
+
320
+ def bearer(headers: Mapping[str, str]) -> str | None:
321
+ value = headers.get("authorization")
322
+ if value is None:
323
+ return None
324
+ match = re.fullmatch(r"Bearer ([A-Za-z0-9_-]{43})", value, re.IGNORECASE)
325
+ if match is None:
326
+ raise OperationError("invalid_token", 401)
327
+ return match[1]
328
+
329
+
330
+ class _JSHeaders(Protocol):
331
+ def get(self, key: str) -> str | None: ...
332
+ def keys(self) -> Iterator[str]: ...
333
+
334
+
335
+ class _Bytes(Protocol):
336
+ def to_py(self) -> bytes | bytearray | memoryview: ...
337
+
338
+
339
+ class _ReadResult(Protocol):
340
+ done: bool
341
+ value: _Bytes
342
+
343
+
344
+ class _Reader(Protocol):
345
+ async def read(self) -> _ReadResult: ...
346
+ async def cancel(self) -> None: ...
347
+ def releaseLock(self) -> None: ...
348
+
349
+
350
+ class _Body(Protocol):
351
+ def getReader(self) -> _Reader: ...
352
+
353
+
354
+ class _JSRequest(Protocol):
355
+ method: str
356
+ url: str
357
+ headers: _JSHeaders
358
+ body: _Body | None
359
+
360
+
361
+ @dataclass
362
+ class _HostRequest:
363
+ source: _JSRequest
364
+ reader: _Reader | None = field(init=False, default=None)
365
+
366
+ @property
367
+ def method(self) -> str:
368
+ return self.source.method
369
+
370
+ @property
371
+ def url(self) -> str:
372
+ return self.source.url
373
+
374
+ @property
375
+ def headers(self) -> Mapping[str, str]:
376
+ return {
377
+ key.lower(): value
378
+ for key in self.source.headers.keys()
379
+ if key.lower() != "proxy-authorization"
380
+ if (value := self.source.headers.get(key)) is not None
381
+ }
382
+
383
+ async def chunks(self) -> AsyncIterator[bytes]:
384
+ if self.source.body is None:
385
+ return
386
+ reader = self.reader = self.source.body.getReader()
387
+ try:
388
+ while True:
389
+ result = await reader.read()
390
+ if result.done:
391
+ break
392
+ yield bytes(result.value.to_py())
393
+ finally:
394
+ if self.reader is reader:
395
+ self.reader = None
396
+ reader.releaseLock()
397
+
398
+ async def cancel(self) -> None:
399
+ if self.reader is not None:
400
+ reader, self.reader = self.reader, None
401
+ try:
402
+ await reader.cancel()
403
+ finally:
404
+ reader.releaseLock()
405
+
406
+
407
+ class _Worker(Protocol):
408
+ env: object
409
+ ctx: object
410
+
411
+
412
+ class _HostResponse(Protocol):
413
+ def __call__(
414
+ self, body: str | None, *, status: int, headers: Mapping[str, str]
415
+ ) -> object: ...
416
+
417
+
418
+ @dataclass(frozen=True, slots=True)
419
+ class _SetupFailure:
420
+ cancelled: bool
421
+
422
+
423
+ @overload
424
+ def create_worker_entrypoint(
425
+ factory: Callable[[object, object], Application[C]],
426
+ *,
427
+ _secret_names: tuple[str, ...] = (),
428
+ _vault: bool = False,
429
+ _storage_names: tuple[str, ...] = (),
430
+ ) -> type[object]: ...
431
+
432
+
433
+ @overload
434
+ def create_worker_entrypoint(
435
+ factory: Callable[[object, object, Options], Application[C]],
436
+ *,
437
+ setup: Callable[[], Awaitable[Options]],
438
+ _secret_names: tuple[str, ...] = (),
439
+ _vault: bool = False,
440
+ _storage_names: tuple[str, ...] = (),
441
+ _auth_config: str | None = None,
442
+ _auth_hooks: Callable[[Options], "tuple[AuthHooks, Sequence[IdentityProvider]]"]
443
+ | None = None,
444
+ ) -> type[object]: ...
445
+
446
+
447
+ def create_worker_entrypoint(
448
+ factory: Callable[[object, object], Application[C]]
449
+ | Callable[[object, object, Options], Application[C]],
450
+ *,
451
+ setup: Callable[[], Awaitable[Options]] | None = None,
452
+ _secret_names: tuple[str, ...] = (),
453
+ _vault: bool = False,
454
+ _storage_names: tuple[str, ...] = (),
455
+ _auth_config: str | None = None,
456
+ _auth_hooks: Callable[[Options], "tuple[AuthHooks, Sequence[IdentityProvider]]"]
457
+ | None = None,
458
+ ) -> type[object]:
459
+ """Generated create_application returns a Default class composed with the factory.
460
+
461
+ The factory receives the trusted environment and execution context per
462
+ request and opens no connection at import time. Optional setup runs once
463
+ per entrypoint instance, before its first application is created. Its result
464
+ or failure is retained, and cancelling a waiter does not cancel setup.
465
+ """
466
+ host = import_module("workers")
467
+ base = cast(type[object], host.WorkerEntrypoint)
468
+ response_factory = cast(_HostResponse, host.Response)
469
+
470
+ async def fetch(self: _Worker, request: _JSRequest) -> object:
471
+ environment = self.env
472
+ if sys.platform == "emscripten":
473
+ environment = getattr(self.env, "CHIK_LOCAL_BINDINGS", self.env)
474
+ if setup is None:
475
+ application = cast(Callable[[object, object], Application[C]], factory)(
476
+ environment, self.ctx
477
+ )
478
+ else:
479
+ task = cast(
480
+ asyncio.Task[Options | _SetupFailure] | None,
481
+ getattr(self, "_chickinfry_setup", None),
482
+ )
483
+ if task is None:
484
+
485
+ async def initialize() -> Options | _SetupFailure:
486
+ try:
487
+ return await setup()
488
+ except (Exception, asyncio.CancelledError) as error:
489
+ # Retained exceptions can acquire request frames when awaited.
490
+ return _SetupFailure(isinstance(error, asyncio.CancelledError))
491
+
492
+ task = asyncio.create_task(initialize())
493
+ setattr(self, "_chickinfry_setup", task)
494
+ options = await asyncio.shield(task)
495
+ if isinstance(options, _SetupFailure):
496
+ if options.cancelled:
497
+ raise asyncio.CancelledError from None
498
+ raise RuntimeError("Application setup failed.") from None
499
+ if (
500
+ sys.platform == "emscripten"
501
+ and _auth_config is not None
502
+ and _auth_hooks is not None
503
+ ):
504
+ from ._workerd import _authenticate
505
+
506
+ hooks, providers = _auth_hooks(options)
507
+ response, request = await _authenticate(
508
+ request, _auth_config, hooks, providers
509
+ )
510
+ if response is not None:
511
+ return response
512
+ application = cast(
513
+ Callable[[object, object, Options], Application[C]], factory
514
+ )(environment, self.ctx, options)
515
+ response = await application.fetch(_HostRequest(request))
516
+ return response_factory(
517
+ response.body.decode() if response.body else None,
518
+ status=response.status,
519
+ headers=response.headers,
520
+ )
521
+
522
+ if sys.platform == "emscripten":
523
+ from ._workerd import _fetch
524
+
525
+ original = fetch
526
+
527
+ async def workerd_fetch(self: _Worker, request: _JSRequest) -> object:
528
+ return await _fetch(
529
+ original,
530
+ self,
531
+ request,
532
+ _secret_names,
533
+ _vault,
534
+ auth=_auth_config is not None,
535
+ storage_names=_storage_names,
536
+ )
537
+
538
+ return type("Default", (base,), {"fetch": workerd_fetch})
539
+
540
+ return type("Default", (base,), {"fetch": fetch})