xerv-core 0.1.0

Workflow orchestration core: memory-mapped arena, write-ahead log, traits, and type system
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
//! Flow definition - the top-level YAML document.

use super::validation::{FlowValidator, ValidationResult};
use super::{EdgeDefinition, FlowSettings, NodeDefinition, TriggerDefinition};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// A complete flow definition from YAML.
///
/// This is the top-level structure representing a XERV flow document.
///
/// # Example
///
/// ```yaml
/// name: order_processing
/// version: "1.0"
/// description: Process incoming orders with fraud detection
///
/// triggers:
///   - id: api_webhook
///     type: webhook
///     params:
///       port: 8080
///       path: /orders
///
/// nodes:
///   validate:
///     type: std::json_parse
///     config:
///       strict: true
///
///   fraud_check:
///     type: std::switch
///     config:
///       condition:
///         type: greater_than
///         field: risk_score
///         value: 0.8
///
///   process_order:
///     type: plugins::order_processor
///
///   flag_fraud:
///     type: plugins::fraud_handler
///
/// edges:
///   - from: api_webhook
///     to: validate
///   - from: validate
///     to: fraud_check
///   - from: fraud_check.true
///     to: flag_fraud
///   - from: fraud_check.false
///     to: process_order
///
/// settings:
///   max_concurrent_executions: 100
///   execution_timeout_ms: 30000
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowDefinition {
    /// Flow name (required).
    pub name: String,

    /// Flow version (optional, defaults to "1.0").
    #[serde(default)]
    pub version: Option<String>,

    /// Human-readable description.
    #[serde(default)]
    pub description: Option<String>,

    /// Triggers that start this flow.
    #[serde(default)]
    pub triggers: Vec<TriggerDefinition>,

    /// Nodes in the flow, keyed by node ID.
    #[serde(default)]
    pub nodes: HashMap<String, NodeDefinition>,

    /// Edges connecting nodes.
    #[serde(default)]
    pub edges: Vec<EdgeDefinition>,

    /// Runtime settings.
    #[serde(default)]
    pub settings: FlowSettings,
}

impl FlowDefinition {
    /// Create a new flow definition.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            version: Some("1.0".to_string()),
            description: None,
            triggers: Vec::new(),
            nodes: HashMap::new(),
            edges: Vec::new(),
            settings: FlowSettings::default(),
        }
    }

    /// Parse a flow definition from YAML string.
    pub fn from_yaml(yaml: &str) -> Result<Self, serde_yaml::Error> {
        serde_yaml::from_str(yaml)
    }

    /// Parse a flow definition from YAML file.
    pub fn from_file(path: &std::path::Path) -> Result<Self, FlowLoadError> {
        let content = std::fs::read_to_string(path).map_err(|e| FlowLoadError::Io {
            path: path.to_path_buf(),
            source: e,
        })?;

        Self::from_yaml(&content).map_err(|e| FlowLoadError::Parse {
            path: path.to_path_buf(),
            source: e,
        })
    }

    /// Serialize to YAML string.
    pub fn to_yaml(&self) -> Result<String, serde_yaml::Error> {
        serde_yaml::to_string(self)
    }

    /// Validate the flow definition.
    pub fn validate(&self) -> ValidationResult {
        FlowValidator::new().validate(self)
    }

    /// Parse and validate in one step.
    pub fn from_yaml_validated(yaml: &str) -> Result<Self, FlowLoadError> {
        let flow = Self::from_yaml(yaml).map_err(|e| FlowLoadError::ParseString { source: e })?;

        flow.validate()
            .map_err(|errors| FlowLoadError::Validation { errors })?;

        Ok(flow)
    }

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

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

    /// Add a trigger.
    pub fn with_trigger(mut self, trigger: TriggerDefinition) -> Self {
        self.triggers.push(trigger);
        self
    }

    /// Add a node.
    pub fn with_node(mut self, id: impl Into<String>, node: NodeDefinition) -> Self {
        self.nodes.insert(id.into(), node);
        self
    }

    /// Add an edge.
    pub fn with_edge(mut self, edge: EdgeDefinition) -> Self {
        self.edges.push(edge);
        self
    }

    /// Set settings.
    pub fn with_settings(mut self, settings: FlowSettings) -> Self {
        self.settings = settings;
        self
    }

    /// Get the effective version (defaults to "1.0").
    pub fn effective_version(&self) -> &str {
        self.version.as_deref().unwrap_or("1.0")
    }

    /// Get all node IDs.
    pub fn node_ids(&self) -> impl Iterator<Item = &str> {
        self.nodes.keys().map(|s| s.as_str())
    }

    /// Get all trigger IDs.
    pub fn trigger_ids(&self) -> impl Iterator<Item = &str> {
        self.triggers.iter().map(|t| t.id.as_str())
    }

    /// Get a node by ID.
    pub fn get_node(&self, id: &str) -> Option<&NodeDefinition> {
        self.nodes.get(id)
    }

    /// Get a trigger by ID.
    pub fn get_trigger(&self, id: &str) -> Option<&TriggerDefinition> {
        self.triggers.iter().find(|t| t.id == id)
    }

    /// Check if a trigger with the given ID exists.
    pub fn has_trigger(&self, id: &str) -> bool {
        self.triggers.iter().any(|t| t.id == id)
    }

    /// Check if a node with the given ID exists.
    pub fn has_node(&self, id: &str) -> bool {
        self.nodes.contains_key(id)
    }

    /// Get enabled triggers.
    pub fn enabled_triggers(&self) -> impl Iterator<Item = &TriggerDefinition> {
        self.triggers.iter().filter(|t| t.enabled)
    }

    /// Get enabled nodes.
    pub fn enabled_nodes(&self) -> impl Iterator<Item = (&str, &NodeDefinition)> {
        self.nodes
            .iter()
            .filter(|(_, n)| n.enabled)
            .map(|(k, v)| (k.as_str(), v))
    }

    /// Find edges from a given node.
    pub fn edges_from(&self, node_id: &str) -> impl Iterator<Item = &EdgeDefinition> {
        self.edges.iter().filter(move |e| e.from_node() == node_id)
    }

    /// Find edges to a given node.
    pub fn edges_to(&self, node_id: &str) -> impl Iterator<Item = &EdgeDefinition> {
        self.edges.iter().filter(move |e| e.to_node() == node_id)
    }
}

/// Error loading a flow definition.
#[derive(Debug)]
pub enum FlowLoadError {
    /// I/O error reading file.
    Io {
        path: std::path::PathBuf,
        source: std::io::Error,
    },
    /// YAML parse error.
    Parse {
        path: std::path::PathBuf,
        source: serde_yaml::Error,
    },
    /// YAML parse error (from string).
    ParseString { source: serde_yaml::Error },
    /// Validation errors.
    Validation {
        errors: Vec<super::validation::ValidationError>,
    },
}

impl std::fmt::Display for FlowLoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io { path, source } => {
                write!(
                    f,
                    "failed to read flow file '{}': {}",
                    path.display(),
                    source
                )
            }
            Self::Parse { path, source } => {
                write!(
                    f,
                    "failed to parse flow file '{}': {}",
                    path.display(),
                    source
                )
            }
            Self::ParseString { source } => {
                write!(f, "failed to parse YAML: {}", source)
            }
            Self::Validation { errors } => {
                writeln!(f, "flow validation failed with {} error(s):", errors.len())?;
                for error in errors {
                    writeln!(f, "  - {}", error)?;
                }
                Ok(())
            }
        }
    }
}

impl std::error::Error for FlowLoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::Parse { source, .. } => Some(source),
            Self::ParseString { source } => Some(source),
            Self::Validation { .. } => None,
        }
    }
}

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

    #[test]
    fn parse_complete_flow() {
        let yaml = r#"
name: order_processing
version: "2.0"
description: Process orders with fraud detection

triggers:
  - id: api_webhook
    type: webhook
    params:
      port: 8080
      path: /orders

nodes:
  fraud_check:
    type: std::switch
    config:
      condition:
        type: greater_than
        field: risk_score
        value: 0.8

  process_order:
    type: std::log
    config:
      message: "Processing order"

  flag_fraud:
    type: std::log
    config:
      message: "Fraud detected"

edges:
  - from: api_webhook
    to: fraud_check
  - from: fraud_check.false
    to: process_order
  - from: fraud_check.true
    to: flag_fraud

settings:
  max_concurrent_executions: 50
  execution_timeout_ms: 30000
"#;

        let flow = FlowDefinition::from_yaml(yaml).unwrap();

        assert_eq!(flow.name, "order_processing");
        assert_eq!(flow.version, Some("2.0".to_string()));
        assert_eq!(
            flow.description,
            Some("Process orders with fraud detection".to_string())
        );

        assert_eq!(flow.triggers.len(), 1);
        assert_eq!(flow.triggers[0].id, "api_webhook");

        assert_eq!(flow.nodes.len(), 3);
        assert!(flow.has_node("fraud_check"));
        assert!(flow.has_node("process_order"));
        assert!(flow.has_node("flag_fraud"));

        assert_eq!(flow.edges.len(), 3);

        assert_eq!(flow.settings.max_concurrent_executions, 50);
        assert_eq!(flow.settings.execution_timeout_ms, 30000);
    }

    #[test]
    fn parse_minimal_flow() {
        let yaml = r#"
name: simple
"#;
        let flow = FlowDefinition::from_yaml(yaml).unwrap();
        assert_eq!(flow.name, "simple");
        assert!(flow.triggers.is_empty());
        assert!(flow.nodes.is_empty());
        assert!(flow.edges.is_empty());
    }

    #[test]
    fn flow_builder() {
        let flow = FlowDefinition::new("test_flow")
            .with_version("1.0.0")
            .with_description("A test flow")
            .with_trigger(TriggerDefinition::new("webhook", "webhook"))
            .with_node("log", NodeDefinition::new("std::log"))
            .with_edge(EdgeDefinition::new("webhook", "log"));

        assert_eq!(flow.name, "test_flow");
        assert_eq!(flow.triggers.len(), 1);
        assert_eq!(flow.nodes.len(), 1);
        assert_eq!(flow.edges.len(), 1);
    }

    #[test]
    fn validate_and_parse() {
        let yaml = r#"
name: validated_flow
triggers:
  - id: webhook
    type: webhook
nodes:
  log:
    type: std::log
edges:
  - from: webhook
    to: log
"#;

        let result = FlowDefinition::from_yaml_validated(yaml);
        assert!(result.is_ok());
    }

    #[test]
    fn validation_errors() {
        let yaml = r#"
name: ""
triggers:
  - id: test
    type: invalid_trigger_type
"#;

        let result = FlowDefinition::from_yaml_validated(yaml);
        assert!(result.is_err());

        if let Err(FlowLoadError::Validation { errors }) = result {
            assert!(!errors.is_empty());
        } else {
            panic!("Expected validation error");
        }
    }

    #[test]
    fn to_yaml_roundtrip() {
        let flow = FlowDefinition::new("roundtrip_test")
            .with_trigger(TriggerDefinition::new("webhook", "webhook"))
            .with_node("log", NodeDefinition::new("std::log"));

        let yaml = flow.to_yaml().unwrap();
        let parsed = FlowDefinition::from_yaml(&yaml).unwrap();

        assert_eq!(parsed.name, "roundtrip_test");
        assert_eq!(parsed.triggers.len(), 1);
        assert_eq!(parsed.nodes.len(), 1);
    }

    #[test]
    fn query_methods() {
        let flow = FlowDefinition::new("query_test")
            .with_trigger(TriggerDefinition::new("t1", "webhook"))
            .with_node("n1", NodeDefinition::new("std::log"))
            .with_node("n2", NodeDefinition::new("std::switch"))
            .with_edge(EdgeDefinition::new("t1", "n1"))
            .with_edge(EdgeDefinition::new("n1", "n2"));

        assert!(flow.has_trigger("t1"));
        assert!(!flow.has_trigger("nonexistent"));

        assert!(flow.has_node("n1"));
        assert!(!flow.has_node("nonexistent"));

        let edges_from_t1: Vec<_> = flow.edges_from("t1").collect();
        assert_eq!(edges_from_t1.len(), 1);

        let edges_to_n2: Vec<_> = flow.edges_to("n2").collect();
        assert_eq!(edges_to_n2.len(), 1);
    }
}