pondsocket 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.
- pondsocket/__init__.py +205 -0
- pondsocket/channel.py +580 -0
- pondsocket/contexts/__init__.py +16 -0
- pondsocket/contexts/connection_context.py +135 -0
- pondsocket/contexts/event_context.py +127 -0
- pondsocket/contexts/join_context.py +162 -0
- pondsocket/contexts/leave_context.py +78 -0
- pondsocket/contexts/outgoing_context.py +72 -0
- pondsocket/distributed/__init__.py +5 -0
- pondsocket/distributed/redis_pubsub.py +137 -0
- pondsocket/endpoint.py +348 -0
- pondsocket/errors.py +90 -0
- pondsocket/hooks.py +227 -0
- pondsocket/in_memory_transport.py +112 -0
- pondsocket/lobby.py +183 -0
- pondsocket/middleware.py +100 -0
- pondsocket/parser.py +85 -0
- pondsocket/presence.py +109 -0
- pondsocket/pubsub.py +44 -0
- pondsocket/pubsub_local.py +85 -0
- pondsocket/py.typed +0 -0
- pondsocket/server.py +88 -0
- pondsocket/sse_transport.py +122 -0
- pondsocket/store.py +83 -0
- pondsocket/transport.py +29 -0
- pondsocket/types.py +154 -0
- pondsocket/wire.py +87 -0
- pondsocket-0.0.1.dist-info/METADATA +144 -0
- pondsocket-0.0.1.dist-info/RECORD +30 -0
- pondsocket-0.0.1.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import contextlib
|
|
5
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
6
|
+
|
|
7
|
+
from ..errors import not_found
|
|
8
|
+
from ..pubsub import PubSubClosedError, PubSubHandler, match_topic
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from redis.asyncio.client import PubSub as RedisAsyncPubSub
|
|
12
|
+
from redis.asyncio.client import Redis as RedisAsyncClient
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_REDIS_GLOB_ESCAPE = str.maketrans({"*": r"\*", "?": r"\?", "[": r"\[", "\\": r"\\"})
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _escape_redis_glob(segment: str) -> str:
|
|
19
|
+
return segment.translate(_REDIS_GLOB_ESCAPE)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _pond_pattern_to_redis(pattern: str) -> str:
|
|
23
|
+
if pattern.endswith(".*"):
|
|
24
|
+
return _escape_redis_glob(pattern[:-2]) + "*"
|
|
25
|
+
return _escape_redis_glob(pattern)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class RedisPubSub:
|
|
29
|
+
__slots__ = (
|
|
30
|
+
"_client",
|
|
31
|
+
"_closed",
|
|
32
|
+
"_lock",
|
|
33
|
+
"_owns_client",
|
|
34
|
+
"_pubsub",
|
|
35
|
+
"_reader_task",
|
|
36
|
+
"_subs",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
client: RedisAsyncClient,
|
|
42
|
+
*,
|
|
43
|
+
owns_client: bool = False,
|
|
44
|
+
) -> None:
|
|
45
|
+
self._client = client
|
|
46
|
+
self._pubsub: RedisAsyncPubSub = client.pubsub()
|
|
47
|
+
self._closed = False
|
|
48
|
+
self._owns_client = owns_client
|
|
49
|
+
self._subs: dict[str, PubSubHandler] = {}
|
|
50
|
+
self._lock = asyncio.Lock()
|
|
51
|
+
self._reader_task: asyncio.Task[None] | None = None
|
|
52
|
+
|
|
53
|
+
async def subscribe(self, pattern: str, handler: PubSubHandler) -> None:
|
|
54
|
+
async with self._lock:
|
|
55
|
+
if self._closed:
|
|
56
|
+
raise PubSubClosedError()
|
|
57
|
+
if pattern in self._subs:
|
|
58
|
+
raise not_found("pubsub", "pattern already subscribed")
|
|
59
|
+
redis_pattern = _pond_pattern_to_redis(pattern)
|
|
60
|
+
await self._pubsub.psubscribe(redis_pattern)
|
|
61
|
+
self._subs[pattern] = handler
|
|
62
|
+
if self._reader_task is None or self._reader_task.done():
|
|
63
|
+
self._reader_task = asyncio.create_task(self._reader_loop())
|
|
64
|
+
|
|
65
|
+
async def unsubscribe(self, pattern: str) -> None:
|
|
66
|
+
async with self._lock:
|
|
67
|
+
if self._closed:
|
|
68
|
+
raise PubSubClosedError()
|
|
69
|
+
if pattern not in self._subs:
|
|
70
|
+
raise not_found("pubsub", "pattern not found")
|
|
71
|
+
redis_pattern = _pond_pattern_to_redis(pattern)
|
|
72
|
+
await self._pubsub.punsubscribe(redis_pattern)
|
|
73
|
+
del self._subs[pattern]
|
|
74
|
+
|
|
75
|
+
async def publish(self, topic: str, data: bytes) -> None:
|
|
76
|
+
if self._closed:
|
|
77
|
+
raise PubSubClosedError()
|
|
78
|
+
await self._client.publish(topic, data)
|
|
79
|
+
|
|
80
|
+
async def close(self) -> None:
|
|
81
|
+
async with self._lock:
|
|
82
|
+
if self._closed:
|
|
83
|
+
return
|
|
84
|
+
self._closed = True
|
|
85
|
+
if self._reader_task is not None and not self._reader_task.done():
|
|
86
|
+
self._reader_task.cancel()
|
|
87
|
+
with contextlib.suppress(asyncio.CancelledError, Exception):
|
|
88
|
+
await self._reader_task
|
|
89
|
+
with contextlib.suppress(Exception):
|
|
90
|
+
await cast(Any, self._pubsub).aclose()
|
|
91
|
+
if self._owns_client:
|
|
92
|
+
with contextlib.suppress(Exception):
|
|
93
|
+
await cast(Any, self._client).aclose()
|
|
94
|
+
|
|
95
|
+
async def _reader_loop(self) -> None:
|
|
96
|
+
while True:
|
|
97
|
+
if self._closed:
|
|
98
|
+
return
|
|
99
|
+
try:
|
|
100
|
+
msg = await self._pubsub.get_message(
|
|
101
|
+
ignore_subscribe_messages=True,
|
|
102
|
+
timeout=0.05,
|
|
103
|
+
)
|
|
104
|
+
except asyncio.CancelledError:
|
|
105
|
+
return
|
|
106
|
+
except Exception:
|
|
107
|
+
await asyncio.sleep(0.05)
|
|
108
|
+
continue
|
|
109
|
+
if msg is None:
|
|
110
|
+
continue
|
|
111
|
+
if msg.get("type") != "pmessage":
|
|
112
|
+
continue
|
|
113
|
+
topic = _decode_topic(msg.get("channel"))
|
|
114
|
+
data = msg.get("data")
|
|
115
|
+
if topic is None or not isinstance(data, bytes):
|
|
116
|
+
continue
|
|
117
|
+
await self._dispatch_to_handlers(topic, data)
|
|
118
|
+
|
|
119
|
+
async def _dispatch_to_handlers(self, topic: str, data: bytes) -> None:
|
|
120
|
+
async with self._lock:
|
|
121
|
+
handlers = [h for p, h in self._subs.items() if match_topic(p, topic)]
|
|
122
|
+
for handler in handlers:
|
|
123
|
+
try:
|
|
124
|
+
await handler(topic, data)
|
|
125
|
+
except Exception:
|
|
126
|
+
continue
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _decode_topic(value: Any) -> str | None:
|
|
130
|
+
if isinstance(value, bytes):
|
|
131
|
+
try:
|
|
132
|
+
return value.decode("utf-8")
|
|
133
|
+
except UnicodeDecodeError:
|
|
134
|
+
return None
|
|
135
|
+
if isinstance(value, str):
|
|
136
|
+
return value
|
|
137
|
+
return None
|
pondsocket/endpoint.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from collections.abc import Awaitable, Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import TypeAlias
|
|
7
|
+
|
|
8
|
+
from pondsocket_common import ClientActions, IncomingConnection, ServerActions, uuid
|
|
9
|
+
|
|
10
|
+
from .channel import Channel
|
|
11
|
+
from .contexts.connection_context import ConnectionContext, ConnectionDecision
|
|
12
|
+
from .contexts.join_context import JoinContext
|
|
13
|
+
from .errors import PondError, forbidden, not_found
|
|
14
|
+
from .lobby import Lobby
|
|
15
|
+
from .middleware import execute_with_middleware
|
|
16
|
+
from .parser import parse
|
|
17
|
+
from .pubsub import PubSub
|
|
18
|
+
from .store import Store
|
|
19
|
+
from .transport import Transport
|
|
20
|
+
from .types import (
|
|
21
|
+
Event,
|
|
22
|
+
LeaveReason,
|
|
23
|
+
Options,
|
|
24
|
+
SystemEntity,
|
|
25
|
+
SystemEvents,
|
|
26
|
+
User,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
ConnectionHandler: TypeAlias = Callable[[ConnectionContext], Awaitable[None]]
|
|
30
|
+
ConnectionMiddlewareFn: TypeAlias = Callable[
|
|
31
|
+
[ConnectionContext, Callable[[], Awaitable[None]]], Awaitable[None]
|
|
32
|
+
]
|
|
33
|
+
JoinHandler: TypeAlias = Callable[[JoinContext], Awaitable[None]]
|
|
34
|
+
JoinMiddlewareFn: TypeAlias = Callable[
|
|
35
|
+
[JoinContext, Callable[[], Awaitable[None]]], Awaitable[None]
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(slots=True)
|
|
40
|
+
class _ChannelRegistration:
|
|
41
|
+
pattern: str
|
|
42
|
+
handler: JoinHandler
|
|
43
|
+
middlewares: list[JoinMiddlewareFn]
|
|
44
|
+
lobby: Lobby
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Endpoint:
|
|
48
|
+
__slots__ = (
|
|
49
|
+
"_channel_registrations",
|
|
50
|
+
"_connect_times",
|
|
51
|
+
"_connection_handler",
|
|
52
|
+
"_connection_middlewares",
|
|
53
|
+
"_connections",
|
|
54
|
+
"_options",
|
|
55
|
+
"_path",
|
|
56
|
+
"_pubsub",
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
*,
|
|
62
|
+
path: str,
|
|
63
|
+
connection_handler: ConnectionHandler,
|
|
64
|
+
options: Options | None = None,
|
|
65
|
+
pubsub: PubSub | None = None,
|
|
66
|
+
connection_middlewares: list[ConnectionMiddlewareFn] | None = None,
|
|
67
|
+
) -> None:
|
|
68
|
+
self._path = path
|
|
69
|
+
self._connection_handler = connection_handler
|
|
70
|
+
self._connection_middlewares = list(connection_middlewares or [])
|
|
71
|
+
self._options = options or Options()
|
|
72
|
+
self._pubsub = pubsub
|
|
73
|
+
self._connections: Store[Transport] = Store()
|
|
74
|
+
self._channel_registrations: list[_ChannelRegistration] = []
|
|
75
|
+
self._connect_times: dict[str, float] = {}
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def path(self) -> str:
|
|
79
|
+
return self._path
|
|
80
|
+
|
|
81
|
+
def use(self, *middlewares: ConnectionMiddlewareFn) -> None:
|
|
82
|
+
self._connection_middlewares.extend(middlewares)
|
|
83
|
+
|
|
84
|
+
def create_channel(
|
|
85
|
+
self,
|
|
86
|
+
pattern: str,
|
|
87
|
+
handler: JoinHandler,
|
|
88
|
+
*middlewares: JoinMiddlewareFn,
|
|
89
|
+
) -> Lobby:
|
|
90
|
+
lobby = Lobby(
|
|
91
|
+
path=pattern,
|
|
92
|
+
endpoint_path=self._path,
|
|
93
|
+
options=self._options,
|
|
94
|
+
pubsub=self._pubsub,
|
|
95
|
+
)
|
|
96
|
+
self._channel_registrations.append(
|
|
97
|
+
_ChannelRegistration(
|
|
98
|
+
pattern=pattern,
|
|
99
|
+
handler=handler,
|
|
100
|
+
middlewares=list(middlewares),
|
|
101
|
+
lobby=lobby,
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
return lobby
|
|
105
|
+
|
|
106
|
+
async def request_connection(
|
|
107
|
+
self,
|
|
108
|
+
incoming: IncomingConnection,
|
|
109
|
+
*,
|
|
110
|
+
user_id: str | None = None,
|
|
111
|
+
) -> ConnectionContext:
|
|
112
|
+
uid = user_id or uuid()
|
|
113
|
+
ctx = ConnectionContext(user_id=uid, request=incoming)
|
|
114
|
+
try:
|
|
115
|
+
await execute_with_middleware(
|
|
116
|
+
ctx, self._connection_handler, self._connection_middlewares
|
|
117
|
+
)
|
|
118
|
+
except PondError as e:
|
|
119
|
+
if ctx.decision is ConnectionDecision.PENDING:
|
|
120
|
+
ctx.decline(e.code, e.message)
|
|
121
|
+
except Exception as e:
|
|
122
|
+
if ctx.decision is ConnectionDecision.PENDING:
|
|
123
|
+
ctx.decline(500, str(e))
|
|
124
|
+
if ctx.decision is ConnectionDecision.PENDING:
|
|
125
|
+
ctx.decline(401, "Connection handler did not accept or decline")
|
|
126
|
+
return ctx
|
|
127
|
+
|
|
128
|
+
async def register_transport(self, transport: Transport) -> None:
|
|
129
|
+
await self._check_max_connections()
|
|
130
|
+
await self._connections.create(transport.get_id(), transport)
|
|
131
|
+
self._connect_times[transport.get_id()] = time.monotonic()
|
|
132
|
+
await self._send_connect_event(transport)
|
|
133
|
+
transport.on_close(self._on_transport_closed)
|
|
134
|
+
transport.on_message(self._handle_transport_message)
|
|
135
|
+
self._fire_metric_connection_opened(transport)
|
|
136
|
+
await self._fire_on_connect(transport)
|
|
137
|
+
await transport.handle_messages()
|
|
138
|
+
|
|
139
|
+
async def _check_max_connections(self) -> None:
|
|
140
|
+
if self._options.max_connections <= 0:
|
|
141
|
+
return
|
|
142
|
+
current = await self._connections.len()
|
|
143
|
+
if current >= self._options.max_connections:
|
|
144
|
+
raise forbidden(
|
|
145
|
+
SystemEntity.GATEWAY.value,
|
|
146
|
+
"Maximum connections reached",
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
async def _send_connect_event(self, transport: Transport) -> None:
|
|
150
|
+
transport_id = transport.get_id()
|
|
151
|
+
ev = Event(
|
|
152
|
+
action=ServerActions.CONNECT.value,
|
|
153
|
+
channel_name=SystemEntity.GATEWAY.value,
|
|
154
|
+
request_id=uuid(),
|
|
155
|
+
event=SystemEvents.CONNECTION.value,
|
|
156
|
+
payload={"id": transport_id, "connectionId": transport_id},
|
|
157
|
+
)
|
|
158
|
+
try:
|
|
159
|
+
await transport.send_event(ev)
|
|
160
|
+
except Exception:
|
|
161
|
+
return
|
|
162
|
+
|
|
163
|
+
async def _on_transport_closed(self, transport: Transport) -> None:
|
|
164
|
+
user_id = transport.get_id()
|
|
165
|
+
for reg in list(self._channel_registrations):
|
|
166
|
+
for channel in await reg.lobby.list_channels():
|
|
167
|
+
if await channel.has_user(user_id):
|
|
168
|
+
await channel.remove_user(
|
|
169
|
+
user_id, reason=LeaveReason.CONNECTION_CLOSED.value
|
|
170
|
+
)
|
|
171
|
+
await self._connections.discard(user_id)
|
|
172
|
+
connect_at = self._connect_times.pop(user_id, None)
|
|
173
|
+
duration = (
|
|
174
|
+
time.monotonic() - connect_at if connect_at is not None else 0.0
|
|
175
|
+
)
|
|
176
|
+
self._fire_metric_connection_closed(user_id, duration)
|
|
177
|
+
await self._fire_on_disconnect(transport)
|
|
178
|
+
|
|
179
|
+
async def _handle_transport_message(self, event: Event, transport: Transport) -> None:
|
|
180
|
+
action = event.action
|
|
181
|
+
if action == ClientActions.JOIN_CHANNEL.value:
|
|
182
|
+
await self._handle_join(event, transport)
|
|
183
|
+
elif action == ClientActions.LEAVE_CHANNEL.value:
|
|
184
|
+
await self._handle_leave(event, transport)
|
|
185
|
+
elif action == ClientActions.BROADCAST.value:
|
|
186
|
+
await self._handle_broadcast(event, transport)
|
|
187
|
+
|
|
188
|
+
async def _handle_join(self, event: Event, transport: Transport) -> None:
|
|
189
|
+
channel_name = event.channel_name
|
|
190
|
+
for reg in self._channel_registrations:
|
|
191
|
+
try:
|
|
192
|
+
route = parse(reg.pattern, channel_name)
|
|
193
|
+
except PondError:
|
|
194
|
+
continue
|
|
195
|
+
channel = await reg.lobby.get_or_create_channel(channel_name)
|
|
196
|
+
ctx = JoinContext(
|
|
197
|
+
channel=channel,
|
|
198
|
+
event=event,
|
|
199
|
+
transport=transport,
|
|
200
|
+
route=route,
|
|
201
|
+
)
|
|
202
|
+
await self._fire_before_join(transport, channel_name)
|
|
203
|
+
try:
|
|
204
|
+
await execute_with_middleware(ctx, reg.handler, reg.middlewares)
|
|
205
|
+
except PondError as e:
|
|
206
|
+
if not ctx.has_responded:
|
|
207
|
+
await ctx.decline(e.code, e.message)
|
|
208
|
+
except Exception as e:
|
|
209
|
+
if not ctx.has_responded:
|
|
210
|
+
await ctx.decline(500, str(e))
|
|
211
|
+
if not ctx.has_responded:
|
|
212
|
+
await ctx.decline(401, "Join handler did not respond")
|
|
213
|
+
if ctx.is_accepted:
|
|
214
|
+
await self._fire_after_join(transport, channel_name)
|
|
215
|
+
return
|
|
216
|
+
await self._send_not_found(transport, event)
|
|
217
|
+
|
|
218
|
+
async def _handle_leave(self, event: Event, transport: Transport) -> None:
|
|
219
|
+
channel = await self._find_channel(event.channel_name)
|
|
220
|
+
if channel is None:
|
|
221
|
+
return
|
|
222
|
+
await channel.remove_user(
|
|
223
|
+
transport.get_id(), reason=LeaveReason.EXPLICIT_LEAVE.value
|
|
224
|
+
)
|
|
225
|
+
ack = Event(
|
|
226
|
+
action=ServerActions.SYSTEM.value,
|
|
227
|
+
channel_name=event.channel_name,
|
|
228
|
+
request_id=event.request_id,
|
|
229
|
+
event=SystemEvents.EXIT_ACKNOWLEDGE.value,
|
|
230
|
+
payload={},
|
|
231
|
+
)
|
|
232
|
+
try:
|
|
233
|
+
await transport.send_event(ack)
|
|
234
|
+
except Exception:
|
|
235
|
+
return
|
|
236
|
+
|
|
237
|
+
async def _handle_broadcast(self, event: Event, transport: Transport) -> None:
|
|
238
|
+
channel = await self._find_channel(event.channel_name)
|
|
239
|
+
if channel is None:
|
|
240
|
+
await self._send_not_found(transport, event)
|
|
241
|
+
return
|
|
242
|
+
await channel.handle_incoming_event(event, transport.get_id())
|
|
243
|
+
|
|
244
|
+
async def _find_channel(self, name: str) -> Channel | None:
|
|
245
|
+
for reg in self._channel_registrations:
|
|
246
|
+
ch = await reg.lobby.get_channel(name)
|
|
247
|
+
if ch is not None:
|
|
248
|
+
return ch
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
async def _send_not_found(self, transport: Transport, event: Event) -> None:
|
|
252
|
+
ev = Event(
|
|
253
|
+
action=ServerActions.SYSTEM.value,
|
|
254
|
+
channel_name=event.channel_name,
|
|
255
|
+
request_id=event.request_id,
|
|
256
|
+
event=SystemEvents.NOT_FOUND.value,
|
|
257
|
+
payload={"channel": event.channel_name},
|
|
258
|
+
)
|
|
259
|
+
try:
|
|
260
|
+
await transport.send_event(ev)
|
|
261
|
+
except Exception:
|
|
262
|
+
return
|
|
263
|
+
|
|
264
|
+
async def close_connection(self, user_id: str) -> None:
|
|
265
|
+
transport = await self._connections.get(user_id)
|
|
266
|
+
if transport is None:
|
|
267
|
+
raise not_found(self._path, f"Connection {user_id} not found")
|
|
268
|
+
await transport.close()
|
|
269
|
+
|
|
270
|
+
async def get_transport(self, user_id: str) -> Transport | None:
|
|
271
|
+
return await self._connections.get(user_id)
|
|
272
|
+
|
|
273
|
+
async def connection_count(self) -> int:
|
|
274
|
+
return await self._connections.len()
|
|
275
|
+
|
|
276
|
+
async def close(self) -> None:
|
|
277
|
+
for reg in list(self._channel_registrations):
|
|
278
|
+
await reg.lobby.close()
|
|
279
|
+
for transport in await self._connections.values():
|
|
280
|
+
await transport.close()
|
|
281
|
+
await self._connections.clear()
|
|
282
|
+
self._connect_times.clear()
|
|
283
|
+
|
|
284
|
+
def _fire_metric_connection_opened(self, transport: Transport) -> None:
|
|
285
|
+
hooks = self._options.hooks
|
|
286
|
+
if hooks is None or hooks.metrics is None:
|
|
287
|
+
return
|
|
288
|
+
try:
|
|
289
|
+
hooks.metrics.connection_opened(transport.get_id(), self._path)
|
|
290
|
+
except Exception:
|
|
291
|
+
return
|
|
292
|
+
|
|
293
|
+
def _fire_metric_connection_closed(self, user_id: str, duration: float) -> None:
|
|
294
|
+
hooks = self._options.hooks
|
|
295
|
+
if hooks is None or hooks.metrics is None:
|
|
296
|
+
return
|
|
297
|
+
try:
|
|
298
|
+
hooks.metrics.connection_closed(user_id, duration)
|
|
299
|
+
except Exception:
|
|
300
|
+
return
|
|
301
|
+
|
|
302
|
+
async def _fire_on_connect(self, transport: Transport) -> None:
|
|
303
|
+
hooks = self._options.hooks
|
|
304
|
+
if hooks is None or hooks.on_connect is None:
|
|
305
|
+
return
|
|
306
|
+
try:
|
|
307
|
+
await hooks.on_connect(transport)
|
|
308
|
+
except Exception:
|
|
309
|
+
return
|
|
310
|
+
|
|
311
|
+
async def _fire_on_disconnect(self, transport: Transport) -> None:
|
|
312
|
+
hooks = self._options.hooks
|
|
313
|
+
if hooks is None or hooks.on_disconnect is None:
|
|
314
|
+
return
|
|
315
|
+
try:
|
|
316
|
+
await hooks.on_disconnect(transport)
|
|
317
|
+
except Exception:
|
|
318
|
+
return
|
|
319
|
+
|
|
320
|
+
async def _fire_before_join(
|
|
321
|
+
self, transport: Transport, channel_name: str
|
|
322
|
+
) -> None:
|
|
323
|
+
hooks = self._options.hooks
|
|
324
|
+
if hooks is None or hooks.before_join is None:
|
|
325
|
+
return
|
|
326
|
+
user = User(
|
|
327
|
+
id=transport.get_id(),
|
|
328
|
+
assigns=dict(transport.clone_assigns()),
|
|
329
|
+
)
|
|
330
|
+
try:
|
|
331
|
+
await hooks.before_join(user, channel_name)
|
|
332
|
+
except Exception:
|
|
333
|
+
return
|
|
334
|
+
|
|
335
|
+
async def _fire_after_join(
|
|
336
|
+
self, transport: Transport, channel_name: str
|
|
337
|
+
) -> None:
|
|
338
|
+
hooks = self._options.hooks
|
|
339
|
+
if hooks is None or hooks.after_join is None:
|
|
340
|
+
return
|
|
341
|
+
user = User(
|
|
342
|
+
id=transport.get_id(),
|
|
343
|
+
assigns=dict(transport.clone_assigns()),
|
|
344
|
+
)
|
|
345
|
+
try:
|
|
346
|
+
await hooks.after_join(user, channel_name)
|
|
347
|
+
except Exception:
|
|
348
|
+
return
|
pondsocket/errors.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from pondsocket_common import (
|
|
6
|
+
STATUS_BAD_REQUEST,
|
|
7
|
+
STATUS_CONFLICT,
|
|
8
|
+
STATUS_FORBIDDEN,
|
|
9
|
+
STATUS_GATEWAY_TIMEOUT,
|
|
10
|
+
STATUS_INTERNAL_SERVER_ERROR,
|
|
11
|
+
STATUS_NOT_FOUND,
|
|
12
|
+
STATUS_SERVICE_UNAVAILABLE,
|
|
13
|
+
STATUS_TOO_MANY_REQUESTS,
|
|
14
|
+
STATUS_UNAUTHORIZED,
|
|
15
|
+
MultiError,
|
|
16
|
+
PondError,
|
|
17
|
+
ServerActions,
|
|
18
|
+
add_error,
|
|
19
|
+
bad_request,
|
|
20
|
+
combine,
|
|
21
|
+
conflict,
|
|
22
|
+
forbidden,
|
|
23
|
+
internal,
|
|
24
|
+
not_found,
|
|
25
|
+
temporary_error,
|
|
26
|
+
timeout,
|
|
27
|
+
too_many_requests,
|
|
28
|
+
unauthorized,
|
|
29
|
+
unavailable,
|
|
30
|
+
uuid,
|
|
31
|
+
wrap,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
from .types import Event, SystemEntity, SystemEvents
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def error_event(err: BaseException | None) -> Event | None:
|
|
38
|
+
if err is None:
|
|
39
|
+
return None
|
|
40
|
+
if isinstance(err, PondError):
|
|
41
|
+
message = str(err.cause) if err.cause is not None else err.message
|
|
42
|
+
payload: dict[str, Any] = {
|
|
43
|
+
"code": err.code,
|
|
44
|
+
"details": err.details,
|
|
45
|
+
"temporary": err.temporary,
|
|
46
|
+
"message": message,
|
|
47
|
+
}
|
|
48
|
+
return Event(
|
|
49
|
+
action=ServerActions.SYSTEM.value,
|
|
50
|
+
channel_name=err.channel_name or SystemEntity.GATEWAY.value,
|
|
51
|
+
request_id=uuid(),
|
|
52
|
+
event=SystemEvents.INTERNAL_ERROR.value,
|
|
53
|
+
payload=payload,
|
|
54
|
+
)
|
|
55
|
+
return Event(
|
|
56
|
+
action=ServerActions.SYSTEM.value,
|
|
57
|
+
channel_name=SystemEntity.GATEWAY.value,
|
|
58
|
+
request_id=uuid(),
|
|
59
|
+
event=SystemEvents.INTERNAL_ERROR.value,
|
|
60
|
+
payload={"message": str(err)},
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
__all__ = [
|
|
65
|
+
"STATUS_BAD_REQUEST",
|
|
66
|
+
"STATUS_CONFLICT",
|
|
67
|
+
"STATUS_FORBIDDEN",
|
|
68
|
+
"STATUS_GATEWAY_TIMEOUT",
|
|
69
|
+
"STATUS_INTERNAL_SERVER_ERROR",
|
|
70
|
+
"STATUS_NOT_FOUND",
|
|
71
|
+
"STATUS_SERVICE_UNAVAILABLE",
|
|
72
|
+
"STATUS_TOO_MANY_REQUESTS",
|
|
73
|
+
"STATUS_UNAUTHORIZED",
|
|
74
|
+
"MultiError",
|
|
75
|
+
"PondError",
|
|
76
|
+
"add_error",
|
|
77
|
+
"bad_request",
|
|
78
|
+
"combine",
|
|
79
|
+
"conflict",
|
|
80
|
+
"error_event",
|
|
81
|
+
"forbidden",
|
|
82
|
+
"internal",
|
|
83
|
+
"not_found",
|
|
84
|
+
"temporary_error",
|
|
85
|
+
"timeout",
|
|
86
|
+
"too_many_requests",
|
|
87
|
+
"unauthorized",
|
|
88
|
+
"unavailable",
|
|
89
|
+
"wrap",
|
|
90
|
+
]
|