Skip to content

Commit

Permalink
fix: gracefully close the socket
Browse files Browse the repository at this point in the history
  • Loading branch information
juancarlospaco authored May 29, 2024
1 parent 8bcf6da commit 9c0ffd1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
12 changes: 12 additions & 0 deletions realtime/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,18 @@ async def _connect(self) -> None:
else:
raise Exception("Connection Failed")

@ensure_connection
def close(self) -> None:
"""
Wrapper for async def _close() to expose a non-async interface
"""
loop = asyncio.get_event_loop()
loop.run_until_complete(self._close())
self.connected = False

async def _close(self) -> None:
await self.ws_connection.close()

async def _keep_alive(self) -> None:
"""
Sending heartbeat to server every 5 seconds
Expand Down
27 changes: 27 additions & 0 deletions tests/tests_close.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import os

from realtime.connection import Socket


def callback(payload):
print("Callback:\t", payload)


def test():
SUPABASE_ID = os.environ.get("SUPABASE_TEST_URL")
API_KEY = os.environ.get("SUPABASE_TEST_KEY")

URL = f"wss://{SUPABASE_ID}.supabase.co/realtime/v1/websocket?apikey={API_KEY}&vsn=1.0.0"

s = Socket(URL)
s.connect()

channel_1 = s.set_channel("realtime:public:sample")
channel_1.join().on("INSERT", callback)

s.close()
assert s.ws_connection.closed, "Connection was not closed as expected."


if __name__ == "__main__":
test()

0 comments on commit 9c0ffd1

Please sign in to comment.