sprigpy 0.1.0.dev1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sprig/__init__.py +52 -0
- sprig/base.py +47 -0
- sprig/client.py +415 -0
- sprig/codegen/__init__.py +1 -0
- sprig/codegen/cli.py +212 -0
- sprig/codegen/python.py +237 -0
- sprig/codegen/render.py +165 -0
- sprig/codegen/templates/bonsai/operators.cs.j2 +151 -0
- sprig/codegen/templates/python/protocol.py.j2 +58 -0
- sprig/envelope.py +138 -0
- sprig/loader.py +42 -0
- sprig/protocol.py +233 -0
- sprig/py.typed +0 -0
- sprig/recording.py +226 -0
- sprig/server.py +322 -0
- sprig/spec.py +497 -0
- sprig/transports/__init__.py +24 -0
- sprig/transports/http.py +180 -0
- sprig/transports/zmq.py +186 -0
- sprig/types.py +29 -0
- sprigpy-0.1.0.dev1.dist-info/METADATA +175 -0
- sprigpy-0.1.0.dev1.dist-info/RECORD +25 -0
- sprigpy-0.1.0.dev1.dist-info/WHEEL +4 -0
- sprigpy-0.1.0.dev1.dist-info/entry_points.txt +2 -0
- sprigpy-0.1.0.dev1.dist-info/licenses/LICENSE +21 -0
sprig/recording.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Recording: everything a server or client sends and receives, as JSON lines, plus the spec that explains it.
|
|
2
|
+
|
|
3
|
+
A recording is one folder per protocol (named after the protocol unless you name it)::
|
|
4
|
+
|
|
5
|
+
<root>/Fip/
|
|
6
|
+
protocol.yml the exact spec the code was generated from: the key to every other file
|
|
7
|
+
session.json who recorded, from where, when (one entry per run with append=True)
|
|
8
|
+
rpc.jsonl requests, replies and errors, in both directions
|
|
9
|
+
<channel>.jsonl one file per channel (events and notifications)
|
|
10
|
+
|
|
11
|
+
Each line is ``{"direction": "in" | "out", "message": <the message as on the wire>}``.
|
|
12
|
+
Python (``Recorder``) and Bonsai (``Record``) write the same layout; ``open_recording`` reads either, with typed
|
|
13
|
+
models built from the recording's own ``protocol.yml``.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import contextlib
|
|
20
|
+
import json
|
|
21
|
+
import types
|
|
22
|
+
import typing as t
|
|
23
|
+
from datetime import datetime
|
|
24
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
from .envelope import Event, Message, Notification, parse_message, utcnow
|
|
28
|
+
from .spec import ALIVE, Direction, Spec, load_spec, spec_text
|
|
29
|
+
|
|
30
|
+
if t.TYPE_CHECKING:
|
|
31
|
+
from .client import Client
|
|
32
|
+
from .server import Server
|
|
33
|
+
|
|
34
|
+
RPC_KINDS = frozenset({"request", "reply", "error"})
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _sprig_version() -> str:
|
|
38
|
+
try:
|
|
39
|
+
return version("sprigpy")
|
|
40
|
+
except PackageNotFoundError:
|
|
41
|
+
return "dev"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Recorder:
|
|
45
|
+
"""Writes a recording of one server or client.
|
|
46
|
+
|
|
47
|
+
``Recorder(root)`` writes to ``root/<protocol>``; ``folder=`` names it. An existing folder is refused unless
|
|
48
|
+
``append=True``. Use ``async with Recorder(root) as rec: rec.attach(client)``.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, root: str | Path, folder: str | None = None, append: bool = False) -> None:
|
|
52
|
+
self.root = Path(root)
|
|
53
|
+
self.folder_name = folder
|
|
54
|
+
self.append = append
|
|
55
|
+
self.path: Path | None = None
|
|
56
|
+
self._files: dict[str, t.TextIO] = {}
|
|
57
|
+
self._tasks: list[asyncio.Task[None]] = []
|
|
58
|
+
self._session: dict[str, t.Any] = {}
|
|
59
|
+
self._endpoint: Server | Client | None = None
|
|
60
|
+
|
|
61
|
+
# -- attaching -------------------------------------------------------------------------------------------
|
|
62
|
+
def attach(self, endpoint: Server | Client) -> Path:
|
|
63
|
+
"""Start recording ``endpoint`` (a Server or a Client). Returns the recording folder."""
|
|
64
|
+
from .client import Client
|
|
65
|
+
from .server import Server
|
|
66
|
+
|
|
67
|
+
if self._endpoint is not None:
|
|
68
|
+
raise RuntimeError("a Recorder records one server or client")
|
|
69
|
+
if isinstance(endpoint, Server):
|
|
70
|
+
spec, side, name, where = endpoint.protocol.spec(), "server", endpoint.name, endpoint.manifest().bound
|
|
71
|
+
elif isinstance(endpoint, Client):
|
|
72
|
+
side, name, where = "client", endpoint.name, endpoint.manifest.bound
|
|
73
|
+
if endpoint.protocol is not None and endpoint.protocol.__protocol_spec__ is not None:
|
|
74
|
+
spec = endpoint.protocol.spec() # the exact text the client was generated from
|
|
75
|
+
else: # only the server's manifest: its normalized form, without what the server filled in
|
|
76
|
+
spec = endpoint.manifest.model_copy(deep=True, update={"bound": {}})
|
|
77
|
+
for op in spec.operations.values():
|
|
78
|
+
op.handled = None
|
|
79
|
+
else:
|
|
80
|
+
raise TypeError(f"can only record a Server or a Client, not {type(endpoint).__name__}")
|
|
81
|
+
self._open(spec, side, name, where, endpoint)
|
|
82
|
+
if isinstance(endpoint, Server):
|
|
83
|
+
for channel in spec.channels: # start from the current state, as a subscribing client would
|
|
84
|
+
retained = endpoint.retained(channel)
|
|
85
|
+
if retained is not None:
|
|
86
|
+
self._tap("out", retained)
|
|
87
|
+
endpoint._taps.append(self._tap)
|
|
88
|
+
if isinstance(endpoint, Client):
|
|
89
|
+
for channel, ch in spec.channels.items():
|
|
90
|
+
if ch.direction is Direction.SERVER_TO_CLIENT:
|
|
91
|
+
self._tasks.append(asyncio.create_task(self._subscribe(endpoint, channel)))
|
|
92
|
+
self._endpoint = endpoint
|
|
93
|
+
assert self.path is not None
|
|
94
|
+
return self.path
|
|
95
|
+
|
|
96
|
+
def _open(self, spec: Spec, side: str, name: str, where: dict[str, str], endpoint: Server | Client) -> None:
|
|
97
|
+
path = self.root / (self.folder_name or spec.protocol)
|
|
98
|
+
if path.exists() and not self.append:
|
|
99
|
+
raise FileExistsError(f"{path} exists; pass append=True to add to it, or another folder name")
|
|
100
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
self.path = path
|
|
102
|
+
spec_file = path / "protocol.yml"
|
|
103
|
+
text = spec_text(spec)
|
|
104
|
+
if spec_file.exists() and load_spec(spec_file).digest() != spec.digest():
|
|
105
|
+
raise ValueError(f"{path} holds a recording of a different spec; record into another folder")
|
|
106
|
+
spec_file.write_text(text, encoding="utf-8", newline="\n")
|
|
107
|
+
session_file = path / "session.json"
|
|
108
|
+
previous = json.loads(session_file.read_text(encoding="utf-8")) if session_file.exists() else {}
|
|
109
|
+
self._session = {
|
|
110
|
+
"sprig": 1,
|
|
111
|
+
"protocol": spec.protocol,
|
|
112
|
+
"version": spec.version,
|
|
113
|
+
"recorder": f"python {_sprig_version()}",
|
|
114
|
+
"side": side,
|
|
115
|
+
"name": name,
|
|
116
|
+
"endpoints": where,
|
|
117
|
+
"runs": [*previous.get("runs", []), {"started": utcnow().isoformat(), "stopped": None}],
|
|
118
|
+
}
|
|
119
|
+
self._write_session()
|
|
120
|
+
|
|
121
|
+
def _write_session(self) -> None:
|
|
122
|
+
assert self.path is not None
|
|
123
|
+
(self.path / "session.json").write_text(json.dumps(self._session, indent=2) + "\n", encoding="utf-8")
|
|
124
|
+
|
|
125
|
+
# -- writing ---------------------------------------------------------------------------------------------
|
|
126
|
+
def _tap(self, direction: str, raw: dict[str, t.Any]) -> None:
|
|
127
|
+
"""Called by the server or client for every message it sends ("out") or receives ("in")."""
|
|
128
|
+
if self.path is None or raw.get("name") == ALIVE:
|
|
129
|
+
return
|
|
130
|
+
kind = raw.get("kind")
|
|
131
|
+
file = "rpc" if kind in RPC_KINDS else str(raw.get("name"))
|
|
132
|
+
line = {"direction": direction, "message": raw}
|
|
133
|
+
handle = self._files.get(file)
|
|
134
|
+
if handle is None:
|
|
135
|
+
handle = self._files[file] = open( # noqa: SIM115 - kept open for the recording, closed in close()
|
|
136
|
+
self.path / f"{file}.jsonl", "a", encoding="utf-8", buffering=1, newline="\n"
|
|
137
|
+
)
|
|
138
|
+
handle.write(json.dumps(line, separators=(",", ":")) + "\n") # line-buffered: a crash loses at most one line
|
|
139
|
+
|
|
140
|
+
async def _subscribe(self, client: Client, channel: str) -> None:
|
|
141
|
+
async for event in client._transport.events(channel):
|
|
142
|
+
self._tap("in", event)
|
|
143
|
+
|
|
144
|
+
# -- closing ---------------------------------------------------------------------------------------------
|
|
145
|
+
async def close(self) -> None:
|
|
146
|
+
for task in self._tasks:
|
|
147
|
+
task.cancel()
|
|
148
|
+
for task in self._tasks:
|
|
149
|
+
with contextlib.suppress(asyncio.CancelledError, Exception):
|
|
150
|
+
await task
|
|
151
|
+
if self._endpoint is not None:
|
|
152
|
+
with contextlib.suppress(ValueError):
|
|
153
|
+
self._endpoint._taps.remove(self._tap)
|
|
154
|
+
if self._session:
|
|
155
|
+
self._session["runs"][-1]["stopped"] = utcnow().isoformat()
|
|
156
|
+
self._write_session()
|
|
157
|
+
for handle in self._files.values():
|
|
158
|
+
handle.close()
|
|
159
|
+
self._files.clear()
|
|
160
|
+
|
|
161
|
+
async def __aenter__(self) -> t.Self:
|
|
162
|
+
return self
|
|
163
|
+
|
|
164
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
165
|
+
await self.close()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class Recording:
|
|
169
|
+
"""A recording folder, read with typed models built from its own protocol.yml."""
|
|
170
|
+
|
|
171
|
+
def __init__(self, path: str | Path) -> None:
|
|
172
|
+
from .loader import load
|
|
173
|
+
|
|
174
|
+
self.path = Path(path)
|
|
175
|
+
self.spec: Spec = load_spec(self.path / "protocol.yml")
|
|
176
|
+
self.session: dict[str, t.Any] = json.loads((self.path / "session.json").read_text(encoding="utf-8"))
|
|
177
|
+
self.module: types.ModuleType = load(self.spec)
|
|
178
|
+
self.protocol = getattr(self.module, self.spec.class_name)
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def files(self) -> list[str]:
|
|
182
|
+
return sorted(p.stem for p in self.path.glob("*.jsonl"))
|
|
183
|
+
|
|
184
|
+
def lines(self, file: str) -> t.Iterator[dict[str, t.Any]]:
|
|
185
|
+
"""The raw lines of one file. A torn last line (the recorder crashed mid-write) is skipped."""
|
|
186
|
+
path = self.path / f"{file}.jsonl"
|
|
187
|
+
if not path.exists():
|
|
188
|
+
return
|
|
189
|
+
with path.open(encoding="utf-8") as handle:
|
|
190
|
+
for text in handle:
|
|
191
|
+
try:
|
|
192
|
+
yield json.loads(text)
|
|
193
|
+
except json.JSONDecodeError:
|
|
194
|
+
continue
|
|
195
|
+
|
|
196
|
+
def channel(self, name: str) -> t.Iterator[Event[t.Any] | Notification[t.Any]]:
|
|
197
|
+
"""Messages on a channel, typed: ``Event[FrameStats]`` (or ``Notification[...]``)."""
|
|
198
|
+
ch = self.spec.channels[name]
|
|
199
|
+
model = getattr(self.module, ch.payload, None) or _builtin(ch.payload)
|
|
200
|
+
kind = Event if ch.direction is Direction.SERVER_TO_CLIENT else Notification
|
|
201
|
+
typed = kind[model]
|
|
202
|
+
for line in self.lines(name):
|
|
203
|
+
yield typed.model_validate(line["message"])
|
|
204
|
+
|
|
205
|
+
def rpc(self) -> t.Iterator[tuple[str, Message[t.Any]]]:
|
|
206
|
+
"""Requests, replies and errors in order, as (direction, message); payloads stay JSON."""
|
|
207
|
+
for line in self.lines("rpc"):
|
|
208
|
+
message = parse_message(line["message"])
|
|
209
|
+
yield line["direction"], message
|
|
210
|
+
|
|
211
|
+
def runs(self) -> list[tuple[datetime, datetime | None]]:
|
|
212
|
+
return [
|
|
213
|
+
(datetime.fromisoformat(r["started"]), datetime.fromisoformat(r["stopped"]) if r["stopped"] else None)
|
|
214
|
+
for r in self.session.get("runs", [])
|
|
215
|
+
]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _builtin(name: str) -> type[t.Any]:
|
|
219
|
+
from . import base, protocol
|
|
220
|
+
|
|
221
|
+
return t.cast(type[t.Any], getattr(base, name, None) or getattr(protocol, name))
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def open_recording(path: str | Path) -> Recording:
|
|
225
|
+
"""Open a recording folder written by Python or Bonsai."""
|
|
226
|
+
return Recording(path)
|
sprig/server.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""Transport-independent server: dispatches requests, publishes events, routes inbound channels."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
import logging
|
|
8
|
+
import typing as t
|
|
9
|
+
from collections import defaultdict
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, ValidationError
|
|
14
|
+
|
|
15
|
+
from .base import SERVER_MANAGED, Heartbeat, Lifecycle, LifecycleState
|
|
16
|
+
from .envelope import (
|
|
17
|
+
ErrorCode,
|
|
18
|
+
ErrorInfo,
|
|
19
|
+
ErrorReply,
|
|
20
|
+
Event,
|
|
21
|
+
Notification,
|
|
22
|
+
Reply,
|
|
23
|
+
Request,
|
|
24
|
+
dump,
|
|
25
|
+
new_id,
|
|
26
|
+
parse_message,
|
|
27
|
+
utcnow,
|
|
28
|
+
)
|
|
29
|
+
from .protocol import Channel, Direction, Protocol, ProtocolError, Rpc
|
|
30
|
+
from .spec import ALIVE, DESCRIBE, HEARTBEAT, LIFECYCLE, Spec
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
TReq = t.TypeVar("TReq", bound=BaseModel)
|
|
35
|
+
TRep = t.TypeVar("TRep", bound=BaseModel)
|
|
36
|
+
TPay = t.TypeVar("TPay", bound=BaseModel)
|
|
37
|
+
|
|
38
|
+
Handler: t.TypeAlias = t.Callable[[Request[TReq]], TRep | t.Awaitable[TRep]]
|
|
39
|
+
|
|
40
|
+
__all__ = ["RpcFault", "Server", "ServerTransport", "new_id"]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RpcFault(Exception):
|
|
44
|
+
"""Raise from a handler to return one of the operation's declared errors."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, error: BaseModel, message: str | None = None) -> None:
|
|
47
|
+
super().__init__(message or type(error).__name__)
|
|
48
|
+
self.error = error
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ServerTransport(t.Protocol):
|
|
52
|
+
async def start(self, server: Server) -> None: ...
|
|
53
|
+
async def stop(self) -> None: ...
|
|
54
|
+
async def send_event(self, event: dict[str, t.Any]) -> None: ...
|
|
55
|
+
def endpoints(self) -> dict[str, str]: ...
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
MISSED_HEARTBEATS = 3
|
|
59
|
+
"""Heartbeat periods of silence before a server marks a client gone (and a client marks a server lost)."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class ClientInfo:
|
|
64
|
+
"""A client as the server last heard from it."""
|
|
65
|
+
|
|
66
|
+
name: str
|
|
67
|
+
last_seen: datetime
|
|
68
|
+
alive: bool
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Server:
|
|
72
|
+
"""Serves a protocol. For protocols built on ``BaseProtocol`` it also, without user code: announces
|
|
73
|
+
``lifecycle`` started/stopping, re-sends the heartbeat status every ``heartbeat_period`` seconds, and answers requests still running at stop
|
|
74
|
+
(``server_stopped``).
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self, protocol: type[Protocol], name: str | None = None, timeout: float = 10.0, heartbeat_period: float = 1.0
|
|
79
|
+
) -> None:
|
|
80
|
+
self.protocol = protocol
|
|
81
|
+
self.name = name or protocol.__protocol_name__ or protocol.__name__
|
|
82
|
+
self.timeout = timeout
|
|
83
|
+
self.heartbeat_period = heartbeat_period
|
|
84
|
+
self.instance = new_id()
|
|
85
|
+
self._status = Heartbeat()
|
|
86
|
+
self._heartbeat_task: asyncio.Task[None] | None = None
|
|
87
|
+
self._last_seen: dict[str, datetime] = {}
|
|
88
|
+
self._taps: list[t.Callable[[str, dict[str, t.Any]], None]] = [] # recorders: (direction, message)
|
|
89
|
+
self._handlers: dict[str, Handler[t.Any, t.Any]] = {}
|
|
90
|
+
self._seq: dict[str, int] = defaultdict(int)
|
|
91
|
+
self._retained: dict[str, dict[str, t.Any]] = {}
|
|
92
|
+
self._inbound: dict[str, list[asyncio.Queue[Notification[t.Any]]]] = defaultdict(list)
|
|
93
|
+
self._transports: list[ServerTransport] = []
|
|
94
|
+
|
|
95
|
+
# -- declaring handlers -------------------------------------------------
|
|
96
|
+
def handle(self, operation: Rpc[TReq, TRep]) -> t.Callable[[Handler[TReq, TRep]], Handler[TReq, TRep]]:
|
|
97
|
+
"""Register the handler of ``operation``: ``@server.handle(FipProtocol.start)``."""
|
|
98
|
+
op = self._operation(operation)
|
|
99
|
+
|
|
100
|
+
def register(fn: Handler[TReq, TRep]) -> Handler[TReq, TRep]:
|
|
101
|
+
if op.name in self._handlers:
|
|
102
|
+
raise ProtocolError(f"'{op.name}' already has a handler")
|
|
103
|
+
self._handlers[op.name] = fn
|
|
104
|
+
return fn
|
|
105
|
+
|
|
106
|
+
return register
|
|
107
|
+
|
|
108
|
+
def _operation(self, operation: Rpc[t.Any, t.Any] | str) -> Rpc[t.Any, t.Any]:
|
|
109
|
+
name = operation if isinstance(operation, str) else operation.name
|
|
110
|
+
op = self.protocol.__operations__.get(name)
|
|
111
|
+
if op is None or (not isinstance(operation, str) and op != operation):
|
|
112
|
+
raise ProtocolError(f"{self.protocol.__name__} has no operation {name!r}")
|
|
113
|
+
return op
|
|
114
|
+
|
|
115
|
+
def _channel(self, channel: Channel[t.Any] | str) -> Channel[t.Any]:
|
|
116
|
+
name = channel if isinstance(channel, str) else channel.name
|
|
117
|
+
ch = self.protocol.__channels__.get(name)
|
|
118
|
+
if ch is None or (not isinstance(channel, str) and ch != channel):
|
|
119
|
+
raise ProtocolError(f"{self.protocol.__name__} has no channel {name!r}")
|
|
120
|
+
return ch
|
|
121
|
+
|
|
122
|
+
def manifest(self) -> Spec:
|
|
123
|
+
"""The protocol's spec with ``handled`` per operation and the addresses bound (what ``describe`` returns)."""
|
|
124
|
+
m = self.protocol.spec().model_copy(deep=True)
|
|
125
|
+
for name, op in m.operations.items():
|
|
126
|
+
op.handled = name in self._handlers
|
|
127
|
+
for tr in self._transports:
|
|
128
|
+
m.bound.update(tr.endpoints())
|
|
129
|
+
return m
|
|
130
|
+
|
|
131
|
+
# -- lifecycle ----------------------------------------------------------
|
|
132
|
+
async def start(self, *transports: ServerTransport) -> None:
|
|
133
|
+
missing = set(self.protocol.__operations__) - set(self._handlers)
|
|
134
|
+
if missing:
|
|
135
|
+
# Allowed, as in Bonsai: callers get method_not_found and describe says handled: false.
|
|
136
|
+
logger.warning("%s: no handler for %s; callers get method_not_found", self.name, ", ".join(sorted(missing)))
|
|
137
|
+
for tr in transports:
|
|
138
|
+
await tr.start(self)
|
|
139
|
+
self._transports.append(tr)
|
|
140
|
+
if self._managed:
|
|
141
|
+
await self._publish(LIFECYCLE, self._lifecycle(LifecycleState.STARTED))
|
|
142
|
+
await self._publish(HEARTBEAT, self._status)
|
|
143
|
+
if self.heartbeat_period > 0:
|
|
144
|
+
self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
|
|
145
|
+
|
|
146
|
+
async def stop(self) -> None:
|
|
147
|
+
if self._heartbeat_task is not None:
|
|
148
|
+
self._heartbeat_task.cancel()
|
|
149
|
+
self._heartbeat_task = None
|
|
150
|
+
if self._managed and self._transports:
|
|
151
|
+
await self._publish(LIFECYCLE, self._lifecycle(LifecycleState.STOPPING))
|
|
152
|
+
for tr in self._transports:
|
|
153
|
+
await tr.stop() # answers requests still running with server_stopped, flushes, closes
|
|
154
|
+
self._transports.clear()
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def _managed(self) -> bool:
|
|
158
|
+
return LIFECYCLE in self.protocol.__channels__ and HEARTBEAT in self.protocol.__channels__
|
|
159
|
+
|
|
160
|
+
def _lifecycle(self, state: LifecycleState) -> Lifecycle:
|
|
161
|
+
return Lifecycle(state=state, instance=self.instance, heartbeat_period_s=self.heartbeat_period)
|
|
162
|
+
|
|
163
|
+
async def _heartbeat_loop(self) -> None:
|
|
164
|
+
while True:
|
|
165
|
+
await asyncio.sleep(self.heartbeat_period)
|
|
166
|
+
await self._publish(HEARTBEAT, self._status)
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def clients(self) -> dict[str, ClientInfo]:
|
|
170
|
+
"""Clients heard from, by name, and whether each is alive (heard within 3 heartbeat periods). Internal state:
|
|
171
|
+
nothing is published."""
|
|
172
|
+
now = utcnow()
|
|
173
|
+
window = MISSED_HEARTBEATS * self.heartbeat_period
|
|
174
|
+
return {
|
|
175
|
+
name: ClientInfo(name, seen, window <= 0 or (now - seen).total_seconds() <= window)
|
|
176
|
+
for name, seen in self._last_seen.items()
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
def _seen(self, source: str) -> None:
|
|
180
|
+
if source:
|
|
181
|
+
self._last_seen[source] = utcnow()
|
|
182
|
+
|
|
183
|
+
def stopped_error(self, id_: str, name: str) -> dict[str, t.Any]:
|
|
184
|
+
"""The error sent to a request still running when the server stops."""
|
|
185
|
+
return self._error(id_, name, ErrorCode.SERVER_STOPPED, "the server stopped before answering")
|
|
186
|
+
|
|
187
|
+
# -- request/reply ------------------------------------------------------
|
|
188
|
+
def _tapped(self, direction: str, raw: t.Any) -> None:
|
|
189
|
+
if isinstance(raw, dict):
|
|
190
|
+
for tap in self._taps:
|
|
191
|
+
try:
|
|
192
|
+
tap(direction, raw)
|
|
193
|
+
except Exception:
|
|
194
|
+
logger.exception("recorder failed")
|
|
195
|
+
|
|
196
|
+
async def dispatch(self, raw: t.Any) -> dict[str, t.Any]:
|
|
197
|
+
"""Answer one request envelope. Always returns exactly one reply or error envelope."""
|
|
198
|
+
self._tapped("in", raw)
|
|
199
|
+
reply = await self._dispatch(raw)
|
|
200
|
+
self._tapped("out", reply)
|
|
201
|
+
return reply
|
|
202
|
+
|
|
203
|
+
async def _dispatch(self, raw: t.Any) -> dict[str, t.Any]:
|
|
204
|
+
try:
|
|
205
|
+
req = parse_message(raw)
|
|
206
|
+
except ValidationError as e:
|
|
207
|
+
fallback = raw if isinstance(raw, dict) else {}
|
|
208
|
+
return self._error(
|
|
209
|
+
str(fallback.get("id", "?")), str(fallback.get("name", "?")), ErrorCode.INVALID_PARAMS, str(e)
|
|
210
|
+
)
|
|
211
|
+
self._seen(req.source)
|
|
212
|
+
if not isinstance(req, Request):
|
|
213
|
+
return self._error(
|
|
214
|
+
getattr(req, "id", "?"), req.name, ErrorCode.INVALID_PARAMS, f"expected a request, got {req.kind}"
|
|
215
|
+
)
|
|
216
|
+
if req.name == DESCRIBE:
|
|
217
|
+
return dump(
|
|
218
|
+
Reply(name=req.name, id=req.id, source=self.name, payload=self.manifest().model_dump(mode="json"))
|
|
219
|
+
)
|
|
220
|
+
op = self.protocol.__operations__.get(req.name)
|
|
221
|
+
handler = self._handlers.get(req.name)
|
|
222
|
+
if op is None or handler is None:
|
|
223
|
+
return self._error(req.id, req.name, ErrorCode.METHOD_NOT_FOUND, f"no operation '{req.name}'")
|
|
224
|
+
try:
|
|
225
|
+
typed = req.model_copy(update={"payload": op.request.model_validate(req.payload)})
|
|
226
|
+
except ValidationError as e:
|
|
227
|
+
return self._error(
|
|
228
|
+
req.id, req.name, ErrorCode.INVALID_PARAMS, "invalid params", e.errors(include_url=False)
|
|
229
|
+
)
|
|
230
|
+
try:
|
|
231
|
+
result = handler(typed)
|
|
232
|
+
if inspect.isawaitable(result):
|
|
233
|
+
result = await asyncio.wait_for(result, self.timeout)
|
|
234
|
+
if not isinstance(result, op.reply):
|
|
235
|
+
result = op.reply.model_validate(result)
|
|
236
|
+
except RpcFault as f:
|
|
237
|
+
if type(f.error) not in op.errors:
|
|
238
|
+
logger.error("%s raised undeclared error %s", op.name, type(f.error).__name__)
|
|
239
|
+
return self._error(
|
|
240
|
+
req.id, req.name, ErrorCode.INTERNAL_ERROR, f"undeclared error {type(f.error).__name__}"
|
|
241
|
+
)
|
|
242
|
+
return self._error(req.id, req.name, type(f.error).__name__, str(f), f.error.model_dump(mode="json"))
|
|
243
|
+
except TimeoutError:
|
|
244
|
+
return self._error(req.id, req.name, ErrorCode.TIMEOUT, f"no reply within {self.timeout} s")
|
|
245
|
+
except Exception as e:
|
|
246
|
+
logger.exception("handler %s failed", op.name)
|
|
247
|
+
return self._error(req.id, req.name, ErrorCode.INTERNAL_ERROR, repr(e))
|
|
248
|
+
return dump(Reply(name=req.name, id=req.id, source=self.name, payload=result))
|
|
249
|
+
|
|
250
|
+
def _error(self, id_: str, name: str, code: str, message: str, data: t.Any = None) -> dict[str, t.Any]:
|
|
251
|
+
info = ErrorInfo(code=code, message=message, data=data)
|
|
252
|
+
return dump(ErrorReply(name=name, id=id_, source=self.name, payload=info))
|
|
253
|
+
|
|
254
|
+
# -- server-to-client channels -------------------------------------------
|
|
255
|
+
@t.overload
|
|
256
|
+
async def publish(self, channel: Channel[TPay], payload: TPay) -> None: ...
|
|
257
|
+
@t.overload
|
|
258
|
+
async def publish(self, channel: str, payload: BaseModel | dict[str, t.Any]) -> None: ...
|
|
259
|
+
async def publish(self, channel: Channel[t.Any] | str, payload: BaseModel | dict[str, t.Any]) -> None:
|
|
260
|
+
ch = self._channel(channel)
|
|
261
|
+
if ch.name in SERVER_MANAGED:
|
|
262
|
+
raise ProtocolError(f"'{ch.name}' is published by the server automatically")
|
|
263
|
+
if ch.direction is not Direction.SERVER_TO_CLIENT:
|
|
264
|
+
raise ProtocolError(f"'{ch.name}' is {ch.direction}; the server cannot publish to it")
|
|
265
|
+
await self._publish(ch.name, payload)
|
|
266
|
+
|
|
267
|
+
async def _publish(self, name: str, payload: BaseModel | dict[str, t.Any]) -> None:
|
|
268
|
+
ch = self.protocol.__channels__[name]
|
|
269
|
+
model = payload if isinstance(payload, ch.payload) else ch.payload.model_validate(payload)
|
|
270
|
+
if ch.name == HEARTBEAT:
|
|
271
|
+
self._status = t.cast(Heartbeat, model) # the status the heartbeat loop keeps re-sending
|
|
272
|
+
self._seq[ch.name] += 1
|
|
273
|
+
event = dump(Event(name=ch.name, seq=self._seq[ch.name], source=self.name, payload=model))
|
|
274
|
+
if ch.retain_last:
|
|
275
|
+
self._retained[ch.name] = event
|
|
276
|
+
self._tapped("out", event)
|
|
277
|
+
for tr in self._transports:
|
|
278
|
+
await tr.send_event(event)
|
|
279
|
+
|
|
280
|
+
def retained(self, channel: str) -> dict[str, t.Any] | None:
|
|
281
|
+
return self._retained.get(channel)
|
|
282
|
+
|
|
283
|
+
# -- client-to-server channels -------------------------------------------
|
|
284
|
+
@t.overload
|
|
285
|
+
def receive(self, channel: Channel[TPay]) -> t.AsyncIterator[Notification[TPay]]: ...
|
|
286
|
+
@t.overload
|
|
287
|
+
def receive(self, channel: str) -> t.AsyncIterator[Notification[t.Any]]: ...
|
|
288
|
+
def receive(self, channel: Channel[t.Any] | str) -> t.AsyncIterator[Notification[t.Any]]:
|
|
289
|
+
ch = self._channel(channel)
|
|
290
|
+
if ch.direction is not Direction.CLIENT_TO_SERVER:
|
|
291
|
+
raise ProtocolError(f"'{ch.name}' is not a client-to-server channel")
|
|
292
|
+
queue: asyncio.Queue[Notification[t.Any]] = asyncio.Queue()
|
|
293
|
+
self._inbound[ch.name].append(queue)
|
|
294
|
+
|
|
295
|
+
async def gen() -> t.AsyncIterator[Notification[t.Any]]:
|
|
296
|
+
try:
|
|
297
|
+
while True:
|
|
298
|
+
yield await queue.get()
|
|
299
|
+
finally:
|
|
300
|
+
self._inbound[ch.name].remove(queue)
|
|
301
|
+
|
|
302
|
+
return gen()
|
|
303
|
+
|
|
304
|
+
async def on_notification(self, raw: t.Any) -> None:
|
|
305
|
+
if isinstance(raw, dict):
|
|
306
|
+
self._seen(str(raw.get("source", "")))
|
|
307
|
+
if raw.get("name") == ALIVE:
|
|
308
|
+
return # a sign of life, nothing more
|
|
309
|
+
self._tapped("in", raw)
|
|
310
|
+
try:
|
|
311
|
+
note = parse_message(raw)
|
|
312
|
+
if not isinstance(note, Notification):
|
|
313
|
+
raise ProtocolError(f"expected a notification, got {note.kind}")
|
|
314
|
+
ch = self._channel(note.name)
|
|
315
|
+
if ch.direction is not Direction.CLIENT_TO_SERVER:
|
|
316
|
+
raise ProtocolError(f"'{note.name}' is not client-to-server")
|
|
317
|
+
typed = note.model_copy(update={"payload": ch.payload.model_validate(note.payload)})
|
|
318
|
+
except (ValidationError, ProtocolError) as e:
|
|
319
|
+
logger.warning("dropped invalid notification: %s", e)
|
|
320
|
+
return
|
|
321
|
+
for q in self._inbound[note.name]:
|
|
322
|
+
q.put_nowait(typed)
|