hosteday-python 0.1.0__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.
- hosteday/__init__.py +111 -0
- hosteday/_version.py +3 -0
- hosteday/auth/__init__.py +34 -0
- hosteday/auth/hosteday_auth.py +444 -0
- hosteday/auth/hosteday_auth_storage.py +130 -0
- hosteday/auth/hosteday_session.py +184 -0
- hosteday/auth/hosteday_token_provider.py +82 -0
- hosteday/auth/hosteday_user.py +223 -0
- hosteday/cli/__init__.py +5 -0
- hosteday/cli/setup.py +163 -0
- hosteday/config/__init__.py +15 -0
- hosteday/config/hosteday_config.py +576 -0
- hosteday/config/hosteday_option_keys.py +60 -0
- hosteday/config/hosteday_url_resolver.py +255 -0
- hosteday/connectivity/__init__.py +5 -0
- hosteday/connectivity/hosteday_connectivity.py +147 -0
- hosteday/exceptions.py +233 -0
- hosteday/features/__init__.py +5 -0
- hosteday/features/hosteday_features.py +78 -0
- hosteday/hosteday.py +346 -0
- hosteday/hosteday_client.py +579 -0
- hosteday/http/__init__.py +18 -0
- hosteday/http/hosteday_http_client.py +340 -0
- hosteday/http/hosteday_response_reader.py +171 -0
- hosteday/http/query_builder.py +204 -0
- hosteday/jobs/__init__.py +9 -0
- hosteday/jobs/hosteday_job_response.py +76 -0
- hosteday/jobs/hosteday_jobs_client.py +109 -0
- hosteday/notifications/__init__.py +13 -0
- hosteday/notifications/hosteday_notification_client.py +290 -0
- hosteday/notifications/hosteday_notification_response.py +79 -0
- hosteday/py.typed +1 -0
- hosteday/reactive/__init__.py +5 -0
- hosteday/reactive/observable_state.py +67 -0
- hosteday/realtime/__init__.py +31 -0
- hosteday/realtime/connection_state.py +14 -0
- hosteday/realtime/hosteday_channel.py +258 -0
- hosteday/realtime/hosteday_channel_auth.py +163 -0
- hosteday/realtime/hosteday_channel_type.py +68 -0
- hosteday/realtime/hosteday_realtime_client.py +790 -0
- hosteday/realtime/hosteday_realtime_event.py +130 -0
- hosteday/web/__init__.py +5 -0
- hosteday/web/server.py +637 -0
- hosteday_python/__init__.py +6 -0
- hosteday_python/py.typed +1 -0
- hosteday_python-0.1.0.dist-info/METADATA +205 -0
- hosteday_python-0.1.0.dist-info/RECORD +50 -0
- hosteday_python-0.1.0.dist-info/WHEEL +4 -0
- hosteday_python-0.1.0.dist-info/entry_points.txt +2 -0
- hosteday_python-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
"""Pusher v7 / Laravel Reverb asyncio WebSocket client with heartbeat and auto-reconnect."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
|
|
9
|
+
from typing import Any, Protocol
|
|
10
|
+
from urllib.parse import urlencode
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from hosteday._version import __version__
|
|
15
|
+
from hosteday.auth.hosteday_auth_storage import (
|
|
16
|
+
HostedayAuthStorage,
|
|
17
|
+
HostedayAuthStorageKeys,
|
|
18
|
+
)
|
|
19
|
+
from hosteday.auth.hosteday_token_provider import HostedayTokenProvider
|
|
20
|
+
from hosteday.config.hosteday_config import HostedayConfig
|
|
21
|
+
from hosteday.config.hosteday_url_resolver import HostedayUrlResolver
|
|
22
|
+
from hosteday.exceptions import HostedayException
|
|
23
|
+
from hosteday.reactive.observable_state import ObservableState
|
|
24
|
+
from hosteday.realtime.connection_state import RealtimeConnectionState
|
|
25
|
+
from hosteday.realtime.hosteday_channel import (
|
|
26
|
+
ChannelSubscription,
|
|
27
|
+
HostedayChannel,
|
|
28
|
+
PresenceChannel,
|
|
29
|
+
)
|
|
30
|
+
from hosteday.realtime.hosteday_channel_auth import HostedayChannelAuthorizationDelegate
|
|
31
|
+
from hosteday.realtime.hosteday_channel_type import (
|
|
32
|
+
HostedayChannelType,
|
|
33
|
+
infer_channel_type,
|
|
34
|
+
normalize_channel_name,
|
|
35
|
+
)
|
|
36
|
+
from hosteday.realtime.hosteday_realtime_event import HostedayRealtimeEvent
|
|
37
|
+
|
|
38
|
+
HostedayRealtimeCallback = Callable[[HostedayRealtimeEvent], Any]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class WebSocketProtocol(Protocol):
|
|
42
|
+
"""Minimal WebSocket interface compatible with ``websockets`` and test doubles."""
|
|
43
|
+
|
|
44
|
+
async def send(self, message: str) -> None:
|
|
45
|
+
...
|
|
46
|
+
|
|
47
|
+
async def recv(self) -> str | bytes:
|
|
48
|
+
...
|
|
49
|
+
|
|
50
|
+
async def close(self, code: int = 1000, reason: str = "") -> None:
|
|
51
|
+
...
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
WebSocketConnector = Callable[[str], Awaitable[WebSocketProtocol]]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def _default_ws_connector(uri: str) -> WebSocketProtocol:
|
|
58
|
+
import websockets
|
|
59
|
+
|
|
60
|
+
return await websockets.connect(uri, ping_interval=None, ping_timeout=None)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class HostedayRealtimeClient:
|
|
64
|
+
"""Manages HosteDay Pusher v7 / Laravel Reverb WebSocket connections and channels."""
|
|
65
|
+
|
|
66
|
+
DEFAULT_ACTIVITY_SECONDS: float = 120.0
|
|
67
|
+
WAIT_FOR_PONG_SECONDS: float = 30.0
|
|
68
|
+
MIN_RECONNECT_DELAY_SECONDS: float = 1.0
|
|
69
|
+
MAX_RECONNECT_DELAY_SECONDS: float = 30.0
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
*,
|
|
74
|
+
config: HostedayConfig,
|
|
75
|
+
token_provider: HostedayTokenProvider | None = None,
|
|
76
|
+
auth_storage: HostedayAuthStorage | None = None,
|
|
77
|
+
headers_callback: Callable[[], Awaitable[Mapping[str, str]]] | None = None,
|
|
78
|
+
http_client: httpx.AsyncClient | None = None,
|
|
79
|
+
ws_connector: WebSocketConnector | None = None,
|
|
80
|
+
activity_timeout: float = DEFAULT_ACTIVITY_SECONDS,
|
|
81
|
+
pong_timeout: float = WAIT_FOR_PONG_SECONDS,
|
|
82
|
+
min_reconnect_delay: float = MIN_RECONNECT_DELAY_SECONDS,
|
|
83
|
+
max_reconnect_delay: float = MAX_RECONNECT_DELAY_SECONDS,
|
|
84
|
+
) -> None:
|
|
85
|
+
self.config = config
|
|
86
|
+
self.token_provider = token_provider
|
|
87
|
+
self.auth_storage = auth_storage
|
|
88
|
+
self.headers_callback = headers_callback
|
|
89
|
+
self._http_client = http_client
|
|
90
|
+
self._ws_connector: WebSocketConnector = ws_connector or _default_ws_connector
|
|
91
|
+
|
|
92
|
+
self._default_activity_timeout = activity_timeout
|
|
93
|
+
self._activity_timeout = activity_timeout
|
|
94
|
+
self._pong_timeout = pong_timeout
|
|
95
|
+
self._min_reconnect_delay = min_reconnect_delay
|
|
96
|
+
self._max_reconnect_delay = max_reconnect_delay
|
|
97
|
+
self._reconnect_delay = min_reconnect_delay
|
|
98
|
+
|
|
99
|
+
self._auth_delegate = HostedayChannelAuthorizationDelegate(
|
|
100
|
+
authorization_endpoint=config.uri(config.broadcasting_auth_path),
|
|
101
|
+
headers_builder=self.build_authorization_headers,
|
|
102
|
+
http_client=http_client,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
self._channels: dict[str, HostedayChannel] = {}
|
|
106
|
+
self._subscriptions: dict[str, list[ChannelSubscription]] = {}
|
|
107
|
+
self._subscribed_or_pending: set[str] = set()
|
|
108
|
+
|
|
109
|
+
self._ws: WebSocketProtocol | None = None
|
|
110
|
+
self._socket_id: str | None = None
|
|
111
|
+
self._last_error: str | None = None
|
|
112
|
+
self._last_activity: float = time.monotonic()
|
|
113
|
+
self._manual_disconnect: bool = False
|
|
114
|
+
|
|
115
|
+
self._connection_state = ObservableState(
|
|
116
|
+
RealtimeConnectionState.DISCONNECTED,
|
|
117
|
+
distinct_until_changed=True,
|
|
118
|
+
)
|
|
119
|
+
self._is_connected_state = ObservableState(False, distinct_until_changed=True)
|
|
120
|
+
self._error_state: ObservableState[str | None] = ObservableState(None)
|
|
121
|
+
|
|
122
|
+
self._receive_task: asyncio.Task[None] | None = None
|
|
123
|
+
self._heartbeat_task: asyncio.Task[None] | None = None
|
|
124
|
+
self._pong_task: asyncio.Task[None] | None = None
|
|
125
|
+
self._reconnect_task: asyncio.Task[None] | None = None
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def connection_state(self) -> RealtimeConnectionState:
|
|
129
|
+
return self._connection_state.value
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def is_connected(self) -> bool:
|
|
133
|
+
return self._is_connected_state.value
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def socket_id(self) -> str | None:
|
|
137
|
+
return self._socket_id
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def last_error(self) -> str | None:
|
|
141
|
+
return self._last_error
|
|
142
|
+
|
|
143
|
+
def on_connection_state_changed(self) -> AsyncIterator[bool]:
|
|
144
|
+
return self._is_connected_state.stream(replay_current=True)
|
|
145
|
+
|
|
146
|
+
def on_error(self) -> AsyncIterator[str | None]:
|
|
147
|
+
return self._error_state.stream(replay_current=False)
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def resolved_host(self) -> str:
|
|
151
|
+
return HostedayUrlResolver.normalize_realtime_host(self.config.realtime_host)
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def resolved_port(self) -> int:
|
|
155
|
+
return HostedayUrlResolver.resolve_realtime_port(
|
|
156
|
+
scheme=self.config.realtime_scheme,
|
|
157
|
+
host=self.resolved_host,
|
|
158
|
+
port=self.config.realtime_port,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def resolved_websocket_uri(self) -> str:
|
|
163
|
+
scheme = self.config.realtime_scheme.lower()
|
|
164
|
+
host = self.resolved_host
|
|
165
|
+
port = self.resolved_port
|
|
166
|
+
key = self.config.pusher_key.strip()
|
|
167
|
+
query = urlencode(
|
|
168
|
+
{
|
|
169
|
+
"protocol": "7",
|
|
170
|
+
"client": "hosteday-python",
|
|
171
|
+
"version": __version__,
|
|
172
|
+
"flash": "false",
|
|
173
|
+
}
|
|
174
|
+
)
|
|
175
|
+
return f"{scheme}://{host}:{port}/app/{key}?{query}"
|
|
176
|
+
|
|
177
|
+
async def connect(self) -> None:
|
|
178
|
+
"""Opens the WebSocket connection to Laravel Reverb / Pusher v7."""
|
|
179
|
+
if self._ws is not None and self.connection_state in {
|
|
180
|
+
RealtimeConnectionState.CONNECTED,
|
|
181
|
+
RealtimeConnectionState.CONNECTING,
|
|
182
|
+
}:
|
|
183
|
+
return
|
|
184
|
+
|
|
185
|
+
if not self.resolved_host:
|
|
186
|
+
msg = "Missing realtime host. Configure realtime_host before connecting realtime."
|
|
187
|
+
self._report_error(msg)
|
|
188
|
+
raise HostedayException(msg)
|
|
189
|
+
|
|
190
|
+
if not self.config.pusher_key.strip():
|
|
191
|
+
msg = "Missing Pusher key. Configure realtime_app_key before connecting realtime."
|
|
192
|
+
self._report_error(msg)
|
|
193
|
+
raise HostedayException(msg)
|
|
194
|
+
|
|
195
|
+
self._manual_disconnect = False
|
|
196
|
+
self._connection_state.emit(RealtimeConnectionState.CONNECTING)
|
|
197
|
+
|
|
198
|
+
try:
|
|
199
|
+
self._ws = await self._ws_connector(self.resolved_websocket_uri)
|
|
200
|
+
except Exception as exc:
|
|
201
|
+
self._report_error(
|
|
202
|
+
f"WebSocket connection error ({self.resolved_host}:{self.resolved_port}): {exc}"
|
|
203
|
+
)
|
|
204
|
+
self._schedule_reconnect()
|
|
205
|
+
raise HostedayException(
|
|
206
|
+
f"Failed to connect to Hosteday realtime: {exc}",
|
|
207
|
+
error=exc,
|
|
208
|
+
) from exc
|
|
209
|
+
|
|
210
|
+
self._last_activity = time.monotonic()
|
|
211
|
+
self._reconnect_delay = self._min_reconnect_delay
|
|
212
|
+
self._receive_task = asyncio.create_task(self._receive_loop())
|
|
213
|
+
self._start_heartbeat()
|
|
214
|
+
|
|
215
|
+
async def disconnect(self) -> None:
|
|
216
|
+
"""Cancels listeners, unsubscribes channels, and closes the WebSocket cleanly."""
|
|
217
|
+
self._manual_disconnect = True
|
|
218
|
+
await self._cancel_background_tasks()
|
|
219
|
+
|
|
220
|
+
for subs in self._subscriptions.values():
|
|
221
|
+
for sub in subs:
|
|
222
|
+
sub.cancel()
|
|
223
|
+
self._subscriptions.clear()
|
|
224
|
+
|
|
225
|
+
if self._ws is not None:
|
|
226
|
+
for ch_name in list(self._channels.keys()):
|
|
227
|
+
try:
|
|
228
|
+
await self._send_raw(
|
|
229
|
+
json.dumps(
|
|
230
|
+
{"event": "pusher:unsubscribe", "data": {"channel": ch_name}}
|
|
231
|
+
)
|
|
232
|
+
)
|
|
233
|
+
except Exception:
|
|
234
|
+
pass
|
|
235
|
+
try:
|
|
236
|
+
await self._ws.close(1000, "Client disconnect")
|
|
237
|
+
except Exception:
|
|
238
|
+
pass
|
|
239
|
+
self._ws = None
|
|
240
|
+
|
|
241
|
+
for channel in self._channels.values():
|
|
242
|
+
channel.clear_listeners()
|
|
243
|
+
self._channels.clear()
|
|
244
|
+
self._subscribed_or_pending.clear()
|
|
245
|
+
|
|
246
|
+
self._socket_id = None
|
|
247
|
+
self._connection_state.emit(RealtimeConnectionState.DISCONNECTED)
|
|
248
|
+
self._is_connected_state.emit(False)
|
|
249
|
+
|
|
250
|
+
# ------------------------------------------------------------------
|
|
251
|
+
# Channel Accessors & Subscription APIs
|
|
252
|
+
# ------------------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
def public_channel(self, channel_name: str) -> HostedayChannel:
|
|
255
|
+
normalized = normalize_channel_name(channel_name, HostedayChannelType.PUBLIC)
|
|
256
|
+
return self._get_or_create_channel(normalized, HostedayChannelType.PUBLIC)
|
|
257
|
+
|
|
258
|
+
def private_channel(self, channel_name: str) -> HostedayChannel:
|
|
259
|
+
normalized = normalize_channel_name(channel_name, HostedayChannelType.PRIVATE)
|
|
260
|
+
return self._get_or_create_channel(normalized, HostedayChannelType.PRIVATE)
|
|
261
|
+
|
|
262
|
+
def presence_channel(self, channel_name: str) -> PresenceChannel:
|
|
263
|
+
normalized = normalize_channel_name(channel_name, HostedayChannelType.PRESENCE)
|
|
264
|
+
channel = self._get_or_create_channel(normalized, HostedayChannelType.PRESENCE)
|
|
265
|
+
if not isinstance(channel, PresenceChannel):
|
|
266
|
+
raise HostedayException(
|
|
267
|
+
f'A different channel type is already registered for "{normalized}".'
|
|
268
|
+
)
|
|
269
|
+
return channel
|
|
270
|
+
|
|
271
|
+
def private_encrypted_channel(self, channel_name: str) -> HostedayChannel:
|
|
272
|
+
normalized = normalize_channel_name(channel_name, HostedayChannelType.PRIVATE_ENCRYPTED)
|
|
273
|
+
return self._get_or_create_channel(normalized, HostedayChannelType.PRIVATE_ENCRYPTED)
|
|
274
|
+
|
|
275
|
+
def channel(
|
|
276
|
+
self,
|
|
277
|
+
channel_name: str,
|
|
278
|
+
*,
|
|
279
|
+
channel_type: HostedayChannelType = HostedayChannelType.PUBLIC,
|
|
280
|
+
) -> HostedayChannel:
|
|
281
|
+
if channel_type is HostedayChannelType.PUBLIC:
|
|
282
|
+
return self.public_channel(channel_name)
|
|
283
|
+
if channel_type is HostedayChannelType.PRIVATE:
|
|
284
|
+
return self.private_channel(channel_name)
|
|
285
|
+
if channel_type is HostedayChannelType.PRESENCE:
|
|
286
|
+
return self.presence_channel(channel_name)
|
|
287
|
+
return self.private_encrypted_channel(channel_name)
|
|
288
|
+
|
|
289
|
+
def get_channel(
|
|
290
|
+
self,
|
|
291
|
+
channel_name: str,
|
|
292
|
+
*,
|
|
293
|
+
channel_type: HostedayChannelType = HostedayChannelType.PUBLIC,
|
|
294
|
+
) -> HostedayChannel | None:
|
|
295
|
+
normalized = normalize_channel_name(channel_name, channel_type)
|
|
296
|
+
return self._channels.get(normalized)
|
|
297
|
+
|
|
298
|
+
async def subscribe_public(self, channel_name: str) -> HostedayChannel:
|
|
299
|
+
ch = self.public_channel(channel_name)
|
|
300
|
+
await self._subscribe_channel_if_connected(ch)
|
|
301
|
+
return ch
|
|
302
|
+
|
|
303
|
+
async def subscribe_private(self, channel_name: str) -> HostedayChannel:
|
|
304
|
+
if not self.is_connected and self._ws is None:
|
|
305
|
+
await self.connect()
|
|
306
|
+
ch = self.private_channel(channel_name)
|
|
307
|
+
await self._subscribe_channel_if_connected(ch)
|
|
308
|
+
return ch
|
|
309
|
+
|
|
310
|
+
async def subscribe_presence(self, channel_name: str) -> PresenceChannel:
|
|
311
|
+
if not self.is_connected and self._ws is None:
|
|
312
|
+
await self.connect()
|
|
313
|
+
ch = self.presence_channel(channel_name)
|
|
314
|
+
await self._subscribe_channel_if_connected(ch)
|
|
315
|
+
return ch
|
|
316
|
+
|
|
317
|
+
async def subscribe_private_encrypted(self, channel_name: str) -> HostedayChannel:
|
|
318
|
+
if not self.is_connected and self._ws is None:
|
|
319
|
+
await self.connect()
|
|
320
|
+
ch = self.private_encrypted_channel(channel_name)
|
|
321
|
+
await self._subscribe_channel_if_connected(ch)
|
|
322
|
+
return ch
|
|
323
|
+
|
|
324
|
+
async def listen(
|
|
325
|
+
self,
|
|
326
|
+
*,
|
|
327
|
+
channel: str,
|
|
328
|
+
event: str,
|
|
329
|
+
on_event: HostedayRealtimeCallback,
|
|
330
|
+
channel_type: HostedayChannelType = HostedayChannelType.PUBLIC,
|
|
331
|
+
) -> ChannelSubscription:
|
|
332
|
+
ch = self.channel(channel, channel_type=channel_type)
|
|
333
|
+
sub = ch.bind(event, on_event)
|
|
334
|
+
self._track_subscription(ch.name, sub)
|
|
335
|
+
await self._subscribe_channel_if_connected(ch)
|
|
336
|
+
return sub
|
|
337
|
+
|
|
338
|
+
async def listen_public(
|
|
339
|
+
self,
|
|
340
|
+
*,
|
|
341
|
+
channel: str,
|
|
342
|
+
event: str,
|
|
343
|
+
on_event: HostedayRealtimeCallback,
|
|
344
|
+
) -> ChannelSubscription:
|
|
345
|
+
return await self.listen(
|
|
346
|
+
channel=channel,
|
|
347
|
+
event=event,
|
|
348
|
+
on_event=on_event,
|
|
349
|
+
channel_type=HostedayChannelType.PUBLIC,
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
async def listen_private(
|
|
353
|
+
self,
|
|
354
|
+
*,
|
|
355
|
+
channel: str,
|
|
356
|
+
event: str,
|
|
357
|
+
on_event: HostedayRealtimeCallback,
|
|
358
|
+
) -> ChannelSubscription:
|
|
359
|
+
return await self.listen(
|
|
360
|
+
channel=channel,
|
|
361
|
+
event=event,
|
|
362
|
+
on_event=on_event,
|
|
363
|
+
channel_type=HostedayChannelType.PRIVATE,
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
async def listen_presence(
|
|
367
|
+
self,
|
|
368
|
+
*,
|
|
369
|
+
channel: str,
|
|
370
|
+
event: str,
|
|
371
|
+
on_event: HostedayRealtimeCallback,
|
|
372
|
+
) -> ChannelSubscription:
|
|
373
|
+
return await self.listen(
|
|
374
|
+
channel=channel,
|
|
375
|
+
event=event,
|
|
376
|
+
on_event=on_event,
|
|
377
|
+
channel_type=HostedayChannelType.PRESENCE,
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
async def listen_private_encrypted(
|
|
381
|
+
self,
|
|
382
|
+
*,
|
|
383
|
+
channel: str,
|
|
384
|
+
event: str,
|
|
385
|
+
on_event: HostedayRealtimeCallback,
|
|
386
|
+
) -> ChannelSubscription:
|
|
387
|
+
return await self.listen(
|
|
388
|
+
channel=channel,
|
|
389
|
+
event=event,
|
|
390
|
+
on_event=on_event,
|
|
391
|
+
channel_type=HostedayChannelType.PRIVATE_ENCRYPTED,
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
async def listen_presence_members_list(
|
|
395
|
+
self,
|
|
396
|
+
*,
|
|
397
|
+
channel: str,
|
|
398
|
+
on_event: HostedayRealtimeCallback,
|
|
399
|
+
) -> ChannelSubscription:
|
|
400
|
+
"""Listens for initial presence members; immediately replays snapshot if already subscribed."""
|
|
401
|
+
presence = self.presence_channel(channel)
|
|
402
|
+
sub = presence.bind("pusher:subscription_succeeded", on_event)
|
|
403
|
+
self._track_subscription(presence.name, sub)
|
|
404
|
+
|
|
405
|
+
if presence.is_subscribed:
|
|
406
|
+
snapshot = presence.build_presence_snapshot_payload()
|
|
407
|
+
event = HostedayRealtimeEvent.from_raw(
|
|
408
|
+
name="pusher:subscription_succeeded",
|
|
409
|
+
channel_name=presence.name,
|
|
410
|
+
data=snapshot,
|
|
411
|
+
)
|
|
412
|
+
loop = asyncio.get_running_loop()
|
|
413
|
+
loop.call_soon(self._invoke_callback, on_event, event)
|
|
414
|
+
|
|
415
|
+
await self._subscribe_channel_if_connected(presence)
|
|
416
|
+
return sub
|
|
417
|
+
|
|
418
|
+
async def listen_presence_member_added(
|
|
419
|
+
self,
|
|
420
|
+
*,
|
|
421
|
+
channel: str,
|
|
422
|
+
on_event: HostedayRealtimeCallback,
|
|
423
|
+
) -> ChannelSubscription:
|
|
424
|
+
return await self.listen_presence(
|
|
425
|
+
channel=channel,
|
|
426
|
+
event="pusher:member_added",
|
|
427
|
+
on_event=on_event,
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
async def listen_presence_member_removed(
|
|
431
|
+
self,
|
|
432
|
+
*,
|
|
433
|
+
channel: str,
|
|
434
|
+
on_event: HostedayRealtimeCallback,
|
|
435
|
+
) -> ChannelSubscription:
|
|
436
|
+
return await self.listen_presence(
|
|
437
|
+
channel=channel,
|
|
438
|
+
event="pusher:member_removed",
|
|
439
|
+
on_event=on_event,
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
async def unsubscribe(
|
|
443
|
+
self,
|
|
444
|
+
channel_name: str,
|
|
445
|
+
*,
|
|
446
|
+
channel_type: HostedayChannelType | None = None,
|
|
447
|
+
) -> None:
|
|
448
|
+
trimmed = channel_name.strip()
|
|
449
|
+
if not trimmed:
|
|
450
|
+
return
|
|
451
|
+
|
|
452
|
+
effective_type = channel_type or infer_channel_type(trimmed)
|
|
453
|
+
primary = normalize_channel_name(trimmed, effective_type)
|
|
454
|
+
candidates = [primary, trimmed]
|
|
455
|
+
if not trimmed.startswith(("presence-", "private-")):
|
|
456
|
+
candidates.extend(
|
|
457
|
+
[f"presence-{trimmed}", f"private-{trimmed}", f"private-encrypted-{trimmed}"]
|
|
458
|
+
)
|
|
459
|
+
|
|
460
|
+
resolved_key = primary
|
|
461
|
+
for candidate in candidates:
|
|
462
|
+
if candidate in self._channels or candidate in self._subscriptions:
|
|
463
|
+
resolved_key = candidate
|
|
464
|
+
break
|
|
465
|
+
|
|
466
|
+
subs = self._subscriptions.pop(resolved_key, [])
|
|
467
|
+
for sub in subs:
|
|
468
|
+
sub.cancel()
|
|
469
|
+
|
|
470
|
+
removed = self._channels.pop(resolved_key, None)
|
|
471
|
+
self._subscribed_or_pending.discard(resolved_key)
|
|
472
|
+
if removed is not None:
|
|
473
|
+
removed.clear_listeners()
|
|
474
|
+
if self.is_connected and self._ws is not None:
|
|
475
|
+
await self._send_raw(
|
|
476
|
+
json.dumps(
|
|
477
|
+
{"event": "pusher:unsubscribe", "data": {"channel": resolved_key}}
|
|
478
|
+
)
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
async def send_client_event(
|
|
482
|
+
self,
|
|
483
|
+
*,
|
|
484
|
+
channel_name: str,
|
|
485
|
+
event_name: str,
|
|
486
|
+
data: Mapping[str, Any],
|
|
487
|
+
) -> None:
|
|
488
|
+
if not self.is_connected or self._ws is None:
|
|
489
|
+
raise HostedayException("Realtime client is not connected. Call connect() first.")
|
|
490
|
+
await self._send_raw(
|
|
491
|
+
json.dumps(
|
|
492
|
+
{
|
|
493
|
+
"event": event_name,
|
|
494
|
+
"channel": channel_name,
|
|
495
|
+
"data": dict(data),
|
|
496
|
+
}
|
|
497
|
+
)
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
async def build_authorization_headers(self) -> dict[str, str]:
|
|
501
|
+
"""Builds dynamic HTTP headers for ``/api/broadcasting/auth-manual``."""
|
|
502
|
+
if self.headers_callback is not None:
|
|
503
|
+
return dict(await self.headers_callback())
|
|
504
|
+
|
|
505
|
+
headers: dict[str, str] = {
|
|
506
|
+
"Accept": "application/json",
|
|
507
|
+
**self.config.default_headers,
|
|
508
|
+
}
|
|
509
|
+
api_token = self.config.api_token.strip() if self.config.api_token else ""
|
|
510
|
+
if api_token:
|
|
511
|
+
headers["X-Api-Token"] = api_token
|
|
512
|
+
if self.config.api_token_header:
|
|
513
|
+
headers[self.config.api_token_header] = api_token
|
|
514
|
+
|
|
515
|
+
token: str | None = None
|
|
516
|
+
if self.token_provider is not None:
|
|
517
|
+
token = await self.token_provider.get_token()
|
|
518
|
+
if not token and self.auth_storage is not None:
|
|
519
|
+
token = await self.auth_storage.read(HostedayAuthStorageKeys.ACCESS_TOKEN)
|
|
520
|
+
|
|
521
|
+
if token and token.strip():
|
|
522
|
+
headers["Authorization"] = f"Bearer {token.strip()}"
|
|
523
|
+
|
|
524
|
+
return headers
|
|
525
|
+
|
|
526
|
+
# ------------------------------------------------------------------
|
|
527
|
+
# Internal Pusher v7 Protocol Engine
|
|
528
|
+
# ------------------------------------------------------------------
|
|
529
|
+
|
|
530
|
+
async def handle_incoming_message(self, raw_message: str) -> None:
|
|
531
|
+
"""Processes a single Pusher v7 JSON frame (public for deterministic unit testing)."""
|
|
532
|
+
self._last_activity = time.monotonic()
|
|
533
|
+
if self._pong_task is not None and not self._pong_task.done():
|
|
534
|
+
self._pong_task.cancel()
|
|
535
|
+
self._pong_task = None
|
|
536
|
+
|
|
537
|
+
try:
|
|
538
|
+
frame = json.loads(raw_message)
|
|
539
|
+
except json.JSONDecodeError:
|
|
540
|
+
return
|
|
541
|
+
|
|
542
|
+
if not isinstance(frame, Mapping):
|
|
543
|
+
return
|
|
544
|
+
|
|
545
|
+
raw_event = frame.get("event")
|
|
546
|
+
if not isinstance(raw_event, str) or not raw_event:
|
|
547
|
+
return
|
|
548
|
+
|
|
549
|
+
event_name = self._normalize_event_name(raw_event)
|
|
550
|
+
channel_name = frame.get("channel")
|
|
551
|
+
data = frame.get("data")
|
|
552
|
+
|
|
553
|
+
if event_name == "pusher:connection_established":
|
|
554
|
+
parsed = HostedayRealtimeEvent.from_raw(
|
|
555
|
+
name=event_name,
|
|
556
|
+
channel_name="",
|
|
557
|
+
data=data,
|
|
558
|
+
).payload
|
|
559
|
+
sid = parsed.get("socket_id")
|
|
560
|
+
if sid is not None and str(sid).strip():
|
|
561
|
+
self._socket_id = str(sid).strip()
|
|
562
|
+
|
|
563
|
+
server_timeout = parsed.get("activity_timeout")
|
|
564
|
+
if isinstance(server_timeout, (int, float)) and server_timeout > 0:
|
|
565
|
+
self._activity_timeout = min(
|
|
566
|
+
float(server_timeout), self._default_activity_timeout
|
|
567
|
+
)
|
|
568
|
+
else:
|
|
569
|
+
self._activity_timeout = self._default_activity_timeout
|
|
570
|
+
|
|
571
|
+
self._last_error = None
|
|
572
|
+
self._reconnect_delay = self._min_reconnect_delay
|
|
573
|
+
self._connection_state.emit(RealtimeConnectionState.CONNECTED)
|
|
574
|
+
self._is_connected_state.emit(True)
|
|
575
|
+
await self._resubscribe_all_channels()
|
|
576
|
+
return
|
|
577
|
+
|
|
578
|
+
if event_name == "pusher:pong":
|
|
579
|
+
return
|
|
580
|
+
|
|
581
|
+
if event_name == "pusher:error":
|
|
582
|
+
err_detail = HostedayRealtimeEvent.from_raw(
|
|
583
|
+
name=event_name,
|
|
584
|
+
channel_name=str(channel_name or ""),
|
|
585
|
+
data=data,
|
|
586
|
+
).payload
|
|
587
|
+
code = err_detail.get("code")
|
|
588
|
+
msg = err_detail.get("message") or data
|
|
589
|
+
code_part = f" (code {code})" if code is not None else ""
|
|
590
|
+
ch_part = f" on {channel_name}" if channel_name else ""
|
|
591
|
+
self._report_error(f"Pusher/Reverb server error{code_part}{ch_part}: {msg}")
|
|
592
|
+
return
|
|
593
|
+
|
|
594
|
+
if isinstance(channel_name, str) and channel_name.strip():
|
|
595
|
+
ch = self._channels.get(channel_name.strip())
|
|
596
|
+
if ch is not None:
|
|
597
|
+
ch.dispatch_event(event_name, data, raw=frame)
|
|
598
|
+
|
|
599
|
+
@staticmethod
|
|
600
|
+
def _normalize_event_name(event: str) -> str:
|
|
601
|
+
if event.startswith("pusher_internal:"):
|
|
602
|
+
return f"pusher:{event[len('pusher_internal:'):]}"
|
|
603
|
+
return event
|
|
604
|
+
|
|
605
|
+
async def _receive_loop(self) -> None:
|
|
606
|
+
ws = self._ws
|
|
607
|
+
if ws is None:
|
|
608
|
+
return
|
|
609
|
+
try:
|
|
610
|
+
while True:
|
|
611
|
+
raw = await ws.recv()
|
|
612
|
+
text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
|
|
613
|
+
await self.handle_incoming_message(text)
|
|
614
|
+
except asyncio.CancelledError:
|
|
615
|
+
return
|
|
616
|
+
except Exception as exc:
|
|
617
|
+
if not self._manual_disconnect:
|
|
618
|
+
self._report_error(f"WebSocket closed unexpectedly: {exc}")
|
|
619
|
+
self._handle_unexpected_disconnect()
|
|
620
|
+
|
|
621
|
+
def _start_heartbeat(self) -> None:
|
|
622
|
+
if self._heartbeat_task is not None and not self._heartbeat_task.done():
|
|
623
|
+
self._heartbeat_task.cancel()
|
|
624
|
+
self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
|
|
625
|
+
|
|
626
|
+
async def _heartbeat_loop(self) -> None:
|
|
627
|
+
try:
|
|
628
|
+
while not self._manual_disconnect:
|
|
629
|
+
check_step = min(1.0, max(0.05, self._activity_timeout / 4.0))
|
|
630
|
+
await asyncio.sleep(check_step)
|
|
631
|
+
if not self.is_connected or self._ws is None:
|
|
632
|
+
continue
|
|
633
|
+
idle = time.monotonic() - self._last_activity
|
|
634
|
+
if idle >= self._activity_timeout and (
|
|
635
|
+
self._pong_task is None or self._pong_task.done()
|
|
636
|
+
):
|
|
637
|
+
await self._send_ping()
|
|
638
|
+
except asyncio.CancelledError:
|
|
639
|
+
return
|
|
640
|
+
|
|
641
|
+
async def _send_ping(self) -> None:
|
|
642
|
+
await self._send_raw(json.dumps({"event": "pusher:ping", "data": {}}))
|
|
643
|
+
if self._pong_task is not None and not self._pong_task.done():
|
|
644
|
+
self._pong_task.cancel()
|
|
645
|
+
self._pong_task = asyncio.create_task(self._wait_for_pong())
|
|
646
|
+
|
|
647
|
+
async def _wait_for_pong(self) -> None:
|
|
648
|
+
try:
|
|
649
|
+
await asyncio.sleep(self._pong_timeout)
|
|
650
|
+
if self._ws is not None and not self._manual_disconnect:
|
|
651
|
+
self._report_error("WebSocket pong timeout; reconnecting.")
|
|
652
|
+
try:
|
|
653
|
+
await self._ws.close(1001, "Pong timeout")
|
|
654
|
+
except Exception:
|
|
655
|
+
pass
|
|
656
|
+
self._handle_unexpected_disconnect()
|
|
657
|
+
except asyncio.CancelledError:
|
|
658
|
+
return
|
|
659
|
+
|
|
660
|
+
def _handle_unexpected_disconnect(self) -> None:
|
|
661
|
+
self._ws = None
|
|
662
|
+
self._socket_id = None
|
|
663
|
+
self._subscribed_or_pending.clear()
|
|
664
|
+
for ch in self._channels.values():
|
|
665
|
+
ch.is_subscribed = False
|
|
666
|
+
self._is_connected_state.emit(False)
|
|
667
|
+
self._connection_state.emit(RealtimeConnectionState.RECONNECTING)
|
|
668
|
+
self._schedule_reconnect()
|
|
669
|
+
|
|
670
|
+
def _schedule_reconnect(self) -> None:
|
|
671
|
+
if self._manual_disconnect:
|
|
672
|
+
return
|
|
673
|
+
if self._reconnect_task is not None and not self._reconnect_task.done():
|
|
674
|
+
return
|
|
675
|
+
self._reconnect_task = asyncio.create_task(self._reconnect_loop())
|
|
676
|
+
|
|
677
|
+
async def _reconnect_loop(self) -> None:
|
|
678
|
+
try:
|
|
679
|
+
delay = self._reconnect_delay
|
|
680
|
+
self._reconnect_delay = min(delay * 2.0, self._max_reconnect_delay)
|
|
681
|
+
await asyncio.sleep(delay)
|
|
682
|
+
if not self._manual_disconnect:
|
|
683
|
+
try:
|
|
684
|
+
await self.connect()
|
|
685
|
+
except Exception:
|
|
686
|
+
pass
|
|
687
|
+
except asyncio.CancelledError:
|
|
688
|
+
return
|
|
689
|
+
|
|
690
|
+
async def _resubscribe_all_channels(self) -> None:
|
|
691
|
+
self._subscribed_or_pending.clear()
|
|
692
|
+
for ch in list(self._channels.values()):
|
|
693
|
+
try:
|
|
694
|
+
await self._subscribe_channel_on_socket(ch)
|
|
695
|
+
except Exception as exc:
|
|
696
|
+
self._report_error(f'Channel subscribe failed for "{ch.name}": {exc}')
|
|
697
|
+
|
|
698
|
+
async def _subscribe_channel_if_connected(self, channel: HostedayChannel) -> None:
|
|
699
|
+
if (
|
|
700
|
+
self.is_connected
|
|
701
|
+
and self._socket_id
|
|
702
|
+
and self._ws is not None
|
|
703
|
+
and channel.name not in self._subscribed_or_pending
|
|
704
|
+
):
|
|
705
|
+
await self._subscribe_channel_on_socket(channel)
|
|
706
|
+
|
|
707
|
+
async def _subscribe_channel_on_socket(self, channel: HostedayChannel) -> None:
|
|
708
|
+
self._subscribed_or_pending.add(channel.name)
|
|
709
|
+
data_obj: dict[str, Any] = {"channel": channel.name}
|
|
710
|
+
if channel.channel_type is not HostedayChannelType.PUBLIC:
|
|
711
|
+
if not self._socket_id:
|
|
712
|
+
self._subscribed_or_pending.discard(channel.name)
|
|
713
|
+
return
|
|
714
|
+
try:
|
|
715
|
+
auth_data = await self._auth_delegate.authorize(
|
|
716
|
+
socket_id=self._socket_id,
|
|
717
|
+
channel_name=channel.name,
|
|
718
|
+
channel_type=channel.channel_type,
|
|
719
|
+
)
|
|
720
|
+
except Exception as exc:
|
|
721
|
+
self._subscribed_or_pending.discard(channel.name)
|
|
722
|
+
self._report_error(f'Channel authorization failed for "{channel.name}": {exc}')
|
|
723
|
+
raise
|
|
724
|
+
data_obj["auth"] = auth_data.auth
|
|
725
|
+
if auth_data.channel_data is not None:
|
|
726
|
+
data_obj["channel_data"] = (
|
|
727
|
+
auth_data.channel_data
|
|
728
|
+
if isinstance(auth_data.channel_data, str)
|
|
729
|
+
else json.dumps(auth_data.channel_data, separators=(",", ":"))
|
|
730
|
+
)
|
|
731
|
+
if auth_data.shared_secret is not None:
|
|
732
|
+
channel.shared_secret = auth_data.shared_secret
|
|
733
|
+
|
|
734
|
+
await self._send_raw(json.dumps({"event": "pusher:subscribe", "data": data_obj}))
|
|
735
|
+
|
|
736
|
+
async def _send_raw(self, payload: str) -> None:
|
|
737
|
+
if self._ws is None:
|
|
738
|
+
return
|
|
739
|
+
self._last_activity = time.monotonic()
|
|
740
|
+
await self._ws.send(payload)
|
|
741
|
+
|
|
742
|
+
def _get_or_create_channel(
|
|
743
|
+
self,
|
|
744
|
+
normalized: str,
|
|
745
|
+
channel_type: HostedayChannelType,
|
|
746
|
+
) -> HostedayChannel:
|
|
747
|
+
existing = self._channels.get(normalized)
|
|
748
|
+
if existing is not None:
|
|
749
|
+
return existing
|
|
750
|
+
if channel_type is HostedayChannelType.PRESENCE:
|
|
751
|
+
ch: HostedayChannel = PresenceChannel(name=normalized, client=self)
|
|
752
|
+
else:
|
|
753
|
+
ch = HostedayChannel(name=normalized, channel_type=channel_type, client=self)
|
|
754
|
+
self._channels[normalized] = ch
|
|
755
|
+
return ch
|
|
756
|
+
|
|
757
|
+
def _track_subscription(self, channel_name: str, sub: ChannelSubscription) -> None:
|
|
758
|
+
self._subscriptions.setdefault(channel_name, []).append(sub)
|
|
759
|
+
|
|
760
|
+
def _report_error(self, message: str) -> None:
|
|
761
|
+
self._last_error = message
|
|
762
|
+
self._error_state.emit(message)
|
|
763
|
+
|
|
764
|
+
@staticmethod
|
|
765
|
+
def _invoke_callback(
|
|
766
|
+
callback: HostedayRealtimeCallback,
|
|
767
|
+
event: HostedayRealtimeEvent,
|
|
768
|
+
) -> None:
|
|
769
|
+
result = callback(event)
|
|
770
|
+
if asyncio.iscoroutine(result):
|
|
771
|
+
asyncio.ensure_future(result)
|
|
772
|
+
|
|
773
|
+
async def _cancel_background_tasks(self) -> None:
|
|
774
|
+
tasks = [
|
|
775
|
+
self._receive_task,
|
|
776
|
+
self._heartbeat_task,
|
|
777
|
+
self._pong_task,
|
|
778
|
+
self._reconnect_task,
|
|
779
|
+
]
|
|
780
|
+
self._receive_task = None
|
|
781
|
+
self._heartbeat_task = None
|
|
782
|
+
self._pong_task = None
|
|
783
|
+
self._reconnect_task = None
|
|
784
|
+
for task in tasks:
|
|
785
|
+
if task is not None and not task.done():
|
|
786
|
+
task.cancel()
|
|
787
|
+
try:
|
|
788
|
+
await task
|
|
789
|
+
except asyncio.CancelledError:
|
|
790
|
+
pass
|