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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//! E2E tests for Transform Pipeline
//!
//! These tests verify multi-step transform pipeline behavior:
//! - Filter step: passes/rejects messages based on conditions
//! - Remap step: transforms message payload field structure
//! - Multi-step: filter + remap chained together
//! - Multi-condition filter: AND/OR logic
//!
//! Each test uses a mock HTTP server and temp file to verify transformations.

#![cfg(all(feature = "http-client", feature = "file"))]

use std::time::Duration;

use wiremock::matchers::{method, path};
use wiremock::{Mock, ResponseTemplate};

mod common;

// =============================================================================
// Filter Step Tests
// =============================================================================

/// Scenario: Filter Passes Matching Messages
///
/// Verifies that messages matching the filter condition are passed through.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_filter_step_passes_matching() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "value": 42
        })))
        .expect(1..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "200ms"
  transforms:
    - id: filter
      inputs: [source]
      outputs: [sink]
      steps:
        - type: filter
          config:
            field: "$.status"
            operator: eq
            value: "success"
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for content
    let content = common::wait_for_file_content(&output_path, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok(), "Engine should shutdown gracefully");

    let lines: Vec<&str> = content.lines().collect();

    assert!(!lines.is_empty(), "File should contain at least one line");

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).expect("Invalid JSON");
    assert_eq!(parsed["payload"]["status"], "success");
    assert_eq!(parsed["payload"]["value"], 42);
}

/// Scenario: Filter Rejects Non-Matching Messages
///
/// Verifies that messages not matching the filter condition are dropped.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_filter_step_rejects_non_matching() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "error",
            "message": "Something went wrong"
        })))
        .expect(2..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "200ms"
  transforms:
    - id: filter
      inputs: [source]
      outputs: [sink]
      steps:
        - type: filter
          config:
            field: "$.status"
            operator: eq
            value: "success"
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for requests to be sure processing happened
    common::wait_for_requests(&harness.mock_server, 2, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let content = std::fs::read_to_string(&output_path).unwrap_or_default();
    assert!(
        content.is_empty(),
        "File should be empty when all messages are filtered out"
    );
}

// =============================================================================
// Remap Step Tests
// =============================================================================

/// Scenario: Remap Step Transforms Fields
///
/// Verifies that remap step correctly transforms field structure.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_remap_step_transforms_fields() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "id": 123,
            "name": "test item",
            "nested": {
                "value": 456
            }
        })))
        .expect(1..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "200ms"
  transforms:
    - id: remap
      inputs: [source]
      outputs: [sink]
      steps:
        - type: remap
          config:
            mappings:
              - from: "$.id"
                to: "$.item_id"
              - from: "$.name"
                to: "$.item_name"
              - from: "$.nested.value"
                to: "$.flat_value"
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for content
    let content = common::wait_for_file_content(&output_path, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let lines: Vec<&str> = content.lines().collect();

    assert!(!lines.is_empty(), "File should contain remapped messages");

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    assert_eq!(parsed["payload"]["item_id"], 123);
    assert_eq!(parsed["payload"]["item_name"], "test item");
    assert_eq!(parsed["payload"]["flat_value"], 456);
    // Original fields should not exist when keep_unmapped is false (default)
    assert!(parsed["payload"]["id"].is_null());
    assert!(parsed["payload"]["name"].is_null());
}

// =============================================================================
// Multi-Step Pipeline Tests
// =============================================================================

/// Scenario: Filter Then Remap Multi-Step Pipeline
///
/// Verifies that filter + remap steps work correctly when chained together.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_multi_step_filter_then_remap() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "userId": 1,
            "id": 101,
            "title": "Hello World"
        })))
        .expect(1..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "200ms"
  transforms:
    - id: pipeline
      inputs: [source]
      outputs: [sink]
      steps:
        - type: filter
          config:
            field: "$.userId"
            operator: eq
            value: 1
        - type: remap
          config:
            mappings:
              - from: "$.id"
                to: "$.post_id"
              - from: "$.title"
                to: "$.post_title"
              - from: "$.userId"
                to: "$.author_id"
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for content
    let content = common::wait_for_file_content(&output_path, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let lines: Vec<&str> = content.lines().collect();

    assert!(
        !lines.is_empty(),
        "File should contain transformed messages"
    );

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    // Fields should be remapped
    assert_eq!(parsed["payload"]["post_id"], 101);
    assert_eq!(parsed["payload"]["post_title"], "Hello World");
    assert_eq!(parsed["payload"]["author_id"], 1);
}

// =============================================================================
// Multi-Condition Filter Tests
// =============================================================================

/// Scenario: Filter with Multiple Conditions (AND Mode)
///
/// Verifies that all conditions must match when using AND mode.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_filter_multi_conditions_and() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    // Message that matches BOTH conditions
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "active",
            "priority": 5
        })))
        .expect(1..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "200ms"
  transforms:
    - id: filter
      inputs: [source]
      outputs: [sink]
      steps:
        - type: filter
          config:
            mode: and
            conditions:
              - field: "$.status"
                operator: eq
                value: "active"
              - field: "$.priority"
                operator: ge
                value: 3
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for content
    let content = common::wait_for_file_content(&output_path, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let lines: Vec<&str> = content.lines().collect();

    assert!(
        !lines.is_empty(),
        "Message matching all AND conditions should pass"
    );

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    assert_eq!(parsed["payload"]["status"], "active");
    assert_eq!(parsed["payload"]["priority"], 5);
}

/// Scenario: Filter with Multiple Conditions (OR Mode)
///
/// Verifies that at least one condition must match when using OR mode.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_filter_multi_conditions_or() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    // Message that matches only ONE condition (priority >= 10, but status != "critical")
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "normal",
            "priority": 15
        })))
        .expect(1..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "200ms"
  transforms:
    - id: filter
      inputs: [source]
      outputs: [sink]
      steps:
        - type: filter
          config:
            mode: or
            conditions:
              - field: "$.status"
                operator: eq
                value: "critical"
              - field: "$.priority"
                operator: ge
                value: 10
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for content
    let content = common::wait_for_file_content(&output_path, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let lines: Vec<&str> = content.lines().collect();

    assert!(
        !lines.is_empty(),
        "Message matching at least one OR condition should pass"
    );

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    assert_eq!(parsed["payload"]["status"], "normal"); // This doesn't match, but...
    assert_eq!(parsed["payload"]["priority"], 15); // ...this matches >= 10
}

// =============================================================================
// Advanced Filter Operator Tests
// =============================================================================

/// Scenario: Filter with Absolute Value Operator (abs_gt)
///
/// Verifies that abs_gt operator compares absolute values correctly.
/// Useful for detecting significant changes regardless of direction.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_filter_abs_gt_operator() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    // Message with negative change that should pass abs_gt filter (|-5| > 3)
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "symbol": "BTC",
            "price_change": -5.5
        })))
        .expect(1..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "200ms"
  transforms:
    - id: filter
      inputs: [source]
      outputs: [sink]
      steps:
        - type: filter
          config:
            field: "$.price_change"
            operator: abs_gt
            value: 3
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for content
    let content = common::wait_for_file_content(&output_path, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let lines: Vec<&str> = content.lines().collect();

    assert!(
        !lines.is_empty(),
        "Message with |price_change| > 3 should pass filter"
    );

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    assert_eq!(parsed["payload"]["symbol"], "BTC");
    assert_eq!(parsed["payload"]["price_change"], -5.5);
}

/// Scenario: Filter with Regex Match Operator
///
/// Verifies that matches operator correctly applies regex patterns.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_filter_matches_regex_operator() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    // Message with email that should match regex pattern
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "user": "john_doe",
            "email": "john@example.com"
        })))
        .expect(1..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "200ms"
  transforms:
    - id: filter
      inputs: [source]
      outputs: [sink]
      steps:
        - type: filter
          config:
            field: "$.email"
            operator: matches
            value: "^[a-z]+@example\\.com$"
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for content
    let content = common::wait_for_file_content(&output_path, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let lines: Vec<&str> = content.lines().collect();

    assert!(
        !lines.is_empty(),
        "Message with email matching regex should pass filter"
    );

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    assert_eq!(parsed["payload"]["user"], "john_doe");
    assert_eq!(parsed["payload"]["email"], "john@example.com");
}

// =============================================================================
// Window Step Tests
// =============================================================================

/// Scenario: Window Count Trigger with Merge
///
/// Verifies that window step buffers messages and emits merged output
/// when count trigger is reached.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_window_count_trigger_merge() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    // Mock server returns sequential values
    let counter = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(1));
    let counter_clone = counter.clone();

    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(move |_: &wiremock::Request| {
            let n = counter_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "seq": n,
                "value": format!("item_{}", n)
            }))
        })
        .expect(3..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "100ms"
  transforms:
    - id: window
      inputs: [source]
      outputs: [sink]
      steps:
        - type: window
          config:
            size: 3
            operation: merge
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for content (window emits after 3 messages)
    let content = common::wait_for_file_content(&output_path, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let lines: Vec<&str> = content.lines().collect();
    assert!(!lines.is_empty(), "Window should emit merged message");

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    // Merged payload should have last value wins for overlapping keys
    assert!(parsed["payload"]["seq"].is_number());
    assert!(parsed["payload"]["value"].is_string());
}

/// Scenario: Window Select One (First)
///
/// Verifies that window step with select_one operation returns the first message.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_window_select_first() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    let counter = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(1));
    let counter_clone = counter.clone();

    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(move |_: &wiremock::Request| {
            let n = counter_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "seq": n
            }))
        })
        .expect(3..)
        .mount(&harness.mock_server)
        .await;

    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "100ms"
  transforms:
    - id: window
      inputs: [source]
      outputs: [sink]
      steps:
        - type: window
          config:
            size: 3
            operation: select_one
            strategy: first
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    let content = common::wait_for_file_content(&output_path, Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let lines: Vec<&str> = content.lines().collect();
    assert!(!lines.is_empty(), "Window should emit first message");

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    // First message should have seq=1
    assert_eq!(parsed["payload"]["seq"], 1);
}

/// Scenario: Window Time Trigger
///
/// Verifies that window step emits messages after the configured duration
/// even if the count threshold is not reached.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_window_time_trigger() {
    if common::skip_if_no_network() {
        return;
    }

    let harness = common::TestHarness::new().await;
    let output_path = harness.output_path("output.jsonl");

    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "value": "timer_test"
        })))
        .expect(1..)
        .mount(&harness.mock_server)
        .await;

    // Source emits every 100ms, window triggers after 800ms or 100 messages (whichever first).
    // With 100ms interval, we should get ~8 messages before time trigger fires.
    let yaml = format!(
        r#"
pipeline:
  sources:
    - id: source
      type: http_client
      config:
        url: "{}"
        interval: "100ms"
  transforms:
    - id: window
      inputs: [source]
      outputs: [sink]
      steps:
        - type: window
          config:
            size: 100
            duration: "800ms"
            operation: merge
  sinks:
    - id: sink
      type: file
      config:
        path: "{}"
"#,
        harness.mock_server.uri(),
        output_path.display()
    );

    let (shutdown_tx, engine_handle) = harness.run_pipeline(&yaml).await;

    // Wait for window to emit via time trigger (should happen before 100 messages)
    let content =
        common::wait_for_file_content(&output_path, std::time::Duration::from_secs(5)).await;

    let _ = shutdown_tx.send(());
    let result = engine_handle.await.expect("Engine task panicked");
    assert!(result.is_ok());

    let lines: Vec<&str> = content.lines().collect();
    assert!(!lines.is_empty(), "Window should emit via time trigger");

    let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    assert_eq!(parsed["payload"]["value"], "timer_test");
}