Skip to main content

assay_workflow/
ctx.rs

1use std::sync::Arc;
2
3use tokio::task::JoinHandle;
4use tracing::info;
5
6use crate::dispatch_recovery;
7use crate::events::{WorkflowBusEvent, WorkflowEventBus};
8use crate::health;
9use crate::scheduler;
10use crate::store::WorkflowStore;
11use crate::timers;
12
13/// Holds the background-task JoinHandles. When the last Arc<BackgroundTasks>
14/// is dropped the tasks are abandoned (tokio will cancel them on shutdown).
15pub struct BackgroundTasks {
16    _scheduler: JoinHandle<()>,
17    _timer_poller: JoinHandle<()>,
18    _health_monitor: JoinHandle<()>,
19    _dispatch_recovery: JoinHandle<()>,
20    #[cfg(feature = "s3-archival")]
21    _archival: Option<JoinHandle<()>>,
22}
23
24/// The workflow context. Owns the store, background-task handles, and
25/// per-request config. Serves as both the orchestrator (all engine methods
26/// live as `impl WorkflowCtx<S>`) and the axum state (`Arc<WorkflowCtx<S>>`).
27///
28/// `S` is the concrete store backend (`SqliteStore` or `PostgresStore`).
29/// `WorkflowStore` uses RPIT futures and is not dyn-compatible, so the
30/// generic parameter is retained here to avoid boxing every async call.
31pub struct WorkflowCtx<S: WorkflowStore> {
32    pub(crate) store: Arc<S>,
33    /// Engine-wide CDC outbox. When wired, state-mutating methods
34    /// publish typed `WorkflowBusEvent` variants via `emit(...)`.
35    /// `None` for tests / embedders without a dashboard — emit becomes
36    /// a no-op.
37    pub(crate) bus: Option<WorkflowEventBus>,
38    pub(crate) _bg: Arc<BackgroundTasks>,
39    /// Version of the containing binary (e.g. the `assay-lua` CLI) — set
40    /// by embedders so `/api/v1/engine/workflow/version` reflects the user-facing
41    /// binary, not this internal engine-crate version.
42    pub binary_version: Option<&'static str>,
43}
44
45impl<S: WorkflowStore> WorkflowCtx<S> {
46    /// Start the context with all background tasks.
47    pub fn start(store: Arc<S>) -> Self {
48        let _scheduler = tokio::spawn(scheduler::run_scheduler(Arc::clone(&store)));
49        let _timer_poller = tokio::spawn(timers::run_timer_poller(Arc::clone(&store)));
50        let _health_monitor = tokio::spawn(health::run_health_monitor(Arc::clone(&store)));
51        let _dispatch_recovery = tokio::spawn(dispatch_recovery::run_dispatch_recovery(
52            Arc::clone(&store),
53        ));
54
55        #[cfg(feature = "s3-archival")]
56        let _archival = crate::archival::ArchivalConfig::from_env()
57            .map(|cfg| tokio::spawn(crate::archival::run_archival(Arc::clone(&store), cfg)));
58
59        info!("Workflow engine started");
60
61        Self {
62            store,
63            bus: None,
64            _bg: Arc::new(BackgroundTasks {
65                _scheduler,
66                _timer_poller,
67                _health_monitor,
68                _dispatch_recovery,
69                #[cfg(feature = "s3-archival")]
70                _archival,
71            }),
72            binary_version: None,
73        }
74    }
75
76    /// Attach the engine-wide event bus. The API layer sets this up so
77    /// the SSE stream (`/events/stream`) and the dispatch-wakeup loop
78    /// see state transitions as they happen. Returns the context by
79    /// value so callers can chain.
80    pub fn with_event_bus(mut self, bus: WorkflowEventBus) -> Self {
81        self.bus = Some(bus);
82        self
83    }
84
85    /// Set the binary version string surfaced by `/api/v1/engine/workflow/version`.
86    pub fn with_binary_version(mut self, version: &'static str) -> Self {
87        self.binary_version = Some(version);
88        self
89    }
90
91    /// Access the underlying store (for the API layer).
92    pub fn store(&self) -> &S {
93        &self.store
94    }
95
96    /// Access the event bus (for SSE + scheduler wake-up).
97    pub fn bus(&self) -> Option<&WorkflowEventBus> {
98        self.bus.as_ref()
99    }
100
101    /// Emit a typed workflow event. No-op when no bus is wired (tests,
102    /// embedders without a dashboard). Errors are logged, not returned —
103    /// an emission failure must not fail the state-mutating method that
104    /// triggered it (atomicity for the state change is the DB tx's job;
105    /// this is a notification fired *after* the row write).
106    pub(crate) async fn emit(&self, namespace: &str, ev: WorkflowBusEvent) {
107        if let Some(bus) = &self.bus
108            && let Err(e) = bus.publish(namespace, ev).await
109        {
110            tracing::warn!(?e, "engine event emit failed");
111        }
112    }
113
114    /// Mark a workflow dispatchable AND emit a `WorkflowNeedsDispatch`
115    /// on the bus so the dispatch-wakeup loop (phase 6) wakes workers
116    /// on this node / across the cluster. The extra SELECT is skipped
117    /// when no bus is wired.
118    pub(crate) async fn mark_and_emit_needs_dispatch(
119        &self,
120        workflow_id: &str,
121    ) -> anyhow::Result<()> {
122        self.store.mark_workflow_dispatchable(workflow_id).await?;
123        if self.bus.is_some()
124            && let Some(wf) = self.store.get_workflow(workflow_id).await?
125        {
126            self.emit(
127                &wf.namespace,
128                WorkflowBusEvent::WorkflowNeedsDispatch {
129                    workflow_id: workflow_id.to_string(),
130                    task_queue: wf.task_queue,
131                },
132            )
133            .await;
134        }
135        Ok(())
136    }
137}
138
139/// Strip a trailing `-continued-<digits>` from a workflow id so
140/// sequential continue-as-new calls don't pile up suffixes. Matches
141/// the pattern emitted by the default id-derivation path; returns the
142/// input unchanged if there's no such suffix.
143pub(crate) fn strip_continued_suffix(id: &str) -> &str {
144    if let Some(idx) = id.rfind("-continued-") {
145        let (head, tail) = id.split_at(idx);
146        let rest = &tail["-continued-".len()..];
147        if !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()) {
148            return head;
149        }
150    }
151    id
152}
153
154pub(crate) fn timestamp_now() -> f64 {
155    std::time::SystemTime::now()
156        .duration_since(std::time::UNIX_EPOCH)
157        .unwrap()
158        .as_secs_f64()
159}
160
161/// WorkflowCtx version (the binary version pulled from Cargo at build time).
162/// Stamped into every workflow's search_attributes at start so operators
163/// can correlate runs to the engine release that executed them.
164pub(crate) const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");
165
166/// Auto-stamp `assay_engine_version` into a workflow's search attributes.
167/// Returns `Some` JSON string for the caller to store in the record.
168///
169/// If the caller already supplied `assay_engine_version` in their patch,
170/// we leave their value alone (explicit override wins). Otherwise we
171/// backfill the running engine's version. Callers who supply no
172/// attributes at all get a single-key object with just the version.
173pub(crate) fn inject_engine_version(caller_attrs: Option<&str>) -> Option<String> {
174    let mut obj: serde_json::Map<String, serde_json::Value> = match caller_attrs {
175        Some(raw) => match serde_json::from_str::<serde_json::Value>(raw) {
176            Ok(serde_json::Value::Object(m)) => m,
177            Ok(other) => return Some(other.to_string()),
178            Err(_) => return Some(raw.to_string()),
179        },
180        None => serde_json::Map::new(),
181    };
182    obj.entry("assay_engine_version".to_string())
183        .or_insert_with(|| serde_json::Value::String(ENGINE_VERSION.to_string()));
184    Some(serde_json::Value::Object(obj).to_string())
185}
186
187#[cfg(test)]
188mod engine_version_stamp_tests {
189    use super::*;
190
191    #[test]
192    fn no_attrs_produces_single_key_object() {
193        let out = inject_engine_version(None).unwrap();
194        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
195        assert_eq!(v["assay_engine_version"], ENGINE_VERSION);
196        assert_eq!(v.as_object().unwrap().len(), 1);
197    }
198
199    #[test]
200    fn existing_attrs_gain_the_version_field() {
201        let out = inject_engine_version(Some(r#"{"env":"prod","tenant":"acme"}"#)).unwrap();
202        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
203        assert_eq!(v["env"], "prod");
204        assert_eq!(v["tenant"], "acme");
205        assert_eq!(v["assay_engine_version"], ENGINE_VERSION);
206    }
207
208    #[test]
209    fn caller_supplied_version_wins_on_conflict() {
210        let out =
211            inject_engine_version(Some(r#"{"assay_engine_version":"0.0.1-test"}"#)).unwrap();
212        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
213        assert_eq!(v["assay_engine_version"], "0.0.1-test");
214    }
215
216    #[test]
217    fn non_object_json_is_preserved_unchanged() {
218        let out = inject_engine_version(Some("[1, 2, 3]")).unwrap();
219        assert_eq!(out, "[1,2,3]");
220    }
221
222    #[test]
223    fn unparsable_json_is_preserved_unchanged() {
224        let out = inject_engine_version(Some("not json")).unwrap();
225        assert_eq!(out, "not json");
226    }
227}