pondsocket-asgi 0.0.1__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,17 @@
1
+ from __future__ import annotations
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from .app import PondASGIApp
6
+ from .transport import ASGIWebSocketTransport
7
+
8
+ try:
9
+ __version__ = version("pondsocket-asgi")
10
+ except PackageNotFoundError:
11
+ __version__ = "0.0.1"
12
+
13
+ __all__ = [
14
+ "ASGIWebSocketTransport",
15
+ "PondASGIApp",
16
+ "__version__",
17
+ ]
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ from http.cookies import SimpleCookie
4
+ from typing import Any
5
+ from urllib.parse import parse_qs
6
+
7
+ from pondsocket.types import Route
8
+ from pondsocket_common import Headers, IncomingConnection
9
+
10
+
11
+ def parse_query(query_string: bytes) -> dict[str, str]:
12
+ if not query_string:
13
+ return {}
14
+ qs = query_string.decode("utf-8", errors="replace")
15
+ parsed = parse_qs(qs, keep_blank_values=True)
16
+ return {k: v[0] if v else "" for k, v in parsed.items()}
17
+
18
+
19
+ def parse_cookies(headers: Headers) -> dict[str, str]:
20
+ cookie_header = headers.get("cookie")
21
+ if cookie_header is None:
22
+ return {}
23
+ jar: SimpleCookie = SimpleCookie()
24
+ try:
25
+ jar.load(cookie_header)
26
+ except Exception:
27
+ return {}
28
+ return {key: morsel.value for key, morsel in jar.items()}
29
+
30
+
31
+ def client_address(scope: dict[str, Any]) -> str:
32
+ client = scope.get("client")
33
+ if client and isinstance(client, (list, tuple)) and len(client) >= 1:
34
+ host = client[0]
35
+ if isinstance(host, str):
36
+ return host
37
+ return ""
38
+
39
+
40
+ def build_incoming_connection(
41
+ *,
42
+ user_id: str,
43
+ scope: dict[str, Any],
44
+ route: Route,
45
+ ) -> IncomingConnection:
46
+ raw_headers = scope.get("headers", [])
47
+ headers = Headers(raw_headers)
48
+ return IncomingConnection(
49
+ id=user_id,
50
+ address=client_address(scope),
51
+ headers=headers,
52
+ cookies=parse_cookies(headers),
53
+ query=parse_query(scope.get("query_string", b"")),
54
+ params=dict(route.params),
55
+ )
@@ -0,0 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ from pondsocket.wire import (
4
+ event_to_json,
5
+ event_to_wire,
6
+ parse_inbound_text,
7
+ wire_to_event,
8
+ )
9
+
10
+ __all__ = [
11
+ "event_to_json",
12
+ "event_to_wire",
13
+ "parse_inbound_text",
14
+ "wire_to_event",
15
+ ]
@@ -0,0 +1,14 @@
1
+ from __future__ import annotations
2
+
3
+ from pondsocket.types import Event
4
+ from pondsocket.wire import event_to_json
5
+
6
+
7
+ def event_to_sse_frame(event: Event) -> bytes:
8
+ body = event_to_json(event)
9
+ name = event.event or "message"
10
+ return f"event: {name}\ndata: {body}\n\n".encode()
11
+
12
+
13
+ def sse_comment(text: str) -> bytes:
14
+ return f": {text}\n\n".encode()
pondsocket_asgi/app.py ADDED
@@ -0,0 +1,386 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections.abc import Awaitable, Callable
5
+ from typing import Any, TypeAlias
6
+
7
+ from pondsocket import (
8
+ ConnectionContext,
9
+ Endpoint,
10
+ Event,
11
+ PondSocket,
12
+ SystemEntity,
13
+ )
14
+ from pondsocket.sse_transport import SSEServerTransport
15
+ from pondsocket.transport import PushableTransport, Transport
16
+ from pondsocket_common import Headers, ServerActions, uuid
17
+
18
+ from ._scope import build_incoming_connection
19
+ from ._sse import event_to_sse_frame
20
+ from .transport import ASGIWebSocketTransport
21
+
22
+ ASGISend: TypeAlias = Callable[[dict[str, Any]], Awaitable[None]]
23
+ ASGIReceive: TypeAlias = Callable[[], Awaitable[dict[str, Any]]]
24
+
25
+ _SSE_INIT_HEADERS: list[tuple[bytes, bytes]] = [
26
+ (b"content-type", b"text/event-stream; charset=utf-8"),
27
+ (b"cache-control", b"no-cache, no-transform"),
28
+ (b"connection", b"keep-alive"),
29
+ (b"x-accel-buffering", b"no"),
30
+ ]
31
+
32
+
33
+ def _http_to_ws_close_code(http_code: int) -> int:
34
+ if 1000 <= http_code <= 4999:
35
+ return http_code
36
+ if 100 <= http_code <= 999:
37
+ return 4000 + http_code
38
+ return 1008
39
+
40
+
41
+ class PondASGIApp:
42
+ __slots__ = ("_pond",)
43
+
44
+ def __init__(self, pond: PondSocket) -> None:
45
+ self._pond = pond
46
+
47
+ @property
48
+ def pond(self) -> PondSocket:
49
+ return self._pond
50
+
51
+ async def __call__(
52
+ self,
53
+ scope: dict[str, Any],
54
+ receive: ASGIReceive,
55
+ send: ASGISend,
56
+ ) -> None:
57
+ scope_type = scope.get("type")
58
+ if scope_type == "lifespan":
59
+ await self._handle_lifespan(receive, send)
60
+ return
61
+ if scope_type == "websocket":
62
+ await self._handle_websocket(scope, receive, send)
63
+ return
64
+ if scope_type == "http":
65
+ await self._handle_http(scope, receive, send)
66
+ return
67
+ raise RuntimeError(f"PondASGIApp does not support scope type: {scope_type!r}")
68
+
69
+ async def _handle_lifespan(self, receive: ASGIReceive, send: ASGISend) -> None:
70
+ while True:
71
+ event = await receive()
72
+ event_type = event.get("type")
73
+ if event_type == "lifespan.startup":
74
+ await send({"type": "lifespan.startup.complete"})
75
+ elif event_type == "lifespan.shutdown":
76
+ try:
77
+ await self._pond.close()
78
+ except Exception as e:
79
+ await send(
80
+ {
81
+ "type": "lifespan.shutdown.failed",
82
+ "message": str(e),
83
+ }
84
+ )
85
+ return
86
+ await send({"type": "lifespan.shutdown.complete"})
87
+ return
88
+ else:
89
+ return
90
+
91
+ async def _handle_websocket(
92
+ self,
93
+ scope: dict[str, Any],
94
+ receive: ASGIReceive,
95
+ send: ASGISend,
96
+ ) -> None:
97
+ path = scope.get("path", "")
98
+ match = self._pond.match_endpoint(path)
99
+ if match is None:
100
+ await self._reject_websocket_before_accept(
101
+ send, code=4404, reason="endpoint not found"
102
+ )
103
+ return
104
+ endpoint = match.endpoint
105
+ route = match.route
106
+
107
+ first = await receive()
108
+ if first.get("type") != "websocket.connect":
109
+ return
110
+
111
+ user_id = uuid()
112
+ incoming = build_incoming_connection(
113
+ user_id=user_id, scope=scope, route=route
114
+ )
115
+ ctx = await endpoint.request_connection(incoming, user_id=user_id)
116
+
117
+ if ctx.is_declined:
118
+ code, message = ctx.decline_info
119
+ await self._reject_websocket_before_accept(
120
+ send, code=_http_to_ws_close_code(code), reason=message
121
+ )
122
+ return
123
+
124
+ await send({"type": "websocket.accept"})
125
+ transport = ASGIWebSocketTransport(
126
+ id=ctx.user_id,
127
+ send=send,
128
+ receive=receive,
129
+ assigns=ctx.assigns,
130
+ )
131
+ await endpoint.register_transport(transport)
132
+ await self._send_pending_reply(ctx, transport, endpoint)
133
+ await transport.wait_until_closed()
134
+
135
+ async def _handle_http(
136
+ self,
137
+ scope: dict[str, Any],
138
+ receive: ASGIReceive,
139
+ send: ASGISend,
140
+ ) -> None:
141
+ method = scope.get("method", "")
142
+ headers = Headers(scope.get("headers", []))
143
+
144
+ if method == "GET" and _is_sse_request(headers):
145
+ await self._handle_sse_init(scope, receive, send, headers)
146
+ return
147
+ connection_id = headers.get("x-connection-id")
148
+ if method == "POST" and connection_id:
149
+ await self._handle_sse_push(receive, send, connection_id)
150
+ return
151
+ if method == "DELETE" and connection_id:
152
+ await self._handle_sse_disconnect(send, connection_id)
153
+ return
154
+ await self._send_simple_http(send, status=404, body=b"PondSocket: not found")
155
+
156
+ async def _handle_sse_init(
157
+ self,
158
+ scope: dict[str, Any],
159
+ receive: ASGIReceive,
160
+ send: ASGISend,
161
+ _headers: Headers,
162
+ ) -> None:
163
+ path = scope.get("path", "")
164
+ match = self._pond.match_endpoint(path)
165
+ if match is None:
166
+ await self._send_simple_http(
167
+ send, status=404, body=b"endpoint not found"
168
+ )
169
+ return
170
+ endpoint = match.endpoint
171
+ route = match.route
172
+
173
+ user_id = uuid()
174
+ incoming = build_incoming_connection(
175
+ user_id=user_id, scope=scope, route=route
176
+ )
177
+ ctx = await endpoint.request_connection(incoming, user_id=user_id)
178
+
179
+ if ctx.is_declined:
180
+ code, message = ctx.decline_info
181
+ await self._send_simple_http(
182
+ send, status=code, body=message.encode("utf-8")
183
+ )
184
+ return
185
+
186
+ sse_headers: list[tuple[bytes, bytes]] = [
187
+ *_SSE_INIT_HEADERS,
188
+ (b"x-connection-id", ctx.user_id.encode("utf-8")),
189
+ ]
190
+ await send(
191
+ {
192
+ "type": "http.response.start",
193
+ "status": 200,
194
+ "headers": sse_headers,
195
+ }
196
+ )
197
+
198
+ transport = SSEServerTransport(id=ctx.user_id, assigns=ctx.assigns)
199
+ await endpoint.register_transport(transport)
200
+ await self._send_pending_reply_sse(ctx, transport)
201
+
202
+ await self._stream_sse(transport, receive, send)
203
+
204
+ async def _stream_sse(
205
+ self,
206
+ transport: SSEServerTransport,
207
+ receive: ASGIReceive,
208
+ send: ASGISend,
209
+ ) -> None:
210
+ disconnect_task = asyncio.create_task(_watch_disconnect(receive))
211
+ try:
212
+ while transport.is_active():
213
+ next_task = asyncio.create_task(transport.next_event())
214
+ done, _pending = await asyncio.wait(
215
+ {next_task, disconnect_task},
216
+ return_when=asyncio.FIRST_COMPLETED,
217
+ )
218
+ if disconnect_task in done:
219
+ next_task.cancel()
220
+ break
221
+ event = next_task.result()
222
+ if event is None:
223
+ break
224
+ frame = event_to_sse_frame(event)
225
+ try:
226
+ await send(
227
+ {
228
+ "type": "http.response.body",
229
+ "body": frame,
230
+ "more_body": True,
231
+ }
232
+ )
233
+ except Exception:
234
+ break
235
+ finally:
236
+ disconnect_task.cancel()
237
+ await transport.close()
238
+ try:
239
+ await send(
240
+ {"type": "http.response.body", "body": b"", "more_body": False}
241
+ )
242
+ except Exception:
243
+ return
244
+
245
+ async def _handle_sse_push(
246
+ self,
247
+ receive: ASGIReceive,
248
+ send: ASGISend,
249
+ connection_id: str,
250
+ ) -> None:
251
+ transport = await self._pond.find_transport(connection_id)
252
+ if transport is None:
253
+ await self._send_simple_http(
254
+ send, status=404, body=b"connection not found"
255
+ )
256
+ return
257
+ if not isinstance(transport, PushableTransport):
258
+ await self._send_simple_http(
259
+ send,
260
+ status=400,
261
+ body=b"connection does not accept inbound messages",
262
+ )
263
+ return
264
+ body = await _read_body(receive)
265
+ await transport.push_message(body)
266
+ await self._send_simple_http(send, status=204, body=b"")
267
+
268
+ async def _handle_sse_disconnect(
269
+ self,
270
+ send: ASGISend,
271
+ connection_id: str,
272
+ ) -> None:
273
+ transport = await self._pond.find_transport(connection_id)
274
+ if transport is None:
275
+ await self._send_simple_http(send, status=404, body=b"")
276
+ return
277
+ await transport.close()
278
+ await self._send_simple_http(send, status=204, body=b"")
279
+
280
+ async def _send_pending_reply(
281
+ self,
282
+ ctx: ConnectionContext,
283
+ transport: Transport,
284
+ _endpoint: Endpoint,
285
+ ) -> None:
286
+ if ctx.pending_reply is None:
287
+ return
288
+ name, payload = ctx.pending_reply
289
+ ev = Event(
290
+ action=ServerActions.SYSTEM.value,
291
+ channel_name=SystemEntity.GATEWAY.value,
292
+ request_id=uuid(),
293
+ event=name,
294
+ payload=payload,
295
+ )
296
+ try:
297
+ await transport.send_event(ev)
298
+ except Exception:
299
+ return
300
+
301
+ async def _send_pending_reply_sse(
302
+ self,
303
+ ctx: ConnectionContext,
304
+ transport: SSEServerTransport,
305
+ ) -> None:
306
+ if ctx.pending_reply is None:
307
+ return
308
+ name, payload = ctx.pending_reply
309
+ ev = Event(
310
+ action=ServerActions.SYSTEM.value,
311
+ channel_name=SystemEntity.GATEWAY.value,
312
+ request_id=uuid(),
313
+ event=name,
314
+ payload=payload,
315
+ )
316
+ try:
317
+ await transport.send_event(ev)
318
+ except Exception:
319
+ return
320
+
321
+ async def _reject_websocket_before_accept(
322
+ self,
323
+ send: ASGISend,
324
+ *,
325
+ code: int,
326
+ reason: str,
327
+ ) -> None:
328
+ first = {"type": "websocket.close", "code": code, "reason": reason[:123]}
329
+ try:
330
+ await send(first)
331
+ except Exception:
332
+ return
333
+
334
+ async def _send_simple_http(
335
+ self,
336
+ send: ASGISend,
337
+ *,
338
+ status: int,
339
+ body: bytes,
340
+ ) -> None:
341
+ try:
342
+ await send(
343
+ {
344
+ "type": "http.response.start",
345
+ "status": status,
346
+ "headers": [(b"content-type", b"text/plain; charset=utf-8")],
347
+ }
348
+ )
349
+ await send(
350
+ {
351
+ "type": "http.response.body",
352
+ "body": body,
353
+ "more_body": False,
354
+ }
355
+ )
356
+ except Exception:
357
+ return
358
+
359
+
360
+ def _is_sse_request(headers: Headers) -> bool:
361
+ accept = headers.get("accept", "")
362
+ return "text/event-stream" in accept
363
+
364
+
365
+ async def _read_body(receive: ASGIReceive) -> bytes:
366
+ chunks: list[bytes] = []
367
+ while True:
368
+ msg = await receive()
369
+ msg_type = msg.get("type")
370
+ if msg_type == "http.request":
371
+ chunks.append(msg.get("body", b""))
372
+ if not msg.get("more_body", False):
373
+ break
374
+ elif msg_type == "http.disconnect":
375
+ break
376
+ return b"".join(chunks)
377
+
378
+
379
+ async def _watch_disconnect(receive: ASGIReceive) -> None:
380
+ while True:
381
+ try:
382
+ msg = await receive()
383
+ except asyncio.CancelledError:
384
+ return
385
+ if msg.get("type") == "http.disconnect":
386
+ return
File without changes
@@ -0,0 +1,313 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from pondsocket_common import uuid
9
+
10
+ from .app import PondASGIApp
11
+
12
+
13
+ @dataclass(slots=True)
14
+ class WebSocketSession:
15
+ scope: dict[str, Any]
16
+ inbox: asyncio.Queue[dict[str, Any]]
17
+ outbox: asyncio.Queue[dict[str, Any]]
18
+ app_task: asyncio.Task[None]
19
+ accepted: bool = False
20
+ closed: bool = False
21
+
22
+ async def send_text(self, text: str) -> None:
23
+ await self.inbox.put({"type": "websocket.receive", "text": text})
24
+
25
+ async def send_json(self, data: dict[str, Any]) -> None:
26
+ await self.send_text(json.dumps(data))
27
+
28
+ async def send_client_message(
29
+ self,
30
+ *,
31
+ action: str,
32
+ channel_name: str,
33
+ event: str,
34
+ payload: dict[str, Any] | None = None,
35
+ request_id: str | None = None,
36
+ ) -> str:
37
+ rid = request_id or uuid()
38
+ await self.send_json(
39
+ {
40
+ "action": action,
41
+ "channelName": channel_name,
42
+ "event": event,
43
+ "payload": payload or {},
44
+ "requestId": rid,
45
+ }
46
+ )
47
+ return rid
48
+
49
+ async def receive_message(self, *, wait: float = 1.0) -> dict[str, Any]:
50
+ msg = await asyncio.wait_for(self.outbox.get(), wait)
51
+ return msg
52
+
53
+ async def receive_json(self, *, wait: float = 1.0) -> dict[str, Any]:
54
+ msg = await self.receive_message(wait=wait)
55
+ if msg.get("type") != "websocket.send":
56
+ raise AssertionError(f"expected websocket.send, got {msg!r}")
57
+ text = msg.get("text")
58
+ if text is None:
59
+ raise AssertionError(f"expected text frame, got {msg!r}")
60
+ data = json.loads(text)
61
+ assert isinstance(data, dict)
62
+ return data
63
+
64
+ async def disconnect(self, code: int = 1000) -> None:
65
+ if not self.closed:
66
+ self.closed = True
67
+ await self.inbox.put({"type": "websocket.disconnect", "code": code})
68
+ try:
69
+ await asyncio.wait_for(self.app_task, timeout=1.0)
70
+ except TimeoutError:
71
+ self.app_task.cancel()
72
+
73
+ def is_closed(self) -> bool:
74
+ return self.closed
75
+
76
+
77
+ @dataclass(slots=True)
78
+ class LifespanSession:
79
+ inbox: asyncio.Queue[dict[str, Any]]
80
+ outbox: asyncio.Queue[dict[str, Any]]
81
+ app_task: asyncio.Task[None]
82
+
83
+ async def startup(self) -> dict[str, Any]:
84
+ await self.inbox.put({"type": "lifespan.startup"})
85
+ return await asyncio.wait_for(self.outbox.get(), timeout=1.0)
86
+
87
+ async def shutdown(self) -> dict[str, Any]:
88
+ await self.inbox.put({"type": "lifespan.shutdown"})
89
+ msg = await asyncio.wait_for(self.outbox.get(), timeout=1.0)
90
+ try:
91
+ await asyncio.wait_for(self.app_task, timeout=1.0)
92
+ except TimeoutError:
93
+ self.app_task.cancel()
94
+ return msg
95
+
96
+
97
+ @dataclass(slots=True)
98
+ class _ASGIQueues:
99
+ inbox: asyncio.Queue[dict[str, Any]] = field(default_factory=asyncio.Queue)
100
+ outbox: asyncio.Queue[dict[str, Any]] = field(default_factory=asyncio.Queue)
101
+
102
+ def receive(self) -> Any:
103
+ async def _recv() -> dict[str, Any]:
104
+ return await self.inbox.get()
105
+
106
+ return _recv
107
+
108
+ def send(self) -> Any:
109
+ async def _send(message: dict[str, Any]) -> None:
110
+ await self.outbox.put(message)
111
+
112
+ return _send
113
+
114
+
115
+ class ASGITestDriver:
116
+ __slots__ = ("_app",)
117
+
118
+ def __init__(self, app: PondASGIApp) -> None:
119
+ self._app = app
120
+
121
+ async def connect_websocket(
122
+ self,
123
+ path: str,
124
+ *,
125
+ query_string: bytes = b"",
126
+ headers: list[tuple[bytes, bytes]] | None = None,
127
+ client: tuple[str, int] | None = ("127.0.0.1", 12345),
128
+ subprotocols: list[str] | None = None,
129
+ ) -> WebSocketSession:
130
+ scope: dict[str, Any] = {
131
+ "type": "websocket",
132
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
133
+ "scheme": "ws",
134
+ "server": ("localhost", 80),
135
+ "client": client,
136
+ "root_path": "",
137
+ "path": path,
138
+ "raw_path": path.encode("utf-8"),
139
+ "query_string": query_string,
140
+ "headers": headers or [],
141
+ "subprotocols": subprotocols or [],
142
+ }
143
+ queues = _ASGIQueues()
144
+ task = asyncio.create_task(self._app(scope, queues.receive(), queues.send()))
145
+ session = WebSocketSession(
146
+ scope=scope, inbox=queues.inbox, outbox=queues.outbox, app_task=task
147
+ )
148
+ await session.inbox.put({"type": "websocket.connect"})
149
+ first = await asyncio.wait_for(session.outbox.get(), timeout=1.0)
150
+ if first.get("type") == "websocket.accept":
151
+ session.accepted = True
152
+ return session
153
+ if first.get("type") == "websocket.close":
154
+ session.closed = True
155
+ await asyncio.wait_for(task, timeout=1.0)
156
+ await session.outbox.put(first)
157
+ return session
158
+ raise AssertionError(f"unexpected first server message: {first!r}")
159
+
160
+ async def open_lifespan(self) -> LifespanSession:
161
+ scope: dict[str, Any] = {
162
+ "type": "lifespan",
163
+ "asgi": {"version": "3.0", "spec_version": "2.0"},
164
+ }
165
+ queues = _ASGIQueues()
166
+ task = asyncio.create_task(self._app(scope, queues.receive(), queues.send()))
167
+ return LifespanSession(inbox=queues.inbox, outbox=queues.outbox, app_task=task)
168
+
169
+ async def call_http(
170
+ self,
171
+ path: str,
172
+ *,
173
+ method: str = "GET",
174
+ headers: list[tuple[bytes, bytes]] | None = None,
175
+ body: bytes = b"",
176
+ ) -> tuple[int, bytes]:
177
+ scope: dict[str, Any] = {
178
+ "type": "http",
179
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
180
+ "http_version": "1.1",
181
+ "method": method,
182
+ "scheme": "http",
183
+ "path": path,
184
+ "raw_path": path.encode("utf-8"),
185
+ "query_string": b"",
186
+ "headers": headers or [],
187
+ "client": ("127.0.0.1", 12345),
188
+ "server": ("localhost", 80),
189
+ }
190
+ queues = _ASGIQueues()
191
+ await queues.inbox.put(
192
+ {"type": "http.request", "body": body, "more_body": False}
193
+ )
194
+ await self._app(scope, queues.receive(), queues.send())
195
+ start = await queues.outbox.get()
196
+ body_msg = await queues.outbox.get()
197
+ return start["status"], body_msg.get("body", b"")
198
+
199
+ async def connect_sse(
200
+ self,
201
+ path: str,
202
+ *,
203
+ query_string: bytes = b"",
204
+ headers: list[tuple[bytes, bytes]] | None = None,
205
+ ) -> SSESession:
206
+ all_headers: list[tuple[bytes, bytes]] = [
207
+ *(headers or []),
208
+ (b"accept", b"text/event-stream"),
209
+ ]
210
+ scope: dict[str, Any] = {
211
+ "type": "http",
212
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
213
+ "http_version": "1.1",
214
+ "method": "GET",
215
+ "scheme": "http",
216
+ "path": path,
217
+ "raw_path": path.encode("utf-8"),
218
+ "query_string": query_string,
219
+ "headers": all_headers,
220
+ "client": ("127.0.0.1", 12345),
221
+ "server": ("localhost", 80),
222
+ }
223
+ queues = _ASGIQueues()
224
+ await queues.inbox.put(
225
+ {"type": "http.request", "body": b"", "more_body": False}
226
+ )
227
+ task = asyncio.create_task(
228
+ self._app(scope, queues.receive(), queues.send())
229
+ )
230
+ start = await asyncio.wait_for(queues.outbox.get(), timeout=1.0)
231
+ connection_id = ""
232
+ accepted = False
233
+ if start.get("type") == "http.response.start" and start.get("status") == 200:
234
+ accepted = True
235
+ for name, value in start.get("headers", []):
236
+ if name == b"x-connection-id":
237
+ connection_id = value.decode("utf-8")
238
+ break
239
+ return SSESession(
240
+ scope=scope,
241
+ inbox=queues.inbox,
242
+ outbox=queues.outbox,
243
+ app_task=task,
244
+ connection_id=connection_id,
245
+ status=start.get("status", 0),
246
+ accepted=accepted,
247
+ )
248
+
249
+ async def sse_push(
250
+ self, connection_id: str, payload: dict[str, Any]
251
+ ) -> tuple[int, bytes]:
252
+ body = json.dumps(payload).encode("utf-8")
253
+ return await self.call_http(
254
+ "/push",
255
+ method="POST",
256
+ headers=[
257
+ (b"x-connection-id", connection_id.encode("utf-8")),
258
+ (b"content-type", b"application/json"),
259
+ ],
260
+ body=body,
261
+ )
262
+
263
+ async def sse_disconnect(self, connection_id: str) -> tuple[int, bytes]:
264
+ return await self.call_http(
265
+ "/disconnect",
266
+ method="DELETE",
267
+ headers=[(b"x-connection-id", connection_id.encode("utf-8"))],
268
+ )
269
+
270
+
271
+ @dataclass(slots=True)
272
+ class SSESession:
273
+ scope: dict[str, Any]
274
+ inbox: asyncio.Queue[dict[str, Any]]
275
+ outbox: asyncio.Queue[dict[str, Any]]
276
+ app_task: asyncio.Task[None]
277
+ connection_id: str
278
+ status: int
279
+ accepted: bool
280
+
281
+ async def receive_frame_bytes(self, *, wait: float = 1.0) -> bytes:
282
+ msg = await asyncio.wait_for(self.outbox.get(), wait)
283
+ if msg.get("type") != "http.response.body":
284
+ raise AssertionError(f"expected http.response.body, got {msg!r}")
285
+ body = msg.get("body", b"")
286
+ assert isinstance(body, bytes)
287
+ return body
288
+
289
+ async def receive_event(self, *, wait: float = 1.0) -> dict[str, Any]:
290
+ frame = await self.receive_frame_bytes(wait=wait)
291
+ text = frame.decode("utf-8").strip()
292
+ for line in text.split("\n"):
293
+ if line.startswith("data: "):
294
+ data = json.loads(line[6:])
295
+ assert isinstance(data, dict)
296
+ return data
297
+ raise AssertionError(f"no data line in SSE frame: {text!r}")
298
+
299
+ async def receive_event_named(
300
+ self, event_name: str, *, wait: float = 1.0, attempts: int = 10
301
+ ) -> dict[str, Any]:
302
+ for _ in range(attempts):
303
+ data = await self.receive_event(wait=wait)
304
+ if data.get("event") == event_name:
305
+ return data
306
+ raise AssertionError(f"did not receive event {event_name!r}")
307
+
308
+ async def disconnect(self) -> None:
309
+ await self.inbox.put({"type": "http.disconnect"})
310
+ try:
311
+ await asyncio.wait_for(self.app_task, timeout=1.0)
312
+ except TimeoutError:
313
+ self.app_task.cancel()
@@ -0,0 +1,174 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections.abc import Awaitable, Callable
5
+ from typing import Any, TypeAlias
6
+
7
+ from pondsocket.errors import internal
8
+ from pondsocket.transport import OnCloseCallback, OnMessageHandler
9
+ from pondsocket.types import Event, SystemEntity, TransportType
10
+ from pondsocket_common import ErrorTypes, ServerActions, ValidationError, uuid
11
+
12
+ from ._serialize import event_to_json, parse_inbound_text
13
+
14
+ ASGISend: TypeAlias = Callable[[dict[str, Any]], Awaitable[None]]
15
+ ASGIReceive: TypeAlias = Callable[[], Awaitable[dict[str, Any]]]
16
+
17
+
18
+ class ASGIWebSocketTransport:
19
+ __slots__ = (
20
+ "_active",
21
+ "_assigns",
22
+ "_close_callbacks",
23
+ "_closed_event",
24
+ "_id",
25
+ "_message_handler",
26
+ "_receive",
27
+ "_receive_task",
28
+ "_send",
29
+ "_send_lock",
30
+ )
31
+
32
+ def __init__(
33
+ self,
34
+ *,
35
+ id: str,
36
+ send: ASGISend,
37
+ receive: ASGIReceive,
38
+ assigns: dict[str, Any] | None = None,
39
+ ) -> None:
40
+ self._id = id
41
+ self._send = send
42
+ self._receive = receive
43
+ self._assigns: dict[str, Any] = dict(assigns or {})
44
+ self._active = True
45
+ self._close_callbacks: list[OnCloseCallback] = []
46
+ self._message_handler: OnMessageHandler | None = None
47
+ self._receive_task: asyncio.Task[None] | None = None
48
+ self._closed_event = asyncio.Event()
49
+ self._send_lock = asyncio.Lock()
50
+
51
+ def get_id(self) -> str:
52
+ return self._id
53
+
54
+ def get_assign(self, key: str) -> Any:
55
+ return self._assigns.get(key)
56
+
57
+ def set_assign(self, key: str, value: Any) -> None:
58
+ self._assigns[key] = value
59
+
60
+ def clone_assigns(self) -> dict[str, Any]:
61
+ return dict(self._assigns)
62
+
63
+ def is_active(self) -> bool:
64
+ return self._active
65
+
66
+ def transport_type(self) -> TransportType:
67
+ return TransportType.WEBSOCKET
68
+
69
+ async def send_event(self, event: Event) -> None:
70
+ if not self._active:
71
+ raise internal("", "Transport is closed")
72
+ wire = event_to_json(event)
73
+ async with self._send_lock:
74
+ try:
75
+ await self._send({"type": "websocket.send", "text": wire})
76
+ except Exception as e:
77
+ raise internal("", f"WebSocket send failed: {e}") from e
78
+
79
+ async def close(self, *, code: int = 1000, reason: str = "") -> None:
80
+ if not self._active:
81
+ return
82
+ self._active = False
83
+ try:
84
+ async with self._send_lock:
85
+ await self._send(
86
+ {"type": "websocket.close", "code": code, "reason": reason[:123]}
87
+ )
88
+ except Exception:
89
+ pass
90
+ await self._fire_close_callbacks()
91
+ if self._receive_task is not None and not self._receive_task.done():
92
+ self._receive_task.cancel()
93
+ self._closed_event.set()
94
+
95
+ def on_close(self, callback: OnCloseCallback) -> None:
96
+ self._close_callbacks.append(callback)
97
+
98
+ def on_message(self, handler: OnMessageHandler) -> None:
99
+ self._message_handler = handler
100
+
101
+ async def handle_messages(self) -> None:
102
+ if self._message_handler is None:
103
+ raise RuntimeError("on_message must be set before handle_messages")
104
+ if self._receive_task is not None and not self._receive_task.done():
105
+ return
106
+ self._receive_task = asyncio.create_task(self._receive_loop())
107
+
108
+ async def wait_until_closed(self) -> None:
109
+ await self._closed_event.wait()
110
+
111
+ async def _receive_loop(self) -> None:
112
+ assert self._message_handler is not None
113
+ try:
114
+ while True:
115
+ try:
116
+ msg = await self._receive()
117
+ except asyncio.CancelledError:
118
+ return
119
+ if not self._active:
120
+ return
121
+ msg_type = msg.get("type")
122
+ if msg_type == "websocket.disconnect":
123
+ self._active = False
124
+ await self._fire_close_callbacks()
125
+ self._closed_event.set()
126
+ return
127
+ if msg_type != "websocket.receive":
128
+ continue
129
+ await self._dispatch_receive(msg)
130
+ except asyncio.CancelledError:
131
+ return
132
+
133
+ async def _dispatch_receive(self, msg: dict[str, Any]) -> None:
134
+ text = msg.get("text")
135
+ if text is None:
136
+ bytes_payload = msg.get("bytes")
137
+ if bytes_payload is None:
138
+ return
139
+ try:
140
+ text = bytes_payload.decode("utf-8")
141
+ except UnicodeDecodeError:
142
+ await self._send_invalid_message("Binary frame is not valid UTF-8")
143
+ return
144
+ try:
145
+ event = parse_inbound_text(text)
146
+ except ValidationError as e:
147
+ await self._send_invalid_message(str(e))
148
+ return
149
+ if self._message_handler is None:
150
+ return
151
+ try:
152
+ await self._message_handler(event, self)
153
+ except Exception:
154
+ return
155
+
156
+ async def _fire_close_callbacks(self) -> None:
157
+ for cb in list(self._close_callbacks):
158
+ try:
159
+ await cb(self)
160
+ except Exception:
161
+ continue
162
+
163
+ async def _send_invalid_message(self, detail: str) -> None:
164
+ ev = Event(
165
+ action=ServerActions.ERROR.value,
166
+ channel_name=SystemEntity.GATEWAY.value,
167
+ request_id=uuid(),
168
+ event=ErrorTypes.INVALID_MESSAGE.value,
169
+ payload={"error": detail},
170
+ )
171
+ try:
172
+ await self.send_event(ev)
173
+ except Exception:
174
+ return
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: pondsocket-asgi
3
+ Version: 0.0.1
4
+ Summary: Canonical ASGI adapter for PondSocket.
5
+ Author: eleven-am
6
+ License: GPL-3.0-or-later
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: pondsocket-common<0.1.0,>=0.0.1
9
+ Requires-Dist: pondsocket<0.1.0,>=0.0.1
10
+ Description-Content-Type: text/markdown
11
+
12
+ # pondsocket-asgi
13
+
14
+ Canonical ASGI adapter for [`pondsocket`](../pondsocket/). Mount under any ASGI host — FastAPI, Starlette, Litestar, Django, raw uvicorn.
15
+
16
+ Handles WebSocket and SSE (Server-Sent Events) transports. The same `PondSocket` instance serves both — the adapter detects the request type and dispatches.
17
+
18
+ ## Install
19
+
20
+ ```
21
+ pip install pondsocket-asgi
22
+ ```
23
+
24
+ Pulls in `pondsocket` and `pondsocket-common` automatically.
25
+
26
+ ## Quick start: raw uvicorn
27
+
28
+ ```python
29
+ from pondsocket import ConnectionContext, EventContext, JoinContext, PondSocket
30
+ from pondsocket_asgi import PondASGIApp
31
+
32
+
33
+ async def auth(ctx: ConnectionContext) -> None:
34
+ ctx.accept()
35
+
36
+
37
+ async def on_join(ctx: JoinContext) -> None:
38
+ await ctx.accept()
39
+
40
+
41
+ async def on_message(ctx: EventContext) -> None:
42
+ await ctx.broadcast(ctx.event_name, ctx.get_payload())
43
+
44
+
45
+ pond = PondSocket()
46
+ endpoint = pond.create_endpoint("/socket", auth)
47
+ lobby = endpoint.create_channel("/chat/:room_id", on_join)
48
+ lobby.on_message("message", on_message)
49
+
50
+ app = PondASGIApp(pond)
51
+ ```
52
+
53
+ ```
54
+ uvicorn module:app --host 127.0.0.1 --port 8000
55
+ ```
56
+
57
+ WebSocket clients connect to `ws://127.0.0.1:8000/socket`.
58
+
59
+ ## Mount under FastAPI
60
+
61
+ ```python
62
+ from fastapi import FastAPI
63
+ from pondsocket_asgi import PondASGIApp
64
+
65
+ app = FastAPI()
66
+ app.mount("/ws", PondASGIApp(pond))
67
+ ```
68
+
69
+ When mounted at `/ws`, the adapter sees `scope["path"]` already stripped of the prefix — register your pond endpoints with the *post-mount* path (e.g. `/socket` resolves at `ws://host/ws/socket`).
70
+
71
+ See [`examples/`](./examples/) for FastAPI, Starlette, and raw uvicorn variants.
72
+
73
+ ## SSE transport
74
+
75
+ The same endpoint serves Server-Sent Events to clients that don't have WebSocket:
76
+
77
+ ```
78
+ GET /socket
79
+ Accept: text/event-stream
80
+ → 200, response carries X-Connection-ID header and a `CONNECTION` event with `payload.connectionId`, stream of "event: <name>\ndata: <json>\n\n" frames
81
+
82
+ POST /socket
83
+ X-Connection-ID: <id>
84
+ Content-Type: application/json
85
+ body: <client message JSON>
86
+ → 204
87
+
88
+ DELETE /socket
89
+ X-Connection-ID: <id>
90
+ → 204
91
+ ```
92
+
93
+ Use SSE when WebSocket is blocked (some corporate proxies). The connection handler is the same — the adapter routes by `Accept` header and method.
94
+
95
+ ## Lifespan
96
+
97
+ `PondASGIApp` handles the ASGI lifespan protocol. On `lifespan.startup`, it acknowledges immediately. On `lifespan.shutdown`, it closes the PondSocket (which closes every endpoint, every channel, every transport).
98
+
99
+ ## Testing
100
+
101
+ `pondsocket_asgi.testing` exposes an in-memory ASGI driver — no real network needed:
102
+
103
+ ```python
104
+ from pondsocket_asgi.testing import ASGITestDriver
105
+
106
+ driver = ASGITestDriver(PondASGIApp(pond))
107
+
108
+ # WebSocket
109
+ session = await driver.connect_websocket("/socket")
110
+ await session.send_client_message(
111
+ action="JOIN_CHANNEL",
112
+ channel_name="/chat/1",
113
+ event="join",
114
+ )
115
+ ack = await session.receive_json()
116
+ await session.disconnect()
117
+
118
+ # SSE
119
+ sse = await driver.connect_sse("/socket")
120
+ status, _ = await driver.sse_push(sse.connection_id, {"action": "BROADCAST", ...})
121
+ frame = await sse.receive_event()
122
+ await sse.disconnect()
123
+
124
+ # Lifespan
125
+ lifespan = await driver.open_lifespan()
126
+ await lifespan.startup()
127
+ await lifespan.shutdown()
128
+ ```
129
+
130
+ ## Public API
131
+
132
+ `from pondsocket_asgi import ...`
133
+
134
+ - `PondASGIApp` — the adapter itself
135
+ - `ASGIWebSocketTransport` — WebSocket transport (you usually don't construct this directly; the app does)
136
+
137
+ `from pondsocket_asgi.testing import ...`
138
+
139
+ - `ASGITestDriver`, `WebSocketSession`, `LifespanSession`, `SSESession`
140
+
141
+ ## License
142
+
143
+ GPL-3.0-or-later.
@@ -0,0 +1,11 @@
1
+ pondsocket_asgi/__init__.py,sha256=Shha72surzvURqvgHNkl2OB3hWVrKp8PHAjm3g1nhhI,362
2
+ pondsocket_asgi/_scope.py,sha256=ZkD8wyclEeHqglhid9fP02_xk_Bj4qXKAMKQSBe5qO4,1539
3
+ pondsocket_asgi/_serialize.py,sha256=2MerN7M14wV00iB8EzJLvVDz0LTPRO9835OGygCS0y8,253
4
+ pondsocket_asgi/_sse.py,sha256=AVaRu_TJHViUbqj9S1Bcbx1X1-gzeSUqMUUZjWBBC8A,360
5
+ pondsocket_asgi/app.py,sha256=J_XdnUvH9MHlbXimg_79uMhV6EWFHcxkH95SMBYNEQs,11903
6
+ pondsocket_asgi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ pondsocket_asgi/testing.py,sha256=4GjW5_rBZwH3_dkfSXXeLG2ovIhXK4iDOBpfWauzsyc,10601
8
+ pondsocket_asgi/transport.py,sha256=mpuX88rZ_xJczL3DoOY5A99tsfACwwDzNTqSEV-kxFA,5734
9
+ pondsocket_asgi-0.0.1.dist-info/METADATA,sha256=QMGAUFFjj5mtaFKjMYpF0NCFRa8hb2o4mwXl2Wzi9ZA,3822
10
+ pondsocket_asgi-0.0.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
11
+ pondsocket_asgi-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any