statewire 0.24.1__tar.gz → 0.24.2__tar.gz
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.
- {statewire-0.24.1 → statewire-0.24.2}/PKG-INFO +1 -1
- {statewire-0.24.1 → statewire-0.24.2}/pyproject.toml +1 -1
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/__init__.py +7 -1
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/client.py +73 -14
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/document.py +69 -17
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/documents.py +20 -8
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_document.py +12 -5
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_durable_admission.py +3 -3
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_ops.py +2 -5
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_state_proxy.py +5 -6
- statewire-0.24.2/tests/test_values.py +194 -0
- {statewire-0.24.1 → statewire-0.24.2}/.gitignore +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/README.md +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/examples/__init__.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/examples/demo_app.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/examples/local_origin.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/api.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/filter.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/langgraph.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/limits.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/metrics.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/ops.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/protocol.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/state.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/src/statewire/testing.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/client_helpers.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/statewire_helpers.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/storage_probe.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_attach_fence.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_attach_guardrail.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_attached_hook.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_authorize.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_client.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_client_binding.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_client_ws.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_context.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_date_registry.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_departure.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_eviction.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_filter.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_frames.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_gap_fill.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_idle.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_lanes.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_langgraph.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_lifespan.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_meta.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_observer.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_origin.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_protocol_negotiation.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_read_filters.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_route_auth.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_start_session.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_statewire_hostable.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_storage_bridge.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_stream.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_testing.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_writer_lease.py +0 -0
- {statewire-0.24.1 → statewire-0.24.2}/tests/test_ws.py +0 -0
|
@@ -12,7 +12,12 @@ from .api import (
|
|
|
12
12
|
from .filter import ANY, UNFILTERED, Filter
|
|
13
13
|
from .protocol import Subprotocol
|
|
14
14
|
from statepatch import Proxy as StateProxy, append, plain
|
|
15
|
-
from .document import
|
|
15
|
+
from .document import (
|
|
16
|
+
StatewireDocument,
|
|
17
|
+
StatewireValueError,
|
|
18
|
+
decode_document,
|
|
19
|
+
encode_document,
|
|
20
|
+
)
|
|
16
21
|
|
|
17
22
|
__all__ = [
|
|
18
23
|
"ANY",
|
|
@@ -21,6 +26,7 @@ __all__ = [
|
|
|
21
26
|
"HeldFrame",
|
|
22
27
|
"StatewireDocument",
|
|
23
28
|
"encode_document",
|
|
29
|
+
"StatewireValueError",
|
|
24
30
|
"decode_document",
|
|
25
31
|
"Statewire",
|
|
26
32
|
"StatewireAttach",
|
|
@@ -6,6 +6,7 @@ import asyncio
|
|
|
6
6
|
import contextlib
|
|
7
7
|
import copy
|
|
8
8
|
import json
|
|
9
|
+
import math
|
|
9
10
|
import inspect
|
|
10
11
|
import logging
|
|
11
12
|
import random
|
|
@@ -29,7 +30,7 @@ from .protocol import (
|
|
|
29
30
|
validate_selection,
|
|
30
31
|
)
|
|
31
32
|
from .documents import Document, apply_documents, resolve_key
|
|
32
|
-
from .document import encode_document, _decode_meta
|
|
33
|
+
from .document import encode_document, format_path, _decode_meta
|
|
33
34
|
from .ops import (
|
|
34
35
|
CLIENT_ID_HEADER,
|
|
35
36
|
LEASE_HEADER,
|
|
@@ -222,6 +223,59 @@ def _backoff(timing: Timing, attempt: int) -> float:
|
|
|
222
223
|
# ─── Wire values (meta-typed dates) ─────────────────────────
|
|
223
224
|
|
|
224
225
|
|
|
226
|
+
_MAX_DEPTH = 512
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _received(
|
|
230
|
+
value: Any, parent: Any = None, path: tuple[str | int, ...] = (), strip: bool = True
|
|
231
|
+
) -> Any:
|
|
232
|
+
"""What a client keeps of a value the host sent: unsafe keys stripped and
|
|
233
|
+
integers past the JS safe range as None, each with a warning, as the
|
|
234
|
+
TypeScript client does. The client checks this itself; the host doesn't."""
|
|
235
|
+
if isinstance(value, bool):
|
|
236
|
+
return value
|
|
237
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
238
|
+
# JSON has no such number (json.loads reads 1e400 as inf).
|
|
239
|
+
raise StatewireProtocolError(
|
|
240
|
+
f"protocol error: the number {value} at {format_path(path)} is not JSON"
|
|
241
|
+
)
|
|
242
|
+
if isinstance(value, int) or isinstance(value, float) and value.is_integer():
|
|
243
|
+
if abs(value) > 2**53 - 1:
|
|
244
|
+
logger.warning(
|
|
245
|
+
"statewire: replaced %s with null at %s", value, format_path(path)
|
|
246
|
+
)
|
|
247
|
+
return None
|
|
248
|
+
return value
|
|
249
|
+
if isinstance(value, (list, dict)) and len(path) >= _MAX_DEPTH:
|
|
250
|
+
raise StatewireProtocolError(
|
|
251
|
+
f"protocol error: value at {format_path(path)} is nested deeper than {_MAX_DEPTH}"
|
|
252
|
+
)
|
|
253
|
+
if isinstance(value, list):
|
|
254
|
+
return [_received(item, None, (*path, i), strip) for i, item in enumerate(value)]
|
|
255
|
+
if isinstance(value, dict):
|
|
256
|
+
out: dict[str, Any] = {}
|
|
257
|
+
for key, item in value.items():
|
|
258
|
+
if strip and (
|
|
259
|
+
key == "__proto__" or key == "prototype" and parent == "constructor"
|
|
260
|
+
):
|
|
261
|
+
logger.warning(
|
|
262
|
+
"statewire: stripped unsafe key %r at %s", key, format_path(path)
|
|
263
|
+
)
|
|
264
|
+
continue
|
|
265
|
+
out[key] = _received(item, key, (*path, key), strip)
|
|
266
|
+
return out
|
|
267
|
+
return value
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _no_constant(name: str) -> Any:
|
|
271
|
+
raise StatewireProtocolError(f"protocol error: {name} is not JSON")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _loads(raw: str | bytes) -> Any:
|
|
275
|
+
"""JSON as the wire allows it: no NaN or Infinity tokens."""
|
|
276
|
+
return json.loads(raw, parse_constant=_no_constant)
|
|
277
|
+
|
|
278
|
+
|
|
225
279
|
def _revive_value(value: Any, meta: Any) -> Any:
|
|
226
280
|
try:
|
|
227
281
|
return _decode_meta(value, meta)
|
|
@@ -230,23 +284,30 @@ def _revive_value(value: Any, meta: Any) -> Any:
|
|
|
230
284
|
|
|
231
285
|
|
|
232
286
|
def _revive_op(op: Any) -> Any:
|
|
233
|
-
if not isinstance(op, dict) or "
|
|
287
|
+
if not isinstance(op, dict) or "value" not in op:
|
|
234
288
|
return op
|
|
235
289
|
revived = {k: v for k, v in op.items() if k != "meta"}
|
|
236
|
-
|
|
290
|
+
# Dates first: a meta path may name a key the receive check strips.
|
|
291
|
+
if "meta" in op:
|
|
292
|
+
revived["value"] = _revive_value(revived["value"], op["meta"])
|
|
293
|
+
path = op.get("path")
|
|
294
|
+
last = path[-1] if isinstance(path, list) and path else None
|
|
295
|
+
revived["value"] = _received(revived["value"], last if isinstance(last, str) else None)
|
|
237
296
|
return revived
|
|
238
297
|
|
|
239
298
|
|
|
240
299
|
def _revive_response(response: dict[str, Any]) -> dict[str, Any]:
|
|
241
|
-
if "
|
|
300
|
+
if "payload" not in response:
|
|
242
301
|
return response
|
|
243
302
|
revived = {k: v for k, v in response.items() if k != "meta"}
|
|
244
|
-
|
|
303
|
+
if "meta" in response:
|
|
304
|
+
revived["payload"] = _revive_value(revived["payload"], response["meta"])
|
|
305
|
+
revived["payload"] = _received(revived["payload"])
|
|
245
306
|
return revived
|
|
246
307
|
|
|
247
308
|
|
|
248
|
-
def _encode_params(params: list[Any]) -> dict[str, Any]:
|
|
249
|
-
document = encode_document(params)
|
|
309
|
+
def _encode_params(params: list[Any], method: str | None = None) -> dict[str, Any]:
|
|
310
|
+
document = encode_document(params, "params" if method is None else f"{method} params")
|
|
250
311
|
encoded, meta = document["value"], document.get("meta")
|
|
251
312
|
return {"params": encoded, "meta": meta} if meta else {"params": encoded}
|
|
252
313
|
|
|
@@ -603,7 +664,7 @@ class StatewireHttp:
|
|
|
603
664
|
try:
|
|
604
665
|
async for chunk in response.aiter_text():
|
|
605
666
|
for data in parser.feed(chunk):
|
|
606
|
-
yield
|
|
667
|
+
yield _loads(data)
|
|
607
668
|
except httpx.HTTPError as exc:
|
|
608
669
|
raise TransportError(str(exc) or "network") from exc
|
|
609
670
|
|
|
@@ -748,7 +809,7 @@ class StatewireWebsocket:
|
|
|
748
809
|
raise
|
|
749
810
|
except Exception as exc:
|
|
750
811
|
raise TransportError(str(exc) or "network") from exc
|
|
751
|
-
envelope =
|
|
812
|
+
envelope = _loads(raw)
|
|
752
813
|
if envelope == {}:
|
|
753
814
|
continue # heartbeat, below the packet layer
|
|
754
815
|
yield envelope
|
|
@@ -1013,7 +1074,7 @@ class StatewireClient:
|
|
|
1013
1074
|
return future
|
|
1014
1075
|
name = protocol or self.protocol
|
|
1015
1076
|
self._check_protocol(name)
|
|
1016
|
-
command = {"protocol": name, "method": method, **_encode_params(list(params))}
|
|
1077
|
+
command = {"protocol": name, "method": method, **_encode_params(list(params), method)}
|
|
1017
1078
|
lane = self._lane(name)
|
|
1018
1079
|
seq = lane.next_seq
|
|
1019
1080
|
lane.next_seq = seq + 1
|
|
@@ -1259,7 +1320,7 @@ class StatewireClient:
|
|
|
1259
1320
|
if cmd.get("message") is not None:
|
|
1260
1321
|
failure["message"] = cmd["message"]
|
|
1261
1322
|
if "payload" in cmd:
|
|
1262
|
-
failure["payload"] = cmd["payload"]
|
|
1323
|
+
failure["payload"] = _revive_response(cmd)["payload"]
|
|
1263
1324
|
self._reject(entry, failure)
|
|
1264
1325
|
elif kind == "failed":
|
|
1265
1326
|
failure = {"fate": "failed", "cause": "server"}
|
|
@@ -1441,9 +1502,7 @@ class StatewireClient:
|
|
|
1441
1502
|
reason if reason in ("reconnect", "error", "unauthorized") else "error"
|
|
1442
1503
|
)
|
|
1443
1504
|
return "reattach"
|
|
1444
|
-
payload = fin.get("payload")
|
|
1445
|
-
if "meta" in fin:
|
|
1446
|
-
payload = _revive_value(payload, fin["meta"])
|
|
1505
|
+
payload = _revive_response(fin).get("payload")
|
|
1447
1506
|
self._finished = fin
|
|
1448
1507
|
self._settle_all("gone")
|
|
1449
1508
|
gone: dict[str, Any] = {"status": "gone", "reason": reason}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import json
|
|
3
4
|
import math
|
|
4
5
|
import re
|
|
5
6
|
from datetime import datetime, timezone
|
|
@@ -16,74 +17,125 @@ class StatewireDocument:
|
|
|
16
17
|
meta: NotRequired[list[StatewireDocument.MetaEntry]]
|
|
17
18
|
|
|
18
19
|
|
|
20
|
+
_IDENTIFIER = re.compile(r"[A-Za-z_$][\w$]*")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def format_path(path: tuple[str | int, ...] | list[str | int], root: str = "") -> str:
|
|
24
|
+
"""A path as code reads it: ``events[2].approvalRequired``, ``params[2]``."""
|
|
25
|
+
out = root
|
|
26
|
+
for key in path:
|
|
27
|
+
if isinstance(key, int):
|
|
28
|
+
out += f"[{key}]"
|
|
29
|
+
elif _IDENTIFIER.fullmatch(key):
|
|
30
|
+
out += key if out == "" else f".{key}"
|
|
31
|
+
else:
|
|
32
|
+
out += f"[{json.dumps(key)}]"
|
|
33
|
+
return out or "the root"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class StatewireValueError(ValueError, TypeError):
|
|
37
|
+
"""A value a writer gave statewire that the wire can't carry, raised where it's written."""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self, found: str, path: tuple[str | int, ...], rule: str, root: str = ""
|
|
41
|
+
) -> None:
|
|
42
|
+
super().__init__(
|
|
43
|
+
f"statewire: can't encode {found} at {format_path(path, root)}: {rule}"
|
|
44
|
+
)
|
|
45
|
+
self.path = list(path)
|
|
46
|
+
self.found = found
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
_PLAIN_RULE = (
|
|
50
|
+
"documents hold null, booleans, numbers, strings, dates, arrays and plain objects"
|
|
51
|
+
)
|
|
52
|
+
_INT_RULE = "integers must be within the safe integer range, so every client reads them exactly"
|
|
53
|
+
|
|
54
|
+
|
|
19
55
|
def _copy_value(
|
|
20
56
|
value: Any,
|
|
21
57
|
mode: Literal["encode", "native", "json"],
|
|
22
58
|
meta: list[StatewireDocument.MetaEntry],
|
|
23
59
|
path: tuple[str | int, ...] = (),
|
|
24
60
|
ancestors: set[int] | None = None,
|
|
61
|
+
root: str = "",
|
|
25
62
|
) -> Any:
|
|
63
|
+
# encode and native copy a writer's value (the shared rules in
|
|
64
|
+
# packages/statewire/core/tests/fixtures/values.json); json checks a
|
|
65
|
+
# document that arrived, which the wire contract (document.json) bounds.
|
|
66
|
+
def fail(found: str, rule: str, at: tuple[str | int, ...] = path) -> Any:
|
|
67
|
+
if mode == "json":
|
|
68
|
+
raise ValueError(
|
|
69
|
+
f"statewire: protocol error: invalid document: {found} at {format_path(at)}: {rule}"
|
|
70
|
+
)
|
|
71
|
+
raise StatewireValueError(found, at, rule, root)
|
|
72
|
+
|
|
26
73
|
if value is None or isinstance(value, (bool, str)):
|
|
27
74
|
return value
|
|
28
75
|
if isinstance(value, (int, float)):
|
|
29
76
|
if isinstance(value, float) and not math.isfinite(value):
|
|
30
|
-
|
|
77
|
+
if mode == "json":
|
|
78
|
+
fail(f"the number {value}", "numbers must be finite")
|
|
79
|
+
# As JSON.stringify writes them.
|
|
80
|
+
return None
|
|
31
81
|
if (isinstance(value, int) or mode != "native" and value.is_integer()) and abs(
|
|
32
82
|
value
|
|
33
83
|
) > 2**53 - 1:
|
|
34
|
-
|
|
84
|
+
fail(f"the number {value}", _INT_RULE)
|
|
35
85
|
return value
|
|
36
86
|
if mode != "json" and isinstance(value, datetime):
|
|
37
87
|
if value.tzinfo is None or value.utcoffset() is None:
|
|
38
|
-
|
|
88
|
+
fail("a naive datetime", "datetimes need a timezone")
|
|
39
89
|
if mode == "native":
|
|
40
90
|
meta.append({"path": list(path), "type": "date"})
|
|
41
91
|
return value
|
|
42
92
|
try:
|
|
43
93
|
utc = value.astimezone(timezone.utc)
|
|
44
94
|
except (OverflowError, ValueError):
|
|
45
|
-
|
|
46
|
-
f"
|
|
47
|
-
)
|
|
95
|
+
fail(
|
|
96
|
+
f"the datetime {value!r}", "dates must have a UTC year from 0001 to 9999"
|
|
97
|
+
)
|
|
48
98
|
if utc.microsecond % 1000:
|
|
49
|
-
|
|
99
|
+
fail(f"the datetime {value!r}", "dates have millisecond precision")
|
|
50
100
|
meta.append({"path": list(path), "type": "date"})
|
|
51
101
|
return _iso(utc)
|
|
52
102
|
if not isinstance(value, (list, dict)) and not (
|
|
53
103
|
mode == "native" and isinstance(value, tuple)
|
|
54
104
|
):
|
|
55
|
-
|
|
105
|
+
fail(f"a {type(value).__name__}", _PLAIN_RULE)
|
|
56
106
|
if ancestors is None:
|
|
57
107
|
ancestors = set()
|
|
58
108
|
if id(value) in ancestors:
|
|
59
|
-
|
|
109
|
+
fail("a cycle", "a value can't contain itself")
|
|
60
110
|
ancestors.add(id(value))
|
|
61
111
|
if isinstance(value, (list, tuple)):
|
|
62
112
|
result = [
|
|
63
|
-
_copy_value(item, mode, meta, (*path, i), ancestors)
|
|
113
|
+
_copy_value(item, mode, meta, (*path, i), ancestors, root)
|
|
64
114
|
for i, item in enumerate(value)
|
|
65
115
|
]
|
|
66
116
|
else:
|
|
67
117
|
result = {}
|
|
68
118
|
for key, item in value.items():
|
|
69
119
|
if not isinstance(key, str):
|
|
70
|
-
|
|
71
|
-
if mode
|
|
120
|
+
fail(f"a {type(key).__name__} key", "keys must be strings")
|
|
121
|
+
if mode == "json" and (
|
|
72
122
|
key == "__proto__"
|
|
73
123
|
or key == "prototype"
|
|
74
124
|
and path
|
|
75
125
|
and path[-1] == "constructor"
|
|
76
126
|
):
|
|
77
|
-
|
|
78
|
-
result[key] = _copy_value(
|
|
127
|
+
fail("an unsafe key", "it could pollute prototypes", (*path, key))
|
|
128
|
+
result[key] = _copy_value(
|
|
129
|
+
item, mode, meta, (*path, key), ancestors, root
|
|
130
|
+
)
|
|
79
131
|
ancestors.remove(id(value))
|
|
80
132
|
return result
|
|
81
133
|
|
|
82
134
|
|
|
83
|
-
def encode_document(value: Any) -> StatewireDocument.Encoded:
|
|
84
|
-
"""Encode a document value as detached JSON data with date metadata."""
|
|
135
|
+
def encode_document(value: Any, root: str = "") -> StatewireDocument.Encoded:
|
|
136
|
+
"""Encode a document value as detached JSON data with date metadata; ``root`` names it in a StatewireValueError."""
|
|
85
137
|
meta: list[StatewireDocument.MetaEntry] = []
|
|
86
|
-
encoded = _copy_value(value, "encode", meta)
|
|
138
|
+
encoded = _copy_value(value, "encode", meta, root=root)
|
|
87
139
|
return {"value": encoded, "meta": meta} if meta else {"value": encoded}
|
|
88
140
|
|
|
89
141
|
|
|
@@ -34,7 +34,19 @@ def apply_documents(
|
|
|
34
34
|
*,
|
|
35
35
|
strict: bool = True,
|
|
36
36
|
) -> dict[int, Document]:
|
|
37
|
-
from .client import _apply_mutable, StatewireProtocolError
|
|
37
|
+
from .client import _apply_mutable, _received, StatewireProtocolError
|
|
38
|
+
|
|
39
|
+
def received(value: Any, meta: Any, parent: Any = None) -> Any:
|
|
40
|
+
# Clients check what they receive; a host checks client patches to its
|
|
41
|
+
# own documents the same way. A checked copy first (no deepcopy: it
|
|
42
|
+
# recurses twice per level), then dates, then unsafe keys go.
|
|
43
|
+
try:
|
|
44
|
+
value = _received(value, parent, strip=False)
|
|
45
|
+
if meta is not None:
|
|
46
|
+
value = _decode_meta(value, meta, reject_unknown=strict)
|
|
47
|
+
return _received(value, parent)
|
|
48
|
+
except StatewireProtocolError as exc:
|
|
49
|
+
raise ValueError(str(exc)) from exc
|
|
38
50
|
from .document import _decode_meta
|
|
39
51
|
|
|
40
52
|
if not isinstance(operations, list):
|
|
@@ -73,9 +85,7 @@ def apply_documents(
|
|
|
73
85
|
for d in documents.values()
|
|
74
86
|
):
|
|
75
87
|
raise ValueError("duplicate document key or main")
|
|
76
|
-
value =
|
|
77
|
-
if "meta" in op:
|
|
78
|
-
value = _decode_meta(value, op["meta"], reject_unknown=strict)
|
|
88
|
+
value = received(op["value"], op.get("meta"))
|
|
79
89
|
documents[doc] = Document(
|
|
80
90
|
protocol, value, tuple(key) if key is not None else None, main
|
|
81
91
|
)
|
|
@@ -94,10 +104,12 @@ def apply_documents(
|
|
|
94
104
|
raise ValueError("operation requires valid path")
|
|
95
105
|
if kind != "remove" and "value" not in op:
|
|
96
106
|
raise ValueError("operation requires value")
|
|
97
|
-
mutation =
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
107
|
+
mutation = {k: v for k, v in op.items() if k not in ("value", "meta")}
|
|
108
|
+
mutation["path"] = list(path)
|
|
109
|
+
if "value" in op:
|
|
110
|
+
last = path[-1] if path else None
|
|
111
|
+
mutation["value"] = received(
|
|
112
|
+
op["value"], op.get("meta"), last if isinstance(last, str) else None
|
|
101
113
|
)
|
|
102
114
|
try:
|
|
103
115
|
value = _apply_mutable(document.value, mutation)
|
|
@@ -70,14 +70,9 @@ def test_empty_metadata_leaves_strings_as_strings():
|
|
|
70
70
|
@pytest.mark.parametrize(
|
|
71
71
|
"value",
|
|
72
72
|
[
|
|
73
|
-
float("nan"),
|
|
74
|
-
float("inf"),
|
|
75
|
-
float("-inf"),
|
|
76
73
|
2**53,
|
|
77
74
|
float(2**53),
|
|
78
75
|
{1: "key"},
|
|
79
|
-
{"__proto__": {}},
|
|
80
|
-
{"constructor": {"prototype": {}}},
|
|
81
76
|
(1, 2),
|
|
82
77
|
{1, 2},
|
|
83
78
|
b"bytes",
|
|
@@ -95,6 +90,18 @@ def test_unsupported_native_values(value):
|
|
|
95
90
|
decode_document({"value": value})
|
|
96
91
|
|
|
97
92
|
|
|
93
|
+
@pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")])
|
|
94
|
+
def test_non_finite_numbers_encode_as_none(value):
|
|
95
|
+
assert encode_document({"a": [value]}) == {"value": {"a": [None]}}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@pytest.mark.parametrize("value", [{"__proto__": {}}, {"constructor": {"prototype": {}}}])
|
|
99
|
+
def test_unsafe_keys_encode_as_written_and_never_decode(value):
|
|
100
|
+
assert encode_document(value) == {"value": value}
|
|
101
|
+
with pytest.raises(ValueError, match="unsafe key"):
|
|
102
|
+
decode_document({"value": value})
|
|
103
|
+
|
|
104
|
+
|
|
98
105
|
def test_cycles_in_both_directions():
|
|
99
106
|
value = []
|
|
100
107
|
value.append(value)
|
|
@@ -990,7 +990,7 @@ async def test_non_encodable_identity_fins_a_websocket_attach():
|
|
|
990
990
|
async def test_an_invalid_identity_value_is_refused_the_same_way():
|
|
991
991
|
class NonFinite(Admitting):
|
|
992
992
|
async def authorize(self, request):
|
|
993
|
-
return {"score":
|
|
993
|
+
return {"score": 2**60}
|
|
994
994
|
|
|
995
995
|
async with statewire_client(
|
|
996
996
|
NonFinite, worker=Worker(state_store=MemoryStateStore())
|
|
@@ -1004,11 +1004,11 @@ async def test_an_invalid_identity_value_is_refused_the_same_way():
|
|
|
1004
1004
|
|
|
1005
1005
|
@pytest.mark.parametrize(
|
|
1006
1006
|
"auth_result,error",
|
|
1007
|
-
[({"user": UserModel()}, TypeError), ({"score":
|
|
1007
|
+
[({"user": UserModel()}, TypeError), ({"score": 2**60}, ValueError)],
|
|
1008
1008
|
)
|
|
1009
1009
|
async def test_start_session_raises_the_encoder_error(auth_result, error):
|
|
1010
1010
|
async with instance(Admitting, state_store=MemoryStateStore()) as live:
|
|
1011
|
-
with pytest.raises(error, match="
|
|
1011
|
+
with pytest.raises(error, match="can't encode"):
|
|
1012
1012
|
await anext(live.start_session("c1", auth_result))
|
|
1013
1013
|
assert live.attaches() == []
|
|
1014
1014
|
|
|
@@ -51,12 +51,9 @@ def test_observables_encode_without_materializing(stdlib, monkeypatch):
|
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
|
|
54
|
-
def
|
|
55
|
-
# Validation, not the serializer, owns this rejection: orjson would
|
|
56
|
-
# encode non-finite floats as null instead of raising.
|
|
54
|
+
def test_non_finite_floats_are_none_as_json_writes_them():
|
|
57
55
|
for bad in (math.nan, math.inf, -math.inf):
|
|
58
|
-
|
|
59
|
-
_frozen_encoded({"n": bad})
|
|
56
|
+
assert _frozen_encoded({"n": bad}) == ({"n": None}, None)
|
|
60
57
|
|
|
61
58
|
|
|
62
59
|
def test_stdlib_fallback_rejects_non_finite_floats(monkeypatch):
|
|
@@ -215,13 +215,12 @@ async def test_setdefault():
|
|
|
215
215
|
]
|
|
216
216
|
|
|
217
217
|
|
|
218
|
-
async def
|
|
218
|
+
async def test_non_finite_float_write_is_none_as_json_writes_it():
|
|
219
219
|
inst = make({"n": 0})
|
|
220
220
|
for bad in (float("nan"), float("inf"), float("-inf")):
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
assert ops_of(inst) == []
|
|
221
|
+
inst.state["n"] = bad
|
|
222
|
+
assert inst._state.value["n"] is None
|
|
223
|
+
assert ops_of(inst) == [{"op": "replace", "path": ["n"], "value": None}]
|
|
225
224
|
|
|
226
225
|
|
|
227
226
|
async def test_finite_float_write_encodes_unchanged():
|
|
@@ -259,7 +258,7 @@ async def test_strict_default_still_raises_on_invalid_state_values():
|
|
|
259
258
|
inst = make({})
|
|
260
259
|
with pytest.raises(ValueError, match="naive datetime"):
|
|
261
260
|
inst.state["t"] = datetime(2020, 1, 1)
|
|
262
|
-
with pytest.raises(ValueError, match="
|
|
261
|
+
with pytest.raises(ValueError, match="safe integer range"):
|
|
263
262
|
inst.state["n"] = 2**60
|
|
264
263
|
with pytest.raises(TypeError, match="keys must be strings"):
|
|
265
264
|
inst.state["d"] = {1: "x"}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""The value rules shared with the TypeScript statewire (values.test.ts): the
|
|
2
|
+
table in packages/statewire/core/tests/fixtures/values.json, run against every
|
|
3
|
+
Python path. Python has no undefined, holes or BigInt; those cases are
|
|
4
|
+
TypeScript's only."""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
from statewire_helpers import make_instance
|
|
12
|
+
|
|
13
|
+
from statewire import Statewire, StatewireValueError, encode_document
|
|
14
|
+
from statewire.client import (
|
|
15
|
+
StatewireProtocolError,
|
|
16
|
+
_document_ops,
|
|
17
|
+
_encode_params,
|
|
18
|
+
_loads,
|
|
19
|
+
_revive_response,
|
|
20
|
+
)
|
|
21
|
+
from statewire.document import _frozen_encoded, format_path
|
|
22
|
+
from statewire.documents import Document, apply_documents
|
|
23
|
+
|
|
24
|
+
TABLE = json.loads(
|
|
25
|
+
(
|
|
26
|
+
Path(__file__).resolve().parents[4]
|
|
27
|
+
/ "packages/statewire/core/tests/fixtures/values.json"
|
|
28
|
+
).read_text()
|
|
29
|
+
)
|
|
30
|
+
TS_ONLY = {"undefined", "hole", "bigint"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Row:
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def markers(node):
|
|
38
|
+
if isinstance(node, list):
|
|
39
|
+
return {m for item in node for m in markers(item)}
|
|
40
|
+
if isinstance(node, dict):
|
|
41
|
+
if "$" in node:
|
|
42
|
+
return {node["$"]}
|
|
43
|
+
return {m for item in node.values() for m in markers(item)}
|
|
44
|
+
return set()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def build(node, holder=None):
|
|
48
|
+
if isinstance(node, list):
|
|
49
|
+
out = []
|
|
50
|
+
for item in node:
|
|
51
|
+
out.append(build(item, out))
|
|
52
|
+
return out
|
|
53
|
+
if isinstance(node, dict):
|
|
54
|
+
if "$" in node:
|
|
55
|
+
return {
|
|
56
|
+
"NaN": float("nan"),
|
|
57
|
+
"Infinity": float("inf"),
|
|
58
|
+
"-Infinity": float("-inf"),
|
|
59
|
+
"unsafe": 2**53,
|
|
60
|
+
"function": lambda: None,
|
|
61
|
+
"instance": Row(),
|
|
62
|
+
"cycle": holder,
|
|
63
|
+
}[node["$"]]
|
|
64
|
+
out = {}
|
|
65
|
+
for key, item in node.items():
|
|
66
|
+
out[key] = build(item, out)
|
|
67
|
+
return out
|
|
68
|
+
return node
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Plain(Statewire):
|
|
72
|
+
async def lifespan(self):
|
|
73
|
+
self.state = {}
|
|
74
|
+
yield
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def state_write(value):
|
|
78
|
+
inst = make_instance(Plain)
|
|
79
|
+
inst.state = {}
|
|
80
|
+
inst._pending_ops.clear()
|
|
81
|
+
for key, item in value.items():
|
|
82
|
+
inst.state[key] = item
|
|
83
|
+
return [json.loads(op.data)["value"] for op in inst._pending_ops], inst
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def written_state(value):
|
|
87
|
+
_, inst = state_write(value)
|
|
88
|
+
return inst._state.value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
PATHS = [
|
|
92
|
+
("encode_document (results, context, auth)", lambda v: encode_document(v)["value"], []),
|
|
93
|
+
("command params", lambda v: _encode_params([1, v], "m")["params"][1], [1]),
|
|
94
|
+
("documents and op values", lambda v: _frozen_encoded(v)[0], []),
|
|
95
|
+
("a state write", written_state, []),
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
CASES = [c for c in TABLE["cases"] if not markers(c["input"]) & TS_ONLY]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@pytest.mark.parametrize("path", PATHS, ids=[p[0] for p in PATHS])
|
|
102
|
+
@pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES])
|
|
103
|
+
async def test_value_rules(case, path):
|
|
104
|
+
_name, encode, prefix = path
|
|
105
|
+
value = build(case["input"])
|
|
106
|
+
if "value" in case:
|
|
107
|
+
assert encode(value) == case["value"]
|
|
108
|
+
return
|
|
109
|
+
with pytest.raises((ValueError, TypeError)) as raised:
|
|
110
|
+
encode(value)
|
|
111
|
+
at = [*prefix, *case["error"]]
|
|
112
|
+
if isinstance(raised.value, StatewireValueError):
|
|
113
|
+
assert raised.value.path == at
|
|
114
|
+
else:
|
|
115
|
+
# statepatch's own error names the path in its message.
|
|
116
|
+
assert format_path(at) in str(raised.value)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def test_a_state_write_sends_what_it_keeps():
|
|
120
|
+
sent, _ = state_write({"a": float("nan"), "b": [float("inf"), 1]})
|
|
121
|
+
assert sent == [None, [None, 1]]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def mounted(value):
|
|
125
|
+
documents, _ = _document_ops(
|
|
126
|
+
{}, None, [{"op": "mount", "doc": 0, "key": ["root"], "value": value}]
|
|
127
|
+
)
|
|
128
|
+
return documents[0]["value"]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def patched(value):
|
|
132
|
+
documents, _ = _document_ops(
|
|
133
|
+
{0: {"key": ["root"], "value": {}}},
|
|
134
|
+
"mounted",
|
|
135
|
+
[{"op": "replace", "doc": 0, "path": ["x"], "value": value}],
|
|
136
|
+
)
|
|
137
|
+
return documents[0]["value"]["x"]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def selected_mount(value):
|
|
141
|
+
return apply_documents(
|
|
142
|
+
{}, [{"op": "mount", "doc": 0, "protocol": "default", "main": True, "value": value}],
|
|
143
|
+
{"default": ""}, strict=False,
|
|
144
|
+
)[0].value
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def selected_patch(value):
|
|
148
|
+
current = {0: Document("default", {}, None, True)}
|
|
149
|
+
return apply_documents(
|
|
150
|
+
current, [{"op": "replace", "doc": 0, "path": ["x"], "value": value}],
|
|
151
|
+
{"default": ""}, strict=False,
|
|
152
|
+
)[0].value["x"]
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
RECEIVED = [
|
|
156
|
+
("a snapshot", mounted),
|
|
157
|
+
("a patch", patched),
|
|
158
|
+
("a negotiated snapshot", selected_mount),
|
|
159
|
+
("a negotiated patch", selected_patch),
|
|
160
|
+
("a result", lambda v: _revive_response({"payload": v})["payload"]),
|
|
161
|
+
]
|
|
162
|
+
RECEIVED_CASES = TABLE["received"]["cases"]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@pytest.mark.parametrize("path", RECEIVED, ids=[p[0] for p in RECEIVED])
|
|
166
|
+
@pytest.mark.parametrize(
|
|
167
|
+
"case", RECEIVED_CASES, ids=[c["name"] for c in RECEIVED_CASES]
|
|
168
|
+
)
|
|
169
|
+
def test_received_values(case, path, caplog):
|
|
170
|
+
_name, receive = path
|
|
171
|
+
caplog.set_level(logging.WARNING)
|
|
172
|
+
if "error" in case:
|
|
173
|
+
with pytest.raises((StatewireProtocolError, ValueError)):
|
|
174
|
+
receive(_loads(case["json"]))
|
|
175
|
+
return
|
|
176
|
+
assert receive(_loads(case["json"])) == case["value"]
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def test_a_patch_under_constructor_strips_prototype():
|
|
180
|
+
documents, _ = _document_ops(
|
|
181
|
+
{0: {"key": ["root"], "value": {"x": {}}}},
|
|
182
|
+
"mounted",
|
|
183
|
+
[{"op": "replace", "doc": 0, "path": ["x", "constructor"],
|
|
184
|
+
"value": {"prototype": {"p": True}, "ok": 1}}],
|
|
185
|
+
)
|
|
186
|
+
assert documents[0]["value"] == {"x": {"constructor": {"ok": 1}}}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def test_dates_revive_before_unsafe_keys_go():
|
|
190
|
+
response = _revive_response({
|
|
191
|
+
"payload": {"__proto__": {"at": "2026-09-07T12:00:00.123Z"}, "ok": 1},
|
|
192
|
+
"meta": [{"path": ["__proto__", "at"], "type": "date"}],
|
|
193
|
+
})
|
|
194
|
+
assert response["payload"] == {"ok": 1}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|