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/_workerd.py
ADDED
|
@@ -0,0 +1,731 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import builtins
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Awaitable, Callable, Coroutine, Mapping, Sequence
|
|
11
|
+
from contextvars import ContextVar
|
|
12
|
+
from datetime import date, datetime
|
|
13
|
+
from typing import Any, TypeVar
|
|
14
|
+
from uuid import UUID
|
|
15
|
+
|
|
16
|
+
from .auth import AuthHooks, AuthUser, IdentityProvider
|
|
17
|
+
from .orm import DatabasePort, format_timestamp
|
|
18
|
+
from .postgres import CommitOutcomeUnknown
|
|
19
|
+
from .server import MAX_REQUEST_BYTES, OperationError, Session, User
|
|
20
|
+
|
|
21
|
+
T = TypeVar("T")
|
|
22
|
+
_MAX_SAFE = 9007199254740991
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _DatabaseFailure(Exception):
|
|
26
|
+
def __init__(self, sqlstate: str | None = None) -> None:
|
|
27
|
+
self.sqlstate = sqlstate
|
|
28
|
+
super().__init__("Database operation failed.")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _HostRequest:
|
|
32
|
+
def __init__(
|
|
33
|
+
self, bridge: Any, rid: int, wait_until: Callable[[Awaitable[None]], None]
|
|
34
|
+
) -> None:
|
|
35
|
+
self.bridge, self.rid = bridge, rid
|
|
36
|
+
self.wait_until = wait_until
|
|
37
|
+
self.closed = False
|
|
38
|
+
self.business_ready = True
|
|
39
|
+
self.auth_frame: bytes | None = None
|
|
40
|
+
self.output: dict[str, io.StringIO | None] = {}
|
|
41
|
+
|
|
42
|
+
def finish(self, cancel: bool = False) -> None:
|
|
43
|
+
if self.closed:
|
|
44
|
+
return
|
|
45
|
+
for level, stream in self.output.items():
|
|
46
|
+
if stream is not None:
|
|
47
|
+
_log(level, stream.getvalue().removesuffix("\n"))
|
|
48
|
+
self.output.clear()
|
|
49
|
+
self.closed = True
|
|
50
|
+
finish = self.bridge.finish(self.rid, cancel)
|
|
51
|
+
try:
|
|
52
|
+
self.wait_until(finish)
|
|
53
|
+
except Exception:
|
|
54
|
+
finish.close()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
_request: ContextVar[_HostRequest | None] = ContextVar(
|
|
58
|
+
"chickinfry_host_request", default=None
|
|
59
|
+
)
|
|
60
|
+
_active: ContextVar[frozenset[int]] = ContextVar(
|
|
61
|
+
"chickinfry_host_transactions", default=frozenset()
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
_LOG_LEVELS = frozenset(("debug", "info", "warn", "error"))
|
|
65
|
+
_LOG_LIMIT = 4 << 20
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _json_value(value: object, depth: int) -> bool:
|
|
69
|
+
if depth > 64:
|
|
70
|
+
return False
|
|
71
|
+
if value is None or type(value) in (str, int, float, bool):
|
|
72
|
+
return True
|
|
73
|
+
if type(value) is list:
|
|
74
|
+
return all(_json_value(item, depth + 1) for item in value)
|
|
75
|
+
if type(value) is dict:
|
|
76
|
+
return all(
|
|
77
|
+
type(key) is str and _json_value(item, depth + 1)
|
|
78
|
+
for key, item in value.items()
|
|
79
|
+
)
|
|
80
|
+
return False
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _log(level: str, message: str, fields: object = None) -> None:
|
|
84
|
+
state = _request.get()
|
|
85
|
+
if state is None or state.closed:
|
|
86
|
+
return
|
|
87
|
+
try:
|
|
88
|
+
if (
|
|
89
|
+
type(level) is not str
|
|
90
|
+
or level not in _LOG_LEVELS
|
|
91
|
+
or type(message) is not str
|
|
92
|
+
):
|
|
93
|
+
return
|
|
94
|
+
record: dict[str, object] = {
|
|
95
|
+
"rid": state.rid,
|
|
96
|
+
"level": level,
|
|
97
|
+
"message": message,
|
|
98
|
+
}
|
|
99
|
+
if fields is not None:
|
|
100
|
+
if type(fields) is not dict or not _json_value(fields, 1):
|
|
101
|
+
return
|
|
102
|
+
record["fields"] = fields
|
|
103
|
+
frame = json.dumps(
|
|
104
|
+
record, ensure_ascii=False, allow_nan=False, separators=(",", ":")
|
|
105
|
+
).encode()
|
|
106
|
+
if len(frame) <= _LOG_LIMIT:
|
|
107
|
+
state.bridge.log(state.rid, frame)
|
|
108
|
+
except Exception:
|
|
109
|
+
pass
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _bind_log() -> Callable[[str, str, object], None]:
|
|
113
|
+
owner = _request.get()
|
|
114
|
+
|
|
115
|
+
def write(level: str, message: str, fields: object) -> None:
|
|
116
|
+
if owner is _request.get():
|
|
117
|
+
_log(level, message, fields)
|
|
118
|
+
|
|
119
|
+
return write
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
_unscoped_output = False
|
|
123
|
+
_output_blocked: Callable[[], None] | None = None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _report_blocked_output() -> None:
|
|
127
|
+
global _unscoped_output
|
|
128
|
+
if _output_blocked is None:
|
|
129
|
+
_unscoped_output = True
|
|
130
|
+
return
|
|
131
|
+
try:
|
|
132
|
+
_output_blocked()
|
|
133
|
+
except Exception:
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class _LogStream(io.TextIOBase):
|
|
138
|
+
encoding = "utf-8"
|
|
139
|
+
|
|
140
|
+
def __init__(self, level: str) -> None:
|
|
141
|
+
self.level = level
|
|
142
|
+
|
|
143
|
+
def writable(self) -> bool:
|
|
144
|
+
return True
|
|
145
|
+
|
|
146
|
+
def write(self, text: str, /) -> int:
|
|
147
|
+
size = len(text)
|
|
148
|
+
state = _request.get()
|
|
149
|
+
if state is None or state.closed:
|
|
150
|
+
_report_blocked_output()
|
|
151
|
+
return size
|
|
152
|
+
if self.level not in state.output:
|
|
153
|
+
state.output[self.level] = io.StringIO()
|
|
154
|
+
stream = state.output[self.level]
|
|
155
|
+
if stream is not None:
|
|
156
|
+
if stream.tell() + size <= _LOG_LIMIT:
|
|
157
|
+
stream.write(text)
|
|
158
|
+
else:
|
|
159
|
+
state.output[self.level] = None
|
|
160
|
+
return size
|
|
161
|
+
|
|
162
|
+
def flush(self) -> None:
|
|
163
|
+
# Buffer until completion so secrets spanning writes and line breaks are redacted.
|
|
164
|
+
pass
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class _RequestLogHandler(logging.Handler):
|
|
168
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
169
|
+
state = _request.get()
|
|
170
|
+
if state is None or state.closed:
|
|
171
|
+
_report_blocked_output()
|
|
172
|
+
return
|
|
173
|
+
level = (
|
|
174
|
+
"error"
|
|
175
|
+
if record.levelno >= logging.ERROR
|
|
176
|
+
else "warn"
|
|
177
|
+
if record.levelno >= logging.WARNING
|
|
178
|
+
else "info"
|
|
179
|
+
if record.levelno >= logging.INFO
|
|
180
|
+
else "debug"
|
|
181
|
+
)
|
|
182
|
+
try:
|
|
183
|
+
_log(level, self.format(record))
|
|
184
|
+
except Exception:
|
|
185
|
+
pass
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _install_standard_logging() -> None:
|
|
189
|
+
# Native writes can bypass these descriptors and are blocked by the collector.
|
|
190
|
+
sink = os.open(os.devnull, os.O_WRONLY)
|
|
191
|
+
try:
|
|
192
|
+
for fd in (1, 2):
|
|
193
|
+
os.dup2(sink, fd)
|
|
194
|
+
finally:
|
|
195
|
+
os.close(sink)
|
|
196
|
+
sys.stdout = _LogStream("info")
|
|
197
|
+
sys.stderr = _LogStream("error")
|
|
198
|
+
setattr(sys, "__stdout__", sys.stdout)
|
|
199
|
+
setattr(sys, "__stderr__", sys.stderr)
|
|
200
|
+
logging.getLogger().addHandler(_RequestLogHandler())
|
|
201
|
+
logging.getLogger().setLevel(logging.INFO)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
if sys.platform == "emscripten":
|
|
205
|
+
_install_standard_logging()
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _wait_until(work: Coroutine[None, None, None]) -> None:
|
|
209
|
+
state = _request.get()
|
|
210
|
+
if state is None or state.closed:
|
|
211
|
+
raise RuntimeError("An active request is required.")
|
|
212
|
+
background = _HostRequest(
|
|
213
|
+
state.bridge, state.bridge.background(state.rid), state.wait_until
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
async def run() -> None:
|
|
217
|
+
marker = _request.set(background)
|
|
218
|
+
try:
|
|
219
|
+
await work
|
|
220
|
+
finally:
|
|
221
|
+
background.finish()
|
|
222
|
+
_request.reset(marker)
|
|
223
|
+
|
|
224
|
+
scheduled = run()
|
|
225
|
+
try:
|
|
226
|
+
state.wait_until(scheduled)
|
|
227
|
+
except Exception:
|
|
228
|
+
scheduled.close()
|
|
229
|
+
background.finish(True)
|
|
230
|
+
raise
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _parameter(value: object) -> object:
|
|
234
|
+
if isinstance(value, datetime):
|
|
235
|
+
return format_timestamp(value)
|
|
236
|
+
if type(value) is date:
|
|
237
|
+
return value.isoformat()
|
|
238
|
+
if isinstance(value, UUID):
|
|
239
|
+
return str(value)
|
|
240
|
+
if value is None or type(value) in (str, bool):
|
|
241
|
+
return value
|
|
242
|
+
if (
|
|
243
|
+
(type(value) is int or type(value) is float)
|
|
244
|
+
and abs(value) <= _MAX_SAFE
|
|
245
|
+
and math.isfinite(value)
|
|
246
|
+
):
|
|
247
|
+
return value
|
|
248
|
+
raise ValueError("A safe database parameter is required.")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
|
252
|
+
output: dict[str, object] = {}
|
|
253
|
+
for key, value in pairs:
|
|
254
|
+
if key in output:
|
|
255
|
+
raise ValueError("Invalid database response.")
|
|
256
|
+
output[key] = value
|
|
257
|
+
return output
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _fields(value: object, keys: set[str]) -> dict[str, Any]:
|
|
261
|
+
if not isinstance(value, dict) or set(value) != keys:
|
|
262
|
+
raise ValueError("Invalid host frame.")
|
|
263
|
+
return value
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _text(value: object) -> str:
|
|
267
|
+
if not isinstance(value, str) or not value:
|
|
268
|
+
raise ValueError("Invalid host frame.")
|
|
269
|
+
return value
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _trusted_session() -> Session | None:
|
|
273
|
+
state = _request.get()
|
|
274
|
+
data = state.auth_frame if state is not None and not state.closed else None
|
|
275
|
+
try:
|
|
276
|
+
if data is None or len(data) > MAX_REQUEST_BYTES:
|
|
277
|
+
raise ValueError
|
|
278
|
+
frame = _fields(
|
|
279
|
+
json.loads(data.decode("utf-8"), object_pairs_hook=_object), {"auth"}
|
|
280
|
+
)
|
|
281
|
+
auth = _fields(frame["auth"], {"version", "session"})
|
|
282
|
+
if type(auth["version"]) is not int or auth["version"] != 1:
|
|
283
|
+
raise ValueError
|
|
284
|
+
if auth["session"] is None:
|
|
285
|
+
return None
|
|
286
|
+
session = _fields(auth["session"], {"id", "user"})
|
|
287
|
+
user = _fields(session["user"], {"id", "email"})
|
|
288
|
+
return Session(
|
|
289
|
+
_text(session["id"]), User(_text(user["id"]), _text(user["email"]))
|
|
290
|
+
)
|
|
291
|
+
except (ValueError, RecursionError):
|
|
292
|
+
raise OperationError("operation_failed", 500) from None
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class _HostPort:
|
|
296
|
+
def __init__(self, _dsn: str | None = None) -> None:
|
|
297
|
+
state = _request.get()
|
|
298
|
+
if state is None or state.closed or not state.business_ready:
|
|
299
|
+
raise RuntimeError("An active database request is required.")
|
|
300
|
+
self._state = state
|
|
301
|
+
self._closed = False
|
|
302
|
+
self._lock = asyncio.Lock()
|
|
303
|
+
|
|
304
|
+
def _check(self) -> None:
|
|
305
|
+
if (
|
|
306
|
+
self._closed
|
|
307
|
+
or self._state.closed
|
|
308
|
+
or not self._state.business_ready
|
|
309
|
+
or _request.get() is not self._state
|
|
310
|
+
):
|
|
311
|
+
raise RuntimeError("The database request is no longer active.")
|
|
312
|
+
|
|
313
|
+
async def _call(self, op: str, **fields: object) -> dict[str, Any]:
|
|
314
|
+
self._check()
|
|
315
|
+
frame = json.dumps(
|
|
316
|
+
{"rid": self._state.rid, "op": op, **fields},
|
|
317
|
+
ensure_ascii=False,
|
|
318
|
+
allow_nan=False,
|
|
319
|
+
separators=(",", ":"),
|
|
320
|
+
).encode()
|
|
321
|
+
try:
|
|
322
|
+
data = await self._state.bridge.db(frame)
|
|
323
|
+
if len(data) > 4 << 20:
|
|
324
|
+
raise ValueError
|
|
325
|
+
result = json.loads(
|
|
326
|
+
data.decode("utf-8"),
|
|
327
|
+
object_pairs_hook=_object,
|
|
328
|
+
parse_constant=lambda _: (_ for _ in ()).throw(ValueError()),
|
|
329
|
+
)
|
|
330
|
+
self._check()
|
|
331
|
+
if not isinstance(result, dict):
|
|
332
|
+
raise ValueError
|
|
333
|
+
if "error" in result:
|
|
334
|
+
if set(result) != {"error"}:
|
|
335
|
+
raise ValueError
|
|
336
|
+
error = result["error"]
|
|
337
|
+
if error == "commit_unknown":
|
|
338
|
+
self._closed = True
|
|
339
|
+
raise CommitOutcomeUnknown()
|
|
340
|
+
if isinstance(error, str) and re.fullmatch(r"[A-Z0-9]{5}", error):
|
|
341
|
+
raise _DatabaseFailure(error)
|
|
342
|
+
raise _DatabaseFailure()
|
|
343
|
+
return result
|
|
344
|
+
except asyncio.CancelledError:
|
|
345
|
+
self._state.finish(True)
|
|
346
|
+
raise
|
|
347
|
+
except (CommitOutcomeUnknown, _DatabaseFailure):
|
|
348
|
+
raise
|
|
349
|
+
except Exception:
|
|
350
|
+
raise _DatabaseFailure() from None
|
|
351
|
+
|
|
352
|
+
async def _query(
|
|
353
|
+
self, op: str, sql: str, parameters: Sequence[object], **fields: object
|
|
354
|
+
) -> Sequence[Mapping[str, object]]:
|
|
355
|
+
result = await self._call(
|
|
356
|
+
op, sql=sql, params=[_parameter(value) for value in parameters], **fields
|
|
357
|
+
)
|
|
358
|
+
if (
|
|
359
|
+
set(result) != {"rows"}
|
|
360
|
+
or not isinstance(result["rows"], list)
|
|
361
|
+
or any(not isinstance(row, dict) for row in result["rows"])
|
|
362
|
+
):
|
|
363
|
+
raise _DatabaseFailure()
|
|
364
|
+
return result["rows"]
|
|
365
|
+
|
|
366
|
+
async def query(
|
|
367
|
+
self, sql: str, parameters: Sequence[object]
|
|
368
|
+
) -> Sequence[Mapping[str, object]]:
|
|
369
|
+
self._check()
|
|
370
|
+
if id(self) in _active.get():
|
|
371
|
+
raise RuntimeError(
|
|
372
|
+
"Root database reentry inside a transaction is not supported."
|
|
373
|
+
)
|
|
374
|
+
async with self._lock:
|
|
375
|
+
return await self._query("query", sql, parameters)
|
|
376
|
+
|
|
377
|
+
async def transaction(self, work: Callable[[DatabasePort], Awaitable[T]]) -> T:
|
|
378
|
+
self._check()
|
|
379
|
+
if id(self) in _active.get():
|
|
380
|
+
raise RuntimeError("Nested transactions are not supported.")
|
|
381
|
+
async with self._lock:
|
|
382
|
+
response = await self._call("begin")
|
|
383
|
+
lease = response.get("lease")
|
|
384
|
+
if (
|
|
385
|
+
set(response) != {"lease"}
|
|
386
|
+
or type(lease) is not int
|
|
387
|
+
or not 0 < lease <= _MAX_SAFE
|
|
388
|
+
):
|
|
389
|
+
raise _DatabaseFailure()
|
|
390
|
+
tx = _Transaction(self, lease)
|
|
391
|
+
marker = _active.set(_active.get() | {id(self)})
|
|
392
|
+
committing = False
|
|
393
|
+
try:
|
|
394
|
+
value = await work(tx)
|
|
395
|
+
tx.active = False
|
|
396
|
+
committing = True
|
|
397
|
+
if await self._call("commit", lease=lease) != {}:
|
|
398
|
+
raise _DatabaseFailure()
|
|
399
|
+
return value
|
|
400
|
+
except BaseException as error:
|
|
401
|
+
tx.active = False
|
|
402
|
+
if isinstance(error, asyncio.CancelledError):
|
|
403
|
+
self._state.finish(True)
|
|
404
|
+
raise
|
|
405
|
+
if not committing and not self._state.closed:
|
|
406
|
+
try:
|
|
407
|
+
if await self._call("rollback", lease=lease) != {}:
|
|
408
|
+
raise _DatabaseFailure()
|
|
409
|
+
except BaseException:
|
|
410
|
+
self._state.finish(True)
|
|
411
|
+
raise
|
|
412
|
+
finally:
|
|
413
|
+
tx.active = False
|
|
414
|
+
_active.reset(marker)
|
|
415
|
+
|
|
416
|
+
async def close(self) -> None:
|
|
417
|
+
self._closed = True
|
|
418
|
+
|
|
419
|
+
def terminate(self) -> None:
|
|
420
|
+
self._closed = True
|
|
421
|
+
self._state.finish(True)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
class _Transaction:
|
|
425
|
+
def __init__(self, root: _HostPort, lease: int) -> None:
|
|
426
|
+
self.root, self.lease = root, lease
|
|
427
|
+
self.active = True
|
|
428
|
+
self._lock = asyncio.Lock()
|
|
429
|
+
|
|
430
|
+
async def query(
|
|
431
|
+
self, sql: str, parameters: Sequence[object]
|
|
432
|
+
) -> Sequence[Mapping[str, object]]:
|
|
433
|
+
async with self._lock:
|
|
434
|
+
if not self.active:
|
|
435
|
+
raise RuntimeError("The transaction is no longer active.")
|
|
436
|
+
return await self.root._query("exec", sql, parameters, lease=self.lease)
|
|
437
|
+
|
|
438
|
+
async def transaction(self, work: Callable[[DatabasePort], Awaitable[T]]) -> T:
|
|
439
|
+
raise RuntimeError("Nested transactions are not supported.")
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
class Storage:
|
|
443
|
+
"""A declared file store for the current request."""
|
|
444
|
+
|
|
445
|
+
__slots__ = ("_name", "_owner")
|
|
446
|
+
|
|
447
|
+
def __init__(self, name: str) -> None:
|
|
448
|
+
self._name = name
|
|
449
|
+
self._owner = _request.get()
|
|
450
|
+
|
|
451
|
+
def _active_request(self) -> _HostRequest:
|
|
452
|
+
owner = self._owner
|
|
453
|
+
if owner is None or owner.closed or _request.get() is not owner:
|
|
454
|
+
raise OperationError("service_unavailable", 503)
|
|
455
|
+
return owner
|
|
456
|
+
|
|
457
|
+
async def get(self, key: str) -> bytes | None:
|
|
458
|
+
"""Read an object as bytes, returning None when the key is absent."""
|
|
459
|
+
owner = self._active_request()
|
|
460
|
+
result: bytes | None = await owner.bridge.storage(
|
|
461
|
+
owner.rid, "get", self._name, key
|
|
462
|
+
)
|
|
463
|
+
return result
|
|
464
|
+
|
|
465
|
+
async def put(self, key: str, bytes: builtins.bytes, content_type: str) -> None:
|
|
466
|
+
"""Write bytes with the supplied media type."""
|
|
467
|
+
owner = self._active_request()
|
|
468
|
+
if type(bytes) is not builtins.bytes or len(bytes) > 4 << 20:
|
|
469
|
+
raise OperationError("operation_failed", 500)
|
|
470
|
+
await owner.bridge.storage(
|
|
471
|
+
owner.rid, "put", self._name, key, bytes, content_type
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
class _JSBridge:
|
|
476
|
+
def __init__(self, host: Any, ffi: Any, js: Any) -> None:
|
|
477
|
+
self.host, self.ffi, self.js = host, ffi, js
|
|
478
|
+
|
|
479
|
+
async def db(self, frame: bytes) -> bytes:
|
|
480
|
+
# Copy before yielding; no Python buffer is retained across the Promise.
|
|
481
|
+
result = await self.host.db(self.binary(frame))
|
|
482
|
+
return bytes(result.to_py())
|
|
483
|
+
|
|
484
|
+
def binary(self, frame: bytes) -> Any:
|
|
485
|
+
return self.js.Uint8Array.new(self.ffi.to_js(memoryview(frame)))
|
|
486
|
+
|
|
487
|
+
async def storage(
|
|
488
|
+
self,
|
|
489
|
+
rid: int,
|
|
490
|
+
operation: str,
|
|
491
|
+
name: str,
|
|
492
|
+
key: str,
|
|
493
|
+
data: bytes | None = None,
|
|
494
|
+
content_type: str | None = None,
|
|
495
|
+
) -> bytes | None:
|
|
496
|
+
if type(key) is not str or (
|
|
497
|
+
operation == "put" and type(content_type) is not str
|
|
498
|
+
):
|
|
499
|
+
raise OperationError("operation_failed", 500)
|
|
500
|
+
try:
|
|
501
|
+
payload = None if data is None else self.binary(data)
|
|
502
|
+
result = await self.host.storage(
|
|
503
|
+
rid, operation, name, key, payload, content_type
|
|
504
|
+
)
|
|
505
|
+
error = getattr(result, "error", None)
|
|
506
|
+
if error == "service_unavailable":
|
|
507
|
+
raise OperationError("service_unavailable", 503)
|
|
508
|
+
if error is None:
|
|
509
|
+
if operation == "put" or result.value is self.ffi.jsnull:
|
|
510
|
+
return None
|
|
511
|
+
return bytes(result.value.to_py())
|
|
512
|
+
except OperationError:
|
|
513
|
+
raise
|
|
514
|
+
except Exception:
|
|
515
|
+
pass
|
|
516
|
+
raise OperationError("operation_failed", 500)
|
|
517
|
+
|
|
518
|
+
def finish(self, rid: int, cancel: bool) -> Coroutine[None, None, None]:
|
|
519
|
+
pending = self.host.finish(rid, cancel)
|
|
520
|
+
|
|
521
|
+
async def wait() -> None:
|
|
522
|
+
await pending
|
|
523
|
+
|
|
524
|
+
return wait()
|
|
525
|
+
|
|
526
|
+
def background(self, rid: int) -> int:
|
|
527
|
+
return int(self.host.background(rid))
|
|
528
|
+
|
|
529
|
+
def log(self, rid: int, frame: bytes) -> None:
|
|
530
|
+
self.host.log(rid, self.binary(frame))
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
class _BorrowedAuthPort:
|
|
534
|
+
def __init__(self, state: _HostRequest, query: Any) -> None:
|
|
535
|
+
self._owner = state
|
|
536
|
+
self._query = query
|
|
537
|
+
self.active = True
|
|
538
|
+
|
|
539
|
+
def _check(self) -> None:
|
|
540
|
+
if not self.active or self._owner.closed or _request.get() is not self._owner:
|
|
541
|
+
raise RuntimeError("The transaction is no longer active.")
|
|
542
|
+
|
|
543
|
+
async def query(
|
|
544
|
+
self, sql: str, parameters: Sequence[object]
|
|
545
|
+
) -> Sequence[Mapping[str, object]]:
|
|
546
|
+
self._check()
|
|
547
|
+
try:
|
|
548
|
+
frame = json.dumps(
|
|
549
|
+
{"sql": sql, "params": [_parameter(value) for value in parameters]},
|
|
550
|
+
allow_nan=False,
|
|
551
|
+
).encode()
|
|
552
|
+
result = await self._query(self._owner.bridge.binary(frame))
|
|
553
|
+
data = bytes(result.to_py())
|
|
554
|
+
if len(data) > MAX_REQUEST_BYTES:
|
|
555
|
+
raise ValueError
|
|
556
|
+
rows = _fields(json.loads(data, object_pairs_hook=_object), {"rows"})[
|
|
557
|
+
"rows"
|
|
558
|
+
]
|
|
559
|
+
if not isinstance(rows, list) or any(
|
|
560
|
+
not isinstance(row, dict) for row in rows
|
|
561
|
+
):
|
|
562
|
+
raise ValueError
|
|
563
|
+
except Exception:
|
|
564
|
+
raise _DatabaseFailure() from None
|
|
565
|
+
self._check()
|
|
566
|
+
return rows
|
|
567
|
+
|
|
568
|
+
async def transaction(self, work: Callable[[DatabasePort], Awaitable[T]]) -> T:
|
|
569
|
+
raise RuntimeError("Nested transactions are not supported.")
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
async def _authenticate(
|
|
573
|
+
request: Any,
|
|
574
|
+
config: str,
|
|
575
|
+
hooks: AuthHooks,
|
|
576
|
+
providers: Sequence[IdentityProvider],
|
|
577
|
+
) -> tuple[Any, Any]:
|
|
578
|
+
from importlib import import_module
|
|
579
|
+
|
|
580
|
+
state = _request.get()
|
|
581
|
+
if state is None or state.closed:
|
|
582
|
+
raise OperationError("operation_failed", 500)
|
|
583
|
+
by_id = {provider.id: provider for provider in providers}
|
|
584
|
+
pending: set[asyncio.Task[Any]] = set()
|
|
585
|
+
accepting_callbacks = True
|
|
586
|
+
|
|
587
|
+
async def call(metadata: str, query: Any = None) -> str | None:
|
|
588
|
+
if state.closed or not accepting_callbacks:
|
|
589
|
+
raise RuntimeError("The request is no longer active.")
|
|
590
|
+
task = asyncio.current_task()
|
|
591
|
+
if task is not None:
|
|
592
|
+
pending.add(task)
|
|
593
|
+
marker = _request.set(state)
|
|
594
|
+
borrowed = None
|
|
595
|
+
try:
|
|
596
|
+
message = json.loads(metadata, object_pairs_hook=_object)
|
|
597
|
+
if "provider" in message:
|
|
598
|
+
identity = await by_id[message["provider"]].verify(
|
|
599
|
+
message["credential"]
|
|
600
|
+
)
|
|
601
|
+
return json.dumps(
|
|
602
|
+
{
|
|
603
|
+
"subject": identity.subject,
|
|
604
|
+
"verifiedEmail": identity.verified_email,
|
|
605
|
+
}
|
|
606
|
+
)
|
|
607
|
+
message = _fields(message, {"version", "hook", "user"})
|
|
608
|
+
user = _fields(message["user"], {"id", "email", "createdAt"})
|
|
609
|
+
actor = AuthUser(
|
|
610
|
+
_text(user["id"]), _text(user["email"]), _text(user["createdAt"])
|
|
611
|
+
)
|
|
612
|
+
if (
|
|
613
|
+
message["version"] == 1
|
|
614
|
+
and message["hook"] == "userCreating"
|
|
615
|
+
and hooks.user_creating
|
|
616
|
+
and query is not None
|
|
617
|
+
):
|
|
618
|
+
borrowed = _BorrowedAuthPort(state, query)
|
|
619
|
+
await hooks.user_creating(borrowed, actor)
|
|
620
|
+
elif (
|
|
621
|
+
message["version"] == 1
|
|
622
|
+
and message["hook"] == "userCreated"
|
|
623
|
+
and hooks.user_created
|
|
624
|
+
):
|
|
625
|
+
await hooks.user_created(actor)
|
|
626
|
+
else:
|
|
627
|
+
raise ValueError("Invalid host hook.")
|
|
628
|
+
return None
|
|
629
|
+
finally:
|
|
630
|
+
if borrowed is not None:
|
|
631
|
+
borrowed.active = False
|
|
632
|
+
_request.reset(marker)
|
|
633
|
+
if task is not None:
|
|
634
|
+
pending.discard(task)
|
|
635
|
+
|
|
636
|
+
bridge = state.bridge
|
|
637
|
+
callback = bridge.ffi.create_proxy(call)
|
|
638
|
+
workers = import_module("workers")
|
|
639
|
+
try:
|
|
640
|
+
result = await bridge.host.authenticate(
|
|
641
|
+
state.rid,
|
|
642
|
+
request.js_object,
|
|
643
|
+
config,
|
|
644
|
+
json.dumps(list(by_id)),
|
|
645
|
+
hooks.user_creating is not None,
|
|
646
|
+
hooks.user_created is not None,
|
|
647
|
+
callback,
|
|
648
|
+
)
|
|
649
|
+
response = getattr(result, "response", None)
|
|
650
|
+
if response is not None:
|
|
651
|
+
return workers.Response(response), request
|
|
652
|
+
frame = getattr(result, "frame", None)
|
|
653
|
+
state.auth_frame = bytes(frame.to_py()) if frame is not None else None
|
|
654
|
+
_trusted_session()
|
|
655
|
+
state.business_ready = True
|
|
656
|
+
return None, workers.Request(result.request)
|
|
657
|
+
except asyncio.CancelledError:
|
|
658
|
+
bridge.host.cancelAuth(state.rid)
|
|
659
|
+
raise
|
|
660
|
+
except Exception:
|
|
661
|
+
return workers.Response(
|
|
662
|
+
'{"error":"operation_failed"}',
|
|
663
|
+
status=500,
|
|
664
|
+
headers={
|
|
665
|
+
"content-type": "application/json",
|
|
666
|
+
"cache-control": "no-store",
|
|
667
|
+
},
|
|
668
|
+
), request
|
|
669
|
+
finally:
|
|
670
|
+
accepting_callbacks = False
|
|
671
|
+
active = tuple(pending)
|
|
672
|
+
remaining = len(active)
|
|
673
|
+
if remaining == 0:
|
|
674
|
+
callback.destroy()
|
|
675
|
+
|
|
676
|
+
def retire(_: asyncio.Task[Any]) -> None:
|
|
677
|
+
nonlocal remaining
|
|
678
|
+
remaining -= 1
|
|
679
|
+
if remaining == 0:
|
|
680
|
+
callback.destroy()
|
|
681
|
+
|
|
682
|
+
for task in active:
|
|
683
|
+
task.add_done_callback(retire)
|
|
684
|
+
task.cancel()
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
async def _fetch(
|
|
688
|
+
fetch: Callable[..., Awaitable[object]],
|
|
689
|
+
worker: Any,
|
|
690
|
+
request: Any,
|
|
691
|
+
secret_names: tuple[str, ...] = (),
|
|
692
|
+
vault: bool = False,
|
|
693
|
+
auth: bool = False,
|
|
694
|
+
storage_names: tuple[str, ...] = (),
|
|
695
|
+
) -> object:
|
|
696
|
+
global _output_blocked, _unscoped_output
|
|
697
|
+
from importlib import import_module
|
|
698
|
+
|
|
699
|
+
workers = import_module("workers")
|
|
700
|
+
ffi = import_module("pyodide.ffi")
|
|
701
|
+
js = import_module("js")
|
|
702
|
+
host = workers.import_from_javascript("_chik/host.js")
|
|
703
|
+
pyodide = import_module("pyodide")
|
|
704
|
+
host.verify(sys.version.split()[0], pyodide.__version__)
|
|
705
|
+
host.prepare(
|
|
706
|
+
worker.env, ffi.to_js(list(secret_names)), vault, ffi.to_js(list(storage_names))
|
|
707
|
+
)
|
|
708
|
+
if _output_blocked is None:
|
|
709
|
+
_output_blocked = host.outputBlocked
|
|
710
|
+
if _unscoped_output:
|
|
711
|
+
_unscoped_output = False
|
|
712
|
+
_report_blocked_output()
|
|
713
|
+
state = _HostRequest(
|
|
714
|
+
_JSBridge(host, ffi, js),
|
|
715
|
+
host.start(request.js_object.signal, request.js_object.headers, True)
|
|
716
|
+
if auth
|
|
717
|
+
else host.start(request.js_object.signal, request.js_object.headers),
|
|
718
|
+
worker.ctx.waitUntil,
|
|
719
|
+
)
|
|
720
|
+
state.business_ready = not auth
|
|
721
|
+
marker = _request.set(state)
|
|
722
|
+
try:
|
|
723
|
+
return await fetch(worker, request)
|
|
724
|
+
except BaseException:
|
|
725
|
+
state.finish(True)
|
|
726
|
+
raise
|
|
727
|
+
finally:
|
|
728
|
+
try:
|
|
729
|
+
state.finish()
|
|
730
|
+
finally:
|
|
731
|
+
_request.reset(marker)
|