|
| 1 | +import uuid |
| 2 | +from logging import getLogger |
| 3 | + |
| 4 | +from aiopg import Pool, create_pool |
| 5 | +from pydantic import ValidationError |
| 6 | +from taskiq import ScheduledTask |
| 7 | + |
| 8 | +from taskiq_pg import exceptions |
| 9 | +from taskiq_pg._internal import BasePostgresScheduleSource |
| 10 | +from taskiq_pg.aiopg.queries import ( |
| 11 | + CREATE_SCHEDULES_TABLE_QUERY, |
| 12 | + DELETE_ALL_SCHEDULES_QUERY, |
| 13 | + INSERT_SCHEDULE_QUERY, |
| 14 | + SELECT_SCHEDULES_QUERY, |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +logger = getLogger("taskiq_pg.aiopg_schedule_source") |
| 19 | + |
| 20 | + |
| 21 | +class AiopgScheduleSource(BasePostgresScheduleSource): |
| 22 | + """Schedule source that uses aiopg to store schedules in PostgreSQL.""" |
| 23 | + |
| 24 | + _database_pool: Pool |
| 25 | + |
| 26 | + async def _update_schedules_on_startup(self, schedules: list[ScheduledTask]) -> None: |
| 27 | + """Update schedules in the database on startup: truncate table and insert new ones.""" |
| 28 | + async with self._database_pool.acquire() as connection, connection.cursor() as cursor: |
| 29 | + await cursor.execute(DELETE_ALL_SCHEDULES_QUERY.format(self._table_name)) |
| 30 | + for schedule in schedules: |
| 31 | + await cursor.execute( |
| 32 | + INSERT_SCHEDULE_QUERY.format(self._table_name), |
| 33 | + [ |
| 34 | + schedule.schedule_id, |
| 35 | + schedule.task_name, |
| 36 | + schedule.model_dump_json( |
| 37 | + exclude={"schedule_id", "task_name"}, |
| 38 | + ), |
| 39 | + ], |
| 40 | + ) |
| 41 | + |
| 42 | + def _get_schedules_from_broker_tasks(self) -> list[ScheduledTask]: |
| 43 | + """Extract schedules from the broker's registered tasks.""" |
| 44 | + scheduled_tasks_for_creation: list[ScheduledTask] = [] |
| 45 | + for task_name, task in self._broker.get_all_tasks().items(): |
| 46 | + if "schedule" not in task.labels: |
| 47 | + logger.debug("Task %s has no schedule, skipping", task_name) |
| 48 | + continue |
| 49 | + if not isinstance(task.labels["schedule"], list): |
| 50 | + logger.warning( |
| 51 | + "Schedule for task %s is not a list, skipping", |
| 52 | + task_name, |
| 53 | + ) |
| 54 | + continue |
| 55 | + for schedule in task.labels["schedule"]: |
| 56 | + try: |
| 57 | + new_schedule = ScheduledTask.model_validate( |
| 58 | + { |
| 59 | + "task_name": task_name, |
| 60 | + "labels": schedule.get("labels", {}), |
| 61 | + "args": schedule.get("args", []), |
| 62 | + "kwargs": schedule.get("kwargs", {}), |
| 63 | + "schedule_id": str(uuid.uuid4()), |
| 64 | + "cron": schedule.get("cron", None), |
| 65 | + "cron_offset": schedule.get("cron_offset", None), |
| 66 | + "time": schedule.get("time", None), |
| 67 | + }, |
| 68 | + ) |
| 69 | + scheduled_tasks_for_creation.append(new_schedule) |
| 70 | + except ValidationError: |
| 71 | + logger.exception( |
| 72 | + "Schedule for task %s is not valid, skipping", |
| 73 | + task_name, |
| 74 | + ) |
| 75 | + continue |
| 76 | + return scheduled_tasks_for_creation |
| 77 | + |
| 78 | + async def startup(self) -> None: |
| 79 | + """ |
| 80 | + Initialize the schedule source. |
| 81 | +
|
| 82 | + Construct new connection pool, create new table for schedules if not exists |
| 83 | + and fill table with schedules from task labels. |
| 84 | + """ |
| 85 | + try: |
| 86 | + self._database_pool = await create_pool( |
| 87 | + dsn=self.dsn, |
| 88 | + **self._connect_kwargs, |
| 89 | + ) |
| 90 | + async with self._database_pool.acquire() as connection, connection.cursor() as cursor: |
| 91 | + await cursor.execute(CREATE_SCHEDULES_TABLE_QUERY.format(self._table_name)) |
| 92 | + scheduled_tasks_for_creation = self._get_schedules_from_broker_tasks() |
| 93 | + await self._update_schedules_on_startup(scheduled_tasks_for_creation) |
| 94 | + except Exception as error: |
| 95 | + raise exceptions.DatabaseConnectionError(str(error)) from error |
| 96 | + |
| 97 | + async def shutdown(self) -> None: |
| 98 | + """Close the connection pool.""" |
| 99 | + if getattr(self, "_database_pool", None) is not None: |
| 100 | + self._database_pool.close() |
| 101 | + |
| 102 | + async def get_schedules(self) -> list["ScheduledTask"]: |
| 103 | + """Fetch schedules from the database.""" |
| 104 | + async with self._database_pool.acquire() as connection, connection.cursor() as cursor: |
| 105 | + await cursor.execute( |
| 106 | + SELECT_SCHEDULES_QUERY.format(self._table_name), |
| 107 | + ) |
| 108 | + schedules, rows = [], await cursor.fetchall() |
| 109 | + for schedule_id, task_name, schedule in rows: |
| 110 | + schedules.append( |
| 111 | + ScheduledTask.model_validate( |
| 112 | + { |
| 113 | + "schedule_id": str(schedule_id), |
| 114 | + "task_name": task_name, |
| 115 | + "labels": schedule["labels"], |
| 116 | + "args": schedule["args"], |
| 117 | + "kwargs": schedule["kwargs"], |
| 118 | + "cron": schedule["cron"], |
| 119 | + "cron_offset": schedule["cron_offset"], |
| 120 | + "time": schedule["time"], |
| 121 | + }, |
| 122 | + ), |
| 123 | + ) |
| 124 | + return schedules |
0 commit comments