From 19dbb698bd7da8df0a777e67031642ded01b0064 Mon Sep 17 00:00:00 2001 From: Dmitry Davlyatshin Date: Sat, 11 Apr 2026 15:52:59 +0300 Subject: [PATCH 1/5] feat: add keep_schedules flag to schedule sources If True, startup no longer deletes and re-creates schedules from broker tasks, so schedules added in a previous run are kept. --- docs/tutorial/schedule_source.md | 19 +++++ src/taskiq_pg/_internal/schedule_source.py | 12 ++-- src/taskiq_pg/aiopg/schedule_source.py | 12 +++- src/taskiq_pg/asyncpg/schedule_source.py | 12 +++- src/taskiq_pg/psqlpy/schedule_source.py | 14 +++- src/taskiq_pg/psycopg/schedule_source.py | 13 +++- tests/integration/test_schedule_source.py | 82 +++++++++++++++++++++- 7 files changed, 149 insertions(+), 15 deletions(-) diff --git a/docs/tutorial/schedule_source.md b/docs/tutorial/schedule_source.md index b1131e6..0c3d580 100644 --- a/docs/tutorial/schedule_source.md +++ b/docs/tutorial/schedule_source.md @@ -82,6 +82,25 @@ You can also add schedules in runtime using `add_schedule` method of the schedul await schedule_source.add_schedule(ScheduledTask(...)) ``` +## Keeping schedules between runs + +By default, on every startup the schedule source refreshes the schedules table: it deletes all stored schedules +and creates new ones from schedules declared in broker tasks. This means schedules added in runtime (see above) are +lost after a restart. + +If you want to keep schedules from the previous run, pass `keep_schedules=True` to the schedule source: + + ```python + schedule_source = AsyncpgScheduleSource( + dsn=dsn, + broker=broker, + keep_schedules=True, + ) + ``` + +With this flag, startup no longer deletes or re-creates schedules: the table is only created if it doesn't exist +yet, and all previously stored schedules are kept as they are. + ## Using multiple schedules You can use multiple schedules for one task. Just provide a list of schedules to the `@broker.task` decorator: diff --git a/src/taskiq_pg/_internal/schedule_source.py b/src/taskiq_pg/_internal/schedule_source.py index 499fc74..576d8d3 100644 --- a/src/taskiq_pg/_internal/schedule_source.py +++ b/src/taskiq_pg/_internal/schedule_source.py @@ -20,6 +20,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", + keep_schedules: bool = False, **connect_kwargs: tp.Any, ) -> None: """ @@ -34,12 +35,15 @@ def __init__( table_name: Name of the table to store scheduled tasks. Will be created automatically if it doesn't exist. broker: The TaskIQ broker instance to use for finding and managing tasks. Required if startup_schedule is provided. + keep_schedules: Whether or not to keep schedules created on previous run. + If False (default), the schedules table is refreshed from schedules declared in broker tasks on startup. **connect_kwargs: Additional keyword arguments passed to the database connection pool. """ - self._broker: tp.Final = broker - self._dsn: tp.Final = dsn - self._table_name: tp.Final = table_name - self._connect_kwargs: tp.Final = connect_kwargs + self._broker: tp.Final[AsyncBroker] = broker + self._dsn: tp.Final[str | tp.Callable[[], str]] = dsn + self._table_name: tp.Final[str] = table_name + self._connect_kwargs: tp.Final[tp.Any] = connect_kwargs + self._keep_schedules: tp.Final[bool] = keep_schedules def extract_scheduled_tasks_from_broker(self) -> list[ScheduledTask]: """ diff --git a/src/taskiq_pg/aiopg/schedule_source.py b/src/taskiq_pg/aiopg/schedule_source.py index 2fc6434..8833078 100644 --- a/src/taskiq_pg/aiopg/schedule_source.py +++ b/src/taskiq_pg/aiopg/schedule_source.py @@ -30,6 +30,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., + keep_schedules: bool = ..., *, pool: None = ..., **connect_kwargs: tp.Any, @@ -41,6 +42,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., + keep_schedules: bool = ..., *, pool: Pool, ) -> None: ... @@ -50,6 +52,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", + keep_schedules: bool = False, *, pool: Pool | None = None, **connect_kwargs: tp.Any, @@ -61,6 +64,7 @@ def __init__( broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. + keep_schedules: Whether or not to keep schedules created on previous run. pool: An existing connection pool to reuse. **connect_kwargs: Extra kwargs for connection pool creation. """ @@ -73,6 +77,7 @@ def __init__( broker=broker, dsn=dsn, table_name=table_name, + keep_schedules=keep_schedules, **connect_kwargs, ) @@ -107,8 +112,11 @@ async def startup(self) -> None: ) async with self._database_pool.acquire() as connection, connection.cursor() as cursor: await cursor.execute(CREATE_SCHEDULES_TABLE_QUERY.format(self._table_name)) - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) + + if not self._keep_schedules: + logger.debug("Refreshing schedules table") + scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() + await self._update_schedules_on_startup(scheduled_tasks_for_creation) except Exception as error: raise exceptions.DatabaseConnectionError(str(error)) from error diff --git a/src/taskiq_pg/asyncpg/schedule_source.py b/src/taskiq_pg/asyncpg/schedule_source.py index 52c921f..51829b6 100644 --- a/src/taskiq_pg/asyncpg/schedule_source.py +++ b/src/taskiq_pg/asyncpg/schedule_source.py @@ -30,6 +30,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., + keep_schedules: bool = ..., *, pool: None = ..., **connect_kwargs: tp.Any, @@ -41,6 +42,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., + keep_schedules: bool = ..., *, pool: "asyncpg.Pool[asyncpg.Record]", ) -> None: ... @@ -50,6 +52,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", + keep_schedules: bool = False, *, pool: "asyncpg.Pool[asyncpg.Record] | None" = None, **connect_kwargs: tp.Any, @@ -61,6 +64,7 @@ def __init__( broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. + keep_schedules: Whether or not to keep schedules created on previous run. pool: An existing connection pool to reuse. **connect_kwargs: Extra kwargs for connection pool creation. """ @@ -73,6 +77,7 @@ def __init__( broker=broker, dsn=dsn, table_name=table_name, + keep_schedules=keep_schedules, **connect_kwargs, ) @@ -107,8 +112,11 @@ async def startup(self) -> None: self._table_name, ), ) - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) + + if not self._keep_schedules: + logger.debug("Refreshing schedules table") + scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() + await self._update_schedules_on_startup(scheduled_tasks_for_creation) async def shutdown(self) -> None: """Close the connection pool if it created by this schedule source.""" diff --git a/src/taskiq_pg/psqlpy/schedule_source.py b/src/taskiq_pg/psqlpy/schedule_source.py index 0114c60..19f4da4 100644 --- a/src/taskiq_pg/psqlpy/schedule_source.py +++ b/src/taskiq_pg/psqlpy/schedule_source.py @@ -31,6 +31,7 @@ def __init__( broker: AsyncBroker, dsn: "str | tp.Callable[[], str]" = ..., table_name: str = ..., + keep_schedules: bool = ..., *, pool: None = ..., **connect_kwargs: tp.Any, @@ -42,6 +43,7 @@ def __init__( broker: AsyncBroker, dsn: "str | tp.Callable[[], str]" = ..., table_name: str = ..., + keep_schedules: bool = ..., *, pool: ConnectionPool, ) -> None: ... @@ -51,6 +53,7 @@ def __init__( broker: AsyncBroker, dsn: "str | tp.Callable[[], str]" = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", + keep_schedules: bool = False, *, pool: ConnectionPool | None = None, **connect_kwargs: tp.Any, @@ -62,6 +65,7 @@ def __init__( broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. + keep_schedules: Whether or not to keep schedules created on previous run. pool: An existing connection pool to reuse. **connect_kwargs: Extra kwargs for connection pool creation. """ @@ -75,6 +79,7 @@ def __init__( broker=broker, dsn=dsn, table_name=table_name, + keep_schedules=keep_schedules, **connect_kwargs, ) @@ -119,8 +124,11 @@ async def startup(self) -> None: self._table_name, ), ) - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) + + if not self._keep_schedules: + logger.debug("Refreshing schedules table") + scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() + await self._update_schedules_on_startup(scheduled_tasks_for_creation) async def shutdown(self) -> None: """Close the connection pool if was created by this schedule source.""" @@ -171,7 +179,7 @@ async def add_schedule(self, schedule: "ScheduledTask") -> None: uuid.UUID(schedule.schedule_id), schedule.task_name, JSONB(schedule_dict), - ] + ], ) async def delete_schedule(self, schedule_id: str) -> None: diff --git a/src/taskiq_pg/psycopg/schedule_source.py b/src/taskiq_pg/psycopg/schedule_source.py index 418f021..e560e40 100644 --- a/src/taskiq_pg/psycopg/schedule_source.py +++ b/src/taskiq_pg/psycopg/schedule_source.py @@ -31,6 +31,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., + keep_schedules: bool = ..., *, pool: None = ..., **connect_kwargs: tp.Any, @@ -42,6 +43,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., + keep_schedules: bool = ..., *, pool: AsyncConnectionPool, ) -> None: ... @@ -51,6 +53,7 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", + keep_schedules: bool = False, *, pool: AsyncConnectionPool | None = None, **connect_kwargs: tp.Any, @@ -62,9 +65,9 @@ def __init__( broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. + keep_schedules: Whether or not to keep schedules created on previous run. pool: An existing connection pool to reuse. **connect_kwargs: Extra kwargs for connection pool creation. - """ self._owns_pool = True if pool is not None: @@ -75,6 +78,7 @@ def __init__( broker=broker, dsn=dsn, table_name=table_name, + keep_schedules=keep_schedules, **connect_kwargs, ) @@ -118,8 +122,11 @@ async def startup(self) -> None: await cursor.execute( sql.SQL(CREATE_SCHEDULES_TABLE_QUERY).format(sql.Identifier(self._table_name)), ) - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) + + if not self._keep_schedules: + logger.debug("Refreshing schedules table") + scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() + await self._update_schedules_on_startup(scheduled_tasks_for_creation) async def shutdown(self) -> None: """Close the connection pool (only if owned by this source).""" diff --git a/tests/integration/test_schedule_source.py b/tests/integration/test_schedule_source.py index 6a18be1..26ac8ed 100644 --- a/tests/integration/test_schedule_source.py +++ b/tests/integration/test_schedule_source.py @@ -1,6 +1,7 @@ import uuid from contextlib import asynccontextmanager from datetime import timedelta +from typing import Any import pytest from polyfactory.factories.pydantic_factory import ModelFactory @@ -31,8 +32,9 @@ async def _get_schedule_source( schedule_source_class: type[BasePostgresScheduleSource], broker: BasePostgresBroker, dsn: str, + **kwargs: Any, ): - schedule_source = schedule_source_class(broker, dsn) + schedule_source = schedule_source_class(broker, dsn, **kwargs) try: yield schedule_source finally: @@ -198,3 +200,81 @@ async def test_when_call_delete_schedule__then_schedule_deleted( schedules: list[ScheduledTask] = await schedule_source.get_schedules() assert len(schedules) == 2 assert all(task.schedule_id != schedule_id_to_delete for task in schedules) + + +@pytest.mark.integration +@pytest.mark.parametrize( + "schedule_source_class", + [ + PSQLPyScheduleSource, + AiopgScheduleSource, + AsyncpgScheduleSource, + PsycopgScheduleSource, + ], +) +async def test_when_keep_schedules__then_schedules_from_previous_run_kept( + pg_dsn: str, + broker_with_scheduled_tasks: PSQLPyBroker, + schedule_source_class: type[PSQLPyScheduleSource | AiopgScheduleSource | AsyncpgScheduleSource], +) -> None: + # Given + new_schedule = ScheduledTaskFactory.build( + task_name="tests:added_schedule", + cron="*/5 * * * *", + interval=None, + schedule_id=str(uuid.uuid4()), + ) + async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: + await schedule_source.startup() + await schedule_source.add_schedule(new_schedule) + assert len(await schedule_source.get_schedules()) == 4 + + # When + async with _get_schedule_source( + schedule_source_class, + broker_with_scheduled_tasks, + pg_dsn, + keep_schedules=True, + ) as schedule_source: + await schedule_source.startup() + + # Then + schedules: list[ScheduledTask] = await schedule_source.get_schedules() + assert len(schedules) == 4 + assert any(task.schedule_id == new_schedule.schedule_id for task in schedules) + + +@pytest.mark.integration +@pytest.mark.parametrize( + "schedule_source_class", + [ + PSQLPyScheduleSource, + AiopgScheduleSource, + AsyncpgScheduleSource, + PsycopgScheduleSource, + ], +) +async def test_when_not_keep_schedules__then_schedules_from_previous_run_reset( + pg_dsn: str, + broker_with_scheduled_tasks: PSQLPyBroker, + schedule_source_class: type[PSQLPyScheduleSource | AiopgScheduleSource | AsyncpgScheduleSource], +) -> None: + # Given + new_schedule = ScheduledTaskFactory.build( + task_name="tests:added_schedule", + cron="*/5 * * * *", + interval=None, + schedule_id=str(uuid.uuid4()), + ) + async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: + await schedule_source.startup() + await schedule_source.add_schedule(new_schedule) + + # When + async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: + await schedule_source.startup() + + # Then + schedules: list[ScheduledTask] = await schedule_source.get_schedules() + assert len(schedules) == 3 + assert all(task.schedule_id != new_schedule.schedule_id for task in schedules) From 6663ceef530736b6c06b5dc0d00abcf80d8ce789 Mon Sep 17 00:00:00 2001 From: Dmitry Davlyatshin Date: Thu, 26 Nov 2026 18:21:00 +0300 Subject: [PATCH 2/5] refactor: drop the unreleased keep_schedules flag from schedule sources --- docs/tutorial/schedule_source.md | 19 --------- src/taskiq_pg/_internal/schedule_source.py | 4 -- src/taskiq_pg/aiopg/schedule_source.py | 12 ++---- src/taskiq_pg/asyncpg/schedule_source.py | 12 ++---- src/taskiq_pg/psqlpy/schedule_source.py | 12 ++---- src/taskiq_pg/psycopg/schedule_source.py | 12 ++---- tests/integration/test_schedule_source.py | 48 +--------------------- 7 files changed, 14 insertions(+), 105 deletions(-) diff --git a/docs/tutorial/schedule_source.md b/docs/tutorial/schedule_source.md index 0c3d580..b1131e6 100644 --- a/docs/tutorial/schedule_source.md +++ b/docs/tutorial/schedule_source.md @@ -82,25 +82,6 @@ You can also add schedules in runtime using `add_schedule` method of the schedul await schedule_source.add_schedule(ScheduledTask(...)) ``` -## Keeping schedules between runs - -By default, on every startup the schedule source refreshes the schedules table: it deletes all stored schedules -and creates new ones from schedules declared in broker tasks. This means schedules added in runtime (see above) are -lost after a restart. - -If you want to keep schedules from the previous run, pass `keep_schedules=True` to the schedule source: - - ```python - schedule_source = AsyncpgScheduleSource( - dsn=dsn, - broker=broker, - keep_schedules=True, - ) - ``` - -With this flag, startup no longer deletes or re-creates schedules: the table is only created if it doesn't exist -yet, and all previously stored schedules are kept as they are. - ## Using multiple schedules You can use multiple schedules for one task. Just provide a list of schedules to the `@broker.task` decorator: diff --git a/src/taskiq_pg/_internal/schedule_source.py b/src/taskiq_pg/_internal/schedule_source.py index 576d8d3..0ade9ac 100644 --- a/src/taskiq_pg/_internal/schedule_source.py +++ b/src/taskiq_pg/_internal/schedule_source.py @@ -20,7 +20,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", - keep_schedules: bool = False, **connect_kwargs: tp.Any, ) -> None: """ @@ -35,15 +34,12 @@ def __init__( table_name: Name of the table to store scheduled tasks. Will be created automatically if it doesn't exist. broker: The TaskIQ broker instance to use for finding and managing tasks. Required if startup_schedule is provided. - keep_schedules: Whether or not to keep schedules created on previous run. - If False (default), the schedules table is refreshed from schedules declared in broker tasks on startup. **connect_kwargs: Additional keyword arguments passed to the database connection pool. """ self._broker: tp.Final[AsyncBroker] = broker self._dsn: tp.Final[str | tp.Callable[[], str]] = dsn self._table_name: tp.Final[str] = table_name self._connect_kwargs: tp.Final[tp.Any] = connect_kwargs - self._keep_schedules: tp.Final[bool] = keep_schedules def extract_scheduled_tasks_from_broker(self) -> list[ScheduledTask]: """ diff --git a/src/taskiq_pg/aiopg/schedule_source.py b/src/taskiq_pg/aiopg/schedule_source.py index 8833078..5dbd1e3 100644 --- a/src/taskiq_pg/aiopg/schedule_source.py +++ b/src/taskiq_pg/aiopg/schedule_source.py @@ -30,7 +30,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., - keep_schedules: bool = ..., *, pool: None = ..., **connect_kwargs: tp.Any, @@ -42,7 +41,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., - keep_schedules: bool = ..., *, pool: Pool, ) -> None: ... @@ -52,7 +50,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", - keep_schedules: bool = False, *, pool: Pool | None = None, **connect_kwargs: tp.Any, @@ -64,7 +61,6 @@ def __init__( broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. - keep_schedules: Whether or not to keep schedules created on previous run. pool: An existing connection pool to reuse. **connect_kwargs: Extra kwargs for connection pool creation. """ @@ -77,7 +73,6 @@ def __init__( broker=broker, dsn=dsn, table_name=table_name, - keep_schedules=keep_schedules, **connect_kwargs, ) @@ -113,10 +108,9 @@ async def startup(self) -> None: async with self._database_pool.acquire() as connection, connection.cursor() as cursor: await cursor.execute(CREATE_SCHEDULES_TABLE_QUERY.format(self._table_name)) - if not self._keep_schedules: - logger.debug("Refreshing schedules table") - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) + logger.debug("Refreshing schedules table") + scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() + await self._update_schedules_on_startup(scheduled_tasks_for_creation) except Exception as error: raise exceptions.DatabaseConnectionError(str(error)) from error diff --git a/src/taskiq_pg/asyncpg/schedule_source.py b/src/taskiq_pg/asyncpg/schedule_source.py index 51829b6..84ace5e 100644 --- a/src/taskiq_pg/asyncpg/schedule_source.py +++ b/src/taskiq_pg/asyncpg/schedule_source.py @@ -30,7 +30,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., - keep_schedules: bool = ..., *, pool: None = ..., **connect_kwargs: tp.Any, @@ -42,7 +41,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., - keep_schedules: bool = ..., *, pool: "asyncpg.Pool[asyncpg.Record]", ) -> None: ... @@ -52,7 +50,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", - keep_schedules: bool = False, *, pool: "asyncpg.Pool[asyncpg.Record] | None" = None, **connect_kwargs: tp.Any, @@ -64,7 +61,6 @@ def __init__( broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. - keep_schedules: Whether or not to keep schedules created on previous run. pool: An existing connection pool to reuse. **connect_kwargs: Extra kwargs for connection pool creation. """ @@ -77,7 +73,6 @@ def __init__( broker=broker, dsn=dsn, table_name=table_name, - keep_schedules=keep_schedules, **connect_kwargs, ) @@ -113,10 +108,9 @@ async def startup(self) -> None: ), ) - if not self._keep_schedules: - logger.debug("Refreshing schedules table") - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) + logger.debug("Refreshing schedules table") + scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() + await self._update_schedules_on_startup(scheduled_tasks_for_creation) async def shutdown(self) -> None: """Close the connection pool if it created by this schedule source.""" diff --git a/src/taskiq_pg/psqlpy/schedule_source.py b/src/taskiq_pg/psqlpy/schedule_source.py index 19f4da4..7bcc4e5 100644 --- a/src/taskiq_pg/psqlpy/schedule_source.py +++ b/src/taskiq_pg/psqlpy/schedule_source.py @@ -31,7 +31,6 @@ def __init__( broker: AsyncBroker, dsn: "str | tp.Callable[[], str]" = ..., table_name: str = ..., - keep_schedules: bool = ..., *, pool: None = ..., **connect_kwargs: tp.Any, @@ -43,7 +42,6 @@ def __init__( broker: AsyncBroker, dsn: "str | tp.Callable[[], str]" = ..., table_name: str = ..., - keep_schedules: bool = ..., *, pool: ConnectionPool, ) -> None: ... @@ -53,7 +51,6 @@ def __init__( broker: AsyncBroker, dsn: "str | tp.Callable[[], str]" = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", - keep_schedules: bool = False, *, pool: ConnectionPool | None = None, **connect_kwargs: tp.Any, @@ -65,7 +62,6 @@ def __init__( broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. - keep_schedules: Whether or not to keep schedules created on previous run. pool: An existing connection pool to reuse. **connect_kwargs: Extra kwargs for connection pool creation. """ @@ -79,7 +75,6 @@ def __init__( broker=broker, dsn=dsn, table_name=table_name, - keep_schedules=keep_schedules, **connect_kwargs, ) @@ -125,10 +120,9 @@ async def startup(self) -> None: ), ) - if not self._keep_schedules: - logger.debug("Refreshing schedules table") - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) + logger.debug("Refreshing schedules table") + scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() + await self._update_schedules_on_startup(scheduled_tasks_for_creation) async def shutdown(self) -> None: """Close the connection pool if was created by this schedule source.""" diff --git a/src/taskiq_pg/psycopg/schedule_source.py b/src/taskiq_pg/psycopg/schedule_source.py index e560e40..1342401 100644 --- a/src/taskiq_pg/psycopg/schedule_source.py +++ b/src/taskiq_pg/psycopg/schedule_source.py @@ -31,7 +31,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., - keep_schedules: bool = ..., *, pool: None = ..., **connect_kwargs: tp.Any, @@ -43,7 +42,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., - keep_schedules: bool = ..., *, pool: AsyncConnectionPool, ) -> None: ... @@ -53,7 +51,6 @@ def __init__( broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", - keep_schedules: bool = False, *, pool: AsyncConnectionPool | None = None, **connect_kwargs: tp.Any, @@ -65,7 +62,6 @@ def __init__( broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. - keep_schedules: Whether or not to keep schedules created on previous run. pool: An existing connection pool to reuse. **connect_kwargs: Extra kwargs for connection pool creation. """ @@ -78,7 +74,6 @@ def __init__( broker=broker, dsn=dsn, table_name=table_name, - keep_schedules=keep_schedules, **connect_kwargs, ) @@ -123,10 +118,9 @@ async def startup(self) -> None: sql.SQL(CREATE_SCHEDULES_TABLE_QUERY).format(sql.Identifier(self._table_name)), ) - if not self._keep_schedules: - logger.debug("Refreshing schedules table") - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) + logger.debug("Refreshing schedules table") + scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() + await self._update_schedules_on_startup(scheduled_tasks_for_creation) async def shutdown(self) -> None: """Close the connection pool (only if owned by this source).""" diff --git a/tests/integration/test_schedule_source.py b/tests/integration/test_schedule_source.py index 26ac8ed..be6a341 100644 --- a/tests/integration/test_schedule_source.py +++ b/tests/integration/test_schedule_source.py @@ -1,7 +1,6 @@ import uuid from contextlib import asynccontextmanager from datetime import timedelta -from typing import Any import pytest from polyfactory.factories.pydantic_factory import ModelFactory @@ -32,9 +31,8 @@ async def _get_schedule_source( schedule_source_class: type[BasePostgresScheduleSource], broker: BasePostgresBroker, dsn: str, - **kwargs: Any, ): - schedule_source = schedule_source_class(broker, dsn, **kwargs) + schedule_source = schedule_source_class(broker, dsn) try: yield schedule_source finally: @@ -212,49 +210,7 @@ async def test_when_call_delete_schedule__then_schedule_deleted( PsycopgScheduleSource, ], ) -async def test_when_keep_schedules__then_schedules_from_previous_run_kept( - pg_dsn: str, - broker_with_scheduled_tasks: PSQLPyBroker, - schedule_source_class: type[PSQLPyScheduleSource | AiopgScheduleSource | AsyncpgScheduleSource], -) -> None: - # Given - new_schedule = ScheduledTaskFactory.build( - task_name="tests:added_schedule", - cron="*/5 * * * *", - interval=None, - schedule_id=str(uuid.uuid4()), - ) - async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: - await schedule_source.startup() - await schedule_source.add_schedule(new_schedule) - assert len(await schedule_source.get_schedules()) == 4 - - # When - async with _get_schedule_source( - schedule_source_class, - broker_with_scheduled_tasks, - pg_dsn, - keep_schedules=True, - ) as schedule_source: - await schedule_source.startup() - - # Then - schedules: list[ScheduledTask] = await schedule_source.get_schedules() - assert len(schedules) == 4 - assert any(task.schedule_id == new_schedule.schedule_id for task in schedules) - - -@pytest.mark.integration -@pytest.mark.parametrize( - "schedule_source_class", - [ - PSQLPyScheduleSource, - AiopgScheduleSource, - AsyncpgScheduleSource, - PsycopgScheduleSource, - ], -) -async def test_when_not_keep_schedules__then_schedules_from_previous_run_reset( +async def test_when_starting_source_again__then_schedules_are_reset( pg_dsn: str, broker_with_scheduled_tasks: PSQLPyBroker, schedule_source_class: type[PSQLPyScheduleSource | AiopgScheduleSource | AsyncpgScheduleSource], From 8d2a7cbd36c842a35955a1a495f5a390c88efe20 Mon Sep 17 00:00:00 2001 From: Dmitry Davlyatshin Date: Thu, 26 Nov 2026 18:28:54 +0300 Subject: [PATCH 3/5] refactor!: never delete stored schedules on startup; remove label-based schedule extraction and broker parameter (#65) --- src/taskiq_pg/_internal/schedule_source.py | 54 ------- src/taskiq_pg/aiopg/schedule_source.py | 35 +---- src/taskiq_pg/asyncpg/schedule_source.py | 33 +---- src/taskiq_pg/psqlpy/schedule_source.py | 41 +----- src/taskiq_pg/psycopg/schedule_source.py | 37 +---- tests/integration/test_schedule_source.py | 163 +++++---------------- tests/integration/test_shared_pool.py | 3 - 7 files changed, 47 insertions(+), 319 deletions(-) diff --git a/src/taskiq_pg/_internal/schedule_source.py b/src/taskiq_pg/_internal/schedule_source.py index 0ade9ac..082d07d 100644 --- a/src/taskiq_pg/_internal/schedule_source.py +++ b/src/taskiq_pg/_internal/schedule_source.py @@ -1,23 +1,14 @@ import abc import typing as tp -import uuid -from logging import getLogger -from pydantic import ValidationError from taskiq import ScheduleSource -from taskiq.abc.broker import AsyncBroker -from taskiq.scheduler.scheduled_task import ScheduledTask from taskiq_pg._internal.utils import DsnHelper -logger = getLogger("taskiq_pg") - - class BasePostgresScheduleSource(ScheduleSource, DsnHelper, abc.ABC): def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", **connect_kwargs: tp.Any, @@ -32,53 +23,8 @@ def __init__( Args: dsn: PostgreSQL connection string table_name: Name of the table to store scheduled tasks. Will be created automatically if it doesn't exist. - broker: The TaskIQ broker instance to use for finding and managing tasks. - Required if startup_schedule is provided. **connect_kwargs: Additional keyword arguments passed to the database connection pool. """ - self._broker: tp.Final[AsyncBroker] = broker self._dsn: tp.Final[str | tp.Callable[[], str]] = dsn self._table_name: tp.Final[str] = table_name self._connect_kwargs: tp.Final[tp.Any] = connect_kwargs - - def extract_scheduled_tasks_from_broker(self) -> list[ScheduledTask]: - """ - Extract schedules from tasks that were registered in broker. - - Returns: - A list of ScheduledTask instances extracted from the task's labels. - """ - scheduled_tasks_for_creation: list[ScheduledTask] = [] - for task_name, task in self._broker.get_all_tasks().items(): - if "schedule" not in task.labels: - logger.debug("Task %s has no schedule, skipping", task_name) - continue - if not isinstance(task.labels["schedule"], list): - logger.warning( - "Schedule for task %s is not a list, skipping", - task_name, - ) - continue - for schedule in task.labels["schedule"]: - try: - new_schedule = ScheduledTask.model_validate( - { - "task_name": task_name, - "labels": schedule.get("labels", {}), - "args": schedule.get("args", []), - "kwargs": schedule.get("kwargs", {}), - "schedule_id": str(uuid.uuid4()), - "cron": schedule.get("cron", None), - "cron_offset": schedule.get("cron_offset", None), - "interval": schedule.get("interval", None), - "time": schedule.get("time", None), - }, - ) - scheduled_tasks_for_creation.append(new_schedule) - except ValidationError: # noqa: PERF203 - logger.exception( - "Schedule for task %s is not valid, skipping", - task_name, - ) - continue - return scheduled_tasks_for_creation diff --git a/src/taskiq_pg/aiopg/schedule_source.py b/src/taskiq_pg/aiopg/schedule_source.py index 5dbd1e3..f70c515 100644 --- a/src/taskiq_pg/aiopg/schedule_source.py +++ b/src/taskiq_pg/aiopg/schedule_source.py @@ -1,23 +1,18 @@ import typing as tp -from logging import getLogger from aiopg import Pool, create_pool -from taskiq import AsyncBroker, ScheduledTask +from taskiq import ScheduledTask from taskiq_pg import exceptions from taskiq_pg._internal import BasePostgresScheduleSource from taskiq_pg.aiopg.queries import ( CREATE_SCHEDULES_TABLE_QUERY, - DELETE_ALL_SCHEDULES_QUERY, DELETE_SCHEDULE_QUERY, INSERT_SCHEDULE_QUERY, SELECT_SCHEDULES_QUERY, ) -logger = getLogger("taskiq_pg.aiopg_schedule_source") - - class AiopgScheduleSource(BasePostgresScheduleSource): """Schedule source that uses aiopg to store schedules in PostgreSQL.""" @@ -27,7 +22,6 @@ class AiopgScheduleSource(BasePostgresScheduleSource): @tp.overload def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., *, @@ -38,7 +32,6 @@ def __init__( @tp.overload def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., *, @@ -47,7 +40,6 @@ def __init__( def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", *, @@ -58,7 +50,6 @@ def __init__( Construct a new AiopgScheduleSource. Args: - broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. pool: An existing connection pool to reuse. @@ -70,34 +61,16 @@ def __init__( self._database_pool = pool super().__init__( - broker=broker, dsn=dsn, table_name=table_name, **connect_kwargs, ) - async def _update_schedules_on_startup(self, schedules: list[ScheduledTask]) -> None: - """Update schedules in the database on startup: truncate table and insert new ones.""" - async with self._database_pool.acquire() as connection, connection.cursor() as cursor: - await cursor.execute(DELETE_ALL_SCHEDULES_QUERY.format(self._table_name)) - for schedule in schedules: - await cursor.execute( - INSERT_SCHEDULE_QUERY.format(self._table_name), - [ - schedule.schedule_id, - schedule.task_name, - schedule.model_dump_json( - exclude={"schedule_id", "task_name"}, - ), - ], - ) - async def startup(self) -> None: """ Initialize the schedule source. - Construct new connection pool (if not provided externally), create new table for schedules if not exists - and fill table with schedules from task labels. + Construct new connection pool (if not provided externally), create new table for schedules if not exists. """ try: if self._owns_pool: @@ -107,10 +80,6 @@ async def startup(self) -> None: ) async with self._database_pool.acquire() as connection, connection.cursor() as cursor: await cursor.execute(CREATE_SCHEDULES_TABLE_QUERY.format(self._table_name)) - - logger.debug("Refreshing schedules table") - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) except Exception as error: raise exceptions.DatabaseConnectionError(str(error)) from error diff --git a/src/taskiq_pg/asyncpg/schedule_source.py b/src/taskiq_pg/asyncpg/schedule_source.py index 84ace5e..8e3b71a 100644 --- a/src/taskiq_pg/asyncpg/schedule_source.py +++ b/src/taskiq_pg/asyncpg/schedule_source.py @@ -1,23 +1,18 @@ import json import typing as tp -from logging import getLogger import asyncpg -from taskiq import AsyncBroker, ScheduledTask +from taskiq import ScheduledTask from taskiq_pg._internal import BasePostgresScheduleSource from taskiq_pg.asyncpg.queries import ( CREATE_SCHEDULES_TABLE_QUERY, - DELETE_ALL_SCHEDULES_QUERY, DELETE_SCHEDULE_QUERY, INSERT_SCHEDULE_QUERY, SELECT_SCHEDULES_QUERY, ) -logger = getLogger("taskiq_pg.asyncpg_schedule_source") - - class AsyncpgScheduleSource(BasePostgresScheduleSource): """Schedule source that uses asyncpg to store schedules in PostgreSQL.""" @@ -27,7 +22,6 @@ class AsyncpgScheduleSource(BasePostgresScheduleSource): @tp.overload def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., *, @@ -38,7 +32,6 @@ def __init__( @tp.overload def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., *, @@ -47,7 +40,6 @@ def __init__( def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", *, @@ -58,7 +50,6 @@ def __init__( Construct a new AsyncpgScheduleSource. Args: - broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. pool: An existing connection pool to reuse. @@ -70,32 +61,16 @@ def __init__( self._database_pool = pool super().__init__( - broker=broker, dsn=dsn, table_name=table_name, **connect_kwargs, ) - async def _update_schedules_on_startup(self, schedules: list[ScheduledTask]) -> None: - """Update schedules in the database on startup: truncate table and insert new ones.""" - async with self._database_pool.acquire() as connection, connection.transaction(): - await connection.execute(DELETE_ALL_SCHEDULES_QUERY.format(self._table_name)) - for schedule in schedules: - await self._database_pool.execute( - INSERT_SCHEDULE_QUERY.format(self._table_name), - str(schedule.schedule_id), - schedule.task_name, - schedule.model_dump_json( - exclude={"schedule_id", "task_name"}, - ), - ) - async def startup(self) -> None: """ Initialize the schedule source. - Construct new connection pool (if not provided externally), create new table for schedules if not exists - and fill table with schedules from task labels. + Construct new connection pool (if not provided externally), create new table for schedules if not exists. """ if self._owns_pool: self._database_pool = await asyncpg.create_pool( @@ -108,10 +83,6 @@ async def startup(self) -> None: ), ) - logger.debug("Refreshing schedules table") - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) - async def shutdown(self) -> None: """Close the connection pool if it created by this schedule source.""" if self._owns_pool and getattr(self, "_database_pool", None) is not None: diff --git a/src/taskiq_pg/psqlpy/schedule_source.py b/src/taskiq_pg/psqlpy/schedule_source.py index 7bcc4e5..9065da1 100644 --- a/src/taskiq_pg/psqlpy/schedule_source.py +++ b/src/taskiq_pg/psqlpy/schedule_source.py @@ -1,24 +1,19 @@ import typing as tp import uuid -from logging import getLogger from psqlpy import ConnectionPool from psqlpy.extra_types import JSONB -from taskiq import AsyncBroker, ScheduledTask +from taskiq import ScheduledTask from taskiq_pg._internal import BasePostgresScheduleSource from taskiq_pg.psqlpy.queries import ( CREATE_SCHEDULES_TABLE_QUERY, - DELETE_ALL_SCHEDULES_QUERY, DELETE_SCHEDULE_QUERY, INSERT_SCHEDULE_QUERY, SELECT_SCHEDULES_QUERY, ) -logger = getLogger("taskiq_pg.psqlpy_schedule_source") - - class PSQLPyScheduleSource(BasePostgresScheduleSource): """Schedule source that uses psqlpy to store schedules in PostgreSQL.""" @@ -28,7 +23,6 @@ class PSQLPyScheduleSource(BasePostgresScheduleSource): @tp.overload def __init__( self, - broker: AsyncBroker, dsn: "str | tp.Callable[[], str]" = ..., table_name: str = ..., *, @@ -39,7 +33,6 @@ def __init__( @tp.overload def __init__( self, - broker: AsyncBroker, dsn: "str | tp.Callable[[], str]" = ..., table_name: str = ..., *, @@ -48,7 +41,6 @@ def __init__( def __init__( self, - broker: AsyncBroker, dsn: "str | tp.Callable[[], str]" = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", *, @@ -59,7 +51,6 @@ def __init__( Construct a new PSQLPyScheduleSource. Args: - broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. pool: An existing connection pool to reuse. @@ -72,41 +63,17 @@ def __init__( self._owns_pool = True super().__init__( - broker=broker, dsn=dsn, table_name=table_name, **connect_kwargs, ) - async def _update_schedules_on_startup(self, schedules: list[ScheduledTask]) -> None: - """Update schedules in the database on startup: truncate table and insert new ones.""" - async with self._database_pool.acquire() as connection, connection.transaction(): - await connection.execute(DELETE_ALL_SCHEDULES_QUERY.format(self._table_name)) - data_to_insert: list = [] - for schedule in schedules: - schedule_dict = schedule.model_dump( - mode="json", - exclude={"schedule_id", "task_name"}, - ) - data_to_insert.append( - [ - uuid.UUID(schedule.schedule_id), - schedule.task_name, - JSONB(schedule_dict), - ] - ) - - await connection.execute_many( - INSERT_SCHEDULE_QUERY.format(self._table_name), - data_to_insert, - ) - async def startup(self) -> None: """ Initialize the schedule source. Construct new connection pool (if not provided externally), create new table for - schedules if not exists and fill table with schedules from task labels. + schedules if not exists. """ if self._owns_pool: self._database_pool = ConnectionPool( @@ -120,10 +87,6 @@ async def startup(self) -> None: ), ) - logger.debug("Refreshing schedules table") - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) - async def shutdown(self) -> None: """Close the connection pool if was created by this schedule source.""" if self._owns_pool and getattr(self, "_database_pool", None) is not None: diff --git a/src/taskiq_pg/psycopg/schedule_source.py b/src/taskiq_pg/psycopg/schedule_source.py index 1342401..b10a6ec 100644 --- a/src/taskiq_pg/psycopg/schedule_source.py +++ b/src/taskiq_pg/psycopg/schedule_source.py @@ -1,24 +1,19 @@ import typing as tp import uuid -from logging import getLogger from psycopg import sql from psycopg_pool import AsyncConnectionPool -from taskiq import AsyncBroker, ScheduledTask +from taskiq import ScheduledTask from taskiq_pg._internal import BasePostgresScheduleSource from taskiq_pg.psycopg.queries import ( CREATE_SCHEDULES_TABLE_QUERY, - DELETE_ALL_SCHEDULES_QUERY, DELETE_SCHEDULE_QUERY, INSERT_SCHEDULE_QUERY, SELECT_SCHEDULES_QUERY, ) -logger = getLogger("taskiq_pg.psycopg_schedule_source") - - class PsycopgScheduleSource(BasePostgresScheduleSource): """Schedule source that uses psycopg to store schedules in PostgreSQL.""" @@ -28,7 +23,6 @@ class PsycopgScheduleSource(BasePostgresScheduleSource): @tp.overload def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., *, @@ -39,7 +33,6 @@ def __init__( @tp.overload def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = ..., table_name: str = ..., *, @@ -48,7 +41,6 @@ def __init__( def __init__( self, - broker: AsyncBroker, dsn: str | tp.Callable[[], str] = "postgresql://postgres:postgres@localhost:5432/postgres", table_name: str = "taskiq_schedules", *, @@ -59,7 +51,6 @@ def __init__( Construct a new PsycopgScheduleSource. Args: - broker: The TaskIQ broker instance. dsn: PostgreSQL connection string or callable. Ignored in pool mode. table_name: Table to store schedules in. pool: An existing connection pool to reuse. @@ -71,37 +62,17 @@ def __init__( self._database_pool = pool super().__init__( - broker=broker, dsn=dsn, table_name=table_name, **connect_kwargs, ) - async def _update_schedules_on_startup(self, schedules: list[ScheduledTask]) -> None: - """Update schedules in the database on startup: truncate table and insert new ones.""" - async with self._database_pool.connection() as connection, connection.cursor() as cursor: - await cursor.execute(sql.SQL(DELETE_ALL_SCHEDULES_QUERY).format(sql.Identifier(self._table_name))) - data_to_insert: list = [ - [ - uuid.UUID(schedule.schedule_id), - schedule.task_name, - schedule.model_dump_json( - exclude={"schedule_id", "task_name"}, - ), - ] - for schedule in schedules - ] - await cursor.executemany( - sql.SQL(INSERT_SCHEDULE_QUERY).format(sql.Identifier(self._table_name)), - data_to_insert, - ) - async def startup(self) -> None: """ Initialize the schedule source. Construct new connection pool (if not provided externally), create new table for - schedules if not exists and fill table with schedules from task labels. + schedules if not exists. """ if self._owns_pool: self._database_pool = AsyncConnectionPool( @@ -118,10 +89,6 @@ async def startup(self) -> None: sql.SQL(CREATE_SCHEDULES_TABLE_QUERY).format(sql.Identifier(self._table_name)), ) - logger.debug("Refreshing schedules table") - scheduled_tasks_for_creation = self.extract_scheduled_tasks_from_broker() - await self._update_schedules_on_startup(scheduled_tasks_for_creation) - async def shutdown(self) -> None: """Close the connection pool (only if owned by this source).""" if self._owns_pool and getattr(self, "_database_pool", None) is not None: diff --git a/tests/integration/test_schedule_source.py b/tests/integration/test_schedule_source.py index be6a341..6bcee13 100644 --- a/tests/integration/test_schedule_source.py +++ b/tests/integration/test_schedule_source.py @@ -1,16 +1,14 @@ import uuid from contextlib import asynccontextmanager -from datetime import timedelta import pytest from polyfactory.factories.pydantic_factory import ModelFactory -from sqlalchemy_utils.types.enriched_datetime.arrow_datetime import datetime from taskiq import ScheduledTask -from taskiq_pg._internal import BasePostgresBroker, BasePostgresScheduleSource +from taskiq_pg._internal import BasePostgresScheduleSource from taskiq_pg.aiopg import AiopgScheduleSource from taskiq_pg.asyncpg import AsyncpgScheduleSource -from taskiq_pg.psqlpy import PSQLPyBroker, PSQLPyScheduleSource +from taskiq_pg.psqlpy import PSQLPyScheduleSource from taskiq_pg.psycopg import PsycopgScheduleSource @@ -29,113 +27,16 @@ def schedule_id(cls) -> str: @asynccontextmanager async def _get_schedule_source( schedule_source_class: type[BasePostgresScheduleSource], - broker: BasePostgresBroker, dsn: str, + table_name: str, ): - schedule_source = schedule_source_class(broker, dsn) + schedule_source = schedule_source_class(dsn=dsn, table_name=table_name) try: yield schedule_source finally: await schedule_source.shutdown() -@pytest.fixture -def broker_with_scheduled_tasks(pg_dsn: str) -> PSQLPyBroker: - """Test broker with two tasks: one with one schedule and second with two schedules.""" - broker = PSQLPyBroker(dsn=pg_dsn) - - @broker.task( - task_name="tests:two_schedules", - schedule=[ - { - "cron": "*/10 * * * *", - "cron_offset": "Europe/Berlin", - "time": None, - "args": [42], - "kwargs": {"x": 10}, - "labels": {"foo": "bar"}, - }, - { - "cron": "0 1 * * *", - "cron_offset": timedelta(hours=1), - "time": None, - "args": [], - "kwargs": {}, - "labels": {}, - }, - ], - ) - async def _two_schedules() -> None: - return None - - @broker.task( - task_name="tests:one_schedule", - schedule=[ - { - "cron_offset": None, - "time": datetime(2024, 1, 1, 12, 0, 0), - "args": [], - "kwargs": {}, - "labels": {}, - }, - ], - ) - async def _one_schedule() -> None: - return None - - @broker.task( - task_name="tests:without_schedule", - ) - async def _without_schedule() -> None: - return None - - @broker.task(task_name="tests:invalid_schedule", schedule={}) - async def _invalid_schedule() -> None: - return None - - @broker.task( - task_name="tests:invalid_schedule_2", - schedule=[ - { - "invalid": "data", - } - ], - ) - async def _invalid_schedule_2() -> None: - return None - - return broker - - -@pytest.mark.integration -@pytest.mark.parametrize( - "schedule_source_class", - [ - PSQLPyScheduleSource, - AiopgScheduleSource, - AsyncpgScheduleSource, - PsycopgScheduleSource, - ], -) -async def test_when_labels_contain_schedules__then_get_schedules_returns_scheduled_tasks( - pg_dsn: str, - broker_with_scheduled_tasks: PSQLPyBroker, - schedule_source_class: type[PSQLPyScheduleSource | AiopgScheduleSource | AsyncpgScheduleSource], -) -> None: - # When - async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: - await schedule_source.startup() - schedules: list[ScheduledTask] = await schedule_source.get_schedules() - - # Then - assert len(schedules) == 3 - assert {item.cron for item in schedules} == {"*/10 * * * *", "0 1 * * *", None} - assert {item.cron_offset for item in schedules} == {None, "Europe/Berlin", timedelta(hours=1)} - assert {item.task_name for item in schedules} == {"tests:one_schedule", "tests:two_schedules"} - assert {item.time for item in schedules} == {datetime(2024, 1, 1, 12, 0, 0), None} - assert all(item.schedule_id is not None for item in schedules) - - @pytest.mark.integration @pytest.mark.parametrize( "schedule_source_class", @@ -148,12 +49,17 @@ async def test_when_labels_contain_schedules__then_get_schedules_returns_schedul ) async def test_when_call_add_schedule__then_schedule_creates( pg_dsn: str, - broker_with_scheduled_tasks: PSQLPyBroker, schedule_source_class: type[PSQLPyScheduleSource | AiopgScheduleSource | AsyncpgScheduleSource], ) -> None: # Given - new_schedule = ScheduledTaskFactory.build(task_name="tests:added_schedule", cron="*/5 * * * *", interval=None) - async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: + new_schedule = ScheduledTaskFactory.build( + task_name="tests:added_schedule", + cron="*/5 * * * *", + interval=None, + schedule_id=str(uuid.uuid4()), + ) + table_name = f"taskiq_schedules_{uuid.uuid4().hex}" + async with _get_schedule_source(schedule_source_class, pg_dsn, table_name) as schedule_source: await schedule_source.startup() # When @@ -161,13 +67,8 @@ async def test_when_call_add_schedule__then_schedule_creates( # Then schedules: list[ScheduledTask] = await schedule_source.get_schedules() - assert len(schedules) == 4 - added_schedule = None - for task in schedules: - if task.task_name == "tests:added_schedule": - added_schedule = task - break - assert added_schedule is not None + assert len(schedules) == 1 + assert schedules[0].schedule_id == new_schedule.schedule_id @pytest.mark.integration @@ -182,21 +83,34 @@ async def test_when_call_add_schedule__then_schedule_creates( ) async def test_when_call_delete_schedule__then_schedule_deleted( pg_dsn: str, - broker_with_scheduled_tasks: PSQLPyBroker, schedule_source_class: type[PSQLPyScheduleSource | AiopgScheduleSource | AsyncpgScheduleSource], ) -> None: # Given - async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: + first_schedule = ScheduledTaskFactory.build( + task_name="tests:first_schedule", + cron="*/5 * * * *", + interval=None, + schedule_id=str(uuid.uuid4()), + ) + second_schedule = ScheduledTaskFactory.build( + task_name="tests:second_schedule", + cron="0 1 * * *", + interval=None, + schedule_id=str(uuid.uuid4()), + ) + table_name = f"taskiq_schedules_{uuid.uuid4().hex}" + async with _get_schedule_source(schedule_source_class, pg_dsn, table_name) as schedule_source: await schedule_source.startup() - schedules: list[ScheduledTask] = await schedule_source.get_schedules() - schedule_id_to_delete = str(schedules[0].schedule_id) + await schedule_source.add_schedule(first_schedule) + await schedule_source.add_schedule(second_schedule) + schedule_id_to_delete = first_schedule.schedule_id # When await schedule_source.delete_schedule(schedule_id_to_delete) # Then schedules: list[ScheduledTask] = await schedule_source.get_schedules() - assert len(schedules) == 2 + assert len(schedules) == 1 assert all(task.schedule_id != schedule_id_to_delete for task in schedules) @@ -210,9 +124,8 @@ async def test_when_call_delete_schedule__then_schedule_deleted( PsycopgScheduleSource, ], ) -async def test_when_starting_source_again__then_schedules_are_reset( +async def test_when_starting_source_again__then_schedules_from_previous_run_kept( pg_dsn: str, - broker_with_scheduled_tasks: PSQLPyBroker, schedule_source_class: type[PSQLPyScheduleSource | AiopgScheduleSource | AsyncpgScheduleSource], ) -> None: # Given @@ -222,15 +135,17 @@ async def test_when_starting_source_again__then_schedules_are_reset( interval=None, schedule_id=str(uuid.uuid4()), ) - async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: + table_name = f"taskiq_schedules_{uuid.uuid4().hex}" + async with _get_schedule_source(schedule_source_class, pg_dsn, table_name) as schedule_source: await schedule_source.startup() await schedule_source.add_schedule(new_schedule) + assert len(await schedule_source.get_schedules()) == 1 # When - async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: + async with _get_schedule_source(schedule_source_class, pg_dsn, table_name) as schedule_source: await schedule_source.startup() # Then schedules: list[ScheduledTask] = await schedule_source.get_schedules() - assert len(schedules) == 3 - assert all(task.schedule_id != new_schedule.schedule_id for task in schedules) + assert len(schedules) == 1 + assert any(task.schedule_id == new_schedule.schedule_id for task in schedules) diff --git a/tests/integration/test_shared_pool.py b/tests/integration/test_shared_pool.py index 41adc41..07a5470 100644 --- a/tests/integration/test_shared_pool.py +++ b/tests/integration/test_shared_pool.py @@ -25,7 +25,6 @@ async def test_asyncpg_shared_pool_not_closed_after_shutdown(pg_dsn: str) -> Non pool=pool, ) schedule_source = AsyncpgScheduleSource( - broker=broker, dsn=pg_dsn, table_name=f"taskiq_schedules_{uuid.uuid4().hex}", pool=pool, @@ -92,7 +91,6 @@ async def test_psycopg_shared_pool_not_closed_after_shutdown(pg_dsn: str) -> Non pool=pool, ) schedule_source = PsycopgScheduleSource( - broker=broker, dsn=pg_dsn, table_name=f"taskiq_schedules_{uuid.uuid4().hex}", pool=pool, @@ -165,7 +163,6 @@ async def test_psqlpy_shared_pool_not_closed_after_shutdown(pg_dsn: str) -> None pool=pool, ) schedule_source = PSQLPyScheduleSource( - broker=broker, dsn=pg_dsn, table_name=f"taskiq_schedules_{uuid.uuid4().hex}", pool=pool, From dedffb6ea00da566eb788b5e7b54856c6af021d0 Mon Sep 17 00:00:00 2001 From: Dmitry Davlyatshin Date: Thu, 26 Nov 2026 18:31:16 +0300 Subject: [PATCH 4/5] chore: remove unused DELETE_ALL_SCHEDULES_QUERY from all drivers --- src/taskiq_pg/aiopg/queries.py | 4 ---- src/taskiq_pg/asyncpg/queries.py | 4 ---- src/taskiq_pg/psqlpy/queries.py | 4 ---- src/taskiq_pg/psycopg/queries.py | 4 ---- 4 files changed, 16 deletions(-) diff --git a/src/taskiq_pg/aiopg/queries.py b/src/taskiq_pg/aiopg/queries.py index c85b425..a1ab4ea 100644 --- a/src/taskiq_pg/aiopg/queries.py +++ b/src/taskiq_pg/aiopg/queries.py @@ -70,10 +70,6 @@ FROM {}; """ -DELETE_ALL_SCHEDULES_QUERY = """ -DELETE FROM {}; -""" - DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = %s; """ diff --git a/src/taskiq_pg/asyncpg/queries.py b/src/taskiq_pg/asyncpg/queries.py index cf985d7..5f34913 100644 --- a/src/taskiq_pg/asyncpg/queries.py +++ b/src/taskiq_pg/asyncpg/queries.py @@ -97,10 +97,6 @@ FROM {}; """ -DELETE_ALL_SCHEDULES_QUERY = """ -DELETE FROM {}; -""" - DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = $1; """ diff --git a/src/taskiq_pg/psqlpy/queries.py b/src/taskiq_pg/psqlpy/queries.py index 7ae82a0..da0d0c0 100644 --- a/src/taskiq_pg/psqlpy/queries.py +++ b/src/taskiq_pg/psqlpy/queries.py @@ -97,10 +97,6 @@ FROM {}; """ -DELETE_ALL_SCHEDULES_QUERY = """ -DELETE FROM {}; -""" - DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = $1; """ diff --git a/src/taskiq_pg/psycopg/queries.py b/src/taskiq_pg/psycopg/queries.py index eae3bd3..5c2d6cc 100644 --- a/src/taskiq_pg/psycopg/queries.py +++ b/src/taskiq_pg/psycopg/queries.py @@ -97,10 +97,6 @@ FROM {}; """ -DELETE_ALL_SCHEDULES_QUERY = """ -DELETE FROM {}; -""" - DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = %s; """ From 58c1912a24dc42870423748e013841fe5f685032 Mon Sep 17 00:00:00 2001 From: Dmitry Davlyatshin Date: Thu, 26 Nov 2026 18:35:04 +0300 Subject: [PATCH 5/5] docs: use LabelScheduleSource for label-based schedules in examples and tutorial --- README.md | 9 +++--- docs/index.md | 36 +++++++++++++---------- docs/tutorial/schedule_source.md | 37 ++++++++++++++---------- docs/tutorial/sharing_pool.md | 2 +- examples/example_with_schedule_source.py | 7 ++--- 5 files changed, 50 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 5958c3d..d3c4aae 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ Your experience with other drivers will be pretty similar. Just change the impor # scheduler_example.py import asyncio from taskiq import TaskiqScheduler + from taskiq.schedule_sources import LabelScheduleSource from taskiq_pg.asyncpg import AsyncpgBroker, AsyncpgScheduleSource @@ -101,10 +102,10 @@ Your experience with other drivers will be pretty similar. Just change the impor broker = AsyncpgBroker(dsn) scheduler = TaskiqScheduler( broker=broker, - sources=[AsyncpgScheduleSource( - dsn=dsn, - broker=broker, - )], + sources=[ + LabelScheduleSource(broker), + AsyncpgScheduleSource(dsn=dsn), + ], ) diff --git a/docs/index.md b/docs/index.md index a234421..3bf0b07 100644 --- a/docs/index.md +++ b/docs/index.md @@ -200,6 +200,7 @@ Your experience with other drivers will be pretty similar. Just change the impor # scheduler_example.py import asyncio from taskiq import TaskiqScheduler + from taskiq.schedule_sources import LabelScheduleSource from taskiq_pg.asyncpg import AsyncpgBroker, AsyncpgScheduleSource @@ -207,10 +208,10 @@ Your experience with other drivers will be pretty similar. Just change the impor broker = AsyncpgBroker(dsn) scheduler = TaskiqScheduler( broker=broker, - sources=[AsyncpgScheduleSource( - dsn=dsn, - broker=broker, - )], + sources=[ + LabelScheduleSource(broker), + AsyncpgScheduleSource(dsn=dsn), + ], ) @@ -239,6 +240,7 @@ Your experience with other drivers will be pretty similar. Just change the impor # scheduler_example.py import asyncio from taskiq import TaskiqScheduler + from taskiq.schedule_sources import LabelScheduleSource from taskiq_pg.psqlpy import PSQLPyBroker, PSQLPyScheduleSource @@ -246,10 +248,10 @@ Your experience with other drivers will be pretty similar. Just change the impor broker = PSQLPyBroker(dsn) scheduler = TaskiqScheduler( broker=broker, - sources=[PSQLPyScheduleSource( - dsn=dsn, - broker=broker, - )], + sources=[ + LabelScheduleSource(broker), + PSQLPyScheduleSource(dsn=dsn), + ], ) @@ -279,6 +281,7 @@ Your experience with other drivers will be pretty similar. Just change the impor # scheduler_example.py import asyncio from taskiq import TaskiqScheduler + from taskiq.schedule_sources import LabelScheduleSource from taskiq_pg.psycopg import PsycopgBroker, PsycopgScheduleSource @@ -286,10 +289,10 @@ Your experience with other drivers will be pretty similar. Just change the impor broker = PsycopgBroker(dsn) scheduler = TaskiqScheduler( broker=broker, - sources=[PsycopgScheduleSource( - dsn=dsn, - broker=broker, - )], + sources=[ + LabelScheduleSource(broker), + PsycopgScheduleSource(dsn=dsn), + ], ) @@ -319,6 +322,7 @@ Your experience with other drivers will be pretty similar. Just change the impor # scheduler_example.py import asyncio from taskiq import TaskiqScheduler + from taskiq.schedule_sources import LabelScheduleSource from taskiq_pg.aiopg import AiopgBroker, AiopgScheduleSource @@ -326,10 +330,10 @@ Your experience with other drivers will be pretty similar. Just change the impor broker = AiopgBroker(dsn) scheduler = TaskiqScheduler( broker=broker, - sources=[AiopgScheduleSource( - dsn=dsn, - broker=broker, - )], + sources=[ + LabelScheduleSource(broker), + AiopgScheduleSource(dsn=dsn), + ], ) diff --git a/docs/tutorial/schedule_source.md b/docs/tutorial/schedule_source.md index b1131e6..fef69c0 100644 --- a/docs/tutorial/schedule_source.md +++ b/docs/tutorial/schedule_source.md @@ -4,14 +4,16 @@ title: Schedule Source ## Basic usage -The easiest way to schedule task with this library is to add `schedule` label to task. Schedule source will automatically -parse this label and add new schedule to database on start of scheduler. +The PostgreSQL schedule source stores schedules in a database table: the schedules you add in runtime +(see below) and the ones you pre-populate the table with. They all survive application restarts. -You can define your scheduled task like this: +Schedules declared in task labels are not read by this source: they are handled by taskiq's built-in +`LabelScheduleSource`. Add both sources to your scheduler: ```python import asyncio from taskiq import TaskiqScheduler + from taskiq.schedule_sources import LabelScheduleSource from taskiq_pg.asyncpg import AsyncpgBroker, AsyncpgScheduleSource @@ -19,10 +21,10 @@ You can define your scheduled task like this: broker = AsyncpgBroker(dsn) scheduler = TaskiqScheduler( broker=broker, - sources=[AsyncpgScheduleSource( - dsn=dsn, - broker=broker, - )], + sources=[ + LabelScheduleSource(broker), # schedules declared in task labels + AsyncpgScheduleSource(dsn=dsn), # schedules stored in PostgreSQL + ], ) @@ -59,10 +61,7 @@ You can also add schedules in runtime using `add_schedule` method of the schedul dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres" broker = AsyncpgBroker(dsn) - schedule_source = AsyncpgScheduleSource( - dsn=dsn, - broker=broker, - ) + schedule_source = AsyncpgScheduleSource(dsn=dsn) scheduler = TaskiqScheduler( broker=broker, sources=[schedule_source], @@ -82,13 +81,19 @@ You can also add schedules in runtime using `add_schedule` method of the schedul await schedule_source.add_schedule(ScheduledTask(...)) ``` +Schedules stored in the database are never deleted on startup — they survive restarts. +One-shot (`time`) schedules are removed automatically after they fire. + ## Using multiple schedules -You can use multiple schedules for one task. Just provide a list of schedules to the `@broker.task` decorator: +You can use multiple schedules for one task. Just provide a list of schedules to the `@broker.task` decorator. +These label-based schedules are picked up by `LabelScheduleSource`; the PostgreSQL source only stores +the schedules you add via `add_schedule`: ```python import asyncio from taskiq import TaskiqScheduler +from taskiq.schedule_sources import LabelScheduleSource from taskiq_pg.asyncpg import AsyncpgBroker, AsyncpgScheduleSource @@ -96,10 +101,10 @@ dsn = "postgres://taskiq_postgres:look_in_vault@localhost:5432/taskiq_postgres" broker = AsyncpgBroker(dsn) scheduler = TaskiqScheduler( broker=broker, - sources=[AsyncpgScheduleSource( - dsn=dsn, - broker=broker, - )], + sources=[ + LabelScheduleSource(broker), + AsyncpgScheduleSource(dsn=dsn), + ], ) diff --git a/docs/tutorial/sharing_pool.md b/docs/tutorial/sharing_pool.md index 80ed43a..a5c1135 100644 --- a/docs/tutorial/sharing_pool.md +++ b/docs/tutorial/sharing_pool.md @@ -40,7 +40,7 @@ async def main() -> None: PsycopgResultBackend(pool=pool) ) - schedule_source = PsycopgScheduleSource(broker=broker, pool=pool) + schedule_source = PsycopgScheduleSource(pool=pool) scheduler = TaskiqScheduler(broker=broker, sources=[schedule_source]) await broker.startup() diff --git a/examples/example_with_schedule_source.py b/examples/example_with_schedule_source.py index 2a459f3..73f5237 100644 --- a/examples/example_with_schedule_source.py +++ b/examples/example_with_schedule_source.py @@ -11,6 +11,7 @@ import asyncio from taskiq import TaskiqScheduler +from taskiq.schedule_sources import LabelScheduleSource from taskiq_pg.psycopg import PsycopgBroker, PsycopgScheduleSource @@ -20,10 +21,8 @@ scheduler = TaskiqScheduler( broker=broker, sources=[ - PsycopgScheduleSource( - dsn=dsn, - broker=broker, - ), + LabelScheduleSource(broker), + PsycopgScheduleSource(dsn=dsn), ], )