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
23 changes: 23 additions & 0 deletions src/taskiq_pg/_internal/broker.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import abc
import hashlib
import typing as tp

from taskiq import AsyncBroker, AsyncResultBackend
Expand Down Expand Up @@ -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.
Expand All @@ -47,13 +49,19 @@ 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"
raise ValueError(msg)
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,
Expand All @@ -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)})"
100 changes: 75 additions & 25 deletions src/taskiq_pg/aiopg/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -49,6 +51,7 @@ def __init__(
read_connection: None = ...,
listen_keepalive_interval: float | None = ...,
listen_keepalive_timeout: float = ...,
poll_interval: float = ...,
) -> None: ...

@tp.overload
Expand All @@ -67,6 +70,7 @@ def __init__(
read_connection: None = ...,
listen_keepalive_interval: float | None = ...,
listen_keepalive_timeout: float = ...,
poll_interval: float = ...,
) -> None: ...

@tp.overload
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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),
Expand All @@ -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)

Expand All @@ -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)
20 changes: 20 additions & 0 deletions src/taskiq_pg/aiopg/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
"""
Loading