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,235 @@
1
+ """RPC subscription hub for WebSocket connections."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import itertools
7
+ import json
8
+ import logging
9
+ from collections import deque
10
+ from typing import Any
11
+
12
+ from webcompy.hydration._transfer_meta import encode_with_meta
13
+ from webcompy.rpc._errors import INVALID_PARAMS, INVALID_REQUEST, METHOD_NOT_FOUND
14
+ from webcompy.rpc._registry import ProcedureRegistry, SubscriptionInfo
15
+ from webcompy_server.rpc._dispatcher import _decode_params, _error_body, _ParamError
16
+
17
+ _logger = logging.getLogger(__name__)
18
+
19
+ EVENT_METHOD = "_webcompy.event"
20
+
21
+ _STREAM_IDLE_TIMEOUT = 60.0
22
+
23
+ _sub_counter = itertools.count(1)
24
+
25
+
26
+ def _event_frame(sub_id: str, cursor: int, data: Any, meta: dict[str, str] | None) -> dict[str, Any]:
27
+ params: dict[str, Any] = {"subscription_id": sub_id, "cursor": cursor, "data": data}
28
+ if meta:
29
+ params["meta"] = meta
30
+ return {"jsonrpc": "2.0", "method": EVENT_METHOD, "params": params}
31
+
32
+
33
+ class _Stream:
34
+ def __init__(self, hub: SubscriptionHub, info: SubscriptionInfo, params_key: str, kwargs: dict[str, Any]) -> None:
35
+ self.hub = hub
36
+ self.info = info
37
+ self.params_key = params_key
38
+ self.kwargs = kwargs
39
+ self.cursor = 0
40
+ self.buffer: deque[tuple[int, Any, dict[str, str] | None]] = deque(maxlen=info.replay_size)
41
+ self.subscribers: dict[str, asyncio.Queue] = {}
42
+ self.source_task: asyncio.Task | None = None
43
+ self.idle_task: asyncio.Task | None = None
44
+
45
+ def start_source(self) -> None:
46
+ encoders = self.hub.registry.meta_encoders
47
+
48
+ async def _run() -> None:
49
+ try:
50
+ async for event in self.info.func(**self.kwargs):
51
+ json_data, meta = encode_with_meta(event, type_handlers=encoders)
52
+ self.cursor += 1
53
+ self.buffer.append((self.cursor, json_data, meta or None))
54
+ for sub_id, queue in list(self.subscribers.items()):
55
+ queue.put_nowait(_event_frame(sub_id, self.cursor, json_data, meta or None))
56
+ except asyncio.CancelledError:
57
+ raise
58
+ except Exception:
59
+ _logger.exception("RPC subscription %r failed", self.info.name)
60
+ if not self.subscribers:
61
+ self.schedule_idle()
62
+
63
+ self.source_task = asyncio.create_task(_run())
64
+
65
+ def check_rejoin(self, last_cursor: int) -> tuple[list[tuple[int, Any, dict[str, str] | None]], bool]:
66
+ if last_cursor == self.cursor:
67
+ return [], False
68
+ if last_cursor > self.cursor or not self.buffer:
69
+ return [], True
70
+ oldest = self.buffer[0][0]
71
+ if last_cursor < oldest - 1:
72
+ return [], True
73
+ return [(c, d, m) for c, d, m in self.buffer if c > last_cursor], False
74
+
75
+ def attach(self, sub_id: str, queue: asyncio.Queue) -> None:
76
+ if self.idle_task is not None:
77
+ self.idle_task.cancel()
78
+ self.idle_task = None
79
+ self.subscribers[sub_id] = queue
80
+
81
+ def detach(self, sub_id: str) -> None:
82
+ self.subscribers.pop(sub_id, None)
83
+ if not self.subscribers and self.source_task is not None:
84
+ self.schedule_idle()
85
+
86
+ def schedule_idle(self) -> None:
87
+ if self.idle_task is not None:
88
+ return
89
+
90
+ async def _idle() -> None:
91
+ await asyncio.sleep(_STREAM_IDLE_TIMEOUT)
92
+ if not self.subscribers:
93
+ self.hub.reap(self)
94
+
95
+ self.idle_task = asyncio.create_task(_idle())
96
+
97
+
98
+ class SubscriptionHub:
99
+ def __init__(self, registry: ProcedureRegistry) -> None:
100
+ self.registry = registry
101
+ self._streams: dict[tuple[str, str], _Stream] = {}
102
+
103
+ def attach(self, websocket: Any) -> _Connection:
104
+ conn = _Connection(self, websocket)
105
+ conn.start_sender()
106
+ return conn
107
+
108
+ def handle_subscribe(self, conn: _Connection, payload: dict[str, Any]) -> None:
109
+ req_id = payload.get("id")
110
+ if req_id is None:
111
+ return
112
+ params = payload.get("params")
113
+ if not isinstance(params, dict):
114
+ conn.send(_error_body(req_id, INVALID_REQUEST, "Invalid params"))
115
+ return
116
+ method = params.get("method")
117
+ if not isinstance(method, str):
118
+ conn.send(_error_body(req_id, INVALID_REQUEST, "Invalid params"))
119
+ return
120
+ info = self.registry.get_subscription(method)
121
+ if info is None:
122
+ conn.send(_error_body(req_id, METHOD_NOT_FOUND, "Method not found"))
123
+ return
124
+ raw_params = params.get("params")
125
+ meta = params.get("meta")
126
+ if meta is not None and not isinstance(meta, dict):
127
+ conn.send(_error_body(req_id, INVALID_PARAMS, "Invalid params"))
128
+ return
129
+ try:
130
+ kwargs = _decode_params(info, raw_params, meta, self.registry)
131
+ except _ParamError as err:
132
+ conn.send(_error_body(req_id, INVALID_PARAMS, "Invalid params", str(err)))
133
+ return
134
+ last_cursor = params.get("last_cursor")
135
+ if last_cursor is not None and (isinstance(last_cursor, bool) or not isinstance(last_cursor, int)):
136
+ conn.send(_error_body(req_id, INVALID_PARAMS, "Invalid params"))
137
+ return
138
+ params_key = json.dumps(raw_params, sort_keys=True)
139
+ stream = self._streams.get((method, params_key))
140
+ if stream is not None and stream.source_task is not None and stream.source_task.done():
141
+ self.reap(stream)
142
+ stream = None
143
+ if stream is None:
144
+ stream = _Stream(self, info, params_key, kwargs)
145
+ self._streams[(method, params_key)] = stream
146
+ stream.start_source()
147
+ if last_cursor is not None:
148
+ replay, resync = stream.check_rejoin(last_cursor)
149
+ if resync:
150
+ conn.send(
151
+ {
152
+ "jsonrpc": "2.0",
153
+ "result": {"subscription_id": None, "resync_required": True},
154
+ "id": req_id,
155
+ }
156
+ )
157
+ if not stream.subscribers:
158
+ self.reap(stream)
159
+ return
160
+ else:
161
+ replay = []
162
+ sub_id = f"s{next(_sub_counter)}"
163
+ conn.send({"jsonrpc": "2.0", "result": {"subscription_id": sub_id, "resync_required": False}, "id": req_id})
164
+ for cursor, data, event_meta in replay:
165
+ conn.send(_event_frame(sub_id, cursor, data, event_meta))
166
+ stream.attach(sub_id, conn.queue)
167
+ conn.subscriptions[sub_id] = stream
168
+
169
+ def handle_unsubscribe(self, conn: _Connection, payload: dict[str, Any]) -> None:
170
+ params = payload.get("params")
171
+ if not isinstance(params, dict):
172
+ return
173
+ sub_id = params.get("subscription_id")
174
+ if not isinstance(sub_id, str):
175
+ return
176
+ stream = conn.subscriptions.pop(sub_id, None)
177
+ if stream is not None:
178
+ stream.detach(sub_id)
179
+
180
+ def reap(self, stream: _Stream) -> None:
181
+ if stream.subscribers:
182
+ return
183
+ key = (stream.info.name, stream.params_key)
184
+ if self._streams.get(key) is not stream:
185
+ return
186
+ self._streams.pop(key, None)
187
+ if stream.source_task is not None:
188
+ stream.source_task.cancel()
189
+ if stream.idle_task is not None:
190
+ stream.idle_task.cancel()
191
+
192
+
193
+ class _Connection:
194
+ def __init__(self, hub: SubscriptionHub, websocket: Any) -> None:
195
+ self.hub = hub
196
+ self.websocket = websocket
197
+ self.queue: asyncio.Queue = asyncio.Queue()
198
+ self.subscriptions: dict[str, _Stream] = {}
199
+ self.stream_tasks: dict[str, asyncio.Task] = {}
200
+ self.sender_task: asyncio.Task | None = None
201
+
202
+ def start_sender(self) -> None:
203
+ websocket = self.websocket
204
+
205
+ async def _drain() -> None:
206
+ try:
207
+ while True:
208
+ frame = await self.queue.get()
209
+ await websocket.send_text(json.dumps(frame))
210
+ except asyncio.CancelledError:
211
+ raise
212
+ except Exception:
213
+ _logger.exception("RPC WebSocket sender failed")
214
+
215
+ self.sender_task = asyncio.create_task(_drain())
216
+
217
+ def send(self, frame: Any) -> None:
218
+ self.queue.put_nowait(frame)
219
+
220
+ async def close(self) -> None:
221
+ stream_tasks = list(self.stream_tasks.values())
222
+ self.stream_tasks.clear()
223
+ for task in stream_tasks:
224
+ task.cancel()
225
+ if stream_tasks:
226
+ await asyncio.gather(*stream_tasks, return_exceptions=True)
227
+ for sub_id in list(self.subscriptions):
228
+ stream = self.subscriptions.pop(sub_id, None)
229
+ if stream is not None:
230
+ stream.detach(sub_id)
231
+ if self.sender_task is not None:
232
+ self.sender_task.cancel()
233
+
234
+
235
+ __all__ = ["SubscriptionHub"]
@@ -0,0 +1,102 @@
1
+ """WebSocket endpoint for JSON-RPC with subscriptions and streaming."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from webcompy.rpc._errors import PARSE_ERROR
8
+ from webcompy.rpc._registry import ProcedureRegistry
9
+ from webcompy.rpc._stream import STREAM_CANCEL_METHOD
10
+ from webcompy_server.rpc._dispatcher import _classify_stream_call, _error_body, dispatch_payload
11
+ from webcompy_server.rpc._streams import StreamCallHub
12
+ from webcompy_server.rpc._subscriptions import SubscriptionHub
13
+
14
+ CLOSE_METHOD = "_webcompy.close"
15
+ SUBSCRIBE_METHOD = "_webcompy.subscribe"
16
+ UNSUBSCRIBE_METHOD = "_webcompy.unsubscribe"
17
+ PING_METHOD = "_webcompy.ping"
18
+ PONG_METHOD = "_webcompy.pong"
19
+
20
+
21
+ def create_rpc_ws_endpoint(registry: ProcedureRegistry):
22
+ """Return the JSON-RPC WebSocket endpoint handler for ``registry``.
23
+
24
+ The endpoint accepts a WebSocket, feeds each incoming text frame through
25
+ the shared transport-neutral dispatch core (``dispatch_payload``) and
26
+ writes each response back as a text frame via a per-connection send queue
27
+ (single FIFO path guarantees response → replay → live ordering for
28
+ subscriptions). Reserved ``_webcompy.*`` methods are handled here: ping is
29
+ answered with pong, close closes the socket with code 1011 so the client
30
+ reconnect loop engages, subscribe/unsubscribe drive the subscription
31
+ hub, and stream-cancel stops a per-call stream. Single ``"stream": true``
32
+ calls to streaming procedures are answered with a ``stream_id`` and
33
+ streamed by the ``StreamCallHub``. Starlette is imported lazily so this
34
+ module stays importable outside a Starlette context.
35
+
36
+ Args:
37
+ registry: Procedure registry serving the dispatched calls and
38
+ backing the subscription/stream hubs.
39
+
40
+ Returns:
41
+ The async Starlette WebSocket endpoint handler for ``registry``.
42
+
43
+ """
44
+ from starlette.websockets import WebSocket, WebSocketDisconnect
45
+
46
+ hub = SubscriptionHub(registry)
47
+ stream_hub = StreamCallHub(registry)
48
+
49
+ async def endpoint(websocket: WebSocket) -> None:
50
+ await websocket.accept()
51
+ conn = hub.attach(websocket)
52
+ try:
53
+ while True:
54
+ message = await websocket.receive()
55
+ if message["type"] != "websocket.receive":
56
+ break
57
+ text = message.get("text")
58
+ if text is None:
59
+ continue
60
+ try:
61
+ payload = json.loads(text)
62
+ except (json.JSONDecodeError, UnicodeDecodeError, ValueError):
63
+ conn.send(_error_body(None, PARSE_ERROR, "Parse error"))
64
+ continue
65
+ if isinstance(payload, dict):
66
+ method = payload.get("method")
67
+ if method == CLOSE_METHOD:
68
+ await websocket.close(code=1011)
69
+ return
70
+ if method == PING_METHOD:
71
+ conn.send({"jsonrpc": "2.0", "method": PONG_METHOD, "params": {}})
72
+ continue
73
+ if method == PONG_METHOD:
74
+ continue
75
+ if method == SUBSCRIBE_METHOD:
76
+ hub.handle_subscribe(conn, payload)
77
+ continue
78
+ if method == UNSUBSCRIBE_METHOD:
79
+ hub.handle_unsubscribe(conn, payload)
80
+ continue
81
+ if method == STREAM_CANCEL_METHOD:
82
+ stream_hub.handle_cancel(conn, payload)
83
+ continue
84
+ classified = _classify_stream_call(payload, registry)
85
+ if isinstance(classified, dict):
86
+ conn.send(classified)
87
+ continue
88
+ if classified is not None:
89
+ stream_hub.start_call(conn, classified)
90
+ continue
91
+ response = await dispatch_payload(payload, registry)
92
+ if response is not None:
93
+ conn.send(response)
94
+ except WebSocketDisconnect:
95
+ pass
96
+ finally:
97
+ await conn.close()
98
+
99
+ return endpoint
100
+
101
+
102
+ __all__ = ["create_rpc_ws_endpoint"]
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.5
2
+ Name: webcompy-server
3
+ Version: 0.0.14
4
+ Summary: WebComPy server-side rendering and HTML generation
5
+ Project-URL: Homepage, https://github.com/kniwase/WebComPy
6
+ Project-URL: Documentation, https://webcompy.net/documents/
7
+ Project-URL: LLM Docs, https://webcompy.net/llms.txt
8
+ Author-email: Kento Niwase <kento.niwase@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: browser,framework,frontend,server
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Python: >=3.12
17
+ Requires-Dist: httpx
18
+ Requires-Dist: nest-asyncio2>=1.7.4
19
+ Requires-Dist: starlette
20
+ Requires-Dist: webcompy==0.0.14
21
+ Description-Content-Type: text/markdown
22
+
23
+ # webcompy-server
24
+
25
+ Server-side rendering, HTML generation, ASGI embedding, and JSON-RPC server dispatch for [WebComPy](https://github.com/kniwase/WebComPy).
26
+
27
+ `webcompy-server` provides the server runtime layer for WebComPy applications without requiring `webcompy-cli`:
28
+
29
+ - Server-side `ServerRenderContext` and in-memory DOM ports (`configure_server_context`, `generate_html`)
30
+ - Lightweight production ASGI serving from prebuilt artifacts (`create_prebuilt_asgi_app`, `PrebuildManifest`, `load_prebuild_manifest`, `validate_prebuild_manifest`) for CPython FaaS and threadless server-side Emscripten runtimes
31
+ - JSON-RPC HTTP, streaming, and WebSocket server endpoints (`webcompy_server.rpc`)
32
+ - Typed server response helpers (`webcompy_server.contrib`)
33
+
34
+ This distribution is versioned in lockstep with `webcompy`.
35
+
36
+ ## Documentation & Resources
37
+
38
+ - [Documentation](https://webcompy.net/documents/)
39
+ - [ASGI & Server Integration](https://webcompy.net/documents/server/asgi-integration/)
40
+ - [LLM Documentation Index (`llms.txt`)](https://webcompy.net/llms.txt) — bundles: [`llms-small.txt`](https://webcompy.net/llms-small.txt) / [`llms-full.txt`](https://webcompy.net/llms-full.txt)
41
+ - [Source Code & Discussions](https://github.com/kniwase/WebComPy)
42
+
43
+ ## License
44
+
45
+ MIT License — see [LICENSE](LICENSE).
@@ -0,0 +1,35 @@
1
+ webcompy_server/__init__.py,sha256=mZ9Q95ZzuOiAMGxbwRODl3Rh4LFS13pIATNCczHXneE,3106
2
+ webcompy_server/_asgi.py,sha256=5HiCy9OB92xocKeC5__KlHTIe_NQPRY954s9g9HIBXU,35784
3
+ webcompy_server/_context.py,sha256=mh9OmXg2LnAiKDIjnyEha_wQXvw5OegHEXWJSPNyPLM,4768
4
+ webcompy_server/_html.py,sha256=rzXo0-qNusqU1vFN-mcAIXyH3jbJ2yd-qnt5TtbRLr8,35499
5
+ webcompy_server/_prebuild.py,sha256=KoFSIEwMZU29nDEumqxaLCUf3rmno-OptC_x3z-Pxs8,22843
6
+ webcompy_server/_static_route.py,sha256=381PiAMhALoMIEvWNANDfsOEH-BNMLgJtyvhTi_Vlns,1672
7
+ webcompy_server/_teleport_emission.py,sha256=gKrP57M4lf3g_CITwLtJolMjdcRYwYQzqxt5IlE5K34,3119
8
+ webcompy_server/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ webcompy_server/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ webcompy_server/contrib/fastapi.py,sha256=4at1Ooe9pUvHmDekJ1n0sD-8MfPBwYOI1bIOOFdDDBM,1375
11
+ webcompy_server/ports/__init__.py,sha256=oiro31nECf332XX_BEypKH0Nsav1lD61ZREAiax3oLQ,1413
12
+ webcompy_server/ports/_async_scheduler.py,sha256=21SEe9M2oPLurAyBmh-vUenyCNspPJI_Af16voIThcM,2091
13
+ webcompy_server/ports/_cookie.py,sha256=pfG1P4d2B4pp-jUTx1vtpBPmCHWy1P374he_9fb6H5I,4514
14
+ webcompy_server/ports/_custom_element.py,sha256=RWAyv8HfDQF9BY_V_Plf85sB0IVmWKk9OlRsLRlih6U,1958
15
+ webcompy_server/ports/_dom.py,sha256=Z8X60R8xbiuq3sw1hsAm7Z7yzHftcWC97ZyQ1R89tkM,11068
16
+ webcompy_server/ports/_event_source.py,sha256=mDWEwIK1ohnB1HZOikHNczuMMaNwTxSKZKKGNZos_a8,1301
17
+ webcompy_server/ports/_fetch.py,sha256=lB2q8xl-4Xum-Un5Llndiv0OMw-DA6gNrzsTZGwaKQ0,10089
18
+ webcompy_server/ports/_ffi.py,sha256=KgLwvDohoYZ3YUWXAMaKnAwyplZWesV6-rNeADC2n78,1384
19
+ webcompy_server/ports/_history.py,sha256=QQRq5uMHOthG2ElK2s0ddR9IWPQEK2lN3jSjWUu8ClI,987
20
+ webcompy_server/ports/_host.py,sha256=90XjXwG6_g91jmLfSBrFEnc64z7cDY7VPWBrplnkM5g,1920
21
+ webcompy_server/ports/_media_query.py,sha256=6CVUX1iPOs1e9EHQwS4zXeZB1d7miUQXPkNJXnCNWLY,611
22
+ webcompy_server/ports/_resource.py,sha256=ivnQFs3esBBWpPirppeLX7j63GUY6kMSsKQ80O-DM7c,9571
23
+ webcompy_server/ports/_selector.py,sha256=mEHwHzkgquxLZ5MTLtPlcyVwqbJQL0uFeIQwmpXsVdk,7938
24
+ webcompy_server/ports/_transition.py,sha256=UaQk6V0t_zfaDc1BiJCMn4aUhUXNixBCf85UPTS4o1A,1733
25
+ webcompy_server/ports/_virtual_dom.py,sha256=4kdeTLeHtah1ULyxvfawpgwxPXqYoTmW3dZY24Fxx88,17723
26
+ webcompy_server/ports/_websocket.py,sha256=RsSGH-MEP9ak_kmtYQvtEueYOwKV1g3iK9_hG9l86l4,1522
27
+ webcompy_server/rpc/__init__.py,sha256=OKYrsA88BBg6eF07WF60EoCqx_zY34mbL9XiNSOYVWc,298
28
+ webcompy_server/rpc/_dispatcher.py,sha256=GR4NBir7Vu5h8H7MPoQnw3Ja-3RuvTfpUf0yPIv_Ja8,15809
29
+ webcompy_server/rpc/_streams.py,sha256=v_MhoHkHIQCExsYRWSgz_Twdp5cezRi0jWooG3J1JMU,3983
30
+ webcompy_server/rpc/_subscriptions.py,sha256=0l8v7nQo2ezGlJQh9I2gjfUkhBjZ5mhKpzZoxXZk0UQ,8919
31
+ webcompy_server/rpc/_ws_endpoint.py,sha256=n-0YgB3GytztHd-kLswf_-gUocMQt-lQexIoR3CLw9s,4235
32
+ webcompy_server-0.0.14.dist-info/METADATA,sha256=i652LphORPMrhJNq64FHcjAm1OPZ5K3Sd3Aj8XgfyJw,2111
33
+ webcompy_server-0.0.14.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
34
+ webcompy_server-0.0.14.dist-info/licenses/LICENSE,sha256=endi3iQMQFbLs2ZrHgpdhZB7G0qTxwHw_DcSn6PjQrM,1069
35
+ webcompy_server-0.0.14.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Kento NIWASE
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.