Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.
Open
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 = 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 @@ -72,9 +72,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()], []):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

# Unsubscribe all
for queue_set in self._subscribers.values():
    for queue in queue_set:
        await queue.put(None)

Seems like a lot less wasteful / clear what's going on.
As far as I know, you can loop over sets directly in python, no need
to convert to a list.

await queue.put(None)

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

Expand Down