corebase 1.0.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.
Files changed (106) hide show
  1. corebase/__init__.py +108 -0
  2. corebase/_async/__init__.py +1 -0
  3. corebase/_async/auth_client.py +55 -0
  4. corebase/_async/client.py +398 -0
  5. corebase/_sync/__init__.py +1 -0
  6. corebase/_sync/auth_client.py +55 -0
  7. corebase/_sync/client.py +393 -0
  8. corebase/auth/__init__.py +20 -0
  9. corebase/auth/_async/__init__.py +1 -0
  10. corebase/auth/_async/gotrue_admin_api.py +356 -0
  11. corebase/auth/_async/gotrue_admin_mfa_api.py +32 -0
  12. corebase/auth/_async/gotrue_admin_oauth_api.py +93 -0
  13. corebase/auth/_async/gotrue_base_api.py +78 -0
  14. corebase/auth/_async/gotrue_client.py +1404 -0
  15. corebase/auth/_async/gotrue_mfa_api.py +94 -0
  16. corebase/auth/_async/storage.py +31 -0
  17. corebase/auth/_sync/__init__.py +1 -0
  18. corebase/auth/_sync/gotrue_admin_api.py +356 -0
  19. corebase/auth/_sync/gotrue_admin_mfa_api.py +32 -0
  20. corebase/auth/_sync/gotrue_admin_oauth_api.py +93 -0
  21. corebase/auth/_sync/gotrue_base_api.py +78 -0
  22. corebase/auth/_sync/gotrue_client.py +1394 -0
  23. corebase/auth/_sync/gotrue_mfa_api.py +94 -0
  24. corebase/auth/_sync/storage.py +31 -0
  25. corebase/auth/constants.py +15 -0
  26. corebase/auth/errors.py +259 -0
  27. corebase/auth/helpers.py +288 -0
  28. corebase/auth/py.typed +0 -0
  29. corebase/auth/timer.py +53 -0
  30. corebase/auth/types.py +1021 -0
  31. corebase/auth/version.py +1 -0
  32. corebase/client.py +12 -0
  33. corebase/functions/__init__.py +47 -0
  34. corebase/functions/_async/__init__.py +1 -0
  35. corebase/functions/_async/functions_client.py +218 -0
  36. corebase/functions/_sync/__init__.py +1 -0
  37. corebase/functions/_sync/functions_client.py +218 -0
  38. corebase/functions/errors.py +62 -0
  39. corebase/functions/py.typed +0 -0
  40. corebase/functions/utils.py +33 -0
  41. corebase/functions/version.py +1 -0
  42. corebase/lib/__init__.py +3 -0
  43. corebase/lib/client_options.py +189 -0
  44. corebase/migrate/__init__.py +374 -0
  45. corebase/migrate/__main__.py +7 -0
  46. corebase/postgrest/__init__.py +62 -0
  47. corebase/postgrest/_async/__init__.py +1 -0
  48. corebase/postgrest/_async/client.py +206 -0
  49. corebase/postgrest/_async/request_builder.py +503 -0
  50. corebase/postgrest/_sync/__init__.py +1 -0
  51. corebase/postgrest/_sync/client.py +206 -0
  52. corebase/postgrest/_sync/request_builder.py +503 -0
  53. corebase/postgrest/base_client.py +61 -0
  54. corebase/postgrest/base_request_builder.py +787 -0
  55. corebase/postgrest/constants.py +6 -0
  56. corebase/postgrest/exceptions.py +115 -0
  57. corebase/postgrest/py.typed +0 -0
  58. corebase/postgrest/types.py +72 -0
  59. corebase/postgrest/utils.py +91 -0
  60. corebase/postgrest/version.py +1 -0
  61. corebase/py.typed +0 -0
  62. corebase/realtime/__init__.py +17 -0
  63. corebase/realtime/_async/__init__.py +0 -0
  64. corebase/realtime/_async/channel.py +766 -0
  65. corebase/realtime/_async/client.py +498 -0
  66. corebase/realtime/_async/presence.py +185 -0
  67. corebase/realtime/_async/push.py +162 -0
  68. corebase/realtime/_async/timer.py +41 -0
  69. corebase/realtime/_sync/__init__.py +0 -0
  70. corebase/realtime/_sync/channel.py +30 -0
  71. corebase/realtime/_sync/client.py +71 -0
  72. corebase/realtime/_sync/presence.py +10 -0
  73. corebase/realtime/exceptions.py +38 -0
  74. corebase/realtime/message.py +176 -0
  75. corebase/realtime/py.typed +0 -0
  76. corebase/realtime/transformers.py +9 -0
  77. corebase/realtime/types.py +246 -0
  78. corebase/realtime/utils.py +5 -0
  79. corebase/realtime/version.py +1 -0
  80. corebase/storage/__init__.py +56 -0
  81. corebase/storage/_async/__init__.py +1 -0
  82. corebase/storage/_async/analytics.py +82 -0
  83. corebase/storage/_async/bucket.py +142 -0
  84. corebase/storage/_async/client.py +106 -0
  85. corebase/storage/_async/file_api.py +630 -0
  86. corebase/storage/_async/request.py +32 -0
  87. corebase/storage/_async/vectors.py +213 -0
  88. corebase/storage/_sync/__init__.py +1 -0
  89. corebase/storage/_sync/analytics.py +80 -0
  90. corebase/storage/_sync/bucket.py +142 -0
  91. corebase/storage/_sync/client.py +106 -0
  92. corebase/storage/_sync/file_api.py +630 -0
  93. corebase/storage/_sync/request.py +32 -0
  94. corebase/storage/_sync/vectors.py +199 -0
  95. corebase/storage/constants.py +16 -0
  96. corebase/storage/exceptions.py +84 -0
  97. corebase/storage/py.typed +0 -0
  98. corebase/storage/types.py +313 -0
  99. corebase/storage/utils.py +26 -0
  100. corebase/storage/version.py +1 -0
  101. corebase/types.py +8 -0
  102. corebase/version.py +1 -0
  103. corebase-1.0.0.dist-info/METADATA +78 -0
  104. corebase-1.0.0.dist-info/RECORD +106 -0
  105. corebase-1.0.0.dist-info/WHEEL +4 -0
  106. corebase-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,498 @@
1
+ import asyncio
2
+ import logging
3
+ import re
4
+ from collections.abc import Callable
5
+ from functools import wraps
6
+ from typing import Any
7
+ from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
8
+
9
+ import websockets
10
+ from pydantic import ValidationError
11
+ from websockets import connect
12
+ from websockets.asyncio.client import ClientConnection
13
+
14
+ from ..exceptions import NotConnectedError
15
+ from ..message import Message, ServerMessageAdapter
16
+ from ..transformers import http_endpoint_url
17
+ from ..types import (
18
+ DEFAULT_HEARTBEAT_INTERVAL,
19
+ DEFAULT_TIMEOUT,
20
+ PHOENIX_CHANNEL,
21
+ VSN,
22
+ ChannelEvents,
23
+ ChannelStates,
24
+ RealtimeSubscribeStates,
25
+ )
26
+ from ..utils import is_ws_url
27
+ from .channel import AsyncRealtimeChannel, RealtimeChannelOptions
28
+
29
+
30
+ def deprecated(func: Callable) -> Callable:
31
+ @wraps(func)
32
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
33
+ logger.warning(f"Warning: {func.__name__} is deprecated.")
34
+ return func(*args, **kwargs)
35
+
36
+ return wrapper
37
+
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+
42
+ class AsyncRealtimeClient:
43
+ def __init__(
44
+ self,
45
+ url: str,
46
+ token: str | None = None,
47
+ auto_reconnect: bool = True,
48
+ params: dict[str, Any] | None = None,
49
+ hb_interval: int = DEFAULT_HEARTBEAT_INTERVAL,
50
+ max_retries: int = 5,
51
+ initial_backoff: float = 1.0,
52
+ timeout: int = DEFAULT_TIMEOUT,
53
+ ) -> None:
54
+ """
55
+ Initialize a RealtimeClient instance for WebSocket communication.
56
+
57
+ :param url: WebSocket URL of the Realtime server. Starts with `ws://` or `wss://`.
58
+ Also accepts default Supabase URL: `http://` or `https://`.
59
+ :param token: Authentication token for the WebSocket connection.
60
+ :param auto_reconnect: If True, automatically attempt to reconnect on disconnection. Defaults to True.
61
+ :param params: Optional parameters for the connection. Defaults to None.
62
+ :param hb_interval: Interval (in seconds) for sending heartbeat messages to keep the connection alive. Defaults to 25.
63
+ :param max_retries: Maximum number of reconnection attempts. Defaults to 5.
64
+ :param initial_backoff: Initial backoff time (in seconds) for reconnection attempts. Defaults to 1.0.
65
+ :param timeout: Connection timeout in seconds. Defaults to DEFAULT_TIMEOUT.
66
+ """
67
+ if not is_ws_url(url):
68
+ raise ValueError("url must be a valid WebSocket URL or HTTP URL string")
69
+
70
+ self.url = f"{re.sub(r'https://', 'wss://', re.sub(r'http://', 'ws://', url, flags=re.IGNORECASE), flags=re.IGNORECASE)}/websocket"
71
+ if token:
72
+ self.url += "?" + urlencode({"apikey": token})
73
+ self.http_endpoint = http_endpoint_url(url)
74
+ self.params = params or {}
75
+ self.apikey = token
76
+ self.access_token = token
77
+ self.send_buffer: list[Callable] = []
78
+ self.hb_interval = hb_interval
79
+ self._ws_connection: ClientConnection | None = None
80
+ self._connect_lock = asyncio.Lock()
81
+ self._connect_lock_loop: asyncio.AbstractEventLoop | None = None
82
+ self._close_generation = 0
83
+ self.ref = 0
84
+ self.auto_reconnect = auto_reconnect
85
+ self.channels: dict[str, AsyncRealtimeChannel] = {}
86
+ self.max_retries = max_retries
87
+ self.initial_backoff = initial_backoff
88
+ self.timeout = timeout
89
+ self._listen_task: asyncio.Task | None = None
90
+ self._heartbeat_task: asyncio.Task | None = None
91
+ self._channels_to_rejoin: list[AsyncRealtimeChannel] = []
92
+
93
+ @property
94
+ def is_connected(self) -> bool:
95
+ return self._ws_connection is not None
96
+
97
+ async def _listen(self) -> None:
98
+ """
99
+ An infinite loop that keeps listening.
100
+ :return: None
101
+ """
102
+
103
+ ws_connection = self._ws_connection
104
+ if not ws_connection:
105
+ raise NotConnectedError("_listen")
106
+
107
+ try:
108
+ async for msg in ws_connection:
109
+ logger.debug(f"receive: {msg!r}")
110
+
111
+ try:
112
+ message = ServerMessageAdapter.validate_json(msg)
113
+ except ValidationError as e:
114
+ logger.error(f"Unrecognized message format {msg!r}\n{e}")
115
+ continue
116
+ logger.debug(f"parsed message as {message!r}")
117
+ if channel := self.channels.get(message.topic):
118
+ channel._handle_message(message)
119
+ except websockets.exceptions.ConnectionClosedError as e:
120
+ await self._on_connect_error(e)
121
+ else:
122
+ # websockets ends the iteration without raising when the server closes
123
+ # with 1000 or 1001. close() clears _ws_connection before closing, so a
124
+ # connection that is still current here was closed by the server.
125
+ if self._ws_connection is not ws_connection:
126
+ return
127
+ logger.debug(
128
+ f"WebSocket connection closed by server with code: {ws_connection.close_code}"
129
+ )
130
+ if self.auto_reconnect:
131
+ await self._reconnect(ws_connection.protocol.close_exc)
132
+ else:
133
+ self._ws_connection = None
134
+ self._set_channels_errored(ws_connection.protocol.close_exc)
135
+
136
+ def _set_channels_errored(self, error: Exception) -> None:
137
+ for channel in self.channels.values():
138
+ if channel.is_joined or channel.is_joining:
139
+ channel.state = ChannelStates.ERRORED
140
+ if channel not in self._channels_to_rejoin:
141
+ self._channels_to_rejoin.append(channel)
142
+ try:
143
+ channel._notify_subscribe_state(
144
+ RealtimeSubscribeStates.CHANNEL_ERROR, error
145
+ )
146
+ except Exception:
147
+ logger.exception(
148
+ f"subscribe callback failed for channel {channel.topic}"
149
+ )
150
+
151
+ async def _reconnect(self, error: Exception) -> None:
152
+ self._ws_connection = None
153
+
154
+ self._set_channels_errored(error)
155
+
156
+ await self.connect()
157
+
158
+ async def connect(self) -> None:
159
+ """
160
+ Establishes a WebSocket connection with exponential backoff retry mechanism.
161
+
162
+ This method attempts to connect to the WebSocket server. If the connection fails,
163
+ it will retry with an exponential backoff strategy up to a maximum number of retries.
164
+
165
+ Returns:
166
+ None
167
+
168
+ Raises:
169
+ Exception: If unable to establish a connection after max_retries attempts.
170
+
171
+ Note:
172
+ - The initial backoff time and maximum retries are set during RealtimeClient initialization.
173
+ - The backoff time doubles after each failed attempt, up to a maximum of 60 seconds.
174
+ """
175
+
176
+ if self.is_connected:
177
+ logger.debug("WebSocket connection already established")
178
+ return
179
+
180
+ loop = asyncio.get_running_loop()
181
+ if self._connect_lock_loop is not loop:
182
+ self._connect_lock = asyncio.Lock()
183
+ self._connect_lock_loop = loop
184
+
185
+ generation = self._close_generation
186
+ retries = 0
187
+ endpoint_url = self.endpoint_url()
188
+ parsed_url = urlparse(endpoint_url)
189
+ redacted_query = urlencode(
190
+ [
191
+ (k, "REDACTED" if k == "apikey" else v)
192
+ for k, v in parse_qsl(parsed_url.query, keep_blank_values=True)
193
+ ]
194
+ )
195
+ logger.debug(
196
+ f"Attempting to connect to WebSocket at {urlunparse(parsed_url._replace(query=redacted_query))}"
197
+ )
198
+
199
+ while retries < self.max_retries:
200
+ try:
201
+ async with self._connect_lock:
202
+ if self.is_connected or generation != self._close_generation:
203
+ return
204
+ ws = await connect(endpoint_url, open_timeout=self.timeout)
205
+ if generation != self._close_generation:
206
+ logger.debug("Client closed during handshake, dropping socket")
207
+ await ws.close()
208
+ return
209
+ self._ws_connection = ws
210
+ logger.debug("WebSocket connection established successfully")
211
+ return await self._on_connect()
212
+ except Exception as e:
213
+ retries += 1
214
+ logger.error(f"Connection attempt failed: {str(e)}")
215
+
216
+ if retries >= self.max_retries or not self.auto_reconnect:
217
+ logger.error(
218
+ f"Connection failed permanently after {retries} attempts. Error: {str(e)}"
219
+ )
220
+ raise
221
+ else:
222
+ wait_time = min(self.initial_backoff * (2 ** (retries - 1)), 60)
223
+ logger.debug(
224
+ f"Retry {retries}/{self.max_retries}: Next attempt in {wait_time:.2f}s (initial_backoff={self.initial_backoff}s)"
225
+ )
226
+ await asyncio.sleep(wait_time)
227
+
228
+ raise Exception(
229
+ f"Failed to establish WebSocket connection after {self.max_retries} attempts"
230
+ )
231
+
232
+ @deprecated
233
+ async def listen(self) -> None:
234
+ pass
235
+
236
+ async def _on_connect(self) -> None:
237
+ current_task = asyncio.current_task()
238
+
239
+ if self._listen_task:
240
+ if self._listen_task is not current_task:
241
+ self._listen_task.cancel()
242
+ self._listen_task = None
243
+
244
+ if self._heartbeat_task:
245
+ if self._heartbeat_task is not current_task:
246
+ self._heartbeat_task.cancel()
247
+ self._heartbeat_task = None
248
+
249
+ self._listen_task = asyncio.create_task(self._listen())
250
+ self._heartbeat_task = asyncio.create_task(self._heartbeat())
251
+ await self._flush_send_buffer()
252
+ await self._rejoin_errored_channels()
253
+
254
+ async def _rejoin_errored_channels(self) -> None:
255
+ to_rejoin = self._channels_to_rejoin
256
+ self._channels_to_rejoin = []
257
+ for channel in list(self.channels.values()):
258
+ channel.rejoin_timer.reset()
259
+ if channel.is_errored and channel not in to_rejoin:
260
+ to_rejoin.append(channel)
261
+ to_rejoin = [
262
+ channel
263
+ for channel in to_rejoin
264
+ if self.channels.get(channel.topic) is channel and not channel.is_leaving
265
+ ]
266
+ if to_rejoin:
267
+ await asyncio.gather(*(channel._rejoin() for channel in to_rejoin))
268
+
269
+ async def _on_connect_error(
270
+ self, e: websockets.exceptions.ConnectionClosedError
271
+ ) -> None:
272
+ logger.error(
273
+ f"WebSocket connection closed with code: {e.code}, reason: {e.reason}"
274
+ )
275
+
276
+ if self.auto_reconnect:
277
+ logger.debug("Initiating auto-reconnect sequence...")
278
+ await self._reconnect(e)
279
+ else:
280
+ logger.error("Auto-reconnect disabled, terminating connection")
281
+ self._ws_connection = None
282
+ self._set_channels_errored(e)
283
+
284
+ async def _flush_send_buffer(self) -> None:
285
+ if self.is_connected and len(self.send_buffer) > 0:
286
+ for callback in self.send_buffer:
287
+ await callback()
288
+ self.send_buffer = []
289
+
290
+ async def close(self) -> None:
291
+ """
292
+ Close the WebSocket connection.
293
+
294
+ Returns:
295
+ None
296
+
297
+ Raises:
298
+ NotConnectedError: If the connection is not established when this method is called.
299
+ """
300
+
301
+ self._close_generation += 1
302
+ ws_connection = self._ws_connection
303
+ self._ws_connection = None
304
+ for channel in self.channels.values():
305
+ channel._release_subscribe_waiter()
306
+
307
+ if ws_connection:
308
+ await ws_connection.close()
309
+
310
+ if self._listen_task:
311
+ self._listen_task.cancel()
312
+ self._listen_task = None
313
+
314
+ if self._heartbeat_task:
315
+ self._heartbeat_task.cancel()
316
+ self._heartbeat_task = None
317
+
318
+ async def _heartbeat(self) -> None:
319
+ if not self._ws_connection:
320
+ raise NotConnectedError("_heartbeat")
321
+
322
+ while self.is_connected:
323
+ try:
324
+ data = Message(
325
+ topic=PHOENIX_CHANNEL,
326
+ event=ChannelEvents.heartbeat,
327
+ payload={},
328
+ ref=None,
329
+ )
330
+ await self.send(data)
331
+ await asyncio.sleep(max(self.hb_interval, 15))
332
+
333
+ except websockets.exceptions.ConnectionClosedError as e:
334
+ await self._on_connect_error(e)
335
+ return
336
+ except websockets.exceptions.ConnectionClosedOK:
337
+ return
338
+
339
+ def channel(
340
+ self, topic: str, params: RealtimeChannelOptions | None = None
341
+ ) -> AsyncRealtimeChannel:
342
+ """
343
+ Initialize a channel and create a two-way association with the socket.
344
+
345
+ If a channel for this topic already exists and is not being left, that
346
+ channel is returned instead of a new one. Messages are routed to one
347
+ channel per topic, so replacing it would silently stop delivering
348
+ events to callbacks registered on the existing channel.
349
+
350
+ :param topic: The topic to subscribe to
351
+ :param params: Optional channel parameters
352
+ :return: AsyncRealtimeChannel instance
353
+ """
354
+ topic = f"realtime:{topic}"
355
+ existing = self.channels.get(topic)
356
+ if existing and not existing.is_leaving:
357
+ return existing
358
+ chan = AsyncRealtimeChannel(self, topic, params)
359
+ self.channels[topic] = chan
360
+
361
+ return chan
362
+
363
+ def get_channels(self) -> list[AsyncRealtimeChannel]:
364
+ return list(self.channels.values())
365
+
366
+ def _remove_channel(self, channel: AsyncRealtimeChannel) -> None:
367
+ if self.channels.get(channel.topic) is channel:
368
+ del self.channels[channel.topic]
369
+
370
+ async def remove_channel(self, channel: AsyncRealtimeChannel) -> None:
371
+ """
372
+ Unsubscribes and removes a channel from the socket
373
+ :param channel: Channel to remove
374
+ :return: None
375
+ """
376
+ if self.channels.get(channel.topic) is channel:
377
+ await channel.unsubscribe()
378
+ self._remove_channel(channel)
379
+
380
+ if len(self.channels) == 0:
381
+ await self.close()
382
+
383
+ async def remove_all_channels(self) -> None:
384
+ """
385
+ Unsubscribes and removes all channels from the socket
386
+ :return: None
387
+ """
388
+ first_error: Exception | None = None
389
+ channels = list(self.channels.values())
390
+ try:
391
+ for channel in channels:
392
+ try:
393
+ await channel.unsubscribe()
394
+ except Exception as error:
395
+ if first_error is None:
396
+ first_error = error
397
+ finally:
398
+ self._remove_channel(channel)
399
+ finally:
400
+ for channel in channels:
401
+ if self.channels.get(channel.topic) is channel:
402
+ channel.rejoin_timer.reset()
403
+ channel.join_push.destroy()
404
+ channel.state = ChannelStates.CLOSED
405
+ channel._release_subscribe_waiter()
406
+ self._remove_channel(channel)
407
+ await self.close()
408
+
409
+ if first_error is not None:
410
+ raise first_error
411
+
412
+ async def set_auth(self, token: str | None) -> None:
413
+ """
414
+ Set the authentication token for the connection and update all joined channels.
415
+
416
+ This method updates the access token for the current connection and sends the new token
417
+ to all joined channels. This is useful for refreshing authentication or changing users.
418
+
419
+ Args:
420
+ token (Optional[str]): The new authentication token. Can be None to remove authentication.
421
+
422
+ Returns:
423
+ None
424
+ """
425
+ self.access_token = token
426
+
427
+ for _, channel in self.channels.items():
428
+ # Rejoins resend the stored join payload, so keep its token current.
429
+ channel.join_push.update_payload({"access_token": token})
430
+ if channel._joined_once and channel.is_joined:
431
+ await channel.push(ChannelEvents.access_token, {"access_token": token})
432
+
433
+ def _make_ref(self) -> str:
434
+ self.ref += 1
435
+ return f"{self.ref}"
436
+
437
+ async def send(self, message: Message | dict[str, Any]) -> None:
438
+ """
439
+ Send a message through the WebSocket connection.
440
+
441
+ This method serializes the given message dictionary to JSON,
442
+ and sends it through the WebSocket connection. If the connection
443
+ is not currently established, the message will be buffered and sent
444
+ once the connection is re-established.
445
+
446
+ Args:
447
+ message (Dict[str, Any]): The message to be sent, as a dictionary.
448
+
449
+ Returns:
450
+ None
451
+ """
452
+ if isinstance(message, Message):
453
+ msg = message
454
+ else:
455
+ logger.warning(
456
+ "Warning: calling AsyncRealtimeClient.send with a dictionary is deprecated. Please call it with a Message object instead. This will be a hard error in the future."
457
+ )
458
+ msg = Message(**message)
459
+ message_str = msg.model_dump_json()
460
+ if logger.isEnabledFor(logging.DEBUG):
461
+ redacted = {
462
+ k: "<redacted>" if k == "access_token" else v
463
+ for k, v in msg.payload.items()
464
+ }
465
+ logger.debug(
466
+ f"send: {msg.model_copy(update={'payload': redacted}).model_dump_json()}"
467
+ )
468
+
469
+ async def send_message() -> None:
470
+ if not self._ws_connection:
471
+ raise NotConnectedError("_send")
472
+
473
+ try:
474
+ await self._ws_connection.send(message_str)
475
+ except websockets.exceptions.ConnectionClosedError as e:
476
+ await self._on_connect_error(e)
477
+ except websockets.exceptions.ConnectionClosedOK:
478
+ pass
479
+
480
+ if self.is_connected:
481
+ await send_message()
482
+ else:
483
+ self.send_buffer.append(send_message)
484
+
485
+ def endpoint_url(self) -> str:
486
+ parsed_url = urlparse(self.url)
487
+ current_params = dict(parse_qsl(parsed_url.query, keep_blank_values=True))
488
+ query = urlencode({**self.params, **current_params, "vsn": VSN}, doseq=True)
489
+ return urlunparse(
490
+ (
491
+ parsed_url.scheme,
492
+ parsed_url.netloc,
493
+ parsed_url.path,
494
+ parsed_url.params,
495
+ query,
496
+ parsed_url.fragment,
497
+ )
498
+ )
@@ -0,0 +1,185 @@
1
+ """
2
+ Defines the RealtimePresence class and its dependencies.
3
+ """
4
+
5
+ import logging
6
+ from collections.abc import Callable
7
+
8
+ from ..types import (
9
+ Presence,
10
+ PresenceOnJoinCallback,
11
+ PresenceOnLeaveCallback,
12
+ RawPresenceDiff,
13
+ RawPresenceState,
14
+ RealtimePresenceState,
15
+ )
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class AsyncRealtimePresence:
21
+ @property
22
+ def _has_callback_attached(self) -> bool:
23
+ return (
24
+ self.on_join_callback is not None
25
+ or self.on_leave_callback is not None
26
+ or self.on_sync_callback is not None
27
+ )
28
+
29
+ def __init__(self) -> None:
30
+ self.state: RealtimePresenceState = {}
31
+ self.on_join_callback: PresenceOnJoinCallback | None = None
32
+ self.on_leave_callback: PresenceOnLeaveCallback | None = None
33
+ self.on_sync_callback: Callable[[], None] | None = None
34
+
35
+ def on_join(self, callback: PresenceOnJoinCallback) -> None:
36
+ self.on_join_callback = callback
37
+
38
+ def on_leave(self, callback: PresenceOnLeaveCallback) -> None:
39
+ self.on_leave_callback = callback
40
+
41
+ def on_sync(self, callback: Callable[[], None]) -> None:
42
+ self.on_sync_callback = callback
43
+
44
+ def _on_state_event(self, payload: RawPresenceState) -> None:
45
+ state = AsyncRealtimePresence._transform_state(payload)
46
+ self.state = self._sync_state(state)
47
+
48
+ if self.on_sync_callback:
49
+ self.on_sync_callback()
50
+
51
+ def _on_diff_event(self, payload: RawPresenceDiff) -> None:
52
+ joins = AsyncRealtimePresence._transform_state(payload["joins"])
53
+ leaves = AsyncRealtimePresence._transform_state(payload["leaves"])
54
+ self.state = self._sync_diff(joins, leaves)
55
+ if self.on_sync_callback:
56
+ self.on_sync_callback()
57
+
58
+ def _sync_state(
59
+ self,
60
+ new_state: RealtimePresenceState,
61
+ ) -> RealtimePresenceState:
62
+ joins = {}
63
+ leaves = {k: v for k, v in self.state.items() if k not in new_state}
64
+
65
+ for key, value in new_state.items():
66
+ current_presences = self.state.get(key, [])
67
+
68
+ if len(current_presences) > 0:
69
+ new_presence_refs = {presence["presence_ref"] for presence in value}
70
+ cur_presence_refs = {
71
+ presence["presence_ref"] for presence in current_presences
72
+ }
73
+
74
+ joined_presences = [
75
+ p for p in value if p["presence_ref"] not in cur_presence_refs
76
+ ]
77
+ left_presences = [
78
+ p
79
+ for p in current_presences
80
+ if p["presence_ref"] not in new_presence_refs
81
+ ]
82
+
83
+ if joined_presences:
84
+ joins[key] = joined_presences
85
+ if left_presences:
86
+ leaves[key] = left_presences
87
+ else:
88
+ joins[key] = value
89
+
90
+ return self._sync_diff(joins, leaves)
91
+
92
+ def _sync_diff(
93
+ self, joins: RealtimePresenceState, leaves: RealtimePresenceState
94
+ ) -> RealtimePresenceState:
95
+ for key, new_presences in joins.items():
96
+ current_presences = self.state.get(key, [])
97
+ self.state[key] = new_presences
98
+
99
+ if len(current_presences) > 0:
100
+ joined_presence_refs = {
101
+ presence.get("presence_ref") for presence in new_presences
102
+ }
103
+ cur_presences = list(
104
+ presence
105
+ for presence in current_presences
106
+ if presence.get("presence_ref") not in joined_presence_refs
107
+ )
108
+ self.state[key] = cur_presences + self.state[key]
109
+
110
+ if self.on_join_callback:
111
+ self.on_join_callback(key, current_presences, new_presences)
112
+
113
+ for key, left_presences in leaves.items():
114
+ current_presences = self.state.get(key, [])
115
+
116
+ if len(current_presences) == 0:
117
+ continue
118
+
119
+ presence_refs_to_remove = {
120
+ presence.get("presence_ref") for presence in left_presences
121
+ }
122
+ current_presences = [
123
+ presence
124
+ for presence in current_presences
125
+ if presence.get("presence_ref") not in presence_refs_to_remove
126
+ ]
127
+ self.state[key] = current_presences
128
+
129
+ if self.on_leave_callback:
130
+ self.on_leave_callback(key, current_presences, left_presences)
131
+
132
+ if len(current_presences) == 0:
133
+ del self.state[key]
134
+
135
+ return self.state
136
+
137
+ @staticmethod
138
+ def _transform_state(
139
+ state: RawPresenceState,
140
+ ) -> RealtimePresenceState:
141
+ """
142
+ Transform the raw presence state into a standardized RealtimePresenceState format.
143
+
144
+ This method processes the input state, which can be either a RawPresenceState or
145
+ an already transformed RealtimePresenceState. It handles the conversion of the
146
+ Phoenix channel's presence format to our internal representation.
147
+
148
+ Args:
149
+ state (Union[RawPresenceState, RealtimePresenceState[T]]): The presence state to transform.
150
+
151
+ Returns:
152
+ RealtimePresenceState[T]: The transformed presence state.
153
+
154
+ Example:
155
+ Input (RawPresenceState):
156
+ {
157
+ "user1": {
158
+ "metas": [
159
+ {"phx_ref": "ABC123", "user_id": "user1", "status": "online"},
160
+ {"phx_ref": "DEF456", "phx_ref_prev": "ABC123", "user_id": "user1", "status": "away"}
161
+ ]
162
+ },
163
+ "user2": [{"user_id": "user2", "status": "offline"}]
164
+ }
165
+
166
+ Output (RealtimePresenceState):
167
+ {
168
+ "user1": [
169
+ {"presence_ref": "ABC123", "user_id": "user1", "status": "online"},
170
+ {"presence_ref": "DEF456", "user_id": "user1", "status": "away"}
171
+ ],
172
+ "user2": [{"user_id": "user2", "status": "offline"}]
173
+ }
174
+ """
175
+ new_state: RealtimePresenceState = {}
176
+ for key, presences in state.items():
177
+ new_state[key] = []
178
+
179
+ for presence in presences["metas"]:
180
+ if "phx_ref_prev" in presence:
181
+ del presence["phx_ref_prev"]
182
+ new_presence: Presence = {"presence_ref": presence.pop("phx_ref")}
183
+ new_presence.update(presence)
184
+ new_state[key].append(new_presence)
185
+ return new_state