fiddler 4.9.1

Data Stream processor written in rust
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
//! FiddlerScript processor for inline message manipulation.
//!
//! This processor uses the FiddlerScript scripting language to transform messages.

use crate::config::register_plugin;
use crate::config::ItemType;
use crate::config::{ConfigSpec, ExecutionType};
use crate::Message;
use crate::MessageBatch;
use crate::{Closer, Error, Processor};
use async_trait::async_trait;
use fiddler_macros::fiddler_registration_func;
use fiddler_script::{Interpreter, Value};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_yaml::Value as YamlValue;
use std::collections::HashMap;

/// Configuration for the FiddlerScript processor.
#[derive(Clone, Deserialize, Serialize)]
pub struct FiddlerScriptSpec {
    /// The FiddlerScript code to execute
    code: String,
}

/// FiddlerScript processor implementation.
pub struct FiddlerScriptProcessor {
    /// The script code to execute
    code: String,
}

impl FiddlerScriptProcessor {
    /// Convert metadata from serde_yaml::Value to fiddler_script::Value
    fn convert_metadata(metadata: &HashMap<String, serde_yaml::Value>) -> IndexMap<String, Value> {
        metadata
            .iter()
            .map(|(k, v)| (k.clone(), Self::yaml_to_script_value(v)))
            .collect()
    }

    /// Convert a serde_yaml::Value to a fiddler_script::Value
    fn yaml_to_script_value(yaml: &serde_yaml::Value) -> Value {
        match yaml {
            serde_yaml::Value::Null => Value::Null,
            serde_yaml::Value::Bool(b) => Value::Boolean(*b),
            serde_yaml::Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    Value::Integer(i)
                } else if let Some(f) = n.as_f64() {
                    Value::Float(f)
                } else {
                    Value::Null
                }
            }
            serde_yaml::Value::String(s) => Value::String(s.clone()),
            serde_yaml::Value::Sequence(seq) => {
                Value::Array(seq.iter().map(Self::yaml_to_script_value).collect())
            }
            serde_yaml::Value::Mapping(map) => {
                let dict: IndexMap<String, Value> = map
                    .iter()
                    .filter_map(|(k, v)| {
                        k.as_str()
                            .map(|key| (key.to_string(), Self::yaml_to_script_value(v)))
                    })
                    .collect();
                Value::Dictionary(dict)
            }
            serde_yaml::Value::Tagged(tagged) => Self::yaml_to_script_value(&tagged.value),
        }
    }

    /// Convert a fiddler_script::Value back to serde_yaml::Value for metadata
    #[allow(dead_code)]
    fn script_to_yaml_value(value: &Value) -> serde_yaml::Value {
        match value {
            Value::Null => serde_yaml::Value::Null,
            Value::Boolean(b) => serde_yaml::Value::Bool(*b),
            Value::Integer(n) => serde_yaml::Value::Number((*n).into()),
            Value::Float(f) => serde_yaml::Value::Number(serde_yaml::Number::from(*f)),
            Value::String(s) => serde_yaml::Value::String(s.clone()),
            Value::Bytes(b) => {
                // Convert bytes to string if valid UTF-8, otherwise base64
                match String::from_utf8(b.clone()) {
                    Ok(s) => serde_yaml::Value::String(s),
                    Err(_) => serde_yaml::Value::String(base64::Engine::encode(
                        &base64::engine::general_purpose::STANDARD,
                        b,
                    )),
                }
            }
            Value::Array(arr) => {
                serde_yaml::Value::Sequence(arr.iter().map(Self::script_to_yaml_value).collect())
            }
            Value::Dictionary(dict) => {
                let mapping: serde_yaml::Mapping = dict
                    .iter()
                    .map(|(k, v)| {
                        (
                            serde_yaml::Value::String(k.clone()),
                            Self::script_to_yaml_value(v),
                        )
                    })
                    .collect();
                serde_yaml::Value::Mapping(mapping)
            }
        }
    }

    /// Extract bytes from a Value
    fn value_to_bytes(value: &Value) -> Vec<u8> {
        value.to_bytes()
    }

    /// Create a message from a Value and original metadata
    fn create_message(
        value: &Value,
        original_metadata: &HashMap<String, serde_yaml::Value>,
    ) -> Message {
        Message {
            bytes: Self::value_to_bytes(value),
            metadata: original_metadata.clone(),
            ..Default::default()
        }
    }
}

#[async_trait]
impl Processor for FiddlerScriptProcessor {
    async fn process(&self, message: Message) -> Result<MessageBatch, Error> {
        // Create a new interpreter for each message (clean state)
        let mut interpreter = Interpreter::new_without_env();

        // Set 'this' to the message bytes
        interpreter.set_variable_bytes("this", message.bytes.clone());

        // Convert metadata to a dictionary and set as 'metadata'
        let metadata_dict = Self::convert_metadata(&message.metadata);
        interpreter.set_variable_dict("metadata", metadata_dict);

        // Run the script
        interpreter
            .run(&self.code)
            .map_err(|e| Error::ProcessingError(format!("FiddlerScript error: {}", e)))?;

        // Get the result from 'this'
        let result = interpreter.get_value("this").ok_or_else(|| {
            Error::ProcessingError("'this' variable not found after script execution".to_string())
        })?;

        // Check if result is an array (multiple messages), null (filtered), or single value
        match &result {
            // Null explicitly filters the message - return empty batch
            Value::Null => Ok(vec![]),
            // Empty array explicitly filters the message - return empty batch
            Value::Array(arr) if arr.is_empty() => Ok(vec![]),
            // Non-empty array - multiple messages
            Value::Array(arr) => {
                let messages: Vec<Message> = arr
                    .iter()
                    .map(|v| Self::create_message(v, &message.metadata))
                    .collect();
                Ok(messages)
            }
            // Single message
            _ => Ok(vec![Self::create_message(&result, &message.metadata)]),
        }
    }
}

impl Closer for FiddlerScriptProcessor {}

#[fiddler_registration_func]
fn create_fiddlerscript(conf: YamlValue) -> Result<ExecutionType, Error> {
    let c: FiddlerScriptSpec = serde_yaml::from_value(conf)?;
    fiddler_script::check(&c.code)
        .map_err(|e| Error::ConfigFailedValidation(format!("FiddlerScript syntax error: {e}")))?;
    Ok(ExecutionType::Processor(Box::new(FiddlerScriptProcessor {
        code: c.code,
    })))
}

pub(super) fn register_fiddlerscript() -> Result<(), Error> {
    let config = r#"type: object
properties:
  code:
    type: string
required:
  - code"#;
    let conf_spec = ConfigSpec::from_schema(config)?;

    register_plugin(
        "fiddlerscript".into(),
        ItemType::Processor,
        conf_spec,
        create_fiddlerscript,
    )
}

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

    #[test]
    fn register_plugin() {
        register_fiddlerscript().unwrap()
    }

    #[tokio::test]
    async fn test_simple_passthrough() {
        let processor = FiddlerScriptProcessor {
            code: "// passthrough".to_string(),
        };

        let message = Message {
            bytes: b"hello world".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].bytes, b"hello world");
    }

    #[tokio::test]
    async fn test_modify_message() {
        let processor = FiddlerScriptProcessor {
            code: r#"
                let text = bytes_to_string(this);
                this = bytes(text + " modified");
            "#
            .to_string(),
        };

        let message = Message {
            bytes: b"hello".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].bytes, b"hello modified");
    }

    #[tokio::test]
    async fn test_multiple_messages() {
        let processor = FiddlerScriptProcessor {
            code: r#"
                this = array(bytes("one"), bytes("two"), bytes("three"));
            "#
            .to_string(),
        };

        let message = Message {
            bytes: b"original".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].bytes, b"one");
        assert_eq!(result[1].bytes, b"two");
        assert_eq!(result[2].bytes, b"three");
    }

    #[tokio::test]
    async fn test_access_metadata() {
        let processor = FiddlerScriptProcessor {
            code: r#"
                let source = get(metadata, "source");
                this = bytes(source);
            "#
            .to_string(),
        };

        let mut metadata = HashMap::new();
        metadata.insert(
            "source".to_string(),
            serde_yaml::Value::String("test-input".to_string()),
        );

        let message = Message {
            bytes: b"original".to_vec(),
            metadata,
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].bytes, b"test-input");
    }

    #[tokio::test]
    async fn test_json_parsing() {
        let processor = FiddlerScriptProcessor {
            code: r#"
                let data = parse_json(this);
                let name = get(data, "name");
                this = bytes(name);
            "#
            .to_string(),
        };

        let message = Message {
            bytes: br#"{"name": "Alice", "age": 30}"#.to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].bytes, b"Alice");
    }

    #[tokio::test]
    async fn test_split_lines() {
        let processor = FiddlerScriptProcessor {
            code: r#"
                let text = bytes_to_string(this);
                let lines = array();
                let current = "";
                for (let i = 0; i < len(text); i = i + 1) {
                    let char = get(text, i);
                    if (char == "\n") {
                        if (len(current) > 0) {
                            lines = push(lines, bytes(current));
                        }
                        current = "";
                    } else {
                        current = current + char;
                    }
                }
                if (len(current) > 0) {
                    lines = push(lines, bytes(current));
                }
                this = lines;
            "#
            .to_string(),
        };

        let message = Message {
            bytes: b"line1\nline2\nline3".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 3);
    }

    #[tokio::test]
    async fn test_float_metadata() {
        let processor = FiddlerScriptProcessor {
            code: r#"
                let price = get(metadata, "price");
                let tax = price * 0.1;
                this = bytes(str(tax));
            "#
            .to_string(),
        };

        let mut metadata = HashMap::new();
        metadata.insert(
            "price".to_string(),
            serde_yaml::Value::Number(serde_yaml::Number::from(99.99)),
        );

        let message = Message {
            bytes: b"original".to_vec(),
            metadata,
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 1);
        // 99.99 * 0.1 = 9.999
        let result_str = String::from_utf8(result[0].bytes.clone()).unwrap();
        assert!(result_str.starts_with("9.999"));
    }

    #[tokio::test]
    async fn test_float_arithmetic() {
        let processor = FiddlerScriptProcessor {
            code: r#"
                let a = 3.14;
                let b = 2.0;
                let result = a * b;
                this = bytes(str(result));
            "#
            .to_string(),
        };

        let message = Message {
            bytes: b"original".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 1);
        let result_str = String::from_utf8(result[0].bytes.clone()).unwrap();
        assert!(result_str.starts_with("6.28"));
    }

    #[tokio::test]
    async fn test_float_math_functions() {
        let processor = FiddlerScriptProcessor {
            code: r#"
                let x = 3.7;
                let c = ceil(x);
                let f = floor(x);
                let r = round(x);
                this = bytes(str(c) + "," + str(f) + "," + str(r));
            "#
            .to_string(),
        };

        let message = Message {
            bytes: b"original".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].bytes, b"4,3,4");
    }

    #[tokio::test]
    async fn test_filter_with_null() {
        // Setting this to null filters the message
        let processor = FiddlerScriptProcessor {
            code: r#"
                this = null;
            "#
            .to_string(),
        };

        let message = Message {
            bytes: b"should be filtered".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(
            result.len(),
            0,
            "null should result in empty batch (filtered)"
        );
    }

    #[tokio::test]
    async fn test_filter_with_empty_array() {
        // Setting this to empty array filters the message
        let processor = FiddlerScriptProcessor {
            code: r#"
                this = array();
            "#
            .to_string(),
        };

        let message = Message {
            bytes: b"should be filtered".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(
            result.len(),
            0,
            "empty array should result in empty batch (filtered)"
        );
    }

    #[tokio::test]
    async fn test_conditional_filter() {
        // Filter messages based on content using null
        let processor = FiddlerScriptProcessor {
            code: r#"
                let text = bytes_to_string(this);
                if (text == "drop") {
                    this = null;
                }
            "#
            .to_string(),
        };

        // Message that should be filtered
        let message = Message {
            bytes: b"drop".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 0, "message 'drop' should be filtered");

        // Message that should pass through
        let message = Message {
            bytes: b"keep".to_vec(),
            ..Default::default()
        };

        let result = processor.process(message).await.unwrap();
        assert_eq!(result.len(), 1, "message 'keep' should pass through");
        assert_eq!(result[0].bytes, b"keep");
    }
}