Skip to content

Commit

Permalink
rebuild sync methods and fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
grdsdev committed Aug 13, 2024
1 parent ec038c1 commit 78279eb
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 69 deletions.
64 changes: 42 additions & 22 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ classifiers = [
]

[tool.poetry.dependencies]
python = "^3.8"
python = "^3.8.18"
postgrest = ">=0.14,<0.17.0"
realtime = { path = "../realtime-py", develop = true }
gotrue = ">=1.3,<3.0"
Expand All @@ -38,7 +38,7 @@ python-dotenv = "^1.0.1"
tests = 'poetry_scripts:run_tests'

[tool.poetry.group.dev.dependencies]
unasync-cli = "^0.0.9"
unasync-cli = { git = "https://github.com/supabase-community/unasync-cli.git", branch = "main" }

[tool.semantic_release]
version_variables = ["supabase/__version__.py:__version__"]
Expand Down
4 changes: 0 additions & 4 deletions supabase/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@
from ._sync.client import SyncStorageClient as SupabaseStorageClient
from ._sync.client import create_client

# Realtime Client
from .lib.realtime_client import SupabaseRealtimeClient

__all__ = [
"acreate_client",
"AClient",
Expand All @@ -31,7 +28,6 @@
"Client",
"SupabaseAuthClient",
"SupabaseStorageClient",
"SupabaseRealtimeClient",
"PostgrestAPIError",
"PostgrestAPIResponse",
"StorageException",
Expand Down
75 changes: 34 additions & 41 deletions supabase/_sync/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import re
from typing import Any, Dict, Optional, Union
from typing import Any, Dict, List, Optional, Union

from gotrue import SyncMemoryStorage
from gotrue.types import AuthChangeEvent, Session
Expand All @@ -10,6 +10,8 @@
SyncRPCFilterRequestBuilder,
)
from postgrest.constants import DEFAULT_POSTGREST_CLIENT_TIMEOUT
from realtime.channel import Channel, RealtimeChannelOptions
from realtime.client import RealtimeClient
from storage3 import SyncStorageClient
from storage3.constants import DEFAULT_TIMEOUT as DEFAULT_STORAGE_CLIENT_TIMEOUT
from supafunc import SyncFunctionsClient
Expand Down Expand Up @@ -80,11 +82,11 @@ def __init__(
auth_url=self.auth_url,
client_options=options,
)
# TODO: Bring up to parity with JS client.
# self.realtime: SupabaseRealtimeClient = self._init_realtime_client(
# realtime_url=self.realtime_url,
# supabase_key=self.supabase_key,
# )
self.realtime: RealtimeClient = self._init_realtime_client(
realtime_url=self.realtime_url,
supabase_key=self.supabase_key,
options=options.realtime if options else None,
)
self.realtime = None
self._postgrest = None
self._storage = None
Expand Down Expand Up @@ -197,41 +199,29 @@ def functions(self):
)
return self._functions

# async def remove_subscription_helper(resolve):
# try:
# await self._close_subscription(subscription)
# open_subscriptions = len(self.get_subscriptions())
# if not open_subscriptions:
# error = await self.realtime.disconnect()
# if error:
# return {"error": None, "data": { open_subscriptions}}
# except Exception as e:
# raise e
# return remove_subscription_helper(subscription)

# async def _close_subscription(self, subscription):
# """Close a given subscription

# Parameters
# ----------
# subscription
# The name of the channel
# """
# if not subscription.closed:
# await self._closeChannel(subscription)

# def get_subscriptions(self):
# """Return all channels the client is subscribed to."""
# return self.realtime.channels

# @staticmethod
# def _init_realtime_client(
# realtime_url: str, supabase_key: str
# ) -> SupabaseRealtimeClient:
# """Private method for creating an instance of the realtime-py client."""
# return SupabaseRealtimeClient(
# realtime_url, {"params": {"apikey": supabase_key}}
# )
def channel(self, topic: str, params: RealtimeChannelOptions = {}) -> Channel:
"""Creates a Realtime channel with Broadcast, Presence, and Postgres Changes."""
return self.realtime.channel(topic, params)

def get_channels(self) -> List[Channel]:
"""Returns all realtime channels."""
return self.realtime.get_channels()

def remove_channel(self, channel: Channel) -> None:
"""Unsubscribes and removes Realtime channel from Realtime client."""
self.realtime.remove_channel(channel)

def remove_all_channels(self) -> None:
"""Unsubscribes and removes all Realtime channels from Realtime client."""
self.realtime.remove_all_channels()

@staticmethod
def _init_realtime_client(
realtime_url: str, supabase_key: str, options: Optional[Dict[str, Any]]
) -> RealtimeClient:
"""Private method for creating an instance of the realtime-py client."""
return RealtimeClient(realtime_url, token=supabase_key, params=options or {})

@staticmethod
def _init_storage_client(
storage_url: str,
Expand Down Expand Up @@ -303,6 +293,9 @@ def _listen_to_auth_events(

self.options.headers["Authorization"] = self._create_auth_header(access_token)

# set_auth is a coroutine, how to handle this?
self.realtime.set_auth(access_token)


def create_client(
supabase_url: str,
Expand Down
5 changes: 5 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ def test_updates_the_authorization_header_on_auth_events() -> None:
assert client.options.headers.get("Authorization") == f"Bearer {key}"

mock_session = MagicMock(access_token="secretuserjwt")
realtime_mock = MagicMock()
client.realtime = realtime_mock

client._listen_to_auth_events("SIGNED_IN", mock_session)

updated_authorization = f"Bearer {mock_session.access_token}"
Expand All @@ -89,3 +92,5 @@ def test_updates_the_authorization_header_on_auth_events() -> None:

assert client.storage.session.headers.get("apiKey") == key
assert client.storage.session.headers.get("Authorization") == updated_authorization

realtime_mock.set_auth.assert_called_once_with(mock_session.access_token)
14 changes: 14 additions & 0 deletions tests/test_realtime_configuration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import supabase


def test_functions_client_initialization() -> None:
ref = "ooqqmozurnggtljmjkii"
url = f"https://{ref}.supabase.co"
# Sample JWT Key
key = "xxxxxxxxxxxxxx.xxxxxxxxxxxxxxx.xxxxxxxxxxxxxxx"
sp = supabase.Client(url, key)
assert sp.realtime_url == f"wss://{ref}.supabase.co/realtime/v1"

url = "http://localhost:54322"
sp_local = supabase.Client(url, key)
assert sp_local.realtime_url == f"ws://localhost:54322/realtime/v1"

0 comments on commit 78279eb

Please sign in to comment.