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), ], ) diff --git a/src/taskiq_pg/_internal/schedule_source.py b/src/taskiq_pg/_internal/schedule_source.py index 499fc74..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 = broker - self._dsn: tp.Final = dsn - self._table_name: tp.Final = table_name - self._connect_kwargs: tp.Final = 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 + 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 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/aiopg/schedule_source.py b/src/taskiq_pg/aiopg/schedule_source.py index 2fc6434..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,8 +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)) - 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/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/asyncpg/schedule_source.py b/src/taskiq_pg/asyncpg/schedule_source.py index 52c921f..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( @@ -107,8 +82,6 @@ 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) async def shutdown(self) -> None: """Close the connection pool if it created by this schedule source.""" 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/psqlpy/schedule_source.py b/src/taskiq_pg/psqlpy/schedule_source.py index 0114c60..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( @@ -119,8 +86,6 @@ 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) async def shutdown(self) -> None: """Close the connection pool if was created by this schedule source.""" @@ -171,7 +136,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/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; """ diff --git a/src/taskiq_pg/psycopg/schedule_source.py b/src/taskiq_pg/psycopg/schedule_source.py index 418f021..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,12 +51,10 @@ 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. **connect_kwargs: Extra kwargs for connection pool creation. - """ self._owns_pool = True if pool is not None: @@ -72,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,8 +88,6 @@ 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) 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..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,84 +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", @@ -117,23 +47,28 @@ async def _invalid_schedule_2() -> None: PsycopgScheduleSource, ], ) -async def test_when_labels_contain_schedules__then_get_schedules_returns_scheduled_tasks( +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: - # When - async with _get_schedule_source(schedule_source_class, broker_with_scheduled_tasks, pg_dsn) as schedule_source: + # Given + 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() - 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) + # When + await schedule_source.add_schedule(new_schedule) + + # Then + schedules: list[ScheduledTask] = await schedule_source.get_schedules() + assert len(schedules) == 1 + assert schedules[0].schedule_id == new_schedule.schedule_id @pytest.mark.integration @@ -146,28 +81,37 @@ async def test_when_labels_contain_schedules__then_get_schedules_returns_schedul PsycopgScheduleSource, ], ) -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 - 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: + 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() + 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.add_schedule(new_schedule) + await schedule_source.delete_schedule(schedule_id_to_delete) # 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 all(task.schedule_id != schedule_id_to_delete for task in schedules) @pytest.mark.integration @@ -180,21 +124,28 @@ async def test_when_call_add_schedule__then_schedule_creates( PsycopgScheduleSource, ], ) -async def test_when_call_delete_schedule__then_schedule_deleted( +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 - 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() - schedules: list[ScheduledTask] = await schedule_source.get_schedules() - schedule_id_to_delete = str(schedules[0].schedule_id) + await schedule_source.add_schedule(new_schedule) + assert len(await schedule_source.get_schedules()) == 1 - # When - await schedule_source.delete_schedule(schedule_id_to_delete) + # When + 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) == 2 - assert all(task.schedule_id != schedule_id_to_delete 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,