webcompy-server 0.0.14__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,424 @@
1
+ """JSON-RPC dispatcher for HTTP and WebSocket transports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import json
8
+ import logging
9
+ from collections.abc import AsyncGenerator
10
+ from dataclasses import dataclass
11
+ from typing import Any, Protocol
12
+
13
+ from webcompy.ajax._serde import from_json
14
+ from webcompy.ajax._sse import _format_sse_event
15
+ from webcompy.hydration._transfer_meta import apply_transfer_meta, encode_with_meta
16
+ from webcompy.rpc._errors import (
17
+ INTERNAL_ERROR,
18
+ INVALID_PARAMS,
19
+ INVALID_REQUEST,
20
+ METHOD_NOT_FOUND,
21
+ PARSE_ERROR,
22
+ RpcError,
23
+ )
24
+ from webcompy.rpc._registry import ProcedureInfo, ProcedureRegistry
25
+
26
+ _logger = logging.getLogger(__name__)
27
+
28
+
29
+ class _DecodableProcedure(Protocol):
30
+ @property
31
+ def param_order(self) -> list[str]: ...
32
+
33
+ @property
34
+ def required(self) -> frozenset[str]: ...
35
+
36
+ @property
37
+ def param_schemas(self) -> dict[str, Any]: ...
38
+
39
+
40
+ class _ParamError(Exception):
41
+ pass
42
+
43
+
44
+ def _error_body(req_id: Any, code: int, message: str, data: Any = None) -> dict[str, Any]:
45
+ error: dict[str, Any] = {"code": code, "message": message}
46
+ if data is not None:
47
+ error["data"] = data
48
+ return {"jsonrpc": "2.0", "error": error, "id": req_id}
49
+
50
+
51
+ def _valid_id(value: Any) -> bool:
52
+ return value is None or (isinstance(value, (str, int, float)) and not isinstance(value, bool))
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class _StreamCall:
57
+ """A validated single flagged streaming request handed to a transport."""
58
+
59
+ info: ProcedureInfo
60
+ kwargs: dict[str, Any]
61
+ req_id: Any
62
+
63
+
64
+ def _classify_stream_call(
65
+ payload: Any,
66
+ registry: ProcedureRegistry,
67
+ ) -> _StreamCall | dict[str, Any] | None:
68
+ """Classify a single entry as a streaming call for a transport.
69
+
70
+ Returns a ``_StreamCall`` for a valid single request with ``"stream": true``
71
+ targeting a streaming procedure, a JSON-RPC error body when the request is a
72
+ streaming call whose parameters are invalid, and ``None`` for everything else
73
+ (batch arrays, notifications, mismatch cases, and ordinary requests), which
74
+ the ordinary dispatch path handles.
75
+ """
76
+ if not isinstance(payload, dict) or payload.get("stream") is not True:
77
+ return None
78
+ if payload.get("jsonrpc") != "2.0" or not isinstance(payload.get("method"), str):
79
+ return None
80
+ req_id = payload.get("id")
81
+ if "id" not in payload or not _valid_id(req_id):
82
+ return None
83
+ info = registry.get(payload["method"])
84
+ if info is None or not info.is_streaming:
85
+ return None
86
+ params = payload.get("params")
87
+ if params is not None and not isinstance(params, (list, dict)):
88
+ return _error_body(req_id, INVALID_PARAMS, "Invalid params")
89
+ meta = payload.get("meta")
90
+ if meta is not None and not isinstance(meta, dict):
91
+ return _error_body(req_id, INVALID_PARAMS, "Invalid params")
92
+ try:
93
+ kwargs = _decode_params(info, params, meta, registry)
94
+ except _ParamError as err:
95
+ return _error_body(req_id, INVALID_PARAMS, "Invalid params", str(err))
96
+ return _StreamCall(info=info, kwargs=kwargs, req_id=req_id)
97
+
98
+
99
+ def _ensure_async_iter(generator: Any) -> AsyncGenerator[Any, None]:
100
+ """Return an async generator over a streaming procedure's generator.
101
+
102
+ Async generators are returned as-is; sync generators are wrapped so
103
+ cancellation lands as ``GeneratorExit`` at their next yield.
104
+ """
105
+ if hasattr(generator, "__aiter__"):
106
+ return generator
107
+
108
+ async def _wrap() -> AsyncGenerator[Any, None]:
109
+ try:
110
+ for item in generator:
111
+ yield item
112
+ await asyncio.sleep(0)
113
+ finally:
114
+ generator.close()
115
+
116
+ return _wrap()
117
+
118
+
119
+ def _decode_params(
120
+ info: _DecodableProcedure,
121
+ params: Any,
122
+ meta: Any,
123
+ registry: ProcedureRegistry,
124
+ ) -> dict[str, Any]:
125
+ if meta is not None:
126
+ for tag in meta.values():
127
+ if not isinstance(tag, str) or not registry.is_known_meta_tag(tag):
128
+ raise _ParamError(f"unknown type tag {tag!r}")
129
+ try:
130
+ params = apply_transfer_meta(params, meta, strict=True, decoders=registry.meta_decoders)
131
+ except ValueError as err:
132
+ raise _ParamError(str(err)) from err
133
+ if isinstance(params, list):
134
+ raise _ParamError("array params not supported for contract procedures")
135
+ if params is None:
136
+ if info.required:
137
+ raise _ParamError(f"missing required parameter(s): {', '.join(sorted(info.required))}")
138
+ if not info.param_order:
139
+ return {}
140
+ param_name = info.param_order[0]
141
+ raise _ParamError(f"missing required parameter {param_name!r}")
142
+ if not isinstance(params, dict):
143
+ raise _ParamError("params must be an object")
144
+ if len(info.param_order) != 1:
145
+ raise _ParamError("contract procedure must have exactly one parameter")
146
+ param_name = info.param_order[0]
147
+ schema = info.param_schemas[param_name]
148
+ try:
149
+ decoded_value = from_json(schema, params, strict=True)
150
+ except (TypeError, ValueError) as err:
151
+ raise _ParamError(str(err)) from err
152
+ return {param_name: decoded_value}
153
+
154
+
155
+ async def _process_entry(entry: Any, registry: ProcedureRegistry, *, in_batch: bool = False) -> dict[str, Any] | None:
156
+ if not isinstance(entry, dict):
157
+ return _error_body(None, INVALID_REQUEST, "Invalid Request")
158
+ has_id = "id" in entry
159
+ req_id = entry.get("id")
160
+ if has_id and not _valid_id(req_id):
161
+ return _error_body(None, INVALID_REQUEST, "Invalid Request")
162
+ if entry.get("jsonrpc") != "2.0" or not isinstance(entry.get("method"), str):
163
+ return None if not has_id else _error_body(req_id, INVALID_REQUEST, "Invalid Request")
164
+ method = entry["method"]
165
+ params = entry.get("params")
166
+ if params is not None and not isinstance(params, (list, dict)):
167
+ return None if not has_id else _error_body(req_id, INVALID_PARAMS, "Invalid params")
168
+ meta = entry.get("meta")
169
+ if meta is not None and not isinstance(meta, dict):
170
+ return None if not has_id else _error_body(req_id, INVALID_PARAMS, "Invalid params")
171
+ info = registry.get(method)
172
+ if info is None:
173
+ if not has_id:
174
+ return None
175
+ return _error_body(req_id, METHOD_NOT_FOUND, "Method not found")
176
+ if info.is_streaming:
177
+ if not has_id:
178
+ return None
179
+ if in_batch:
180
+ return _error_body(
181
+ req_id,
182
+ INVALID_REQUEST,
183
+ f"RPC method {method!r} is a streaming procedure; streaming is not supported in batch requests",
184
+ )
185
+ if entry.get("stream") is not True:
186
+ return _error_body(
187
+ req_id,
188
+ INVALID_REQUEST,
189
+ f'RPC method {method!r} is a streaming procedure; send the request with "stream": true',
190
+ )
191
+ return _error_body(
192
+ req_id,
193
+ INVALID_REQUEST,
194
+ f"RPC method {method!r} is a streaming procedure; the transport did not handle the stream",
195
+ )
196
+ if entry.get("stream") is True and has_id:
197
+ return _error_body(req_id, INVALID_REQUEST, f"RPC method {method!r} is not a streaming procedure")
198
+ try:
199
+ kwargs = _decode_params(info, params, meta, registry)
200
+ except _ParamError as err:
201
+ if not has_id:
202
+ return None
203
+ return _error_body(req_id, INVALID_PARAMS, "Invalid params", str(err))
204
+ try:
205
+ result = info.func(**kwargs)
206
+ if info.is_async:
207
+ result = await result
208
+ json_result, result_meta = encode_with_meta(result, type_handlers=registry.meta_encoders)
209
+ except Exception:
210
+ _logger.exception("RPC procedure %r failed", method)
211
+ if not has_id:
212
+ return None
213
+ return _error_body(req_id, INTERNAL_ERROR, "Internal error")
214
+ if not has_id:
215
+ return None
216
+ body: dict[str, Any] = {"jsonrpc": "2.0", "result": json_result, "id": req_id}
217
+ if result_meta:
218
+ body["meta"] = result_meta
219
+ return body
220
+
221
+
222
+ def _json_response_body(data: Any) -> tuple[int, bytes]:
223
+ return (200, json.dumps(data).encode("utf-8"))
224
+
225
+
226
+ async def dispatch_payload(
227
+ payload: Any,
228
+ registry: ProcedureRegistry,
229
+ ) -> dict[str, Any] | list[dict[str, Any]] | None:
230
+ """Dispatch a parsed JSON-RPC payload (transport-neutral).
231
+
232
+ ``payload`` is either a single request object or a batch array. Returns
233
+ the response object(s) as plain JSON-serializable dictionaries, or ``None``
234
+ when there is nothing to respond (e.g. notifications only). HTTP and
235
+ WebSocket transports serialize the result to their own wire format.
236
+
237
+ Args:
238
+ payload: Parsed JSON-RPC request object, or a batch array of them.
239
+ registry: Procedure registry resolving method names to handlers.
240
+
241
+ Returns:
242
+ The JSON-RPC response object, list of responses, or None if no response.
243
+
244
+ """
245
+ if isinstance(payload, list):
246
+ if not payload:
247
+ return _error_body(None, INVALID_REQUEST, "Invalid Request")
248
+ responses = [
249
+ response
250
+ for response in [await _process_entry(entry, registry, in_batch=True) for entry in payload]
251
+ if response is not None
252
+ ]
253
+ return responses or None
254
+ return await _process_entry(payload, registry)
255
+
256
+
257
+ async def _read_body(receive: Any) -> bytes:
258
+ chunks: list[bytes] = []
259
+ more_body = True
260
+ while more_body:
261
+ message = await receive()
262
+ if message["type"] != "http.request":
263
+ break
264
+ chunks.append(message.get("body", b""))
265
+ more_body = message.get("more_body", False)
266
+ return b"".join(chunks)
267
+
268
+
269
+ async def _send_response(
270
+ send: Any,
271
+ status: int,
272
+ body: bytes,
273
+ *,
274
+ media_type: str,
275
+ extra_headers: list[tuple[bytes, bytes]] | None = None,
276
+ ) -> None:
277
+ headers: list[tuple[bytes, bytes]] = [
278
+ (b"content-type", media_type.encode("latin-1")),
279
+ (b"content-length", str(len(body)).encode("latin-1")),
280
+ ]
281
+ if extra_headers:
282
+ headers.extend(extra_headers)
283
+ await send({"type": "http.response.start", "status": status, "headers": headers})
284
+ await send({"type": "http.response.body", "body": body})
285
+
286
+
287
+ async def _run_sse_stream(
288
+ call: _StreamCall,
289
+ registry: ProcedureRegistry,
290
+ receive: Any,
291
+ send: Any,
292
+ ) -> None:
293
+ """Stream a streaming procedure call as Server-Sent Events."""
294
+ await send(
295
+ {
296
+ "type": "http.response.start",
297
+ "status": 200,
298
+ "headers": [
299
+ (b"content-type", b"text/event-stream"),
300
+ (b"cache-control", b"no-store"),
301
+ ],
302
+ }
303
+ )
304
+ agen: AsyncGenerator[Any, None] | None = None
305
+
306
+ async def _pump() -> None:
307
+ nonlocal agen
308
+ try:
309
+ agen = _ensure_async_iter(call.info.func(**call.kwargs))
310
+ async for item in agen:
311
+ json_data, meta = encode_with_meta(item, type_handlers=registry.meta_encoders)
312
+ frame = _format_sse_event("item", json.dumps({"data": json_data, "meta": meta or None}))
313
+ await send({"type": "http.response.body", "body": frame.encode("utf-8"), "more_body": True})
314
+ except asyncio.CancelledError:
315
+ raise
316
+ except RpcError as err:
317
+ _logger.warning("RPC streaming procedure %r failed", call.info.name, exc_info=err)
318
+ try:
319
+ frame = _format_sse_event(
320
+ "error",
321
+ json.dumps({"code": err.code, "message": err.message, "data": err.data}),
322
+ )
323
+ await send({"type": "http.response.body", "body": frame.encode("utf-8"), "more_body": True})
324
+ except Exception:
325
+ _logger.exception("RPC streaming procedure %r: failed to send error event", call.info.name)
326
+ except Exception:
327
+ _logger.exception("RPC streaming procedure %r failed", call.info.name)
328
+ try:
329
+ frame = _format_sse_event(
330
+ "error",
331
+ json.dumps({"code": INTERNAL_ERROR, "message": "Internal error", "data": None}),
332
+ )
333
+ await send({"type": "http.response.body", "body": frame.encode("utf-8"), "more_body": True})
334
+ except Exception:
335
+ _logger.exception("RPC streaming procedure %r: failed to send error event", call.info.name)
336
+ else:
337
+ try:
338
+ frame = _format_sse_event("done", "null")
339
+ await send({"type": "http.response.body", "body": frame.encode("utf-8"), "more_body": True})
340
+ except Exception:
341
+ _logger.exception("RPC streaming procedure %r: failed to send done event", call.info.name)
342
+
343
+ async def _watch_disconnect() -> None:
344
+ while True:
345
+ message = await receive()
346
+ if message["type"] == "http.disconnect":
347
+ return
348
+
349
+ pump_task = asyncio.create_task(_pump())
350
+ watch_task = asyncio.create_task(_watch_disconnect())
351
+ try:
352
+ await asyncio.wait({pump_task, watch_task}, return_when=asyncio.FIRST_COMPLETED)
353
+ finally:
354
+ pump_task.cancel()
355
+ watch_task.cancel()
356
+ await asyncio.gather(pump_task, watch_task, return_exceptions=True)
357
+ if agen is not None:
358
+ await agen.aclose()
359
+ with contextlib.suppress(Exception):
360
+ await send({"type": "http.response.body", "body": b"", "more_body": False})
361
+
362
+
363
+ class _DispatcherASGIApp:
364
+ def __init__(self, registry: ProcedureRegistry) -> None:
365
+ self._registry = registry
366
+
367
+ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
368
+ if scope["type"] != "http":
369
+ await _send_response(send, 404, b"", media_type="text/plain")
370
+ return
371
+ if scope["method"] != "POST":
372
+ await _send_response(
373
+ send,
374
+ 405,
375
+ b"",
376
+ media_type="text/plain",
377
+ extra_headers=[(b"allow", b"POST")],
378
+ )
379
+ return
380
+ body = await _read_body(receive)
381
+ try:
382
+ payload = json.loads(body)
383
+ except (json.JSONDecodeError, UnicodeDecodeError, ValueError):
384
+ await _send_response(
385
+ send,
386
+ 200,
387
+ _json_response_body(_error_body(None, PARSE_ERROR, "Parse error"))[1],
388
+ media_type="application/json",
389
+ )
390
+ return
391
+ classified = _classify_stream_call(payload, self._registry)
392
+ if isinstance(classified, dict):
393
+ await _send_response(send, 200, json.dumps(classified).encode("utf-8"), media_type="application/json")
394
+ return
395
+ if classified is not None:
396
+ await _run_sse_stream(classified, self._registry, receive, send)
397
+ return
398
+ response = await dispatch_payload(payload, self._registry)
399
+ if response is None:
400
+ await _send_response(send, 204, b"", media_type="application/json")
401
+ return
402
+ await _send_response(send, 200, json.dumps(response).encode("utf-8"), media_type="application/json")
403
+
404
+
405
+ def create_dispatcher_app(registry: ProcedureRegistry):
406
+ """Return the JSON-RPC dispatcher as a class-based ASGI application.
407
+
408
+ The returned app is usable directly as an ASGI application or as the
409
+ endpoint of a Starlette ``Route`` (which dispatches to class-based ASGI
410
+ apps verbatim). It serves ordinary JSON-RPC responses as ``application/json``
411
+ and single ``"stream": true`` calls to streaming procedures as
412
+ ``text/event-stream``.
413
+
414
+ Args:
415
+ registry: Procedure registry serving the dispatched calls.
416
+
417
+ Returns:
418
+ The dispatcher ASGI app.
419
+
420
+ """
421
+ return _DispatcherASGIApp(registry)
422
+
423
+
424
+ __all__ = ["create_dispatcher_app", "dispatch_payload"]
@@ -0,0 +1,102 @@
1
+ """WebSocket streaming RPC hub."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import itertools
7
+ import logging
8
+ from collections.abc import AsyncGenerator
9
+ from typing import Any
10
+
11
+ from webcompy.hydration._transfer_meta import encode_with_meta
12
+ from webcompy.rpc._errors import INTERNAL_ERROR, RpcError
13
+ from webcompy.rpc._registry import ProcedureRegistry
14
+ from webcompy.rpc._stream import STREAM_CANCEL_METHOD, STREAM_DONE_METHOD, STREAM_ERROR_METHOD
15
+ from webcompy_server.rpc._dispatcher import _ensure_async_iter, _StreamCall
16
+ from webcompy_server.rpc._subscriptions import EVENT_METHOD, _Connection
17
+
18
+ _logger = logging.getLogger(__name__)
19
+
20
+
21
+ def _stream_event_frame(stream_id: str, data: Any, meta: dict[str, str] | None) -> dict[str, Any]:
22
+ params: dict[str, Any] = {"stream_id": stream_id, "data": data}
23
+ if meta:
24
+ params["meta"] = meta
25
+ return {"jsonrpc": "2.0", "method": EVENT_METHOD, "params": params}
26
+
27
+
28
+ class StreamCallHub:
29
+ """Run per-call streaming procedures over a shared WebSocket connection.
30
+
31
+ Each flagged call spawns its own generator task on the caller's
32
+ ``_Connection``. Streams are never shared, replayed, or given an idle
33
+ grace period; cancellation (via ``_webcompy.stream_cancel`` or socket
34
+ close) stops the generator immediately.
35
+ """
36
+
37
+ def __init__(self, registry: ProcedureRegistry) -> None:
38
+ self.registry = registry
39
+ self._stream_counter = itertools.count(1)
40
+
41
+ def start_call(self, conn: _Connection, call: _StreamCall) -> None:
42
+ stream_id = f"st{next(self._stream_counter)}"
43
+ conn.send({"jsonrpc": "2.0", "result": {"stream_id": stream_id}, "id": call.req_id})
44
+ task = asyncio.create_task(self._run(conn, stream_id, call))
45
+ conn.stream_tasks[stream_id] = task
46
+ task.add_done_callback(lambda _t, c=conn, sid=stream_id: c.stream_tasks.pop(sid, None))
47
+
48
+ def handle_cancel(self, conn: _Connection, payload: dict[str, Any]) -> None:
49
+ params = payload.get("params")
50
+ if not isinstance(params, dict):
51
+ return
52
+ stream_id = params.get("stream_id")
53
+ if not isinstance(stream_id, str):
54
+ return
55
+ task = conn.stream_tasks.pop(stream_id, None)
56
+ if task is not None:
57
+ task.cancel()
58
+
59
+ async def _run(self, conn: _Connection, stream_id: str, call: _StreamCall) -> None:
60
+ agen: AsyncGenerator[Any, None] | None = None
61
+ try:
62
+ agen = _ensure_async_iter(call.info.func(**call.kwargs))
63
+ async for item in agen:
64
+ json_data, meta = encode_with_meta(item, type_handlers=self.registry.meta_encoders)
65
+ conn.send(_stream_event_frame(stream_id, json_data, meta or None))
66
+ conn.send({"jsonrpc": "2.0", "method": STREAM_DONE_METHOD, "params": {"stream_id": stream_id}})
67
+ except asyncio.CancelledError:
68
+ raise
69
+ except RpcError as err:
70
+ _logger.warning("RPC streaming procedure %r failed", call.info.name, exc_info=err)
71
+ conn.send(
72
+ {
73
+ "jsonrpc": "2.0",
74
+ "method": STREAM_ERROR_METHOD,
75
+ "params": {
76
+ "stream_id": stream_id,
77
+ "code": err.code,
78
+ "message": err.message,
79
+ "data": err.data,
80
+ },
81
+ }
82
+ )
83
+ except Exception:
84
+ _logger.exception("RPC streaming procedure %r failed", call.info.name)
85
+ conn.send(
86
+ {
87
+ "jsonrpc": "2.0",
88
+ "method": STREAM_ERROR_METHOD,
89
+ "params": {"stream_id": stream_id, "code": INTERNAL_ERROR, "message": "Internal error"},
90
+ }
91
+ )
92
+ finally:
93
+ if agen is not None:
94
+ await agen.aclose()
95
+
96
+
97
+ __all__ = [
98
+ "STREAM_CANCEL_METHOD",
99
+ "STREAM_DONE_METHOD",
100
+ "STREAM_ERROR_METHOD",
101
+ "StreamCallHub",
102
+ ]