diff --git a/pyproject.toml b/pyproject.toml index a2b5d51bf..11057dc01 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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`. diff --git a/src/realtime/src/realtime/_async/channel.py b/src/realtime/src/realtime/_async/channel.py index 2ca9ee416..f6fa6793d 100644 --- a/src/realtime/src/realtime/_async/channel.py +++ b/src/realtime/src/realtime/_async/channel.py @@ -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 @@ -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( @@ -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: @@ -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( @@ -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 @@ -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 @@ -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 @@ -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() diff --git a/src/realtime/tests/test_background_tasks.py b/src/realtime/tests/test_background_tasks.py new file mode 100644 index 000000000..00a3da244 --- /dev/null +++ b/src/realtime/tests/test_background_tasks.py @@ -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() diff --git a/src/supabase/Makefile b/src/supabase/Makefile index 526e34b58..860d79054 100644 --- a/src/supabase/Makefile +++ b/src/supabase/Makefile @@ -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 diff --git a/src/supabase/src/supabase/_async/client.py b/src/supabase/src/supabase/_async/client.py index ec66ae247..e8303aaaa 100644 --- a/src/supabase/src/supabase/_async/client.py +++ b/src/supabase/src/supabase/_async/client.py @@ -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 @@ -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( diff --git a/src/supabase/tests/test_realtime.py b/src/supabase/tests/test_realtime.py index c377189f0..5fc473a90 100644 --- a/src/supabase/tests/test_realtime.py +++ b/src/supabase/tests/test_realtime.py @@ -1,3 +1,6 @@ +import asyncio +from unittest.mock import AsyncMock, MagicMock + import supabase @@ -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()