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.
@@ -0,0 +1,180 @@
1
+ """HTTP binding.
2
+
3
+ - ``GET /describe`` the manifest
4
+ - ``POST /rpc/{operation}`` body = payload; response = reply or error message
5
+ - ``GET /events/{channel}`` server-sent events; ``id:`` is the event's seq, ``data:`` the event message
6
+ - ``POST /events/{channel}`` body = payload of a client-to-server message
7
+
8
+ Request bodies carry only the payload. The header comes from ``x-sprig-id``,
9
+ ``x-sprig-source`` and ``x-sprig-seq``; the server stamps the timestamp on receipt.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import contextlib
16
+ import json
17
+ import typing as t
18
+ from collections import defaultdict
19
+
20
+ import httpx
21
+ import uvicorn
22
+ from fastapi import FastAPI, Request
23
+ from fastapi.responses import JSONResponse, StreamingResponse
24
+
25
+ from ..envelope import ErrorCode, Notification, Reply, dump, new_id
26
+ from ..envelope import Request as RequestMessage
27
+ from ..spec import DESCRIBE
28
+
29
+ if t.TYPE_CHECKING:
30
+ from ..server import Server
31
+
32
+ _STATUS = {
33
+ ErrorCode.METHOD_NOT_FOUND: 404,
34
+ ErrorCode.INVALID_PARAMS: 422,
35
+ ErrorCode.INTERNAL_ERROR: 500,
36
+ ErrorCode.NO_REPLY: 500,
37
+ ErrorCode.TIMEOUT: 504,
38
+ ErrorCode.SERVER_STOPPED: 503,
39
+ }
40
+
41
+
42
+ def _sse(event: dict[str, t.Any]) -> str:
43
+ return f"id: {event['seq']}\nevent: {event['name']}\ndata: {json.dumps(event)}\n\n"
44
+
45
+
46
+ class HttpServerTransport:
47
+ """``port`` defaults to the protocol spec's ``endpoints.http.port``, then 8080."""
48
+
49
+ def __init__(self, host: str = "127.0.0.1", port: int | None = None) -> None:
50
+ self.host, self.port = host, port or 0
51
+ self._queues: dict[str, set[asyncio.Queue[dict[str, t.Any] | None]]] = defaultdict(set)
52
+ self._inflight: set[asyncio.Task[dict[str, t.Any]]] = set()
53
+ self._stopping = False
54
+
55
+ def endpoints(self) -> dict[str, str]:
56
+ return {"http": f"http://{self.host}:{self.port}"}
57
+
58
+ def _app(self, server: Server) -> FastAPI:
59
+ app = FastAPI(title=server.protocol.__protocol_name__ or server.name)
60
+
61
+ @app.get("/describe")
62
+ async def describe() -> dict[str, t.Any]:
63
+ return server.manifest().model_dump(mode="json")
64
+
65
+ @app.post("/rpc/{operation}")
66
+ async def call(operation: str, request: Request) -> JSONResponse:
67
+ body = await request.body()
68
+ message = RequestMessage[t.Any](
69
+ name=operation,
70
+ id=request.headers.get("x-sprig-id") or new_id(),
71
+ source=request.headers.get("x-sprig-source", "http"),
72
+ payload=json.loads(body or b"{}"),
73
+ )
74
+ task = asyncio.create_task(server.dispatch(dump(message)))
75
+ self._inflight.add(task)
76
+ try:
77
+ reply = await task
78
+ except asyncio.CancelledError:
79
+ if not self._stopping:
80
+ raise
81
+ reply = server.stopped_error(message.id, message.name) # every request gets one response
82
+ finally:
83
+ self._inflight.discard(task)
84
+ status = 200 if reply["kind"] == "reply" else _STATUS.get(reply["payload"]["code"], 409)
85
+ return JSONResponse(reply, status_code=status)
86
+
87
+ @app.get("/events/{channel}")
88
+ async def events(channel: str) -> StreamingResponse:
89
+ queue: asyncio.Queue[dict[str, t.Any] | None] = asyncio.Queue()
90
+ self._queues[channel].add(queue)
91
+ retained = server.retained(channel)
92
+
93
+ async def stream() -> t.AsyncIterator[str]:
94
+ try:
95
+ if retained is not None:
96
+ yield _sse(retained)
97
+ while (event := await queue.get()) is not None: # None: the server is stopping
98
+ yield _sse(event)
99
+ finally:
100
+ self._queues[channel].discard(queue)
101
+
102
+ return StreamingResponse(stream(), media_type="text/event-stream")
103
+
104
+ @app.post("/events/{channel}", status_code=202)
105
+ async def inbound(channel: str, request: Request) -> None:
106
+ message = Notification[t.Any](
107
+ name=channel,
108
+ seq=int(request.headers.get("x-sprig-seq", "0")),
109
+ source=request.headers.get("x-sprig-source", "http"),
110
+ payload=await request.json(),
111
+ )
112
+ await server.on_notification(dump(message))
113
+
114
+ return app
115
+
116
+ async def start(self, server: Server) -> None:
117
+ self.port = self.port or server.protocol.spec().endpoints.http_port
118
+ config = uvicorn.Config(self._app(server), host=self.host, port=self.port, log_level="warning", lifespan="off")
119
+ self._uvicorn = uvicorn.Server(config)
120
+ self._task = asyncio.create_task(self._uvicorn.serve())
121
+ while not self._uvicorn.started:
122
+ await asyncio.sleep(0.02)
123
+
124
+ async def stop(self) -> None:
125
+ self._stopping = True
126
+ for task in list(self._inflight):
127
+ task.cancel() # their handlers answer server_stopped
128
+ await asyncio.sleep(0.1) # let the last events (lifecycle stopping) reach the streams
129
+ for queues in self._queues.values():
130
+ for queue in queues:
131
+ queue.put_nowait(None) # end event streams, which would otherwise hold the shutdown
132
+ await asyncio.sleep(0.2) # let the stopped responses and stream ends go out
133
+ self._uvicorn.should_exit = True
134
+ self._uvicorn.force_exit = True # open SSE streams would otherwise hold shutdown
135
+ with contextlib.suppress(asyncio.CancelledError):
136
+ await self._task
137
+
138
+ async def send_event(self, event: dict[str, t.Any]) -> None:
139
+ for q in self._queues.get(event["name"], ()):
140
+ q.put_nowait(event)
141
+
142
+
143
+ class HttpClientTransport:
144
+ def __init__(self, url: str) -> None:
145
+ self._base = url.rstrip("/")
146
+
147
+ async def open(self) -> None:
148
+ self._http = httpx.AsyncClient(base_url=self._base, timeout=None)
149
+
150
+ def bind_endpoints(self, endpoints: dict[str, str]) -> None:
151
+ pass
152
+
153
+ async def close(self) -> None:
154
+ await self._http.aclose()
155
+
156
+ async def request(self, envelope: dict[str, t.Any], timeout: float) -> dict[str, t.Any]:
157
+ if envelope["name"] == DESCRIBE:
158
+ r = await self._http.get("/describe", timeout=timeout)
159
+ return dump(Reply[t.Any](name=DESCRIBE, id=envelope["id"], source="http", payload=r.json()))
160
+ r = await self._http.post(
161
+ f"/rpc/{envelope['name']}",
162
+ json=envelope["payload"],
163
+ headers={"x-sprig-id": envelope["id"], "x-sprig-source": envelope["source"]},
164
+ timeout=timeout,
165
+ )
166
+ return t.cast(dict[str, t.Any], r.json())
167
+
168
+ async def notify(self, envelope: dict[str, t.Any]) -> None:
169
+ r = await self._http.post(
170
+ f"/events/{envelope['name']}",
171
+ json=envelope["payload"],
172
+ headers={"x-sprig-source": envelope["source"], "x-sprig-seq": str(envelope["seq"])},
173
+ )
174
+ r.raise_for_status()
175
+
176
+ async def events(self, channel: str) -> t.AsyncIterator[dict[str, t.Any]]:
177
+ async with self._http.stream("GET", f"/events/{channel}") as r:
178
+ async for line in r.aiter_lines():
179
+ if line.startswith("data: "):
180
+ yield json.loads(line[6:])
@@ -0,0 +1,186 @@
1
+ """ZeroMQ binding.
2
+
3
+ - Requests and client-to-server notifications: DEALER (client) -> ROUTER (server), one JSON frame.
4
+ - Server-to-client events: XPUB (server) -> SUB (client), frames ``[name, json]``.
5
+ XPUB sees each new subscription, so ``retain_last`` channels are re-sent to late joiners.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import contextlib
12
+ import json
13
+ import logging
14
+ import typing as t
15
+ from urllib.parse import urlparse
16
+
17
+ import zmq
18
+ import zmq.asyncio
19
+
20
+ if t.TYPE_CHECKING:
21
+ from ..server import Server
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ def _dumps(obj: t.Any) -> bytes:
27
+ return json.dumps(obj, separators=(",", ":")).encode()
28
+
29
+
30
+ FLUSH_MS = 500 # how long closing sockets may take to deliver the last messages (server_stopped, lifecycle)
31
+
32
+
33
+ class ZmqServerTransport:
34
+ """``rpc`` and ``events`` default to ``tcp://*:<port>`` with the ports in the protocol's spec."""
35
+
36
+ def __init__(self, rpc: str | None = None, events: str | None = None) -> None:
37
+ self._rpc_addr, self._events_addr = rpc or "", events or ""
38
+ self._ctx = zmq.asyncio.Context.instance()
39
+ self._tasks: list[asyncio.Task[None]] = []
40
+ self._inflight: dict[asyncio.Task[None], tuple[bytes, str, str]] = {} # task -> (identity, id, name)
41
+
42
+ def endpoints(self) -> dict[str, str]:
43
+ return {"zmq.rpc": self._rpc_addr, "zmq.events": self._events_addr}
44
+
45
+ async def start(self, server: Server) -> None:
46
+ self._server = server
47
+ ports = server.protocol.spec().endpoints
48
+ self._rpc_addr = self._rpc_addr or f"tcp://*:{ports.zmq_rpc}"
49
+ self._events_addr = self._events_addr or f"tcp://*:{ports.zmq_events}"
50
+ self._router = self._ctx.socket(zmq.ROUTER)
51
+ self._router.bind(self._rpc_addr)
52
+ self._xpub = self._ctx.socket(zmq.XPUB)
53
+ self._xpub.setsockopt(zmq.XPUB_VERBOSE, 1)
54
+ self._xpub.bind(self._events_addr)
55
+ self._tasks = [asyncio.create_task(self._rpc_loop()), asyncio.create_task(self._subscription_loop())]
56
+
57
+ async def stop(self) -> None:
58
+ for task in self._tasks:
59
+ task.cancel()
60
+ for task in self._tasks:
61
+ with contextlib.suppress(asyncio.CancelledError):
62
+ await task
63
+ # Every request gets exactly one response: those still running get server_stopped.
64
+ for task, (identity, id_, name) in list(self._inflight.items()):
65
+ task.cancel()
66
+ await self._router.send_multipart([identity, _dumps(self._server.stopped_error(id_, name))])
67
+ self._inflight.clear()
68
+ # So do requests that arrived but were not read yet.
69
+ while await self._router.poll(0):
70
+ frames = await self._router.recv_multipart()
71
+ with contextlib.suppress(ValueError):
72
+ msg = json.loads(frames[-1])
73
+ if isinstance(msg, dict) and msg.get("kind") == "request":
74
+ stopped = self._server.stopped_error(str(msg.get("id", "?")), str(msg.get("name", "?")))
75
+ await self._router.send_multipart([frames[0], _dumps(stopped)])
76
+ self._router.close(FLUSH_MS)
77
+ self._xpub.close(FLUSH_MS)
78
+
79
+ async def send_event(self, event: dict[str, t.Any]) -> None:
80
+ await self._xpub.send_multipart([event["name"].encode(), _dumps(event)])
81
+
82
+ async def _rpc_loop(self) -> None:
83
+ while True:
84
+ frames = await self._router.recv_multipart()
85
+ identity, body = frames[0], frames[-1]
86
+ msg = json.loads(body)
87
+ task = asyncio.create_task(self._handle(identity, msg))
88
+ if isinstance(msg, dict) and msg.get("kind") == "request":
89
+ self._inflight[task] = (identity, str(msg.get("id", "?")), str(msg.get("name", "?")))
90
+ task.add_done_callback(lambda done: self._inflight.pop(done, None))
91
+
92
+ async def _handle(self, identity: bytes, msg: t.Any) -> None:
93
+ if isinstance(msg, dict) and msg.get("kind") == "notification":
94
+ await self._server.on_notification(msg)
95
+ return
96
+ reply = await self._server.dispatch(msg)
97
+ self._inflight.pop(t.cast(asyncio.Task[None], asyncio.current_task()), None) # answered: not stopped_error
98
+ await self._router.send_multipart([identity, _dumps(reply)])
99
+
100
+ async def _subscription_loop(self) -> None:
101
+ while True:
102
+ frame = await self._xpub.recv()
103
+ if frame[:1] != b"\x01":
104
+ continue
105
+ topic = frame[1:].decode()
106
+ for name in self._server.protocol.__channels__:
107
+ event = self._server.retained(name)
108
+ if event is not None and name.startswith(topic):
109
+ await self.send_event(event)
110
+
111
+
112
+ class ZmqClientTransport:
113
+ def __init__(self, url: str, default_port: int | None = None) -> None:
114
+ u = urlparse(url)
115
+ self.host = u.hostname or "localhost"
116
+ port = u.port or default_port
117
+ if port is None:
118
+ raise ValueError(f"{url}: give a port, or pass the protocol so its spec's port is used")
119
+ self._rpc_addr = f"tcp://{self.host}:{port}"
120
+ self._ctx = zmq.asyncio.Context.instance()
121
+ self._pending: dict[str, asyncio.Future[dict[str, t.Any]]] = {}
122
+ self._events_addr: str | None = None
123
+
124
+ async def open(self) -> None:
125
+ self._dealer = self._ctx.socket(zmq.DEALER)
126
+ self._dealer.setsockopt(zmq.LINGER, 0)
127
+ # Never queue for a server that is not connected: a request sent while the server is down would
128
+ # otherwise be delivered when it comes back, after its caller timed out.
129
+ self._dealer.setsockopt(zmq.IMMEDIATE, 1)
130
+ self._dealer.connect(self._rpc_addr)
131
+ self._reader = asyncio.create_task(self._read_loop())
132
+
133
+ def bind_endpoints(self, endpoints: dict[str, str]) -> None:
134
+ events = endpoints.get("zmq.events")
135
+ if events:
136
+ self._events_addr = events.replace("*", self.host).replace("0.0.0.0", self.host)
137
+
138
+ async def close(self) -> None:
139
+ self._reader.cancel()
140
+ with contextlib.suppress(asyncio.CancelledError):
141
+ await self._reader
142
+ self._dealer.close(0)
143
+
144
+ async def request(self, envelope: dict[str, t.Any], timeout: float) -> dict[str, t.Any]:
145
+ fut: asyncio.Future[dict[str, t.Any]] = asyncio.get_running_loop().create_future()
146
+ self._pending[envelope["id"]] = fut
147
+
148
+ async def send_and_wait() -> dict[str, t.Any]:
149
+ await self._dealer.send(_dumps(envelope)) # waits while no server is connected
150
+ return await fut
151
+
152
+ try:
153
+ # The timeout covers sending too: a request that could not be sent in time is never sent.
154
+ return await asyncio.wait_for(send_and_wait(), timeout)
155
+ finally:
156
+ self._pending.pop(envelope["id"], None)
157
+
158
+ async def notify(self, envelope: dict[str, t.Any]) -> None:
159
+ await self._dealer.send(_dumps(envelope))
160
+
161
+ def events(self, channel: str) -> t.AsyncIterator[dict[str, t.Any]]:
162
+ """Subscribe now (not on first iteration), so events published after this call are not missed."""
163
+ if self._events_addr is None:
164
+ raise RuntimeError("server did not advertise a zmq.events endpoint")
165
+ sub = self._ctx.socket(zmq.SUB)
166
+ sub.setsockopt(zmq.LINGER, 0)
167
+ sub.setsockopt(zmq.SUBSCRIBE, channel.encode())
168
+ sub.connect(self._events_addr)
169
+
170
+ async def read() -> t.AsyncIterator[dict[str, t.Any]]:
171
+ try:
172
+ while True:
173
+ topic, body = await sub.recv_multipart()
174
+ if topic.decode() == channel: # SUB filters by prefix; keep exact matches only
175
+ yield json.loads(body)
176
+ finally:
177
+ sub.close(0)
178
+
179
+ return read()
180
+
181
+ async def _read_loop(self) -> None:
182
+ while True:
183
+ reply = json.loads(await self._dealer.recv())
184
+ fut = self._pending.get(str(reply.get("id")))
185
+ if fut is not None and not fut.done():
186
+ fut.set_result(reply)
sprig/types.py ADDED
@@ -0,0 +1,29 @@
1
+ """Field types with a fixed wire form."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import typing as t
7
+
8
+ from pydantic import BeforeValidator, PlainSerializer, SerializationInfo, WithJsonSchema
9
+
10
+
11
+ def _to_bytes(value: t.Any) -> t.Any:
12
+ if isinstance(value, str):
13
+ return base64.b64decode(value, validate=True)
14
+ if isinstance(value, bytearray | memoryview):
15
+ return bytes(value)
16
+ return value
17
+
18
+
19
+ def _from_bytes(value: bytes, info: SerializationInfo) -> t.Any:
20
+ return base64.b64encode(value).decode("ascii") if info.mode_is_json() else value
21
+
22
+
23
+ Bytes = t.Annotated[
24
+ bytes,
25
+ BeforeValidator(_to_bytes),
26
+ PlainSerializer(_from_bytes),
27
+ WithJsonSchema({"type": "string", "format": "byte", "contentEncoding": "base64"}),
28
+ ]
29
+ """Binary data. ``bytes`` in Python, a base64 string on the wire, ``byte[]`` in C#."""
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.5
2
+ Name: sprigpy
3
+ Version: 0.1.0.dev1
4
+ Summary: Request/reply and pub/sub protocols written as YAML specs, with generated clients and servers for Python and Bonsai
5
+ Project-URL: Repository, https://github.com/bruno-f-cruz/sprig
6
+ Author: Bruno Cruz
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: bonsai,codegen,neuroscience,pubsub,rpc,zeromq
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.11
18
+ Requires-Dist: jinja2>=3.1
19
+ Requires-Dist: jsonschema>=4.23
20
+ Requires-Dist: pydantic>=2.11
21
+ Requires-Dist: pyyaml>=6
22
+ Requires-Dist: pyzmq>=26
23
+ Provides-Extra: http
24
+ Requires-Dist: fastapi>=0.115; extra == 'http'
25
+ Requires-Dist: httpx>=0.27; extra == 'http'
26
+ Requires-Dist: uvicorn>=0.30; extra == 'http'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # sprig
30
+
31
+ [![ci](https://github.com/bruno-f-cruz/sprig/actions/workflows/ci.yml/badge.svg)](https://github.com/bruno-f-cruz/sprig/actions/workflows/ci.yml) [![PyPI](https://img.shields.io/pypi/v/sprigpy)](https://pypi.org/project/sprigpy/) [![NuGet](https://img.shields.io/nuget/v/BFC.Sprig)](https://www.nuget.org/packages/BFC.Sprig/)
32
+
33
+ Request/reply operations and pub/sub channels written once, as a YAML spec, with generated servers and clients for Python and Bonsai (C#).
34
+
35
+ ```text
36
+ protocol.yml ──► sprig generate ──► Python module (pydantic models + protocol class)
37
+ │ └─► Bonsai operators + C# payload types (bonsai.sgen)
38
+ └─► sprig.load ─────► the same Python module, built at run time (from a file, a server, or a recording)
39
+ ```
40
+
41
+ Transports: ZeroMQ (Python and Bonsai) and HTTP with server-sent events (Python). Both runtimes handle lifecycle, heartbeats, timeouts, schema checks, timestamps and recording for you.
42
+
43
+ | Package | Install |
44
+ |---|---|
45
+ | `sprigpy` (Python; `import sprig`) | `pip install sprigpy` (`sprigpy[http]` for HTTP) |
46
+ | `BFC.Sprig` (C# runtime) and `BFC.Bonsai.Sprig` (operators) | NuGet, or the Bonsai package manager |
47
+
48
+ ## Write a spec
49
+
50
+ ```yaml
51
+ # protocol.yml
52
+ sprig: 1
53
+ protocol: Fip
54
+ version: 0.3.0
55
+ endpoints:
56
+ zmq: {rpc: 6555, events: 6556} # default ports for servers and clients
57
+
58
+ operations:
59
+ Start: {request: StartRequest, reply: StartReply, errors: [AlreadyRunning]}
60
+ Stop: {request: Empty, reply: StopReply, errors: [NotRunning]}
61
+
62
+ channels:
63
+ Frames: {payload: FrameStats}
64
+ LedPower: {payload: LedPower, direction: client_to_server}
65
+
66
+ types: # JSON Schema; `type: object` is implied; every name is PascalCase
67
+ StartRequest:
68
+ properties:
69
+ FrameRateHz: {type: number, default: 20.0, exclusiveMinimum: 0, maximum: 100}
70
+ StartReply:
71
+ properties: {SessionId: {type: string}}
72
+ required: [SessionId]
73
+ # ...
74
+ ```
75
+
76
+ `Heartbeat` and `Lifecycle` channels are added to every protocol. Binary fields are `{type: string, format: byte}`. The loader checks names, references, defaults and ports, and reports `file:line: key: problem`. Full example: [examples/fip/protocol.yml](https://github.com/bruno-f-cruz/sprig/blob/main/examples/fip/protocol.yml).
77
+
78
+ ## Generate
79
+
80
+ ```toml
81
+ # sprig.toml
82
+ [[protocol]]
83
+ spec = "examples/fip/protocol.yml"
84
+ python = "examples/fip/fip.py"
85
+ bonsai = "examples/bonsai/Extensions"
86
+ namespace = "Examples.Fip"
87
+ ```
88
+
89
+ ```sh
90
+ sprig generate # write every target
91
+ sprig generate --check # CI: fail if generated files are stale
92
+ sprig check protocol.yml # validate a spec
93
+ ```
94
+
95
+ Bonsai targets also need [bonsai.sgen](https://github.com/bonsai-rx/sgen) for the C# payload classes; `sprig generate` says how to install it when it is missing, and still writes the Python:
96
+
97
+ ```sh
98
+ # .NET 8 SDK or newer, then in your repository:
99
+ dotnet new tool-manifest
100
+ dotnet tool install bonsai.sgen --version 0.9.0
101
+ ```
102
+
103
+ Without a build step: `fip = sprig.load("protocol.yml")` gives the same module in memory.
104
+
105
+ ## Python
106
+
107
+ ```python
108
+ from sprig import Server, RpcFault, connect
109
+ from sprig.transports import ZmqServerTransport
110
+ from examples.fip.fip import AlreadyRunning, FipProtocol, StartReply, StartRequest
111
+
112
+ server = Server(FipProtocol)
113
+
114
+ @server.handle(FipProtocol.start)
115
+ async def start(request) -> StartReply:
116
+ if running:
117
+ raise RpcFault(AlreadyRunning(session_id=current))
118
+ return StartReply(session_id="s1")
119
+
120
+ await server.start(ZmqServerTransport()) # ports from the spec
121
+
122
+ async with await connect("zmq://rig", FipProtocol) as fip:
123
+ reply = await fip.invoke(FipProtocol.start, StartRequest(frame_rate_hz=30))
124
+ if reply.error: # errors are values, like HTTP
125
+ print(reply.error.code)
126
+ session = reply.raise_from_error().session_id # or raise RemoteError
127
+ async for event in fip.listen(FipProtocol.frames):
128
+ print(event.seq, event.timestamp, event.payload.fps)
129
+ ```
130
+
131
+ Handlers, payloads and replies are typed for mypy/pyright. Python names are snake_case (`frame_rate_hz`, `FipProtocol.led_power`); the wire carries the spec's PascalCase names (`FrameRateHz`, `LedPower`). A client without the generated code uses `client.module`, built from the server's manifest.
132
+
133
+ ## Bonsai
134
+
135
+ ```text
136
+ CreateFipProtocolServer -> ResourceSubject (Fip)
137
+ SubscribeSubject (Fip) -> Parse (Type = Start) -> Reply { ... -> StartReply } <- Fip (last input)
138
+ SubscribeSubject (Fip) -> Parse (Type = LedPower) -> SetLed -> Publish (Heartbeat) <- Fip
139
+ CreateBehaviorProtocolClient -> ResourceSubject (Behavior)
140
+ Timer -> MakeEmpty -> Request (Start) -> RaiseFromError -> ... <- Behavior
141
+ SubscribeSubject (Fip) -> Record (Path = D:\sessions)
142
+ ```
143
+
144
+ `Parse` subscribes to a server or client; `Reply` (nested) answers parsed requests concurrently; `Request` emits replies with `Error`, and `RaiseFromError` turns an error into an exception; `Publish` sends on a channel; `Record` writes a recording. Wrong types and wiring fail at build time. See [Bonsai operators](https://github.com/bruno-f-cruz/sprig/blob/main/docs/knowledge/codegen/bonsai-operators.md).
145
+
146
+ ## Built in, on both sides
147
+
148
+ - `Lifecycle` started/stopping from servers, `lost` from clients after 3 missed heartbeats; heartbeat status re-sent every period.
149
+ - Every request gets exactly one response; `server_stopped` when a server stops first; clients never queue for an absent server.
150
+ - Servers check requests against the spec's schemas; clients check the server's protocol and major version.
151
+ - An internal table of live clients.
152
+ - Recordings: `protocol.yml`, `session.json`, `rpc.jsonl`, one JSONL file per channel; `sprig.open_recording(path)` reads them typed from their own spec, from Python or Bonsai.
153
+
154
+ ## Repository
155
+
156
+ | Path | Contents |
157
+ |---|---|
158
+ | `src/sprig/` | spec loader, generator and CLI, runtime, transports, recording |
159
+ | `dotnet/src/` | `Sprig` and `Bonsai.Sprig` (net472, net8.0) |
160
+ | `dotnet/tests/` | MSTest suite; `Sprig.Interop`, the host the Python interop tests drive |
161
+ | `examples/` | FIP and behavior specs, generated modules, `examples/bonsai/` workflows and `Extensions` |
162
+ | `tests/` | pytest: spec, golden files, runtime, recording, Python <-> Bonsai |
163
+ | `scripts/` | `demo.ps1` (Bonsai FIP server + keyboard client), `regenerate.ps1` |
164
+ | `spec.md` | the protocol specification |
165
+ | `.bonsai/` | Bonsai 2.9.1 environment for the examples |
166
+ | `docs/knowledge/` | architecture notes |
167
+
168
+ ```sh
169
+ uv sync --all-extras && dotnet tool restore
170
+ uv run sprig generate && dotnet build dotnet/Sprig.slnx
171
+ uv run pytest && uv run pytest -m interop && dotnet test dotnet/Sprig.slnx
172
+ .bonsai/setup.cmd && scripts/demo.ps1 # the example in the Bonsai editor with a keyboard-driven Python client
173
+ ```
174
+
175
+ See [build and run](https://github.com/bruno-f-cruz/sprig/blob/main/docs/knowledge/workflows/build-and-run.md), [testing](https://github.com/bruno-f-cruz/sprig/blob/main/docs/knowledge/workflows/testing.md), [packaging](https://github.com/bruno-f-cruz/sprig/blob/main/docs/knowledge/workflows/packaging.md). License: MIT.
@@ -0,0 +1,25 @@
1
+ sprig/__init__.py,sha256=9O_N9bE7lIrcYqjp_f0HWC6FosMksCgP_5WOAlrv5Gc,1346
2
+ sprig/base.py,sha256=qiYe4ZFYMQFZ9f4_n_mcD5Ggzr3qKG7dXvYf94kZGIM,1457
3
+ sprig/client.py,sha256=nLiV6HNanNXL151-2cN1p8AGABvybZxlMc9UeS9HCU0,18154
4
+ sprig/envelope.py,sha256=v5f4-US7ZCVz-73rFCF6R9AAAkA6gY_vtBLXNV9rJQw,4157
5
+ sprig/loader.py,sha256=68IqMS2tlGo0W8-UeeZPWnEWOSJlDgbP2BDJbTE6duU,1623
6
+ sprig/protocol.py,sha256=2IhAgVgLZwHmwadk4_rcm-SMumNrwyxjZrPrNPrGEpw,9370
7
+ sprig/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ sprig/recording.py,sha256=n_n6Vwing5AWl0EM59EntiLFFahoUs7Gcn_LEjokhSs,10303
9
+ sprig/server.py,sha256=cy-BVRhuDGipJSUhkInef_l8JSolF_SOUjcAFwHwSqA,14579
10
+ sprig/spec.py,sha256=VPD4S23gA4SJQHnEZHprAQ2bNS7XLDNfP3fbhZ4SVcM,21715
11
+ sprig/types.py,sha256=WoliV5pWY3K357rCrQ8RAftGb4UNlKDoRpCdnPeEqzo,879
12
+ sprig/codegen/__init__.py,sha256=gZe7yU7Xza73Mq9OSEwomYHLcxcaNr4wRwLyo1mdEo4,102
13
+ sprig/codegen/cli.py,sha256=Dgg98_nIre4yaqiNJeXegUcgn6wJBChvcX0QsFMSjHk,8555
14
+ sprig/codegen/python.py,sha256=gZ8iBRPBHhDFVB445C39m2_Fbqi8Us7gUfalcFlmZtQ,8071
15
+ sprig/codegen/render.py,sha256=u9iQr5KgT5U_7ZiOC0HJnYTXrr1t_9gW5a9FIx1QPCo,5529
16
+ sprig/codegen/templates/bonsai/operators.cs.j2,sha256=3OzRVUgCeIujRvC39zGAELY4T_HJX5SRwfR6t7I7-cU,6626
17
+ sprig/codegen/templates/python/protocol.py.j2,sha256=fDqcTXTUPPR9Ld8fSVnn0lRlbMO6X1vxB_4dmL1_F1Q,2038
18
+ sprig/transports/__init__.py,sha256=gcLAF2uuBpv0s2BsUblBLCYoMNvP0wJuWGaxl0GGasI,840
19
+ sprig/transports/http.py,sha256=VopHnYE37pJckuQ_rGQZTBYo2J5Yk460djRz6jVg3mA,7449
20
+ sprig/transports/zmq.py,sha256=66WFC4gNsgr3weZjO9laA5kkeNGB5S23uKFDJ_4ahLs,8243
21
+ sprigpy-0.1.0.dev1.dist-info/METADATA,sha256=N4iQnWDIA0k0HJhSCYhdLjK_FqS44NOlzuwbwwukUh8,8196
22
+ sprigpy-0.1.0.dev1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
23
+ sprigpy-0.1.0.dev1.dist-info/entry_points.txt,sha256=21Gzkq7xWH-4vQCRSyfapJsPQeIVBx_RFqn7h4nlf_U,49
24
+ sprigpy-0.1.0.dev1.dist-info/licenses/LICENSE,sha256=LPFqdCWM1j45gB0UBjUnrTD7lyk0wlPB4NPGu0a95Fk,1088
25
+ sprigpy-0.1.0.dev1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sprig = sprig.codegen.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bruno Cruz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.