Skip to main content

qail_workflow/
context.rs

1//! Workflow execution context — carries data between steps.
2//!
3//! The context is a typed key-value bag that steps read from and write to.
4//! Query results are stored here, and Notify steps resolve recipient
5//! addresses from context keys.
6
7use std::collections::HashMap;
8
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13use crate::step::WorkflowStep;
14
15/// Workflow execution context.
16///
17/// Persisted between steps so workflows survive process restarts.
18/// Each step can read from and write to the context.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct WorkflowContext {
21    /// Unique identifier for this workflow instance
22    pub workflow_id: String,
23    /// Current state name
24    pub current_state: String,
25    /// Workflow definition name used by this context, when known.
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub definition_name: Option<String>,
28    /// Workflow definition version used by this context, when known.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub definition_version: Option<String>,
31    /// Key-value data bag (query results, user inputs, etc.)
32    pub data: HashMap<String, Value>,
33    /// When this workflow instance was created
34    pub created_at: DateTime<Utc>,
35    /// When this context was last updated
36    pub updated_at: DateTime<Utc>,
37    /// Audit trail of state transitions
38    pub history: Vec<StateChange>,
39    /// Cursor used to resume inside nested workflow blocks after a Wait.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub cursor: Option<WorkflowCursor>,
42}
43
44/// Persisted execution cursor for resuming after a Wait.
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46pub struct WorkflowCursor {
47    /// State whose transition owns the cursor frames.
48    pub state: String,
49    /// Nested frame path to the next executable step.
50    pub frames: Vec<WorkflowCursorFrame>,
51    /// External event currently required before this cursor may resume.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub wait: Option<WorkflowPendingWait>,
54}
55
56/// Persisted metadata for a paused Wait step.
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
58pub struct WorkflowPendingWait {
59    /// Event name required to resume this workflow.
60    pub event: String,
61    /// Wall-clock deadline after which timeout fallback is eligible.
62    pub deadline_at: DateTime<Utc>,
63    /// Steps to execute if the wait times out.
64    #[serde(default, skip_serializing_if = "Vec::is_empty")]
65    pub on_timeout: Vec<WorkflowStep>,
66}
67
68/// One level in a persisted workflow execution cursor.
69#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
70pub enum WorkflowCursorFrame {
71    /// Top-level transition step list.
72    Steps {
73        /// Next top-level step index.
74        index: usize,
75    },
76    /// Selected branch step list.
77    Branch {
78        /// Branch arm that was active when execution paused.
79        selection: WorkflowBranchCursorSelection,
80        /// Next step index inside the selected branch.
81        index: usize,
82    },
83    /// Legacy active ForEach item step list.
84    ///
85    /// This variant remains deserializable for old persisted rows, but the
86    /// engine refuses to resume it because it lacks an item snapshot.
87    ForEach {
88        /// Current array item index.
89        item_index: usize,
90        /// Next step index inside the item block.
91        index: usize,
92    },
93    /// Active ForEach item step list with an item snapshot for drift checks.
94    ///
95    /// New workflow cursors use this variant so a paused workflow cannot resume
96    /// on a different list item if the source array is reordered while waiting.
97    ForEachItem {
98        /// Current array item index.
99        item_index: usize,
100        /// Next step index inside the item block.
101        index: usize,
102        /// JSON item value observed when the cursor was created.
103        item: Value,
104    },
105}
106
107/// Persisted branch arm selection for workflow resume.
108#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
109pub enum WorkflowBranchCursorSelection {
110    /// A concrete branch index from `WorkflowStep::Branch::branches`.
111    Branch(usize),
112    /// The default branch arm.
113    Default,
114}
115
116/// Record of a state transition for audit trail.
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct StateChange {
119    /// Previous state name.
120    pub from: String,
121    /// New state name.
122    pub to: String,
123    /// When the transition occurred.
124    pub at: DateTime<Utc>,
125    /// Optional human-readable reason for the transition.
126    pub reason: Option<String>,
127}
128
129impl WorkflowContext {
130    /// Create a new context for a workflow instance.
131    pub fn new(workflow_id: impl Into<String>, initial_state: impl Into<String>) -> Self {
132        let now = Utc::now();
133        Self {
134            workflow_id: workflow_id.into(),
135            current_state: initial_state.into(),
136            definition_name: None,
137            definition_version: None,
138            data: HashMap::new(),
139            created_at: now,
140            updated_at: now,
141            history: Vec::new(),
142            cursor: None,
143        }
144    }
145
146    /// Store a value in the context.
147    pub fn set(&mut self, key: impl Into<String>, value: Value) {
148        self.data.insert(key.into(), value);
149        self.updated_at = Utc::now();
150    }
151
152    /// Get a value from the context.
153    pub fn get(&self, key: &str) -> Option<&Value> {
154        // Support dot-notation: "item.phone" → data["item"]["phone"]
155        if key.contains('.') {
156            let parts: Vec<&str> = key.splitn(2, '.').collect();
157            if let Some(parent) = self.data.get(parts[0]) {
158                return get_nested(parent, parts[1]);
159            }
160            return None;
161        }
162        self.data.get(key)
163    }
164
165    /// Get a string value from the context.
166    pub fn get_str(&self, key: &str) -> Option<&str> {
167        self.get(key).and_then(|v| v.as_str())
168    }
169
170    /// Transition to a new state, recording the change.
171    pub fn transition_to(&mut self, new_state: impl Into<String>, reason: Option<String>) {
172        let new = new_state.into();
173        self.history.push(StateChange {
174            from: self.current_state.clone(),
175            to: new.clone(),
176            at: Utc::now(),
177            reason,
178        });
179        self.current_state = new;
180        self.cursor = None;
181        self.updated_at = Utc::now();
182    }
183
184    /// Store a resume cursor for the next run.
185    pub fn set_cursor(&mut self, cursor: WorkflowCursor) {
186        self.cursor = Some(cursor);
187        self.updated_at = Utc::now();
188    }
189
190    /// Remove and return the current resume cursor.
191    pub fn take_cursor(&mut self) -> Option<WorkflowCursor> {
192        let cursor = self.cursor.take();
193        if cursor.is_some() {
194            self.updated_at = Utc::now();
195        }
196        cursor
197    }
198
199    /// Clear any saved resume cursor.
200    pub fn clear_cursor(&mut self) {
201        if self.cursor.take().is_some() {
202            self.updated_at = Utc::now();
203        }
204    }
205
206    /// Get the number of state transitions that have occurred.
207    pub fn transition_count(&self) -> usize {
208        self.history.len()
209    }
210}
211
212/// Resolve a dot-notation path within a JSON value.
213fn get_nested<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
214    if path.contains('.') {
215        let parts: Vec<&str> = path.splitn(2, '.').collect();
216        match value {
217            Value::Object(map) => map.get(parts[0]).and_then(|v| get_nested(v, parts[1])),
218            _ => None,
219        }
220    } else {
221        match value {
222            Value::Object(map) => map.get(path),
223            _ => None,
224        }
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn test_new_context() {
234        let ctx = WorkflowContext::new("wf-001", "created");
235        assert_eq!(ctx.workflow_id, "wf-001");
236        assert_eq!(ctx.current_state, "created");
237        assert!(ctx.definition_name.is_none());
238        assert!(ctx.definition_version.is_none());
239        assert!(ctx.data.is_empty());
240        assert!(ctx.history.is_empty());
241        assert!(ctx.cursor.is_none());
242    }
243
244    #[test]
245    fn test_set_and_get() {
246        let mut ctx = WorkflowContext::new("wf-001", "created");
247        ctx.set("name", Value::String("test".into()));
248        assert_eq!(ctx.get_str("name"), Some("test"));
249        assert!(ctx.get("missing").is_none());
250    }
251
252    #[test]
253    fn test_dot_notation() {
254        let mut ctx = WorkflowContext::new("wf-001", "created");
255        ctx.set(
256            "guest",
257            serde_json::json!({
258                "name": "John",
259                "phone": "+628123456",
260                "address": { "city": "Bali" }
261            }),
262        );
263        assert_eq!(ctx.get_str("guest.name"), Some("John"));
264        assert_eq!(ctx.get_str("guest.phone"), Some("+628123456"));
265        assert_eq!(ctx.get_str("guest.address.city"), Some("Bali"));
266        assert!(ctx.get("guest.missing").is_none());
267    }
268
269    #[test]
270    fn test_state_transition() {
271        let mut ctx = WorkflowContext::new("wf-001", "created");
272        ctx.transition_to("paid_escrow", Some("Payment received".into()));
273        assert_eq!(ctx.current_state, "paid_escrow");
274        assert_eq!(ctx.transition_count(), 1);
275        assert_eq!(ctx.history[0].from, "created");
276        assert_eq!(ctx.history[0].to, "paid_escrow");
277    }
278
279    #[test]
280    fn test_context_serialization() {
281        let mut ctx = WorkflowContext::new("wf-001", "created");
282        ctx.set("booking_id", Value::String("b-123".into()));
283        ctx.transition_to("pending", None);
284
285        let json = serde_json::to_string(&ctx).unwrap();
286        let restored: WorkflowContext = serde_json::from_str(&json).unwrap();
287        assert_eq!(restored.workflow_id, "wf-001");
288        assert_eq!(restored.current_state, "pending");
289        assert_eq!(restored.get_str("booking_id"), Some("b-123"));
290        assert!(restored.cursor.is_none());
291    }
292
293    #[test]
294    fn test_context_resume_cursor_round_trip() {
295        let mut ctx = WorkflowContext::new("wf-001", "created");
296        ctx.set_cursor(WorkflowCursor {
297            state: "created".to_string(),
298            frames: vec![
299                WorkflowCursorFrame::Steps { index: 0 },
300                WorkflowCursorFrame::ForEachItem {
301                    item_index: 1,
302                    index: 2,
303                    item: serde_json::json!({"name": "Captain B"}),
304                },
305            ],
306            wait: Some(WorkflowPendingWait {
307                event: "operator_accept".to_string(),
308                deadline_at: Utc::now(),
309                on_timeout: vec![],
310            }),
311        });
312
313        let json = serde_json::to_string(&ctx).unwrap();
314        let restored: WorkflowContext = serde_json::from_str(&json).unwrap();
315        assert_eq!(restored.cursor, ctx.cursor);
316    }
317
318    #[test]
319    fn test_context_deserializes_cursor_without_wait_metadata() {
320        let json = r#"{
321            "workflow_id":"wf-001",
322            "current_state":"created",
323            "data":{},
324            "created_at":"2026-01-01T00:00:00Z",
325            "updated_at":"2026-01-01T00:00:00Z",
326            "history":[],
327            "cursor":{
328                "state":"created",
329                "frames":[{"Steps":{"index":1}}]
330            }
331        }"#;
332
333        let restored: WorkflowContext = serde_json::from_str(json).unwrap();
334        let cursor = restored.cursor.expect("cursor should deserialize");
335        assert!(cursor.wait.is_none());
336    }
337
338    #[test]
339    fn test_context_deserializes_without_cursor() {
340        let json = r#"{
341            "workflow_id":"wf-001",
342            "current_state":"created",
343            "data":{},
344            "created_at":"2026-01-01T00:00:00Z",
345            "updated_at":"2026-01-01T00:00:00Z",
346            "history":[]
347        }"#;
348
349        let restored: WorkflowContext = serde_json::from_str(json).unwrap();
350        assert!(restored.cursor.is_none());
351    }
352}