1use std::collections::HashMap;
8
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13use crate::step::WorkflowStep;
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct WorkflowContext {
21 pub workflow_id: String,
23 pub current_state: String,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub definition_name: Option<String>,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub definition_version: Option<String>,
31 pub data: HashMap<String, Value>,
33 pub created_at: DateTime<Utc>,
35 pub updated_at: DateTime<Utc>,
37 pub history: Vec<StateChange>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub cursor: Option<WorkflowCursor>,
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46pub struct WorkflowCursor {
47 pub state: String,
49 pub frames: Vec<WorkflowCursorFrame>,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub wait: Option<WorkflowPendingWait>,
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
58pub struct WorkflowPendingWait {
59 pub event: String,
61 pub deadline_at: DateTime<Utc>,
63 #[serde(default, skip_serializing_if = "Vec::is_empty")]
65 pub on_timeout: Vec<WorkflowStep>,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
70pub enum WorkflowCursorFrame {
71 Steps {
73 index: usize,
75 },
76 Branch {
78 selection: WorkflowBranchCursorSelection,
80 index: usize,
82 },
83 ForEach {
88 item_index: usize,
90 index: usize,
92 },
93 ForEachItem {
98 item_index: usize,
100 index: usize,
102 item: Value,
104 },
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
109pub enum WorkflowBranchCursorSelection {
110 Branch(usize),
112 Default,
114}
115
116#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct StateChange {
119 pub from: String,
121 pub to: String,
123 pub at: DateTime<Utc>,
125 pub reason: Option<String>,
127}
128
129impl WorkflowContext {
130 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 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 pub fn get(&self, key: &str) -> Option<&Value> {
154 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 pub fn get_str(&self, key: &str) -> Option<&str> {
167 self.get(key).and_then(|v| v.as_str())
168 }
169
170 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 pub fn set_cursor(&mut self, cursor: WorkflowCursor) {
186 self.cursor = Some(cursor);
187 self.updated_at = Utc::now();
188 }
189
190 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 pub fn clear_cursor(&mut self) {
201 if self.cursor.take().is_some() {
202 self.updated_at = Utc::now();
203 }
204 }
205
206 pub fn transition_count(&self) -> usize {
208 self.history.len()
209 }
210}
211
212fn 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}