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.
- corebase/__init__.py +108 -0
- corebase/_async/__init__.py +1 -0
- corebase/_async/auth_client.py +55 -0
- corebase/_async/client.py +398 -0
- corebase/_sync/__init__.py +1 -0
- corebase/_sync/auth_client.py +55 -0
- corebase/_sync/client.py +393 -0
- corebase/auth/__init__.py +20 -0
- corebase/auth/_async/__init__.py +1 -0
- corebase/auth/_async/gotrue_admin_api.py +356 -0
- corebase/auth/_async/gotrue_admin_mfa_api.py +32 -0
- corebase/auth/_async/gotrue_admin_oauth_api.py +93 -0
- corebase/auth/_async/gotrue_base_api.py +78 -0
- corebase/auth/_async/gotrue_client.py +1404 -0
- corebase/auth/_async/gotrue_mfa_api.py +94 -0
- corebase/auth/_async/storage.py +31 -0
- corebase/auth/_sync/__init__.py +1 -0
- corebase/auth/_sync/gotrue_admin_api.py +356 -0
- corebase/auth/_sync/gotrue_admin_mfa_api.py +32 -0
- corebase/auth/_sync/gotrue_admin_oauth_api.py +93 -0
- corebase/auth/_sync/gotrue_base_api.py +78 -0
- corebase/auth/_sync/gotrue_client.py +1394 -0
- corebase/auth/_sync/gotrue_mfa_api.py +94 -0
- corebase/auth/_sync/storage.py +31 -0
- corebase/auth/constants.py +15 -0
- corebase/auth/errors.py +259 -0
- corebase/auth/helpers.py +288 -0
- corebase/auth/py.typed +0 -0
- corebase/auth/timer.py +53 -0
- corebase/auth/types.py +1021 -0
- corebase/auth/version.py +1 -0
- corebase/client.py +12 -0
- corebase/functions/__init__.py +47 -0
- corebase/functions/_async/__init__.py +1 -0
- corebase/functions/_async/functions_client.py +218 -0
- corebase/functions/_sync/__init__.py +1 -0
- corebase/functions/_sync/functions_client.py +218 -0
- corebase/functions/errors.py +62 -0
- corebase/functions/py.typed +0 -0
- corebase/functions/utils.py +33 -0
- corebase/functions/version.py +1 -0
- corebase/lib/__init__.py +3 -0
- corebase/lib/client_options.py +189 -0
- corebase/migrate/__init__.py +374 -0
- corebase/migrate/__main__.py +7 -0
- corebase/postgrest/__init__.py +62 -0
- corebase/postgrest/_async/__init__.py +1 -0
- corebase/postgrest/_async/client.py +206 -0
- corebase/postgrest/_async/request_builder.py +503 -0
- corebase/postgrest/_sync/__init__.py +1 -0
- corebase/postgrest/_sync/client.py +206 -0
- corebase/postgrest/_sync/request_builder.py +503 -0
- corebase/postgrest/base_client.py +61 -0
- corebase/postgrest/base_request_builder.py +787 -0
- corebase/postgrest/constants.py +6 -0
- corebase/postgrest/exceptions.py +115 -0
- corebase/postgrest/py.typed +0 -0
- corebase/postgrest/types.py +72 -0
- corebase/postgrest/utils.py +91 -0
- corebase/postgrest/version.py +1 -0
- corebase/py.typed +0 -0
- corebase/realtime/__init__.py +17 -0
- corebase/realtime/_async/__init__.py +0 -0
- corebase/realtime/_async/channel.py +766 -0
- corebase/realtime/_async/client.py +498 -0
- corebase/realtime/_async/presence.py +185 -0
- corebase/realtime/_async/push.py +162 -0
- corebase/realtime/_async/timer.py +41 -0
- corebase/realtime/_sync/__init__.py +0 -0
- corebase/realtime/_sync/channel.py +30 -0
- corebase/realtime/_sync/client.py +71 -0
- corebase/realtime/_sync/presence.py +10 -0
- corebase/realtime/exceptions.py +38 -0
- corebase/realtime/message.py +176 -0
- corebase/realtime/py.typed +0 -0
- corebase/realtime/transformers.py +9 -0
- corebase/realtime/types.py +246 -0
- corebase/realtime/utils.py +5 -0
- corebase/realtime/version.py +1 -0
- corebase/storage/__init__.py +56 -0
- corebase/storage/_async/__init__.py +1 -0
- corebase/storage/_async/analytics.py +82 -0
- corebase/storage/_async/bucket.py +142 -0
- corebase/storage/_async/client.py +106 -0
- corebase/storage/_async/file_api.py +630 -0
- corebase/storage/_async/request.py +32 -0
- corebase/storage/_async/vectors.py +213 -0
- corebase/storage/_sync/__init__.py +1 -0
- corebase/storage/_sync/analytics.py +80 -0
- corebase/storage/_sync/bucket.py +142 -0
- corebase/storage/_sync/client.py +106 -0
- corebase/storage/_sync/file_api.py +630 -0
- corebase/storage/_sync/request.py +32 -0
- corebase/storage/_sync/vectors.py +199 -0
- corebase/storage/constants.py +16 -0
- corebase/storage/exceptions.py +84 -0
- corebase/storage/py.typed +0 -0
- corebase/storage/types.py +313 -0
- corebase/storage/utils.py +26 -0
- corebase/storage/version.py +1 -0
- corebase/types.py +8 -0
- corebase/version.py +1 -0
- corebase-1.0.0.dist-info/METADATA +78 -0
- corebase-1.0.0.dist-info/RECORD +106 -0
- corebase-1.0.0.dist-info/WHEEL +4 -0
- corebase-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,766 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import warnings
|
|
7
|
+
from collections.abc import Callable, Coroutine
|
|
8
|
+
from typing import TYPE_CHECKING, Any, assert_never
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from corebase.realtime.types import (
|
|
14
|
+
BroadcastCallback,
|
|
15
|
+
BroadcastPayload,
|
|
16
|
+
ChannelEvents,
|
|
17
|
+
ChannelStates,
|
|
18
|
+
PostgresChangesCallback,
|
|
19
|
+
PresenceOnJoinCallback,
|
|
20
|
+
PresenceOnLeaveCallback,
|
|
21
|
+
RealtimeAcknowledgementStatus,
|
|
22
|
+
RealtimeChannelConfig,
|
|
23
|
+
RealtimeChannelOptions,
|
|
24
|
+
RealtimeChannelPresenceConfig,
|
|
25
|
+
RealtimePostgresChangesListenEvent,
|
|
26
|
+
RealtimePresenceState,
|
|
27
|
+
RealtimeSubscribeStates,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
from ..exceptions import RealtimeHTTPError
|
|
31
|
+
from ..message import (
|
|
32
|
+
BroadcastMessage,
|
|
33
|
+
ChannelCloseMessage,
|
|
34
|
+
ChannelErrorMessage,
|
|
35
|
+
HeartbeatMessage,
|
|
36
|
+
PostgresChangesMessage,
|
|
37
|
+
PostgresChangesPayload,
|
|
38
|
+
PostgresRowChange,
|
|
39
|
+
PresenceDiffMessage,
|
|
40
|
+
PresenceStateMessage,
|
|
41
|
+
ReplyMessage,
|
|
42
|
+
ReplyPostgresChanges,
|
|
43
|
+
ServerMessage,
|
|
44
|
+
SuccessSystemPayload,
|
|
45
|
+
SystemMessage,
|
|
46
|
+
)
|
|
47
|
+
from ..transformers import http_endpoint_url
|
|
48
|
+
from .presence import (
|
|
49
|
+
AsyncRealtimePresence,
|
|
50
|
+
)
|
|
51
|
+
from .push import AsyncPush
|
|
52
|
+
from .timer import AsyncTimer
|
|
53
|
+
|
|
54
|
+
if TYPE_CHECKING:
|
|
55
|
+
from .client import AsyncRealtimeClient
|
|
56
|
+
|
|
57
|
+
logger = logging.getLogger(__name__)
|
|
58
|
+
|
|
59
|
+
REJOIN_DELAYS_SECONDS = (1, 2, 5, 10)
|
|
60
|
+
RATE_LIMITED_REJOIN_DELAY_SECONDS = 30
|
|
61
|
+
RATE_LIMIT_ERROR_CODES = (
|
|
62
|
+
"ChannelRateLimitReached",
|
|
63
|
+
"ConnectionRateLimitReached",
|
|
64
|
+
"ClientJoinRateLimitReached",
|
|
65
|
+
"DatabaseConnectionRateLimitReached",
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _rejoin_delay(attempt: int) -> float:
|
|
70
|
+
return REJOIN_DELAYS_SECONDS[min(attempt, len(REJOIN_DELAYS_SECONDS)) - 1]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _is_rate_limit_error(payload: dict[str, Any]) -> bool:
|
|
74
|
+
reason = payload.get("reason")
|
|
75
|
+
return isinstance(reason, str) and reason.startswith(RATE_LIMIT_ERROR_CODES)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class AsyncRealtimeChannel:
|
|
79
|
+
"""
|
|
80
|
+
Channel is an abstraction for a topic subscription on an existing socket connection.
|
|
81
|
+
Each Channel has its own topic and a list of event-callbacks that respond to messages.
|
|
82
|
+
Should only be instantiated through `AsyncRealtimeClient.channel(topic)`.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
socket: AsyncRealtimeClient,
|
|
88
|
+
topic: str,
|
|
89
|
+
params: RealtimeChannelOptions | None = None,
|
|
90
|
+
) -> None:
|
|
91
|
+
"""
|
|
92
|
+
Initialize the Channel object.
|
|
93
|
+
|
|
94
|
+
:param socket: RealtimeClient object
|
|
95
|
+
:param topic: Topic that it subscribes to on the realtime server
|
|
96
|
+
:param params: Optional parameters for connection.
|
|
97
|
+
"""
|
|
98
|
+
self.socket = socket
|
|
99
|
+
self.params: RealtimeChannelOptions = (
|
|
100
|
+
params
|
|
101
|
+
if params
|
|
102
|
+
else {
|
|
103
|
+
"config": {
|
|
104
|
+
"broadcast": {"ack": False, "self": False},
|
|
105
|
+
"presence": {"key": "", "enabled": False},
|
|
106
|
+
"private": False,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
)
|
|
110
|
+
self.topic = topic
|
|
111
|
+
self._joined_once = False
|
|
112
|
+
self._resubscribing = False
|
|
113
|
+
self._presence_enabled = False
|
|
114
|
+
self.presence: AsyncRealtimePresence = AsyncRealtimePresence()
|
|
115
|
+
self.state = ChannelStates.CLOSED
|
|
116
|
+
self._push_buffer: list[AsyncPush] = []
|
|
117
|
+
self._background_tasks: set[asyncio.Task[None]] = set()
|
|
118
|
+
self.timeout = self.socket.timeout
|
|
119
|
+
|
|
120
|
+
self.join_push: AsyncPush = self._create_join_push()
|
|
121
|
+
self.messages_waiting_for_ack: dict[str, AsyncPush] = {}
|
|
122
|
+
self.broadcast_callbacks: list[BroadcastCallback] = []
|
|
123
|
+
self.system_callbacks: list[Callable[[SuccessSystemPayload], None]] = []
|
|
124
|
+
self.postgres_changes_callbacks: list[PostgresChangesCallback] = []
|
|
125
|
+
self.subscribe_callback: (
|
|
126
|
+
Callable[[RealtimeSubscribeStates, Exception | None], None] | None
|
|
127
|
+
) = None
|
|
128
|
+
self._subscribe_waiter: asyncio.Future[None] | None = None
|
|
129
|
+
|
|
130
|
+
self.rejoin_timer = AsyncTimer(self._rejoin_if_connected, _rejoin_delay)
|
|
131
|
+
|
|
132
|
+
self.broadcast_endpoint_url = self._broadcast_endpoint_url()
|
|
133
|
+
|
|
134
|
+
def _create_join_push(self) -> AsyncPush:
|
|
135
|
+
join_push = AsyncPush(self, ChannelEvents.join, self.params, self.timeout)
|
|
136
|
+
|
|
137
|
+
def on_join_push_ok(payload: ReplyPostgresChanges) -> None:
|
|
138
|
+
self.state = ChannelStates.JOINED
|
|
139
|
+
self.rejoin_timer.reset()
|
|
140
|
+
for push in self._push_buffer:
|
|
141
|
+
self._run_in_background(push.send())
|
|
142
|
+
self._push_buffer = []
|
|
143
|
+
|
|
144
|
+
def on_join_push_timeout() -> None:
|
|
145
|
+
if not self.is_joining:
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
logger.error(f"join push timeout for channel {self.topic}")
|
|
149
|
+
self.state = ChannelStates.ERRORED
|
|
150
|
+
if self.socket.is_connected:
|
|
151
|
+
self.rejoin_timer.schedule_timeout()
|
|
152
|
+
|
|
153
|
+
def on_join_push_error(payload: dict[str, Any]) -> None:
|
|
154
|
+
if not self.is_joining:
|
|
155
|
+
return
|
|
156
|
+
|
|
157
|
+
logger.error(f"join push error for channel {self.topic}: {payload}")
|
|
158
|
+
self.state = ChannelStates.ERRORED
|
|
159
|
+
if self.socket.is_connected:
|
|
160
|
+
self.rejoin_timer.schedule_timeout(
|
|
161
|
+
RATE_LIMITED_REJOIN_DELAY_SECONDS
|
|
162
|
+
if _is_rate_limit_error(payload)
|
|
163
|
+
else None
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
join_push.receive(RealtimeAcknowledgementStatus.Ok, on_join_push_ok).receive(
|
|
167
|
+
RealtimeAcknowledgementStatus.Error, on_join_push_error
|
|
168
|
+
).receive(RealtimeAcknowledgementStatus.Timeout, on_join_push_timeout)
|
|
169
|
+
return join_push
|
|
170
|
+
|
|
171
|
+
def on_close(self) -> None:
|
|
172
|
+
logger.info(f"channel {self.topic} closed")
|
|
173
|
+
self.rejoin_timer.reset()
|
|
174
|
+
self.state = ChannelStates.CLOSED
|
|
175
|
+
self.socket._remove_channel(self)
|
|
176
|
+
self._notify_subscribe_state(RealtimeSubscribeStates.CLOSED, None)
|
|
177
|
+
|
|
178
|
+
def on_error(self, payload: dict[str, Any]) -> None:
|
|
179
|
+
if self.is_leaving or self.is_closed:
|
|
180
|
+
return
|
|
181
|
+
|
|
182
|
+
logger.info(f"channel {self.topic} error: {payload}")
|
|
183
|
+
self.state = ChannelStates.ERRORED
|
|
184
|
+
self.rejoin_timer.schedule_timeout()
|
|
185
|
+
self._notify_subscribe_state(
|
|
186
|
+
RealtimeSubscribeStates.CHANNEL_ERROR, Exception(json.dumps(payload))
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
def _notify_subscribe_state(
|
|
190
|
+
self, status: RealtimeSubscribeStates, error: Exception | None
|
|
191
|
+
) -> None:
|
|
192
|
+
try:
|
|
193
|
+
if self.subscribe_callback:
|
|
194
|
+
self.subscribe_callback(status, error)
|
|
195
|
+
finally:
|
|
196
|
+
self._release_subscribe_waiter()
|
|
197
|
+
|
|
198
|
+
def _release_subscribe_waiter(self) -> None:
|
|
199
|
+
waiter = self._subscribe_waiter
|
|
200
|
+
self._subscribe_waiter = None
|
|
201
|
+
if waiter is not None and not waiter.done():
|
|
202
|
+
waiter.set_result(None)
|
|
203
|
+
|
|
204
|
+
# Properties
|
|
205
|
+
@property
|
|
206
|
+
def is_closed(self) -> bool:
|
|
207
|
+
return self.state == ChannelStates.CLOSED
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def is_joining(self) -> bool:
|
|
211
|
+
return self.state == ChannelStates.JOINING
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def is_leaving(self) -> bool:
|
|
215
|
+
return self.state == ChannelStates.LEAVING
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def is_errored(self) -> bool:
|
|
219
|
+
return self.state == ChannelStates.ERRORED
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def is_joined(self) -> bool:
|
|
223
|
+
return self.state == ChannelStates.JOINED
|
|
224
|
+
|
|
225
|
+
# Core channel methods
|
|
226
|
+
async def subscribe(
|
|
227
|
+
self,
|
|
228
|
+
callback: Callable[[RealtimeSubscribeStates, Exception | None], None]
|
|
229
|
+
| None = None,
|
|
230
|
+
) -> AsyncRealtimeChannel:
|
|
231
|
+
"""
|
|
232
|
+
Subscribe to the channel. Can only be called once per channel instance.
|
|
233
|
+
|
|
234
|
+
Waits until the server replies to the join, the join times out, or the
|
|
235
|
+
channel errors or is closed by the server, so the callback has been
|
|
236
|
+
called with the resulting state by the time this returns. Unsubscribing
|
|
237
|
+
or closing the client while the join is pending also ends the wait.
|
|
238
|
+
After unsubscribing, the `CLOSED` callback runs later. After closing
|
|
239
|
+
the client, the join timeout reports `TIMED_OUT` later. Cancelling the
|
|
240
|
+
awaiting task stops the wait but not the join, which keeps running in
|
|
241
|
+
the background.
|
|
242
|
+
|
|
243
|
+
:param callback: Optional callback function that receives subscription state updates
|
|
244
|
+
and any errors that occur during subscription
|
|
245
|
+
:return: The Channel instance for method chaining
|
|
246
|
+
:raises: Exception if called multiple times on the same channel instance
|
|
247
|
+
"""
|
|
248
|
+
if not self.socket.is_connected:
|
|
249
|
+
await self.socket.connect()
|
|
250
|
+
|
|
251
|
+
if self._joined_once:
|
|
252
|
+
raise Exception(
|
|
253
|
+
"Tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance"
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
self._prepare_join(callback)
|
|
257
|
+
waiter: asyncio.Future[None] = asyncio.get_running_loop().create_future()
|
|
258
|
+
self._subscribe_waiter = waiter
|
|
259
|
+
try:
|
|
260
|
+
await self._rejoin()
|
|
261
|
+
if self.is_leaving:
|
|
262
|
+
self._release_subscribe_waiter()
|
|
263
|
+
await asyncio.shield(waiter)
|
|
264
|
+
except Exception:
|
|
265
|
+
self._release_subscribe_waiter()
|
|
266
|
+
raise
|
|
267
|
+
return self
|
|
268
|
+
|
|
269
|
+
def _prepare_join(
|
|
270
|
+
self,
|
|
271
|
+
callback: Callable[[RealtimeSubscribeStates, Exception | None], None] | None,
|
|
272
|
+
) -> None:
|
|
273
|
+
self.subscribe_callback = callback
|
|
274
|
+
config: RealtimeChannelConfig = self.params["config"]
|
|
275
|
+
broadcast = config.get("broadcast")
|
|
276
|
+
presence = config.get("presence") or RealtimeChannelPresenceConfig(
|
|
277
|
+
key="", enabled=False
|
|
278
|
+
)
|
|
279
|
+
private = config.get("private", False)
|
|
280
|
+
|
|
281
|
+
presence_enabled = self.presence._has_callback_attached or presence.get(
|
|
282
|
+
"enabled", False
|
|
283
|
+
)
|
|
284
|
+
presence["enabled"] = presence_enabled
|
|
285
|
+
|
|
286
|
+
config_payload: dict[str, Any] = {
|
|
287
|
+
"config": {
|
|
288
|
+
"broadcast": broadcast,
|
|
289
|
+
"presence": presence,
|
|
290
|
+
"private": private,
|
|
291
|
+
"postgres_changes": [
|
|
292
|
+
c.binding_filter for c in self.postgres_changes_callbacks
|
|
293
|
+
],
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if self.socket.access_token:
|
|
298
|
+
config_payload["access_token"] = self.socket.access_token
|
|
299
|
+
|
|
300
|
+
self.join_push.update_payload(config_payload)
|
|
301
|
+
self._presence_enabled = presence_enabled
|
|
302
|
+
self._joined_once = True
|
|
303
|
+
|
|
304
|
+
def on_join_push_ok(payload: ReplyPostgresChanges) -> None:
|
|
305
|
+
server_postgres_changes = payload.postgres_changes
|
|
306
|
+
|
|
307
|
+
if server_postgres_changes is None:
|
|
308
|
+
self._notify_subscribe_state(RealtimeSubscribeStates.SUBSCRIBED, None)
|
|
309
|
+
return
|
|
310
|
+
|
|
311
|
+
server_ids = []
|
|
312
|
+
|
|
313
|
+
for i, postgres_callback in enumerate(self.postgres_changes_callbacks):
|
|
314
|
+
server_binding: PostgresRowChange | None = (
|
|
315
|
+
server_postgres_changes[i]
|
|
316
|
+
if i < len(server_postgres_changes)
|
|
317
|
+
else None
|
|
318
|
+
)
|
|
319
|
+
logger.debug(f"{server_binding}, {postgres_callback}")
|
|
320
|
+
|
|
321
|
+
if (
|
|
322
|
+
server_binding
|
|
323
|
+
and server_binding.event == postgres_callback.event
|
|
324
|
+
and server_binding.schema_ == postgres_callback.schema
|
|
325
|
+
and server_binding.table == postgres_callback.table
|
|
326
|
+
and server_binding.filter == postgres_callback.filter
|
|
327
|
+
):
|
|
328
|
+
server_ids.append(server_binding.id)
|
|
329
|
+
else:
|
|
330
|
+
self._run_in_background(self.unsubscribe())
|
|
331
|
+
self.state = ChannelStates.ERRORED
|
|
332
|
+
self._notify_subscribe_state(
|
|
333
|
+
RealtimeSubscribeStates.CHANNEL_ERROR,
|
|
334
|
+
Exception(
|
|
335
|
+
"mismatch between server and client bindings for postgres changes"
|
|
336
|
+
),
|
|
337
|
+
)
|
|
338
|
+
return
|
|
339
|
+
|
|
340
|
+
for postgres_callback, server_id in zip(
|
|
341
|
+
self.postgres_changes_callbacks, server_ids, strict=True
|
|
342
|
+
):
|
|
343
|
+
postgres_callback.id = server_id
|
|
344
|
+
self._notify_subscribe_state(RealtimeSubscribeStates.SUBSCRIBED, None)
|
|
345
|
+
|
|
346
|
+
def on_join_push_error(payload: dict[str, Any]) -> None:
|
|
347
|
+
self._notify_subscribe_state(
|
|
348
|
+
RealtimeSubscribeStates.CHANNEL_ERROR,
|
|
349
|
+
Exception(json.dumps(payload)),
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
def on_join_push_timeout(*args) -> None:
|
|
353
|
+
self._notify_subscribe_state(RealtimeSubscribeStates.TIMED_OUT, None)
|
|
354
|
+
|
|
355
|
+
self.join_push.receive(
|
|
356
|
+
RealtimeAcknowledgementStatus.Ok, on_join_push_ok
|
|
357
|
+
).receive(RealtimeAcknowledgementStatus.Error, on_join_push_error).receive(
|
|
358
|
+
RealtimeAcknowledgementStatus.Timeout, on_join_push_timeout
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
async def unsubscribe(self) -> None:
|
|
362
|
+
"""
|
|
363
|
+
Unsubscribe from the channel and leave the topic.
|
|
364
|
+
Sets channel state to LEAVING and cleans up timers and pushes.
|
|
365
|
+
"""
|
|
366
|
+
self._resubscribing = False
|
|
367
|
+
await self._leave()
|
|
368
|
+
|
|
369
|
+
async def _leave(self) -> AsyncPush:
|
|
370
|
+
self.state = ChannelStates.LEAVING
|
|
371
|
+
self._release_subscribe_waiter()
|
|
372
|
+
|
|
373
|
+
self.rejoin_timer.reset()
|
|
374
|
+
self.join_push.destroy()
|
|
375
|
+
|
|
376
|
+
def _close(*args) -> None:
|
|
377
|
+
logger.info(f"channel {self.topic} leave")
|
|
378
|
+
self.on_close()
|
|
379
|
+
|
|
380
|
+
leave_push = AsyncPush(self, ChannelEvents.leave, {}, self.timeout)
|
|
381
|
+
leave_push.receive(RealtimeAcknowledgementStatus.Ok, _close).receive(
|
|
382
|
+
RealtimeAcknowledgementStatus.Error, _close
|
|
383
|
+
).receive(RealtimeAcknowledgementStatus.Timeout, _close)
|
|
384
|
+
await leave_push.send()
|
|
385
|
+
return leave_push
|
|
386
|
+
|
|
387
|
+
async def push(
|
|
388
|
+
self, event: str, payload: dict[str, Any], timeout: int | None = None
|
|
389
|
+
) -> AsyncPush:
|
|
390
|
+
"""
|
|
391
|
+
Push a message to the channel.
|
|
392
|
+
|
|
393
|
+
:param event: The event name to push
|
|
394
|
+
:param payload: The payload to send
|
|
395
|
+
:param timeout: Optional timeout in milliseconds
|
|
396
|
+
:return: AsyncPush instance representing the push operation
|
|
397
|
+
:raises: Exception if called before subscribing to the channel
|
|
398
|
+
"""
|
|
399
|
+
if not self._joined_once:
|
|
400
|
+
raise Exception(
|
|
401
|
+
f"tried to push '{event}' to '{self.topic}' before joining. Use channel.subscribe() before pushing events"
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
timeout = timeout or self.timeout
|
|
405
|
+
|
|
406
|
+
push = AsyncPush(self, event, payload, timeout)
|
|
407
|
+
if self._can_push():
|
|
408
|
+
await push.send()
|
|
409
|
+
assert push.ref is not None, "Sent AsyncPush should have a ref"
|
|
410
|
+
else:
|
|
411
|
+
push.start_timeout()
|
|
412
|
+
self._push_buffer.append(push)
|
|
413
|
+
|
|
414
|
+
return push
|
|
415
|
+
|
|
416
|
+
async def join(self) -> AsyncRealtimeChannel:
|
|
417
|
+
"""
|
|
418
|
+
Deprecated: use `subscribe()` instead.
|
|
419
|
+
|
|
420
|
+
Joins the channel through `subscribe()`. If the channel has already
|
|
421
|
+
been subscribed, waits for a pending join to settle and returns.
|
|
422
|
+
|
|
423
|
+
:return: The Channel instance for method chaining
|
|
424
|
+
"""
|
|
425
|
+
warnings.warn(
|
|
426
|
+
"AsyncRealtimeChannel.join() is deprecated and will be removed in a "
|
|
427
|
+
"future major version. Use AsyncRealtimeChannel.subscribe() instead.",
|
|
428
|
+
DeprecationWarning,
|
|
429
|
+
stacklevel=2,
|
|
430
|
+
)
|
|
431
|
+
if self._joined_once:
|
|
432
|
+
if self._subscribe_waiter is not None:
|
|
433
|
+
await asyncio.shield(self._subscribe_waiter)
|
|
434
|
+
return self
|
|
435
|
+
return await self.subscribe()
|
|
436
|
+
|
|
437
|
+
def on_broadcast(
|
|
438
|
+
self, event: str, callback: Callable[[BroadcastPayload], None]
|
|
439
|
+
) -> AsyncRealtimeChannel:
|
|
440
|
+
"""
|
|
441
|
+
Set up a listener for a specific broadcast event.
|
|
442
|
+
|
|
443
|
+
:param event: The name of the broadcast event to listen for
|
|
444
|
+
:param callback: Function called with the payload when a matching broadcast is received
|
|
445
|
+
:return: The Channel instance for method chaining
|
|
446
|
+
"""
|
|
447
|
+
self.broadcast_callbacks.append(
|
|
448
|
+
BroadcastCallback(callback=callback, event=event)
|
|
449
|
+
)
|
|
450
|
+
return self
|
|
451
|
+
|
|
452
|
+
def on_postgres_changes(
|
|
453
|
+
self,
|
|
454
|
+
event: RealtimePostgresChangesListenEvent,
|
|
455
|
+
callback: Callable[[PostgresChangesPayload], None],
|
|
456
|
+
table: str | None = None,
|
|
457
|
+
schema: str | None = None,
|
|
458
|
+
filter: str | None = None,
|
|
459
|
+
select: list[str] | None = None,
|
|
460
|
+
) -> AsyncRealtimeChannel:
|
|
461
|
+
"""
|
|
462
|
+
Set up a listener for Postgres database changes.
|
|
463
|
+
|
|
464
|
+
:param event: The type of database event to listen for (INSERT, UPDATE, DELETE, or *)
|
|
465
|
+
:param callback: Function called with the payload when a matching change is detected
|
|
466
|
+
:param table: The table name to monitor. Defaults to "*" for all tables
|
|
467
|
+
:param schema: The database schema to monitor. Defaults to "public"
|
|
468
|
+
:param filter: Optional filter string, evaluated server-side, in the form
|
|
469
|
+
``column=operator.value`` (e.g. ``"id=eq.1"`` or ``"title=like.%foo%"``).
|
|
470
|
+
Supported operators: ``eq``, ``neq``, ``lt``, ``lte``, ``gt``, ``gte``,
|
|
471
|
+
``in`` (``"status=in.(active,pending)"``), ``like``, ``ilike``, ``is``
|
|
472
|
+
(``"deleted_at=is.null"``), ``match``, ``imatch`` (POSIX regex),
|
|
473
|
+
``isdistinct`` (NULL-safe inequality). Any operator can be negated with
|
|
474
|
+
the ``not.`` prefix (e.g. ``"status=not.in.(draft,archived)"``). Combine
|
|
475
|
+
multiple conditions with commas to apply them as an ``AND``
|
|
476
|
+
(e.g. ``"amount=gt.100,status=in.(open,pending)"``).
|
|
477
|
+
:param select: Optional list of columns to receive instead of the full row.
|
|
478
|
+
Reduces payload size (helpful for large ``bytea``/``jsonb`` columns). The
|
|
479
|
+
listed columns must be selectable by the subscribing role.
|
|
480
|
+
:return: The Channel instance for method chaining
|
|
481
|
+
"""
|
|
482
|
+
callback = PostgresChangesCallback(
|
|
483
|
+
callback=callback,
|
|
484
|
+
event=event,
|
|
485
|
+
table=table,
|
|
486
|
+
schema=schema,
|
|
487
|
+
filter=filter,
|
|
488
|
+
select=select,
|
|
489
|
+
)
|
|
490
|
+
self.postgres_changes_callbacks.append(callback)
|
|
491
|
+
return self
|
|
492
|
+
|
|
493
|
+
def on_system(
|
|
494
|
+
self, callback: Callable[[SuccessSystemPayload], None]
|
|
495
|
+
) -> AsyncRealtimeChannel:
|
|
496
|
+
"""
|
|
497
|
+
Set up a listener for system events.
|
|
498
|
+
|
|
499
|
+
:param callback: The callback function to execute when a system event is received.
|
|
500
|
+
:return: The Channel instance for method chaining.
|
|
501
|
+
"""
|
|
502
|
+
self.system_callbacks.append(callback)
|
|
503
|
+
return self
|
|
504
|
+
|
|
505
|
+
# Presence methods
|
|
506
|
+
async def track(self, user_status: dict[str, Any]) -> None:
|
|
507
|
+
"""
|
|
508
|
+
Track presence status for the current user.
|
|
509
|
+
|
|
510
|
+
:param user_status: Dictionary containing the user's presence information
|
|
511
|
+
"""
|
|
512
|
+
await self.send_presence("track", user_status)
|
|
513
|
+
|
|
514
|
+
async def untrack(self) -> None:
|
|
515
|
+
"""
|
|
516
|
+
Stop tracking presence for the current user.
|
|
517
|
+
"""
|
|
518
|
+
await self.send_presence("untrack", {})
|
|
519
|
+
|
|
520
|
+
def presence_state(self) -> RealtimePresenceState:
|
|
521
|
+
"""
|
|
522
|
+
Get the current state of presence on this channel.
|
|
523
|
+
|
|
524
|
+
:return: Dictionary mapping presence keys to lists of presence payloads
|
|
525
|
+
"""
|
|
526
|
+
return self.presence.state
|
|
527
|
+
|
|
528
|
+
def on_presence_sync(self, callback: Callable[[], None]) -> AsyncRealtimeChannel:
|
|
529
|
+
"""
|
|
530
|
+
Register a callback for presence sync events.
|
|
531
|
+
|
|
532
|
+
:param callback: The callback function to execute when a presence sync event occurs.
|
|
533
|
+
:return: The Channel instance for method chaining.
|
|
534
|
+
"""
|
|
535
|
+
self.presence.on_sync(callback)
|
|
536
|
+
|
|
537
|
+
self._resubscribe_for_presence()
|
|
538
|
+
|
|
539
|
+
return self
|
|
540
|
+
|
|
541
|
+
def on_presence_join(
|
|
542
|
+
self, callback: PresenceOnJoinCallback
|
|
543
|
+
) -> AsyncRealtimeChannel:
|
|
544
|
+
"""
|
|
545
|
+
Register a callback for presence join events.
|
|
546
|
+
|
|
547
|
+
:param callback: The callback function to execute when a presence join event occurs.
|
|
548
|
+
:return: The Channel instance for method chaining.
|
|
549
|
+
"""
|
|
550
|
+
self.presence.on_join(callback)
|
|
551
|
+
self._resubscribe_for_presence()
|
|
552
|
+
|
|
553
|
+
return self
|
|
554
|
+
|
|
555
|
+
def on_presence_leave(
|
|
556
|
+
self, callback: PresenceOnLeaveCallback
|
|
557
|
+
) -> AsyncRealtimeChannel:
|
|
558
|
+
"""
|
|
559
|
+
Register a callback for presence leave events.
|
|
560
|
+
|
|
561
|
+
:param callback: The callback function to execute when a presence leave event occurs.
|
|
562
|
+
:return: The Channel instance for method chaining.
|
|
563
|
+
"""
|
|
564
|
+
self.presence.on_leave(callback)
|
|
565
|
+
self._resubscribe_for_presence()
|
|
566
|
+
return self
|
|
567
|
+
|
|
568
|
+
# Broadcast methods
|
|
569
|
+
async def send_broadcast(self, event: str, data: Any) -> None:
|
|
570
|
+
"""
|
|
571
|
+
Send a broadcast message through this channel.
|
|
572
|
+
|
|
573
|
+
:param event: The name of the broadcast event
|
|
574
|
+
:param data: The payload to broadcast
|
|
575
|
+
"""
|
|
576
|
+
await self.push(
|
|
577
|
+
ChannelEvents.broadcast,
|
|
578
|
+
{"type": "broadcast", "event": event, "payload": data},
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
async def http_send(
|
|
582
|
+
self,
|
|
583
|
+
event: str,
|
|
584
|
+
payload: Any,
|
|
585
|
+
*,
|
|
586
|
+
timeout: float | None = None,
|
|
587
|
+
) -> None:
|
|
588
|
+
"""
|
|
589
|
+
Send a broadcast message through the REST API.
|
|
590
|
+
|
|
591
|
+
This always uses the HTTP endpoint, whatever the state of the websocket
|
|
592
|
+
connection, and does not require the channel to be subscribed.
|
|
593
|
+
``bytes`` payloads are sent as ``application/octet-stream``; any other
|
|
594
|
+
payload is JSON-encoded. Requires Realtime server v2.97.0 or newer.
|
|
595
|
+
|
|
596
|
+
:param event: The name of the broadcast event
|
|
597
|
+
:param payload: The payload to broadcast (required)
|
|
598
|
+
:param timeout: Optional timeout in seconds, defaults to the client timeout
|
|
599
|
+
:raises ValueError: If the payload is None
|
|
600
|
+
:raises RealtimeHTTPError: If the request times out or the server rejects it
|
|
601
|
+
"""
|
|
602
|
+
if payload is None:
|
|
603
|
+
raise ValueError("Payload is required for http_send()")
|
|
604
|
+
|
|
605
|
+
is_binary = isinstance(payload, (bytes, bytearray, memoryview))
|
|
606
|
+
headers = {
|
|
607
|
+
"apikey": self.socket.apikey or "",
|
|
608
|
+
"Content-Type": "application/octet-stream"
|
|
609
|
+
if is_binary
|
|
610
|
+
else "application/json",
|
|
611
|
+
}
|
|
612
|
+
if self.socket.access_token:
|
|
613
|
+
headers["Authorization"] = f"Bearer {self.socket.access_token}"
|
|
614
|
+
|
|
615
|
+
sub_topic = self.topic
|
|
616
|
+
if sub_topic.startswith("realtime:"):
|
|
617
|
+
sub_topic = sub_topic[len("realtime:") :]
|
|
618
|
+
url = (
|
|
619
|
+
f"{self.broadcast_endpoint_url}/{quote(sub_topic, safe='')}"
|
|
620
|
+
f"/events/{quote(event, safe='')}"
|
|
621
|
+
)
|
|
622
|
+
params = {"private": "true"} if self.params["config"].get("private") else None
|
|
623
|
+
|
|
624
|
+
content = bytes(payload) if is_binary else json.dumps(payload)
|
|
625
|
+
|
|
626
|
+
timeout_seconds = timeout or self.timeout
|
|
627
|
+
try:
|
|
628
|
+
async with httpx.AsyncClient(timeout=timeout_seconds) as client:
|
|
629
|
+
response = await client.post(
|
|
630
|
+
url, headers=headers, params=params, content=content
|
|
631
|
+
)
|
|
632
|
+
except httpx.TimeoutException as e:
|
|
633
|
+
raise RealtimeHTTPError(f"Request timeout: {e}") from e
|
|
634
|
+
|
|
635
|
+
if response.status_code == 202:
|
|
636
|
+
return
|
|
637
|
+
|
|
638
|
+
if response.status_code == 404:
|
|
639
|
+
raise RealtimeHTTPError(
|
|
640
|
+
"http_send() requires Realtime server v2.97.0 or newer; the endpoint "
|
|
641
|
+
"returned 404. Update your Supabase CLI to a recent version, or "
|
|
642
|
+
"upgrade the Realtime server in your self-hosted setup.",
|
|
643
|
+
status=404,
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
error_message = response.reason_phrase
|
|
647
|
+
try:
|
|
648
|
+
error_body = response.json()
|
|
649
|
+
error_message = (
|
|
650
|
+
error_body.get("error") or error_body.get("message") or error_message
|
|
651
|
+
)
|
|
652
|
+
except Exception:
|
|
653
|
+
pass
|
|
654
|
+
raise RealtimeHTTPError(error_message, status=response.status_code)
|
|
655
|
+
|
|
656
|
+
# Internal methods
|
|
657
|
+
|
|
658
|
+
def _run_in_background(self, coroutine: Coroutine[Any, Any, None]) -> None:
|
|
659
|
+
task = asyncio.create_task(coroutine)
|
|
660
|
+
self._background_tasks.add(task)
|
|
661
|
+
task.add_done_callback(self._background_tasks.discard)
|
|
662
|
+
|
|
663
|
+
def _resubscribe_for_presence(self) -> None:
|
|
664
|
+
if not self.is_joined or self._presence_enabled:
|
|
665
|
+
return
|
|
666
|
+
logger.info(
|
|
667
|
+
f"channel {self.topic} resubscribe due to change in presence callbacks on joined channel"
|
|
668
|
+
)
|
|
669
|
+
self._run_in_background(self._resubscribe())
|
|
670
|
+
|
|
671
|
+
async def _resubscribe(self) -> None:
|
|
672
|
+
if self._resubscribing or not self.is_joined:
|
|
673
|
+
return
|
|
674
|
+
self._resubscribing = True
|
|
675
|
+
try:
|
|
676
|
+
callback = self.subscribe_callback
|
|
677
|
+
closed: asyncio.Future[None] = asyncio.get_running_loop().create_future()
|
|
678
|
+
|
|
679
|
+
def _on_left(*args) -> None:
|
|
680
|
+
if not closed.done():
|
|
681
|
+
closed.set_result(None)
|
|
682
|
+
|
|
683
|
+
leave_push = await self._leave()
|
|
684
|
+
leave_push.receive(RealtimeAcknowledgementStatus.Ok, _on_left).receive(
|
|
685
|
+
RealtimeAcknowledgementStatus.Error, _on_left
|
|
686
|
+
).receive(RealtimeAcknowledgementStatus.Timeout, _on_left)
|
|
687
|
+
await closed
|
|
688
|
+
|
|
689
|
+
if (
|
|
690
|
+
not self._resubscribing
|
|
691
|
+
or self.socket.channels.get(self.topic, self) is not self
|
|
692
|
+
):
|
|
693
|
+
return
|
|
694
|
+
|
|
695
|
+
self.socket.channels[self.topic] = self
|
|
696
|
+
self.join_push = self._create_join_push()
|
|
697
|
+
self._prepare_join(callback)
|
|
698
|
+
if self.socket.is_connected:
|
|
699
|
+
await self._rejoin()
|
|
700
|
+
else:
|
|
701
|
+
self.state = ChannelStates.ERRORED
|
|
702
|
+
finally:
|
|
703
|
+
self._resubscribing = False
|
|
704
|
+
|
|
705
|
+
def _broadcast_endpoint_url(self) -> str:
|
|
706
|
+
return f"{http_endpoint_url(self.socket.http_endpoint)}/api/broadcast"
|
|
707
|
+
|
|
708
|
+
async def _rejoin(self) -> None:
|
|
709
|
+
if self.is_leaving:
|
|
710
|
+
return
|
|
711
|
+
logger.debug(f"Rejoining channel after reconnection: {self.topic}")
|
|
712
|
+
self.state = ChannelStates.JOINING
|
|
713
|
+
await self.join_push.resend()
|
|
714
|
+
|
|
715
|
+
def _can_push(self) -> bool:
|
|
716
|
+
return self.socket.is_connected and self._joined_once
|
|
717
|
+
|
|
718
|
+
async def send_presence(self, event: str, data: Any) -> None:
|
|
719
|
+
await self.push(ChannelEvents.presence, {"event": event, "payload": data})
|
|
720
|
+
|
|
721
|
+
def _handle_message(self, message: ServerMessage) -> None:
|
|
722
|
+
logger.debug(f"{self.topic} : {message!r}")
|
|
723
|
+
if isinstance(message, SystemMessage):
|
|
724
|
+
if isinstance(message.payload, SuccessSystemPayload):
|
|
725
|
+
for callback in self.system_callbacks:
|
|
726
|
+
callback(message.payload)
|
|
727
|
+
else:
|
|
728
|
+
self.on_error(dict(message.payload))
|
|
729
|
+
elif isinstance(message, ReplyMessage):
|
|
730
|
+
reply_payload = message.payload
|
|
731
|
+
if message.ref and (
|
|
732
|
+
push := self.messages_waiting_for_ack.pop(message.ref, None)
|
|
733
|
+
):
|
|
734
|
+
if reply_payload.status == "ok":
|
|
735
|
+
push.trigger(
|
|
736
|
+
RealtimeAcknowledgementStatus.Ok, reply_payload.response
|
|
737
|
+
)
|
|
738
|
+
else:
|
|
739
|
+
push.trigger(
|
|
740
|
+
RealtimeAcknowledgementStatus.Error, reply_payload.response
|
|
741
|
+
)
|
|
742
|
+
elif isinstance(message, BroadcastMessage):
|
|
743
|
+
broadcast_payload = message.payload
|
|
744
|
+
for broadcast_callback in self.broadcast_callbacks:
|
|
745
|
+
broadcast_callback(broadcast_payload)
|
|
746
|
+
elif isinstance(message, PresenceStateMessage):
|
|
747
|
+
self.presence._on_state_event(message.payload)
|
|
748
|
+
elif isinstance(message, PresenceDiffMessage):
|
|
749
|
+
self.presence._on_diff_event(message.payload)
|
|
750
|
+
elif isinstance(message, PostgresChangesMessage):
|
|
751
|
+
payload = message.payload
|
|
752
|
+
for postgres_callback in self.postgres_changes_callbacks:
|
|
753
|
+
postgres_callback(payload)
|
|
754
|
+
elif isinstance(message, ChannelErrorMessage):
|
|
755
|
+
self.on_error(message.payload)
|
|
756
|
+
elif isinstance(message, ChannelCloseMessage):
|
|
757
|
+
self._resubscribing = False
|
|
758
|
+
self.on_close()
|
|
759
|
+
elif isinstance(message, HeartbeatMessage): # do nothing
|
|
760
|
+
return
|
|
761
|
+
else:
|
|
762
|
+
assert_never(message)
|
|
763
|
+
|
|
764
|
+
async def _rejoin_if_connected(self) -> None:
|
|
765
|
+
if self.socket.is_connected:
|
|
766
|
+
await self._rejoin()
|