statewire 0.23.4__tar.gz → 0.23.6__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.23.4 → statewire-0.23.6}/PKG-INFO +10 -10
- {statewire-0.23.4 → statewire-0.23.6}/README.md +8 -8
- {statewire-0.23.4 → statewire-0.23.6}/examples/demo_app.py +2 -2
- {statewire-0.23.4 → statewire-0.23.6}/pyproject.toml +3 -3
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/api.py +113 -28
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/testing.py +1 -1
- {statewire-0.23.4 → statewire-0.23.6}/tests/statewire_helpers.py +5 -5
- {statewire-0.23.4 → statewire-0.23.6}/tests/storage_probe.py +7 -2
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_attach_guardrail.py +4 -4
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_attached_hook.py +1 -1
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_authorize.py +2 -2
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_client.py +2 -2
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_client_binding.py +1 -1
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_context.py +4 -4
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_departure.py +1 -1
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_durable_admission.py +88 -30
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_eviction.py +6 -6
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_frames.py +6 -6
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_idle.py +1 -1
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_lanes.py +2 -2
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_read_filters.py +1 -1
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_route_auth.py +2 -2
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_statewire_hostable.py +1 -1
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_stream.py +4 -4
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_writer_lease.py +7 -7
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_ws.py +13 -13
- {statewire-0.23.4 → statewire-0.23.6}/.gitignore +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/examples/__init__.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/__init__.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/client.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/document.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/documents.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/filter.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/langgraph.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/limits.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/metrics.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/ops.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/protocol.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/src/statewire/state.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/client_helpers.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_attach_fence.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_client_ws.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_date_registry.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_document.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_filter.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_gap_fill.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_langgraph.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_lifespan.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_meta.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_observer.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_ops.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_protocol_negotiation.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_start_session.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_state_proxy.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_storage_bridge.py +0 -0
- {statewire-0.23.4 → statewire-0.23.6}/tests/test_testing.py +0 -0
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: statewire
|
|
3
|
-
Version: 0.23.
|
|
3
|
+
Version: 0.23.6
|
|
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:
|
|
10
|
+
Requires-Dist: pinboard-sdk>=0.18.0
|
|
11
11
|
Requires-Dist: statepatch<0.4,>=0.3.0
|
|
12
12
|
Provides-Extra: langgraph
|
|
13
13
|
Requires-Dist: langchain-core>=0.3; extra == 'langgraph'
|
|
@@ -17,7 +17,7 @@ Description-Content-Type: text/markdown
|
|
|
17
17
|
|
|
18
18
|
# statewire
|
|
19
19
|
|
|
20
|
-
The Statewire protocol for Python: a `Statewire` host owns one JSON state dict, streams every change to attached clients as ops, and dispatches typed commands back. Part of [harness-sdk](https://github.com/assistant-ui/harness-sdk), with `harness-sdk` and
|
|
20
|
+
The Statewire protocol for Python: a `Statewire` host owns one JSON state dict, streams every change to attached clients as ops, and dispatches typed commands back. Part of [harness-sdk](https://github.com/assistant-ui/harness-sdk), with `harness-sdk` and Pinboard.
|
|
21
21
|
|
|
22
22
|
## Install
|
|
23
23
|
|
|
@@ -31,7 +31,7 @@ Extras: `uv add "statewire[langgraph]"`, `uv add "statewire[orjson]"`.
|
|
|
31
31
|
|
|
32
32
|
```python
|
|
33
33
|
from fastapi import FastAPI
|
|
34
|
-
from
|
|
34
|
+
from pinboard import Worker
|
|
35
35
|
from statewire import Statewire, StatewireReject, command
|
|
36
36
|
|
|
37
37
|
class Counter(Statewire):
|
|
@@ -45,7 +45,7 @@ class Counter(Statewire):
|
|
|
45
45
|
raise StatewireReject("the counter is full (max 10)")
|
|
46
46
|
self.state["count"] += 1
|
|
47
47
|
|
|
48
|
-
worker =
|
|
48
|
+
worker = Worker(hosts={"/threads": Counter})
|
|
49
49
|
app = FastAPI()
|
|
50
50
|
app.include_router(worker)
|
|
51
51
|
```
|
|
@@ -56,14 +56,14 @@ Connections negotiate date ranges through `Statewire-Version` and `Statewire-Pro
|
|
|
56
56
|
|
|
57
57
|
Each protocol owns its commands and its documents, and mints statement seqs in its own lane. Ephemeral subprotocols (`Statewire.Subprotocol("interest", record="ephemeral")`) restart their lane on every attach and carry per-attach documents mounted from handlers via `ctx.attach`. Python hosts support chained compatibility adapters.
|
|
58
58
|
|
|
59
|
-
See the [protocol registration and migration guide](https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/spec/statewire-protocol/protocols/page.mdx).
|
|
59
|
+
See the [protocol registration and migration guide](https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/spec/statewire-protocol/protocols/page.mdx).
|
|
60
60
|
|
|
61
61
|
## Docs
|
|
62
62
|
|
|
63
|
-
- Get started: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/get-started/statewire/page.mdx
|
|
64
|
-
- Guide: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/guides/statewire/host/page.mdx
|
|
65
|
-
- Reference: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/reference/statewire-python/page.mdx
|
|
66
|
-
- Spec: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/spec/statewire-protocol/envelopes/page.mdx
|
|
63
|
+
- Get started: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/get-started/statewire/page.mdx
|
|
64
|
+
- Guide: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/guides/statewire/host/page.mdx
|
|
65
|
+
- Reference: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/reference/statewire-python/page.mdx
|
|
66
|
+
- Spec: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/spec/statewire-protocol/envelopes/page.mdx
|
|
67
67
|
|
|
68
68
|
## Lease context
|
|
69
69
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# statewire
|
|
2
2
|
|
|
3
|
-
The Statewire protocol for Python: a `Statewire` host owns one JSON state dict, streams every change to attached clients as ops, and dispatches typed commands back. Part of [harness-sdk](https://github.com/assistant-ui/harness-sdk), with `harness-sdk` and
|
|
3
|
+
The Statewire protocol for Python: a `Statewire` host owns one JSON state dict, streams every change to attached clients as ops, and dispatches typed commands back. Part of [harness-sdk](https://github.com/assistant-ui/harness-sdk), with `harness-sdk` and Pinboard.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -14,7 +14,7 @@ Extras: `uv add "statewire[langgraph]"`, `uv add "statewire[orjson]"`.
|
|
|
14
14
|
|
|
15
15
|
```python
|
|
16
16
|
from fastapi import FastAPI
|
|
17
|
-
from
|
|
17
|
+
from pinboard import Worker
|
|
18
18
|
from statewire import Statewire, StatewireReject, command
|
|
19
19
|
|
|
20
20
|
class Counter(Statewire):
|
|
@@ -28,7 +28,7 @@ class Counter(Statewire):
|
|
|
28
28
|
raise StatewireReject("the counter is full (max 10)")
|
|
29
29
|
self.state["count"] += 1
|
|
30
30
|
|
|
31
|
-
worker =
|
|
31
|
+
worker = Worker(hosts={"/threads": Counter})
|
|
32
32
|
app = FastAPI()
|
|
33
33
|
app.include_router(worker)
|
|
34
34
|
```
|
|
@@ -39,14 +39,14 @@ Connections negotiate date ranges through `Statewire-Version` and `Statewire-Pro
|
|
|
39
39
|
|
|
40
40
|
Each protocol owns its commands and its documents, and mints statement seqs in its own lane. Ephemeral subprotocols (`Statewire.Subprotocol("interest", record="ephemeral")`) restart their lane on every attach and carry per-attach documents mounted from handlers via `ctx.attach`. Python hosts support chained compatibility adapters.
|
|
41
41
|
|
|
42
|
-
See the [protocol registration and migration guide](https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/spec/statewire-protocol/protocols/page.mdx).
|
|
42
|
+
See the [protocol registration and migration guide](https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/spec/statewire-protocol/protocols/page.mdx).
|
|
43
43
|
|
|
44
44
|
## Docs
|
|
45
45
|
|
|
46
|
-
- Get started: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/get-started/statewire/page.mdx
|
|
47
|
-
- Guide: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/guides/statewire/host/page.mdx
|
|
48
|
-
- Reference: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/reference/statewire-python/page.mdx
|
|
49
|
-
- Spec: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/statewire/docs/spec/statewire-protocol/envelopes/page.mdx
|
|
46
|
+
- Get started: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/get-started/statewire/page.mdx
|
|
47
|
+
- Guide: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/guides/statewire/host/page.mdx
|
|
48
|
+
- Reference: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/reference/statewire-python/page.mdx
|
|
49
|
+
- Spec: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/spec/statewire-protocol/envelopes/page.mdx
|
|
50
50
|
|
|
51
51
|
## Lease context
|
|
52
52
|
|
|
@@ -15,7 +15,7 @@ window), a hard limit that rejects with a message (StatewireSendError), a
|
|
|
15
15
|
import asyncio
|
|
16
16
|
|
|
17
17
|
from fastapi import FastAPI
|
|
18
|
-
from
|
|
18
|
+
from pinboard import Worker
|
|
19
19
|
from statewire import StatewireReject, Statewire, append, command
|
|
20
20
|
|
|
21
21
|
MAX_COUNT = 10
|
|
@@ -61,6 +61,6 @@ class Counter(Statewire):
|
|
|
61
61
|
await asyncio.sleep(0.03)
|
|
62
62
|
|
|
63
63
|
|
|
64
|
-
worker =
|
|
64
|
+
worker = Worker(hosts={"/threads": Counter})
|
|
65
65
|
app = FastAPI()
|
|
66
66
|
app.include_router(worker)
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "statewire"
|
|
3
|
-
version = "0.23.
|
|
3
|
+
version = "0.23.6"
|
|
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
|
-
"
|
|
9
|
+
"pinboard-sdk>=0.18.0",
|
|
10
10
|
"statepatch>=0.3.0,<0.4",
|
|
11
11
|
"fastapi>=0.115",
|
|
12
12
|
"httpx>=0.27",
|
|
@@ -20,7 +20,7 @@ orjson = ["orjson>=3.9"]
|
|
|
20
20
|
Repository = "https://github.com/assistant-ui/harness-sdk"
|
|
21
21
|
|
|
22
22
|
[tool.uv.sources]
|
|
23
|
-
|
|
23
|
+
pinboard-sdk = { workspace = true }
|
|
24
24
|
statepatch = { workspace = true }
|
|
25
25
|
|
|
26
26
|
[build-system]
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Statewire: a
|
|
1
|
+
"""Statewire: a PinboardAPI replicating one JSON object over packet streams.
|
|
2
2
|
|
|
3
3
|
The wire is documented in ``ops``. ``POST /stream`` takes the first client
|
|
4
4
|
frame (``{"cmd": [...]}``) as its body and answers with the
|
|
@@ -56,7 +56,7 @@ handle and whose ``attach`` is the admitting attach's handle (its ephemeral
|
|
|
56
56
|
documents and view), and ``auth_result`` receives the attach resolver's
|
|
57
57
|
typed return snapshotted at command admission. ``ctx.applied()`` states the
|
|
58
58
|
broadcast state now contains the command's effects.
|
|
59
|
-
``authorize`` (inherited from ``
|
|
59
|
+
``authorize`` (inherited from ``PinboardAPI``) gates every attach and
|
|
60
60
|
every subclass ``@route``, and returns the attach auth result (``None`` =
|
|
61
61
|
anonymous). Each attach carries its own auth result; a frame submitted
|
|
62
62
|
under a lease uses that lease's result, and an invalid or dead lease
|
|
@@ -92,10 +92,10 @@ with its attach — ``POST /frames`` must carry a live token in
|
|
|
92
92
|
``Statewire-Lease`` (else 423: re-attach and resend); over WS, holding
|
|
93
93
|
the connection is the lease.
|
|
94
94
|
|
|
95
|
-
Subclass ``@route`` handlers use
|
|
95
|
+
Subclass ``@route`` handlers use Pinboard's route auth boundary: omitted ``auth``
|
|
96
96
|
calls ``authorize``, ``auth=<method>`` selects a bound resolver, and
|
|
97
97
|
``auth=None`` is public. A handler consumes its resolver's return value with
|
|
98
|
-
``Depends(auth_result)`` from ``
|
|
98
|
+
``Depends(auth_result)`` from ``pinboard``. Statewire attach routes use custom
|
|
99
99
|
resolvers; ``prepare(auth_result, conn)`` runs after lifespan and before client
|
|
100
100
|
registration and the snapshot; ``attached(client_id, auth_result, snapshot)``
|
|
101
101
|
runs once the attach is registered, with the encoded hello.
|
|
@@ -142,11 +142,11 @@ from typing import (
|
|
|
142
142
|
)
|
|
143
143
|
|
|
144
144
|
from fastapi import Depends, HTTPException, Request, WebSocket, WebSocketException
|
|
145
|
-
from
|
|
145
|
+
from pinboard import (
|
|
146
146
|
AuthRejected,
|
|
147
147
|
FenceLost,
|
|
148
148
|
HostableContext,
|
|
149
|
-
|
|
149
|
+
PinboardAPI,
|
|
150
150
|
Receipt,
|
|
151
151
|
Tray,
|
|
152
152
|
TrayCtx,
|
|
@@ -155,9 +155,9 @@ from pinned import (
|
|
|
155
155
|
persistent,
|
|
156
156
|
tray,
|
|
157
157
|
)
|
|
158
|
-
from
|
|
159
|
-
from
|
|
160
|
-
from
|
|
158
|
+
from pinboard import metrics as pinned_metrics
|
|
159
|
+
from pinboard.worker.wire import invalid_id_reason
|
|
160
|
+
from pinboard.hosting.routing import route, routes_of
|
|
161
161
|
from starlette.requests import HTTPConnection
|
|
162
162
|
from starlette.responses import JSONResponse, Response, StreamingResponse
|
|
163
163
|
from starlette.websockets import WebSocketDisconnect, WebSocketState
|
|
@@ -222,12 +222,14 @@ ATTACHER_HEADER = ops.ATTACHER_HEADER
|
|
|
222
222
|
RESULT_CACHE_TTL = 30.0
|
|
223
223
|
TRAY_RETIRING_RETRY_MS = 1000
|
|
224
224
|
RESULT_CACHE_LIMIT = 256
|
|
225
|
+
_PARKED_ANSWERS = 64
|
|
225
226
|
MAX_DRAIN_DEPTH = 50
|
|
226
227
|
MAX_JSON_DEPTH = 256
|
|
227
228
|
Handler = Callable[..., Awaitable[Any]]
|
|
228
229
|
|
|
229
230
|
_UNSET: Any = object()
|
|
230
231
|
_UNBOUND: Any = object()
|
|
232
|
+
_ABSENT: Any = object()
|
|
231
233
|
_WS_FIN_ATTEMPTED = "statewire.ws_fin_attempted"
|
|
232
234
|
|
|
233
235
|
|
|
@@ -454,7 +456,7 @@ def _ws_auth_rejected(exc: AuthRejected) -> AuthRejected:
|
|
|
454
456
|
if exc.payload is not None:
|
|
455
457
|
fin.update(_payload_fields(exc.payload))
|
|
456
458
|
payload = {"fin": _load_json(ops.encode_envelope(fin))}
|
|
457
|
-
#
|
|
459
|
+
# Pinboard serializes this payload itself: hand it wire values, not datetimes.
|
|
458
460
|
return AuthRejected(
|
|
459
461
|
exc.message,
|
|
460
462
|
status_code=exc.status_code,
|
|
@@ -666,7 +668,10 @@ class _Group:
|
|
|
666
668
|
class ClientCommands(Tray):
|
|
667
669
|
"""Per-client durable lanes: seq maps each protocol to its admitted-seq
|
|
668
670
|
watermark, the pool holds admitted frames (each one frame's durable
|
|
669
|
-
statements) until they execute.
|
|
671
|
+
statements) until they execute. parked holds ``{protocol, seq, response}``
|
|
672
|
+
of commands answered through ``_settle_parked``: None until the answer
|
|
673
|
+
lands, then kept for the latest ``_PARKED_ANSWERS`` so a redelivered frame
|
|
674
|
+
or a gap-fill reads it. Admission enlists kick (the running
|
|
670
675
|
claim) before the pool append before seq, so no crash point strands or
|
|
671
676
|
loses a pooled frame; the ack heals seq over the popped frame, so a
|
|
672
677
|
crash-cut seq never durably understates an executed frame.
|
|
@@ -679,6 +684,7 @@ class ClientCommands(Tray):
|
|
|
679
684
|
drain_on_eviction = True
|
|
680
685
|
seq = persistent({})
|
|
681
686
|
pool = persistent([])
|
|
687
|
+
parked = persistent([])
|
|
682
688
|
quarantine = persistent([])
|
|
683
689
|
identity = persistent(None)
|
|
684
690
|
identity_through = persistent({})
|
|
@@ -816,6 +822,39 @@ class ClientCommands(Tray):
|
|
|
816
822
|
self._check_above(statements)
|
|
817
823
|
self._advance(statements)
|
|
818
824
|
|
|
825
|
+
def parked_answer(self, protocol: str, seq: int) -> Any:
|
|
826
|
+
"""A parked command's stored answer: None while pending, _ABSENT when not parked."""
|
|
827
|
+
return next(
|
|
828
|
+
(
|
|
829
|
+
p["response"]
|
|
830
|
+
for p in self.parked.value
|
|
831
|
+
if p["protocol"] == protocol and p["seq"] == seq
|
|
832
|
+
),
|
|
833
|
+
_ABSENT,
|
|
834
|
+
)
|
|
835
|
+
|
|
836
|
+
def pooled(self, protocol: str, seq: int) -> bool:
|
|
837
|
+
return any(
|
|
838
|
+
s["protocol"] == protocol and s["seq"] == seq
|
|
839
|
+
for frame in self.pool.value
|
|
840
|
+
for s in _pool_statements(frame)
|
|
841
|
+
)
|
|
842
|
+
|
|
843
|
+
@inbox
|
|
844
|
+
def answer(self, protocol: str, seq: int, response: dict[str, Any]) -> None:
|
|
845
|
+
"""Store a parked or pooled command's answer."""
|
|
846
|
+
kept = [
|
|
847
|
+
p
|
|
848
|
+
for p in self.parked.value
|
|
849
|
+
if not (p["protocol"] == protocol and p["seq"] == seq)
|
|
850
|
+
]
|
|
851
|
+
answered = [p for p in kept if p["response"] is not None]
|
|
852
|
+
stale = answered[: max(0, len(answered) + 1 - _PARKED_ANSWERS)]
|
|
853
|
+
self.parked.value = [
|
|
854
|
+
*(p for p in kept if not any(p is q for q in stale)),
|
|
855
|
+
{"protocol": protocol, "seq": seq, "response": response},
|
|
856
|
+
]
|
|
857
|
+
|
|
819
858
|
@inbox
|
|
820
859
|
def discard(self, frames: list[tuple[str, list[dict[str, Any]]]]) -> None:
|
|
821
860
|
"""Remove held frames; their seqs stay consumed."""
|
|
@@ -910,12 +949,11 @@ class _Lane:
|
|
|
910
949
|
"type": "rejected",
|
|
911
950
|
**_IDENTITY_UNAVAILABLE,
|
|
912
951
|
}
|
|
913
|
-
if tray is
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
return None # pooled, not yet executed: answers ride the stream
|
|
952
|
+
answer = _ABSENT if tray is None else tray.parked_answer(self.protocol, seq)
|
|
953
|
+
if answer is not None and answer is not _ABSENT:
|
|
954
|
+
return {"protocol": self.protocol, "seq": seq, **answer}
|
|
955
|
+
if answer is None or (tray is not None and tray.pooled(self.protocol, seq)):
|
|
956
|
+
return None # pooled or parked: answers ride the stream
|
|
919
957
|
return {"protocol": self.protocol, "seq": seq, "type": "result-unavailable"}
|
|
920
958
|
|
|
921
959
|
def _retain(self, response: dict[str, Any]) -> None:
|
|
@@ -1242,7 +1280,8 @@ def _release_admission(applied: Callable[[], None]) -> None:
|
|
|
1242
1280
|
the caller bounds its parked commands. ``applied`` is the command's
|
|
1243
1281
|
``ctx.applied``; any other callable is ignored. On a durable host the
|
|
1244
1282
|
caller must have durably recorded the command's intent first: a crash
|
|
1245
|
-
after the release no longer redelivers the frame
|
|
1283
|
+
after the release no longer redelivers the frame, and the seq stays
|
|
1284
|
+
pending until ``_settle_parked`` answers it. No-op after applied or
|
|
1246
1285
|
settle."""
|
|
1247
1286
|
ctx = getattr(applied, "__self__", None)
|
|
1248
1287
|
if not isinstance(ctx, StatewireCommandContext):
|
|
@@ -1251,6 +1290,12 @@ def _release_admission(applied: Callable[[], None]) -> None:
|
|
|
1251
1290
|
if inv.applied or inv.settled:
|
|
1252
1291
|
return
|
|
1253
1292
|
inv.parked = True
|
|
1293
|
+
if inv.tray_ctx is not None:
|
|
1294
|
+
commands = inv.tray_ctx.tray
|
|
1295
|
+
commands.parked.value = [
|
|
1296
|
+
*commands.parked.value,
|
|
1297
|
+
{"protocol": inv.lane.protocol, "seq": inv.seq, "response": None},
|
|
1298
|
+
]
|
|
1254
1299
|
inv.finish()
|
|
1255
1300
|
|
|
1256
1301
|
|
|
@@ -1265,6 +1310,48 @@ def _admission_key(applied: Callable[[], None]) -> str | None:
|
|
|
1265
1310
|
return json.dumps([inv.client.id, inv.lane.protocol, inv.seq])
|
|
1266
1311
|
|
|
1267
1312
|
|
|
1313
|
+
async def _settle_parked(host: "Statewire", key: str, response: dict[str, Any]) -> None:
|
|
1314
|
+
"""Internal (harness_sdk's run manager): answer a durable command by its
|
|
1315
|
+
``_admission_key`` and store the answer in its client's ClientCommands
|
|
1316
|
+
row; returns once that write is durable. ``response`` is a
|
|
1317
|
+
``_response_of`` verdict; a command already answered stays as it was."""
|
|
1318
|
+
client_id, protocol, seq = json.loads(key)
|
|
1319
|
+
while True:
|
|
1320
|
+
try:
|
|
1321
|
+
tray = await host.client_commands.get(client_id)
|
|
1322
|
+
except KeyError:
|
|
1323
|
+
return
|
|
1324
|
+
if tray._retirement is None:
|
|
1325
|
+
break
|
|
1326
|
+
await tray._retirement.task
|
|
1327
|
+
stored = tray.parked_answer(protocol, seq)
|
|
1328
|
+
if stored is not _ABSENT and stored is not None:
|
|
1329
|
+
return
|
|
1330
|
+
if stored is _ABSENT and not tray.pooled(protocol, seq):
|
|
1331
|
+
return
|
|
1332
|
+
lane = host._pooled_client(tray).lane(protocol)
|
|
1333
|
+
inv = lane.inflight.get(seq)
|
|
1334
|
+
if inv is not None:
|
|
1335
|
+
host._settle(inv, response)
|
|
1336
|
+
else:
|
|
1337
|
+
lane.settle_late(seq, response)
|
|
1338
|
+
await tray.answer(protocol, seq, response)
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
def _response_of(outcome: Any) -> dict[str, Any]:
|
|
1342
|
+
"""Internal: a handler's return value, or the exception it raised, as its verdict."""
|
|
1343
|
+
if isinstance(outcome, StatewireReject):
|
|
1344
|
+
response: dict[str, Any] = {"type": "rejected", "message": outcome.message}
|
|
1345
|
+
if outcome.code is not None:
|
|
1346
|
+
response["code"] = outcome.code
|
|
1347
|
+
if outcome.payload is not None:
|
|
1348
|
+
response.update(_payload_fields(outcome.payload))
|
|
1349
|
+
return response
|
|
1350
|
+
if isinstance(outcome, BaseException):
|
|
1351
|
+
return {"type": "failed", "message": "the command failed"}
|
|
1352
|
+
return {"type": "accepted", **({} if outcome is None else _payload_fields(outcome))}
|
|
1353
|
+
|
|
1354
|
+
|
|
1268
1355
|
class StatewireReject(Exception):
|
|
1269
1356
|
"""Definitive handler rejection: a ``rejected`` verdict rides ``cmd`` on
|
|
1270
1357
|
the stream, the seq is consumed (no re-run on retry), and message/payload
|
|
@@ -1469,7 +1556,7 @@ def _reserved_paths() -> set[str]:
|
|
|
1469
1556
|
return {spec.path for fn in vars(Statewire).values() for spec in routes_of(fn)}
|
|
1470
1557
|
|
|
1471
1558
|
|
|
1472
|
-
class Statewire(
|
|
1559
|
+
class Statewire(PinboardAPI):
|
|
1473
1560
|
Protocol = Protocol
|
|
1474
1561
|
Subprotocol = Subprotocol
|
|
1475
1562
|
Filter = Filter
|
|
@@ -3458,7 +3545,10 @@ class Statewire(PinnedAPI):
|
|
|
3458
3545
|
}
|
|
3459
3546
|
slots = []
|
|
3460
3547
|
for statement in statements:
|
|
3461
|
-
|
|
3548
|
+
answer = commands_tray.parked_answer(statement["protocol"], statement["seq"])
|
|
3549
|
+
if answer is not None and answer is not _ABSENT:
|
|
3550
|
+
slot = answer
|
|
3551
|
+
elif denied is not None:
|
|
3462
3552
|
slot = dict(denied)
|
|
3463
3553
|
else:
|
|
3464
3554
|
prepared, rejection = self._prepare_member(statement)
|
|
@@ -3602,7 +3692,7 @@ class Statewire(PinnedAPI):
|
|
|
3602
3692
|
seq = statement["seq"]
|
|
3603
3693
|
lane = self._lane(client, lease, statement["protocol"])
|
|
3604
3694
|
if isinstance(slot, dict):
|
|
3605
|
-
#
|
|
3695
|
+
# A static rejection, or a stored answer, consumes its seq.
|
|
3606
3696
|
lane.settle(seq, {"type": "rejected", **slot})
|
|
3607
3697
|
continue
|
|
3608
3698
|
prepared = slot
|
|
@@ -3680,12 +3770,7 @@ class Statewire(PinnedAPI):
|
|
|
3680
3770
|
try:
|
|
3681
3771
|
value = await prepared.handler(*prepared.params, **kwargs)
|
|
3682
3772
|
except StatewireReject as exc:
|
|
3683
|
-
|
|
3684
|
-
if exc.code is not None:
|
|
3685
|
-
response["code"] = exc.code
|
|
3686
|
-
if exc.payload is not None:
|
|
3687
|
-
response.update(_payload_fields(exc.payload))
|
|
3688
|
-
self._settle(inv, response)
|
|
3773
|
+
self._settle(inv, _response_of(exc))
|
|
3689
3774
|
except HTTPException as exc:
|
|
3690
3775
|
detail = (
|
|
3691
3776
|
exc.detail if isinstance(exc.detail, str) else f"HTTP {exc.status_code}"
|
|
@@ -3904,7 +3989,7 @@ class Statewire(PinnedAPI):
|
|
|
3904
3989
|
)
|
|
3905
3990
|
return
|
|
3906
3991
|
except FenceLost:
|
|
3907
|
-
#
|
|
3992
|
+
# Pinboard cancels this stream after releasing the placement.
|
|
3908
3993
|
await asyncio.Future()
|
|
3909
3994
|
except Exception:
|
|
3910
3995
|
logger.exception(
|
|
@@ -5,7 +5,7 @@ from contextlib import asynccontextmanager
|
|
|
5
5
|
|
|
6
6
|
import httpx
|
|
7
7
|
from fastapi import FastAPI
|
|
8
|
-
from
|
|
8
|
+
from pinboard import Lease, PinboardContext, PinboardHost, Worker, RealDomain
|
|
9
9
|
from statewire.api import CLIENT_ID_HEADER, LEASE_HEADER
|
|
10
10
|
from statewire.client import apply_ops as client_apply_ops
|
|
11
11
|
from statewire.protocol import VERSION, headers as protocol_headers, VersionRange, Offer
|
|
@@ -19,7 +19,7 @@ _AUTO = object()
|
|
|
19
19
|
def make_instance(cls, id: str = "t"):
|
|
20
20
|
domain = RealDomain()
|
|
21
21
|
return cls(
|
|
22
|
-
|
|
22
|
+
PinboardContext(
|
|
23
23
|
id,
|
|
24
24
|
lease=Lease(domain=domain),
|
|
25
25
|
abort=lambda: None,
|
|
@@ -31,13 +31,13 @@ def make_instance(cls, id: str = "t"):
|
|
|
31
31
|
|
|
32
32
|
@asynccontextmanager
|
|
33
33
|
async def statewire_app(cls, **host_kwargs):
|
|
34
|
-
host_kwargs.setdefault("worker",
|
|
34
|
+
host_kwargs.setdefault("worker", Worker())
|
|
35
35
|
host_kwargs.setdefault("namespace", "/threads")
|
|
36
|
-
router =
|
|
36
|
+
router = PinboardHost(cls, **host_kwargs)
|
|
37
37
|
app = FastAPI()
|
|
38
38
|
app.include_router(host_kwargs["worker"])
|
|
39
39
|
app.include_router(router)
|
|
40
|
-
app.state.
|
|
40
|
+
app.state.pinboard_host = router
|
|
41
41
|
async with router.lifespan(app):
|
|
42
42
|
yield app
|
|
43
43
|
|
|
@@ -14,8 +14,13 @@ from importlib.metadata import version
|
|
|
14
14
|
from typing import Any
|
|
15
15
|
|
|
16
16
|
from fastapi import HTTPException
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
from pinboard.durability import MemoryStateStore
|
|
20
|
+
from pinboard.testing import instance
|
|
21
|
+
except ImportError: # legacy venvs predate the pinboard-sdk rename
|
|
22
|
+
from pinned.durability import MemoryStateStore
|
|
23
|
+
from pinned.testing import instance
|
|
19
24
|
|
|
20
25
|
from statewire import Statewire, StatewireReject, command
|
|
21
26
|
from statewire.api import _ingest
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"""Contract: a Statewire attach is the connection presence
|
|
1
|
+
"""Contract: a Statewire attach is the connection presence Pinboard's
|
|
2
2
|
no-connections guardrail gates on. A held stream keeps the instance past
|
|
3
3
|
`detached_timeout`; once every client detaches the window runs out, the
|
|
4
4
|
instance evicts through the normal wind-down, and the next attach
|
|
5
5
|
reactivates it fresh."""
|
|
6
6
|
|
|
7
|
-
from
|
|
8
|
-
from
|
|
7
|
+
from pinboard import Worker
|
|
8
|
+
from pinboard.sim import SimDomain
|
|
9
9
|
from statewire import Statewire
|
|
10
10
|
from statewire_helpers import statewire_app, stream_of
|
|
11
11
|
|
|
@@ -29,7 +29,7 @@ def test_attach_presence_gates_the_no_connections_guardrail():
|
|
|
29
29
|
async def main() -> None:
|
|
30
30
|
async with statewire_app(
|
|
31
31
|
Counter,
|
|
32
|
-
worker=
|
|
32
|
+
worker=Worker(domain=sim),
|
|
33
33
|
idle_timeout=FOREVER,
|
|
34
34
|
detached_timeout=3600.0,
|
|
35
35
|
sweep_interval=60.0,
|
|
@@ -64,7 +64,7 @@ async def test_a_raising_attached_hook_fails_the_attach_and_frees_the_slot():
|
|
|
64
64
|
async with statewire_client(Host) as (app, client):
|
|
65
65
|
with pytest.raises(RuntimeError, match="boom"):
|
|
66
66
|
await client.get("/threads/t1/stream", headers={CLIENT_ID_HEADER: "c1"})
|
|
67
|
-
instance = (await app.state.
|
|
67
|
+
instance = (await app.state.pinboard_host.directory.get("t1")).instance
|
|
68
68
|
assert instance._subscribers == {}
|
|
69
69
|
async with stream_of(app, client_id="c1") as stream:
|
|
70
70
|
assert (await stream.next_event())["ops"][0]["value"] == {}
|
|
@@ -12,7 +12,7 @@ from statewire_helpers import (
|
|
|
12
12
|
ws_of,
|
|
13
13
|
)
|
|
14
14
|
from fastapi import HTTPException, Request
|
|
15
|
-
from
|
|
15
|
+
from pinboard import AuthRejected
|
|
16
16
|
|
|
17
17
|
from statewire import Statewire, command
|
|
18
18
|
|
|
@@ -230,7 +230,7 @@ class Identified(Statewire):
|
|
|
230
230
|
|
|
231
231
|
|
|
232
232
|
async def instance_of(app, thread="t1"):
|
|
233
|
-
return (await app.state.
|
|
233
|
+
return (await app.state.pinboard_host.directory.get(thread)).instance
|
|
234
234
|
|
|
235
235
|
|
|
236
236
|
async def whoami_res(app, client, *, seq, headers=None):
|
|
@@ -187,7 +187,7 @@ async def test_commands_are_sequenced_and_dedup_survives_reconnect():
|
|
|
187
187
|
assert transport.attaches >= 2
|
|
188
188
|
assert client.client_id == session_id
|
|
189
189
|
# the server saw exactly seqs 1 and 2 for this session
|
|
190
|
-
instance = (await app.state.
|
|
190
|
+
instance = (await app.state.pinboard_host.directory.get("t1")).instance
|
|
191
191
|
assert instance._clients[session_id].lane("default").last_seq == 2
|
|
192
192
|
|
|
193
193
|
|
|
@@ -470,7 +470,7 @@ async def test_instance_abort_emits_evicted_fin_and_the_client_recovers():
|
|
|
470
470
|
await client.wait_state()
|
|
471
471
|
await client.commands.inc()
|
|
472
472
|
session_id = client.client_id
|
|
473
|
-
app.state.
|
|
473
|
+
app.state.pinboard_host.directory.abort("t1")
|
|
474
474
|
await wait_for(
|
|
475
475
|
lambda: (
|
|
476
476
|
client.state == {"count": 0, "text": ""}
|
|
@@ -30,7 +30,7 @@ class Identified(Statewire):
|
|
|
30
30
|
|
|
31
31
|
|
|
32
32
|
async def instance_of(app, thread="t1"):
|
|
33
|
-
return (await app.state.
|
|
33
|
+
return (await app.state.pinboard_host.directory.get(thread)).instance
|
|
34
34
|
|
|
35
35
|
|
|
36
36
|
async def test_cross_principal_attach_is_403_before_registration():
|
|
@@ -2,8 +2,8 @@ import asyncio
|
|
|
2
2
|
from datetime import datetime, timezone
|
|
3
3
|
|
|
4
4
|
import pytest
|
|
5
|
-
from
|
|
6
|
-
from
|
|
5
|
+
from pinboard import Worker
|
|
6
|
+
from pinboard.testing import MemoryStateStore
|
|
7
7
|
from statewire import Statewire, command
|
|
8
8
|
from statewire.api import _Violation, _parse_frame
|
|
9
9
|
from statewire.document import encode_document
|
|
@@ -165,7 +165,7 @@ async def test_durable_resume_keeps_original_context_after_replacement_and_resta
|
|
|
165
165
|
runs.append(ctx.context)
|
|
166
166
|
|
|
167
167
|
store = MemoryStateStore()
|
|
168
|
-
async with statewire_client(Queued, worker=
|
|
168
|
+
async with statewire_client(Queued, worker=Worker(state_store=store)) as (
|
|
169
169
|
app,
|
|
170
170
|
client,
|
|
171
171
|
):
|
|
@@ -195,7 +195,7 @@ async def test_durable_resume_keeps_original_context_after_replacement_and_resta
|
|
|
195
195
|
"value": {"original": True}
|
|
196
196
|
}
|
|
197
197
|
Queued.gate.set()
|
|
198
|
-
async with statewire_client(Queued, worker=
|
|
198
|
+
async with statewire_client(Queued, worker=Worker(state_store=store)) as (
|
|
199
199
|
app,
|
|
200
200
|
client,
|
|
201
201
|
):
|
|
@@ -17,7 +17,7 @@ class Host(Statewire):
|
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
async def instance_of(app, thread="t1"):
|
|
20
|
-
return (await app.state.
|
|
20
|
+
return (await app.state.pinboard_host.directory.get(thread)).instance
|
|
21
21
|
|
|
22
22
|
|
|
23
23
|
async def test_client_departed_fires_when_the_last_attach_closes():
|