Coverage for apps / backend / src / orcheo_backend / app / repository_postgres / _triggers.py: 98%
197 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-16 14:04 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-16 14:04 +0000
1"""Trigger configuration and dispatch helpers."""
3from __future__ import annotations
4from collections.abc import Mapping
5from datetime import UTC, datetime
6from typing import Any, Protocol, cast
7from uuid import UUID
8from orcheo.models import WorkflowRun
9from orcheo.triggers.cron import CronTriggerConfig
10from orcheo.triggers.layer.models import CronDispatchPlan
11from orcheo.triggers.manual import ManualDispatchRequest
12from orcheo.triggers.webhook import WebhookRequest, WebhookTriggerConfig
13from orcheo.vault.oauth import CredentialHealthError
14from orcheo_backend.app.errors import WorkspaceQuotaExceededError
15from orcheo_backend.app.repository import (
16 CronTriggerNotFoundError,
17 WorkflowNotFoundError,
18 WorkflowVersionNotFoundError,
19)
20from orcheo_backend.app.repository_postgres._base import logger
21from orcheo_backend.app.repository_postgres._persistence import PostgresPersistenceMixin
24class _WorkflowWorkspaceLookup(Protocol):
25 async def _get_workflow_workspace_id_locked(
26 self, workflow_id: UUID
27 ) -> str | None: ... # pragma: no cover
30def _enqueue_run_for_execution(run: WorkflowRun) -> bool:
31 """Enqueue the workflow run for execution.
33 Single-process deployments (the desktop app) have no Celery broker, so with
34 ``ORCHEO_INPROCESS_EXECUTION`` enabled the run is executed on the backend
35 event loop instead. Otherwise the run is published to Celery.
37 This function is best-effort: if Celery/Redis is unavailable, flagged
38 trigger runs remain pending for the background reconciler to republish.
40 NOTE: This must only be called AFTER the run has been committed to the database.
41 """
42 from orcheo_backend.app.local_execution import schedule_run_inprocess 1xzAByCDUE
44 if schedule_run_inprocess(run): 1xzAByCDUE
45 return True 1U
47 try: 1xzAByCDE
48 from orcheo_backend.worker.tasks import execute_run 1xzAByCDE
50 headers = ( 1xzAByCDE
51 {"workspace_id": run.workspace_id} if run.workspace_id is not None else {}
52 )
53 enqueue = getattr(execute_run, "apply_async", None) 1xzAByCDE
54 if enqueue is None: 1xzAByCDE
55 execute_run.delay(str(run.id), headers=headers or None) 1AB
56 else:
57 enqueue(args=(str(run.id),), headers=headers or None) 1xzyCDE
58 logger.info("Enqueued run %s for execution", run.id) 1zABCDE
59 return True 1zABCDE
60 except Exception as exc: 1xy
61 logger.warning( 1xy
62 "Failed to enqueue run %s for execution: %s. "
63 "Run remains pending for reconciliation.",
64 run.id,
65 exc,
66 )
67 return False 1xy
70async def _enqueue_run_and_confirm(
71 repository: PostgresPersistenceMixin, run: WorkflowRun
72) -> None:
73 """Publish a committed run and record acceptance by the broker."""
74 if not _enqueue_run_for_execution(run): 1fVOXWacgn
75 return 1X
76 try: 1fVOWacgn
77 await repository.mark_run_enqueued(run.id) 1fVOWacgn
78 except Exception: 1O
79 logger.exception("Could not confirm enqueue for run %s", run.id) 1O
82class TriggerRepositoryMixin(PostgresPersistenceMixin):
83 """Coordinate trigger configuration and dispatch flows."""
85 async def configure_webhook_trigger(
86 self,
87 workflow_id: UUID,
88 config: WebhookTriggerConfig,
89 ) -> WebhookTriggerConfig:
90 await self._ensure_initialized() 1opvGPH
91 async with self._lock: 1opvGPH
92 workflow = await self._get_workflow_locked(workflow_id) 1opvGPH
93 if workflow.is_archived: 1opvGPH
94 raise WorkflowNotFoundError(str(workflow_id)) 1P
95 normalized = self._trigger_layer.configure_webhook(workflow_id, config) 1opvGH
96 async with self._connection() as conn: 1opvGH
97 await conn.execute( 1opvGH
98 """
99 INSERT INTO webhook_triggers (workflow_id, config)
100 VALUES (%s, %s)
101 ON CONFLICT(workflow_id) DO UPDATE SET config=EXCLUDED.config
102 """,
103 (str(workflow_id), self._dump_config(normalized)),
104 )
105 return normalized.model_copy(deep=True) 1opvGH
107 async def get_webhook_trigger_config(
108 self, workflow_id: UUID
109 ) -> WebhookTriggerConfig:
110 await self._ensure_initialized() 1vT
111 async with self._lock: 1vT
112 await self._get_workflow_locked(workflow_id) 1vT
113 return self._trigger_layer.get_webhook_config(workflow_id) 1vT
115 async def handle_webhook_trigger(
116 self,
117 workflow_id: UUID,
118 *,
119 method: str,
120 headers: Mapping[str, str],
121 query_params: Mapping[str, str],
122 payload: Any,
123 source_ip: str | None,
124 ) -> WorkflowRun:
125 await self._ensure_initialized() 1Qn
126 async with self._lock: 1Qn
127 workflow = await self._get_workflow_locked(workflow_id) 1Qn
128 if workflow.is_archived: 1Qn
129 raise WorkflowNotFoundError(str(workflow_id)) 1Q
130 workspace_repo = cast(_WorkflowWorkspaceLookup, self) 1n
131 workspace_id = await workspace_repo._get_workflow_workspace_id_locked( 1n
132 workflow_id
133 )
134 version = await self._get_latest_version_locked(workflow_id) 1n
135 await self._ensure_workflow_health( 1n
136 workflow_id,
137 actor="webhook",
138 workspace_id=workspace_id,
139 )
140 request = WebhookRequest( 1n
141 method=method,
142 headers=headers,
143 query_params=query_params,
144 payload=payload,
145 source_ip=source_ip,
146 )
147 dispatch = self._trigger_layer.prepare_webhook_dispatch( 1n
148 workflow_id, request
149 )
150 run = await self._create_run_locked( 1n
151 workflow_id=workflow_id,
152 workflow_version_id=version.id,
153 triggered_by=dispatch.triggered_by,
154 input_payload=dispatch.input_payload,
155 actor=dispatch.actor,
156 workspace_id=workspace_id,
157 dispatch_requested=True,
158 )
159 run_copy = run.model_copy(deep=True) 1n
160 # Enqueue AFTER lock is released to ensure commit is fully visible
161 await _enqueue_run_and_confirm(self, run_copy) 1n
162 return run_copy 1n
164 async def configure_cron_trigger(
165 self,
166 workflow_id: UUID,
167 config: CronTriggerConfig,
168 ) -> CronTriggerConfig:
169 await self._ensure_initialized() 1jopIrsRJ
170 async with self._lock: 1jopIrsRJ
171 workflow = await self._get_workflow_locked(workflow_id) 1jopIrsRJ
172 if workflow.is_archived: 1jopIrsRJ
173 raise WorkflowNotFoundError(str(workflow_id)) 1R
174 normalized = self._trigger_layer.configure_cron(workflow_id, config) 1jopIrsJ
175 async with self._connection() as conn: 1jopIrsJ
176 await conn.execute( 1jopIrsJ
177 """
178 INSERT INTO cron_triggers (workflow_id, config)
179 VALUES (%s, %s)
180 ON CONFLICT(workflow_id) DO UPDATE SET config=EXCLUDED.config
181 """,
182 (str(workflow_id), self._dump_config(normalized)),
183 )
184 return normalized.model_copy(deep=True) 1jopIrsJ
186 async def get_cron_trigger_config(self, workflow_id: UUID) -> CronTriggerConfig:
187 await self._ensure_initialized() 1jsM
188 async with self._lock: 1jsM
189 await self._get_workflow_locked(workflow_id) 1jsM
190 config = self._trigger_layer.get_cron_config(workflow_id) 1jsM
191 if config is None: 1jsM
192 raise CronTriggerNotFoundError( # pragma: no cover - defensive
193 f"No cron trigger configured for workflow {workflow_id}"
194 )
195 return config 1jsM
197 async def delete_cron_trigger(self, workflow_id: UUID) -> None:
198 await self._ensure_initialized() 1jrN
199 async with self._lock: 1jrN
200 await self._get_workflow_locked(workflow_id) 1jrN
201 async with self._connection() as conn: 1jrN
202 await conn.execute( 1jrN
203 """
204 DELETE FROM cron_triggers
205 WHERE workflow_id = %s
206 """,
207 (str(workflow_id),),
208 )
209 self._trigger_layer.remove_cron_config(workflow_id) 1jrN
211 async def _plans_in_workspace_locked(
212 self, plans: list[CronDispatchPlan], workspace_id: str | None
213 ) -> list[CronDispatchPlan]:
214 """Keep only ``workspace_id``'s plans; all of them when it is None."""
215 if workspace_id is None: 1dtmkehal
216 return plans 1dmkehal
217 lookup = cast(_WorkflowWorkspaceLookup, self) 1t
218 return [ 1t
219 plan
220 for plan in plans
221 if str(await lookup._get_workflow_workspace_id_locked(plan.workflow_id))
222 == workspace_id
223 ]
225 async def dispatch_due_cron_runs(
226 self, *, now: datetime | None = None, workspace_id: str | None = None
227 ) -> list[WorkflowRun]:
228 await self._ensure_initialized() 1dtmkehal
229 reference = now or datetime.now(tz=UTC) 1dtmkehal
230 if reference.tzinfo is None: 1dtmkehal
231 reference = reference.replace(tzinfo=UTC) 1l
233 runs: list[WorkflowRun] = [] 1dtmkehal
235 async with self._lock: 1dtmkehal
236 # Sync cron triggers each dispatch to reflect updates from other processes.
237 await self._refresh_cron_triggers() 1dtmkehal
238 plans = self._trigger_layer.collect_due_cron_dispatches(now=reference) 1dtmkehal
239 plans = await self._plans_in_workspace_locked(plans, workspace_id) 1dtmkehal
240 for plan in plans: 1dtmkehal
241 try: 1dmkehal
242 workflow = await self._get_workflow_locked(plan.workflow_id) 1dmkehal
243 except WorkflowNotFoundError: 1l
244 self._trigger_layer.remove_cron_config(plan.workflow_id) 1l
245 continue 1l
246 if workflow.is_archived: 1dmkeha
247 self._trigger_layer.remove_cron_config(plan.workflow_id) 1m
248 continue 1m
249 try: 1dkeha
250 version = await self._get_latest_version_locked(plan.workflow_id) 1dkeha
251 except WorkflowVersionNotFoundError: 1k
252 continue 1k
253 workspace_repo = cast(_WorkflowWorkspaceLookup, self) 1deha
254 workspace_id = await workspace_repo._get_workflow_workspace_id_locked( 1deha
255 plan.workflow_id
256 )
258 try: 1deha
259 await self._ensure_workflow_health( 1deha
260 plan.workflow_id,
261 actor="cron",
262 workspace_id=workspace_id,
263 )
264 except CredentialHealthError as exc: 1h
265 logger.warning( 1h
266 "Skipping cron dispatch for workflow %s due to credential "
267 "health error: %s",
268 plan.workflow_id,
269 exc,
270 )
271 continue 1h
273 try: 1dea
274 run = await self._create_cron_run_once( 1dea
275 plan, version_id=version.id, workspace_id=workspace_id
276 )
277 except WorkspaceQuotaExceededError:
278 logger.warning(
279 "Skipping cron dispatch for workflow %s because workspace "
280 "quota was exceeded",
281 plan.workflow_id,
282 )
283 continue
284 if run is not None: 1dea
285 runs.append(run.model_copy(deep=True)) 1a
286 # Enqueue AFTER lock is released to ensure commits are fully visible
287 for run in runs: 1dtmkehal
288 await _enqueue_run_and_confirm(self, run) 1a
289 return runs 1dtmkehal
291 async def _create_cron_run_once(
292 self,
293 plan: CronDispatchPlan,
294 *,
295 version_id: UUID,
296 workspace_id: str | None,
297 ) -> WorkflowRun | None:
298 """Create a run and advance its schedule in one row-locked transaction."""
299 async with self._connection() as conn: 1wFLdea
300 cursor = await conn.execute( 1wFLdea
301 """
302 SELECT config, last_dispatched_at FROM cron_triggers
303 WHERE workflow_id = %s FOR UPDATE SKIP LOCKED
304 """,
305 (str(plan.workflow_id),),
306 )
307 row = await cursor.fetchone() 1wFLdea
308 if row is None: 1wFLdea
309 return None 1de
310 config = CronTriggerConfig.model_validate(row["config"]) 1wFLa
311 if config != self._trigger_layer.get_cron_config(plan.workflow_id): 1wFLa
312 return None 1L
313 last_dispatched = row["last_dispatched_at"] 1wFa
314 if last_dispatched is not None and last_dispatched >= plan.scheduled_for: 1wFa
315 return None 1F
316 if not config.allow_overlapping: 316 ↛ 327line 316 didn't jump to line 327 because the condition on line 316 was always true1wa
317 cursor = await conn.execute( 1wa
318 """
319 SELECT 1 FROM workflow_runs
320 WHERE workflow_id = %s AND triggered_by = 'cron'
321 AND status IN ('pending', 'running') LIMIT 1
322 """,
323 (str(plan.workflow_id),),
324 )
325 if await cursor.fetchone() is not None: 1wa
326 return None 1w
327 run = await self._create_run_locked( 1a
328 workflow_id=plan.workflow_id,
329 workflow_version_id=version_id,
330 triggered_by="cron",
331 input_payload={
332 "scheduled_for": plan.scheduled_for.isoformat(),
333 "timezone": plan.timezone,
334 },
335 actor="cron",
336 workspace_id=workspace_id,
337 dispatch_requested=True,
338 connection=conn,
339 )
340 await conn.execute( 1a
341 "UPDATE cron_triggers SET last_dispatched_at = %s "
342 "WHERE workflow_id = %s",
343 (plan.scheduled_for, str(plan.workflow_id)),
344 )
345 self._trigger_layer.track_run(plan.workflow_id, run.id) 1a
346 self._trigger_layer.register_cron_run(run.id) 1a
347 self._trigger_layer.commit_cron_dispatch(plan.workflow_id) 1a
348 return run 1a
350 async def dispatch_manual_runs(
351 self, request: ManualDispatchRequest
352 ) -> list[WorkflowRun]:
353 await self._ensure_initialized() 1fKiSqcgu
354 async with self._lock: 1fKiSqcgu
355 workflow = await self._get_workflow_locked(request.workflow_id) 1fKiSqcgu
356 if workflow.is_archived: 1fKiSqcgu
357 raise WorkflowNotFoundError(str(request.workflow_id)) 1S
358 try: 1fKiqcgu
359 latest_version = await self._get_latest_version_locked( 1fKiqcgu
360 request.workflow_id
361 )
362 except WorkflowVersionNotFoundError as exc: 1K
363 raise WorkflowVersionNotFoundError(str(request.workflow_id)) from exc 1K
364 default_version_id = latest_version.id 1fiqcgu
365 plan = self._trigger_layer.prepare_manual_dispatch( 1fiqcgu
366 request, default_workflow_version_id=default_version_id
367 )
368 workspace_repo = cast(_WorkflowWorkspaceLookup, self) 1fiqcgu
369 workspace_id = await workspace_repo._get_workflow_workspace_id_locked( 1fiqcgu
370 request.workflow_id
371 )
373 await self._ensure_workflow_health( 1fiqcgu
374 request.workflow_id,
375 actor=plan.actor or plan.triggered_by,
376 workspace_id=workspace_id,
377 )
379 runs: list[WorkflowRun] = [] 1fiqcgu
380 for resolved in plan.runs: 1fiqcgu
381 version = await self._get_version_locked(resolved.workflow_version_id) 1fiqcgu
382 if version.workflow_id != request.workflow_id: 1fiqcg
383 raise WorkflowVersionNotFoundError( 1q
384 str(resolved.workflow_version_id)
385 )
387 quota_error: WorkspaceQuotaExceededError | None = None 1ficg
388 for resolved in plan.runs: 1ficg
389 try: 1ficg
390 run = await self._create_run_locked( 1ficg
391 workflow_id=request.workflow_id,
392 workflow_version_id=resolved.workflow_version_id,
393 triggered_by=plan.triggered_by,
394 input_payload=resolved.input_payload,
395 runnable_config=resolved.runnable_config,
396 actor=plan.actor,
397 workspace_id=workspace_id,
398 dispatch_requested=True,
399 )
400 except WorkspaceQuotaExceededError as exc: 1ic
401 logger.warning( 1ic
402 "Skipping manual dispatch for workflow %s because workspace "
403 "quota was exceeded",
404 request.workflow_id,
405 )
406 quota_error = exc 1ic
407 continue 1ic
408 runs.append(run.model_copy(deep=True)) 1fcg
409 # Refusing every run is a quota response, not an empty success;
410 # a batch that partly fit still returns the runs it created.
411 if not runs and quota_error is not None: 1ficg
412 raise quota_error 1i
413 # Enqueue AFTER lock is released to ensure commits are fully visible
414 for run in runs: 1fcg
415 await _enqueue_run_and_confirm(self, run) 1fcg
416 return runs 1fcg
419__all__ = ["TriggerRepositoryMixin"]