"""API side of the Temporal layer: TemporalRunManager (same interface as the LangGraph RunManager, so routes, SSE and the web/desktop apps do not change) and TemporalScheduler (patch watch + schedules + purge as Temporal Schedules). The Temporal client is async; it lives on a private event-loop thread and sync FastAPI routes call into it.""" from __future__ import annotations import asyncio import logging import threading from datetime import timedelta from temporalio.client import (Client, Schedule, ScheduleActionStartWorkflow, ScheduleIntervalSpec, ScheduleSpec, ScheduleState, WorkflowExecutionStatus) from temporalio.common import WorkflowIDReusePolicy from temporalio.service import RPCError from ..api.runner import GATE_STATUS, TERMINAL, RunError, create_run_record from ..graph.statestore import StateStore from ..platform import procs from ..platform.scheduler import Scheduler log = logging.getLogger("fpt.temporal") class _Loop: def __init__(self): self.loop = asyncio.new_event_loop() self.thread = threading.Thread(target=self.loop.run_forever, name="fpt-temporal-client", daemon=True) self.thread.start() def run(self, coro, timeout: float = 30): return asyncio.run_coroutine_threadsafe(coro, self.loop).result(timeout) def stop(self) -> None: self.loop.call_soon_threadsafe(self.loop.stop) async def connect(cfg, timeout_s: float = 3.0) -> Client: return await asyncio.wait_for(Client.connect(cfg.temporal_address, namespace=cfg.temporal_namespace), timeout_s) def workflow_input(cfg, run_id: str) -> dict: return {"run_id": run_id, "browser_queue": cfg.temporal_browser_queue, "remind_after_s": cfg.approval_remind_after_s, "escalate_after_s": cfg.approval_escalate_after_s} class TemporalRunManager: orchestrator = "temporal" fallback_reason = None def __init__(self, svc, client: Client | None = None, loop: _Loop | None = None): self.svc, self.cfg = svc, svc.cfg self._loop = loop or _Loop() self.client = client or self._loop.run(connect(self.cfg)) self.store = StateStore(svc.db) self.listeners: list = [] self._thread = None # API /ready compatibility # lifecycle (Temporal is durable: nothing to recover in-process) def recover(self) -> list[str]: return [] def start_worker(self) -> None: pass def stop(self) -> None: pass def drain(self, timeout: float = 600) -> None: pass def ping(self) -> bool: try: self._loop.run(self.client.service_client.check_health(), timeout=3) return True except Exception: # noqa: BLE001 return False def handle(self, run_id: str): return self.client.get_workflow_handle(run_id) # ---------------------------------------------------------------- API def start(self, inputs: dict, actor: str, trigger: str = "manual", run_id: str | None = None) -> str: rid, _ = create_run_record(self.svc, inputs, actor, trigger, orchestrator="temporal", run_id=run_id) self._loop.run(self.client.start_workflow("PatchCycleWorkflow", workflow_input(self.cfg, rid), id=rid, task_queue=self.cfg.temporal_task_queue)) return rid def answer_gate(self, run_id: str, gate: str, answer: dict, actor: str) -> None: run = self._get(run_id) if run["pending_gate"] != gate or run["status"] != GATE_STATUS.get(gate): raise RunError(f"run {run_id} is not waiting at gate {gate} (status {run['status']}, gate {run['pending_gate']})", "NOT_AT_GATE") self.svc.kill.check("gate.answer") # check-and-write in one statement: a double click sends one signal, not one for this gate and one for the next if not self.svc.db.claim_run(run_id, GATE_STATUS[gate], gate, status="running", pending_gate=None, attention=None): raise RunError(f"run {run_id} is no longer waiting at gate {gate}: this answer was already given", "NOT_AT_GATE") signal = "approve_cases" if gate == "approve_cases" else "submit_review" try: self._loop.run(self.handle(run_id).signal(signal, {**answer, "actor": actor})) except BaseException: self.svc.db.update_run(run_id, status=run["status"], pending_gate=gate, attention=run.get("attention")) raise self.svc.db.add_event(run_id, gate, "status", {"status": "running", "answered_by": actor, "via": "temporal signal"}) def resume(self, run_id: str, actor: str) -> None: run = self._get(run_id) if run["status"] not in ("interrupted", "failed"): raise RunError(f"run {run_id} is {run['status']}; only interrupted/failed runs can be resumed", "NOT_RESUMABLE") self.svc.kill.check("run.resume") self.svc.audit.append("run.resumed", actor=actor, run_id=run_id, summary="new workflow execution; finished phases are reused") self.svc.db.update_run(run_id, status="queued", error=None) self._loop.run(self.client.start_workflow("PatchCycleWorkflow", workflow_input(self.cfg, run_id), id=run_id, task_queue=self.cfg.temporal_task_queue, id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE)) def cancel(self, run_id: str, actor: str, reason: str = "") -> None: run = self._get(run_id) if run["status"] in TERMINAL: raise RunError(f"run {run_id} is already {run['status']}", "ALREADY_FINISHED") h = self.handle(run_id) try: self._loop.run(h.signal("cancel", reason or f"cancelled by {actor}")) self._loop.run(h.cancel()) except RPCError as e: log.info("cancel %s: %s", run_id, e) procs.kill_all(f"playwright:{run_id}") self.svc.db.update_run(run_id, status="cancelled", pending_gate=None, error=reason or None) self.svc.db.add_event(run_id, None, "status", {"status": "cancelled", "by": actor, "reason": reason}) self.svc.audit.append("run.cancelled", actor=actor, run_id=run_id, summary=reason) def kill_active(self) -> None: """Kill switch: cancel every non-terminal Temporal run (activities see the cancellation at their next heartbeat).""" for st in ("queued", "running", "waiting_approval", "waiting_review"): for r in self.svc.db.list_runs(st, 1000): if r.get("orchestrator") != "temporal": continue try: self._loop.run(self.handle(r["run_id"]).cancel()) except Exception as e: # noqa: BLE001 log.info("kill cancel %s: %s", r["run_id"], e) procs.kill_all("playwright:") def gate_payload(self, run_id: str) -> dict | None: r = self.svc.db.get_run(run_id) if not r or not r.get("pending_gate"): return None return self.svc.db.kv_get(f"gate:{run_id}") def state(self, run_id: str) -> dict: return self.store.load(run_id) def describe(self, run_id: str) -> dict: try: d = self._loop.run(self.handle(run_id).describe(), timeout=5) q = None if d.status == WorkflowExecutionStatus.RUNNING: q = self._loop.run(self.handle(run_id).query("status"), timeout=5) return {"workflow_id": run_id, "run_id": d.run_id, "status": d.status.name if d.status else None, "query": q, "ui": f"{self.cfg.temporal_ui_url}/namespaces/{self.cfg.temporal_namespace}/workflows/{run_id}"} except Exception as e: # noqa: BLE001 return {"workflow_id": run_id, "error": str(e)[:300]} def _get(self, run_id: str) -> dict: r = self.svc.db.get_run(run_id) if not r: raise RunError(f"run {run_id} not found", "NOT_FOUND", 404) return r class TemporalScheduler(Scheduler): """Patch watch, user schedules and the daily purge as Temporal Schedules (durable, visible in the Temporal UI). DB rows stay the source of truth for the UI; every change re-syncs the Temporal schedules. Schedule ids are namespaced by this deployment's task queue (-patch-watch, -sched-, -purge), so several deployments (e.g. a demo instance and test runs) share one Temporal namespace without touching each other's schedules.""" def __init__(self, svc, runs: TemporalRunManager): super().__init__(svc, runs, svc.cfg.scheduler_tick_s) self.loop, self.client = runs._loop, runs.client q = svc.cfg.temporal_task_queue self.PATCH_ID, self.PURGE_ID, self.SCHED_PREFIX = f"{q}-patch-watch", f"{q}-purge", f"{q}-sched-" def start(self) -> None: try: self.sync() except Exception: # noqa: BLE001 log.exception("temporal schedule sync failed") def stop(self) -> None: pass async def _upsert(self, sid: str, wf: str, arg: dict, spec: ScheduleSpec, paused: bool = False) -> None: try: await self.client.get_schedule_handle(sid).delete() except RPCError: pass await self.client.create_schedule(sid, Schedule( action=ScheduleActionStartWorkflow(wf, arg, id=f"{sid}-run", task_queue=self.svc.cfg.temporal_task_queue), spec=spec, state=ScheduleState(paused=paused, note="managed by the FPT co-worker"))) async def _sync(self) -> None: cfg = self.svc.cfg pw = self.patch_watch() base = workflow_input(cfg, "") await self._upsert(self.PATCH_ID, "PatchWatchWorkflow", base, ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(seconds=max(30, pw["interval_s"])))]), paused=not pw["enabled"]) await self._upsert(self.PURGE_ID, "PurgeWorkflow", {}, ScheduleSpec(cron_expressions=["15 3 * * *"])) wanted = {f"{self.SCHED_PREFIX}{s['id']}": s for s in self.list() if s["enabled"]} async for item in await self.client.list_schedules(): if item.id.startswith(self.SCHED_PREFIX) and item.id not in wanted: await self.client.get_schedule_handle(item.id).delete() for sid, s in wanted.items(): if s["kind"] == "interval": spec = ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(minutes=int(s["every_minutes"] or 60)))]) else: from ..platform.scheduler import cron_of spec = ScheduleSpec(cron_expressions=[cron_of(s)], time_zone_name=s.get("timezone") or "UTC") await self._upsert(sid, "ScheduledRunWorkflow", {**base, "schedule_id": s["id"]}, spec) def sync(self) -> None: self.loop.run(self._sync(), timeout=60) def set_patch_watch(self, **fields) -> dict: out = super().set_patch_watch(**fields) self.start() return out def create(self, rec: dict, actor: str) -> dict: out = super().create(rec, actor) self.start() return out def update(self, sid: int, changes: dict) -> dict: out = super().update(sid, changes) self.start() return out def delete(self, sid: int) -> None: super().delete(sid) self.start() def tick(self, now): # in Temporal mode the Schedules do the work; kept for API compatibility return {"started": [], "patch": None, "purged": None, "note": "Temporal Schedules are active"}