diff --git a/src/taskiq_pg/_internal/broker.py b/src/taskiq_pg/_internal/broker.py index 5377f2e..48b2e53 100644 --- a/src/taskiq_pg/_internal/broker.py +++ b/src/taskiq_pg/_internal/broker.py @@ -1,4 +1,5 @@ import abc +import hashlib import typing as tp from taskiq import AsyncBroker, AsyncResultBackend @@ -29,6 +30,7 @@ def __init__( # noqa: PLR0913 *, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new broker. @@ -47,6 +49,9 @@ def __init__( # noqa: PLR0913 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. + poll_interval: How often, in seconds, a listening worker looks for pending messages whose + NOTIFY it missed (sent while it was not listening or reconnecting), including delayed + messages whose delay has elapsed. It also polls right after start and after reconnecting. """ if listen_keepalive_interval is not None and listen_keepalive_interval <= 0: msg = "listen_keepalive_interval must be positive or None" @@ -54,6 +59,9 @@ def __init__( # noqa: PLR0913 if listen_keepalive_timeout <= 0: msg = "listen_keepalive_timeout must be positive" raise ValueError(msg) + if poll_interval <= 0: + msg = "poll_interval must be positive" + raise ValueError(msg) super().__init__( result_backend=result_backend, task_id_generator=task_id_generator, @@ -66,8 +74,23 @@ def __init__( # noqa: PLR0913 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.poll_interval: float = poll_interval 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.""" + +POLL_NOW = "" +"""Queue item that asks a listening worker to poll for pending messages right away (never a message id).""" + + +def schema_lock_query(table_name: str) -> str: + """ + Return a query that serializes schema setup of one messages table. + + Run it first in the transaction that creates the table and its indexes: brokers that start at the same + time then wait for each other instead of failing on concurrent `CREATE ... IF NOT EXISTS`. + """ + digest = hashlib.sha256(f"taskiq_pg:messages:{table_name}".encode()).digest() + return f"SELECT pg_advisory_xact_lock({int.from_bytes(digest[:8], 'big', signed=True)})" diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index 0026425..7accc20 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -7,12 +7,14 @@ import aiopg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.aiopg.queries import ( CLAIM_MESSAGE_QUERY, + CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, + CREATE_PENDING_INDEX_QUERY, DELETE_MESSAGE_QUERY, INSERT_MESSAGE_QUERY, ) @@ -49,6 +51,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -67,6 +70,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -85,6 +89,7 @@ def __init__( read_connection: aiopg.Connection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -103,6 +108,7 @@ def __init__( read_connection: aiopg.Connection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -120,6 +126,7 @@ def __init__( # noqa: PLR0913 read_connection: aiopg.Connection | None = None, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new AiopgBroker. @@ -139,6 +146,7 @@ def __init__( # noqa: PLR0913 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. + poll_interval: How often, in seconds, to look for pending messages whose NOTIFY was missed. """ super().__init__( dsn=dsn, @@ -151,6 +159,7 @@ def __init__( # noqa: PLR0913 write_kwargs=write_kwargs, listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, + poll_interval=poll_interval, ) self._owns_write_pool = True @@ -172,7 +181,18 @@ async def startup(self) -> None: if self._write_pool is None: self._write_pool = await aiopg.create_pool(self.dsn, **self.write_kwargs) async with self._write_pool.acquire() as conn, conn.cursor() as cursor: - await cursor.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + # aiopg connections are always in autocommit mode, so the transaction is explicit. + await cursor.execute("BEGIN") + try: + await cursor.execute(schema_lock_query(self.table_name)) + await cursor.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + await cursor.execute( + CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + ) + except BaseException: + await cursor.execute("ROLLBACK") + raise + await cursor.execute("COMMIT") if self._owns_read_conn: self._read_conn = await self._connect_listener() elif self._read_conn is not None: @@ -233,6 +253,8 @@ async def _consume_notifications(self) -> None: logger.warning("LISTEN connection lost on channel %s; reconnecting", self.channel_name, exc_info=True) await conn.close() self._read_conn = await self._restore_listener() + if self._queue is not None: # notifications sent while reconnecting were missed + self._queue.put_nowait(POLL_NOW) async def _move_notifications(self, conn: aiopg.Connection) -> None: """Move notifications into the queue until the connection is lost.""" @@ -286,6 +308,10 @@ async def kick(self, message: BrokerMessage) -> None: msg = "Please run startup before kicking." raise ValueError(msg) + # Parse the delay before inserting, so a malformed label does not leave a message behind. + delay_value = message.labels.get("delay") + delay_seconds = None if delay_value is None else int(delay_value) + async with self._write_pool.acquire() as conn, conn.cursor() as cursor: await cursor.execute( INSERT_MESSAGE_QUERY.format(self.table_name), @@ -297,13 +323,12 @@ async def kick(self, message: BrokerMessage) -> None: raise RuntimeError(msg) message_id = int(row[0]) - delay_value = message.labels.get("delay") - if delay_value is None: + if delay_seconds is None: # Send a NOTIFY with the message ID as payload await cursor.execute(f"NOTIFY {self.channel_name}, %s", (str(message_id),)) return - task = asyncio.create_task(self._schedule_notification(message_id, int(delay_value))) + task = asyncio.create_task(self._schedule_notification(message_id, delay_seconds)) self._notify_tasks.add(task) task.add_done_callback(self._notify_tasks.discard) @@ -330,29 +355,54 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: msg = "Startup did not initialize the queue." raise ValueError(msg) + queue = self._queue + loop = asyncio.get_running_loop() + next_poll = loop.time() # poll right away: messages may have been kicked while nobody listened while True: try: - payload = await self._queue.get() - message_id = int(payload) - async with self._write_pool.acquire() as conn, conn.cursor() as cursor: - await cursor.execute(CLAIM_MESSAGE_QUERY.format(self.table_name), (message_id,)) - claimed = await cursor.fetchone() - if claimed is None: + if loop.time() >= next_poll: + next_poll = loop.time() + self.poll_interval + while ( + claimed := await self._claim(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name)) + ) is not None: + yield self._ackable(claimed) + continue + try: + payload = await asyncio.wait_for(queue.get(), next_poll - loop.time()) + except TimeoutError: continue - message_str = claimed[1] - if not isinstance(message_str, str): - msg = "message is not a string" - raise TypeError(msg) - message_data = message_str.encode() - - async def ack(*, _message_id: int = message_id) -> None: - if self._write_pool is None: - msg = "Call startup before starting listening." - raise ValueError(msg) - async with self._write_pool.acquire() as conn, conn.cursor() as cursor: - await cursor.execute(DELETE_MESSAGE_QUERY.format(self.table_name), (_message_id,)) - - yield AckableMessage(data=message_data, ack=ack) + if payload == POLL_NOW: + next_poll = loop.time() + continue + claimed = await self._claim(CLAIM_MESSAGE_QUERY.format(self.table_name), (int(payload),)) + if claimed is not None: + yield self._ackable(claimed) except Exception: logger.exception("Error processing message") continue + + async def _claim(self, query: str, params: tuple[tp.Any, ...] = ()) -> tuple[tp.Any, ...] | None: + """Run a claim query and return the claimed (id, message) row, if any.""" + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn, conn.cursor() as cursor: + await cursor.execute(query, params) + return tp.cast("tuple[tp.Any, ...] | None", await cursor.fetchone()) + + def _ackable(self, claimed: tuple[tp.Any, ...]) -> AckableMessage: + """Wrap a claimed message; acknowledging it deletes the row.""" + message_id = int(claimed[0]) + message_str = claimed[1] + if not isinstance(message_str, str): + msg = "message is not a string" + raise TypeError(msg) + + async def ack() -> None: + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn, conn.cursor() as cursor: + await cursor.execute(DELETE_MESSAGE_QUERY.format(self.table_name), (message_id,)) + + return AckableMessage(data=message_str.encode(), ack=ack) diff --git a/src/taskiq_pg/aiopg/queries.py b/src/taskiq_pg/aiopg/queries.py index 30431dc..7112254 100644 --- a/src/taskiq_pg/aiopg/queries.py +++ b/src/taskiq_pg/aiopg/queries.py @@ -99,3 +99,23 @@ CLAIM_MESSAGE_QUERY = "UPDATE {} SET status = 'processing' WHERE id = %s AND status = 'pending' RETURNING id, message" DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = %s" + +CREATE_PENDING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (id) WHERE status = 'pending'" + +CLAIM_NEXT_READY_MESSAGE_QUERY = """ +UPDATE {table} SET status = 'processing' +WHERE id = ( + SELECT id FROM {table} + WHERE status = 'pending' + AND created_at + make_interval(secs => CASE + -- a label that is not a plain number must not break the query for every other row + WHEN labels->>'delay' ~ '^[0-9]{{1,10}}(\\.[0-9]+)?$' THEN (labels->>'delay')::double precision + WHEN labels->>'delay' ~ '^[0-9]+(\\.[0-9]+)?$' THEN 1e10 -- over 300 years: never ready + ELSE 0 + END) <= now() + ORDER BY id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING id, message +""" diff --git a/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index 39b3210..632490d 100644 --- a/src/taskiq_pg/asyncpg/broker.py +++ b/src/taskiq_pg/asyncpg/broker.py @@ -7,12 +7,14 @@ import asyncpg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.asyncpg.queries import ( CLAIM_MESSAGE_QUERY, + CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, + CREATE_PENDING_INDEX_QUERY, DELETE_MESSAGE_QUERY, INSERT_MESSAGE_QUERY, ) @@ -49,6 +51,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -67,6 +70,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -85,6 +89,7 @@ def __init__( read_connection: asyncpg.Connection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -103,6 +108,7 @@ def __init__( read_connection: asyncpg.Connection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -120,6 +126,7 @@ def __init__( # noqa: PLR0913 read_connection: asyncpg.Connection | None = None, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new AsyncpgBroker. @@ -139,6 +146,7 @@ def __init__( # noqa: PLR0913 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. + poll_interval: How often, in seconds, to look for pending messages whose NOTIFY was missed. """ super().__init__( dsn=dsn, @@ -151,6 +159,7 @@ def __init__( # noqa: PLR0913 write_kwargs=write_kwargs, listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, + poll_interval=poll_interval, ) self._owns_write_pool = True @@ -170,8 +179,12 @@ async def startup(self) -> None: self._listener_disconnected = asyncio.Event() if self._write_pool is None: self._write_pool = await asyncpg.create_pool(self.dsn, **self.write_kwargs) - async with self._write_pool.acquire() as conn: + async with self._write_pool.acquire() as conn, conn.transaction(): + await conn.execute(schema_lock_query(self.table_name)) await conn.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + await conn.execute( + CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + ) await self._connect_listener() self._listener_task = asyncio.create_task(self._restore_listener()) @@ -241,6 +254,8 @@ async def _restore_listener(self) -> None: await asyncio.sleep(delay) else: logger.info("LISTEN connection restored on channel %s", self.channel_name) + if self._queue is not None: # notifications sent while reconnecting were missed + self._queue.put_nowait(POLL_NOW) break async def _wait_for_disconnection(self) -> None: @@ -310,6 +325,10 @@ async def kick(self, message: BrokerMessage) -> None: msg = "Please run startup before kicking." raise ValueError(msg) + # Parse the delay before inserting, so a malformed label does not leave a message behind. + delay_value = message.labels.get("delay") + delay_seconds = None if delay_value is None else int(delay_value) + async with self._write_pool.acquire() as conn: # Insert the message into the database message_inserted_id = tp.cast( @@ -323,9 +342,7 @@ async def kick(self, message: BrokerMessage) -> None: ), ) - delay_value = message.labels.get("delay") - if delay_value is not None: - delay_seconds = int(delay_value) + if delay_seconds is not None: _ = asyncio.create_task( # noqa: RUF006 self._schedule_notification(message_inserted_id, delay_seconds), ) @@ -359,35 +376,59 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: msg = "Startup did not initialize the queue." raise ValueError(msg) + queue = self._queue + loop = asyncio.get_running_loop() + next_poll = loop.time() # poll right away: messages may have been kicked while nobody listened while True: try: - payload = await self._queue.get() - message_id = int(payload) - async with self._write_pool.acquire() as conn: - claimed = await conn.fetchrow( - CLAIM_MESSAGE_QUERY.format(self.table_name), - message_id, - ) - if claimed is None: + if loop.time() >= next_poll: + next_poll = loop.time() + self.poll_interval + while (claimed := await self._claim_next_ready()) is not None: + yield self._ackable(claimed) + continue + try: + payload = await asyncio.wait_for(queue.get(), next_poll - loop.time()) + except TimeoutError: + continue + if payload == POLL_NOW: + next_poll = loop.time() continue - message_str = claimed["message"] - if not isinstance(message_str, str): - msg = "message is not a string" - raise TypeError(msg) - message_data = message_str.encode() - - async def ack(*, _message_id: int = message_id) -> None: - if self._write_pool is None: - msg = "Call startup before starting listening." - raise ValueError(msg) - - async with self._write_pool.acquire() as conn: - _ = await conn.execute( - DELETE_MESSAGE_QUERY.format(self.table_name), - _message_id, - ) - - yield AckableMessage(data=message_data, ack=ack) + claimed = await self._claim(int(payload)) + if claimed is not None: + yield self._ackable(claimed) except Exception: logger.exception("Error processing message") continue + + async def _claim(self, message_id: int) -> asyncpg.Record | None: + """Claim a pending message by its id.""" + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn: + return await conn.fetchrow(CLAIM_MESSAGE_QUERY.format(self.table_name), message_id) + + async def _claim_next_ready(self) -> asyncpg.Record | None: + """Claim the oldest pending message that is ready (its delay, if any, has elapsed).""" + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn: + return await conn.fetchrow(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name)) + + def _ackable(self, claimed: asyncpg.Record) -> AckableMessage: + """Wrap a claimed message; acknowledging it deletes the row.""" + message_str = claimed["message"] + if not isinstance(message_str, str): + msg = "message is not a string" + raise TypeError(msg) + message_id = int(claimed["id"]) + + async def ack() -> None: + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn: + await conn.execute(DELETE_MESSAGE_QUERY.format(self.table_name), message_id) + + return AckableMessage(data=message_str.encode(), ack=ack) diff --git a/src/taskiq_pg/asyncpg/queries.py b/src/taskiq_pg/asyncpg/queries.py index a504d05..ce90015 100644 --- a/src/taskiq_pg/asyncpg/queries.py +++ b/src/taskiq_pg/asyncpg/queries.py @@ -99,3 +99,23 @@ DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = $1; """ + +CREATE_PENDING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (id) WHERE status = 'pending'" + +CLAIM_NEXT_READY_MESSAGE_QUERY = """ +UPDATE {table} SET status = 'processing' +WHERE id = ( + SELECT id FROM {table} + WHERE status = 'pending' + AND created_at + make_interval(secs => CASE + -- a label that is not a plain number must not break the query for every other row + WHEN labels->>'delay' ~ '^[0-9]{{1,10}}(\\.[0-9]+)?$' THEN (labels->>'delay')::double precision + WHEN labels->>'delay' ~ '^[0-9]+(\\.[0-9]+)?$' THEN 1e10 -- over 300 years: never ready + ELSE 0 + END) <= now() + ORDER BY id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING id, message +""" diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index eb8f200..a82d28d 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -11,12 +11,14 @@ from psqlpy.extra_types import JSONB from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.psqlpy.queries import ( CLAIM_MESSAGE_QUERY, + CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, + CREATE_PENDING_INDEX_QUERY, DELETE_MESSAGE_QUERY, INSERT_MESSAGE_QUERY, ) @@ -62,6 +64,7 @@ def __init__( # noqa: PLR0913 write_pool: psqlpy.ConnectionPool | None = None, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new PSQLPyBroker. @@ -80,6 +83,7 @@ def __init__( # noqa: PLR0913 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. + poll_interval: How often, in seconds, to look for pending messages whose NOTIFY was missed. """ super().__init__( dsn=dsn, @@ -91,6 +95,7 @@ def __init__( # noqa: PLR0913 write_kwargs=write_kwargs, listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, + poll_interval=poll_interval, ) self._owns_write_pool = True @@ -109,8 +114,12 @@ async def startup(self) -> None: ) # create messages table if it doesn't exist - async with self._write_pool.acquire() as conn: - await conn.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + async with self._write_pool.acquire() as conn, conn.transaction() as transaction: + await transaction.execute(schema_lock_query(self.table_name)) + await transaction.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + await transaction.execute( + CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + ) self._queue = asyncio.Queue() @@ -170,6 +179,7 @@ async def _consume_notifications(self) -> None: with suppress(Exception): await self._listener.shutdown() self._listener = await self._restore_listener() + self._queue.put_nowait(POLL_NOW) # notifications sent while reconnecting were missed 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.""" @@ -236,6 +246,10 @@ async def kick(self, message: BrokerMessage) -> None: :param message: Message to send. """ + # Parse the delay before inserting, so a malformed label does not leave a message behind. + delay_value = message.labels.get("delay") + delay_seconds = None if delay_value is None else int(delay_value) + async with self._write_pool.acquire() as conn: # insert message into db table message_inserted_id = tp.cast( @@ -251,9 +265,7 @@ async def kick(self, message: BrokerMessage) -> None: ), ) - delay_value = tp.cast("str | None", message.labels.get("delay")) - if delay_value is not None: - delay_seconds = int(delay_value) + if delay_seconds is not None: asyncio.create_task( # noqa: RUF006 self._schedule_notification(message_inserted_id, delay_seconds), ) @@ -278,32 +290,51 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: :yields: AckableMessage instances. """ + loop = asyncio.get_running_loop() + next_poll = loop.time() # poll right away: messages may have been kicked while nobody listened while True: try: - payload = await self._queue.get() - message_id = int(payload) # payload is the message id + if loop.time() >= next_poll: + next_poll = loop.time() + self.poll_interval + while (claimed := await self._claim_next_ready()) is not None: + yield self._ackable(claimed) + continue try: - async with self._write_pool.acquire() as conn: - claimed_message = await conn.fetch_row( - CLAIM_MESSAGE_QUERY.format(self.table_name), - [message_id], - ) - except ConnectionExecuteError: # message was claimed by another worker + payload = await asyncio.wait_for(self._queue.get(), next_poll - loop.time()) + except TimeoutError: continue - message_row_result = tp.cast( - "MessageRow", - tp.cast("object", claimed_message.as_class(MessageRow)), - ) - message_data = message_row_result.message.encode() - - async def ack(*, _message_id: int = message_id) -> None: - async with self._write_pool.acquire() as conn: - _ = await conn.execute( - DELETE_MESSAGE_QUERY.format(self.table_name), - [_message_id], - ) - - yield AckableMessage(data=message_data, ack=ack) + if payload == POLL_NOW: + next_poll = loop.time() + continue + claimed = await self._claim(int(payload)) # payload is the message id + if claimed is not None: + yield self._ackable(claimed) except Exception: logger.exception("Error processing message") continue + + async def _claim(self, message_id: int) -> MessageRow | None: + """Claim a pending message by its id.""" + try: + async with self._write_pool.acquire() as conn: + claimed_message = await conn.fetch_row(CLAIM_MESSAGE_QUERY.format(self.table_name), [message_id]) + except ConnectionExecuteError: # message was claimed by another worker + return None + return tp.cast("MessageRow", tp.cast("object", claimed_message.as_class(MessageRow))) + + async def _claim_next_ready(self) -> MessageRow | None: + """Claim the oldest pending message that is ready (its delay, if any, has elapsed).""" + async with self._write_pool.acquire() as conn: + result = await conn.fetch(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name)) + rows = tp.cast("list[MessageRow]", result.as_class(MessageRow)) + return rows[0] if rows else None + + def _ackable(self, claimed: MessageRow) -> AckableMessage: + """Wrap a claimed message; acknowledging it deletes the row.""" + message_id = claimed.id + + async def ack() -> None: + async with self._write_pool.acquire() as conn: + await conn.execute(DELETE_MESSAGE_QUERY.format(self.table_name), [message_id]) + + return AckableMessage(data=claimed.message.encode(), ack=ack) diff --git a/src/taskiq_pg/psqlpy/queries.py b/src/taskiq_pg/psqlpy/queries.py index 5214ebc..87bcf11 100644 --- a/src/taskiq_pg/psqlpy/queries.py +++ b/src/taskiq_pg/psqlpy/queries.py @@ -99,3 +99,23 @@ DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = $1; """ + +CREATE_PENDING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (id) WHERE status = 'pending'" + +CLAIM_NEXT_READY_MESSAGE_QUERY = """ +UPDATE {table} SET status = 'processing' +WHERE id = ( + SELECT id FROM {table} + WHERE status = 'pending' + AND created_at + make_interval(secs => CASE + -- a label that is not a plain number must not break the query for every other row + WHEN labels->>'delay' ~ '^[0-9]{{1,10}}(\\.[0-9]+)?$' THEN (labels->>'delay')::double precision + WHEN labels->>'delay' ~ '^[0-9]+(\\.[0-9]+)?$' THEN 1e10 -- over 300 years: never ready + ELSE 0 + END) <= now() + ORDER BY id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING * +""" diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 8466b0f..29f6dc7 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -10,11 +10,14 @@ from psycopg_pool import AsyncConnectionPool from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query from taskiq_pg._internal.retry import retry_delays +from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.psycopg.queries import ( CLAIM_MESSAGE_QUERY, + CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, + CREATE_PENDING_INDEX_QUERY, DELETE_MESSAGE_QUERY, INSERT_MESSAGE_QUERY, ) @@ -58,6 +61,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -76,6 +80,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -94,6 +99,7 @@ def __init__( read_connection: AsyncConnection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -112,6 +118,7 @@ def __init__( read_connection: AsyncConnection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -129,6 +136,7 @@ def __init__( # noqa: PLR0913 read_connection: AsyncConnection | None = None, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new PsycopgBroker. @@ -148,6 +156,7 @@ def __init__( # noqa: PLR0913 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. + poll_interval: How often, in seconds, to look for pending messages whose NOTIFY was missed. """ super().__init__( dsn=dsn, @@ -160,6 +169,7 @@ def __init__( # noqa: PLR0913 write_kwargs=write_kwargs, listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, + poll_interval=poll_interval, ) self._owns_write_pool = True @@ -172,6 +182,8 @@ def __init__( # noqa: PLR0913 self._read_conn = read_connection self._owns_read_conn = False + self._notify_tasks: set[asyncio.Task[None]] = set() + async def startup(self) -> None: """Initialize the broker.""" await super().startup() @@ -187,8 +199,19 @@ async def startup(self) -> None: if self._write_pool.closed: await self._write_pool.open() - async with self._write_pool.connection() as connection, connection.cursor() as cursor: + async with ( + self._write_pool.connection() as connection, + connection.transaction(), + connection.cursor() as cursor, + ): + await cursor.execute(schema_lock_query(self.table_name)) await cursor.execute(sql.SQL(CREATE_MESSAGE_TABLE_QUERY).format(sql.Identifier(self.table_name))) + await cursor.execute( + sql.SQL(CREATE_PENDING_INDEX_QUERY).format( + index=sql.Identifier(f"{self.table_name}_pending_idx"), + table=sql.Identifier(self.table_name), + ), + ) if self._owns_read_conn: await self._connect_listener() @@ -254,6 +277,8 @@ def _is_closing(self) -> bool: async def shutdown(self) -> None: """Close all connections on shutdown.""" self._closing = True + for task in list(self._notify_tasks): + await cancel_and_wait(task) await super().shutdown() if self._notifies_iter is not None: with suppress(RuntimeError): # RuntimeError: aclose(): asynchronous generator is already running @@ -272,6 +297,10 @@ async def kick(self, message: BrokerMessage) -> None: :param message: Message to send. """ + # Parse the delay before inserting, so a malformed label does not leave a message behind. + delay_value = message.labels.get("delay") + delay_seconds = None if delay_value is None else int(delay_value) + async with self._write_pool.connection() as connection, connection.cursor() as cursor: # insert message into db table await cursor.execute( @@ -289,8 +318,7 @@ async def kick(self, message: BrokerMessage) -> None: raise RuntimeError(msg) message_inserted_id = int(row[0]) - delay_value = tp.cast("str | None", message.labels.get("delay")) - if delay_value is None: + if delay_seconds is None: # Send NOTIFY with message ID as payload await cursor.execute( sql.SQL("NOTIFY {}, {}").format( @@ -302,7 +330,11 @@ async def kick(self, message: BrokerMessage) -> None: # The insert is committed once the connection is returned to the pool, # so a delayed NOTIFY sent from here never reaches a worker before the row is visible. - await self._schedule_notification(message_inserted_id, int(delay_value)) + # The NOTIFY is only the fast path: workers also poll for messages whose delay has elapsed, + # so the message is delivered even if this producer exits before sending it. + 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) async def _schedule_notification(self, message_id: int, delay_seconds: int) -> None: """Schedule a notification to be sent after a delay.""" @@ -318,23 +350,30 @@ 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. + Yield notification payloads from the current LISTEN connection, and POLL_NOW when it is time to poll. - 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. + POLL_NOW comes first, so the table is polled right after start and after every reconnect. The + connection is read in slices up to the next poll and, for a broker-owned connection, up to the + next keepalive query; a keepalive 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 + keepalive = self.listen_keepalive_interval if self._owns_read_conn else None + loop = asyncio.get_running_loop() + next_poll = loop.time() + next_keepalive = None if keepalive is None else loop.time() + keepalive while not self._is_closing(): - self._notifies_iter = self._read_conn.notifies(timeout=interval) + now = loop.time() + if now >= next_poll: + next_poll = now + self.poll_interval + yield POLL_NOW + continue + if keepalive is not None and next_keepalive is not None and now >= next_keepalive: + await self._check_listener() + next_keepalive = loop.time() + keepalive + continue + deadline = next_poll if next_keepalive is None else min(next_poll, next_keepalive) + self._notifies_iter = self._read_conn.notifies(timeout=deadline - now) 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: """ @@ -386,30 +425,52 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: :yields: AckableMessage instances. """ - async for message_id_str in self._listen_context(): - message_id = int(message_id_str) # payload is the message id - try: - async with self._write_pool.connection() as connection, connection.cursor() as cursor: - await cursor.execute( - sql.SQL(CLAIM_MESSAGE_QUERY).format(sql.Identifier(self.table_name)), - [message_id], - ) - claimed_message = await cursor.fetchone() - if claimed_message is None: - continue - except psycopg.OperationalError: # message was claimed by another worker + async for payload in self._listen_context(): + if payload == POLL_NOW: + while (claimed := await self._claim_next_ready()) is not None: + yield self._ackable(claimed) continue - message_str = claimed_message[3] - if not isinstance(message_str, str): - msg = "Message is not a string" - raise TypeError(msg) - message_data = message_str.encode() - - async def ack(*, _message_id: int = message_id) -> None: - async with self._write_pool.connection() as connection, connection.cursor() as cursor: - await cursor.execute( - sql.SQL(DELETE_MESSAGE_QUERY).format(sql.Identifier(self.table_name)), - [_message_id], - ) - - yield AckableMessage(data=message_data, ack=ack) + claimed = await self._claim(int(payload)) # payload is the message id + if claimed is not None: + yield self._ackable(claimed) + + async def _claim(self, message_id: int) -> tuple[tp.Any, ...] | None: + """Claim a pending message by its id.""" + try: + async with self._write_pool.connection() as connection, connection.cursor() as cursor: + await cursor.execute( + sql.SQL(CLAIM_MESSAGE_QUERY).format(sql.Identifier(self.table_name)), + [message_id], + ) + return await cursor.fetchone() + except psycopg.OperationalError: # message was claimed by another worker + return None + + async def _claim_next_ready(self) -> tuple[tp.Any, ...] | None: + """Claim the oldest pending message that is ready (its delay, if any, has elapsed).""" + try: + async with self._write_pool.connection() as connection, connection.cursor() as cursor: + await cursor.execute( + sql.SQL(CLAIM_NEXT_READY_MESSAGE_QUERY).format(table=sql.Identifier(self.table_name)), + ) + return await cursor.fetchone() + except psycopg.OperationalError: + logger.warning("Polling for pending messages failed; will retry", exc_info=True) + return None + + def _ackable(self, claimed: tuple[tp.Any, ...]) -> AckableMessage: + """Wrap a claimed message; acknowledging it deletes the row.""" + message_id = int(claimed[0]) + message_str = claimed[3] + if not isinstance(message_str, str): + msg = "Message is not a string" + raise TypeError(msg) + + async def ack() -> None: + async with self._write_pool.connection() as connection, connection.cursor() as cursor: + await cursor.execute( + sql.SQL(DELETE_MESSAGE_QUERY).format(sql.Identifier(self.table_name)), + [message_id], + ) + + return AckableMessage(data=message_str.encode(), ack=ack) diff --git a/src/taskiq_pg/psycopg/queries.py b/src/taskiq_pg/psycopg/queries.py index b7e1b46..a4bfaeb 100644 --- a/src/taskiq_pg/psycopg/queries.py +++ b/src/taskiq_pg/psycopg/queries.py @@ -99,3 +99,23 @@ DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = %s; """ + +CREATE_PENDING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (id) WHERE status = 'pending'" + +CLAIM_NEXT_READY_MESSAGE_QUERY = """ +UPDATE {table} SET status = 'processing' +WHERE id = ( + SELECT id FROM {table} + WHERE status = 'pending' + AND created_at + make_interval(secs => CASE + -- a label that is not a plain number must not break the query for every other row + WHEN labels->>'delay' ~ '^[0-9]{{1,10}}(\\.[0-9]+)?$' THEN (labels->>'delay')::double precision + WHEN labels->>'delay' ~ '^[0-9]+(\\.[0-9]+)?$' THEN 1e10 -- over 300 years: never ready + ELSE 0 + END) <= now() + ORDER BY id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING * +""" diff --git a/tests/integration/test_aiopg_reconnect.py b/tests/integration/test_aiopg_reconnect.py index f926c6c..448bfb3 100644 --- a/tests/integration/test_aiopg_reconnect.py +++ b/tests/integration/test_aiopg_reconnect.py @@ -20,7 +20,7 @@ async def test_when_reconnect_attempts_fail__then_listener_keeps_retrying( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = AiopgBroker(dsn=pg_dsn, channel_name=channel) + broker = AiopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() connect_listener = broker._connect_listener # noqa: SLF001 attempts = 0 @@ -71,7 +71,7 @@ async def test_when_supplied_read_connection_was_terminated__then_warning_is_log # given channel = f"reconnect_{uuid.uuid4().hex}" read_connection = await aiopg.connect(pg_dsn) - broker = AiopgBroker(dsn=pg_dsn, channel_name=channel, read_connection=read_connection) + broker = AiopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel, read_connection=read_connection) await broker.startup() try: with caplog.at_level("WARNING", logger="taskiq.aiopg_broker"): @@ -98,7 +98,7 @@ async def test_when_shutdown_during_reconnect__then_reconnect_is_cancelled( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = AiopgBroker(dsn=pg_dsn, channel_name=channel) + broker = AiopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() connecting = asyncio.Event() cancelled = asyncio.Event() diff --git a/tests/integration/test_asyncpg_reconnect.py b/tests/integration/test_asyncpg_reconnect.py index 0428a04..a57b68f 100644 --- a/tests/integration/test_asyncpg_reconnect.py +++ b/tests/integration/test_asyncpg_reconnect.py @@ -7,6 +7,7 @@ import pytest from taskiq import BrokerMessage +from taskiq_pg._internal.broker import POLL_NOW from taskiq_pg.asyncpg import AsyncpgBroker @@ -39,7 +40,7 @@ async def test_listener_receives_messages_after_connection_loss( failures: int, ) -> None: """Resume receiving tasks after disconnection, including temporary database unavailability.""" - broker = AsyncpgBroker(dsn=pg_dsn) + broker = AsyncpgBroker(dsn=pg_dsn, table_name=f"reconnect_{uuid.uuid4().hex}") await broker.startup() original = broker._read_conn # noqa: SLF001 assert original is not None @@ -144,7 +145,10 @@ async def fail_once( queue = broker._queue # noqa: SLF001 assert queue is not None await connection.execute(f"NOTIFY {broker.channel_name}, '42'") - assert await asyncio.wait_for(queue.get(), timeout=5) == "42" + payload = await asyncio.wait_for(queue.get(), timeout=5) + while payload == POLL_NOW: # reconnecting also asks the worker to poll the table + payload = await asyncio.wait_for(queue.get(), timeout=5) + assert payload == "42" assert len(failed_connections) == 1 assert failed_connections[0].is_closed() finally: diff --git a/tests/integration/test_broker.py b/tests/integration/test_broker.py index 54f5697..a883f3c 100644 --- a/tests/integration/test_broker.py +++ b/tests/integration/test_broker.py @@ -1,4 +1,5 @@ import asyncio +import time import typing as tp import uuid @@ -178,3 +179,33 @@ async def test_when_delayed_message_was_published__then_worker_received_message( assert task.result().data == message.message finally: task.cancel() + + +@pytest.mark.integration +@pytest.mark.parametrize( + "broker", + [ + AsyncpgBroker, + PSQLPyBroker, + PsycopgBroker, + AiopgBroker, + ], + indirect=True, +) +async def test_when_delayed_message_was_published__then_kick_does_not_wait_for_the_delay( + broker, +) -> None: + # given + message: BrokerMessage = BrokerMessage( + task_id=uuid.uuid4().hex, + task_name="example:delayed_task", + message=b'{"hello":"later"}', + labels={"delay": 3}, + ) + + # when + started = time.monotonic() + await broker.kick(message) + + # then + assert time.monotonic() - started < 1, "kick() must return before the delay elapses" diff --git a/tests/integration/test_listen_keepalive.py b/tests/integration/test_listen_keepalive.py index 59616ee..602a6b7 100644 --- a/tests/integration/test_listen_keepalive.py +++ b/tests/integration/test_listen_keepalive.py @@ -72,7 +72,7 @@ async def test_when_keepalive_query_hangs__then_listener_reconnects( ) -> None: # given channel = f"keepalive_{uuid.uuid4().hex}" - broker = broker_class(dsn=pg_dsn, channel_name=channel, **FAST_KEEPALIVE) + broker = broker_class(dsn=pg_dsn, channel_name=channel, table_name=channel, **FAST_KEEPALIVE) keepalive_query = broker._keepalive_query # noqa: SLF001 hung = asyncio.Event() @@ -118,6 +118,7 @@ async def _listen_backends_after_idle_period( broker = broker_class( dsn=pg_dsn, channel_name=channel, + table_name=channel, read_kwargs=read_kwargs, listen_keepalive_interval=keepalive_interval, listen_keepalive_timeout=1.0, @@ -181,7 +182,7 @@ async def test_when_psycopg_keepalive_query_ignores_cancellation__then_hang_is_d """ # given channel = f"keepalive_{uuid.uuid4().hex}" - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, **FAST_KEEPALIVE) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel, **FAST_KEEPALIVE) keepalive_query = broker._keepalive_query # noqa: SLF001 hung = asyncio.Event() diff --git a/tests/integration/test_listener_reconnect.py b/tests/integration/test_listener_reconnect.py index 6210cc8..da7710e 100644 --- a/tests/integration/test_listener_reconnect.py +++ b/tests/integration/test_listener_reconnect.py @@ -46,7 +46,7 @@ async def test_when_listen_connection_was_terminated__then_worker_received_next_ ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = broker_class(dsn=pg_dsn, channel_name=channel) + broker = broker_class(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() listener = broker.listen() task: asyncio.Task[tp.Any] = asyncio.create_task(listener.__anext__()) diff --git a/tests/integration/test_polling.py b/tests/integration/test_polling.py new file mode 100644 index 0000000..b28cf69 --- /dev/null +++ b/tests/integration/test_polling.py @@ -0,0 +1,250 @@ +import asyncio +import json +import typing as tp +import uuid + +import asyncpg +import pytest +from taskiq import AckableMessage, 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 + + +Broker: tp.TypeAlias = AsyncpgBroker | PsycopgBroker | PSQLPyBroker | AiopgBroker +BROKERS: list[tp.Any] = [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker] + + +def unique_names() -> dict[str, str]: + suffix = uuid.uuid4().hex[:12] + return {"table_name": f"poll_{suffix}", "channel_name": f"poll_{suffix}"} + + +async def insert_pending(connection: asyncpg.Connection, table: str, data: str, labels: dict[str, tp.Any]) -> int: + """Insert a pending message without sending a NOTIFY, like a kick whose notification was missed.""" + return tp.cast( + "int", + await connection.fetchval( + f"INSERT INTO {table} (task_id, task_name, message, labels) VALUES ($1, $2, $3, $4) RETURNING id", # noqa: S608 + uuid.uuid4().hex, + "example:polled", + data, + json.dumps(labels), + ), + ) + + +async def take(listener: tp.AsyncIterator[AckableMessage], count: int, timeout: float) -> list[bytes]: + """Read `count` messages from a listener within `timeout` seconds.""" + + async def read() -> list[bytes]: + return [(await anext(listener)).data for _ in range(count)] + + return await asyncio.wait_for(read(), timeout) + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_message_was_inserted_without_notify__then_worker_claims_it_by_polling( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + await broker.startup() + listener = broker.listen() + try: + # when + await insert_pending(connection, names["table_name"], '{"polled":true}', {}) + + # then + assert await take(listener, 1, timeout=3) == [b'{"polled":true}'] + finally: + await listener.aclose() + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_messages_were_kicked_before_worker_started__then_worker_processes_them( + pg_dsn: str, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + producer = broker_class(dsn=pg_dsn, **names) + await producer.startup() + expected = {f'{{"n":{n}}}'.encode() for n in range(5)} + for data in expected: + await producer.kick( + BrokerMessage(task_id=uuid.uuid4().hex, task_name="example:early", message=data, labels={}), + ) + worker = broker_class(dsn=pg_dsn, **names) + + # when + await worker.startup() + listener = worker.listen() + try: + received = await take(listener, len(expected), timeout=3) + + # then + assert set(received) == expected + finally: + await listener.aclose() + await worker.shutdown() + await producer.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_delayed_message_was_not_notified__then_it_is_claimed_after_its_delay( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + await broker.startup() + listener = broker.listen() + pending: asyncio.Task[AckableMessage] = asyncio.create_task(anext(listener)) # type: ignore[arg-type] + try: + # when + await insert_pending(connection, names["table_name"], '{"delayed":true}', {"delay": 1}) + done, _ = await asyncio.wait({pending}, timeout=0.6) + + # then + assert not done, "A delayed message must not be claimed before its delay elapses" + done, _ = await asyncio.wait({pending}, timeout=3) + assert pending in done + assert pending.result().data == b'{"delayed":true}' + finally: + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_two_workers_poll__then_each_message_is_claimed_once( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + first = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + second = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + await first.startup() + await second.startup() + expected = [f'{{"n":{n}}}' for n in range(20)] + for data in expected: + await insert_pending(connection, names["table_name"], data, {}) + received: list[bytes] = [] + + async def consume(broker: Broker) -> None: + async for message in broker.listen(): + received.append(message.data) # noqa: PERF401 - the loop runs until cancelled + + # when + consumers = [asyncio.create_task(consume(first)), asyncio.create_task(consume(second))] + try: + + async def all_received() -> None: + while len(received) < len(expected): # noqa: ASYNC110 + await asyncio.sleep(0.05) + + await asyncio.wait_for(all_received(), timeout=5) + await asyncio.sleep(0.5) # give a duplicate the chance to show up + + # then + assert sorted(received) == sorted(data.encode() for data in expected) + finally: + for consumer in consumers: + consumer.cancel() + await asyncio.gather(*consumers, return_exceptions=True) + await first.shutdown() + await second.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_broker_starts__then_pending_index_is_created( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, **names) + + # when + await broker.startup() + try: + definition = await connection.fetchval( + "SELECT indexdef FROM pg_indexes WHERE indexname = $1", + f"{names['table_name']}_pending_idx", + ) + + # then + assert definition is not None + assert "WHERE (status = 'pending'::text)" in definition + finally: + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_pending_rows_have_malformed_delay_labels__then_polling_still_claims_messages( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + table = names["table_name"] + broker = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + await broker.startup() + await insert_pending(connection, table, '{"label":"text"}', {"delay": "abc"}) + await insert_pending(connection, table, '{"label":"negative"}', {"delay": "-3"}) + await insert_pending(connection, table, '{"label":"huge"}', {"delay": "9" * 400}) + await insert_pending(connection, table, '{"label":"none"}', {}) + listener = broker.listen() + try: + # when + received = await take(listener, 3, timeout=5) + + # then + assert received == [b'{"label":"text"}', b'{"label":"negative"}', b'{"label":"none"}'] + pending = await connection.fetchval(f"SELECT message FROM {table} WHERE status = 'pending'") # noqa: S608 + assert pending == '{"label":"huge"}' + finally: + await listener.aclose() + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_delay_label_is_malformed__then_kick_fails_without_inserting_the_message( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, **names) + await broker.startup() + message = BrokerMessage(task_id=uuid.uuid4().hex, task_name="example:bad", message=b"{}", labels={"delay": "abc"}) + try: + # when + with pytest.raises(ValueError, match="invalid literal"): + await broker.kick(message) + + # then + assert await connection.fetchval(f"SELECT count(*) FROM {names['table_name']}") == 0 # noqa: S608 + finally: + await broker.shutdown() diff --git a/tests/integration/test_psqlpy_reconnect.py b/tests/integration/test_psqlpy_reconnect.py index af0ee2c..b89f33c 100644 --- a/tests/integration/test_psqlpy_reconnect.py +++ b/tests/integration/test_psqlpy_reconnect.py @@ -20,7 +20,7 @@ async def test_when_reconnect_attempts_fail__then_listener_keeps_retrying( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PSQLPyBroker(dsn=pg_dsn, channel_name=channel) + broker = PSQLPyBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() start_listener = broker._start_listener # noqa: SLF001 attempts = 0 @@ -70,7 +70,7 @@ async def test_when_shutdown_during_reconnect__then_reconnect_is_cancelled( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PSQLPyBroker(dsn=pg_dsn, channel_name=channel) + broker = PSQLPyBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() connecting = asyncio.Event() cancelled = asyncio.Event() diff --git a/tests/integration/test_psycopg_reconnect.py b/tests/integration/test_psycopg_reconnect.py index 989466c..ece3823 100644 --- a/tests/integration/test_psycopg_reconnect.py +++ b/tests/integration/test_psycopg_reconnect.py @@ -20,7 +20,7 @@ async def test_when_reconnect_attempts_fail__then_listener_keeps_retrying( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() connect_listener = broker._connect_listener # noqa: SLF001 attempts = 0 @@ -70,7 +70,7 @@ async def test_when_supplied_read_connection_was_terminated__then_error_is_raise # given channel = f"reconnect_{uuid.uuid4().hex}" read_connection = await psycopg.AsyncConnection.connect(pg_dsn, autocommit=True) - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, read_connection=read_connection) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel, read_connection=read_connection) await broker.startup() listener = broker.listen() task: asyncio.Task[tp.Any] = asyncio.create_task(listener.__anext__()) @@ -98,7 +98,7 @@ async def test_when_broker_is_shut_down_while_listening__then_listener_stops_wit ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() listener = broker.listen() task: asyncio.Task[tp.Any] = asyncio.create_task(listener.__anext__()) @@ -123,7 +123,7 @@ async def test_when_broker_is_shut_down_during_reconnect__then_reconnect_stops( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() attempts = 0 diff --git a/tests/integration/test_schema_setup.py b/tests/integration/test_schema_setup.py new file mode 100644 index 0000000..ddb474b --- /dev/null +++ b/tests/integration/test_schema_setup.py @@ -0,0 +1,41 @@ +import asyncio +import typing as tp +import uuid + +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 + + +# Small pools, so that eight brokers stay well below max_connections (asyncpg opens 10 connections by default). +SMALL_POOLS: list[tp.Any] = [ + pytest.param(AsyncpgBroker, {"min_size": 1, "max_size": 2}, id="AsyncpgBroker"), + pytest.param(PsycopgBroker, {"min_size": 1, "max_size": 2}, id="PsycopgBroker"), + pytest.param(PSQLPyBroker, {"max_db_pool_size": 2}, id="PSQLPyBroker"), + pytest.param(AiopgBroker, {"minsize": 1, "maxsize": 2}, id="AiopgBroker"), +] + + +@pytest.mark.integration +@pytest.mark.parametrize(("broker_class", "write_kwargs"), SMALL_POOLS) +async def test_when_many_brokers_start_at_once_on_a_new_table__then_all_of_them_start( + pg_dsn: str, + broker_class: type[tp.Any], + write_kwargs: dict[str, tp.Any], +) -> None: + """Workers of one deployment start together; concurrent schema setup must not make any of them fail.""" + # given + names = {"table_name": f"setup_{uuid.uuid4().hex[:12]}", "channel_name": f"setup_{uuid.uuid4().hex[:12]}"} + brokers = [broker_class(dsn=pg_dsn, write_kwargs=write_kwargs, **names) for _ in range(8)] + + # when + results = await asyncio.gather(*(broker.startup() for broker in brokers), return_exceptions=True) + + # then + try: + assert [r for r in results if isinstance(r, BaseException)] == [] + finally: + await asyncio.gather(*(broker.shutdown() for broker in brokers), return_exceptions=True) diff --git a/tests/unit/test_listen_keepalive_params.py b/tests/unit/test_listen_keepalive_params.py index 99284cb..11f7c76 100644 --- a/tests/unit/test_listen_keepalive_params.py +++ b/tests/unit/test_listen_keepalive_params.py @@ -50,3 +50,22 @@ def test_when_keepalive_settings_are_invalid__then_error_is_raised( # when / then with pytest.raises(ValueError, match=match): broker_class(**kwargs) + + +@pytest.mark.unit +@pytest.mark.parametrize("broker_class", BROKERS) +def test_when_broker_is_created__then_poll_interval_defaults_to_five_seconds(broker_class: tp.Any) -> None: + # when + broker = broker_class() + + # then + assert broker.poll_interval == 5.0 + + +@pytest.mark.unit +@pytest.mark.parametrize("broker_class", BROKERS) +@pytest.mark.parametrize("poll_interval", [0, -1]) +def test_when_poll_interval_is_not_positive__then_error_is_raised(broker_class: tp.Any, poll_interval: float) -> None: + # when / then + with pytest.raises(ValueError, match="poll_interval"): + broker_class(poll_interval=poll_interval)