swf-runtime 1.0.0-alpha9

Runtime engine for Serverless Workflow DSL — execute, validate, and orchestrate workflows
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
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>,
}

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,
        }
    }

    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,
}

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",
        }
    }

    /// 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"
            }
        }
    }

    /// 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,
}

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, ""),
        }
    }

    /// 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, ""),
        }
    }

    /// 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),
        }
    }

    /// 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 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))),
        }
    }

    /// 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, ""),
        }
    }

    /// 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))),
        }
    }

    /// 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 }
    }

    /// 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("details".to_string(), Value::String(detail.to_string()));
        }
        if let Some(instance) = self.instance() {
            map.insert("instance".to_string(), Value::String(instance.to_string()));
        }
        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,
            },
        }
    }
}

/// 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["details"], "Auth failed");
    }

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