SurfSense/surfsense_backend/app/automations/triggers/schedule/dispatch.py
2026-05-27 17:56:02 +02:00

48 lines
1.6 KiB
Python

"""Schedule dispatch adapter: load + guard, then call generic dispatch."""
from __future__ import annotations
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.automations.dispatch import DispatchError, dispatch_run
from app.automations.persistence.enums.automation_status import AutomationStatus
from app.automations.persistence.models.automation import Automation
from app.automations.persistence.models.run import AutomationRun
from app.automations.persistence.models.trigger import AutomationTrigger
async def dispatch_schedule_run(
*,
session: AsyncSession,
trigger: AutomationTrigger,
) -> AutomationRun:
"""Fire one scheduled run for ``trigger``.
The caller (the schedule tick) is responsible for selecting due triggers
and advancing ``next_fire_at`` / ``last_fired_at`` before invoking this.
"""
automation = await _load_automation(session, trigger.automation_id)
if automation is None:
raise DispatchError(
f"automation {trigger.automation_id} not found for trigger {trigger.id}"
)
if automation.status != AutomationStatus.ACTIVE:
raise DispatchError(
f"automation {trigger.automation_id} is {automation.status.value}, not active"
)
return await dispatch_run(
session=session,
automation=automation,
trigger=trigger,
payload=None,
)
async def _load_automation(
session: AsyncSession, automation_id: int
) -> Automation | None:
stmt = select(Automation).where(Automation.id == automation_id)
return (await session.execute(stmt)).scalar_one_or_none()