|
1 |
| -from dataclasses import dataclass, field |
2 |
| -from typing import Any, Callable, Dict, Optional, Union |
| 1 | +from typing import Any, Callable |
3 | 2 |
|
4 |
| -from gotrue import SyncMemoryStorage, SyncSupportedStorage |
5 |
| -from httpx import Timeout |
6 |
| -from postgrest.constants import DEFAULT_POSTGREST_CLIENT_TIMEOUT |
| 3 | +from realtime.connection import Socket |
| 4 | +from realtime.transformers import convert_change_data |
7 | 5 |
|
8 |
| -from supabase import __version__ |
9 | 6 |
|
10 |
| -DEFAULT_HEADERS = {"X-Client-Info": f"supabase-py/{__version__}"} |
11 |
| - |
12 |
| - |
13 |
| -@dataclass |
14 |
| -class ClientOptions: |
15 |
| - schema: str = "public" |
16 |
| - """ |
17 |
| - The Postgres schema which your tables belong to. |
18 |
| - Must be on the list of exposed schemas in Supabase. Defaults to 'public'. |
19 |
| - """ |
20 |
| - |
21 |
| - headers: Dict[str, str] = field(default_factory=DEFAULT_HEADERS.copy) |
22 |
| - """Optional headers for initializing the client.""" |
23 |
| - |
24 |
| - auto_refresh_token: bool = True |
25 |
| - """Automatically refreshes the token for logged in users.""" |
26 |
| - |
27 |
| - persist_session: bool = True |
28 |
| - """Whether to persist a logged in session to storage.""" |
29 |
| - |
30 |
| - local_storage: SyncSupportedStorage = field(default_factory=SyncMemoryStorage) |
31 |
| - """A storage provider. Used to store the logged in session.""" |
32 |
| - |
33 |
| - realtime: Optional[Dict[str, Any]] = None |
34 |
| - """Options passed to the realtime-py instance""" |
35 |
| - |
36 |
| - fetch: Optional[Callable] = None |
37 |
| - """A custom `fetch` implementation.""" |
38 |
| - |
39 |
| - timeout: Union[int, float, Timeout] = DEFAULT_POSTGREST_CLIENT_TIMEOUT |
40 |
| - """Timeout passed to the SyncPostgrestClient instance.""" |
41 |
| - |
42 |
| - def replace( |
43 |
| - self, |
44 |
| - schema: Optional[str] = None, |
45 |
| - headers: Optional[Dict[str, str]] = None, |
46 |
| - auto_refresh_token: Optional[bool] = None, |
47 |
| - persist_session: Optional[bool] = None, |
48 |
| - local_storage: Optional[SyncSupportedStorage] = None, |
49 |
| - realtime: Optional[Dict[str, Any]] = None, |
50 |
| - fetch: Optional[Callable] = None, |
51 |
| - timeout: Union[int, float, Timeout] = DEFAULT_POSTGREST_CLIENT_TIMEOUT, |
52 |
| - ) -> "ClientOptions": |
53 |
| - """Create a new SupabaseClientOptions with changes""" |
54 |
| - client_options = ClientOptions() |
55 |
| - client_options.schema = schema or self.schema |
56 |
| - client_options.headers = headers or self.headers |
57 |
| - client_options.auto_refresh_token = ( |
58 |
| - auto_refresh_token or self.auto_refresh_token |
| 7 | +class SupabaseRealtimeClient: |
| 8 | + def __init__(self, socket: Socket, schema: str, table_name: str): |
| 9 | + topic = ( |
| 10 | + f"realtime:{schema}" |
| 11 | + if table_name == "*" |
| 12 | + else f"realtime:{schema}:{table_name}" |
| 13 | + ) |
| 14 | + self.subscription = socket.set_channel(topic) |
| 15 | + |
| 16 | + @staticmethod |
| 17 | + def get_payload_records(payload: Any): |
| 18 | + records: dict = {"new": {}, "old": {}} |
| 19 | + if payload.type in ["INSERT", "UPDATE"]: |
| 20 | + records["new"] = payload.record |
| 21 | + convert_change_data(payload.columns, payload.record) |
| 22 | + if payload.type in ["UPDATE", "DELETE"]: |
| 23 | + records["old"] = payload.record |
| 24 | + convert_change_data(payload.columns, payload.old_record) |
| 25 | + return records |
| 26 | + |
| 27 | + def on(self, event, callback: Callable[..., Any]): |
| 28 | + def cb(payload): |
| 29 | + enriched_payload = { |
| 30 | + "schema": payload.schema, |
| 31 | + "table": payload.table, |
| 32 | + "commit_timestamp": payload.commit_timestamp, |
| 33 | + "event_type": payload.type, |
| 34 | + "new": {}, |
| 35 | + "old": {}, |
| 36 | + } |
| 37 | + enriched_payload = {**enriched_payload, **self.get_payload_records(payload)} |
| 38 | + callback(enriched_payload) |
| 39 | + |
| 40 | + self.subscription.join().on(event, cb) |
| 41 | + return self |
| 42 | + |
| 43 | + def subscribe(self, callback: Callable[..., Any]): |
| 44 | + # TODO: Handle state change callbacks for error and close |
| 45 | + self.subscription.join().on("ok", callback("SUBSCRIBED")) |
| 46 | + self.subscription.join().on( |
| 47 | + "error", lambda x: callback("SUBSCRIPTION_ERROR", x) |
| 48 | + ) |
| 49 | + self.subscription.join().on( |
| 50 | + "timeout", lambda: callback("RETRYING_AFTER_TIMEOUT") |
59 | 51 | )
|
60 |
| - client_options.persist_session = persist_session or self.persist_session |
61 |
| - client_options.local_storage = local_storage or self.local_storage |
62 |
| - client_options.realtime = realtime or self.realtime |
63 |
| - client_options.fetch = fetch or self.fetch |
64 |
| - client_options.timeout = timeout or self.timeout |
65 |
| - return client_options |
| 52 | + return self.subscription |
0 commit comments