Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,12 @@ select = [
"PT014",
# unused noqa directives
"RUF100",
# unreferenced asyncio tasks
"RUF006",
# flake8-async
"ASYNC",
]
ignore = ["F403", "E501", "E402", "UP006", "UP035"]
ignore = ["F403", "E501", "E402", "UP006", "UP035", "ASYNC230"]

[tool.ruff.lint.pyupgrade]
# Preserve types, even if a file imports `from __future__ import annotations`.
Expand Down
18 changes: 12 additions & 6 deletions src/realtime/src/realtime/_async/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio
import json
import logging
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Dict, List, Optional

from typing_extensions import assert_never

Expand Down Expand Up @@ -91,6 +91,7 @@ def __init__(
self.presence: AsyncRealtimePresence = AsyncRealtimePresence()
self.state = ChannelStates.CLOSED
self._push_buffer: list[AsyncPush] = []
self._background_tasks: set[asyncio.Task[None]] = set()
self.timeout = self.socket.timeout

self.join_push: AsyncPush = AsyncPush(
Expand All @@ -114,7 +115,7 @@ def on_join_push_ok(payload: ReplyPostgresChanges) -> None:
self.state = ChannelStates.JOINED
self.rejoin_timer.reset()
for push in self._push_buffer:
asyncio.create_task(push.send())
self._run_in_background(push.send())
self._push_buffer = []

def on_join_push_timeout() -> None:
Expand Down Expand Up @@ -249,7 +250,7 @@ def on_join_push_ok(payload: ReplyPostgresChanges) -> None:
postgres_callback.id = server_binding.id
new_postgres_bindings.append(postgres_callback)
else:
asyncio.create_task(self.unsubscribe())
self._run_in_background(self.unsubscribe())
callback and callback(
RealtimeSubscribeStates.CHANNEL_ERROR,
Exception(
Expand Down Expand Up @@ -463,7 +464,7 @@ def on_presence_sync(self, callback: Callable[[], None]) -> AsyncRealtimeChannel
logger.info(
f"channel {self.topic} resubscribe due to change in presence callbacks on joined channel"
)
asyncio.create_task(self._resubscribe())
self._run_in_background(self._resubscribe())

return self

Expand All @@ -481,7 +482,7 @@ def on_presence_join(
logger.info(
f"channel {self.topic} resubscribe due to change in presence callbacks on joined channel"
)
asyncio.create_task(self._resubscribe())
self._run_in_background(self._resubscribe())

return self

Expand All @@ -499,7 +500,7 @@ def on_presence_leave(
logger.info(
f"channel {self.topic} resubscribe due to change in presence callbacks on joined channel"
)
asyncio.create_task(self._resubscribe())
self._run_in_background(self._resubscribe())
return self

# Broadcast methods
Expand All @@ -517,6 +518,11 @@ async def send_broadcast(self, event: str, data: Any) -> None:

# Internal methods

def _run_in_background(self, coroutine: Coroutine[Any, Any, None]) -> None:
task = asyncio.create_task(coroutine)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)

async def _resubscribe(self) -> None:
await self.unsubscribe()
await self.subscribe()
Expand Down
24 changes: 24 additions & 0 deletions src/realtime/tests/test_background_tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import asyncio
from unittest.mock import AsyncMock, patch

import pytest

from realtime import AsyncRealtimeClient
from realtime.types import ChannelStates


@pytest.mark.asyncio
async def test_resubscribe_task_is_kept_until_it_finishes() -> None:
socket = AsyncRealtimeClient("ws://127.0.0.1:54321/realtime/v1", "key")
channel = socket.channel("background-tasks")
channel.state = ChannelStates.JOINED

with patch.object(channel, "_resubscribe", new=AsyncMock()) as resubscribe:
channel.on_presence_sync(lambda: None)

assert len(channel._background_tasks) == 1
await asyncio.gather(*channel._background_tasks)
await asyncio.sleep(0)

resubscribe.assert_awaited_once()
assert channel._background_tasks == set()
2 changes: 1 addition & 1 deletion src/supabase/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ include ../../gnu-sed.mk

build-sync: gnu-sed
@$(MAKE) --no-print-directory unasync
$(SED) -i 's/asyncio.create_task(self.realtime.set_auth(access_token))//g' src/supabase/_sync/client.py
$(SED) -i '/_background_tasks\|asyncio\.create_task(self\.realtime\.set_auth/d' src/supabase/_sync/client.py
$(SED) -i 's/asynch/synch/g' src/supabase/_sync/auth_client.py
$(SED) -i 's/Async/Sync/g' src/supabase/_sync/auth_client.py
$(SED) -i 's/Async/Sync/g' src/supabase/_sync/client.py
Expand Down
5 changes: 4 additions & 1 deletion src/supabase/src/supabase/_async/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def __init__(
self._postgrest: Optional[AsyncPostgrestClient] = None
self._storage: Optional[AsyncStorageClient] = None
self._functions: Optional[AsyncFunctionsClient] = None
self._background_tasks: set[asyncio.Task[None]] = set()
self.auth.on_auth_state_change(self._listen_to_auth_events)

@classmethod
Expand Down Expand Up @@ -344,7 +345,9 @@ def _listen_to_auth_events(
auth_header = self._create_auth_header(access_token)
self.options.headers["Authorization"] = auth_header
self.auth._headers["Authorization"] = auth_header
asyncio.create_task(self.realtime.set_auth(access_token))
task = asyncio.create_task(self.realtime.set_auth(access_token))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)


async def create_client(
Expand Down
17 changes: 17 additions & 0 deletions src/supabase/tests/test_realtime.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import asyncio
from unittest.mock import AsyncMock, MagicMock

import supabase


Expand All @@ -12,3 +15,17 @@ def test_realtime_client_initialization() -> None:
url = "http://localhost:54322"
sp_local = supabase.Client(url, key)
assert str(sp_local.realtime_url) == "ws://localhost:54322/realtime/v1"


async def test_auth_events_keep_the_realtime_set_auth_task_until_it_finishes() -> None:
client = supabase.AsyncClient("http://localhost:54321", "key")
client.realtime = AsyncMock()

client._listen_to_auth_events("SIGNED_IN", MagicMock(access_token="userjwt"))

assert len(client._background_tasks) == 1
await asyncio.gather(*client._background_tasks)
await asyncio.sleep(0)

client.realtime.set_auth.assert_awaited_once_with("userjwt")
assert client._background_tasks == set()
Loading