diff --git a/src/taskiq_pg/_internal/broker.py b/src/taskiq_pg/_internal/broker.py index 8cab583..5377f2e 100644 --- a/src/taskiq_pg/_internal/broker.py +++ b/src/taskiq_pg/_internal/broker.py @@ -16,7 +16,7 @@ class BasePostgresBroker(AsyncBroker, DsnHelper, abc.ABC): """Base class for Postgres brokers.""" - def __init__( + def __init__( # noqa: PLR0913 self, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", result_backend: AsyncResultBackend[_T] | None = None, @@ -26,6 +26,9 @@ def __init__( max_retry_attempts: int = 5, read_kwargs: dict[str, tp.Any] | None = None, write_kwargs: dict[str, tp.Any] | None = None, + *, + listen_keepalive_interval: float | None = 30.0, + listen_keepalive_timeout: float = 5.0, ) -> None: """ Construct a new broker. @@ -39,7 +42,18 @@ def __init__( max_retry_attempts: Maximum number of message processing attempts. read_kwargs: Additional arguments for read connection creation. write_kwargs: Additional arguments for write pool creation. + listen_keepalive_interval: How often, in seconds, to run a query on the broker-owned LISTEN + connection. It keeps proxies and `idle_session_timeout` from closing an idle connection + and detects a connection that hangs without being closed. None disables the check. + listen_keepalive_timeout: How long, in seconds, to wait for the answer before treating + the LISTEN connection as lost and reconnecting. """ + if listen_keepalive_interval is not None and listen_keepalive_interval <= 0: + msg = "listen_keepalive_interval must be positive or None" + raise ValueError(msg) + if listen_keepalive_timeout <= 0: + msg = "listen_keepalive_timeout must be positive" + raise ValueError(msg) super().__init__( result_backend=result_backend, task_id_generator=task_id_generator, @@ -50,4 +64,10 @@ def __init__( self.read_kwargs: dict[str, tp.Any] = read_kwargs or {} self.write_kwargs: dict[str, tp.Any] = write_kwargs or {} self.max_retry_attempts: int = max_retry_attempts + self.listen_keepalive_interval: float | None = listen_keepalive_interval + self.listen_keepalive_timeout: float = listen_keepalive_timeout self._queue: asyncio.Queue[str] | None = None + + +LISTEN_KEEPALIVE_QUERY = "SELECT 1 /* taskiq-pg LISTEN keepalive */" +"""Query used to check a LISTEN connection; the comment makes it recognizable in pg_stat_activity.""" diff --git a/src/taskiq_pg/_internal/tasks.py b/src/taskiq_pg/_internal/tasks.py index 3b617a1..a06aebd 100644 --- a/src/taskiq_pg/_internal/tasks.py +++ b/src/taskiq_pg/_internal/tasks.py @@ -16,3 +16,22 @@ async def cancel_and_wait(task: asyncio.Task[tp.Any]) -> None: current = asyncio.current_task() if current is not None and current.cancelling(): raise + + +async def run_until_first_done(*coroutines: tp.Coroutine[tp.Any, tp.Any, tp.Any]) -> None: + """ + Run coroutines concurrently until the first one finishes, then cancel the others. + + The exception of the first finished coroutine, if any, is raised. If the caller is cancelled, + all coroutines are cancelled and awaited before the cancellation propagates. + """ + tasks = [asyncio.create_task(coroutine) for coroutine in coroutines] + try: + done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + finally: + pending = [task for task in tasks if not task.done()] + for task in pending: + task.cancel() + await asyncio.gather(*pending, return_exceptions=True) + for task in done: + task.result() diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index 53ff355..0026425 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -7,9 +7,9 @@ import aiopg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker from taskiq_pg._internal.retry import retry_delays -from taskiq_pg._internal.tasks import cancel_and_wait +from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.aiopg.queries import ( CLAIM_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, @@ -47,6 +47,8 @@ def __init__( *, write_pool: None = ..., read_connection: None = ..., + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... @tp.overload @@ -63,6 +65,8 @@ def __init__( *, write_pool: aiopg.Pool, read_connection: None = ..., + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... @tp.overload @@ -79,6 +83,8 @@ def __init__( *, write_pool: None = ..., read_connection: aiopg.Connection, + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... @tp.overload @@ -95,6 +101,8 @@ def __init__( *, write_pool: aiopg.Pool, read_connection: aiopg.Connection, + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -110,6 +118,8 @@ def __init__( # noqa: PLR0913 *, write_pool: aiopg.Pool | None = None, read_connection: aiopg.Connection | None = None, + listen_keepalive_interval: float | None = 30.0, + listen_keepalive_timeout: float = 5.0, ) -> None: """ Construct a new AiopgBroker. @@ -126,6 +136,9 @@ def __init__( # noqa: PLR0913 write_pool: An existing connection pool to reuse for writes. read_connection: An existing connection to reuse for LISTEN. Its lifecycle, including reconnection, remains the caller's responsibility. + listen_keepalive_interval: How often, in seconds, to check the broker-owned LISTEN connection + with a query; None disables the check. + listen_keepalive_timeout: How long, in seconds, to wait for the check before reconnecting. """ super().__init__( dsn=dsn, @@ -136,6 +149,8 @@ def __init__( # noqa: PLR0913 max_retry_attempts=max_retry_attempts, read_kwargs=read_kwargs, write_kwargs=write_kwargs, + listen_keepalive_interval=listen_keepalive_interval, + listen_keepalive_timeout=listen_keepalive_timeout, ) self._owns_write_pool = True @@ -203,11 +218,10 @@ async def _consume_notifications(self) -> None: while self._read_conn is not None: conn = self._read_conn try: - while True: - notify = await conn.notifies.get() - logger.debug("Received notification on channel %s: %s", notify.channel, notify.payload) - if self._queue is not None: - self._queue.put_nowait(notify.payload) + if self.listen_keepalive_interval is None or not self._owns_read_conn: + await self._move_notifications(conn) + else: + await run_until_first_done(self._move_notifications(conn), self._keepalive()) except Exception: if not self._owns_read_conn: logger.warning( @@ -220,6 +234,32 @@ async def _consume_notifications(self) -> None: await conn.close() self._read_conn = await self._restore_listener() + async def _move_notifications(self, conn: aiopg.Connection) -> None: + """Move notifications into the queue until the connection is lost.""" + while True: + notify = await conn.notifies.get() + logger.debug("Received notification on channel %s: %s", notify.channel, notify.payload) + if self._queue is not None: + self._queue.put_nowait(notify.payload) + + async def _keepalive(self) -> None: + """Run the keepalive query every interval; raise when it does not answer in time.""" + interval = self.listen_keepalive_interval + if interval is None: + return + while True: + await asyncio.sleep(interval) + try: + await asyncio.wait_for(self._keepalive_query(), self.listen_keepalive_timeout) + except TimeoutError as exc: + msg = "LISTEN connection did not answer a keepalive query" + raise ConnectionError(msg) from exc + + async def _keepalive_query(self) -> None: + """Run a trivial query on the LISTEN connection.""" + if self._read_conn is not None: + await self._execute(self._read_conn, LISTEN_KEEPALIVE_QUERY) + async def _restore_listener(self) -> aiopg.Connection: """Open a new LISTEN connection, retrying with randomized delays of up to 30 seconds.""" delays = retry_delays() diff --git a/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index 2805e82..39b3210 100644 --- a/src/taskiq_pg/asyncpg/broker.py +++ b/src/taskiq_pg/asyncpg/broker.py @@ -7,7 +7,7 @@ import asyncpg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.asyncpg.queries import ( @@ -47,6 +47,8 @@ def __init__( *, write_pool: None = ..., read_connection: None = ..., + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... @tp.overload @@ -63,6 +65,8 @@ def __init__( *, write_pool: asyncpg.pool.Pool, read_connection: None = ..., + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... @tp.overload @@ -79,6 +83,8 @@ def __init__( *, write_pool: None = ..., read_connection: asyncpg.Connection, + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... @tp.overload @@ -95,6 +101,8 @@ def __init__( *, write_pool: asyncpg.pool.Pool, read_connection: asyncpg.Connection, + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -110,6 +118,8 @@ def __init__( # noqa: PLR0913 *, write_pool: asyncpg.pool.Pool | None = None, read_connection: asyncpg.Connection | None = None, + listen_keepalive_interval: float | None = 30.0, + listen_keepalive_timeout: float = 5.0, ) -> None: """ Construct a new AsyncpgBroker. @@ -126,6 +136,9 @@ def __init__( # noqa: PLR0913 write_pool: An existing connection pool to reuse for writes. read_connection: An existing connection to reuse for LISTEN. Its lifecycle, including reconnection, remains the caller's responsibility. + listen_keepalive_interval: How often, in seconds, to check the broker-owned LISTEN connection + with a query; None disables the check. + listen_keepalive_timeout: How long, in seconds, to wait for the check before reconnecting. """ super().__init__( dsn=dsn, @@ -136,6 +149,8 @@ def __init__( # noqa: PLR0913 max_retry_attempts=max_retry_attempts, read_kwargs=read_kwargs, write_kwargs=write_kwargs, + listen_keepalive_interval=listen_keepalive_interval, + listen_keepalive_timeout=listen_keepalive_timeout, ) self._owns_write_pool = True @@ -215,7 +230,7 @@ def _connection_terminated( async def _restore_listener(self) -> None: """Restore LISTEN after disconnection, retrying with randomized delays of up to 30 seconds.""" while True: - await self._listener_disconnected.wait() + await self._wait_for_disconnection() delays = retry_delays() while True: try: @@ -228,6 +243,39 @@ async def _restore_listener(self) -> None: logger.info("LISTEN connection restored on channel %s", self.channel_name) break + async def _wait_for_disconnection(self) -> None: + """Wait until the LISTEN connection is closed or, if it is broker-owned, stops answering keepalive queries.""" + interval = self.listen_keepalive_interval + if interval is None or not self._owns_read_conn: + await self._listener_disconnected.wait() + return + while True: + try: + await asyncio.wait_for(self._listener_disconnected.wait(), interval) + except TimeoutError: + pass + else: + return + conn = self._read_conn + if conn is None: + return + try: + await asyncio.wait_for(self._keepalive_query(), self.listen_keepalive_timeout) + except Exception: + logger.warning( + "LISTEN connection on channel %s did not answer a keepalive query; reconnecting", + self.channel_name, + exc_info=True, + ) + conn.remove_termination_listener(self._connection_terminated) + conn.terminate() + return + + async def _keepalive_query(self) -> None: + """Run a trivial query on the LISTEN connection.""" + if self._read_conn is not None: + await self._read_conn.fetchval(LISTEN_KEEPALIVE_QUERY) + def _notification_handler( self, con_ref: asyncpg.Connection | asyncpg.pool.PoolConnectionProxy, # noqa: ARG002 diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index d15272f..eb8f200 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -11,9 +11,9 @@ from psqlpy.extra_types import JSONB from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker from taskiq_pg._internal.retry import retry_delays -from taskiq_pg._internal.tasks import cancel_and_wait +from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.psqlpy.queries import ( CLAIM_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, @@ -49,7 +49,7 @@ class PSQLPyBroker(BasePostgresBroker): _queue: asyncio.Queue _owns_write_pool: bool - def __init__( + def __init__( # noqa: PLR0913 self, dsn: str | Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", result_backend: AsyncResultBackend[_T] | None = None, @@ -60,6 +60,8 @@ def __init__( write_kwargs: dict[str, tp.Any] | None = None, *, write_pool: psqlpy.ConnectionPool | None = None, + listen_keepalive_interval: float | None = 30.0, + listen_keepalive_timeout: float = 5.0, ) -> None: """ Construct a new PSQLPyBroker. @@ -75,6 +77,9 @@ def __init__( max_retry_attempts: Maximum number of message processing attempts. write_kwargs: Extra kwargs forwarded to `psqlpy.ConnectionPool()` write_pool: An existing pool to reuse for writes and LISTEN. + listen_keepalive_interval: How often, in seconds, to check the broker-owned LISTEN connection + with a query; None disables the check. + listen_keepalive_timeout: How long, in seconds, to wait for the check before reconnecting. """ super().__init__( dsn=dsn, @@ -84,6 +89,8 @@ def __init__( table_name=table_name, max_retry_attempts=max_retry_attempts, write_kwargs=write_kwargs, + listen_keepalive_interval=listen_keepalive_interval, + listen_keepalive_timeout=listen_keepalive_timeout, ) self._owns_write_pool = True @@ -152,13 +159,10 @@ async def _consume_notifications(self) -> None: """Move notifications into the queue and restore LISTEN after connection loss.""" while True: try: - async for message in self._listener: - await self._notification_handler( - message.connection, - message.payload, - message.channel, - message.process_id, - ) + if self.listen_keepalive_interval is None: + await self._move_notifications(self._listener) + else: + await run_until_first_done(self._move_notifications(self._listener), self._keepalive()) except Exception: logger.warning("LISTEN connection lost on channel %s; reconnecting", self.channel_name, exc_info=True) else: @@ -167,6 +171,33 @@ async def _consume_notifications(self) -> None: await self._listener.shutdown() self._listener = await self._restore_listener() + async def _move_notifications(self, listener: psqlpy.Listener) -> None: + """Move notifications from the listener into the queue until it stops or its connection is lost.""" + async for message in listener: + await self._notification_handler( + message.connection, + message.payload, + message.channel, + message.process_id, + ) + + async def _keepalive(self) -> None: + """Run the keepalive query every interval; raise when it does not answer in time.""" + interval = self.listen_keepalive_interval + if interval is None: + return + while True: + await asyncio.sleep(interval) + try: + await asyncio.wait_for(self._keepalive_query(), self.listen_keepalive_timeout) + except TimeoutError as exc: + msg = "LISTEN connection did not answer a keepalive query" + raise ConnectionError(msg) from exc + + async def _keepalive_query(self) -> None: + """Run a trivial query on the listener connection.""" + await self._listener.connection.execute(LISTEN_KEEPALIVE_QUERY) + async def _restore_listener(self) -> psqlpy.Listener: """Create a new listener, retrying with randomized delays of up to 30 seconds.""" delays = retry_delays() diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 1e5b3af..8466b0f 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -10,7 +10,7 @@ from psycopg_pool import AsyncConnectionPool from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker from taskiq_pg._internal.retry import retry_delays from taskiq_pg.psycopg.queries import ( CLAIM_MESSAGE_QUERY, @@ -25,6 +25,12 @@ _T = tp.TypeVar("_T") +def _retrieve_exception(task: asyncio.Future[tp.Any]) -> None: + """Mark an abandoned task's exception as retrieved, so asyncio does not log it.""" + if not task.cancelled(): + task.exception() + + class PsycopgBroker(BasePostgresBroker): """Broker that uses PostgreSQL and psycopg with LISTEN/NOTIFY.""" @@ -34,6 +40,7 @@ class PsycopgBroker(BasePostgresBroker): _owns_write_pool: bool _owns_read_conn: bool _closing: bool = False + _unanswered_keepalive: asyncio.Task[None] | None = None @tp.overload def __init__( @@ -49,6 +56,8 @@ def __init__( *, write_pool: None = ..., read_connection: None = ..., + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... @tp.overload @@ -65,6 +74,8 @@ def __init__( *, write_pool: AsyncConnectionPool, read_connection: None = ..., + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... @tp.overload @@ -81,6 +92,8 @@ def __init__( *, write_pool: None = ..., read_connection: AsyncConnection, + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... @tp.overload @@ -97,6 +110,8 @@ def __init__( *, write_pool: AsyncConnectionPool, read_connection: AsyncConnection, + listen_keepalive_interval: float | None = ..., + listen_keepalive_timeout: float = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -112,6 +127,8 @@ def __init__( # noqa: PLR0913 *, write_pool: AsyncConnectionPool | None = None, read_connection: AsyncConnection | None = None, + listen_keepalive_interval: float | None = 30.0, + listen_keepalive_timeout: float = 5.0, ) -> None: """ Construct a new PsycopgBroker. @@ -128,6 +145,9 @@ def __init__( # noqa: PLR0913 write_pool: An existing connection pool to reuse for writes. read_connection: An existing connection to reuse for LISTEN. Its lifecycle, including reconnection, remains the caller's responsibility. + listen_keepalive_interval: How often, in seconds, to check the broker-owned LISTEN connection + with a query; None disables the check. + listen_keepalive_timeout: How long, in seconds, to wait for the check before reconnecting. """ super().__init__( dsn=dsn, @@ -138,6 +158,8 @@ def __init__( # noqa: PLR0913 max_retry_attempts=max_retry_attempts, read_kwargs=read_kwargs, write_kwargs=write_kwargs, + listen_keepalive_interval=listen_keepalive_interval, + listen_keepalive_timeout=listen_keepalive_timeout, ) self._owns_write_pool = True @@ -196,7 +218,7 @@ async def _restore_listener(self) -> bool: Returns False without reconnecting when the broker is shutting down. """ - await self._read_conn.close() + await self._close_read_conn() delays = retry_delays() while not self._is_closing(): try: @@ -213,6 +235,13 @@ async def _restore_listener(self) -> bool: return True return False + async def _close_read_conn(self) -> None: + """Close the LISTEN connection, then cancel a keepalive query it never answered.""" + await self._read_conn.close() + if self._unanswered_keepalive is not None: + self._unanswered_keepalive.cancel() + self._unanswered_keepalive = None + def _is_closing(self) -> bool: """ Tell whether shutdown() has started. @@ -231,7 +260,7 @@ async def shutdown(self) -> None: await self._notifies_iter.aclose() # type: ignore[attr-defined] if self._read_conn is not None and self._owns_read_conn: await self._read_conn.notifies().aclose() - await self._read_conn.close() + await self._close_read_conn() if self._write_pool is not None and self._owns_write_pool: await self._write_pool.close() @@ -287,11 +316,57 @@ async def _schedule_notification(self, message_id: int, delay_seconds: int) -> N ) ) + async def _notifications(self) -> AsyncGenerator[str, None]: + """ + Yield notification payloads from the current LISTEN connection. + + A broker-owned connection is read in slices of `listen_keepalive_interval` seconds with a + keepalive query in between; a query that does not answer in time raises OperationalError. + """ + interval = self.listen_keepalive_interval + if interval is None or not self._owns_read_conn: + async for notify in self._notifies_iter: + yield notify.payload + return + while not self._is_closing(): + self._notifies_iter = self._read_conn.notifies(timeout=interval) + async for notify in self._notifies_iter: + yield notify.payload + if self._is_closing(): + return + await self._check_listener() + + async def _check_listener(self) -> None: + """ + Run the keepalive query; raise OperationalError if it does not answer in time. + + The unanswered query is not cancelled here: psycopg waits for the server to acknowledge + a cancellation, which a hung connection never does. It is cancelled once the connection + is closed. + """ + query = asyncio.ensure_future(self._keepalive_query()) + query.add_done_callback(_retrieve_exception) + try: + done, _ = await asyncio.wait({query}, timeout=self.listen_keepalive_timeout) + except asyncio.CancelledError: + query.cancel() + raise + if query in done: + query.result() + return + self._unanswered_keepalive = query + msg = "LISTEN connection did not answer a keepalive query" + raise psycopg.OperationalError(msg) + + async def _keepalive_query(self) -> None: + """Run a trivial query on the LISTEN connection.""" + await self._read_conn.execute(LISTEN_KEEPALIVE_QUERY) + async def _listen_context(self) -> AsyncGenerator[str, None]: while True: try: - async for notify in self._notifies_iter: - yield notify.payload + async for payload in self._notifications(): + yield payload except psycopg.OperationalError: # noqa: PERF203 if self._closing: # the connection was closed by shutdown() return diff --git a/tests/integration/test_listen_keepalive.py b/tests/integration/test_listen_keepalive.py new file mode 100644 index 0000000..59616ee --- /dev/null +++ b/tests/integration/test_listen_keepalive.py @@ -0,0 +1,211 @@ +import asyncio +import typing as tp +import uuid + +import asyncpg +import pytest +from taskiq import BrokerMessage + +from tests.integration.test_listener_reconnect import listen_backends + +from taskiq_pg.aiopg import AiopgBroker +from taskiq_pg.asyncpg import AsyncpgBroker +from taskiq_pg.psqlpy import PSQLPyBroker +from taskiq_pg.psycopg import PsycopgBroker + + +Broker: tp.TypeAlias = AsyncpgBroker | PsycopgBroker | PSQLPyBroker | AiopgBroker + +FAST_KEEPALIVE: dict[str, tp.Any] = {"listen_keepalive_interval": 0.2, "listen_keepalive_timeout": 0.5} + + +# Make the server close the LISTEN session after one second without client queries. +async def alive(connection: asyncpg.Connection, pids: set[int]) -> set[int]: + """Return which of the backends still exist (a LISTEN backend's last query may be the keepalive query).""" + rows = await connection.fetch("SELECT pid FROM pg_stat_activity WHERE pid = ANY($1::int[])", list(pids)) + return {row["pid"] for row in rows} + + +async def wait_until_gone(connection: asyncpg.Connection, pids: set[int]) -> None: + while await alive(connection, pids): # noqa: ASYNC110 + await asyncio.sleep(0.05) + + +async def kick_until_received(broker: Broker, task: asyncio.Task[tp.Any], timeout: float) -> set[bytes]: + """ + Kick messages until the worker receives one and return the kicked payloads. + + The replacement LISTEN connection may not be listening yet when the old one is gone, + and PostgreSQL drops a NOTIFY sent before LISTEN. + """ + kicked: set[bytes] = set() + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while not task.done() and loop.time() < deadline: + payload = f'{{"restored":{len(kicked)}}}'.encode() + message = BrokerMessage( + task_id=uuid.uuid4().hex, + task_name="example:after_keepalive", + message=payload, + labels={}, + ) + await broker.kick(message) + kicked.add(payload) + await asyncio.wait({task}, timeout=0.3) + return kicked + + +IDLE_TIMEOUT_READ_KWARGS: list[tp.Any] = [ + pytest.param(AsyncpgBroker, {"server_settings": {"idle_session_timeout": "1000"}}, id="AsyncpgBroker"), + pytest.param(PsycopgBroker, {"options": "-c idle_session_timeout=1000"}, id="PsycopgBroker"), + pytest.param(AiopgBroker, {"options": "-c idle_session_timeout=1000"}, id="AiopgBroker"), +] + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker]) +async def test_when_keepalive_query_hangs__then_listener_reconnects( + pg_dsn: str, + connection: asyncpg.Connection, + monkeypatch: pytest.MonkeyPatch, + broker_class: type[Broker], +) -> None: + # given + channel = f"keepalive_{uuid.uuid4().hex}" + broker = broker_class(dsn=pg_dsn, channel_name=channel, **FAST_KEEPALIVE) + keepalive_query = broker._keepalive_query # noqa: SLF001 + hung = asyncio.Event() + + async def hang_once() -> None: + """Hang like a connection that silently stopped answering, then behave normally.""" + if not hung.is_set(): + hung.set() + await asyncio.Future() + await keepalive_query() + + monkeypatch.setattr(broker, "_keepalive_query", hang_once) + await broker.startup() + listener = broker.listen() + task: asyncio.Task[tp.Any] = asyncio.create_task(listener.__anext__()) + try: + original = await listen_backends(connection, channel) + + assert original + + # when + await asyncio.wait_for(hung.wait(), timeout=5) + await asyncio.wait_for(wait_until_gone(connection, original), timeout=5) + kicked = await kick_until_received(broker, task, timeout=10.0) + + # then + assert task.done(), "Worker should receive a message kicked after the hung connection was replaced" + assert task.result().data in kicked + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await broker.shutdown() + + +async def _listen_backends_after_idle_period( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], + read_kwargs: dict[str, tp.Any], + keepalive_interval: float | None, +) -> tuple[set[int], set[int]]: + """Return the LISTEN backends right after startup and which of them survived the server's idle timeout twice.""" + channel = f"keepalive_{uuid.uuid4().hex}" + broker = broker_class( + dsn=pg_dsn, + channel_name=channel, + read_kwargs=read_kwargs, + listen_keepalive_interval=keepalive_interval, + listen_keepalive_timeout=1.0, + ) + await broker.startup() + listener = broker.listen() + task: asyncio.Task[tp.Any] = asyncio.create_task(listener.__anext__()) + try: + original = await listen_backends(connection, channel) + await asyncio.sleep(2.5) + return original, await alive(connection, original) + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize(("broker_class", "read_kwargs"), IDLE_TIMEOUT_READ_KWARGS) +async def test_when_server_closes_idle_sessions__then_keepalive_keeps_listen_connection_open( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], + read_kwargs: dict[str, tp.Any], +) -> None: + # when + original, after = await _listen_backends_after_idle_period(pg_dsn, connection, broker_class, read_kwargs, 0.3) + + # then + assert original + assert after == original, "The LISTEN connection should survive the server's idle timeout" + + +@pytest.mark.integration +@pytest.mark.parametrize(("broker_class", "read_kwargs"), IDLE_TIMEOUT_READ_KWARGS) +async def test_when_server_closes_idle_sessions_without_keepalive__then_listen_connection_is_closed( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], + read_kwargs: dict[str, tp.Any], +) -> None: + """Control case: proves that the idle timeout in read_kwargs really closes the LISTEN connection.""" + # when + original, after = await _listen_backends_after_idle_period(pg_dsn, connection, broker_class, read_kwargs, None) + + # then + assert original + assert not after, "Without keepalive the server should have closed the idle LISTEN connection" + + +@pytest.mark.integration +async def test_when_psycopg_keepalive_query_ignores_cancellation__then_hang_is_detected_in_time( + pg_dsn: str, + connection: asyncpg.Connection, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + A cancelled psycopg query waits for the server to acknowledge it, which a hung connection never does. + + The broker must not wait for that: the stub below ignores the first cancellation like such a query. + """ + # given + channel = f"keepalive_{uuid.uuid4().hex}" + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, **FAST_KEEPALIVE) + keepalive_query = broker._keepalive_query # noqa: SLF001 + hung = asyncio.Event() + + async def stubborn_once() -> None: + if not hung.is_set(): + hung.set() + try: + await asyncio.Future() + except asyncio.CancelledError: + await asyncio.sleep(10) # keeps "waiting for the server" after being cancelled + raise + await keepalive_query() + + monkeypatch.setattr(broker, "_keepalive_query", stubborn_once) + await broker.startup() + listener = broker.listen() + task: asyncio.Task[tp.Any] = asyncio.create_task(listener.__anext__()) + try: + original = await listen_backends(connection, channel) + await asyncio.wait_for(hung.wait(), timeout=5) + + # when / then + await asyncio.wait_for(wait_until_gone(connection, original), timeout=3) + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await broker.shutdown() diff --git a/tests/unit/test_listen_keepalive_params.py b/tests/unit/test_listen_keepalive_params.py new file mode 100644 index 0000000..99284cb --- /dev/null +++ b/tests/unit/test_listen_keepalive_params.py @@ -0,0 +1,52 @@ +import typing as tp + +import pytest + +from taskiq_pg.aiopg import AiopgBroker +from taskiq_pg.asyncpg import AsyncpgBroker +from taskiq_pg.psqlpy import PSQLPyBroker +from taskiq_pg.psycopg import PsycopgBroker + + +BROKERS: list[tp.Any] = [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker] + + +@pytest.mark.unit +@pytest.mark.parametrize("broker_class", BROKERS) +def test_when_broker_is_created__then_keepalive_is_enabled_by_default(broker_class: tp.Any) -> None: + # when + broker = broker_class() + + # then + assert broker.listen_keepalive_interval == 30.0 + assert broker.listen_keepalive_timeout == 5.0 + + +@pytest.mark.unit +@pytest.mark.parametrize("broker_class", BROKERS) +def test_when_keepalive_interval_is_none__then_keepalive_is_disabled(broker_class: tp.Any) -> None: + # when + broker = broker_class(listen_keepalive_interval=None) + + # then + assert broker.listen_keepalive_interval is None + + +@pytest.mark.unit +@pytest.mark.parametrize("broker_class", BROKERS) +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"listen_keepalive_interval": 0}, "listen_keepalive_interval"), + ({"listen_keepalive_interval": -1}, "listen_keepalive_interval"), + ({"listen_keepalive_timeout": 0}, "listen_keepalive_timeout"), + ], +) +def test_when_keepalive_settings_are_invalid__then_error_is_raised( + broker_class: tp.Any, + kwargs: dict[str, float], + match: str, +) -> None: + # when / then + with pytest.raises(ValueError, match=match): + broker_class(**kwargs) diff --git a/tests/unit/test_run_until_first_done.py b/tests/unit/test_run_until_first_done.py new file mode 100644 index 0000000..4d34b4d --- /dev/null +++ b/tests/unit/test_run_until_first_done.py @@ -0,0 +1,57 @@ +import asyncio + +import pytest + +from taskiq_pg._internal.tasks import run_until_first_done + + +async def forever(cancelled: list[str], name: str) -> None: + try: + await asyncio.Future() + except asyncio.CancelledError: + cancelled.append(name) + raise + + +@pytest.mark.unit +async def test_when_one_coroutine_finishes__then_the_others_are_cancelled() -> None: + # given + cancelled: list[str] = [] + + # when + await run_until_first_done(asyncio.sleep(0.01), forever(cancelled, "a"), forever(cancelled, "b")) + + # then + assert sorted(cancelled) == ["a", "b"] + + +@pytest.mark.unit +async def test_when_one_coroutine_fails__then_its_error_is_raised_and_the_others_are_cancelled() -> None: + # given + cancelled: list[str] = [] + + async def fail() -> None: + await asyncio.sleep(0.01) + msg = "connection lost" + raise ConnectionError(msg) + + # when / then + with pytest.raises(ConnectionError, match="connection lost"): + await run_until_first_done(fail(), forever(cancelled, "a")) + assert cancelled == ["a"] + + +@pytest.mark.unit +async def test_when_caller_is_cancelled__then_all_coroutines_are_cancelled() -> None: + # given + cancelled: list[str] = [] + runner = asyncio.create_task(run_until_first_done(forever(cancelled, "a"), forever(cancelled, "b"))) + await asyncio.sleep(0.01) + + # when + runner.cancel() + await asyncio.gather(runner, return_exceptions=True) + + # then + assert runner.cancelled() + assert sorted(cancelled) == ["a", "b"]