|
| 1 | +import asyncio |
| 2 | +from contextlib import suppress |
| 3 | +from datetime import timedelta |
| 4 | +from typing import Any |
| 5 | +from unittest.mock import AsyncMock |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | +from taskiq import BrokerMessage, ScheduleSource, TaskiqScheduler |
| 10 | +from taskiq.api import run_scheduler_task |
| 11 | +from taskiq.cli.scheduler.args import SchedulerArgs |
| 12 | +from taskiq.cli.scheduler.run import SchedulerLoop, run_scheduler |
| 13 | +from taskiq.scheduler.scheduled_task import ScheduledTask |
| 14 | +from tests.utils import AsyncQueueBroker |
| 15 | + |
| 16 | + |
| 17 | +class PendingOperation: |
| 18 | + def __init__(self, cleanup_allowed: asyncio.Event) -> None: |
| 19 | + self.started = asyncio.Event() |
| 20 | + self.cleanup_started = asyncio.Event() |
| 21 | + self.finished = asyncio.Event() |
| 22 | + self.cleanup_allowed = cleanup_allowed |
| 23 | + self.task: asyncio.Task[Any] | None = None |
| 24 | + |
| 25 | + async def run(self) -> None: |
| 26 | + self.task = asyncio.current_task() |
| 27 | + self.started.set() |
| 28 | + try: |
| 29 | + await asyncio.Event().wait() |
| 30 | + finally: |
| 31 | + self.cleanup_started.set() |
| 32 | + await self.cleanup_allowed.wait() |
| 33 | + self.finished.set() |
| 34 | + |
| 35 | + |
| 36 | +@pytest.mark.parametrize("entrypoint", ["loop", "api", "cli"]) |
| 37 | +async def test_shutdown_drains_sends_and_updates( |
| 38 | + entrypoint: str, |
| 39 | + monkeypatch: pytest.MonkeyPatch, |
| 40 | + caplog: pytest.LogCaptureFixture, |
| 41 | +) -> None: |
| 42 | + """Owned operations must finish cleanup before scheduler resources close.""" |
| 43 | + cleanup_allowed = asyncio.Event() |
| 44 | + sending = PendingOperation(cleanup_allowed) |
| 45 | + updating = PendingOperation(cleanup_allowed) |
| 46 | + shutdowns: list[str] = [] |
| 47 | + |
| 48 | + class BlockingBroker(AsyncQueueBroker): |
| 49 | + async def kick(self, message: BrokerMessage) -> None: |
| 50 | + await sending.run() |
| 51 | + |
| 52 | + async def shutdown(self) -> None: |
| 53 | + shutdowns.append("broker") |
| 54 | + assert sending.finished.is_set() |
| 55 | + assert updating.finished.is_set() |
| 56 | + await super().shutdown() |
| 57 | + |
| 58 | + class BlockingSource(ScheduleSource): |
| 59 | + fetched = False |
| 60 | + |
| 61 | + async def get_schedules(self) -> list[ScheduledTask]: |
| 62 | + if self.fetched: |
| 63 | + await updating.run() |
| 64 | + self.fetched = True |
| 65 | + return [ |
| 66 | + ScheduledTask( |
| 67 | + task_name="test", |
| 68 | + labels={}, |
| 69 | + args=[], |
| 70 | + kwargs={}, |
| 71 | + interval=1, |
| 72 | + ), |
| 73 | + ] |
| 74 | + |
| 75 | + async def shutdown(self) -> None: |
| 76 | + shutdowns.append("source") |
| 77 | + assert updating.finished.is_set() |
| 78 | + |
| 79 | + monkeypatch.setattr( |
| 80 | + "taskiq.cli.scheduler.run._sleep_until_next_second", |
| 81 | + AsyncMock(), |
| 82 | + ) |
| 83 | + scheduler = TaskiqScheduler(BlockingBroker(), [BlockingSource()]) |
| 84 | + if entrypoint == "cli": |
| 85 | + coroutine = run_scheduler( |
| 86 | + SchedulerArgs( |
| 87 | + scheduler=scheduler, |
| 88 | + modules=[], |
| 89 | + update_interval=0, |
| 90 | + configure_logging=False, |
| 91 | + ), |
| 92 | + ) |
| 93 | + elif entrypoint == "api": |
| 94 | + coroutine = run_scheduler_task(scheduler, interval=timedelta(0)) |
| 95 | + else: |
| 96 | + coroutine = SchedulerLoop(scheduler).run(update_interval=timedelta(0)) |
| 97 | + |
| 98 | + scheduler_task = asyncio.create_task(coroutine) |
| 99 | + cleanup_started = asyncio.gather( |
| 100 | + sending.cleanup_started.wait(), |
| 101 | + updating.cleanup_started.wait(), |
| 102 | + ) |
| 103 | + try: |
| 104 | + await asyncio.wait_for( |
| 105 | + asyncio.gather(sending.started.wait(), updating.started.wait()), |
| 106 | + 5, |
| 107 | + ) |
| 108 | + scheduler_task.cancel() |
| 109 | + waitables: list[asyncio.Future[Any]] = [scheduler_task, cleanup_started] |
| 110 | + done, _ = await asyncio.wait( |
| 111 | + waitables, |
| 112 | + timeout=5, |
| 113 | + return_when=asyncio.FIRST_COMPLETED, |
| 114 | + ) |
| 115 | + assert cleanup_started in done |
| 116 | + assert not scheduler_task.done() |
| 117 | + assert not shutdowns |
| 118 | + |
| 119 | + cleanup_allowed.set() |
| 120 | + with suppress(asyncio.CancelledError): |
| 121 | + await asyncio.wait_for(scheduler_task, 5) |
| 122 | + |
| 123 | + assert sending.finished.is_set() |
| 124 | + assert updating.finished.is_set() |
| 125 | + assert scheduler_task.cancelled() == (entrypoint != "cli") |
| 126 | + assert shutdowns == (["broker", "source"] if entrypoint == "cli" else []) |
| 127 | + finally: |
| 128 | + cleanup_allowed.set() |
| 129 | + tasks = [ |
| 130 | + task |
| 131 | + for task in (scheduler_task, sending.task, updating.task) |
| 132 | + if task is not None |
| 133 | + ] |
| 134 | + for task in tasks: |
| 135 | + task.cancel() |
| 136 | + await asyncio.gather(*tasks, return_exceptions=True) |
| 137 | + cleanup_started.cancel() |
| 138 | + await asyncio.gather(cleanup_started, return_exceptions=True) |
| 139 | + |
| 140 | + assert "Exception in callback" not in caplog.text |
0 commit comments