Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Postgres backend: handle connection loss #130

Closed
Closed
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
8 changes: 6 additions & 2 deletions broadcaster/_backends/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ def __init__(self, url: str):
async def connect(self) -> None:
self._conn = await asyncpg.connect(self._url)
self._listen_queue: asyncio.Queue[Event] = asyncio.Queue()
self._conn.add_termination_listener(self._termination_listener)

async def disconnect(self) -> None:
await self._conn.close()
Expand All @@ -27,10 +28,13 @@ async def unsubscribe(self, channel: str) -> None:
async def publish(self, channel: str, message: str) -> None:
await self._conn.execute("SELECT pg_notify($1, $2);", channel, message)

def _listener(self, *args: Any) -> None:
async def _listener(self, *args: Any) -> None:
connection, pid, channel, payload = args
event = Event(channel=channel, message=payload)
self._listen_queue.put_nowait(event)
await self._listen_queue.put(event)

async def _termination_listener(self, *args: Any) -> None:
await self._listen_queue.put(None)

async def next_published(self) -> Event:
return await self._listen_queue.get()
8 changes: 8 additions & 0 deletions broadcaster/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,17 @@ async def disconnect(self) -> None:
async def _listener(self) -> None:
while True:
event = await self._backend.next_published()
if event is None:
# Backend is disconnected
break

for queue in list(self._subscribers.get(event.channel, [])):
await queue.put(event)

# Ubsubscribe all
for queue in sum([list(qs) for qs in self._subscribers.values()], []):
await queue.put(None)

async def publish(self, channel: str, message: Any) -> None:
await self._backend.publish(channel, message)

Expand Down
Loading