swf-runtime 1.0.0-alpha10

Runtime engine for Serverless Workflow DSL — execute, validate, and orchestrate workflows
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
use serde_json::{json, Value};
use std::fmt;

/// Common fields shared by all workflow error types
#[derive(Debug, Clone)]
pub struct ErrorFields {
    pub message: String,
    pub task: String,
    pub instance: String,
    pub status: Option<Value>,
    pub title: Option<String>,
    pub detail: Option<String>,
    pub original_type: Option<String>,
    /// Runtime extension: number of retry attempts made before this error (swf.retryCount)
    pub retry_count: u32,
    /// Runtime extension: ISO 8601 timestamp when the error occurred (swf.timestamp)
    pub timestamp: Option<String>,
}

impl ErrorFields {
    fn new(
        message: impl Into<String>,
        task: impl Into<String>,
        instance: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            task: task.into(),
            instance: instance.into(),
            status: None,
            title: None,
            detail: None,
            original_type: None,
            retry_count: 0,
            timestamp: None,
        }
    }

    fn with_status(mut self, status: Option<Value>) -> Self {
        self.status = status;
        self
    }

    fn with_title(mut self, title: Option<String>) -> Self {
        self.title = title;
        self
    }

    fn with_detail(mut self, detail: Option<String>) -> Self {
        self.detail = detail;
        self
    }

    fn with_original_type(mut self, original_type: Option<String>) -> Self {
        self.original_type = original_type;
        self
    }

    fn instance_opt(&self) -> Option<&str> {
        if self.instance.is_empty() {
            None
        } else {
            Some(&self.instance)
        }
    }
}

/// Error kind discriminator for WorkflowError
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
    Validation,
    Expression,
    Runtime,
    Timeout,
    Communication,
    Authentication,
    Authorization,
    Configuration,
    /// Special kind indicating the workflow should end (from `then: end`)
    WorkflowEnd,
}

impl ErrorKind {
    /// Returns the short type name (e.g., "validation", "runtime")
    pub fn as_str(&self) -> &'static str {
        match self {
            ErrorKind::Validation => "validation",
            ErrorKind::Expression => "expression",
            ErrorKind::Runtime => "runtime",
            ErrorKind::Timeout => "timeout",
            ErrorKind::Communication => "communication",
            ErrorKind::Authentication => "authentication",
            ErrorKind::Authorization => "authorization",
            ErrorKind::Configuration => "configuration",
            ErrorKind::WorkflowEnd => "workflow-end",
        }
    }

    /// Returns the full error type URI per the Serverless Workflow spec
    pub fn type_uri(&self) -> &'static str {
        match self {
            ErrorKind::Validation => "https://serverlessworkflow.io/spec/1.0.0/errors/validation",
            ErrorKind::Expression => "https://serverlessworkflow.io/spec/1.0.0/errors/expression",
            ErrorKind::Runtime => "https://serverlessworkflow.io/spec/1.0.0/errors/runtime",
            ErrorKind::Timeout => "https://serverlessworkflow.io/spec/1.0.0/errors/timeout",
            ErrorKind::Communication => {
                "https://serverlessworkflow.io/spec/1.0.0/errors/communication"
            }
            ErrorKind::Authentication => {
                "https://serverlessworkflow.io/spec/1.0.0/errors/authentication"
            }
            ErrorKind::Authorization => {
                "https://serverlessworkflow.io/spec/1.0.0/errors/authorization"
            }
            ErrorKind::Configuration => {
                "https://serverlessworkflow.io/spec/1.0.0/errors/configuration"
            }
            ErrorKind::WorkflowEnd => {
                "https://serverlessworkflow.io/spec/1.0.0/errors/workflow-end"
            }
        }
    }

    /// Resolves an error type string to an ErrorKind.
    /// Matches both the full URI (from ErrorTypes constants) and short names (suffix after last '/').
    /// Returns ErrorKind::Runtime as the default for unknown types.
    pub fn from_type_str(error_type: &str) -> Self {
        const TYPE_MAP: &[(&str, ErrorKind)] = &[
            ("validation", ErrorKind::Validation),
            ("expression", ErrorKind::Expression),
            ("timeout", ErrorKind::Timeout),
            ("communication", ErrorKind::Communication),
            ("authentication", ErrorKind::Authentication),
            ("authorization", ErrorKind::Authorization),
            ("configuration", ErrorKind::Configuration),
        ];
        TYPE_MAP
            .iter()
            .find(|(suffix, _)| {
                error_type.ends_with(suffix)
                    && (error_type.len() == suffix.len()
                        || error_type
                            .as_bytes()
                            .get(error_type.len() - suffix.len() - 1)
                            == Some(&b'/'))
            })
            .map(|(_, kind)| *kind)
            .unwrap_or(ErrorKind::Runtime)
    }
}

/// Runtime error for the Serverless Workflow engine
#[derive(Debug, Clone)]
pub struct WorkflowError {
    kind: ErrorKind,
    fields: ErrorFields,
    /// For WorkflowEnd, carries the output at the point of termination
    end_output: Option<Value>,
}

impl std::error::Error for WorkflowError {}

impl fmt::Display for WorkflowError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} error in task '{}': {}",
            self.kind.as_str(),
            self.fields.task,
            self.fields.message
        )
    }
}

impl WorkflowError {
    /// Returns the error kind
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Returns a reference to the error fields
    pub fn fields(&self) -> &ErrorFields {
        &self.fields
    }

    /// Creates a validation error
    pub fn validation(message: impl Into<String>, task: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Validation,
            fields: ErrorFields::new(message, task, ""),
            end_output: None,
        }
    }

    /// Creates an expression error
    pub fn expression(message: impl Into<String>, task: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Expression,
            fields: ErrorFields::new(message, task, ""),
            end_output: None,
        }
    }

    /// Creates a runtime error
    pub fn runtime(
        message: impl Into<String>,
        task: impl Into<String>,
        instance: impl Into<String>,
    ) -> Self {
        Self {
            kind: ErrorKind::Runtime,
            fields: ErrorFields::new(message, task, instance),
            end_output: None,
        }
    }

    /// Creates a runtime error without an instance (defaults to empty string)
    pub fn runtime_simple(message: impl Into<String>, task: impl Into<String>) -> Self {
        Self::runtime(message, task, "")
    }

    /// Creates a WorkflowEnd signal — not a real error, but a control flow mechanism
    /// used when `then: end` is encountered. The workflow runner catches this
    /// and returns the current output as the workflow result.
    pub fn workflow_end(task: impl Into<String>, output: Value) -> Self {
        Self {
            kind: ErrorKind::WorkflowEnd,
            fields: ErrorFields::new("workflow ended via 'then: end' directive", task, ""),
            end_output: Some(output),
        }
    }

    /// Returns the output captured at the point of WorkflowEnd, if any
    pub fn end_output(&self) -> Option<&Value> {
        self.end_output.as_ref()
    }

    /// Returns true if this error is a WorkflowEnd signal (not a real error)
    pub fn is_workflow_end(&self) -> bool {
        self.kind == ErrorKind::WorkflowEnd
    }

    /// Creates a timeout error
    /// Per the Serverless Workflow spec, timeout errors have status 408
    pub fn timeout(message: impl Into<String>, task: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Timeout,
            fields: ErrorFields::new(message, task, "").with_status(Some(json!(408))),
            end_output: None,
        }
    }

    /// Creates a communication error
    pub fn communication(message: impl Into<String>, task: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Communication,
            fields: ErrorFields::new(message, task, ""),
            end_output: None,
        }
    }

    /// Creates a communication error with an HTTP status code
    pub fn communication_with_status(
        message: impl Into<String>,
        task: impl Into<String>,
        status_code: u16,
    ) -> Self {
        Self {
            kind: ErrorKind::Communication,
            fields: ErrorFields::new(message, task, "").with_status(Some(Value::from(status_code))),
            end_output: None,
        }
    }

    /// Creates a typed error from DSL error definition fields
    pub fn typed(
        error_type: &str,
        detail: String,
        task: String,
        instance: String,
        status: Option<Value>,
        title: Option<String>,
    ) -> Self {
        let details = if detail.is_empty() {
            None
        } else {
            Some(detail)
        };
        let fields = ErrorFields::new(details.clone().unwrap_or_default(), task, instance)
            .with_status(status)
            .with_title(title)
            .with_detail(details)
            .with_original_type(Some(error_type.to_string()));

        let kind = ErrorKind::from_type_str(error_type);

        Self {
            kind,
            fields,
            end_output: None,
        }
    }

    /// Returns the error type as a full URI (prefers original type from DSL if available)
    pub fn error_type(&self) -> &str {
        self.fields
            .original_type
            .as_deref()
            .unwrap_or(self.kind.type_uri())
    }

    /// Returns the short error type name (last segment of URI)
    pub fn error_type_short(&self) -> &str {
        if let Some(ot) = &self.fields.original_type {
            if let Some(short) = ot.rsplit('/').next() {
                return short;
            }
        }
        self.kind.as_str()
    }

    /// Returns the task name associated with this error
    pub fn task(&self) -> &str {
        &self.fields.task
    }

    /// Returns the instance reference, if available
    pub fn instance(&self) -> Option<&str> {
        self.fields.instance_opt()
    }

    /// Returns the status code, if available
    pub fn status(&self) -> Option<&Value> {
        self.fields.status.as_ref()
    }

    /// Returns the title, if available
    pub fn title(&self) -> Option<&str> {
        self.fields.title.as_deref()
    }

    /// Returns the detail, if available
    pub fn detail(&self) -> Option<&str> {
        self.fields.detail.as_deref()
    }

    /// Converts the error to a JSON Value for use in expressions (e.g., $caughtError)
    pub fn to_value(&self) -> Value {
        let mut map = serde_json::Map::new();
        map.insert(
            "type".to_string(),
            Value::String(self.error_type().to_string()),
        );
        if let Some(status) = self.status() {
            map.insert("status".to_string(), status.clone());
        }
        if let Some(title) = self.title() {
            map.insert("title".to_string(), Value::String(title.to_string()));
        }
        if let Some(detail) = self.detail() {
            map.insert("detail".to_string(), Value::String(detail.to_string()));
        }
        if let Some(instance) = self.instance() {
            map.insert("instance".to_string(), Value::String(instance.to_string()));
        }

        // Runtime extension fields under "swf" namespace
        let mut swf = serde_json::Map::new();
        swf.insert(
            "kind".to_string(),
            Value::String(self.kind.as_str().to_string()),
        );
        swf.insert(
            "retryCount".to_string(),
            Value::from(self.fields.retry_count),
        );
        let ts = match &self.fields.timestamp {
            Some(ts) => ts.clone(),
            None => chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
        };
        swf.insert("timestamp".to_string(), Value::String(ts));
        map.insert("swf".to_string(), Value::Object(swf));

        Value::Object(map)
    }

    /// Sets the instance reference on the error if not already set
    pub fn with_instance(self, instance: impl Into<String>) -> Self {
        let new_instance = instance.into();
        let inst = if self.fields.instance.is_empty() || self.fields.instance == "/" {
            new_instance
        } else {
            self.fields.instance.clone()
        };

        Self {
            kind: self.kind,
            fields: ErrorFields {
                message: self.fields.message,
                task: self.fields.task,
                instance: inst,
                status: self.fields.status,
                title: self.fields.title,
                detail: self.fields.detail,
                original_type: self.fields.original_type,
                retry_count: self.fields.retry_count,
                timestamp: self.fields.timestamp,
            },
            end_output: self.end_output,
        }
    }

    /// Sets the retry attempt count on this error (swf.retryCount)
    pub fn with_retry_count(self, count: u32) -> Self {
        Self {
            kind: self.kind,
            fields: ErrorFields {
                retry_count: count,
                ..self.fields
            },
            end_output: self.end_output,
        }
    }

    /// Sets the ISO 8601 timestamp on this error (swf.timestamp)
    pub fn with_timestamp(self, timestamp: impl Into<String>) -> Self {
        Self {
            kind: self.kind,
            fields: ErrorFields {
                timestamp: Some(timestamp.into()),
                ..self.fields
            },
            end_output: self.end_output,
        }
    }
}

/// Result type alias for workflow operations
pub type WorkflowResult<T> = Result<T, WorkflowError>;

/// Serializes a value to JSON, mapping serialization errors to WorkflowError::runtime.
/// This is a common pattern used across task runners.
pub fn serialize_to_value<T: serde::Serialize>(
    value: &T,
    label: &str,
    task_name: &str,
) -> WorkflowResult<Value> {
    serde_json::to_value(value).map_err(|e| {
        WorkflowError::runtime(
            format!("failed to serialize {}: {}", label, e),
            task_name,
            "",
        )
    })
}

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

    #[test]
    fn test_error_type_validation() {
        let err = WorkflowError::validation("invalid input", "task1");
        assert_eq!(err.error_type_short(), "validation");
        assert!(err.error_type().ends_with("/validation"));
        assert_eq!(err.task(), "task1");
    }

    #[test]
    fn test_error_type_expression() {
        let err = WorkflowError::expression("bad jq", "task2");
        assert_eq!(err.error_type_short(), "expression");
    }

    #[test]
    fn test_error_type_runtime() {
        let err = WorkflowError::runtime("something failed", "task3", "/ref");
        assert_eq!(err.error_type_short(), "runtime");
        assert_eq!(err.instance(), Some("/ref"));
    }

    #[test]
    fn test_error_type_timeout() {
        let err = WorkflowError::timeout("timed out", "task4");
        assert_eq!(err.error_type_short(), "timeout");
        assert!(err.instance().is_none());
    }

    #[test]
    fn test_error_type_communication() {
        let err = WorkflowError::communication("connection refused", "task5");
        assert_eq!(err.error_type_short(), "communication");
    }

    #[test]
    fn test_error_with_instance() {
        let err = WorkflowError::runtime("invalid", "task1", "").with_instance("/ref/task1");
        assert_eq!(err.error_type_short(), "runtime");
        assert_eq!(err.instance(), Some("/ref/task1"));
    }

    #[test]
    fn test_error_with_instance_preserves_type() {
        let err = WorkflowError::timeout("timed out", "task1").with_instance("/ref/task1");
        assert_eq!(err.error_type_short(), "timeout");
        assert_eq!(err.instance(), Some("/ref/task1"));
    }

    #[test]
    fn test_error_task_name() {
        let err = WorkflowError::timeout("timeout", "myTask");
        assert_eq!(err.task(), "myTask");
    }

    #[test]
    fn test_error_display() {
        let err = WorkflowError::validation("bad input", "task1");
        let msg = format!("{}", err);
        assert!(msg.contains("bad input"));
        assert!(msg.contains("task1"));
    }

    #[test]
    fn test_error_typed_with_status() {
        let err = WorkflowError::typed(
            "https://serverlessworkflow.io/spec/1.0.0/errors/transient",
            "Something went wrong".to_string(),
            "testTask".to_string(),
            "/do/0/testTask".to_string(),
            Some(Value::from(503)),
            Some("Transient Error".to_string()),
        );
        assert_eq!(err.error_type_short(), "transient");
        assert_eq!(err.status(), Some(&Value::from(503)));
        assert_eq!(err.title(), Some("Transient Error"));
        assert_eq!(err.detail(), Some("Something went wrong"));
    }

    #[test]
    fn test_error_to_value() {
        let err = WorkflowError::typed(
            "https://serverlessworkflow.io/spec/1.0.0/errors/authentication",
            "Auth failed".to_string(),
            "authTask".to_string(),
            "".to_string(),
            Some(Value::from(401)),
            Some("Auth Error".to_string()),
        );
        let val = err.to_value();
        assert_eq!(
            val["type"],
            "https://serverlessworkflow.io/spec/1.0.0/errors/authentication"
        );
        assert_eq!(val["status"], 401);
        assert_eq!(val["title"], "Auth Error");
        assert_eq!(val["detail"], "Auth failed");
    }

    #[test]
    fn test_error_kind() {
        let err = WorkflowError::timeout("timed out", "task1");
        assert_eq!(err.kind(), ErrorKind::Timeout);
    }

    #[test]
    fn test_error_to_value_swf_namespace() {
        let err = WorkflowError::communication_with_status("connection refused", "task1", 503);
        let val = err.to_value();
        // swf.kind should always be present
        assert_eq!(val["swf"]["kind"], "communication");
        // swf.retryCount defaults to 0
        assert_eq!(val["swf"]["retryCount"], 0);
        // swf.timestamp should be auto-generated (ISO 8601 format)
        let ts = val["swf"]["timestamp"].as_str().unwrap();
        assert!(ts.contains("T"), "timestamp should be ISO 8601: {}", ts);
    }

    #[test]
    fn test_error_with_retry_count() {
        let err = WorkflowError::timeout("timed out", "task1").with_retry_count(3);
        let val = err.to_value();
        assert_eq!(val["swf"]["kind"], "timeout");
        assert_eq!(val["swf"]["retryCount"], 3);
    }

    #[test]
    fn test_error_with_timestamp() {
        let err =
            WorkflowError::runtime("fail", "task1", "/").with_timestamp("2026-05-11T10:30:00.000Z");
        let val = err.to_value();
        assert_eq!(val["swf"]["timestamp"], "2026-05-11T10:30:00.000Z");
    }

    #[test]
    fn test_error_swf_kind_variants() {
        assert_eq!(
            WorkflowError::validation("v", "t").to_value()["swf"]["kind"],
            "validation"
        );
        assert_eq!(
            WorkflowError::expression("e", "t").to_value()["swf"]["kind"],
            "expression"
        );
        assert_eq!(
            WorkflowError::runtime("r", "t", "/").to_value()["swf"]["kind"],
            "runtime"
        );
        assert_eq!(
            WorkflowError::timeout("t", "t").to_value()["swf"]["kind"],
            "timeout"
        );
        assert_eq!(
            WorkflowError::typed(
                "https://serverlessworkflow.io/spec/1.0.0/errors/authentication",
                "a".to_string(),
                "t".to_string(),
                "t".to_string(),
                None,
                None,
            )
            .to_value()["swf"]["kind"],
            "authentication"
        );
    }
}