oximedia-workflow 0.2.0

Comprehensive workflow orchestration engine for OxiMedia
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Workflow monitoring and metrics.

use crate::task::{TaskId, TaskState};
use crate::workflow::{WorkflowId, WorkflowState};
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;

// ---------------------------------------------------------------------------
// Serde helpers for Arc<AtomicU64>
// ---------------------------------------------------------------------------

fn serialize_atomic<S: Serializer>(val: &Arc<AtomicU64>, ser: S) -> Result<S::Ok, S::Error> {
    ser.serialize_u64(val.load(Ordering::Relaxed))
}

fn deserialize_atomic<'de, D: Deserializer<'de>>(de: D) -> Result<Arc<AtomicU64>, D::Error> {
    let n = u64::deserialize(de)?;
    Ok(Arc::new(AtomicU64::new(n)))
}

fn default_atomic() -> Arc<AtomicU64> {
    Arc::new(AtomicU64::new(0))
}

/// Task execution metrics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskMetrics {
    /// Task identifier.
    pub task_id: TaskId,
    /// Task name.
    pub task_name: String,
    /// Current state.
    pub state: TaskState,
    /// Start time.
    pub start_time: Option<DateTime<Utc>>,
    /// End time.
    pub end_time: Option<DateTime<Utc>>,
    /// Execution duration.
    pub duration: Option<Duration>,
    /// Number of retry attempts.
    pub retry_count: u32,
    /// Error message if failed.
    pub error: Option<String>,
}

impl TaskMetrics {
    /// Create new task metrics.
    #[must_use]
    pub fn new(task_id: TaskId, task_name: String) -> Self {
        Self {
            task_id,
            task_name,
            state: TaskState::Pending,
            start_time: None,
            end_time: None,
            duration: None,
            retry_count: 0,
            error: None,
        }
    }

    /// Mark task as started.
    pub fn mark_started(&mut self) {
        self.state = TaskState::Running;
        self.start_time = Some(Utc::now());
    }

    /// Mark task as completed.
    pub fn mark_completed(&mut self) {
        self.state = TaskState::Completed;
        self.end_time = Some(Utc::now());
        if let Some(start) = self.start_time {
            self.duration = Some(Duration::from_millis(
                u64::try_from((Utc::now() - start).num_milliseconds()).unwrap_or(0),
            ));
        }
    }

    /// Mark task as failed.
    pub fn mark_failed(&mut self, error: String) {
        self.state = TaskState::Failed;
        self.end_time = Some(Utc::now());
        self.error = Some(error);
        if let Some(start) = self.start_time {
            self.duration = Some(Duration::from_millis(
                u64::try_from((Utc::now() - start).num_milliseconds()).unwrap_or(0),
            ));
        }
    }

    /// Increment retry count.
    pub fn increment_retry(&mut self) {
        self.retry_count += 1;
    }
}

/// Workflow execution metrics.
///
/// The `completed_tasks`, `failed_tasks`, and `running_tasks` counters are
/// backed by `Arc<AtomicU64>` so they can be incremented/decremented from
/// any thread without a mutable borrow. The `Arc` also allows sharing a
/// counter across cheap clones (each clone shares the same atomic).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowMetrics {
    /// Workflow identifier.
    pub workflow_id: WorkflowId,
    /// Workflow name.
    pub workflow_name: String,
    /// Current state.
    pub state: WorkflowState,
    /// Start time.
    pub start_time: Option<DateTime<Utc>>,
    /// End time.
    pub end_time: Option<DateTime<Utc>>,
    /// Total duration.
    pub duration: Option<Duration>,
    /// Task metrics.
    pub tasks: HashMap<TaskId, TaskMetrics>,
    /// Total task count.
    pub total_tasks: usize,
    /// Completed tasks count (atomic for lock-free concurrent updates).
    #[serde(
        serialize_with = "serialize_atomic",
        deserialize_with = "deserialize_atomic",
        default = "default_atomic"
    )]
    pub completed_tasks: Arc<AtomicU64>,
    /// Failed tasks count (atomic for lock-free concurrent updates).
    #[serde(
        serialize_with = "serialize_atomic",
        deserialize_with = "deserialize_atomic",
        default = "default_atomic"
    )]
    pub failed_tasks: Arc<AtomicU64>,
    /// Running tasks count (atomic for lock-free concurrent updates).
    #[serde(
        serialize_with = "serialize_atomic",
        deserialize_with = "deserialize_atomic",
        default = "default_atomic"
    )]
    pub running_tasks: Arc<AtomicU64>,
}

impl WorkflowMetrics {
    /// Create new workflow metrics.
    #[must_use]
    pub fn new(workflow_id: WorkflowId, workflow_name: String, total_tasks: usize) -> Self {
        Self {
            workflow_id,
            workflow_name,
            state: WorkflowState::Created,
            start_time: None,
            end_time: None,
            duration: None,
            tasks: HashMap::new(),
            total_tasks,
            completed_tasks: Arc::new(AtomicU64::new(0)),
            failed_tasks: Arc::new(AtomicU64::new(0)),
            running_tasks: Arc::new(AtomicU64::new(0)),
        }
    }

    /// Read the completed tasks count.
    #[must_use]
    pub fn completed_tasks_count(&self) -> u64 {
        self.completed_tasks.load(Ordering::Relaxed)
    }

    /// Read the failed tasks count.
    #[must_use]
    pub fn failed_tasks_count(&self) -> u64 {
        self.failed_tasks.load(Ordering::Relaxed)
    }

    /// Read the running tasks count.
    #[must_use]
    pub fn running_tasks_count(&self) -> u64 {
        self.running_tasks.load(Ordering::Relaxed)
    }

    /// Mark workflow as started.
    pub fn mark_started(&mut self) {
        self.state = WorkflowState::Running;
        self.start_time = Some(Utc::now());
    }

    /// Mark workflow as completed.
    pub fn mark_completed(&mut self) {
        self.state = WorkflowState::Completed;
        self.end_time = Some(Utc::now());
        if let Some(start) = self.start_time {
            self.duration = Some(Duration::from_millis(
                u64::try_from((Utc::now() - start).num_milliseconds()).unwrap_or(0),
            ));
        }
    }

    /// Mark workflow as failed.
    pub fn mark_failed(&mut self) {
        self.state = WorkflowState::Failed;
        self.end_time = Some(Utc::now());
        if let Some(start) = self.start_time {
            self.duration = Some(Duration::from_millis(
                u64::try_from((Utc::now() - start).num_milliseconds()).unwrap_or(0),
            ));
        }
    }

    /// Update task metrics.
    pub fn update_task(&mut self, task_metrics: TaskMetrics) {
        // Update counters based on state change
        if let Some(old_metrics) = self.tasks.get(&task_metrics.task_id) {
            self.update_counters(old_metrics.state, false);
        }
        self.update_counters(task_metrics.state, true);

        self.tasks.insert(task_metrics.task_id, task_metrics);
    }

    fn update_counters(&self, state: TaskState, increment: bool) {
        match state {
            TaskState::Completed => {
                if increment {
                    self.completed_tasks.fetch_add(1, Ordering::Relaxed);
                } else {
                    // Saturating decrement — avoid underflow.
                    let _ = self.completed_tasks.fetch_update(
                        Ordering::Relaxed,
                        Ordering::Relaxed,
                        |v| if v > 0 { Some(v - 1) } else { Some(0) },
                    );
                }
            }
            TaskState::Failed => {
                if increment {
                    self.failed_tasks.fetch_add(1, Ordering::Relaxed);
                } else {
                    let _ =
                        self.failed_tasks
                            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
                                if v > 0 {
                                    Some(v - 1)
                                } else {
                                    Some(0)
                                }
                            });
                }
            }
            TaskState::Running | TaskState::Retrying => {
                if increment {
                    self.running_tasks.fetch_add(1, Ordering::Relaxed);
                } else {
                    let _ = self.running_tasks.fetch_update(
                        Ordering::Relaxed,
                        Ordering::Relaxed,
                        |v| if v > 0 { Some(v - 1) } else { Some(0) },
                    );
                }
            }
            _ => {}
        }
    }

    /// Get progress percentage.
    #[must_use]
    pub fn progress_percentage(&self) -> f64 {
        if self.total_tasks == 0 {
            return 100.0;
        }
        self.completed_tasks.load(Ordering::Relaxed) as f64 / self.total_tasks as f64 * 100.0
    }

    /// Get average task duration.
    #[must_use]
    pub fn average_task_duration(&self) -> Option<Duration> {
        let durations: Vec<_> = self.tasks.values().filter_map(|m| m.duration).collect();

        if durations.is_empty() {
            return None;
        }

        let total_ms: u64 = durations.iter().map(|d| d.as_millis() as u64).sum();
        Some(Duration::from_millis(total_ms / durations.len() as u64))
    }

    /// Get throughput (tasks per second).
    #[must_use]
    pub fn throughput(&self) -> f64 {
        let completed = self.completed_tasks.load(Ordering::Relaxed) as f64;
        if let (Some(start), Some(end)) = (self.start_time, self.end_time) {
            let duration_secs = (end - start).num_seconds().max(1);
            completed / duration_secs as f64
        } else if let Some(start) = self.start_time {
            let duration_secs = (Utc::now() - start).num_seconds().max(1);
            completed / duration_secs as f64
        } else {
            0.0
        }
    }
}

/// Monitoring service for tracking workflow execution.
pub struct MonitoringService {
    /// Active workflow metrics.
    workflows: Arc<DashMap<WorkflowId, WorkflowMetrics>>,
    /// Historical metrics (completed workflows).
    history: Arc<DashMap<WorkflowId, WorkflowMetrics>>,
}

impl MonitoringService {
    /// Create a new monitoring service.
    #[must_use]
    pub fn new() -> Self {
        Self {
            workflows: Arc::new(DashMap::new()),
            history: Arc::new(DashMap::new()),
        }
    }

    /// Start tracking a workflow.
    pub fn start_workflow(
        &self,
        workflow_id: WorkflowId,
        workflow_name: String,
        total_tasks: usize,
    ) {
        let mut metrics = WorkflowMetrics::new(workflow_id, workflow_name, total_tasks);
        metrics.mark_started();
        self.workflows.insert(workflow_id, metrics);
    }

    /// Update task progress.
    pub fn update_task(
        &self,
        workflow_id: WorkflowId,
        task_id: TaskId,
        task_name: String,
        state: TaskState,
        error: Option<String>,
    ) {
        if let Some(mut workflow_metrics) = self.workflows.get_mut(&workflow_id) {
            let mut task_metrics = workflow_metrics
                .tasks
                .get(&task_id)
                .cloned()
                .unwrap_or_else(|| TaskMetrics::new(task_id, task_name.clone()));

            match state {
                TaskState::Running => task_metrics.mark_started(),
                TaskState::Completed => task_metrics.mark_completed(),
                TaskState::Failed => {
                    if let Some(err) = error {
                        task_metrics.mark_failed(err);
                    } else {
                        task_metrics.mark_failed("Unknown error".to_string());
                    }
                }
                TaskState::Retrying => task_metrics.increment_retry(),
                _ => task_metrics.state = state,
            }

            workflow_metrics.update_task(task_metrics);
        }
    }

    /// Complete workflow tracking.
    pub fn complete_workflow(&self, workflow_id: WorkflowId, success: bool) {
        if let Some((_, mut metrics)) = self.workflows.remove(&workflow_id) {
            if success {
                metrics.mark_completed();
            } else {
                metrics.mark_failed();
            }
            self.history.insert(workflow_id, metrics);
        }
    }

    /// Get workflow metrics.
    #[must_use]
    pub fn get_workflow_metrics(&self, workflow_id: &WorkflowId) -> Option<WorkflowMetrics> {
        self.workflows
            .get(workflow_id)
            .map(|m| m.clone())
            .or_else(|| self.history.get(workflow_id).map(|m| m.clone()))
    }

    /// Get all active workflow metrics.
    #[must_use]
    pub fn get_active_workflows(&self) -> Vec<WorkflowMetrics> {
        self.workflows
            .iter()
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// Get workflow history.
    #[must_use]
    pub fn get_history(&self, limit: Option<usize>) -> Vec<WorkflowMetrics> {
        let mut history: Vec<_> = self
            .history
            .iter()
            .map(|entry| entry.value().clone())
            .collect();

        // Sort by start time descending
        history.sort_by(|a, b| b.start_time.cmp(&a.start_time));

        if let Some(limit) = limit {
            history.truncate(limit);
        }

        history
    }

    /// Clear old history entries.
    pub fn clear_history(&self, older_than: DateTime<Utc>) {
        self.history.retain(|_, metrics| {
            if let Some(end_time) = metrics.end_time {
                end_time > older_than
            } else {
                true
            }
        });
    }

    /// Get system-wide statistics.
    #[must_use]
    pub fn get_statistics(&self) -> SystemStatistics {
        let active_workflows = self.workflows.len();
        let total_workflows = self.history.len() + active_workflows;

        let completed_workflows = self
            .history
            .iter()
            .filter(|entry| matches!(entry.value().state, WorkflowState::Completed))
            .count();

        let failed_workflows = self
            .history
            .iter()
            .filter(|entry| matches!(entry.value().state, WorkflowState::Failed))
            .count();

        let total_tasks_completed: usize = (self
            .workflows
            .iter()
            .map(|entry| entry.value().completed_tasks.load(Ordering::Relaxed))
            .sum::<u64>()
            + self
                .history
                .iter()
                .map(|entry| entry.value().completed_tasks.load(Ordering::Relaxed))
                .sum::<u64>()) as usize;

        let total_tasks_failed: usize = (self
            .workflows
            .iter()
            .map(|entry| entry.value().failed_tasks.load(Ordering::Relaxed))
            .sum::<u64>()
            + self
                .history
                .iter()
                .map(|entry| entry.value().failed_tasks.load(Ordering::Relaxed))
                .sum::<u64>()) as usize;

        SystemStatistics {
            active_workflows,
            total_workflows,
            completed_workflows,
            failed_workflows,
            total_tasks_completed,
            total_tasks_failed,
        }
    }
}

impl Default for MonitoringService {
    fn default() -> Self {
        Self::new()
    }
}

/// System-wide statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemStatistics {
    /// Number of active workflows.
    pub active_workflows: usize,
    /// Total workflows (active + historical).
    pub total_workflows: usize,
    /// Completed workflows.
    pub completed_workflows: usize,
    /// Failed workflows.
    pub failed_workflows: usize,
    /// Total tasks completed.
    pub total_tasks_completed: usize,
    /// Total tasks failed.
    pub total_tasks_failed: usize,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_task_metrics_creation() {
        let task_id = TaskId::new();
        let metrics = TaskMetrics::new(task_id, "test-task".to_string());
        assert_eq!(metrics.task_id, task_id);
        assert_eq!(metrics.task_name, "test-task");
        assert_eq!(metrics.state, TaskState::Pending);
    }

    #[test]
    fn test_task_metrics_lifecycle() {
        let task_id = TaskId::new();
        let mut metrics = TaskMetrics::new(task_id, "test-task".to_string());

        metrics.mark_started();
        assert_eq!(metrics.state, TaskState::Running);
        assert!(metrics.start_time.is_some());

        metrics.mark_completed();
        assert_eq!(metrics.state, TaskState::Completed);
        assert!(metrics.end_time.is_some());
        assert!(metrics.duration.is_some());
    }

    #[test]
    fn test_task_metrics_failure() {
        let task_id = TaskId::new();
        let mut metrics = TaskMetrics::new(task_id, "test-task".to_string());

        metrics.mark_started();
        metrics.mark_failed("Test error".to_string());

        assert_eq!(metrics.state, TaskState::Failed);
        assert_eq!(metrics.error, Some("Test error".to_string()));
    }

    #[test]
    fn test_workflow_metrics_creation() {
        let workflow_id = WorkflowId::new();
        let metrics = WorkflowMetrics::new(workflow_id, "test-workflow".to_string(), 5);

        assert_eq!(metrics.workflow_id, workflow_id);
        assert_eq!(metrics.total_tasks, 5);
        assert_eq!(metrics.completed_tasks_count(), 0);
    }

    #[test]
    fn test_workflow_metrics_progress() {
        let workflow_id = WorkflowId::new();
        let metrics = WorkflowMetrics::new(workflow_id, "test-workflow".to_string(), 10);

        assert_eq!(metrics.progress_percentage(), 0.0);

        metrics.completed_tasks.store(5, Ordering::Relaxed);
        assert_eq!(metrics.progress_percentage(), 50.0);

        metrics.completed_tasks.store(10, Ordering::Relaxed);
        assert_eq!(metrics.progress_percentage(), 100.0);
    }

    #[test]
    fn test_monitoring_service_creation() {
        let service = MonitoringService::new();
        assert_eq!(service.get_active_workflows().len(), 0);
    }

    #[test]
    fn test_monitoring_service_workflow_tracking() {
        let service = MonitoringService::new();
        let workflow_id = WorkflowId::new();

        service.start_workflow(workflow_id, "test-workflow".to_string(), 3);

        let metrics = service.get_workflow_metrics(&workflow_id);
        assert!(metrics.is_some());
        assert_eq!(
            metrics.expect("should succeed in test").state,
            WorkflowState::Running
        );
    }

    #[test]
    fn test_monitoring_service_task_updates() {
        let service = MonitoringService::new();
        let workflow_id = WorkflowId::new();
        let task_id = TaskId::new();

        service.start_workflow(workflow_id, "test-workflow".to_string(), 1);

        service.update_task(
            workflow_id,
            task_id,
            "task-1".to_string(),
            TaskState::Running,
            None,
        );

        let metrics = service
            .get_workflow_metrics(&workflow_id)
            .expect("should succeed in test");
        assert_eq!(metrics.running_tasks_count(), 1);

        service.update_task(
            workflow_id,
            task_id,
            "task-1".to_string(),
            TaskState::Completed,
            None,
        );

        let metrics = service
            .get_workflow_metrics(&workflow_id)
            .expect("should succeed in test");
        assert_eq!(metrics.completed_tasks_count(), 1);
        assert_eq!(metrics.running_tasks_count(), 0);
    }

    #[test]
    fn test_monitoring_service_completion() {
        let service = MonitoringService::new();
        let workflow_id = WorkflowId::new();

        service.start_workflow(workflow_id, "test-workflow".to_string(), 1);
        assert_eq!(service.get_active_workflows().len(), 1);

        service.complete_workflow(workflow_id, true);
        assert_eq!(service.get_active_workflows().len(), 0);

        let history = service.get_history(None);
        assert_eq!(history.len(), 1);
        assert_eq!(history[0].state, WorkflowState::Completed);
    }

    #[test]
    fn test_statistics() {
        let service = MonitoringService::new();

        let wf1 = WorkflowId::new();
        let wf2 = WorkflowId::new();

        service.start_workflow(wf1, "workflow1".to_string(), 2);
        service.start_workflow(wf2, "workflow2".to_string(), 3);

        service.complete_workflow(wf1, true);
        service.complete_workflow(wf2, false);

        let stats = service.get_statistics();
        assert_eq!(stats.active_workflows, 0);
        assert_eq!(stats.total_workflows, 2);
        assert_eq!(stats.completed_workflows, 1);
        assert_eq!(stats.failed_workflows, 1);
    }
}