statewire 0.24.1__tar.gz → 0.24.3__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.3}/PKG-INFO +3 -3
- {statewire-0.24.1 → statewire-0.24.3}/pyproject.toml +3 -3
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/__init__.py +7 -1
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/api.py +51 -5
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/client.py +74 -14
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/document.py +85 -28
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/documents.py +20 -8
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/limits.py +6 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_attach_fence.py +34 -15
- statewire-0.24.3/tests/test_depth.py +94 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_document.py +24 -5
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_durable_admission.py +134 -3
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_meta.py +18 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_ops.py +2 -5
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_read_filters.py +11 -2
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_state_proxy.py +5 -6
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_storage_bridge.py +15 -3
- statewire-0.24.3/tests/test_values.py +194 -0
- {statewire-0.24.1 → statewire-0.24.3}/.gitignore +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/README.md +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/examples/__init__.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/examples/demo_app.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/examples/local_origin.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/filter.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/langgraph.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/metrics.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/ops.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/protocol.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/state.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/src/statewire/testing.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/client_helpers.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/statewire_helpers.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/storage_probe.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_attach_guardrail.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_attached_hook.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_authorize.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_client.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_client_binding.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_client_ws.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_context.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_date_registry.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_departure.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_eviction.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_filter.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_frames.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_gap_fill.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_idle.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_lanes.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_langgraph.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_lifespan.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_observer.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_origin.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_protocol_negotiation.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_route_auth.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_start_session.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_statewire_hostable.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_stream.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_testing.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_writer_lease.py +0 -0
- {statewire-0.24.1 → statewire-0.24.3}/tests/test_ws.py +0 -0
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: statewire
|
|
3
|
-
Version: 0.24.
|
|
3
|
+
Version: 0.24.3
|
|
4
4
|
Summary: Replicate one JSON object over an SSE op stream + a command endpoint
|
|
5
5
|
Project-URL: Repository, https://github.com/assistant-ui/harness-sdk
|
|
6
6
|
License-Expression: MIT
|
|
7
7
|
Requires-Python: <4.0,>=3.12
|
|
8
8
|
Requires-Dist: fastapi>=0.115
|
|
9
9
|
Requires-Dist: httpx>=0.27
|
|
10
|
-
Requires-Dist: pinboard-sdk>=0.18.
|
|
11
|
-
Requires-Dist: statepatch<0.4,>=0.3.
|
|
10
|
+
Requires-Dist: pinboard-sdk>=0.18.4
|
|
11
|
+
Requires-Dist: statepatch<0.4,>=0.3.2
|
|
12
12
|
Provides-Extra: langgraph
|
|
13
13
|
Requires-Dist: langchain-core>=0.3; extra == 'langgraph'
|
|
14
14
|
Provides-Extra: orjson
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "statewire"
|
|
3
|
-
version = "0.24.
|
|
3
|
+
version = "0.24.3"
|
|
4
4
|
description = "Replicate one JSON object over an SSE op stream + a command endpoint"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
7
7
|
requires-python = ">=3.12,<4.0"
|
|
8
8
|
dependencies = [
|
|
9
|
-
"pinboard-sdk>=0.18.
|
|
10
|
-
"statepatch>=0.3.
|
|
9
|
+
"pinboard-sdk>=0.18.4",
|
|
10
|
+
"statepatch>=0.3.2,<0.4",
|
|
11
11
|
"fastapi>=0.115",
|
|
12
12
|
"httpx>=0.27",
|
|
13
13
|
]
|
|
@@ -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",
|
|
@@ -194,6 +194,7 @@ from .documents import Document, apply_documents, diff_documents
|
|
|
194
194
|
from .limits import (
|
|
195
195
|
COMMAND_CAPACITY_RETRY_MS,
|
|
196
196
|
MAX_COMMANDS_PER_FRAME,
|
|
197
|
+
MAX_DOCUMENT_DEPTH,
|
|
197
198
|
MAX_EPHEMERAL_DOCUMENT_BYTES,
|
|
198
199
|
MAX_FRAME_BODY_BYTES,
|
|
199
200
|
MAX_FRAME_VALUES,
|
|
@@ -682,23 +683,30 @@ _IDENTITY_UNAVAILABLE = {
|
|
|
682
683
|
}
|
|
683
684
|
|
|
684
685
|
|
|
686
|
+
_MAX_STATEMENT_DEPTH = MAX_DOCUMENT_DEPTH - 3
|
|
687
|
+
|
|
688
|
+
|
|
685
689
|
def _unstorable(value: Any) -> str | None:
|
|
686
690
|
"""Why a durable store refuses ``value``: a NUL or a lone surrogate in a
|
|
687
691
|
string or object key, or a non-finite number. Postgres TEXT/JSONB reject
|
|
688
692
|
NUL, UTF-8 has no lone surrogates, and JSON has no inf or NaN, so the
|
|
689
|
-
admission write would fail and abort the instance.
|
|
690
|
-
|
|
693
|
+
admission write would fail and abort the instance. A statement is stored
|
|
694
|
+
3 levels down the pool (envelope, statements, its slot), so it also may
|
|
695
|
+
not nest deeper than the document limit leaves there."""
|
|
696
|
+
stack = [(value, 0)]
|
|
691
697
|
while stack:
|
|
692
|
-
node = stack.pop()
|
|
698
|
+
node, depth = stack.pop()
|
|
693
699
|
if isinstance(node, float):
|
|
694
700
|
if not math.isfinite(node):
|
|
695
701
|
return "numbers must be finite"
|
|
696
702
|
continue
|
|
703
|
+
if isinstance(node, (dict, list)) and depth >= _MAX_STATEMENT_DEPTH:
|
|
704
|
+
return f"params nest too deeply to store (limit {MAX_DOCUMENT_DEPTH} from the pool root)"
|
|
697
705
|
if isinstance(node, dict):
|
|
698
706
|
strings: Any = node.keys()
|
|
699
|
-
stack.extend(node.values())
|
|
707
|
+
stack.extend((item, depth + 1) for item in node.values())
|
|
700
708
|
elif isinstance(node, list):
|
|
701
|
-
stack.extend(node)
|
|
709
|
+
stack.extend((item, depth + 1) for item in node)
|
|
702
710
|
continue
|
|
703
711
|
elif isinstance(node, str):
|
|
704
712
|
strings = (node,)
|
|
@@ -837,11 +845,35 @@ class ClientCommands(Tray):
|
|
|
837
845
|
drain_on_eviction = True
|
|
838
846
|
seq = persistent({})
|
|
839
847
|
pool = persistent([])
|
|
848
|
+
# wall time each pooled frame was admitted, keyed by its head statement;
|
|
849
|
+
# a separate field so the admission envelope keeps its strict shape
|
|
850
|
+
admitted_at = persistent({})
|
|
840
851
|
parked = persistent([])
|
|
841
852
|
quarantine = persistent([])
|
|
842
853
|
identity = persistent(None)
|
|
843
854
|
identity_through = persistent({})
|
|
844
855
|
|
|
856
|
+
@staticmethod
|
|
857
|
+
def _frame_key(frame: Any) -> str:
|
|
858
|
+
head = _pool_statements(frame)[0]
|
|
859
|
+
return f"{head['protocol']}:{head['seq']}"
|
|
860
|
+
|
|
861
|
+
def _stamps(self, keep: Any = ()) -> dict[str, Any]:
|
|
862
|
+
live = {self._frame_key(frame) for frame in self.pool.value}
|
|
863
|
+
return {
|
|
864
|
+
k: v for k, v in self.admitted_at.value.items() if k in live or k in keep
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
def _enqueued_at(self, frame: Any) -> float | None:
|
|
868
|
+
# a frame pooled before admitted_at existed is stamped on first sight
|
|
869
|
+
key = self._frame_key(frame)
|
|
870
|
+
at = self.admitted_at.value.get(key)
|
|
871
|
+
if isinstance(at, (int, float)) and not isinstance(at, bool):
|
|
872
|
+
return float(at)
|
|
873
|
+
at = self._domain.now()
|
|
874
|
+
self.admitted_at.value = {**self._stamps(), key: at}
|
|
875
|
+
return at
|
|
876
|
+
|
|
845
877
|
def attributed(self, frame: Any) -> bool:
|
|
846
878
|
if not isinstance(frame, list):
|
|
847
879
|
return True
|
|
@@ -919,6 +951,9 @@ class ClientCommands(Tray):
|
|
|
919
951
|
yield frame
|
|
920
952
|
self._advance(_pool_statements(frame))
|
|
921
953
|
self.pool.pop(0)
|
|
954
|
+
stamps = self._stamps()
|
|
955
|
+
if stamps != self.admitted_at.value:
|
|
956
|
+
self.admitted_at.value = stamps
|
|
922
957
|
|
|
923
958
|
def _advance(self, statements: list[dict[str, Any]]) -> None:
|
|
924
959
|
self.seq.value = {
|
|
@@ -950,6 +985,11 @@ class ClientCommands(Tray):
|
|
|
950
985
|
self._check_above(statements)
|
|
951
986
|
self.kick()
|
|
952
987
|
self.identity.value = auth
|
|
988
|
+
key = f"{statements[0]['protocol']}:{statements[0]['seq']}"
|
|
989
|
+
self.admitted_at.value = {
|
|
990
|
+
**self._stamps(keep=(key,)),
|
|
991
|
+
key: self._domain.now(),
|
|
992
|
+
}
|
|
953
993
|
if record == "list":
|
|
954
994
|
self.pool.append(statements)
|
|
955
995
|
self.identity_through.value = {
|
|
@@ -1031,6 +1071,9 @@ class ClientCommands(Tray):
|
|
|
1031
1071
|
self._advance(statements)
|
|
1032
1072
|
self.pool.value = pool
|
|
1033
1073
|
self.quarantine.value = quarantine
|
|
1074
|
+
stamps = self._stamps()
|
|
1075
|
+
if stamps != self.admitted_at.value:
|
|
1076
|
+
self.admitted_at.value = stamps
|
|
1034
1077
|
self.kick()
|
|
1035
1078
|
|
|
1036
1079
|
|
|
@@ -4234,6 +4277,9 @@ class Statewire(PinboardAPI):
|
|
|
4234
4277
|
except asyncio.CancelledError:
|
|
4235
4278
|
raise
|
|
4236
4279
|
except WireEncodingError as exc:
|
|
4280
|
+
# Includes WireDepthError: a write past the document depth limit
|
|
4281
|
+
# fails at the write, so the document still encodes for every later
|
|
4282
|
+
# attach; the command settles failed, as in the TypeScript host.
|
|
4237
4283
|
logger.exception("command state is not wire-encodable")
|
|
4238
4284
|
self._settle(inv, {"type": "failed", "message": str(exc)})
|
|
4239
4285
|
except Exception:
|
|
@@ -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,
|
|
@@ -37,6 +38,7 @@ from .ops import (
|
|
|
37
38
|
)
|
|
38
39
|
from .limits import (
|
|
39
40
|
MAX_COMMANDS_PER_FRAME,
|
|
41
|
+
MAX_DOCUMENT_DEPTH,
|
|
40
42
|
MAX_FRAME_BODY_BYTES,
|
|
41
43
|
MAX_EPHEMERAL_DOCUMENT_BYTES,
|
|
42
44
|
)
|
|
@@ -222,6 +224,59 @@ def _backoff(timing: Timing, attempt: int) -> float:
|
|
|
222
224
|
# ─── Wire values (meta-typed dates) ─────────────────────────
|
|
223
225
|
|
|
224
226
|
|
|
227
|
+
_MAX_DEPTH = MAX_DOCUMENT_DEPTH
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _received(
|
|
231
|
+
value: Any, parent: Any = None, path: tuple[str | int, ...] = (), strip: bool = True
|
|
232
|
+
) -> Any:
|
|
233
|
+
"""What a client keeps of a value the host sent: unsafe keys stripped and
|
|
234
|
+
integers past the JS safe range as None, each with a warning, as the
|
|
235
|
+
TypeScript client does. The client checks this itself; the host doesn't."""
|
|
236
|
+
if isinstance(value, bool):
|
|
237
|
+
return value
|
|
238
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
239
|
+
# JSON has no such number (json.loads reads 1e400 as inf).
|
|
240
|
+
raise StatewireProtocolError(
|
|
241
|
+
f"protocol error: the number {value} at {format_path(path)} is not JSON"
|
|
242
|
+
)
|
|
243
|
+
if isinstance(value, int) or isinstance(value, float) and value.is_integer():
|
|
244
|
+
if abs(value) > 2**53 - 1:
|
|
245
|
+
logger.warning(
|
|
246
|
+
"statewire: replaced %s with null at %s", value, format_path(path)
|
|
247
|
+
)
|
|
248
|
+
return None
|
|
249
|
+
return value
|
|
250
|
+
if isinstance(value, (list, dict)) and len(path) >= _MAX_DEPTH:
|
|
251
|
+
raise StatewireProtocolError(
|
|
252
|
+
f"protocol error: value at {format_path(path)} is nested deeper than {_MAX_DEPTH}"
|
|
253
|
+
)
|
|
254
|
+
if isinstance(value, list):
|
|
255
|
+
return [_received(item, None, (*path, i), strip) for i, item in enumerate(value)]
|
|
256
|
+
if isinstance(value, dict):
|
|
257
|
+
out: dict[str, Any] = {}
|
|
258
|
+
for key, item in value.items():
|
|
259
|
+
if strip and (
|
|
260
|
+
key == "__proto__" or key == "prototype" and parent == "constructor"
|
|
261
|
+
):
|
|
262
|
+
logger.warning(
|
|
263
|
+
"statewire: stripped unsafe key %r at %s", key, format_path(path)
|
|
264
|
+
)
|
|
265
|
+
continue
|
|
266
|
+
out[key] = _received(item, key, (*path, key), strip)
|
|
267
|
+
return out
|
|
268
|
+
return value
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _no_constant(name: str) -> Any:
|
|
272
|
+
raise StatewireProtocolError(f"protocol error: {name} is not JSON")
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _loads(raw: str | bytes) -> Any:
|
|
276
|
+
"""JSON as the wire allows it: no NaN or Infinity tokens."""
|
|
277
|
+
return json.loads(raw, parse_constant=_no_constant)
|
|
278
|
+
|
|
279
|
+
|
|
225
280
|
def _revive_value(value: Any, meta: Any) -> Any:
|
|
226
281
|
try:
|
|
227
282
|
return _decode_meta(value, meta)
|
|
@@ -230,23 +285,30 @@ def _revive_value(value: Any, meta: Any) -> Any:
|
|
|
230
285
|
|
|
231
286
|
|
|
232
287
|
def _revive_op(op: Any) -> Any:
|
|
233
|
-
if not isinstance(op, dict) or "
|
|
288
|
+
if not isinstance(op, dict) or "value" not in op:
|
|
234
289
|
return op
|
|
235
290
|
revived = {k: v for k, v in op.items() if k != "meta"}
|
|
236
|
-
|
|
291
|
+
# Dates first: a meta path may name a key the receive check strips.
|
|
292
|
+
if "meta" in op:
|
|
293
|
+
revived["value"] = _revive_value(revived["value"], op["meta"])
|
|
294
|
+
path = op.get("path")
|
|
295
|
+
last = path[-1] if isinstance(path, list) and path else None
|
|
296
|
+
revived["value"] = _received(revived["value"], last if isinstance(last, str) else None)
|
|
237
297
|
return revived
|
|
238
298
|
|
|
239
299
|
|
|
240
300
|
def _revive_response(response: dict[str, Any]) -> dict[str, Any]:
|
|
241
|
-
if "
|
|
301
|
+
if "payload" not in response:
|
|
242
302
|
return response
|
|
243
303
|
revived = {k: v for k, v in response.items() if k != "meta"}
|
|
244
|
-
|
|
304
|
+
if "meta" in response:
|
|
305
|
+
revived["payload"] = _revive_value(revived["payload"], response["meta"])
|
|
306
|
+
revived["payload"] = _received(revived["payload"])
|
|
245
307
|
return revived
|
|
246
308
|
|
|
247
309
|
|
|
248
|
-
def _encode_params(params: list[Any]) -> dict[str, Any]:
|
|
249
|
-
document = encode_document(params)
|
|
310
|
+
def _encode_params(params: list[Any], method: str | None = None) -> dict[str, Any]:
|
|
311
|
+
document = encode_document(params, "params" if method is None else f"{method} params")
|
|
250
312
|
encoded, meta = document["value"], document.get("meta")
|
|
251
313
|
return {"params": encoded, "meta": meta} if meta else {"params": encoded}
|
|
252
314
|
|
|
@@ -603,7 +665,7 @@ class StatewireHttp:
|
|
|
603
665
|
try:
|
|
604
666
|
async for chunk in response.aiter_text():
|
|
605
667
|
for data in parser.feed(chunk):
|
|
606
|
-
yield
|
|
668
|
+
yield _loads(data)
|
|
607
669
|
except httpx.HTTPError as exc:
|
|
608
670
|
raise TransportError(str(exc) or "network") from exc
|
|
609
671
|
|
|
@@ -748,7 +810,7 @@ class StatewireWebsocket:
|
|
|
748
810
|
raise
|
|
749
811
|
except Exception as exc:
|
|
750
812
|
raise TransportError(str(exc) or "network") from exc
|
|
751
|
-
envelope =
|
|
813
|
+
envelope = _loads(raw)
|
|
752
814
|
if envelope == {}:
|
|
753
815
|
continue # heartbeat, below the packet layer
|
|
754
816
|
yield envelope
|
|
@@ -1013,7 +1075,7 @@ class StatewireClient:
|
|
|
1013
1075
|
return future
|
|
1014
1076
|
name = protocol or self.protocol
|
|
1015
1077
|
self._check_protocol(name)
|
|
1016
|
-
command = {"protocol": name, "method": method, **_encode_params(list(params))}
|
|
1078
|
+
command = {"protocol": name, "method": method, **_encode_params(list(params), method)}
|
|
1017
1079
|
lane = self._lane(name)
|
|
1018
1080
|
seq = lane.next_seq
|
|
1019
1081
|
lane.next_seq = seq + 1
|
|
@@ -1259,7 +1321,7 @@ class StatewireClient:
|
|
|
1259
1321
|
if cmd.get("message") is not None:
|
|
1260
1322
|
failure["message"] = cmd["message"]
|
|
1261
1323
|
if "payload" in cmd:
|
|
1262
|
-
failure["payload"] = cmd["payload"]
|
|
1324
|
+
failure["payload"] = _revive_response(cmd)["payload"]
|
|
1263
1325
|
self._reject(entry, failure)
|
|
1264
1326
|
elif kind == "failed":
|
|
1265
1327
|
failure = {"fate": "failed", "cause": "server"}
|
|
@@ -1441,9 +1503,7 @@ class StatewireClient:
|
|
|
1441
1503
|
reason if reason in ("reconnect", "error", "unauthorized") else "error"
|
|
1442
1504
|
)
|
|
1443
1505
|
return "reattach"
|
|
1444
|
-
payload = fin.get("payload")
|
|
1445
|
-
if "meta" in fin:
|
|
1446
|
-
payload = _revive_value(payload, fin["meta"])
|
|
1506
|
+
payload = _revive_response(fin).get("payload")
|
|
1447
1507
|
self._finished = fin
|
|
1448
1508
|
self._settle_all("gone")
|
|
1449
1509
|
gone: dict[str, Any] = {"status": "gone", "reason": reason}
|
|
@@ -1,10 +1,13 @@
|
|
|
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
|
|
6
7
|
from typing import Any, Literal, NotRequired, TypedDict
|
|
7
8
|
|
|
9
|
+
from .limits import MAX_DOCUMENT_DEPTH
|
|
10
|
+
|
|
8
11
|
|
|
9
12
|
class StatewireDocument:
|
|
10
13
|
class MetaEntry(TypedDict):
|
|
@@ -16,92 +19,146 @@ class StatewireDocument:
|
|
|
16
19
|
meta: NotRequired[list[StatewireDocument.MetaEntry]]
|
|
17
20
|
|
|
18
21
|
|
|
22
|
+
_IDENTIFIER = re.compile(r"[A-Za-z_$][\w$]*")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def format_path(path: tuple[str | int, ...] | list[str | int], root: str = "") -> str:
|
|
26
|
+
"""A path as code reads it: ``events[2].approvalRequired``, ``params[2]``."""
|
|
27
|
+
out = root
|
|
28
|
+
for key in path:
|
|
29
|
+
if isinstance(key, int):
|
|
30
|
+
out += f"[{key}]"
|
|
31
|
+
elif _IDENTIFIER.fullmatch(key):
|
|
32
|
+
out += key if out == "" else f".{key}"
|
|
33
|
+
else:
|
|
34
|
+
out += f"[{json.dumps(key)}]"
|
|
35
|
+
return out or "the root"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class StatewireValueError(ValueError, TypeError):
|
|
39
|
+
"""A value a writer gave statewire that the wire can't carry, raised where it's written."""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self, found: str, path: tuple[str | int, ...], rule: str, root: str = ""
|
|
43
|
+
) -> None:
|
|
44
|
+
super().__init__(
|
|
45
|
+
f"statewire: can't encode {found} at {format_path(path, root)}: {rule}"
|
|
46
|
+
)
|
|
47
|
+
self.path = list(path)
|
|
48
|
+
self.found = found
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_PLAIN_RULE = (
|
|
52
|
+
"documents hold null, booleans, numbers, strings, dates, arrays and plain objects"
|
|
53
|
+
)
|
|
54
|
+
_INT_RULE = "integers must be within the safe integer range, so every client reads them exactly"
|
|
55
|
+
|
|
56
|
+
|
|
19
57
|
def _copy_value(
|
|
20
58
|
value: Any,
|
|
21
59
|
mode: Literal["encode", "native", "json"],
|
|
22
60
|
meta: list[StatewireDocument.MetaEntry],
|
|
23
61
|
path: tuple[str | int, ...] = (),
|
|
24
62
|
ancestors: set[int] | None = None,
|
|
63
|
+
root: str = "",
|
|
25
64
|
) -> Any:
|
|
65
|
+
# encode and native copy a writer's value (the shared rules in
|
|
66
|
+
# packages/statewire/core/tests/fixtures/values.json); json checks a
|
|
67
|
+
# document that arrived, which the wire contract (document.json) bounds.
|
|
68
|
+
def fail(found: str, rule: str, at: tuple[str | int, ...] = path) -> Any:
|
|
69
|
+
if mode == "json":
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"statewire: protocol error: invalid document: {found} at {format_path(at)}: {rule}"
|
|
72
|
+
)
|
|
73
|
+
raise StatewireValueError(found, at, rule, root)
|
|
74
|
+
|
|
26
75
|
if value is None or isinstance(value, (bool, str)):
|
|
27
76
|
return value
|
|
28
77
|
if isinstance(value, (int, float)):
|
|
29
78
|
if isinstance(value, float) and not math.isfinite(value):
|
|
30
|
-
|
|
79
|
+
if mode == "json":
|
|
80
|
+
fail(f"the number {value}", "numbers must be finite")
|
|
81
|
+
# As JSON.stringify writes them.
|
|
82
|
+
return None
|
|
31
83
|
if (isinstance(value, int) or mode != "native" and value.is_integer()) and abs(
|
|
32
84
|
value
|
|
33
85
|
) > 2**53 - 1:
|
|
34
|
-
|
|
86
|
+
fail(f"the number {value}", _INT_RULE)
|
|
35
87
|
return value
|
|
36
88
|
if mode != "json" and isinstance(value, datetime):
|
|
37
89
|
if value.tzinfo is None or value.utcoffset() is None:
|
|
38
|
-
|
|
39
|
-
if mode == "native":
|
|
40
|
-
meta.append({"path": list(path), "type": "date"})
|
|
41
|
-
return value
|
|
90
|
+
fail("a naive datetime", "datetimes need a timezone")
|
|
42
91
|
try:
|
|
43
92
|
utc = value.astimezone(timezone.utc)
|
|
44
93
|
except (OverflowError, ValueError):
|
|
45
|
-
|
|
46
|
-
f"
|
|
47
|
-
)
|
|
94
|
+
fail(
|
|
95
|
+
f"the datetime {value!r}", "dates must have a UTC year from 0001 to 9999"
|
|
96
|
+
)
|
|
97
|
+
if mode == "native":
|
|
98
|
+
meta.append({"path": list(path), "type": "date"})
|
|
99
|
+
return value
|
|
48
100
|
if utc.microsecond % 1000:
|
|
49
|
-
|
|
101
|
+
fail(f"the datetime {value!r}", "dates have millisecond precision")
|
|
50
102
|
meta.append({"path": list(path), "type": "date"})
|
|
51
103
|
return _iso(utc)
|
|
52
104
|
if not isinstance(value, (list, dict)) and not (
|
|
53
105
|
mode == "native" and isinstance(value, tuple)
|
|
54
106
|
):
|
|
55
|
-
|
|
107
|
+
fail(f"a {type(value).__name__}", _PLAIN_RULE)
|
|
56
108
|
if ancestors is None:
|
|
57
109
|
ancestors = set()
|
|
58
110
|
if id(value) in ancestors:
|
|
59
|
-
|
|
111
|
+
fail("a cycle", "a value can't contain itself")
|
|
112
|
+
if len(path) >= MAX_DOCUMENT_DEPTH:
|
|
113
|
+
fail("a value", f"it is nested deeper than {MAX_DOCUMENT_DEPTH}")
|
|
60
114
|
ancestors.add(id(value))
|
|
61
115
|
if isinstance(value, (list, tuple)):
|
|
62
116
|
result = [
|
|
63
|
-
_copy_value(item, mode, meta, (*path, i), ancestors)
|
|
117
|
+
_copy_value(item, mode, meta, (*path, i), ancestors, root)
|
|
64
118
|
for i, item in enumerate(value)
|
|
65
119
|
]
|
|
66
120
|
else:
|
|
67
121
|
result = {}
|
|
68
122
|
for key, item in value.items():
|
|
69
123
|
if not isinstance(key, str):
|
|
70
|
-
|
|
71
|
-
if mode
|
|
124
|
+
fail(f"a {type(key).__name__} key", "keys must be strings")
|
|
125
|
+
if mode == "json" and (
|
|
72
126
|
key == "__proto__"
|
|
73
127
|
or key == "prototype"
|
|
74
128
|
and path
|
|
75
129
|
and path[-1] == "constructor"
|
|
76
130
|
):
|
|
77
|
-
|
|
78
|
-
result[key] = _copy_value(
|
|
131
|
+
fail("an unsafe key", "it could pollute prototypes", (*path, key))
|
|
132
|
+
result[key] = _copy_value(
|
|
133
|
+
item, mode, meta, (*path, key), ancestors, root
|
|
134
|
+
)
|
|
79
135
|
ancestors.remove(id(value))
|
|
80
136
|
return result
|
|
81
137
|
|
|
82
138
|
|
|
83
|
-
def encode_document(value: Any) -> StatewireDocument.Encoded:
|
|
84
|
-
"""Encode a document value as detached JSON data with date metadata."""
|
|
139
|
+
def encode_document(value: Any, root: str = "") -> StatewireDocument.Encoded:
|
|
140
|
+
"""Encode a document value as detached JSON data with date metadata; ``root`` names it in a StatewireValueError."""
|
|
85
141
|
meta: list[StatewireDocument.MetaEntry] = []
|
|
86
|
-
encoded = _copy_value(value, "encode", meta)
|
|
142
|
+
encoded = _copy_value(value, "encode", meta, root=root)
|
|
87
143
|
return {"value": encoded, "meta": meta} if meta else {"value": encoded}
|
|
88
144
|
|
|
89
145
|
|
|
90
146
|
def decode_document(encoded: object) -> Any:
|
|
91
147
|
"""Validate and decode a document into detached values with native dates."""
|
|
92
|
-
document = _copy_value(encoded, "json", [])
|
|
93
148
|
if (
|
|
94
|
-
not isinstance(
|
|
95
|
-
or "value" not in
|
|
96
|
-
or
|
|
149
|
+
not isinstance(encoded, dict)
|
|
150
|
+
or "value" not in encoded
|
|
151
|
+
or encoded.keys() - {"value", "meta"}
|
|
97
152
|
):
|
|
98
153
|
raise ValueError("expected an object with value and optional meta")
|
|
99
|
-
value
|
|
100
|
-
|
|
154
|
+
# Depth counts from the value, not the wrapper, as encode_document writes it.
|
|
155
|
+
value = _copy_value(encoded["value"], "json", [])
|
|
156
|
+
if "meta" not in encoded:
|
|
101
157
|
return value
|
|
102
|
-
|
|
158
|
+
meta = _copy_value(encoded["meta"], "json", [])
|
|
159
|
+
if not isinstance(meta, list):
|
|
103
160
|
raise ValueError("meta must be an array")
|
|
104
|
-
return _decode_meta(value,
|
|
161
|
+
return _decode_meta(value, meta, reject_unknown=True, canonical=True)
|
|
105
162
|
|
|
106
163
|
|
|
107
164
|
def _frozen_encoded(value: Any) -> tuple[Any, list[StatewireDocument.MetaEntry] | None]:
|
|
@@ -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)
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
+
from statepatch import MAX_DEPTH
|
|
2
|
+
|
|
1
3
|
MAX_COMMANDS_PER_FRAME = 256
|
|
4
|
+
# Container levels a document may hold, from its root; matches the TypeScript
|
|
5
|
+
# host's MAX_DOCUMENT_DEPTH. State writes count from the document root
|
|
6
|
+
# (statepatch), so the attach snapshot never nests past what orjson encodes.
|
|
7
|
+
MAX_DOCUMENT_DEPTH = MAX_DEPTH
|
|
2
8
|
MAX_INFLIGHT_COMMANDS_PER_CLIENT = 256
|
|
3
9
|
MAX_FRAME_BODY_BYTES = 8 * 1024 * 1024
|
|
4
10
|
# Values (containers and leaves) one frame may hold; matches the TypeScript host.
|