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
22 changes: 21 additions & 1 deletion src/taskiq_pg/_internal/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand All @@ -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,
Expand All @@ -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."""
19 changes: 19 additions & 0 deletions src/taskiq_pg/_internal/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
54 changes: 47 additions & 7 deletions src/taskiq_pg/aiopg/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -47,6 +47,8 @@ def __init__(
*,
write_pool: None = ...,
read_connection: None = ...,
listen_keepalive_interval: float | None = ...,
listen_keepalive_timeout: float = ...,
) -> None: ...

@tp.overload
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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()
Expand Down
52 changes: 50 additions & 2 deletions src/taskiq_pg/asyncpg/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -47,6 +47,8 @@ def __init__(
*,
write_pool: None = ...,
read_connection: None = ...,
listen_keepalive_interval: float | None = ...,
listen_keepalive_timeout: float = ...,
) -> None: ...

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