pipeflow 0.0.4

A lightweight, configuration-driven data pipeline framework
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
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
//! Compute step for mathematical expression evaluation
//!
//! Evaluates expressions using field values from the message payload.
//! The result is stored in a specified output field.
//!
//! # Expression Syntax
//!
//! Expressions support:
//! - Basic arithmetic: `+`, `-`, `*`, `/`
//! - Parentheses for grouping: `(a + b) * c`
//! - Field references via JSONPath: `$.price`, `$.data.value`
//! - Literal numbers: `100`, `3.14`
//!
//! # Example
//!
//! ```yaml
//! - type: compute
//!   config:
//!     expression: "$.eth_price / $.btc_price"
//!     output: "$.eth_btc_ratio"
//! ```

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::common::message::Message;
use crate::error::{Error, Result};
use crate::transform::json_path::CompiledPath;
use crate::transform::step::Step;

/// Compute step configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComputeStepConfig {
    /// Mathematical expression to evaluate
    /// Supports: +, -, *, /, parentheses, JSONPath references ($.field), numbers
    pub expression: String,
    /// JSONPath output location for the result
    pub output: String,
    /// Optional: round result to specified decimal places
    #[serde(default)]
    pub precision: Option<u32>,
}

/// Token types for expression parsing
#[derive(Debug, Clone, PartialEq)]
enum Token {
    Number(f64),
    JsonPath(String),
    Plus,
    Minus,
    Multiply,
    Divide,
    LParen,
    RParen,
}

/// Compiled expression node for evaluation
#[derive(Debug, Clone)]
enum ExprNode {
    /// Literal number
    Number(f64),
    /// JSONPath reference (compiled)
    Field(CompiledPath),
    /// Binary operation
    BinaryOp {
        left: Box<ExprNode>,
        op: BinaryOp,
        right: Box<ExprNode>,
    },
    /// Unary negation
    Negate(Box<ExprNode>),
}

#[derive(Debug, Clone, Copy)]
enum BinaryOp {
    Add,
    Subtract,
    Multiply,
    Divide,
}

/// Tokenize expression string into tokens
fn tokenize(expr: &str) -> Result<Vec<Token>> {
    let mut tokens = Vec::new();
    let mut chars = expr.chars().peekable();

    while let Some(&ch) = chars.peek() {
        match ch {
            ' ' | '\t' | '\n' | '\r' => {
                chars.next();
            }
            '+' => {
                tokens.push(Token::Plus);
                chars.next();
            }
            '-' => {
                tokens.push(Token::Minus);
                chars.next();
            }
            '*' => {
                tokens.push(Token::Multiply);
                chars.next();
            }
            '/' => {
                tokens.push(Token::Divide);
                chars.next();
            }
            '(' => {
                tokens.push(Token::LParen);
                chars.next();
            }
            ')' => {
                tokens.push(Token::RParen);
                chars.next();
            }
            '$' => {
                // JSONPath reference
                let mut path = String::new();
                while let Some(&c) = chars.peek() {
                    if c.is_alphanumeric()
                        || c == '$'
                        || c == '.'
                        || c == '_'
                        || c == '['
                        || c == ']'
                        || c == '\''
                        || c == '"'
                        || c == ':'
                        || c == '-'
                    {
                        path.push(c);
                        chars.next();
                    } else {
                        break;
                    }
                }
                if path.is_empty() {
                    return Err(Error::config("Empty JSONPath reference in expression"));
                }
                tokens.push(Token::JsonPath(path));
            }
            '0'..='9' | '.' => {
                // Number literal
                let mut num_str = String::new();
                let mut has_dot = false;
                while let Some(&c) = chars.peek() {
                    if c.is_ascii_digit() {
                        num_str.push(c);
                        chars.next();
                    } else if c == '.' && !has_dot {
                        has_dot = true;
                        num_str.push(c);
                        chars.next();
                    } else {
                        break;
                    }
                }
                let num: f64 = num_str.parse().map_err(|_| {
                    Error::config(format!("Invalid number in expression: {}", num_str))
                })?;
                tokens.push(Token::Number(num));
            }
            _ => {
                return Err(Error::config(format!(
                    "Unexpected character in expression: '{}'",
                    ch
                )));
            }
        }
    }

    Ok(tokens)
}

/// Recursive descent parser for expressions
struct ExprParser {
    tokens: Vec<Token>,
    pos: usize,
}

impl ExprParser {
    fn new(tokens: Vec<Token>) -> Self {
        Self { tokens, pos: 0 }
    }

    fn peek(&self) -> Option<&Token> {
        self.tokens.get(self.pos)
    }

    fn advance(&mut self) -> Option<&Token> {
        let token = self.tokens.get(self.pos);
        if token.is_some() {
            self.pos += 1;
        }
        token
    }

    /// Parse expression: handles + and - (lowest precedence)
    fn parse_expr(&mut self) -> Result<ExprNode> {
        let mut left = self.parse_term()?;

        loop {
            match self.peek() {
                Some(Token::Plus) => {
                    self.advance();
                    let right = self.parse_term()?;
                    left = ExprNode::BinaryOp {
                        left: Box::new(left),
                        op: BinaryOp::Add,
                        right: Box::new(right),
                    };
                }
                Some(Token::Minus) => {
                    self.advance();
                    let right = self.parse_term()?;
                    left = ExprNode::BinaryOp {
                        left: Box::new(left),
                        op: BinaryOp::Subtract,
                        right: Box::new(right),
                    };
                }
                _ => break,
            }
        }

        Ok(left)
    }

    /// Parse term: handles * and / (higher precedence)
    fn parse_term(&mut self) -> Result<ExprNode> {
        let mut left = self.parse_unary()?;

        loop {
            match self.peek() {
                Some(Token::Multiply) => {
                    self.advance();
                    let right = self.parse_unary()?;
                    left = ExprNode::BinaryOp {
                        left: Box::new(left),
                        op: BinaryOp::Multiply,
                        right: Box::new(right),
                    };
                }
                Some(Token::Divide) => {
                    self.advance();
                    let right = self.parse_unary()?;
                    left = ExprNode::BinaryOp {
                        left: Box::new(left),
                        op: BinaryOp::Divide,
                        right: Box::new(right),
                    };
                }
                _ => break,
            }
        }

        Ok(left)
    }

    /// Parse unary: handles unary minus
    fn parse_unary(&mut self) -> Result<ExprNode> {
        if let Some(Token::Minus) = self.peek() {
            self.advance();
            let operand = self.parse_unary()?;
            return Ok(ExprNode::Negate(Box::new(operand)));
        }
        self.parse_primary()
    }

    /// Parse primary: numbers, JSONPath references, parenthesized expressions
    fn parse_primary(&mut self) -> Result<ExprNode> {
        match self.advance() {
            Some(Token::Number(n)) => Ok(ExprNode::Number(*n)),
            Some(Token::JsonPath(path)) => {
                let compiled = CompiledPath::compile(path)?;
                Ok(ExprNode::Field(compiled))
            }
            Some(Token::LParen) => {
                let expr = self.parse_expr()?;
                match self.advance() {
                    Some(Token::RParen) => Ok(expr),
                    _ => Err(Error::config("Missing closing parenthesis in expression")),
                }
            }
            Some(token) => Err(Error::config(format!(
                "Unexpected token in expression: {:?}",
                token
            ))),
            None => Err(Error::config("Unexpected end of expression")),
        }
    }
}

impl ExprNode {
    /// Evaluate the expression against a payload
    fn evaluate(&self, payload: &Value) -> Result<f64> {
        match self {
            ExprNode::Number(n) => Ok(*n),
            ExprNode::Field(path) => {
                let value = path
                    .extract(payload)
                    .ok_or_else(|| Error::transform(format!("Field not found: {}", path)))?;
                match value {
                    Value::Number(n) => n.as_f64().ok_or_else(|| {
                        Error::transform(format!("Field {} is not a valid number", path))
                    }),
                    Value::String(s) => s.parse::<f64>().map_err(|_| {
                        Error::transform(format!(
                            "Field {} cannot be parsed as number: {}",
                            path, s
                        ))
                    }),
                    _ => Err(Error::transform(format!(
                        "Field {} is not a number: {:?}",
                        path, value
                    ))),
                }
            }
            ExprNode::BinaryOp { left, op, right } => {
                let l = left.evaluate(payload)?;
                let r = right.evaluate(payload)?;
                match op {
                    BinaryOp::Add => Ok(l + r),
                    BinaryOp::Subtract => Ok(l - r),
                    BinaryOp::Multiply => Ok(l * r),
                    BinaryOp::Divide => {
                        if r == 0.0 {
                            Err(Error::transform("Division by zero"))
                        } else {
                            Ok(l / r)
                        }
                    }
                }
            }
            ExprNode::Negate(operand) => Ok(-operand.evaluate(payload)?),
        }
    }
}

/// Compute step that evaluates mathematical expressions
pub struct ComputeStep {
    /// Compiled expression tree
    expr: ExprNode,
    /// Compiled output path
    output: CompiledPath,
    /// Optional precision for rounding
    precision: Option<u32>,
}

impl ComputeStep {
    /// Create a new compute step from configuration
    pub fn new(config: ComputeStepConfig) -> Result<Self> {
        // Tokenize and parse expression
        let tokens = tokenize(&config.expression)?;
        if tokens.is_empty() {
            return Err(Error::config("Empty expression"));
        }

        let mut parser = ExprParser::new(tokens);
        let expr = parser.parse_expr()?;

        // Check for unconsumed tokens
        if parser.peek().is_some() {
            return Err(Error::config(format!(
                "Unexpected tokens after expression: {:?}",
                parser.peek()
            )));
        }

        // Compile output path
        let output = CompiledPath::compile(&config.output)?;

        Ok(Self {
            expr,
            output,
            precision: config.precision,
        })
    }
}

impl Step for ComputeStep {
    fn step_type(&self) -> &'static str {
        "compute"
    }

    fn process(&self, mut msg: Message) -> Result<Option<Message>> {
        let result = self.expr.evaluate(&msg.payload)?;

        // Apply precision if specified
        let result = if let Some(precision) = self.precision {
            let factor = 10_f64.powi(precision as i32);
            (result * factor).round() / factor
        } else {
            result
        };

        // Store result in output path
        let value = serde_json::Number::from_f64(result)
            .map(Value::Number)
            .unwrap_or(Value::Null);

        self.output.set(&mut msg.payload, value);

        tracing::debug!(
            output = %self.output,
            result = result,
            "Compute step evaluated expression"
        );

        Ok(Some(msg))
    }
}

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

    fn make_msg(payload: Value) -> Message {
        Message::new("test", payload)
    }

    #[test]
    fn test_compute_simple_division() {
        let config = ComputeStepConfig {
            expression: "$.eth / $.btc".into(),
            output: "$.ratio".into(),
            precision: Some(6),
        };
        let step = ComputeStep::new(config).unwrap();

        let msg = make_msg(json!({
            "eth": 3000.0,
            "btc": 100000.0
        }));
        let result = step.process(msg).unwrap().unwrap();

        assert_eq!(result.payload["ratio"], 0.03);
    }

    #[test]
    fn test_compute_nested_fields() {
        let config = ComputeStepConfig {
            expression: "$.data.a + $.data.b".into(),
            output: "$.sum".into(),
            precision: None,
        };
        let step = ComputeStep::new(config).unwrap();

        let msg = make_msg(json!({
            "data": {"a": 10, "b": 20}
        }));
        let result = step.process(msg).unwrap().unwrap();

        assert_eq!(result.payload["sum"], 30.0);
    }

    #[test]
    fn test_compute_complex_expression() {
        let config = ComputeStepConfig {
            expression: "($.a + $.b) * $.c".into(),
            output: "$.result".into(),
            precision: None,
        };
        let step = ComputeStep::new(config).unwrap();

        let msg = make_msg(json!({"a": 2, "b": 3, "c": 4}));
        let result = step.process(msg).unwrap().unwrap();

        assert_eq!(result.payload["result"], 20.0);
    }

    #[test]
    fn test_compute_with_literals() {
        let config = ComputeStepConfig {
            expression: "$.value * 100".into(),
            output: "$.percentage".into(),
            precision: None,
        };
        let step = ComputeStep::new(config).unwrap();

        let msg = make_msg(json!({"value": 0.5}));
        let result = step.process(msg).unwrap().unwrap();

        assert_eq!(result.payload["percentage"], 50.0);
    }

    #[test]
    fn test_compute_unary_minus() {
        let config = ComputeStepConfig {
            expression: "-$.value".into(),
            output: "$.negated".into(),
            precision: None,
        };
        let step = ComputeStep::new(config).unwrap();

        let msg = make_msg(json!({"value": 42}));
        let result = step.process(msg).unwrap().unwrap();

        assert_eq!(result.payload["negated"], -42.0);
    }

    #[test]
    fn test_compute_precision() {
        let config = ComputeStepConfig {
            expression: "1 / 3".into(),
            output: "$.result".into(),
            precision: Some(4),
        };
        let step = ComputeStep::new(config).unwrap();

        let msg = make_msg(json!({}));
        let result = step.process(msg).unwrap().unwrap();

        assert_eq!(result.payload["result"], 0.3333);
    }

    #[test]
    fn test_compute_division_by_zero() {
        let config = ComputeStepConfig {
            expression: "$.a / $.b".into(),
            output: "$.result".into(),
            precision: None,
        };
        let step = ComputeStep::new(config).unwrap();

        let msg = make_msg(json!({"a": 10, "b": 0}));
        let result = step.process(msg);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Division by zero"));
    }

    #[test]
    fn test_compute_missing_field() {
        let config = ComputeStepConfig {
            expression: "$.a + $.missing".into(),
            output: "$.result".into(),
            precision: None,
        };
        let step = ComputeStep::new(config).unwrap();

        let msg = make_msg(json!({"a": 10}));
        let result = step.process(msg);

        assert!(result.is_err());
    }

    #[test]
    fn test_compute_string_to_number() {
        let config = ComputeStepConfig {
            expression: "$.price * 2".into(),
            output: "$.double".into(),
            precision: None,
        };
        let step = ComputeStep::new(config).unwrap();

        let msg = make_msg(json!({"price": "50"}));
        let result = step.process(msg).unwrap().unwrap();

        assert_eq!(result.payload["double"], 100.0);
    }

    #[test]
    fn test_tokenize() {
        let tokens = tokenize("$.a + $.b * 2").unwrap();
        assert_eq!(tokens.len(), 5);
        assert!(matches!(tokens[0], Token::JsonPath(_)));
        assert!(matches!(tokens[1], Token::Plus));
        assert!(matches!(tokens[2], Token::JsonPath(_)));
        assert!(matches!(tokens[3], Token::Multiply));
        assert!(matches!(tokens[4], Token::Number(2.0)));
    }

    #[test]
    fn test_tokenize_jsonpath_with_quoted_brackets() {
        let expr = "$['crypto:price:ETH'].price_usd / $['crypto:price:BTC'].price_usd";
        let tokens = tokenize(expr).unwrap();
        assert_eq!(tokens.len(), 3);
        assert!(matches!(tokens[0], Token::JsonPath(_)));
        assert!(matches!(tokens[1], Token::Divide));
        assert!(matches!(tokens[2], Token::JsonPath(_)));
    }

    #[test]
    fn test_invalid_expression() {
        let config = ComputeStepConfig {
            expression: "$.a +".into(),
            output: "$.result".into(),
            precision: None,
        };
        let result = ComputeStep::new(config);
        assert!(result.is_err());
    }
}