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
12 changes: 9 additions & 3 deletions src/taskiq_pg/asyncpg/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class AsyncpgBroker(BasePostgresBroker):
_owns_read_conn: bool
_listener_task: asyncio.Task[None] | None = None
_listener_disconnected: asyncio.Event
_notify_tasks: set[asyncio.Task[None]]

@tp.overload
def __init__(
Expand Down Expand Up @@ -190,6 +191,8 @@ def __init__( # noqa: PLR0913
self._read_conn = read_connection
self._owns_read_conn = False

self._notify_tasks = set()

async def startup(self) -> None:
"""Initialize the broker."""
await super().startup()
Expand Down Expand Up @@ -231,6 +234,8 @@ async def shutdown(self) -> None:
if self._listener_task is not None:
await cancel_and_wait(self._listener_task)
self._listener_task = None
for task in list(self._notify_tasks):
await cancel_and_wait(task)
await super().shutdown()
if self._read_conn is not None:
self._read_conn.remove_termination_listener(self._connection_terminated)
Expand Down Expand Up @@ -381,9 +386,10 @@ async def kick(self, message: BrokerMessage) -> None:
)

if delay_seconds is not None:
_ = asyncio.create_task( # noqa: RUF006
self._schedule_notification(message_inserted_id, delay_seconds),
)
# Keep a reference, so the task is not garbage collected, and cancel it on shutdown.
task = asyncio.create_task(self._schedule_notification(message_inserted_id, delay_seconds))
self._notify_tasks.add(task)
task.add_done_callback(self._notify_tasks.discard)
else:
# Send a NOTIFY with the message ID as payload
_ = await conn.execute(
Expand Down
12 changes: 9 additions & 3 deletions src/taskiq_pg/psqlpy/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ class PSQLPyBroker(BasePostgresBroker):
_listener_task: asyncio.Task[None] | None = None
_queue: asyncio.Queue
_owns_write_pool: bool
_notify_tasks: set[asyncio.Task[None]]

def __init__( # noqa: PLR0913
self,
Expand Down Expand Up @@ -119,6 +120,8 @@ def __init__( # noqa: PLR0913
self._write_pool = write_pool
self._owns_write_pool = False

self._notify_tasks = set()

async def startup(self) -> None:
"""Initialize the broker."""
await super().startup()
Expand Down Expand Up @@ -165,6 +168,8 @@ async def shutdown(self) -> None:
if self._listener_task is not None:
await cancel_and_wait(self._listener_task)
self._listener_task = None
for task in list(self._notify_tasks):
await cancel_and_wait(task)
# startup() may have failed before creating these
listener = getattr(self, "_listener", None)
if listener is not None:
Expand Down Expand Up @@ -300,9 +305,10 @@ async def kick(self, message: BrokerMessage) -> None:
)

if delay_seconds is not None:
asyncio.create_task( # noqa: RUF006
self._schedule_notification(message_inserted_id, delay_seconds),
)
# Keep a reference, so the task is not garbage collected, and cancel it on shutdown.
task = asyncio.create_task(self._schedule_notification(message_inserted_id, delay_seconds))
self._notify_tasks.add(task)
task.add_done_callback(self._notify_tasks.discard)
else:
# Send NOTIFY with message ID as payload
_ = await conn.execute(
Expand Down
39 changes: 39 additions & 0 deletions tests/integration/test_shutdown_cancellation.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import asyncio
import gc
import typing as tp
import uuid

import pytest
from taskiq import BrokerMessage

from taskiq_pg.aiopg import AiopgBroker
from taskiq_pg.asyncpg import AsyncpgBroker
from taskiq_pg.psqlpy import PSQLPyBroker
from taskiq_pg.psycopg import PsycopgBroker


async def slow_to_cancel() -> None:
Expand Down Expand Up @@ -47,3 +52,37 @@ async def test_when_shutdown_is_cancelled__then_cancellation_is_propagated(
assert shutdown.cancelled(), "shutdown() must not swallow its own cancellation"
finally:
await broker.shutdown()


@pytest.mark.integration
@pytest.mark.parametrize("broker_class", [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker])
async def test_when_broker_shuts_down_before_a_delayed_notification__then_the_notification_is_cancelled(
pg_dsn: str,
broker_class: type[AiopgBroker | AsyncpgBroker | PsycopgBroker | PSQLPyBroker],
) -> None:
# given
suffix = uuid.uuid4().hex[:12]
broker = broker_class(dsn=pg_dsn, table_name=f"delayed_{suffix}", channel_name=f"delayed_{suffix}")
await broker.startup()
errors: list[dict[str, tp.Any]] = []
loop = asyncio.get_running_loop()
previous_handler = loop.get_exception_handler()
loop.set_exception_handler(lambda _loop, context: errors.append(context))
try:
message = BrokerMessage(
task_id=uuid.uuid4().hex,
task_name="example:delayed",
message=b"{}",
labels={"delay": 1},
)
await broker.kick(message)

# when: the producer shuts down and keeps running past the delay
await asyncio.wait_for(broker.shutdown(), timeout=5)
await asyncio.sleep(1.5)
gc.collect()

# then: the delayed NOTIFY did not run against the closed pool
assert [context.get("message") for context in errors] == []
finally:
loop.set_exception_handler(previous_handler)