streamling-e2e 0.1.0

End-to-end tests for streamling
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
//! External handler e2e tests.
//!
//! These tests verify that the handler transform correctly sends data to an external
//! HTTP endpoint and processes the response.
//!
//! Ported from crates/streamling/tests/external_handlers.rs

use serde::Serialize;
use streamling_e2e::resources::ExternalHandlerResource;
use streamling_e2e::{init_tracing, PipelineOpts, TestContext};

// ============================================================================
// Test Record Types
// ============================================================================

/// Simple test record matching the slim test message format
#[derive(Debug, Clone, Serialize)]
struct SlimTestRecord {
    id: String,
    data: String,
}

const SLIM_SCHEMA: &str = r#"{
    "type": "record",
    "name": "SlimTestRecord",
    "fields": [
        {"name": "id", "type": "string"},
        {"name": "data", "type": "string"}
    ]
}"#;

// ============================================================================
// External Handler Tests
// ============================================================================

/// Test external handler with single row per request and envelope version 0.
///
/// This test verifies that when `one_row_per_request: true` and `payload_version: 0`,
/// the handler receives one HTTP request per row with flat JSON format.
///
/// Ported from: test_external_handlers_single_row_envelope_zero
#[tokio::test]
async fn test_external_handler_single_row_envelope_zero() {
    init_tracing();

    let ctx = TestContext::new()
        .await
        .expect("Failed to create test context");

    // Start external handler server
    let handler = ExternalHandlerResource::new()
        .await
        .expect("Failed to start handler server");

    // Register schema
    ctx.kafka
        .register_schema(SLIM_SCHEMA)
        .await
        .expect("Failed to register schema");

    // Create test records
    let records: Vec<SlimTestRecord> = vec![
        SlimTestRecord {
            id: "1".to_string(),
            data: "alpha".to_string(),
        },
        SlimTestRecord {
            id: "2".to_string(),
            data: "beta".to_string(),
        },
        SlimTestRecord {
            id: "3".to_string(),
            data: "gamma".to_string(),
        },
    ];

    ctx.kafka
        .produce_avro_records(&records)
        .await
        .expect("Failed to produce records");

    // Pipeline with handler transform - single row, envelope v0
    let pipeline = format!(
        r#"
sources:
  kafka_source:
    type: kafka
    topic: {topic}
    primary_key: id

transforms:
  handler_transform:
    type: handler
    from: kafka_source
    url: {handler_url}
    one_row_per_request: true
    payload_version: 0
    primary_key: id

sinks:
  print_sink:
    type: print
    from: handler_transform
    sample_every: 1
"#,
        topic = ctx.kafka_topic,
        handler_url = handler.slim_handler_url()
    );

    let output = ctx
        .run_pipeline_with_capture(&pipeline, PipelineOpts::new().record_limit(3))
        .await
        .expect("Pipeline execution failed");

    // Verify that we got 3 records with updated data
    assert_eq!(output.rows().len(), 3, "Expected 3 output rows");

    // Verify the handler was called once per row (single row mode)
    assert_eq!(
        handler.request_count(),
        3,
        "Handler should receive 3 requests (one per row)"
    );

    // Verify the data was updated by the handler
    let data_values: Vec<&str> = output
        .rows()
        .iter()
        .filter_map(|r| r.data.get("data").and_then(|v| v.as_str()))
        .collect();

    assert!(
        data_values.iter().all(|d| d.starts_with("updated-")),
        "All data values should be prefixed with 'updated-': {:?}",
        data_values
    );
}

/// Test external handler with single row per request and envelope version 1.
///
/// This test verifies that when `one_row_per_request: true` and `payload_version: 1`,
/// the handler receives one HTTP request per row with envelope wrapper.
///
/// Ported from: test_external_handlers_single_row_envelope_one
#[tokio::test]
async fn test_external_handler_single_row_envelope_one() {
    init_tracing();

    let ctx = TestContext::new()
        .await
        .expect("Failed to create test context");

    // Start external handler server
    let handler = ExternalHandlerResource::new()
        .await
        .expect("Failed to start handler server");

    // Register schema
    ctx.kafka
        .register_schema(SLIM_SCHEMA)
        .await
        .expect("Failed to register schema");

    // Create test records
    let records: Vec<SlimTestRecord> = vec![
        SlimTestRecord {
            id: "1".to_string(),
            data: "alpha".to_string(),
        },
        SlimTestRecord {
            id: "2".to_string(),
            data: "beta".to_string(),
        },
        SlimTestRecord {
            id: "3".to_string(),
            data: "gamma".to_string(),
        },
    ];

    ctx.kafka
        .produce_avro_records(&records)
        .await
        .expect("Failed to produce records");

    // Pipeline with handler transform - single row, envelope v1
    let pipeline = format!(
        r#"
sources:
  kafka_source:
    type: kafka
    topic: {topic}
    primary_key: id

transforms:
  handler_transform:
    type: handler
    from: kafka_source
    url: {handler_url}
    one_row_per_request: true
    payload_version: 1
    primary_key: id

sinks:
  print_sink:
    type: print
    from: handler_transform
    sample_every: 1
"#,
        topic = ctx.kafka_topic,
        handler_url = handler.slim_handler_envelope_url()
    );

    let output = ctx
        .run_pipeline_with_capture(&pipeline, PipelineOpts::new().record_limit(3))
        .await
        .expect("Pipeline execution failed");

    // Verify that we got 3 records with updated data
    assert_eq!(output.rows().len(), 3, "Expected 3 output rows");

    // Verify the handler was called once per row (single row mode)
    assert_eq!(
        handler.request_count(),
        3,
        "Handler should receive 3 requests (one per row)"
    );

    // Verify the data was updated by the handler
    let data_values: Vec<&str> = output
        .rows()
        .iter()
        .filter_map(|r| r.data.get("data").and_then(|v| v.as_str()))
        .collect();

    assert!(
        data_values.iter().all(|d| d.starts_with("updated-")),
        "All data values should be prefixed with 'updated-': {:?}",
        data_values
    );
}

/// Test external handler with batch requests and envelope version 0.
///
/// This test verifies that when `one_row_per_request: false` and `payload_version: 0`,
/// the handler receives batched records in a single HTTP request.
///
/// Ported from: test_external_handlers_batch_envelope_zero
#[tokio::test]
async fn test_external_handler_batch_envelope_zero() {
    init_tracing();

    let ctx = TestContext::new()
        .await
        .expect("Failed to create test context");

    // Start external handler server
    let handler = ExternalHandlerResource::new()
        .await
        .expect("Failed to start handler server");

    // Register schema
    ctx.kafka
        .register_schema(SLIM_SCHEMA)
        .await
        .expect("Failed to register schema");

    // Create test records
    let records: Vec<SlimTestRecord> = vec![
        SlimTestRecord {
            id: "1".to_string(),
            data: "alpha".to_string(),
        },
        SlimTestRecord {
            id: "2".to_string(),
            data: "beta".to_string(),
        },
        SlimTestRecord {
            id: "3".to_string(),
            data: "gamma".to_string(),
        },
    ];

    ctx.kafka
        .produce_avro_records(&records)
        .await
        .expect("Failed to produce records");

    // Pipeline with handler transform - batch mode, envelope v0
    let pipeline = format!(
        r#"
sources:
  kafka_source:
    type: kafka
    topic: {topic}
    primary_key: id

transforms:
  handler_transform:
    type: handler
    from: kafka_source
    url: {handler_url}
    one_row_per_request: false
    payload_version: 0
    primary_key: id

sinks:
  print_sink:
    type: print
    from: handler_transform
    sample_every: 1
"#,
        topic = ctx.kafka_topic,
        handler_url = handler.slim_batch_handler_url()
    );

    let output = ctx
        .run_pipeline_with_capture(&pipeline, PipelineOpts::new().record_limit(3))
        .await
        .expect("Pipeline execution failed");

    // Verify that we got 3 records with updated data
    assert_eq!(output.rows().len(), 3, "Expected 3 output rows");

    // In batch mode, handler should receive fewer requests (ideally 1 for all rows)
    assert!(
        handler.request_count() <= 3,
        "Handler should receive at most 3 requests in batch mode"
    );

    // Verify the data was updated by the handler
    let data_values: Vec<&str> = output
        .rows()
        .iter()
        .filter_map(|r| r.data.get("data").and_then(|v| v.as_str()))
        .collect();

    assert!(
        data_values.iter().all(|d| d.starts_with("updated-")),
        "All data values should be prefixed with 'updated-': {:?}",
        data_values
    );
}

/// Test external handler with batch requests and envelope version 1.
///
/// This test verifies that when `one_row_per_request: false` and `payload_version: 1`,
/// the handler receives batched records with envelope wrapper.
///
/// Ported from: test_external_handlers_batch_envelope_one
#[tokio::test]
async fn test_external_handler_batch_envelope_one() {
    init_tracing();

    let ctx = TestContext::new()
        .await
        .expect("Failed to create test context");

    // Start external handler server
    let handler = ExternalHandlerResource::new()
        .await
        .expect("Failed to start handler server");

    // Register schema
    ctx.kafka
        .register_schema(SLIM_SCHEMA)
        .await
        .expect("Failed to register schema");

    // Create test records
    let records: Vec<SlimTestRecord> = vec![
        SlimTestRecord {
            id: "1".to_string(),
            data: "alpha".to_string(),
        },
        SlimTestRecord {
            id: "2".to_string(),
            data: "beta".to_string(),
        },
        SlimTestRecord {
            id: "3".to_string(),
            data: "gamma".to_string(),
        },
    ];

    ctx.kafka
        .produce_avro_records(&records)
        .await
        .expect("Failed to produce records");

    // Pipeline with handler transform - batch mode, envelope v1
    let pipeline = format!(
        r#"
sources:
  kafka_source:
    type: kafka
    topic: {topic}
    primary_key: id

transforms:
  handler_transform:
    type: handler
    from: kafka_source
    url: {handler_url}
    one_row_per_request: false
    payload_version: 1
    primary_key: id

sinks:
  print_sink:
    type: print
    from: handler_transform
    sample_every: 1
"#,
        topic = ctx.kafka_topic,
        handler_url = handler.slim_batch_handler_envelope_url()
    );

    let output = ctx
        .run_pipeline_with_capture(&pipeline, PipelineOpts::new().record_limit(3))
        .await
        .expect("Pipeline execution failed");

    // Verify that we got 3 records with updated data
    assert_eq!(output.rows().len(), 3, "Expected 3 output rows");

    // In batch mode, handler should receive fewer requests (ideally 1 for all rows)
    assert!(
        handler.request_count() <= 3,
        "Handler should receive at most 3 requests in batch mode"
    );

    // Verify the data was updated by the handler
    let data_values: Vec<&str> = output
        .rows()
        .iter()
        .filter_map(|r| r.data.get("data").and_then(|v| v.as_str()))
        .collect();

    assert!(
        data_values.iter().all(|d| d.starts_with("updated-")),
        "All data values should be prefixed with 'updated-': {:?}",
        data_values
    );
}

/// Test external handler request capture.
///
/// This test verifies that the handler correctly captures incoming requests
/// that can be inspected for verification.
#[tokio::test]
async fn test_external_handler_request_capture() {
    init_tracing();

    let ctx = TestContext::new()
        .await
        .expect("Failed to create test context");

    // Start external handler server
    let handler = ExternalHandlerResource::new()
        .await
        .expect("Failed to start handler server");

    // Register schema
    ctx.kafka
        .register_schema(SLIM_SCHEMA)
        .await
        .expect("Failed to register schema");

    // Create test records
    let records: Vec<SlimTestRecord> = vec![SlimTestRecord {
        id: "1".to_string(),
        data: "test_data".to_string(),
    }];

    ctx.kafka
        .produce_avro_records(&records)
        .await
        .expect("Failed to produce records");

    // Pipeline with passthrough handler
    let pipeline = format!(
        r#"
sources:
  kafka_source:
    type: kafka
    topic: {topic}
    primary_key: id

transforms:
  handler_transform:
    type: handler
    from: kafka_source
    url: {handler_url}
    one_row_per_request: true
    payload_version: 0
    primary_key: id

sinks:
  print_sink:
    type: print
    from: handler_transform
    sample_every: 1
"#,
        topic = ctx.kafka_topic,
        handler_url = handler.passthrough_handler_url()
    );

    let _ = ctx
        .run_pipeline_with_opts(&pipeline, PipelineOpts::new().record_limit(1))
        .await
        .expect("Pipeline execution failed");

    // Verify the handler captured the request
    assert_eq!(
        handler.request_count(),
        1,
        "Handler should have captured 1 request"
    );

    let requests = handler.get_requests();
    assert!(!requests.is_empty(), "Should have captured requests");
    assert_eq!(requests[0].endpoint, "handler_passthrough");
    assert!(
        requests[0].body.contains("test_data"),
        "Request body should contain test_data"
    );
}

// ============================================================================
// Generic batch accumulation on handler transform
// ============================================================================

/// Test that batch_size on a handler transform controls the number of rows
/// sent per HTTP request when one_row_per_request is false.
///
/// Forces the Kafka source to emit one-row batches (RECORD_BATCH_SIZE=1),
/// then configures batch_size=5 on the handler transform. The wrapping layer
/// should accumulate rows and send them to the HTTP handler in batches of 5.
#[tokio::test]
async fn test_handler_transform_batch_accumulation() {
    init_tracing();

    let ctx = TestContext::new()
        .await
        .expect("Failed to create test context");

    let handler = ExternalHandlerResource::new()
        .await
        .expect("Failed to start handler server");

    ctx.kafka
        .register_schema(SLIM_SCHEMA)
        .await
        .expect("Failed to register schema");

    let total_records = 20;
    let records: Vec<SlimTestRecord> = (1..=total_records)
        .map(|i| SlimTestRecord {
            id: i.to_string(),
            data: format!("item_{}", i),
        })
        .collect();

    ctx.kafka
        .produce_avro_records(&records)
        .await
        .expect("Failed to produce records");

    let batch_size = 5;
    let pipeline = format!(
        r#"
sources:
  kafka_source:
    type: kafka
    topic: {topic}
    primary_key: id
    batch_size: 1

transforms:
  handler_transform:
    type: handler
    from: kafka_source
    url: {handler_url}
    one_row_per_request: false
    payload_version: 0
    primary_key: id
    batch_size: {batch_size}
    batch_flush_interval: 5s

sinks:
  print_sink:
    type: print
    from: handler_transform
    sample_every: 1
"#,
        topic = ctx.kafka_topic,
        handler_url = handler.slim_batch_handler_url(),
        batch_size = batch_size,
    );

    let output = ctx
        .run_pipeline_with_capture(
            &pipeline,
            PipelineOpts::new().record_limit(total_records as u64),
        )
        .await
        .expect("Pipeline execution failed");

    // All records should pass through the handler and reach the print sink
    assert_eq!(
        output.rows().len(),
        total_records,
        "All {} records should reach the print sink",
        total_records
    );

    // Verify the handler received batched requests, not one-per-row
    let requests = handler.get_requests();
    assert!(
        !requests.is_empty(),
        "Handler should have received at least one request"
    );

    // Each request body is a JSON array. Parse and check sizes.
    let request_sizes: Vec<usize> = requests
        .iter()
        .map(|r| {
            let parsed: Vec<serde_json::Value> =
                serde_json::from_str(&r.body).expect("Request body should be a JSON array");
            parsed.len()
        })
        .collect();

    let total_rows_received: usize = request_sizes.iter().sum();
    assert_eq!(
        total_rows_received, total_records,
        "Handler should have received all {} records across all requests",
        total_records
    );

    // With batch_size=5 and 20 records, we expect around 4 requests of 5 rows each.
    // Due to timing, the last batch may be smaller, but no batch should exceed batch_size.
    for (i, size) in request_sizes.iter().enumerate() {
        assert!(
            *size <= batch_size,
            "Request {} had {} rows, which exceeds batch_size={}",
            i,
            size,
            batch_size
        );
    }

    // Without batching, we'd get as many requests as input batches (20 with RECORD_BATCH_SIZE=1).
    // With batch_size=5, we should get significantly fewer.
    assert!(
        requests.len() <= total_records / batch_size + 1,
        "Expected at most {} requests with batch_size={}, got {}",
        total_records / batch_size + 1,
        batch_size,
        requests.len()
    );
}