Spaces:
Running

File size: 4,140 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""Event-triggered workflows and continuations after a ``wait`` step.



* ``fan_out``: called by ``core.events.store.record`` for every newly recorded event. Each

  active ``workflow_triggers`` row whose ``event_type`` matches (and whose conditions hold on

  the event) gets one ``workflow.run`` event, deduplicated per (workflow, version, source

  event). Intake routes enqueue them right away; other paths are picked up by the worker's

  stale-event sweep.

* ``fire_due_waits``: called by the schedule sweep (owner role). A due wait becomes one

  ``workflow.run`` continuation event (``resume`` = wait id), dispatched with the schedules.

"""

from __future__ import annotations

import uuid
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from core.agent.state import Event
from core.workflows import refs
from core.workflows.dsl import Condition
from core.workflows.executor import WORKFLOW_INTENT
from core.workflows.models import WorkflowTrigger, WorkflowWait

if TYPE_CHECKING:
    from core.events.intake import NormalizedEvent


def _derived(

    workflow_id: uuid.UUID, version: int, source_event_id: uuid.UUID, event: Event

) -> NormalizedEvent:
    from core.events.intake import NormalizedEvent

    payload = {
        "workflow_id": str(workflow_id),
        "version": version,
        "trigger": "event",
        "source_event_id": str(source_event_id),
        "event": {"type": event.type, "source": event.source, "payload": event.payload},
    }
    wf_event = Event(type=WORKFLOW_INTENT, source=event.source, payload=payload)
    key = f"workflow:{workflow_id}:{version}:{source_event_id}"
    return NormalizedEvent(wf_event, key)


async def matching(

    session: AsyncSession, tenant_id: uuid.UUID, event: Event

) -> list[WorkflowTrigger]:
    if event.type.startswith("workflow."):
        return []
    rows = (
        await session.execute(
            select(WorkflowTrigger).where(
                WorkflowTrigger.tenant_id == tenant_id,
                WorkflowTrigger.event_type == event.type,
                WorkflowTrigger.enabled.is_(True),
            )
        )
    ).scalars()
    scope = refs.Scope(event={"type": event.type, "source": event.source, "payload": event.payload})
    out = []
    for t in rows:
        conds = [Condition.model_validate(c) for c in t.conditions or []]
        if refs.all_hold(conds, scope):
            out.append(t)
    return out


async def fan_out(

    session: AsyncSession, tenant_id: uuid.UUID, event_id: uuid.UUID, event: Event

) -> list[NormalizedEvent]:
    """``workflow.run`` events for the subscriptions an event matches (not yet recorded)."""
    return [
        _derived(t.workflow_id, t.version, event_id, event)
        for t in await matching(session, tenant_id, event)
    ]


async def fire_due_waits(

    session: AsyncSession, now: datetime | None = None, limit: int = 500

) -> list[tuple[uuid.UUID, NormalizedEvent]]:
    """Owner sweep: due waits -> (tenant, continuation event); marks them fired."""
    from core.events.intake import NormalizedEvent

    now = now or datetime.now(UTC)
    due = (
        await session.execute(
            select(WorkflowWait)
            .where(WorkflowWait.status == "waiting", WorkflowWait.resume_at <= now)
            .order_by(WorkflowWait.resume_at)
            .limit(limit)
            .with_for_update(skip_locked=True)
        )
    ).scalars()
    out: list[tuple[uuid.UUID, NormalizedEvent]] = []
    for w in list(due):
        w.status = "fired"
        payload: dict[str, Any] = {
            "workflow_id": str(w.workflow_id),
            "version": w.version,
            "trigger": "continuation",
            "resume": str(w.id),
            "after_step": w.step_id,
        }
        ev = Event(type=WORKFLOW_INTENT, source="cron", payload=payload)
        out.append((w.tenant_id, NormalizedEvent(ev, f"workflow-wait:{w.id}")))
    await session.flush()
    return out