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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! Shared value resolution and field mapping for transforms and sinks
//!
//! Provides unified value sources (static, variables, JSONPath, templates)
//! and field mapping types for use in sink column mappings and transform remap steps.

use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::env;
use std::sync::OnceLock;

use crate::common::message::Message;
use crate::error::{Error, Result};

use super::json_path::CompiledPath;

/// Built-in variables available in mappings
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuiltinVar {
    /// Current timestamp (ISO 8601 format with second precision)
    Now,
    /// Current date (YYYY-MM-DD format)
    Date,
    /// UUIDv7 (time-ordered)
    Uuid,
    /// Unix timestamp (milliseconds since epoch)
    Timestamp,
    /// Source node ID from message metadata
    SourceId,
    /// Message ID from metadata
    MsgId,
}

impl BuiltinVar {
    /// Parse a variable string (e.g., "$NOW") into a BuiltinVar
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "$NOW" => Some(Self::Now),
            "$DATE" => Some(Self::Date),
            "$UUID" => Some(Self::Uuid),
            "$TIMESTAMP" => Some(Self::Timestamp),
            "$SOURCE_ID" => Some(Self::SourceId),
            "$MSG_ID" => Some(Self::MsgId),
            _ => None,
        }
    }

    /// Evaluate the variable to produce a JSON value
    pub fn evaluate(&self, msg: &Message) -> Value {
        match self {
            // Format with seconds precision only (no fractional seconds)
            Self::Now => Value::String(
                chrono::Utc::now()
                    .format("%Y-%m-%dT%H:%M:%S%:z")
                    .to_string(),
            ),
            Self::Date => Value::String(chrono::Utc::now().format("%Y-%m-%d").to_string()),
            Self::Uuid => Value::String(uuid::Uuid::now_v7().to_string()),
            Self::Timestamp => Value::Number(chrono::Utc::now().timestamp_millis().into()),
            Self::SourceId => Value::String(msg.meta.source_node.clone()),
            Self::MsgId => Value::String(msg.meta.id.to_string()),
        }
    }
}

/// Message metadata field accessor
///
/// Provides access to message metadata fields via `$META.field` syntax.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetaField {
    /// Message ID (UUID string)
    Id,
    /// Unix timestamp in milliseconds
    Timestamp,
    /// Source node ID
    SourceNode,
    /// Correlation ID (UUID string, null if unset)
    CorrelationId,
    /// Chain depth counter
    ChainDepth,
    /// Tag value from tags map
    Tag(String),
}

impl MetaField {
    /// Parse a metadata path (e.g., "source_node", "tags.my_key") into a MetaField
    ///
    /// The input should be the path after `$META.` prefix.
    pub fn parse(path: &str) -> Option<Self> {
        match path {
            "id" => Some(Self::Id),
            "timestamp" => Some(Self::Timestamp),
            "source_node" => Some(Self::SourceNode),
            "correlation_id" => Some(Self::CorrelationId),
            "chain_depth" => Some(Self::ChainDepth),
            s if s.starts_with("tags.") => {
                let key = s.strip_prefix("tags.")?;
                if key.is_empty() {
                    None
                } else {
                    Some(Self::Tag(key.to_string()))
                }
            }
            _ => None,
        }
    }

    /// Evaluate the metadata field to produce a JSON value
    pub fn evaluate(&self, msg: &Message) -> Value {
        match self {
            Self::Id => Value::String(msg.meta.id.to_string()),
            Self::Timestamp => Value::Number(msg.meta.timestamp.into()),
            Self::SourceNode => Value::String(msg.meta.source_node.clone()),
            Self::CorrelationId => msg
                .meta
                .correlation_id
                .map(|id| Value::String(id.to_string()))
                .unwrap_or(Value::Null),
            Self::ChainDepth => Value::Number(msg.meta.chain_depth.into()),
            Self::Tag(key) => msg
                .meta
                .tags
                .get(key)
                .map(|v| Value::String(v.clone()))
                .unwrap_or(Value::Null),
        }
    }

    /// Returns true if this field may be missing (returns null)
    pub fn is_optional(&self) -> bool {
        matches!(self, Self::CorrelationId | Self::Tag(_))
    }
}

/// Part of a template string
#[derive(Debug, Clone)]
pub enum TemplatePart {
    /// Literal text
    Literal(String),
    /// JSONPath extraction from payload
    Path(CompiledPath),
    /// Built-in variable ($NOW, $UUID, etc.)
    Variable(BuiltinVar),
    /// Environment variable (resolved at compile time)
    EnvVar(Value),
    /// Message metadata field ($META.field)
    MetaField(MetaField),
}

/// Source for a mapped value
#[derive(Debug, Clone)]
pub enum ValueSource {
    /// Static JSON value
    Static(Value),
    /// Built-in variable ($NOW, $UUID, etc.)
    Variable(BuiltinVar),
    /// JSONPath extraction from payload
    JsonPath(CompiledPath),
    /// Template with interpolation
    Template(Vec<TemplatePart>),
    /// Environment variable (resolved at compile time)
    /// Stores the resolved value directly for efficiency.
    EnvVar {
        /// Original variable name (for debugging/display)
        name: String,
        /// Pre-resolved value
        value: Value,
    },
    /// Message metadata field ($META.field)
    MetaField(MetaField),
}

impl ValueSource {
    /// Returns true if null values from this source should be skipped in mappings.
    ///
    /// JSONPath and Template sources return null when the field is missing,
    /// which typically means "skip this mapping" rather than "set to null".
    /// MetaField returns null for optional fields (correlation_id, tags).
    pub fn should_skip_null(&self) -> bool {
        match self {
            Self::JsonPath(_) | Self::Template(_) => true,
            Self::MetaField(field) => field.is_optional(),
            _ => false,
        }
    }

    /// Compile a value source from `from` and `value` config fields
    ///
    /// Logic:
    /// - If `value` is present: check for variable syntax, else use as static
    /// - If `from` is present:
    ///   - `$ENV:VAR` or `$ENV:VAR:-default` → EnvVar (resolved at compile time)
    ///   - `$META.field` → MetaField
    ///   - `$NOW`, `$UUID`, etc. → Variable
    ///   - `$.path` → JSONPath
    ///   - Contains `{{` → Template
    ///   - Else → Static string
    pub fn compile(from: Option<&str>, value: Option<&Value>) -> Result<Self> {
        if from.is_none() && value.is_none() {
            return Err(Error::config("Must specify either 'from' or 'value'"));
        }

        if let Some(val) = value {
            // Check for built-in variable in string value
            if let Some(var_str) = val.as_str()
                && let Some(var) = BuiltinVar::parse(var_str)
            {
                return Ok(Self::Variable(var));
            }
            return Ok(Self::Static(val.clone()));
        }

        let from_str = from.unwrap().trim();

        // Check for simple variable (e.g., "$UUID" without template syntax)
        if let Some(var) = BuiltinVar::parse(from_str) {
            return Ok(Self::Variable(var));
        }

        // Check for environment variable: "$ENV:VAR" or "$ENV:VAR:-default"
        if from_str.starts_with("$ENV:") {
            let (name, value) = Self::parse_env_var(from_str)?;
            return Ok(Self::EnvVar { name, value });
        }

        // Check for metadata field: "$META.field"
        if from_str.starts_with("$META.") {
            let path = from_str.strip_prefix("$META.").unwrap();
            let field = MetaField::parse(path).ok_or_else(|| {
                Error::config(format!(
                    "Invalid metadata field: '{}'. Valid fields: id, timestamp, source_node, \
                     correlation_id, chain_depth, tags.<key>",
                    path
                ))
            })?;
            return Ok(Self::MetaField(field));
        }

        // Check for JSONPath (starts with $ but not a known prefix and no template)
        if from_str.starts_with('$') && !from_str.contains("{{") {
            return Ok(Self::JsonPath(CompiledPath::compile(from_str)?));
        }

        // Check for template
        if from_str.contains("{{") {
            return Ok(Self::Template(Self::compile_template(from_str)?));
        }

        // Plain static string
        Ok(Self::Static(Value::String(from_str.to_string())))
    }

    /// Parse environment variable syntax: "$ENV:VAR" or "$ENV:VAR:-default"
    ///
    /// Returns (var_name, resolved_value).
    fn parse_env_var(s: &str) -> Result<(String, Value)> {
        let rest = s.strip_prefix("$ENV:").unwrap();

        // Check for default value syntax: VAR:-default
        let (var_name, default) = if let Some(idx) = rest.find(":-") {
            let name = &rest[..idx];
            let default = &rest[idx + 2..];
            (name, Some(default))
        } else {
            (rest, None)
        };

        if var_name.is_empty() {
            return Err(Error::config(
                "Environment variable name cannot be empty (e.g., '$ENV:MY_VAR')",
            ));
        }

        // Resolve environment variable at compile time
        match env::var(var_name) {
            Ok(val) => Ok((var_name.to_string(), Value::String(val))),
            Err(_) => {
                if let Some(default_val) = default {
                    Ok((var_name.to_string(), Value::String(default_val.to_string())))
                } else {
                    Err(Error::config(format!(
                        "Environment variable '{}' is not set and no default provided. \
                         Use '$ENV:{}:-default' syntax to provide a default value.",
                        var_name, var_name
                    )))
                }
            }
        }
    }

    /// Compile a template string into parts
    fn compile_template(template: &str) -> Result<Vec<TemplatePart>> {
        static TEMPLATE_RE: OnceLock<Regex> = OnceLock::new();
        let re = TEMPLATE_RE
            .get_or_init(|| Regex::new(r"\{\{\s*(.*?)\s*\}\}").expect("template regex is valid"));

        let mut parts = Vec::new();
        let mut last_end = 0;

        for cap in re.captures_iter(template) {
            // SAFETY: Regex guarantees capture groups exist:
            // - Group 0 is always the full match
            // - Group 1 is the inner content from (.*?)
            let full_match = cap.get(0).unwrap();
            let inner = cap.get(1).unwrap().as_str().trim();

            // Add literal before match
            if full_match.start() > last_end {
                parts.push(TemplatePart::Literal(
                    template[last_end..full_match.start()].to_string(),
                ));
            }

            // Parse the inner expression
            let part = Self::compile_template_part(inner)?;
            parts.push(part);

            last_end = full_match.end();
        }

        // Add remaining literal
        if last_end < template.len() {
            parts.push(TemplatePart::Literal(template[last_end..].to_string()));
        }

        Ok(parts)
    }

    /// Compile a single template expression (inside {{ }})
    fn compile_template_part(inner: &str) -> Result<TemplatePart> {
        // Check for built-in variable ($NOW, $UUID, etc.)
        if let Some(var) = BuiltinVar::parse(inner) {
            return Ok(TemplatePart::Variable(var));
        }

        // Check for environment variable ($ENV:VAR or $ENV:VAR:-default)
        if inner.starts_with("$ENV:") {
            let (_, value) = Self::parse_env_var(inner)?;
            return Ok(TemplatePart::EnvVar(value));
        }

        // Check for metadata field ($META.field)
        if inner.starts_with("$META.") {
            let path = inner.strip_prefix("$META.").unwrap();
            let field = MetaField::parse(path).ok_or_else(|| {
                Error::config(format!(
                    "Invalid metadata field in template: '{}'. Valid fields: id, timestamp, \
                     source_node, correlation_id, chain_depth, tags.<key>",
                    path
                ))
            })?;
            return Ok(TemplatePart::MetaField(field));
        }

        // Default: JSONPath expression
        Ok(TemplatePart::Path(CompiledPath::compile(inner)?))
    }

    /// Resolve the value source to a concrete JSON value
    pub fn resolve(&self, msg: &Message) -> Value {
        match self {
            Self::Static(val) => val.clone(),
            Self::Variable(var) => var.evaluate(msg),
            Self::JsonPath(path) => path.extract(&msg.payload).cloned().unwrap_or(Value::Null),
            Self::EnvVar { value, .. } => value.clone(),
            Self::MetaField(field) => field.evaluate(msg),
            Self::Template(parts) => {
                let mut result = String::new();
                let mut all_found = true;

                for part in parts {
                    match part {
                        TemplatePart::Literal(s) => result.push_str(s),
                        TemplatePart::Variable(var) => {
                            append_value_as_string(&mut result, &var.evaluate(msg));
                        }
                        TemplatePart::EnvVar(val) => {
                            append_value_as_string(&mut result, val);
                        }
                        TemplatePart::MetaField(field) => {
                            let val = field.evaluate(msg);
                            if val.is_null() && field.is_optional() {
                                all_found = false;
                            } else {
                                append_value_as_string(&mut result, &val);
                            }
                        }
                        TemplatePart::Path(path) => {
                            if let Some(val) = path.extract(&msg.payload) {
                                append_value_as_string(&mut result, val);
                            } else {
                                all_found = false;
                            }
                        }
                    }
                }

                if all_found {
                    Value::String(result)
                } else {
                    Value::Null
                }
            }
        }
    }

    /// Resolve the value source to a string, using a fallback if null or missing.
    ///
    /// This is a convenience method for sinks that need string output with defaults.
    pub fn resolve_to_string(&self, msg: &Message, fallback: impl FnOnce() -> String) -> String {
        let value = self.resolve(msg);
        if value.is_null() && self.should_skip_null() {
            return fallback();
        }
        match value {
            Value::String(s) => s,
            other => other.to_string(),
        }
    }

    /// Compile an optional template string into an optional ValueSource.
    ///
    /// This is a convenience method for sinks that have optional template fields.
    pub fn compile_optional(template: Option<&str>) -> Result<Option<Self>> {
        match template {
            Some(t) => Self::compile(Some(t), None).map(Some),
            None => Ok(None),
        }
    }
}

/// Append a JSON value to a string buffer, using the raw string for String values.
fn append_value_as_string(buf: &mut String, val: &Value) {
    if let Some(s) = val.as_str() {
        buf.push_str(s);
    } else {
        buf.push_str(&val.to_string());
    }
}

// ============================================================================
// Shared Field Mapping Types
// ============================================================================

/// Field mapping definition for transforms and sinks
///
/// Specifies how to extract or generate a value and where to place it.
/// Used by remap transforms.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldMapping {
    /// Source field path (JSONPath-like, e.g., `$.data.user_id`)
    /// OR template string (e.g. "Value: {{ $.data.value }}")
    /// OR built-in variable (e.g., "$UUID")
    /// One of `from` or `value` must be specified.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// Static value or built-in variable to inject
    /// Examples: "warning", 123, true, "$UUID", "$NOW"
    /// One of `from` or `value` must be specified.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value: Option<Value>,
    /// Target field path (e.g., `$.user_id`)
    pub to: String,
}

/// Pre-compiled field mapping for efficient runtime execution
pub struct CompiledMapping {
    /// Source for the value (using shared ValueSource)
    pub source: ValueSource,
    /// Pre-compiled target path
    pub to: CompiledPath,
}

impl FieldMapping {
    /// Compile this mapping into an efficient runtime representation
    pub fn compile(&self) -> Result<CompiledMapping> {
        let source = ValueSource::compile(self.from.as_deref(), self.value.as_ref())?;
        let to = CompiledPath::compile(&self.to)?;
        Ok(CompiledMapping { source, to })
    }
}

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

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

    #[test]
    fn test_builtin_var_parse() {
        assert_eq!(BuiltinVar::parse("$NOW"), Some(BuiltinVar::Now));
        assert_eq!(BuiltinVar::parse("$DATE"), Some(BuiltinVar::Date));
        assert_eq!(BuiltinVar::parse("$UUID"), Some(BuiltinVar::Uuid));
        assert_eq!(BuiltinVar::parse("$TIMESTAMP"), Some(BuiltinVar::Timestamp));
        assert_eq!(BuiltinVar::parse("$SOURCE_ID"), Some(BuiltinVar::SourceId));
        assert_eq!(BuiltinVar::parse("$MSG_ID"), Some(BuiltinVar::MsgId));
        assert_eq!(BuiltinVar::parse("$UNKNOWN"), None);
        assert_eq!(BuiltinVar::parse("NOW"), None);
    }

    #[test]
    fn test_builtin_var_evaluate() {
        let msg = make_msg(json!({}));

        let now = BuiltinVar::Now.evaluate(&msg);
        assert!(now.as_str().unwrap().contains("T")); // ISO 8601

        let date = BuiltinVar::Date.evaluate(&msg);
        let date_str = date.as_str().unwrap();
        assert_eq!(date_str.len(), 10); // YYYY-MM-DD format
        assert!(date_str.contains("-"));

        let uuid = BuiltinVar::Uuid.evaluate(&msg);
        assert_eq!(uuid.as_str().unwrap().len(), 36); // UUID format

        let ts = BuiltinVar::Timestamp.evaluate(&msg);
        assert!(ts.as_i64().unwrap() > 0);

        let source = BuiltinVar::SourceId.evaluate(&msg);
        assert_eq!(source.as_str().unwrap(), "test_source");
    }

    #[test]
    fn test_value_source_static() {
        let source = ValueSource::compile(None, Some(&json!("hello"))).unwrap();
        let msg = make_msg(json!({}));
        assert_eq!(source.resolve(&msg), json!("hello"));
    }

    #[test]
    fn test_value_source_variable() {
        let source = ValueSource::compile(None, Some(&json!("$UUID"))).unwrap();
        let msg = make_msg(json!({}));
        let result = source.resolve(&msg);
        assert_eq!(result.as_str().unwrap().len(), 36);
    }

    #[test]
    fn test_value_source_jsonpath() {
        let source = ValueSource::compile(Some("$.user.name"), None).unwrap();
        let msg = make_msg(json!({"user": {"name": "Alice"}}));
        assert_eq!(source.resolve(&msg), json!("Alice"));
    }

    #[test]
    fn test_value_source_template() {
        let source = ValueSource::compile(Some("Hello {{ $.name }}!"), None).unwrap();
        let msg = make_msg(json!({"name": "World"}));
        assert_eq!(source.resolve(&msg), json!("Hello World!"));
    }

    #[test]
    fn test_value_source_template_with_variable() {
        let source = ValueSource::compile(Some("ID: {{ $UUID }}"), None).unwrap();
        let msg = make_msg(json!({}));
        let result = source.resolve(&msg);
        assert!(result.as_str().unwrap().starts_with("ID: "));
        assert!(result.as_str().unwrap().len() >= 40); // "ID: " + 36 char UUID
    }

    #[test]
    fn test_value_source_from_variable() {
        // Variable specified in `from` field directly
        let source = ValueSource::compile(Some("$NOW"), None).unwrap();
        let msg = make_msg(json!({}));
        let result = source.resolve(&msg);
        assert!(result.as_str().unwrap().contains("T"));
    }

    // ========== MetaField Tests ==========

    #[test]
    fn test_meta_field_parse() {
        assert_eq!(MetaField::parse("id"), Some(MetaField::Id));
        assert_eq!(MetaField::parse("timestamp"), Some(MetaField::Timestamp));
        assert_eq!(MetaField::parse("source_node"), Some(MetaField::SourceNode));
        assert_eq!(
            MetaField::parse("correlation_id"),
            Some(MetaField::CorrelationId)
        );
        assert_eq!(MetaField::parse("chain_depth"), Some(MetaField::ChainDepth));
        assert_eq!(
            MetaField::parse("tags.my_key"),
            Some(MetaField::Tag("my_key".to_string()))
        );

        // Invalid fields
        assert_eq!(MetaField::parse("invalid"), None);
        assert_eq!(MetaField::parse("tags."), None);
        assert_eq!(MetaField::parse("tags"), None);
    }

    #[test]
    fn test_meta_field_evaluate() {
        let msg = make_msg(json!({})).with_tag("my_tag", "tag_value");

        // Test all meta fields
        let id = MetaField::Id.evaluate(&msg);
        assert_eq!(id.as_str().unwrap().len(), 36); // UUID format

        let ts = MetaField::Timestamp.evaluate(&msg);
        assert!(ts.as_i64().unwrap() > 0);

        let source = MetaField::SourceNode.evaluate(&msg);
        assert_eq!(source.as_str().unwrap(), "test_source");

        let corr = MetaField::CorrelationId.evaluate(&msg);
        assert_eq!(corr, Value::Null); // Not set

        let depth = MetaField::ChainDepth.evaluate(&msg);
        assert_eq!(depth, json!(0));

        let tag = MetaField::Tag("my_tag".to_string()).evaluate(&msg);
        assert_eq!(tag, json!("tag_value"));

        let missing_tag = MetaField::Tag("missing".to_string()).evaluate(&msg);
        assert_eq!(missing_tag, Value::Null);
    }

    #[test]
    fn test_value_source_meta_field() {
        // Test $META.source_node
        let source = ValueSource::compile(Some("$META.source_node"), None).unwrap();
        let msg = make_msg(json!({}));
        assert_eq!(source.resolve(&msg), json!("test_source"));

        // Test $META.tags.key (replaces $TAG:key)
        let source = ValueSource::compile(Some("$META.tags.my_tag"), None).unwrap();
        let msg = make_msg(json!({})).with_tag("my_tag", "tag_value");
        assert_eq!(source.resolve(&msg), json!("tag_value"));

        // Test missing tag
        let msg_missing = make_msg(json!({}));
        assert_eq!(source.resolve(&msg_missing), Value::Null);
    }

    #[test]
    fn test_meta_field_in_template() {
        let source = ValueSource::compile(Some("Source: {{ $META.source_node }}"), None).unwrap();
        let msg = make_msg(json!({}));
        assert_eq!(source.resolve(&msg), json!("Source: test_source"));
    }

    // ========== EnvVar Tests ==========

    #[test]
    fn test_env_var_with_default() {
        // Use a non-existent env var with default
        let source =
            ValueSource::compile(Some("$ENV:PIPEFLOW_TEST_MISSING:-default_val"), None).unwrap();
        let msg = make_msg(json!({}));
        assert_eq!(source.resolve(&msg), json!("default_val"));
    }

    #[test]
    fn test_env_var_existing() {
        // Test with PATH which is always set on Unix/Windows
        let source = ValueSource::compile(Some("$ENV:PATH"), None).unwrap();
        let msg = make_msg(json!({}));
        let result = source.resolve(&msg);
        // PATH should be a non-empty string
        assert!(!result.as_str().unwrap().is_empty());
    }

    #[test]
    fn test_env_var_missing_no_default() {
        // Should fail if env var is missing and no default
        let result = ValueSource::compile(Some("$ENV:PIPEFLOW_DEFINITELY_NOT_SET_12345"), None);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("PIPEFLOW_DEFINITELY_NOT_SET_12345"));
    }

    #[test]
    fn test_env_var_in_template() {
        let source =
            ValueSource::compile(Some("Env: {{ $ENV:PIPEFLOW_TEST_TPL:-fallback }}"), None)
                .unwrap();
        let msg = make_msg(json!({}));
        assert_eq!(source.resolve(&msg), json!("Env: fallback"));
    }

    // ========== should_skip_null Tests ==========

    #[test]
    fn test_should_skip_null() {
        // Static and Variable never skip
        let static_src = ValueSource::compile(None, Some(&json!("hello"))).unwrap();
        assert!(!static_src.should_skip_null());

        let var_src = ValueSource::compile(Some("$UUID"), None).unwrap();
        assert!(!var_src.should_skip_null());

        // EnvVar never skips (resolved at compile time)
        let env_src = ValueSource::compile(Some("$ENV:TEST_SKIP:-default"), None).unwrap();
        assert!(!env_src.should_skip_null());

        // JsonPath and Template always skip
        let path_src = ValueSource::compile(Some("$.missing"), None).unwrap();
        assert!(path_src.should_skip_null());

        let tpl_src = ValueSource::compile(Some("Hello {{ $.name }}"), None).unwrap();
        assert!(tpl_src.should_skip_null());

        // MetaField: only optional fields skip
        let meta_source_node = ValueSource::compile(Some("$META.source_node"), None).unwrap();
        assert!(!meta_source_node.should_skip_null());

        let meta_corr = ValueSource::compile(Some("$META.correlation_id"), None).unwrap();
        assert!(meta_corr.should_skip_null()); // Optional

        let meta_tag = ValueSource::compile(Some("$META.tags.key"), None).unwrap();
        assert!(meta_tag.should_skip_null()); // Optional
    }
}