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 ADDED
@@ -0,0 +1,52 @@
1
+ """sprig: request/reply and pub/sub protocols written as YAML specs, for Python and Bonsai."""
2
+
3
+ from .base import BaseProtocol, Heartbeat, HeartbeatCode, Lifecycle, LifecycleState
4
+ from .client import Client, ParamsError, RemoteError, Subscription, connect
5
+ from .envelope import ErrorCode, ErrorInfo, ErrorReply, Event, Message, MessageKind, Notification, Reply, Request
6
+ from .loader import load
7
+ from .protocol import Channel, Direction, Empty, Model, Protocol, ProtocolError, Rpc, channel, rpc
8
+ from .recording import Recorder, Recording, open_recording
9
+ from .server import RpcFault, Server
10
+ from .spec import Spec, SpecError, load_spec
11
+ from .types import Bytes
12
+
13
+ __all__ = [
14
+ "BaseProtocol",
15
+ "Bytes",
16
+ "Channel",
17
+ "Client",
18
+ "Direction",
19
+ "Empty",
20
+ "ErrorCode",
21
+ "ErrorInfo",
22
+ "ErrorReply",
23
+ "Event",
24
+ "Heartbeat",
25
+ "HeartbeatCode",
26
+ "Lifecycle",
27
+ "LifecycleState",
28
+ "Message",
29
+ "MessageKind",
30
+ "Model",
31
+ "Notification",
32
+ "ParamsError",
33
+ "Protocol",
34
+ "ProtocolError",
35
+ "Recorder",
36
+ "Recording",
37
+ "RemoteError",
38
+ "Reply",
39
+ "Request",
40
+ "Rpc",
41
+ "RpcFault",
42
+ "Server",
43
+ "Spec",
44
+ "SpecError",
45
+ "Subscription",
46
+ "channel",
47
+ "connect",
48
+ "load",
49
+ "load_spec",
50
+ "open_recording",
51
+ "rpc",
52
+ ]
sprig/base.py ADDED
@@ -0,0 +1,47 @@
1
+ """The channels every protocol carries. Servers and clients manage both; users only set the heartbeat status."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import enum
6
+
7
+ from pydantic import Field
8
+
9
+ from .protocol import Channel, Model, Protocol, channel
10
+ from .spec import LIFECYCLE
11
+
12
+
13
+ class HeartbeatCode(enum.IntEnum):
14
+ OK = 0
15
+ WARNING = 1
16
+ ERROR = 2
17
+ CRITICAL = 3
18
+
19
+
20
+ class Heartbeat(Model):
21
+ code: HeartbeatCode = HeartbeatCode.OK
22
+ message: str = ""
23
+
24
+
25
+ class LifecycleState(enum.StrEnum):
26
+ STARTED = "started" # published by the server when it starts
27
+ STOPPING = "stopping" # published by the server when it stops
28
+ LOST = "lost" # added by a client when heartbeats stop arriving
29
+
30
+
31
+ class Lifecycle(Model):
32
+ state: LifecycleState
33
+ instance: str = Field(description="Unique per server run; a new value means the server restarted")
34
+ heartbeat_period_s: float = Field(description="How often the server sends a heartbeat; 0 for never")
35
+
36
+
37
+ class BaseProtocol(Protocol):
38
+ heartbeat: Channel[Heartbeat] = channel(
39
+ retain_last=True, description="Health code and message, re-sent every heartbeat period"
40
+ )
41
+ lifecycle: Channel[Lifecycle] = channel(
42
+ retain_last=True, description="Server started or stopping; clients add 'lost' when heartbeats stop"
43
+ )
44
+
45
+
46
+ # Published by the server itself; user code cannot publish to these.
47
+ SERVER_MANAGED = frozenset({LIFECYCLE})
sprig/client.py ADDED
@@ -0,0 +1,415 @@
1
+ """Client of a running server.
2
+
3
+ ``await connect(url, FipProtocol)`` asks the server to ``describe`` itself, checks the protocol and major
4
+ version, and returns a client: ``invoke(FipProtocol.start, StartRequest(...))``,
5
+ ``listen(FipProtocol.frames)``, ``send(FipProtocol.led_power, LedPower(...))``. Results are messages
6
+ (``Reply[StartReply]``, ``Event[FrameStats]``) with their header.
7
+
8
+ Without the generated code, ``client.module`` builds the same classes from the server's manifest.
9
+ Values are checked against the manifest's JSON Schema before sending.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import contextlib
16
+ import logging
17
+ import types
18
+ import typing as t
19
+ from collections import defaultdict
20
+ from urllib.parse import urlparse
21
+
22
+ import jsonschema
23
+ from pydantic import BaseModel
24
+
25
+ from .base import Lifecycle
26
+ from .envelope import (
27
+ ErrorCode,
28
+ ErrorInfo,
29
+ ErrorReply,
30
+ Event,
31
+ Notification,
32
+ RemoteError,
33
+ Reply,
34
+ Request,
35
+ dump,
36
+ new_id,
37
+ parse_message,
38
+ )
39
+
40
+ __all__ = ["Client", "ParamsError", "RemoteError", "Subscription", "connect"]
41
+ from .loader import load
42
+ from .protocol import Channel, Direction, Protocol, Rpc
43
+ from .spec import ALIVE, DESCRIBE, HEARTBEAT, LIFECYCLE, Spec, load_spec
44
+ from .transports.zmq import ZmqClientTransport
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ T = t.TypeVar("T")
49
+ TReq = t.TypeVar("TReq", bound=BaseModel)
50
+ TRep = t.TypeVar("TRep", bound=BaseModel)
51
+ TPay = t.TypeVar("TPay", bound=BaseModel)
52
+
53
+
54
+ class ParamsError(ValueError):
55
+ """Arguments did not match the schema (caught before sending)."""
56
+
57
+
58
+ class _Validator:
59
+ def __init__(self, manifest: Spec) -> None:
60
+ self._manifest = manifest
61
+ self._cache: dict[str, jsonschema.protocols.Validator] = {}
62
+
63
+ def check(self, label: str, type_name: str, value: t.Any) -> None:
64
+ v = self._cache.get(type_name)
65
+ if v is None:
66
+ v = self._cache[type_name] = jsonschema.Draft202012Validator(self._manifest.type_schema(type_name))
67
+ problems = [f"{'.'.join(map(str, e.absolute_path)) or '<root>'}: {e.message}" for e in v.iter_errors(value)]
68
+ if problems:
69
+ raise ParamsError(f"{label}({type_name}): " + "; ".join(problems))
70
+
71
+
72
+ class Subscription(t.Generic[T]):
73
+ """Async iterator over a channel. Drops duplicate seqs and counts gaps."""
74
+
75
+ def __init__(
76
+ self,
77
+ events: t.AsyncIterator[dict[str, t.Any]],
78
+ convert: t.Callable[[dict[str, t.Any]], T],
79
+ dedupe: bool = True,
80
+ ) -> None:
81
+ self._events = events
82
+ self._convert = convert
83
+ self._dedupe = dedupe
84
+ self.last_seq = 0
85
+ self.dropped = 0
86
+
87
+ def __aiter__(self) -> Subscription[T]:
88
+ return self
89
+
90
+ async def __anext__(self) -> T:
91
+ while True:
92
+ event = await self._events.__anext__()
93
+ if not self._dedupe:
94
+ return self._convert(event)
95
+ seq = event["seq"]
96
+ if seq <= self.last_seq:
97
+ continue # replayed retained value we already have
98
+ if self.last_seq and seq > self.last_seq + 1:
99
+ self.dropped += seq - self.last_seq - 1
100
+ logger.warning("%s: missed %d event(s)", event["name"], seq - self.last_seq - 1)
101
+ self.last_seq = seq
102
+ return self._convert(event)
103
+
104
+ async def first(self, predicate: t.Callable[[T], bool] = lambda _: True, timeout: float | None = None) -> T:
105
+ async def scan() -> T:
106
+ async for value in self:
107
+ if predicate(value):
108
+ return value
109
+ raise StopAsyncIteration
110
+
111
+ try:
112
+ return await asyncio.wait_for(scan(), timeout)
113
+ finally:
114
+ await self.aclose()
115
+
116
+ async def aclose(self) -> None:
117
+ aclose = getattr(self._events, "aclose", None)
118
+ if aclose is not None:
119
+ await aclose()
120
+
121
+
122
+ class _Monitor:
123
+ """Watches a server's ``lifecycle`` and ``heartbeat`` channels for the client.
124
+
125
+ Keeps the latest lifecycle, and reports ``lost`` on the lifecycle channel when no heartbeat arrives for
126
+ ``misses`` heartbeat periods. When heartbeats resume from the same server instance, it reports the server's
127
+ last lifecycle again; a restarted server announces itself with a new instance.
128
+ """
129
+
130
+ def __init__(self, client: Client, misses: int = 3) -> None:
131
+ self._client = client
132
+ self._misses = misses
133
+ self._listeners: set[asyncio.Queue[dict[str, t.Any]]] = set()
134
+ self._latest: dict[str, t.Any] | None = None # latest lifecycle event, server's or synthesized
135
+ self._server_latest: dict[str, t.Any] | None = None
136
+ self._last_beat = 0.0
137
+ self.lost = False
138
+ self._tasks: list[asyncio.Task[None]] = []
139
+
140
+ def start(self) -> None:
141
+ self._tasks = [
142
+ asyncio.create_task(self._watch_lifecycle()),
143
+ asyncio.create_task(self._watch_heartbeat()),
144
+ asyncio.create_task(self._watchdog()),
145
+ asyncio.create_task(self._keepalive()),
146
+ ]
147
+
148
+ async def stop(self) -> None:
149
+ for task in self._tasks:
150
+ task.cancel()
151
+ for task in self._tasks:
152
+ with contextlib.suppress(asyncio.CancelledError, Exception):
153
+ await task
154
+
155
+ @property
156
+ def latest(self) -> dict[str, t.Any] | None:
157
+ return self._latest
158
+
159
+ def listen(self) -> t.AsyncIterator[dict[str, t.Any]]:
160
+ queue: asyncio.Queue[dict[str, t.Any]] = asyncio.Queue()
161
+ if self._latest is not None:
162
+ queue.put_nowait(self._latest)
163
+ self._listeners.add(queue)
164
+
165
+ async def gen() -> t.AsyncIterator[dict[str, t.Any]]:
166
+ try:
167
+ while True:
168
+ yield await queue.get()
169
+ finally:
170
+ self._listeners.discard(queue)
171
+
172
+ return gen()
173
+
174
+ def _emit(self, event: dict[str, t.Any]) -> None:
175
+ self._latest = event
176
+ for queue in self._listeners:
177
+ queue.put_nowait(event)
178
+
179
+ def _now(self) -> float:
180
+ return asyncio.get_running_loop().time()
181
+
182
+ async def _watch_lifecycle(self) -> None:
183
+ async for event in self._client._transport.events(LIFECYCLE):
184
+ last = self._server_latest
185
+ if last is not None and (last["source"], last["seq"]) == (event["source"], event["seq"]):
186
+ continue # retained value re-sent on reconnect
187
+ self._server_latest = event
188
+ self._last_beat = self._now()
189
+ self.lost = False
190
+ self._emit(event)
191
+
192
+ def _period(self) -> float:
193
+ """The server's heartbeat period; a short poll until its lifecycle says it (or if it sends none)."""
194
+ server = self._server_latest
195
+ period = float(server["payload"]["HeartbeatPeriodS"]) if server else 0.0
196
+ return period if period > 0 else 0.25
197
+
198
+ async def _keepalive(self) -> None:
199
+ while True:
200
+ await asyncio.sleep(self._period())
201
+ if self._server_latest is None:
202
+ continue # not connected yet
203
+ note = Notification[t.Any](name=ALIVE, source=self._client.name, payload={})
204
+ with contextlib.suppress(Exception): # the server may be gone; the watchdog reports that
205
+ await asyncio.wait_for(self._client._transport.notify(dump(note)), self._period())
206
+
207
+ async def _watch_heartbeat(self) -> None:
208
+ async for _event in self._client._transport.events(HEARTBEAT):
209
+ self._last_beat = self._now()
210
+ if self.lost and self._server_latest is not None:
211
+ self.lost = False
212
+ self._emit(self._server_latest) # the same instance is back
213
+
214
+ async def _watchdog(self) -> None:
215
+ while True:
216
+ server = self._server_latest
217
+ period = float(server["payload"]["HeartbeatPeriodS"]) if server else 0.0
218
+ await asyncio.sleep(period / 2 if period > 0 else 0.5)
219
+ if server is None or period <= 0 or self.lost:
220
+ continue
221
+ if server["payload"]["State"] != "started":
222
+ continue # stopping on purpose is not lost
223
+ if self._now() - self._last_beat > self._misses * period:
224
+ self.lost = True
225
+ self._emit(
226
+ dump(
227
+ Event[t.Any](
228
+ name=LIFECYCLE,
229
+ seq=server["seq"],
230
+ source=self._client.name,
231
+ payload={**server["payload"], "State": "lost"},
232
+ )
233
+ )
234
+ )
235
+
236
+
237
+ class Client:
238
+ def __init__(
239
+ self, transport: t.Any, manifest: Spec, protocol: type[Protocol] | None, timeout: float, name: str
240
+ ) -> None:
241
+ self._transport = transport
242
+ self.manifest = manifest
243
+ self.protocol = protocol
244
+ self.timeout = timeout
245
+ self.name = name
246
+ managed = LIFECYCLE in manifest.channels and HEARTBEAT in manifest.channels
247
+ self._monitor: _Monitor | None = _Monitor(self) if managed else None
248
+ self._validator = _Validator(manifest)
249
+ self._seq: dict[str, int] = defaultdict(int)
250
+ self._module: types.ModuleType | None = None
251
+ self._taps: list[t.Callable[[str, dict[str, t.Any]], None]] = [] # recorders: (direction, message)
252
+ if protocol is not None:
253
+ self._check_protocol(protocol)
254
+
255
+ @property
256
+ def module(self) -> types.ModuleType:
257
+ """The protocol module built from the server's manifest (``sprig.load``): models and the protocol class,
258
+ for talking to a server without its generated code."""
259
+ if self._module is None:
260
+ self._module = load(self.manifest)
261
+ return self._module
262
+
263
+ def _check_protocol(self, protocol: type[Protocol]) -> None:
264
+ name, version = protocol.__protocol_name__, protocol.__protocol_version__
265
+ if name != self.manifest.protocol:
266
+ raise TypeError(f"server speaks {self.manifest.protocol}, not {name}")
267
+ if (version or "").split(".")[0] != self.manifest.version.split(".")[0]:
268
+ raise TypeError(f"server is {self.manifest.protocol} {self.manifest.version}; client expects {version}")
269
+
270
+ # -- typed API ----------------------------------------------------------
271
+ async def invoke(self, operation: Rpc[TReq, TRep], request: TReq) -> Reply[TRep]:
272
+ """Call ``operation`` and return its reply. Errors are values, like HTTP responses: an error reply or a
273
+ timeout returns a ``Reply`` with ``error`` set; ``reply.raise_from_error()`` raises ``RemoteError`` or
274
+ returns the payload. Only misuse raises here (``ParamsError``, an unknown operation, a closed client)."""
275
+ spec = self.manifest.operations.get(operation.name)
276
+ if spec is None or spec.request != operation.request.__name__ or spec.reply != operation.reply.__name__:
277
+ raise TypeError(f"server {self.manifest.protocol} has no operation matching {operation}")
278
+ raw = await self._request(
279
+ operation.name, request.model_dump(mode="json"), {e.__name__: e for e in operation.errors}
280
+ )
281
+ if raw.error is not None:
282
+ typed = Reply[operation.reply]( # type: ignore[name-defined]
283
+ name=raw.name, id=raw.id, timestamp=raw.timestamp, source=raw.source, payload=None
284
+ )
285
+ else:
286
+ typed = Reply[operation.reply].model_validate(dump(raw)) # type: ignore[name-defined]
287
+ typed.error, typed.request, typed.declared = raw.error, raw.request, raw.declared
288
+ return t.cast(Reply[TRep], typed)
289
+
290
+ def listen(self, channel: Channel[TPay]) -> Subscription[Event[TPay]]:
291
+ """Subscribe to a server-to-client channel; yields event messages.
292
+
293
+ ``lifecycle`` starts with the current state and includes ``lost`` reported by this client.
294
+ """
295
+ self._check_channel(channel, Direction.SERVER_TO_CLIENT)
296
+ model = Event[channel.payload] # type: ignore[name-defined]
297
+ if channel.name == LIFECYCLE and self._monitor is not None:
298
+ return Subscription(self._monitor.listen(), model.model_validate, dedupe=False)
299
+ return Subscription(self._transport.events(channel.name), model.model_validate)
300
+
301
+ @property
302
+ def alive(self) -> bool | None:
303
+ """True while the server's heartbeat arrives; False once lost or stopping; None before it is first seen."""
304
+ if self._monitor is None or self._monitor.latest is None:
305
+ return None
306
+ return bool(self._monitor.latest["payload"]["State"] == "started")
307
+
308
+ @property
309
+ def lifecycle(self) -> Lifecycle | None:
310
+ """The server's latest lifecycle, including ``lost`` reported by this client."""
311
+ latest = self._monitor.latest if self._monitor is not None else None
312
+ return Lifecycle.model_validate(latest["payload"]) if latest is not None else None
313
+
314
+ async def send(self, channel: Channel[TPay], payload: TPay) -> None:
315
+ """Send on a client-to-server channel."""
316
+ self._check_channel(channel, Direction.CLIENT_TO_SERVER)
317
+ await self._notify(channel.name, payload.model_dump(mode="json"))
318
+
319
+ def _check_channel(self, channel: Channel[t.Any], direction: Direction) -> None:
320
+ spec = self.manifest.channels.get(channel.name)
321
+ if spec is None or spec.payload != channel.payload.__name__:
322
+ raise TypeError(f"server {self.manifest.protocol} has no channel matching {channel}")
323
+ if spec.direction is not direction:
324
+ raise TypeError(f"'{channel.name}' is {spec.direction}")
325
+
326
+ # -- wire ---------------------------------------------------------------
327
+ async def _request(self, name: str, payload: dict[str, t.Any], errors: dict[str, type[BaseModel]]) -> Reply[t.Any]:
328
+ spec = self.manifest.operations[name]
329
+ self._validator.check(name, spec.request, payload)
330
+ request = Request[t.Any](name=name, id=new_id(), source=self.name, payload=payload)
331
+ self._tapped("out", dump(request))
332
+ try:
333
+ raw = await self._transport.request(dump(request), self.timeout)
334
+ except TimeoutError:
335
+ info = ErrorInfo(code=ErrorCode.TIMEOUT, message=f"no reply within {self.timeout} s")
336
+ return Reply[t.Any](name=name, id=request.id, source=self.name, error=info, request=request)
337
+ self._tapped("in", raw)
338
+ message = parse_message(raw)
339
+ if isinstance(message, ErrorReply):
340
+ info = message.payload
341
+ model = errors.get(info.code) if info.code in spec.errors else None
342
+ return Reply[t.Any](
343
+ name=message.name,
344
+ id=message.id,
345
+ timestamp=message.timestamp,
346
+ source=message.source,
347
+ error=info,
348
+ request=request,
349
+ declared=model.model_validate(info.data or {}) if model else None,
350
+ )
351
+ if not isinstance(message, Reply):
352
+ info = ErrorInfo(code=ErrorCode.INTERNAL_ERROR, message=f"expected a reply, got {message.kind}")
353
+ return Reply[t.Any](name=name, id=request.id, source=self.name, error=info, request=request)
354
+ message.request = request
355
+ return message
356
+
357
+ async def _notify(self, name: str, payload: dict[str, t.Any]) -> None:
358
+ self._validator.check(name, self.manifest.channels[name].payload, payload)
359
+ self._seq[name] += 1
360
+ note = Notification[t.Any](name=name, seq=self._seq[name], source=self.name, payload=payload)
361
+ self._tapped("out", dump(note))
362
+ await asyncio.wait_for(self._transport.notify(dump(note)), self.timeout) # not sent if the server is gone
363
+
364
+ def _tapped(self, direction: str, raw: dict[str, t.Any]) -> None:
365
+ for tap in self._taps:
366
+ try:
367
+ tap(direction, raw)
368
+ except Exception:
369
+ logger.exception("recorder failed")
370
+
371
+ async def close(self) -> None:
372
+ if self._monitor is not None:
373
+ await self._monitor.stop()
374
+ await self._transport.close()
375
+
376
+ async def __aenter__(self) -> t.Self:
377
+ return self
378
+
379
+ async def __aexit__(self, *exc: object) -> None:
380
+ await self.close()
381
+
382
+
383
+ async def connect(
384
+ url: str, protocol: type[Protocol] | None = None, timeout: float = 10.0, name: str | None = None
385
+ ) -> Client:
386
+ """Connect to ``zmq://host[:port]`` or ``http://host[:port]`` and build a client from its manifest.
387
+
388
+ Without a port, the protocol's spec gives it (``endpoints``).
389
+ """
390
+ parsed = urlparse(url)
391
+ ports = protocol.spec().endpoints if protocol is not None and protocol.__protocol_spec__ is not None else None
392
+ if parsed.scheme == "zmq":
393
+ transport: t.Any = ZmqClientTransport(url, ports.zmq_rpc if ports else None)
394
+ elif parsed.scheme in ("http", "https"):
395
+ if parsed.port is None and ports is not None:
396
+ url = f"{parsed.scheme}://{parsed.hostname}:{ports.http_port}{parsed.path}"
397
+ from .transports import HttpClientTransport # the http extra
398
+
399
+ transport = HttpClientTransport(url)
400
+ else:
401
+ raise ValueError(f"unsupported scheme '{parsed.scheme}'")
402
+ name = name or f"client-{new_id()[:6]}"
403
+ await transport.open()
404
+ try:
405
+ request = Request[t.Any](name=DESCRIBE, source=name, payload={})
406
+ reply = parse_message(await transport.request(dump(request), timeout))
407
+ manifest = load_spec(reply.payload, name=f"{url} manifest")
408
+ except BaseException:
409
+ await transport.close()
410
+ raise
411
+ transport.bind_endpoints(manifest.bound)
412
+ client = Client(transport, manifest, protocol, timeout, name)
413
+ if client._monitor is not None:
414
+ client._monitor.start()
415
+ return client
@@ -0,0 +1 @@
1
+ """Code generation from protocol specs: ``sprig generate`` (static) and ``sprig.load`` (runtime)."""