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
//! Structured workflow event log for `oximedia-workflow`.
//!
//! [`WorkflowLog`] stores an in-memory sequence of [`WorkflowEvent`]s and
//! provides filtering helpers such as [`WorkflowLog::recent_errors`] so that
//! operators can quickly surface problems without trawling the full history.

#![allow(dead_code)]

use serde::{Deserialize, Serialize};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

// ── Event type ────────────────────────────────────────────────────────────────

/// Discriminates the kind of event stored in a [`WorkflowEvent`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum WorkflowEventType {
    /// The workflow was submitted to the execution queue.
    Submitted,
    /// A task within the workflow started executing.
    TaskStarted,
    /// A task completed successfully.
    TaskCompleted,
    /// A task failed and will (or will not) be retried.
    TaskFailed,
    /// The workflow completed without any failures.
    WorkflowCompleted,
    /// The workflow was cancelled before completion.
    WorkflowCancelled,
    /// A non-fatal warning was recorded (e.g. resource limit approached).
    Warning,
    /// A fatal error occurred; the workflow cannot continue.
    Error,
}

impl WorkflowEventType {
    /// Returns `true` when this event type indicates a failure or error.
    #[must_use]
    pub fn is_error(self) -> bool {
        matches!(self, Self::TaskFailed | Self::Error)
    }

    /// Returns `true` when this event type signals successful completion.
    #[must_use]
    pub fn is_success(self) -> bool {
        matches!(self, Self::TaskCompleted | Self::WorkflowCompleted)
    }

    /// Returns a short label suitable for log output.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Submitted => "SUBMITTED",
            Self::TaskStarted => "TASK_START",
            Self::TaskCompleted => "TASK_OK",
            Self::TaskFailed => "TASK_FAIL",
            Self::WorkflowCompleted => "WF_OK",
            Self::WorkflowCancelled => "WF_CANCEL",
            Self::Warning => "WARN",
            Self::Error => "ERROR",
        }
    }
}

impl std::fmt::Display for WorkflowEventType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.label())
    }
}

// ── Event ─────────────────────────────────────────────────────────────────────

/// A single structured log entry within a [`WorkflowLog`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkflowEvent {
    /// Monotonically increasing sequence number within the log.
    pub seq: u64,
    /// Seconds since the UNIX epoch when this event was recorded.
    pub timestamp_secs: u64,
    /// The kind of event.
    pub event_type: WorkflowEventType,
    /// Identifier of the workflow this event belongs to.
    pub workflow_id: String,
    /// Optional identifier of the specific task (if task-scoped).
    pub task_id: Option<String>,
    /// Human-readable message providing additional context.
    pub message: String,
}

impl WorkflowEvent {
    /// Creates a workflow-level event using the current system time.
    #[must_use]
    pub fn workflow_event(
        seq: u64,
        event_type: WorkflowEventType,
        workflow_id: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            seq,
            timestamp_secs: now_secs(),
            event_type,
            workflow_id: workflow_id.into(),
            task_id: None,
            message: message.into(),
        }
    }

    /// Creates a task-scoped event using the current system time.
    #[must_use]
    pub fn task_event(
        seq: u64,
        event_type: WorkflowEventType,
        workflow_id: impl Into<String>,
        task_id: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            seq,
            timestamp_secs: now_secs(),
            event_type,
            workflow_id: workflow_id.into(),
            task_id: Some(task_id.into()),
            message: message.into(),
        }
    }

    /// Returns `true` when this event represents a failure or error.
    #[must_use]
    pub fn is_error(&self) -> bool {
        self.event_type.is_error()
    }
}

/// Returns seconds since UNIX epoch (best-effort; returns 0 on overflow).
fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or(Duration::ZERO)
        .as_secs()
}

// ── Log ───────────────────────────────────────────────────────────────────────

/// An in-memory log that accumulates [`WorkflowEvent`]s for one or more
/// workflows and exposes query helpers.
#[derive(Debug, Default, Clone)]
pub struct WorkflowLog {
    events: Vec<WorkflowEvent>,
    next_seq: u64,
}

impl WorkflowLog {
    /// Creates a new, empty log.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends an event to the log, assigning it the next sequence number.
    pub fn append(
        &mut self,
        event_type: WorkflowEventType,
        workflow_id: impl Into<String>,
        message: impl Into<String>,
    ) {
        let ev = WorkflowEvent::workflow_event(self.next_seq, event_type, workflow_id, message);
        self.next_seq += 1;
        self.events.push(ev);
    }

    /// Appends a task-scoped event to the log.
    pub fn append_task(
        &mut self,
        event_type: WorkflowEventType,
        workflow_id: impl Into<String>,
        task_id: impl Into<String>,
        message: impl Into<String>,
    ) {
        let ev =
            WorkflowEvent::task_event(self.next_seq, event_type, workflow_id, task_id, message);
        self.next_seq += 1;
        self.events.push(ev);
    }

    /// Total number of events in the log.
    #[must_use]
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Returns `true` when the log contains no events.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// Returns a slice of all events in insertion order.
    #[must_use]
    pub fn all(&self) -> &[WorkflowEvent] {
        &self.events
    }

    /// Returns the `n` most recently appended error events (`TaskFailed` or
    /// Error), newest first.
    #[must_use]
    pub fn recent_errors(&self, n: usize) -> Vec<&WorkflowEvent> {
        self.events
            .iter()
            .rev()
            .filter(|e| e.is_error())
            .take(n)
            .collect()
    }

    /// Returns all events for the given workflow ID.
    #[must_use]
    pub fn events_for_workflow<'a>(&'a self, workflow_id: &str) -> Vec<&'a WorkflowEvent> {
        self.events
            .iter()
            .filter(|e| e.workflow_id == workflow_id)
            .collect()
    }

    /// Returns all events matching the given event type.
    #[must_use]
    pub fn events_of_type(&self, event_type: WorkflowEventType) -> Vec<&WorkflowEvent> {
        self.events
            .iter()
            .filter(|e| e.event_type == event_type)
            .collect()
    }

    /// Returns the number of error-type events in the log.
    #[must_use]
    pub fn error_count(&self) -> usize {
        self.events.iter().filter(|e| e.is_error()).count()
    }

    /// Clears all events from the log and resets the sequence counter.
    pub fn clear(&mut self) {
        self.events.clear();
        self.next_seq = 0;
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    fn make_log() -> WorkflowLog {
        let mut log = WorkflowLog::new();
        log.append(WorkflowEventType::Submitted, "wf-1", "Workflow submitted");
        log.append_task(
            WorkflowEventType::TaskStarted,
            "wf-1",
            "task-a",
            "Started task-a",
        );
        log.append_task(
            WorkflowEventType::TaskFailed,
            "wf-1",
            "task-a",
            "task-a failed: timeout",
        );
        log.append(WorkflowEventType::Error, "wf-1", "Unrecoverable error");
        log.append_task(
            WorkflowEventType::TaskCompleted,
            "wf-2",
            "task-b",
            "task-b done",
        );
        log
    }

    #[test]
    fn test_new_log_empty() {
        let log = WorkflowLog::new();
        assert!(log.is_empty());
        assert_eq!(log.len(), 0);
    }

    #[test]
    fn test_append_increments_len() {
        let mut log = WorkflowLog::new();
        log.append(WorkflowEventType::Submitted, "wf-x", "msg");
        assert_eq!(log.len(), 1);
    }

    #[test]
    fn test_sequence_numbers_monotonic() {
        let log = make_log();
        for (i, ev) in log.all().iter().enumerate() {
            assert_eq!(ev.seq, i as u64);
        }
    }

    #[test]
    fn test_recent_errors_count() {
        let log = make_log();
        // Two error events: TaskFailed and Error
        let errors = log.recent_errors(10);
        assert_eq!(errors.len(), 2);
    }

    #[test]
    fn test_recent_errors_newest_first() {
        let log = make_log();
        let errors = log.recent_errors(10);
        // The Error event was appended after TaskFailed, so it has higher seq
        assert!(errors[0].seq > errors[1].seq);
    }

    #[test]
    fn test_recent_errors_limit() {
        let log = make_log();
        let errors = log.recent_errors(1);
        assert_eq!(errors.len(), 1);
    }

    #[test]
    fn test_events_for_workflow() {
        let log = make_log();
        let wf1 = log.events_for_workflow("wf-1");
        assert_eq!(wf1.len(), 4);
        let wf2 = log.events_for_workflow("wf-2");
        assert_eq!(wf2.len(), 1);
    }

    #[test]
    fn test_events_of_type() {
        let log = make_log();
        let starts = log.events_of_type(WorkflowEventType::TaskStarted);
        assert_eq!(starts.len(), 1);
    }

    #[test]
    fn test_error_count() {
        let log = make_log();
        assert_eq!(log.error_count(), 2);
    }

    #[test]
    fn test_clear_resets_log() {
        let mut log = make_log();
        log.clear();
        assert!(log.is_empty());
        assert_eq!(log.error_count(), 0);
    }

    #[test]
    fn test_clear_resets_sequence() {
        let mut log = make_log();
        log.clear();
        log.append(WorkflowEventType::Submitted, "wf-new", "msg");
        assert_eq!(log.all()[0].seq, 0);
    }

    #[test]
    fn test_event_type_is_error() {
        assert!(WorkflowEventType::TaskFailed.is_error());
        assert!(WorkflowEventType::Error.is_error());
        assert!(!WorkflowEventType::TaskCompleted.is_error());
        assert!(!WorkflowEventType::Submitted.is_error());
    }

    #[test]
    fn test_event_type_is_success() {
        assert!(WorkflowEventType::TaskCompleted.is_success());
        assert!(WorkflowEventType::WorkflowCompleted.is_success());
        assert!(!WorkflowEventType::TaskFailed.is_success());
    }

    #[test]
    fn test_event_type_label() {
        assert_eq!(WorkflowEventType::Error.label(), "ERROR");
        assert_eq!(WorkflowEventType::Submitted.label(), "SUBMITTED");
    }

    #[test]
    fn test_event_type_display() {
        assert_eq!(format!("{}", WorkflowEventType::Warning), "WARN");
    }

    #[test]
    fn test_task_event_has_task_id() {
        let log = make_log();
        let task_ev = log
            .events_of_type(WorkflowEventType::TaskStarted)
            .into_iter()
            .next()
            .expect("should succeed in test");
        assert_eq!(task_ev.task_id.as_deref(), Some("task-a"));
    }

    #[test]
    fn test_workflow_event_no_task_id() {
        let log = make_log();
        let submitted = log
            .events_of_type(WorkflowEventType::Submitted)
            .into_iter()
            .next()
            .expect("should succeed in test");
        assert!(submitted.task_id.is_none());
    }
}