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
16 changes: 15 additions & 1 deletion src/taskiq_pg/_internal/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def __init__( # noqa: PLR0913
listen_keepalive_interval: float | None = 30.0,
listen_keepalive_timeout: float = 5.0,
poll_interval: float = 5.0,
processing_timeout: float | None = None,
) -> None:
"""
Construct a new broker.
Expand All @@ -41,7 +42,8 @@ def __init__( # noqa: PLR0913
task_id_generator: Custom task_id generator.
channel_name: Name of the channel to listen on.
table_name: Name of the table to store messages.
max_retry_attempts: Maximum number of message processing attempts.
max_retry_attempts: With processing_timeout set, how many times a message may be claimed
before it is marked as failed instead of being delivered again.
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
Expand All @@ -52,6 +54,11 @@ def __init__( # noqa: PLR0913
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.
processing_timeout: Enables at-least-once delivery. A claimed message that is neither acknowledged
nor rejected within this many seconds (for example, because its worker died) is delivered
again, up to max_retry_attempts times. Tasks must then be idempotent, and the timeout must be
longer than the longest task. None (the default) keeps at-most-once delivery: such a message
stays in the 'processing' state.
"""
if listen_keepalive_interval is not None and listen_keepalive_interval <= 0:
msg = "listen_keepalive_interval must be positive or None"
Expand All @@ -62,6 +69,12 @@ def __init__( # noqa: PLR0913
if poll_interval <= 0:
msg = "poll_interval must be positive"
raise ValueError(msg)
if processing_timeout is not None and processing_timeout <= 0:
msg = "processing_timeout must be positive or None"
raise ValueError(msg)
if max_retry_attempts < 1:
msg = "max_retry_attempts must be at least 1"
raise ValueError(msg)
super().__init__(
result_backend=result_backend,
task_id_generator=task_id_generator,
Expand All @@ -75,6 +88,7 @@ def __init__( # noqa: PLR0913
self.listen_keepalive_interval: float | None = listen_keepalive_interval
self.listen_keepalive_timeout: float = listen_keepalive_timeout
self.poll_interval: float = poll_interval
self.processing_timeout: float | None = processing_timeout
self._queue: asyncio.Queue[str] | None = None


Expand Down
46 changes: 45 additions & 1 deletion src/taskiq_pg/aiopg/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@
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 (
ADD_DELIVERY_COLUMNS_QUERY,
CLAIM_MESSAGE_QUERY,
CLAIM_NEXT_READY_MESSAGE_QUERY,
CREATE_MESSAGE_TABLE_QUERY,
CREATE_PENDING_INDEX_QUERY,
CREATE_PROCESSING_INDEX_QUERY,
DELETE_MESSAGE_QUERY,
FAIL_EXHAUSTED_MESSAGES_QUERY,
INSERT_MESSAGE_QUERY,
RELEASE_STALE_MESSAGES_QUERY,
)


Expand Down Expand Up @@ -52,6 +56,7 @@ def __init__(
listen_keepalive_interval: float | None = ...,
listen_keepalive_timeout: float = ...,
poll_interval: float = ...,
processing_timeout: float | None = ...,
) -> None: ...

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

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

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

def __init__( # noqa: PLR0913
Expand All @@ -127,6 +135,7 @@ def __init__( # noqa: PLR0913
listen_keepalive_interval: float | None = 30.0,
listen_keepalive_timeout: float = 5.0,
poll_interval: float = 5.0,
processing_timeout: float | None = None,
) -> None:
"""
Construct a new AiopgBroker.
Expand All @@ -147,6 +156,8 @@ def __init__( # noqa: PLR0913
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.
processing_timeout: Seconds after which an unacknowledged claimed message is delivered again
(at-least-once delivery); None keeps at-most-once delivery.
"""
super().__init__(
dsn=dsn,
Expand All @@ -160,6 +171,7 @@ def __init__( # noqa: PLR0913
listen_keepalive_interval=listen_keepalive_interval,
listen_keepalive_timeout=listen_keepalive_timeout,
poll_interval=poll_interval,
processing_timeout=processing_timeout,
)

self._owns_write_pool = True
Expand All @@ -186,9 +198,17 @@ async def startup(self) -> None:
try:
await cursor.execute(schema_lock_query(self.table_name))
await cursor.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name))
await cursor.execute(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name))
await cursor.execute(
CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name),
)
if self.processing_timeout is not None:
await cursor.execute(
CREATE_PROCESSING_INDEX_QUERY.format(
index=f"{self.table_name}_processing_idx",
table=self.table_name,
),
)
except BaseException:
await cursor.execute("ROLLBACK")
raise
Expand Down Expand Up @@ -362,6 +382,7 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]:
try:
if loop.time() >= next_poll:
next_poll = loop.time() + self.poll_interval
await self._release_stale_messages()
while (
claimed := await self._claim(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name))
) is not None:
Expand Down Expand Up @@ -390,10 +411,33 @@ async def _claim(self, query: str, params: tuple[tp.Any, ...] = ()) -> tuple[tp.
await cursor.execute(query, params)
return tp.cast("tuple[tp.Any, ...] | None", await cursor.fetchone())

async def _release_stale_messages(self) -> None:
"""
With processing_timeout set, return messages claimed too long ago to the queue.

A message whose attempts are exhausted is marked as failed instead.
"""
if self.processing_timeout is None or self._write_pool is None:
return
params = (self.processing_timeout, self.max_retry_attempts)
async with self._write_pool.acquire() as conn, conn.cursor() as cursor:
await cursor.execute(RELEASE_STALE_MESSAGES_QUERY.format(table=self.table_name), params)
await cursor.execute(FAIL_EXHAUSTED_MESSAGES_QUERY.format(table=self.table_name), params)
failed = await cursor.fetchall()
for message_id, task_id, task_name, attempts in failed:
logger.warning(
"Message %s (task %s, %s) was not acknowledged after %s attempts; marked as failed",
message_id,
task_id,
task_name,
attempts,
)

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]
attempts = int(claimed[2])
if not isinstance(message_str, str):
msg = "message is not a string"
raise TypeError(msg)
Expand All @@ -403,6 +447,6 @@ async def ack() -> 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,))
await cursor.execute(DELETE_MESSAGE_QUERY.format(self.table_name), (message_id, attempts))

return AckableMessage(data=message_str.encode(), ack=ack)
36 changes: 32 additions & 4 deletions src/taskiq_pg/aiopg/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,19 @@
RETURNING id
"""

CLAIM_MESSAGE_QUERY = "UPDATE {} SET status = 'processing' WHERE id = %s AND status = 'pending' RETURNING id, message"
CLAIM_MESSAGE_QUERY = """
UPDATE {} SET status = 'processing', claimed_at = now(), attempts = attempts + 1
WHERE id = %s AND status = 'pending'
RETURNING id, message, attempts
"""

DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = %s"
# Delete only the claim being acknowledged: after processing_timeout another worker may have claimed the row again.
DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = %s AND attempts = %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'
UPDATE {table} SET status = 'processing', claimed_at = now(), attempts = attempts + 1
WHERE id = (
SELECT id FROM {table}
WHERE status = 'pending'
Expand All @@ -117,5 +122,28 @@
LIMIT 1
FOR UPDATE SKIP LOCKED
)
RETURNING id, message
RETURNING id, message, attempts
"""

ADD_DELIVERY_COLUMNS_QUERY = """
ALTER TABLE {table}
ADD COLUMN IF NOT EXISTS claimed_at TIMESTAMP WITH TIME ZONE,
ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0
"""

CREATE_PROCESSING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (claimed_at) WHERE status = 'processing'"

RELEASE_STALE_MESSAGES_QUERY = """
UPDATE {table} SET status = 'pending'
WHERE status = 'processing'
AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => %s)
AND attempts < %s
"""

FAIL_EXHAUSTED_MESSAGES_QUERY = """
UPDATE {table} SET status = 'failed'
WHERE status = 'processing'
AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => %s)
AND attempts >= %s
RETURNING id, task_id, task_name, attempts
"""
52 changes: 51 additions & 1 deletion src/taskiq_pg/asyncpg/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@
from taskiq_pg._internal.retry import retry_delays
from taskiq_pg._internal.tasks import cancel_and_wait
from taskiq_pg.asyncpg.queries import (
ADD_DELIVERY_COLUMNS_QUERY,
CLAIM_MESSAGE_QUERY,
CLAIM_NEXT_READY_MESSAGE_QUERY,
CREATE_MESSAGE_TABLE_QUERY,
CREATE_PENDING_INDEX_QUERY,
CREATE_PROCESSING_INDEX_QUERY,
DELETE_MESSAGE_QUERY,
FAIL_EXHAUSTED_MESSAGES_QUERY,
INSERT_MESSAGE_QUERY,
RELEASE_STALE_MESSAGES_QUERY,
)


Expand Down Expand Up @@ -52,6 +56,7 @@ def __init__(
listen_keepalive_interval: float | None = ...,
listen_keepalive_timeout: float = ...,
poll_interval: float = ...,
processing_timeout: float | None = ...,
) -> None: ...

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

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

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

def __init__( # noqa: PLR0913
Expand All @@ -127,6 +135,7 @@ def __init__( # noqa: PLR0913
listen_keepalive_interval: float | None = 30.0,
listen_keepalive_timeout: float = 5.0,
poll_interval: float = 5.0,
processing_timeout: float | None = None,
) -> None:
"""
Construct a new AsyncpgBroker.
Expand All @@ -147,6 +156,8 @@ def __init__( # noqa: PLR0913
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.
processing_timeout: Seconds after which an unacknowledged claimed message is delivered again
(at-least-once delivery); None keeps at-most-once delivery.
"""
super().__init__(
dsn=dsn,
Expand All @@ -160,6 +171,7 @@ def __init__( # noqa: PLR0913
listen_keepalive_interval=listen_keepalive_interval,
listen_keepalive_timeout=listen_keepalive_timeout,
poll_interval=poll_interval,
processing_timeout=processing_timeout,
)

self._owns_write_pool = True
Expand All @@ -182,9 +194,17 @@ async def startup(self) -> None:
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(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name))
await conn.execute(
CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name),
)
if self.processing_timeout is not None:
await conn.execute(
CREATE_PROCESSING_INDEX_QUERY.format(
index=f"{self.table_name}_processing_idx",
table=self.table_name,
),
)
await self._connect_listener()
self._listener_task = asyncio.create_task(self._restore_listener())

Expand Down Expand Up @@ -383,6 +403,7 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]:
try:
if loop.time() >= next_poll:
next_poll = loop.time() + self.poll_interval
await self._release_stale_messages()
while (claimed := await self._claim_next_ready()) is not None:
yield self._ackable(claimed)
continue
Expand Down Expand Up @@ -416,19 +437,48 @@ async def _claim_next_ready(self) -> asyncpg.Record | None:
async with self._write_pool.acquire() as conn:
return await conn.fetchrow(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name))

async def _release_stale_messages(self) -> None:
"""
With processing_timeout set, return messages claimed too long ago to the queue.

A message whose attempts are exhausted is marked as failed instead.
"""
if self.processing_timeout is None or self._write_pool is None:
return
async with self._write_pool.acquire() as conn:
await conn.execute(
RELEASE_STALE_MESSAGES_QUERY.format(table=self.table_name),
self.processing_timeout,
self.max_retry_attempts,
)
failed = await conn.fetch(
FAIL_EXHAUSTED_MESSAGES_QUERY.format(table=self.table_name),
self.processing_timeout,
self.max_retry_attempts,
)
for row in failed:
logger.warning(
"Message %s (task %s, %s) was not acknowledged after %s attempts; marked as failed",
row["id"],
row["task_id"],
row["task_name"],
row["attempts"],
)

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"])
attempts = int(claimed["attempts"])

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)
await conn.execute(DELETE_MESSAGE_QUERY.format(self.table_name), message_id, attempts)

return AckableMessage(data=message_str.encode(), ack=ack)
Loading
Loading