pondsocket 0.0.5__tar.gz → 0.0.7__tar.gz
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.
- {pondsocket-0.0.5 → pondsocket-0.0.7}/PKG-INFO +2 -2
- {pondsocket-0.0.5 → pondsocket-0.0.7}/pyproject.toml +2 -2
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/channel.py +47 -36
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/endpoint.py +10 -15
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/sse_transport.py +22 -2
- pondsocket-0.0.7/tests/test_pondsocket_channel_lifecycle_adversarial.py +276 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_integration.py +31 -13
- pondsocket-0.0.7/tests/test_pondsocket_join_autodecline_adversarial.py +130 -0
- pondsocket-0.0.7/tests/test_pondsocket_leave_event_adversarial.py +184 -0
- pondsocket-0.0.7/tests/test_pondsocket_smoke.py +9 -0
- pondsocket-0.0.7/tests/test_pondsocket_sse_invalid_message_adversarial.py +112 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_sse_transport.py +60 -2
- pondsocket-0.0.5/tests/test_pondsocket_smoke.py +0 -7
- {pondsocket-0.0.5 → pondsocket-0.0.7}/.gitignore +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/README.md +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/__init__.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/contexts/__init__.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/contexts/connection_context.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/contexts/event_context.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/contexts/join_context.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/contexts/leave_context.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/contexts/outgoing_context.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/distributed/__init__.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/distributed/redis_pubsub.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/distributed_wire.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/errors.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/heartbeat.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/hooks.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/in_memory_transport.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/lobby.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/middleware.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/parser.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/presence.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/pubsub.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/pubsub_local.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/py.typed +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/server.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/store.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/transport.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/typed.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/types.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/src/pondsocket/wire.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_channel.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_distributed_local.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_distributed_protocol.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_errors.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_hooks_integration.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_hooks_unit.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_in_memory_transport.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_middleware.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_parser.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_presence.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_pubsub.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_redis_pubsub.py +0 -0
- {pondsocket-0.0.5 → pondsocket-0.0.7}/tests/test_pondsocket_store.py +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pondsocket
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.7
|
|
4
4
|
Summary: PondSocket - channel-based real-time framework with bring-your-own-server design.
|
|
5
5
|
Author: eleven-am
|
|
6
6
|
License: GPL-3.0-or-later
|
|
7
7
|
Requires-Python: >=3.11
|
|
8
|
-
Requires-Dist: pondsocket-common<0.1.0,>=0.0.
|
|
8
|
+
Requires-Dist: pondsocket-common<0.1.0,>=0.0.6
|
|
9
9
|
Provides-Extra: redis
|
|
10
10
|
Requires-Dist: redis>=5; extra == 'redis'
|
|
11
11
|
Description-Content-Type: text/markdown
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "pondsocket"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.7"
|
|
4
4
|
description = "PondSocket - channel-based real-time framework with bring-your-own-server design."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.11"
|
|
7
7
|
license = { text = "GPL-3.0-or-later" }
|
|
8
8
|
authors = [{ name = "eleven-am" }]
|
|
9
9
|
dependencies = [
|
|
10
|
-
"pondsocket-common>=0.0.
|
|
10
|
+
"pondsocket-common>=0.0.6,<0.1.0",
|
|
11
11
|
]
|
|
12
12
|
|
|
13
13
|
[project.optional-dependencies]
|
|
@@ -82,6 +82,7 @@ class Channel:
|
|
|
82
82
|
__slots__ = (
|
|
83
83
|
"_active",
|
|
84
84
|
"_assigns",
|
|
85
|
+
"_close_task",
|
|
85
86
|
"_connections",
|
|
86
87
|
"_dispatch_queue",
|
|
87
88
|
"_dispatch_semaphore",
|
|
@@ -121,23 +122,26 @@ class Channel:
|
|
|
121
122
|
self._on_destroy = opts.on_destroy
|
|
122
123
|
self._active: bool = False
|
|
123
124
|
self._connections: Store[Transport] = Store()
|
|
125
|
+
self._close_task: asyncio.Task[None] | None = None
|
|
124
126
|
self._assigns: Store[PondAssigns] = Store()
|
|
125
127
|
self._presence = PresenceClient(self)
|
|
126
128
|
self._dispatch_queue: asyncio.Queue[_DispatchItem] = asyncio.Queue(
|
|
127
129
|
self._options.internal_queue_buffer
|
|
128
130
|
)
|
|
129
|
-
self._dispatch_semaphore = asyncio.Semaphore(
|
|
130
|
-
self._options.dispatch_concurrency
|
|
131
|
-
)
|
|
131
|
+
self._dispatch_semaphore = asyncio.Semaphore(self._options.dispatch_concurrency)
|
|
132
132
|
self._dispatch_task: asyncio.Task[None] | None = None
|
|
133
133
|
self._lifecycle_lock = asyncio.Lock()
|
|
134
134
|
self._node_users: dict[str, set[str]] = {}
|
|
135
135
|
self._user_get_waiters: dict[str, asyncio.Future[User | None]] = {}
|
|
136
136
|
|
|
137
137
|
async def start(self) -> None:
|
|
138
|
+
close_task = self._close_task
|
|
139
|
+
if close_task is not None:
|
|
140
|
+
await asyncio.shield(close_task)
|
|
138
141
|
async with self._lifecycle_lock:
|
|
139
142
|
if self._active:
|
|
140
143
|
return
|
|
144
|
+
self._close_task = None
|
|
141
145
|
self._active = True
|
|
142
146
|
self._dispatch_task = asyncio.create_task(self._dispatch_loop())
|
|
143
147
|
await self._subscribe_to_pubsub()
|
|
@@ -147,14 +151,30 @@ class Channel:
|
|
|
147
151
|
|
|
148
152
|
async def close(self) -> None:
|
|
149
153
|
async with self._lifecycle_lock:
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
self.
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
154
|
+
close_task = self._close_task
|
|
155
|
+
if close_task is None:
|
|
156
|
+
if not self._active:
|
|
157
|
+
return
|
|
158
|
+
self._active = False
|
|
159
|
+
close_task = asyncio.create_task(
|
|
160
|
+
self._finish_close(),
|
|
161
|
+
name=f"pondsocket-channel-close:{self.name}",
|
|
162
|
+
)
|
|
163
|
+
self._close_task = close_task
|
|
164
|
+
|
|
165
|
+
if close_task is asyncio.current_task():
|
|
166
|
+
return
|
|
167
|
+
if self._dispatch_task is asyncio.current_task():
|
|
168
|
+
return
|
|
169
|
+
await asyncio.shield(close_task)
|
|
170
|
+
|
|
171
|
+
async def _finish_close(self) -> None:
|
|
172
|
+
dispatch_task = self._dispatch_task
|
|
173
|
+
self._dispatch_task = None
|
|
174
|
+
if dispatch_task is not None and not dispatch_task.done():
|
|
175
|
+
dispatch_task.cancel()
|
|
176
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
177
|
+
await dispatch_task
|
|
158
178
|
await self._unsubscribe_from_pubsub()
|
|
159
179
|
self._stop_liveness()
|
|
160
180
|
self._node_users.clear()
|
|
@@ -218,10 +238,10 @@ class Channel:
|
|
|
218
238
|
reason: str = LeaveReason.EXPLICIT_LEAVE.value,
|
|
219
239
|
*,
|
|
220
240
|
skip_distributed: bool = False,
|
|
221
|
-
) ->
|
|
241
|
+
) -> bool:
|
|
222
242
|
if not await self._connections.discard(user_id):
|
|
223
243
|
await self._publish_user_command("user:remove", user_id, reason)
|
|
224
|
-
return
|
|
244
|
+
return False
|
|
225
245
|
assigns = await self._assigns.get(user_id, {}) or {}
|
|
226
246
|
presence: PondPresence | None = None
|
|
227
247
|
if await self._presence.has(user_id):
|
|
@@ -241,7 +261,8 @@ class Channel:
|
|
|
241
261
|
await self._fire_leave_handler(user, reason)
|
|
242
262
|
|
|
243
263
|
if await self._connections.len() == 0:
|
|
244
|
-
await self.
|
|
264
|
+
await self.close()
|
|
265
|
+
return True
|
|
245
266
|
|
|
246
267
|
async def _fire_leave_handler(self, user: User, reason: str) -> None:
|
|
247
268
|
if self._leave_handler is None:
|
|
@@ -315,9 +336,7 @@ class Channel:
|
|
|
315
336
|
node_id=self.node_id,
|
|
316
337
|
)
|
|
317
338
|
await self._send_direct([user_id], ev)
|
|
318
|
-
await self.remove_user(
|
|
319
|
-
user_id, reason=LeaveReason.EVICTED.value, skip_distributed=True
|
|
320
|
-
)
|
|
339
|
+
await self.remove_user(user_id, reason=LeaveReason.EVICTED.value, skip_distributed=True)
|
|
321
340
|
|
|
322
341
|
async def broadcast(self, event_name: str, payload: PondMessage) -> None:
|
|
323
342
|
await self._send_event(
|
|
@@ -607,9 +626,7 @@ class Channel:
|
|
|
607
626
|
if self._pubsub is None or not self._endpoint_path:
|
|
608
627
|
return
|
|
609
628
|
topic = self._channel_topic()
|
|
610
|
-
data = distributed_bytes(
|
|
611
|
-
msg_type, self.node_id, self._clean_endpoint(), self.name, extra
|
|
612
|
-
)
|
|
629
|
+
data = distributed_bytes(msg_type, self.node_id, self._clean_endpoint(), self.name, extra)
|
|
613
630
|
try:
|
|
614
631
|
await self._pubsub.publish(topic, data)
|
|
615
632
|
except Exception:
|
|
@@ -696,9 +713,7 @@ class Channel:
|
|
|
696
713
|
existed = await self._presence.has(user_id)
|
|
697
714
|
await self._presence.set_remote(user_id, presence)
|
|
698
715
|
event.event = (
|
|
699
|
-
PresenceEventTypes.UPDATE.value
|
|
700
|
-
if existed
|
|
701
|
-
else PresenceEventTypes.JOIN.value
|
|
716
|
+
PresenceEventTypes.UPDATE.value if existed else PresenceEventTypes.JOIN.value
|
|
702
717
|
)
|
|
703
718
|
if isinstance(event.payload, dict):
|
|
704
719
|
event.payload["presence"] = await self._presence.values()
|
|
@@ -786,9 +801,7 @@ class Channel:
|
|
|
786
801
|
if not user_id or await self._connections.has(user_id):
|
|
787
802
|
continue
|
|
788
803
|
assigns = user.get("assigns")
|
|
789
|
-
await self._assigns.upsert(
|
|
790
|
-
user_id, dict(assigns) if isinstance(assigns, dict) else {}
|
|
791
|
-
)
|
|
804
|
+
await self._assigns.upsert(user_id, dict(assigns) if isinstance(assigns, dict) else {})
|
|
792
805
|
self._track_node_user(node_id, user_id)
|
|
793
806
|
presence = user.get("presence")
|
|
794
807
|
if isinstance(presence, dict) and presence:
|
|
@@ -800,9 +813,7 @@ class Channel:
|
|
|
800
813
|
return
|
|
801
814
|
node_id = str(raw.get("sourceNodeId") or "")
|
|
802
815
|
assigns = raw.get("assigns")
|
|
803
|
-
await self._assigns.upsert(
|
|
804
|
-
user_id, dict(assigns) if isinstance(assigns, dict) else {}
|
|
805
|
-
)
|
|
816
|
+
await self._assigns.upsert(user_id, dict(assigns) if isinstance(assigns, dict) else {})
|
|
806
817
|
self._track_node_user(node_id, user_id)
|
|
807
818
|
presence = raw.get("presence")
|
|
808
819
|
if isinstance(presence, dict) and presence:
|
|
@@ -868,9 +879,7 @@ class Channel:
|
|
|
868
879
|
"fromNode": self.node_id,
|
|
869
880
|
},
|
|
870
881
|
)
|
|
871
|
-
return await asyncio.wait_for(
|
|
872
|
-
fut, timeout=self._options.user_get_timeout
|
|
873
|
-
)
|
|
882
|
+
return await asyncio.wait_for(fut, timeout=self._options.user_get_timeout)
|
|
874
883
|
except (TimeoutError, asyncio.CancelledError):
|
|
875
884
|
return None
|
|
876
885
|
finally:
|
|
@@ -949,9 +958,7 @@ class Channel:
|
|
|
949
958
|
return exc
|
|
950
959
|
return None
|
|
951
960
|
|
|
952
|
-
async def _fire_after_message(
|
|
953
|
-
self, event: Event, err: BaseException | None
|
|
954
|
-
) -> None:
|
|
961
|
+
async def _fire_after_message(self, event: Event, err: BaseException | None) -> None:
|
|
955
962
|
hooks = self._options.hooks
|
|
956
963
|
if hooks is None or hooks.after_message is None:
|
|
957
964
|
return
|
|
@@ -1051,7 +1058,11 @@ def _event_from_envelope(raw: dict[str, Any]) -> Event | None:
|
|
|
1051
1058
|
message_type = raw.get("type")
|
|
1052
1059
|
channel_name = raw.get("channelName")
|
|
1053
1060
|
node_id = raw.get("sourceNodeId")
|
|
1054
|
-
if
|
|
1061
|
+
if (
|
|
1062
|
+
not isinstance(message_type, str)
|
|
1063
|
+
or not isinstance(channel_name, str)
|
|
1064
|
+
or not isinstance(node_id, str)
|
|
1065
|
+
):
|
|
1055
1066
|
return None
|
|
1056
1067
|
request_id = str(raw.get("requestId") or uuid())
|
|
1057
1068
|
if message_type == "USER_MESSAGE":
|
|
@@ -190,14 +190,10 @@ class Endpoint:
|
|
|
190
190
|
for reg in list(self._channel_registrations):
|
|
191
191
|
for channel in await reg.lobby.list_channels():
|
|
192
192
|
if await channel.has_user(user_id):
|
|
193
|
-
await channel.remove_user(
|
|
194
|
-
user_id, reason=LeaveReason.CONNECTION_CLOSED.value
|
|
195
|
-
)
|
|
193
|
+
await channel.remove_user(user_id, reason=LeaveReason.CONNECTION_CLOSED.value)
|
|
196
194
|
await self._connections.discard(user_id)
|
|
197
195
|
connect_at = self._connect_times.pop(user_id, None)
|
|
198
|
-
duration = (
|
|
199
|
-
time.monotonic() - connect_at if connect_at is not None else 0.0
|
|
200
|
-
)
|
|
196
|
+
duration = time.monotonic() - connect_at if connect_at is not None else 0.0
|
|
201
197
|
self._fire_metric_connection_closed(user_id, duration)
|
|
202
198
|
await self._fire_on_disconnect(transport)
|
|
203
199
|
|
|
@@ -246,9 +242,12 @@ class Endpoint:
|
|
|
246
242
|
channel = await self._find_channel(event.channel_name)
|
|
247
243
|
if channel is None:
|
|
248
244
|
return
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
245
|
+
user_id = transport.get_id()
|
|
246
|
+
if not await channel.has_user(user_id):
|
|
247
|
+
return
|
|
248
|
+
removed = await channel.remove_user(user_id, reason=LeaveReason.EXPLICIT_LEAVE.value)
|
|
249
|
+
if not removed:
|
|
250
|
+
return
|
|
252
251
|
ack = Event(
|
|
253
252
|
action=ServerActions.SYSTEM.value,
|
|
254
253
|
channel_name=event.channel_name,
|
|
@@ -344,9 +343,7 @@ class Endpoint:
|
|
|
344
343
|
except Exception:
|
|
345
344
|
return
|
|
346
345
|
|
|
347
|
-
async def _fire_before_join(
|
|
348
|
-
self, transport: Transport, channel_name: str
|
|
349
|
-
) -> None:
|
|
346
|
+
async def _fire_before_join(self, transport: Transport, channel_name: str) -> None:
|
|
350
347
|
hooks = self._options.hooks
|
|
351
348
|
if hooks is None or hooks.before_join is None:
|
|
352
349
|
return
|
|
@@ -359,9 +356,7 @@ class Endpoint:
|
|
|
359
356
|
except Exception:
|
|
360
357
|
return
|
|
361
358
|
|
|
362
|
-
async def _fire_after_join(
|
|
363
|
-
self, transport: Transport, channel_name: str
|
|
364
|
-
) -> None:
|
|
359
|
+
async def _fire_after_join(self, transport: Transport, channel_name: str) -> None:
|
|
365
360
|
hooks = self._options.hooks
|
|
366
361
|
if hooks is None or hooks.after_join is None:
|
|
367
362
|
return
|
|
@@ -3,9 +3,11 @@ from __future__ import annotations
|
|
|
3
3
|
import asyncio
|
|
4
4
|
from typing import Any
|
|
5
5
|
|
|
6
|
+
from pondsocket_common import ErrorTypes, ServerActions, uuid
|
|
7
|
+
|
|
6
8
|
from .errors import internal
|
|
7
9
|
from .transport import OnCloseCallback, OnMessageHandler
|
|
8
|
-
from .types import Event, TransportType
|
|
10
|
+
from .types import Event, SystemEntity, TransportType
|
|
9
11
|
|
|
10
12
|
|
|
11
13
|
class SSEServerTransport:
|
|
@@ -74,14 +76,32 @@ class SSEServerTransport:
|
|
|
74
76
|
|
|
75
77
|
try:
|
|
76
78
|
text = data.decode("utf-8")
|
|
79
|
+
except UnicodeDecodeError:
|
|
80
|
+
await self._send_invalid_message("Binary frame is not valid UTF-8")
|
|
81
|
+
return
|
|
82
|
+
try:
|
|
77
83
|
event = parse_inbound_text(text)
|
|
78
|
-
except (
|
|
84
|
+
except (ValidationError, RecursionError) as e:
|
|
85
|
+
await self._send_invalid_message(str(e))
|
|
79
86
|
return
|
|
80
87
|
try:
|
|
81
88
|
await self._message_handler(event, self)
|
|
82
89
|
except Exception:
|
|
83
90
|
return
|
|
84
91
|
|
|
92
|
+
async def _send_invalid_message(self, detail: str) -> None:
|
|
93
|
+
ev = Event(
|
|
94
|
+
action=ServerActions.ERROR.value,
|
|
95
|
+
channel_name=SystemEntity.GATEWAY.value,
|
|
96
|
+
request_id=uuid(),
|
|
97
|
+
event=ErrorTypes.INVALID_MESSAGE.value,
|
|
98
|
+
payload={"error": detail},
|
|
99
|
+
)
|
|
100
|
+
try:
|
|
101
|
+
await self.send_event(ev)
|
|
102
|
+
except Exception:
|
|
103
|
+
return
|
|
104
|
+
|
|
85
105
|
async def close(self) -> None:
|
|
86
106
|
if not self._active:
|
|
87
107
|
return
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import Awaitable, Callable
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from pondsocket import (
|
|
10
|
+
ConnectionContext,
|
|
11
|
+
InMemoryTransport,
|
|
12
|
+
JoinContext,
|
|
13
|
+
OutgoingContext,
|
|
14
|
+
PondSocket,
|
|
15
|
+
)
|
|
16
|
+
from pondsocket.channel import Channel, ChannelOptions
|
|
17
|
+
from pondsocket.types import Event, Options, SystemEvents
|
|
18
|
+
from pondsocket_common import ClientActions, IncomingConnection, ServerActions, uuid
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _client_event(action: str, channel: str, event: str) -> Event:
|
|
22
|
+
return Event(
|
|
23
|
+
action=action,
|
|
24
|
+
channel_name=channel,
|
|
25
|
+
request_id=uuid(),
|
|
26
|
+
event=event,
|
|
27
|
+
payload={},
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def _connect(pond: PondSocket, user_id: str) -> InMemoryTransport:
|
|
32
|
+
match = pond.match_endpoint("/api/socket")
|
|
33
|
+
assert match is not None
|
|
34
|
+
incoming = IncomingConnection(id=user_id, address="127.0.0.1", query={})
|
|
35
|
+
ctx = await match.endpoint.request_connection(incoming, user_id=user_id)
|
|
36
|
+
assert ctx.is_accepted
|
|
37
|
+
transport = InMemoryTransport(ctx.user_id, assigns=ctx.assigns)
|
|
38
|
+
await match.endpoint.register_transport(transport)
|
|
39
|
+
await transport.receive_sent()
|
|
40
|
+
return transport
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def _expect_event(transport: InMemoryTransport, event_name: str) -> Event:
|
|
44
|
+
for _ in range(20):
|
|
45
|
+
event = await transport.receive_sent()
|
|
46
|
+
if event.action == ServerActions.SYSTEM.value and event.event == event_name:
|
|
47
|
+
return event
|
|
48
|
+
raise AssertionError(f"did not receive system event {event_name}")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _dispatcher(channel: Channel) -> asyncio.Task[None]:
|
|
52
|
+
task = channel._dispatch_task # type: ignore[attr-defined]
|
|
53
|
+
assert task is not None
|
|
54
|
+
return task
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def _pond_with_channel(
|
|
58
|
+
on_join: Callable[[JoinContext], Awaitable[None]],
|
|
59
|
+
) -> tuple[PondSocket, Any]:
|
|
60
|
+
pond = PondSocket()
|
|
61
|
+
|
|
62
|
+
async def auth(ctx: ConnectionContext) -> None:
|
|
63
|
+
ctx.accept()
|
|
64
|
+
|
|
65
|
+
endpoint = pond.create_endpoint("/api/socket", auth)
|
|
66
|
+
lobby = endpoint.create_channel("/chat/:room", on_join)
|
|
67
|
+
return pond, lobby
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@pytest.mark.asyncio
|
|
71
|
+
async def test_last_user_removal_completes_dispatcher_and_destroys_once() -> None:
|
|
72
|
+
destroyed = 0
|
|
73
|
+
|
|
74
|
+
async def on_destroy() -> None:
|
|
75
|
+
nonlocal destroyed
|
|
76
|
+
destroyed += 1
|
|
77
|
+
|
|
78
|
+
channel = Channel(
|
|
79
|
+
ChannelOptions(
|
|
80
|
+
name="/chat/1",
|
|
81
|
+
options=Options(),
|
|
82
|
+
on_destroy=on_destroy,
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
await channel.start()
|
|
86
|
+
transport = InMemoryTransport("alice")
|
|
87
|
+
await channel.add_user(transport)
|
|
88
|
+
dispatcher = _dispatcher(channel)
|
|
89
|
+
|
|
90
|
+
assert await channel.remove_user("alice")
|
|
91
|
+
|
|
92
|
+
assert not channel.is_active
|
|
93
|
+
assert dispatcher.done()
|
|
94
|
+
assert channel._dispatch_task is None # type: ignore[attr-defined]
|
|
95
|
+
assert destroyed == 1
|
|
96
|
+
|
|
97
|
+
await asyncio.gather(channel.close(), channel.close())
|
|
98
|
+
assert destroyed == 1
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@pytest.mark.asyncio
|
|
102
|
+
async def test_concurrent_close_and_recursive_destroy_complete_once() -> None:
|
|
103
|
+
destroyed = 0
|
|
104
|
+
channel: Channel
|
|
105
|
+
|
|
106
|
+
async def on_destroy() -> None:
|
|
107
|
+
nonlocal destroyed
|
|
108
|
+
destroyed += 1
|
|
109
|
+
await channel.close()
|
|
110
|
+
|
|
111
|
+
channel = Channel(
|
|
112
|
+
ChannelOptions(
|
|
113
|
+
name="/chat/1",
|
|
114
|
+
options=Options(),
|
|
115
|
+
on_destroy=on_destroy,
|
|
116
|
+
)
|
|
117
|
+
)
|
|
118
|
+
await channel.start()
|
|
119
|
+
dispatcher = _dispatcher(channel)
|
|
120
|
+
|
|
121
|
+
async with asyncio.timeout(1.0):
|
|
122
|
+
await asyncio.gather(channel.close(), channel.close(), channel.close())
|
|
123
|
+
|
|
124
|
+
assert dispatcher.done()
|
|
125
|
+
assert destroyed == 1
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@pytest.mark.asyncio
|
|
129
|
+
async def test_explicit_leave_completes_channel_dispatcher() -> None:
|
|
130
|
+
channels: list[Channel] = []
|
|
131
|
+
|
|
132
|
+
async def on_join(ctx: JoinContext) -> None:
|
|
133
|
+
channels.append(ctx.channel)
|
|
134
|
+
await ctx.accept()
|
|
135
|
+
|
|
136
|
+
pond, lobby = await _pond_with_channel(on_join)
|
|
137
|
+
transport = await _connect(pond, "alice")
|
|
138
|
+
await transport.push_inbound(_client_event(ClientActions.JOIN_CHANNEL.value, "/chat/1", "join"))
|
|
139
|
+
await _expect_event(transport, SystemEvents.ACKNOWLEDGE.value)
|
|
140
|
+
dispatcher = _dispatcher(channels[0])
|
|
141
|
+
|
|
142
|
+
await transport.push_inbound(
|
|
143
|
+
_client_event(ClientActions.LEAVE_CHANNEL.value, "/chat/1", "leave")
|
|
144
|
+
)
|
|
145
|
+
await _expect_event(transport, SystemEvents.EXIT_ACKNOWLEDGE.value)
|
|
146
|
+
await asyncio.wait_for(asyncio.shield(dispatcher), timeout=1.0)
|
|
147
|
+
|
|
148
|
+
assert not channels[0].is_active
|
|
149
|
+
assert await lobby.get_channel("/chat/1") is None
|
|
150
|
+
await pond.close()
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@pytest.mark.asyncio
|
|
154
|
+
async def test_abrupt_disconnect_completes_channel_dispatcher() -> None:
|
|
155
|
+
channels: list[Channel] = []
|
|
156
|
+
|
|
157
|
+
async def on_join(ctx: JoinContext) -> None:
|
|
158
|
+
channels.append(ctx.channel)
|
|
159
|
+
await ctx.accept()
|
|
160
|
+
|
|
161
|
+
pond, lobby = await _pond_with_channel(on_join)
|
|
162
|
+
transport = await _connect(pond, "alice")
|
|
163
|
+
await transport.push_inbound(_client_event(ClientActions.JOIN_CHANNEL.value, "/chat/1", "join"))
|
|
164
|
+
await _expect_event(transport, SystemEvents.ACKNOWLEDGE.value)
|
|
165
|
+
dispatcher = _dispatcher(channels[0])
|
|
166
|
+
|
|
167
|
+
await transport.close()
|
|
168
|
+
|
|
169
|
+
assert dispatcher.done()
|
|
170
|
+
assert not channels[0].is_active
|
|
171
|
+
assert await lobby.get_channel("/chat/1") is None
|
|
172
|
+
await pond.close()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@pytest.mark.asyncio
|
|
176
|
+
async def test_dispatcher_can_trigger_last_user_close_without_self_await() -> None:
|
|
177
|
+
channels: list[Channel] = []
|
|
178
|
+
|
|
179
|
+
async def on_join(ctx: JoinContext) -> None:
|
|
180
|
+
channels.append(ctx.channel)
|
|
181
|
+
await ctx.accept()
|
|
182
|
+
|
|
183
|
+
pond, lobby = await _pond_with_channel(on_join)
|
|
184
|
+
|
|
185
|
+
async def remove_recipient(ctx: OutgoingContext) -> None:
|
|
186
|
+
await ctx.channel.remove_user(ctx.user.id)
|
|
187
|
+
|
|
188
|
+
lobby.on_outgoing("message", remove_recipient)
|
|
189
|
+
transport = await _connect(pond, "alice")
|
|
190
|
+
await transport.push_inbound(_client_event(ClientActions.JOIN_CHANNEL.value, "/chat/1", "join"))
|
|
191
|
+
await _expect_event(transport, SystemEvents.ACKNOWLEDGE.value)
|
|
192
|
+
channel = channels[0]
|
|
193
|
+
dispatcher = _dispatcher(channel)
|
|
194
|
+
|
|
195
|
+
await channel.broadcast("message", {"text": "close"})
|
|
196
|
+
done, pending = await asyncio.wait({dispatcher}, timeout=1.0)
|
|
197
|
+
assert done == {dispatcher}
|
|
198
|
+
assert not pending
|
|
199
|
+
close_task = channel._close_task # type: ignore[attr-defined]
|
|
200
|
+
assert close_task is not None
|
|
201
|
+
await asyncio.wait_for(asyncio.shield(close_task), timeout=1.0)
|
|
202
|
+
|
|
203
|
+
assert not channel.is_active
|
|
204
|
+
assert await lobby.get_channel("/chat/1") is None
|
|
205
|
+
await pond.close()
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@pytest.mark.asyncio
|
|
209
|
+
@pytest.mark.parametrize("failure", ["decline", "raise", "no_response"])
|
|
210
|
+
async def test_failed_join_completes_unused_channel_dispatcher(failure: str) -> None:
|
|
211
|
+
channels: list[Channel] = []
|
|
212
|
+
dispatchers: list[asyncio.Task[None]] = []
|
|
213
|
+
|
|
214
|
+
async def on_join(ctx: JoinContext) -> None:
|
|
215
|
+
channels.append(ctx.channel)
|
|
216
|
+
dispatchers.append(_dispatcher(ctx.channel))
|
|
217
|
+
if failure == "decline":
|
|
218
|
+
await ctx.decline(403, "declined")
|
|
219
|
+
elif failure == "raise":
|
|
220
|
+
raise RuntimeError("join failed")
|
|
221
|
+
|
|
222
|
+
pond, lobby = await _pond_with_channel(on_join)
|
|
223
|
+
transport = await _connect(pond, "alice")
|
|
224
|
+
await transport.push_inbound(_client_event(ClientActions.JOIN_CHANNEL.value, "/chat/1", "join"))
|
|
225
|
+
await _expect_event(transport, SystemEvents.UNAUTHORIZED.value)
|
|
226
|
+
await asyncio.wait_for(asyncio.shield(dispatchers[0]), timeout=1.0)
|
|
227
|
+
|
|
228
|
+
assert not channels[0].is_active
|
|
229
|
+
assert await lobby.get_channel("/chat/1") is None
|
|
230
|
+
await pond.close()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@pytest.mark.asyncio
|
|
234
|
+
async def test_repeated_connect_disconnect_reaps_every_dispatcher() -> None:
|
|
235
|
+
channels: list[Channel] = []
|
|
236
|
+
|
|
237
|
+
async def on_join(ctx: JoinContext) -> None:
|
|
238
|
+
channels.append(ctx.channel)
|
|
239
|
+
await ctx.accept()
|
|
240
|
+
|
|
241
|
+
pond, lobby = await _pond_with_channel(on_join)
|
|
242
|
+
dispatchers: list[asyncio.Task[None]] = []
|
|
243
|
+
|
|
244
|
+
for index in range(10):
|
|
245
|
+
transport = await _connect(pond, f"user-{index}")
|
|
246
|
+
await transport.push_inbound(
|
|
247
|
+
_client_event(ClientActions.JOIN_CHANNEL.value, "/chat/1", "join")
|
|
248
|
+
)
|
|
249
|
+
await _expect_event(transport, SystemEvents.ACKNOWLEDGE.value)
|
|
250
|
+
dispatchers.append(_dispatcher(channels[-1]))
|
|
251
|
+
await transport.close()
|
|
252
|
+
assert dispatchers[-1].done()
|
|
253
|
+
assert await lobby.get_channel("/chat/1") is None
|
|
254
|
+
|
|
255
|
+
assert all(task.done() for task in dispatchers)
|
|
256
|
+
await pond.close()
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@pytest.mark.asyncio
|
|
260
|
+
async def test_pondsocket_close_completes_active_channel_dispatcher() -> None:
|
|
261
|
+
channels: list[Channel] = []
|
|
262
|
+
|
|
263
|
+
async def on_join(ctx: JoinContext) -> None:
|
|
264
|
+
channels.append(ctx.channel)
|
|
265
|
+
await ctx.accept()
|
|
266
|
+
|
|
267
|
+
pond, _ = await _pond_with_channel(on_join)
|
|
268
|
+
transport = await _connect(pond, "alice")
|
|
269
|
+
await transport.push_inbound(_client_event(ClientActions.JOIN_CHANNEL.value, "/chat/1", "join"))
|
|
270
|
+
await _expect_event(transport, SystemEvents.ACKNOWLEDGE.value)
|
|
271
|
+
dispatcher = _dispatcher(channels[0])
|
|
272
|
+
|
|
273
|
+
await pond.close()
|
|
274
|
+
|
|
275
|
+
assert dispatcher.done()
|
|
276
|
+
assert not channels[0].is_active
|
|
@@ -26,7 +26,9 @@ from pondsocket_common import (
|
|
|
26
26
|
)
|
|
27
27
|
|
|
28
28
|
|
|
29
|
-
def _client_event(
|
|
29
|
+
def _client_event(
|
|
30
|
+
action: str, channel: str, event: str, payload: dict[str, Any] | None = None
|
|
31
|
+
) -> Event:
|
|
30
32
|
return Event(
|
|
31
33
|
action=action,
|
|
32
34
|
channel_name=channel,
|
|
@@ -141,9 +143,7 @@ async def test_join_channel_acknowledge_flow() -> None:
|
|
|
141
143
|
join_req.request_id = "req-join-1"
|
|
142
144
|
await transport.push_inbound(join_req)
|
|
143
145
|
|
|
144
|
-
ack = await _expect_event(
|
|
145
|
-
transport, ServerActions.SYSTEM.value, SystemEvents.ACKNOWLEDGE.value
|
|
146
|
-
)
|
|
146
|
+
ack = await _expect_event(transport, ServerActions.SYSTEM.value, SystemEvents.ACKNOWLEDGE.value)
|
|
147
147
|
assert ack.request_id == "req-join-1"
|
|
148
148
|
assert ack.channel_name == "/chat/42"
|
|
149
149
|
|
|
@@ -172,13 +172,35 @@ async def test_join_decline_sends_unauthorized() -> None:
|
|
|
172
172
|
join_req = _client_event(ClientActions.JOIN_CHANNEL.value, "/chat/42", "join")
|
|
173
173
|
await transport.push_inbound(join_req)
|
|
174
174
|
|
|
175
|
-
ev = await _expect_event(
|
|
176
|
-
transport, ServerActions.SYSTEM.value, SystemEvents.UNAUTHORIZED.value
|
|
177
|
-
)
|
|
175
|
+
ev = await _expect_event(transport, ServerActions.SYSTEM.value, SystemEvents.UNAUTHORIZED.value)
|
|
178
176
|
assert ev.payload == {"code": 403, "message": "wrong room"}
|
|
179
177
|
await pond.close()
|
|
180
178
|
|
|
181
179
|
|
|
180
|
+
async def test_join_handler_without_response_auto_declines() -> None:
|
|
181
|
+
pond = PondSocket()
|
|
182
|
+
|
|
183
|
+
async def auth(ctx: ConnectionContext) -> None:
|
|
184
|
+
ctx.accept()
|
|
185
|
+
|
|
186
|
+
endpoint = pond.create_endpoint("/api/socket", auth)
|
|
187
|
+
|
|
188
|
+
async def on_join(ctx: JoinContext) -> None:
|
|
189
|
+
return
|
|
190
|
+
|
|
191
|
+
endpoint.create_channel("/chat/:room_id", on_join)
|
|
192
|
+
|
|
193
|
+
transport, _ = await _connect(pond)
|
|
194
|
+
await _next_event(transport)
|
|
195
|
+
|
|
196
|
+
join_req = _client_event(ClientActions.JOIN_CHANNEL.value, "/chat/42", "join")
|
|
197
|
+
await transport.push_inbound(join_req)
|
|
198
|
+
|
|
199
|
+
ev = await _expect_event(transport, ServerActions.SYSTEM.value, SystemEvents.UNAUTHORIZED.value)
|
|
200
|
+
assert ev.payload == {"code": 401, "message": "Join handler did not respond"}
|
|
201
|
+
await pond.close()
|
|
202
|
+
|
|
203
|
+
|
|
182
204
|
async def test_unknown_channel_pattern_sends_not_found() -> None:
|
|
183
205
|
pond = PondSocket()
|
|
184
206
|
|
|
@@ -198,9 +220,7 @@ async def test_unknown_channel_pattern_sends_not_found() -> None:
|
|
|
198
220
|
join_req = _client_event(ClientActions.JOIN_CHANNEL.value, "/missing/path", "join")
|
|
199
221
|
await transport.push_inbound(join_req)
|
|
200
222
|
|
|
201
|
-
ev = await _expect_event(
|
|
202
|
-
transport, ServerActions.SYSTEM.value, SystemEvents.NOT_FOUND.value
|
|
203
|
-
)
|
|
223
|
+
ev = await _expect_event(transport, ServerActions.SYSTEM.value, SystemEvents.NOT_FOUND.value)
|
|
204
224
|
assert ev.payload == {"channel": "/missing/path"}
|
|
205
225
|
await pond.close()
|
|
206
226
|
|
|
@@ -233,9 +253,7 @@ async def test_broadcast_fanouts_to_other_members() -> None:
|
|
|
233
253
|
await _expect_event(t, ServerActions.SYSTEM.value, SystemEvents.ACKNOWLEDGE.value)
|
|
234
254
|
|
|
235
255
|
await alice_t.push_inbound(
|
|
236
|
-
_client_event(
|
|
237
|
-
ClientActions.BROADCAST.value, "/chat/1", "message", {"text": "hi"}
|
|
238
|
-
)
|
|
256
|
+
_client_event(ClientActions.BROADCAST.value, "/chat/1", "message", {"text": "hi"})
|
|
239
257
|
)
|
|
240
258
|
|
|
241
259
|
ev_a = await _expect_event(alice_t, ServerActions.BROADCAST.value, "message")
|