dataflow-rs 2.0.3

A lightweight, rule-driven workflow engine for building powerful data processing pipelines and nanoservices in Rust. Extend it with your custom tasks to create robust, maintainable services.
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
use chrono::Utc;
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Main error type for the dataflow engine
#[derive(Debug, Error, Clone, Serialize, Deserialize)]
pub enum DataflowError {
    /// Validation errors occurring during rule evaluation
    #[error("Validation error: {0}")]
    Validation(String),

    /// Errors during function execution
    #[error("Function execution error: {context}")]
    FunctionExecution {
        context: String,
        #[source]
        #[serde(skip)]
        source: Option<Box<DataflowError>>,
    },

    /// Workflow-related errors
    #[error("Workflow error: {0}")]
    Workflow(String),

    /// Task-related errors
    #[error("Task error: {0}")]
    Task(String),

    /// Function not found errors
    #[error("Function not found: {0}")]
    FunctionNotFound(String),

    /// JSON serialization/deserialization errors
    #[error("Deserialization error: {0}")]
    Deserialization(String),

    /// I/O errors (file reading, etc.)
    #[error("IO error: {0}")]
    Io(String),

    /// JSONLogic/DataLogic evaluation errors
    #[error("Logic evaluation error: {0}")]
    LogicEvaluation(String),

    /// HTTP request errors
    #[error("HTTP error: {status} - {message}")]
    Http { status: u16, message: String },

    /// Timeout errors
    #[error("Timeout error: {0}")]
    Timeout(String),

    /// Any other errors
    #[error("Unknown error: {0}")]
    Unknown(String),
}

impl DataflowError {
    /// Creates a new function execution error with context
    pub fn function_execution<S: Into<String>>(context: S, source: Option<DataflowError>) -> Self {
        DataflowError::FunctionExecution {
            context: context.into(),
            source: source.map(Box::new),
        }
    }

    /// Creates a new HTTP error
    pub fn http<S: Into<String>>(status: u16, message: S) -> Self {
        DataflowError::Http {
            status,
            message: message.into(),
        }
    }

    /// Convert from std::io::Error
    pub fn from_io(err: std::io::Error) -> Self {
        DataflowError::Io(err.to_string())
    }

    /// Convert from serde_json::Error
    pub fn from_serde(err: serde_json::Error) -> Self {
        DataflowError::Deserialization(err.to_string())
    }

    /// Determines if this error is retryable (worth retrying)
    ///
    /// Retryable errors are typically transient infrastructure failures that might succeed on retry.
    /// Non-retryable errors are typically data validation, logic, or configuration errors that
    /// will consistently fail on retry.
    pub fn retryable(&self) -> bool {
        match self {
            // Retryable errors - infrastructure/transient failures
            DataflowError::Http { status, .. } => {
                // Retry on server errors (5xx) and specific client errors that might be transient
                *status >= 500 || *status == 429 || *status == 408 || *status == 0
                // 0 means connection error
            }
            DataflowError::Timeout(_) => true,
            DataflowError::Io(_) => true,
            DataflowError::FunctionExecution { source, .. } => {
                // Inherit retryability from the source error if present
                source.as_ref().map(|e| e.retryable()).unwrap_or(false)
            }

            // Non-retryable errors - data/logic/configuration issues
            DataflowError::Validation(_) => false,
            DataflowError::LogicEvaluation(_) => false,
            DataflowError::Deserialization(_) => false,
            DataflowError::Workflow(_) => false,
            DataflowError::Task(_) => false,
            DataflowError::FunctionNotFound(_) => false,
            DataflowError::Unknown(_) => false,
        }
    }
}

/// Type alias for Result with DataflowError
pub type Result<T> = std::result::Result<T, DataflowError>;

/// Structured error information for error tracking in messages
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorInfo {
    /// Error code (e.g., "WORKFLOW_ERROR", "TASK_ERROR", "VALIDATION_ERROR")
    pub code: String,

    /// Human-readable error message
    pub message: String,

    /// Optional path to the error location (e.g., "workflow.id", "task.id", "data.field")
    pub path: Option<String>,

    /// ID of the workflow where the error occurred (if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow_id: Option<String>,

    /// ID of the task where the error occurred (if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,

    /// Timestamp when the error occurred
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,

    /// Whether a retry was attempted
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_attempted: Option<bool>,

    /// Number of retries attempted
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_count: Option<u32>,
}

impl ErrorInfo {
    /// Create a new error info entry with all fields
    pub fn new(workflow_id: Option<String>, task_id: Option<String>, error: DataflowError) -> Self {
        Self {
            code: match &error {
                DataflowError::Validation(_) => "VALIDATION_ERROR".to_string(),
                DataflowError::Workflow(_) => "WORKFLOW_ERROR".to_string(),
                DataflowError::Task(_) => "TASK_ERROR".to_string(),
                DataflowError::FunctionNotFound(_) => "FUNCTION_NOT_FOUND".to_string(),
                DataflowError::FunctionExecution { .. } => "FUNCTION_ERROR".to_string(),
                DataflowError::LogicEvaluation(_) => "LOGIC_ERROR".to_string(),
                DataflowError::Http { .. } => "HTTP_ERROR".to_string(),
                DataflowError::Timeout(_) => "TIMEOUT_ERROR".to_string(),
                DataflowError::Io(_) => "IO_ERROR".to_string(),
                DataflowError::Deserialization(_) => "DESERIALIZATION_ERROR".to_string(),
                DataflowError::Unknown(_) => "UNKNOWN_ERROR".to_string(),
            },
            message: error.to_string(),
            path: None,
            workflow_id,
            task_id,
            timestamp: Some(Utc::now().to_rfc3339()),
            retry_attempted: Some(false),
            retry_count: Some(0),
        }
    }

    /// Create a simple error info with just code, message, and optional path
    pub fn simple(code: String, message: String, path: Option<String>) -> Self {
        Self {
            code,
            message,
            path,
            workflow_id: None,
            task_id: None,
            timestamp: Some(Utc::now().to_rfc3339()),
            retry_attempted: None,
            retry_count: None,
        }
    }

    /// Create a simple error info from references (avoids cloning when possible)
    pub fn simple_ref(code: &str, message: &str, path: Option<&str>) -> Self {
        Self {
            code: code.to_string(),
            message: message.to_string(),
            path: path.map(|s| s.to_string()),
            workflow_id: None,
            task_id: None,
            timestamp: Some(Utc::now().to_rfc3339()),
            retry_attempted: None,
            retry_count: None,
        }
    }

    /// Mark that a retry was attempted
    pub fn with_retry(mut self) -> Self {
        self.retry_attempted = Some(true);
        self.retry_count = Some(self.retry_count.unwrap_or(0) + 1);
        self
    }

    /// Create a builder for ErrorInfo
    pub fn builder(code: impl Into<String>, message: impl Into<String>) -> ErrorInfoBuilder {
        ErrorInfoBuilder::new(code, message)
    }
}

/// Builder for creating ErrorInfo instances with a fluent API
pub struct ErrorInfoBuilder {
    code: String,
    message: String,
    path: Option<String>,
    workflow_id: Option<String>,
    task_id: Option<String>,
    timestamp: Option<String>,
    retry_attempted: Option<bool>,
    retry_count: Option<u32>,
}

impl ErrorInfoBuilder {
    /// Create a new ErrorInfoBuilder with required fields
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            path: None,
            workflow_id: None,
            task_id: None,
            timestamp: Some(Utc::now().to_rfc3339()),
            retry_attempted: None,
            retry_count: None,
        }
    }

    /// Set the error path
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Set the workflow ID
    pub fn workflow_id(mut self, id: impl Into<String>) -> Self {
        self.workflow_id = Some(id.into());
        self
    }

    /// Set the task ID
    pub fn task_id(mut self, id: impl Into<String>) -> Self {
        self.task_id = Some(id.into());
        self
    }

    /// Set custom timestamp (defaults to now if not set)
    pub fn timestamp(mut self, timestamp: impl Into<String>) -> Self {
        self.timestamp = Some(timestamp.into());
        self
    }

    /// Mark as retry attempted
    pub fn retry_attempted(mut self, attempted: bool) -> Self {
        self.retry_attempted = Some(attempted);
        self
    }

    /// Set retry count
    pub fn retry_count(mut self, count: u32) -> Self {
        self.retry_count = Some(count);
        self
    }

    /// Build the ErrorInfo instance
    pub fn build(self) -> ErrorInfo {
        ErrorInfo {
            code: self.code,
            message: self.message,
            path: self.path,
            workflow_id: self.workflow_id,
            task_id: self.task_id,
            timestamp: self.timestamp,
            retry_attempted: self.retry_attempted,
            retry_count: self.retry_count,
        }
    }
}

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

    #[test]
    fn test_retryable_errors() {
        // Test retryable errors
        assert!(
            DataflowError::Http {
                status: 500,
                message: "Internal Server Error".to_string()
            }
            .retryable()
        );
        assert!(
            DataflowError::Http {
                status: 502,
                message: "Bad Gateway".to_string()
            }
            .retryable()
        );
        assert!(
            DataflowError::Http {
                status: 503,
                message: "Service Unavailable".to_string()
            }
            .retryable()
        );
        assert!(
            DataflowError::Http {
                status: 429,
                message: "Too Many Requests".to_string()
            }
            .retryable()
        );
        assert!(
            DataflowError::Http {
                status: 408,
                message: "Request Timeout".to_string()
            }
            .retryable()
        );
        assert!(
            DataflowError::Http {
                status: 0,
                message: "Connection Error".to_string()
            }
            .retryable()
        );
        assert!(DataflowError::Timeout("Connection timeout".to_string()).retryable());
        assert!(DataflowError::Io("Network error".to_string()).retryable());
    }

    #[test]
    fn test_non_retryable_errors() {
        // Test non-retryable errors
        assert!(
            !DataflowError::Http {
                status: 400,
                message: "Bad Request".to_string()
            }
            .retryable()
        );
        assert!(
            !DataflowError::Http {
                status: 401,
                message: "Unauthorized".to_string()
            }
            .retryable()
        );
        assert!(
            !DataflowError::Http {
                status: 403,
                message: "Forbidden".to_string()
            }
            .retryable()
        );
        assert!(
            !DataflowError::Http {
                status: 404,
                message: "Not Found".to_string()
            }
            .retryable()
        );
        assert!(!DataflowError::Validation("Invalid input".to_string()).retryable());
        assert!(!DataflowError::LogicEvaluation("Invalid logic".to_string()).retryable());
        assert!(!DataflowError::Deserialization("Invalid JSON".to_string()).retryable());
        assert!(!DataflowError::Workflow("Invalid workflow".to_string()).retryable());
        assert!(!DataflowError::Unknown("Unknown error".to_string()).retryable());
    }

    #[test]
    fn test_function_execution_error_retryability() {
        // Test that function execution errors inherit retryability from source
        let retryable_source = DataflowError::Http {
            status: 500,
            message: "Server Error".to_string(),
        };
        let non_retryable_source = DataflowError::Validation("Invalid data".to_string());

        let retryable_func_error =
            DataflowError::function_execution("HTTP call failed", Some(retryable_source));
        let non_retryable_func_error =
            DataflowError::function_execution("Validation failed", Some(non_retryable_source));
        let no_source_func_error = DataflowError::function_execution("Unknown failure", None);

        assert!(retryable_func_error.retryable());
        assert!(!non_retryable_func_error.retryable());
        assert!(!no_source_func_error.retryable());
    }

    #[test]
    fn test_error_info_builder() {
        // Test basic builder
        let error = ErrorInfo::builder("TEST_ERROR", "Test message").build();
        assert_eq!(error.code, "TEST_ERROR");
        assert_eq!(error.message, "Test message");
        assert!(error.timestamp.is_some());
        assert!(error.path.is_none());

        // Test full builder
        let error = ErrorInfo::builder("VALIDATION_ERROR", "Field validation failed")
            .path("data.email")
            .workflow_id("workflow_1")
            .task_id("validate_email")
            .retry_attempted(true)
            .retry_count(2)
            .build();

        assert_eq!(error.code, "VALIDATION_ERROR");
        assert_eq!(error.message, "Field validation failed");
        assert_eq!(error.path, Some("data.email".to_string()));
        assert_eq!(error.workflow_id, Some("workflow_1".to_string()));
        assert_eq!(error.task_id, Some("validate_email".to_string()));
        assert_eq!(error.retry_attempted, Some(true));
        assert_eq!(error.retry_count, Some(2));
    }
}