-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathtest.rs
More file actions
3038 lines (2744 loc) · 93 KB
/
test.rs
File metadata and controls
3038 lines (2744 loc) · 93 KB
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{
Controller, PipelineConfig,
controller::TransactionInfo,
preprocess::{DecryptionPreprocessorFactory, PassthroughPreprocessorFactory},
test::{
DEFAULT_TIMEOUT_MS, TestStruct, generate_test_batch, init_test_logger, test_circuit, wait,
},
transport::set_barrier,
};
use anyhow::anyhow;
use csv::{ReaderBuilder as CsvReaderBuilder, WriterBuilder as CsvWriterBuilder};
use feldera_types::{
config::{InputEndpointConfig, OutputEndpointConfig},
constants::STATE_FILE,
memory_pressure::MemoryPressure,
};
use serde_json::json;
use std::{
borrow::Cow,
cmp::min,
collections::BTreeMap,
fs::{File, create_dir, remove_file},
io::Write,
iter::repeat_n,
ops::Range,
path::{Path, PathBuf},
sync::{atomic::Ordering, mpsc},
thread::sleep,
time::Duration,
};
use tempfile::{NamedTempFile, TempDir};
use tokio::sync::oneshot;
use tracing::info;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use proptest::prelude::*;
#[test]
fn test_start_after_cyclic() {
init_test_logger();
let config: PipelineConfig = serde_json::from_value(json!({
"name": "test",
"workers": 4,
"inputs": {
"test_input1.endpoint1": {
"stream": "test_input1",
"labels": [
"label1"
],
"start_after": "label2",
"transport": {
"name": "file_input",
"config": {
"path": "file1"
}
},
"format": {
"name": "json",
"config": {
"array": true,
"update_format": "raw"
}
}
},
"test_input1.endpoint2": {
"stream": "test_input1",
"labels": [
"label2"
],
"start_after": "label1",
"transport": {
"name": "file_input",
"config": {
"path": "file2"
}
},
"format": {
"name": "json",
"config": {
"array": true,
"update_format": "raw"
}
}
}
}
}))
.unwrap();
let Err(err) = Controller::with_test_config(
|circuit_config| {
Ok(test_circuit::<TestStruct>(
circuit_config,
&TestStruct::schema(),
&[None],
))
},
&config,
Box::new(|e, _| panic!("error: {e}")),
) else {
panic!("expected to fail")
};
assert_eq!(
&err.to_string(),
"invalid controller configuration: cyclic 'start_after' dependency detected: endpoint 'test_input1.endpoint1' with label 'label1' waits for endpoint 'test_input1.endpoint2' with label 'label2', which waits for endpoint 'test_input1.endpoint1' with label 'label1'"
);
}
#[test]
fn test_start_after() {
init_test_logger();
// Two JSON files with a few records each.
let temp_input_file1 = NamedTempFile::new().unwrap();
let temp_input_file2 = NamedTempFile::new().unwrap();
temp_input_file1
.as_file()
.write_all(br#"[{"id": 1, "b": true, "s": "foo"}, {"id": 2, "b": true, "s": "foo"}]"#)
.unwrap();
temp_input_file2
.as_file()
.write_all(br#"[{"id": 3, "b": true, "s": "foo"}, {"id": 4, "b": true, "s": "foo"}]"#)
.unwrap();
// Controller configuration with two input connectors;
// the second starts after the first one finishes.
let config: PipelineConfig = serde_json::from_value(json! ({
"name": "test",
"workers": 4,
"inputs": {
"test_input1.endpoint1": {
"stream": "test_input1",
"transport": {
"name": "file_input",
"labels": [
"backfill"
],
"config": {
"path": temp_input_file1.path(),
}
},
"format": {
"name": "json",
"config": {
"array": true,
"update_format": "raw"
}
}
},
"test_input1.endpoint2": {
"stream": "test_input1",
"start_after": "backfill",
"transport": {
"name": "file_input",
"config": {
"path": temp_input_file2.path(),
}
},
"format": {
"name": "json",
"config": {
"array": true,
"update_format": "raw"
}
}
}
}
}))
.unwrap();
let controller = Controller::with_test_config(
|circuit_config| {
Ok(test_circuit::<TestStruct>(
circuit_config,
&TestStruct::schema(),
&[None],
))
},
&config,
Box::new(|e, _| panic!("error: {e}")),
)
.unwrap();
controller.start();
// Wait 3 seconds, assert(no data in the output table)
// Unpause the first connector.
wait(|| controller.pipeline_complete(), DEFAULT_TIMEOUT_MS).unwrap();
let result = controller
.execute_query_text_sync("select * from test_output1 order by id")
.unwrap();
let expected = r#"+----+------+---+-----+
| id | b | i | s |
+----+------+---+-----+
| 1 | true | | foo |
| 2 | true | | foo |
| 3 | true | | foo |
| 4 | true | | foo |
+----+------+---+-----+"#;
assert_eq!(&result, expected);
controller.stop().unwrap();
}
// TODO: Parameterize this with config string, so we can test different
// input/output formats and transports when we support more than one.
proptest! {
#![proptest_config(ProptestConfig::with_cases(30))]
#[test]
fn proptest_csv_file(
data in generate_test_batch(5000),
min_batch_size_records in 1..100usize,
max_buffering_delay_usecs in 1..2000usize,
input_buffer_size_bytes in 1..1000usize,
output_buffer_size_records in 1..100usize)
{
let temp_input_file = NamedTempFile::new().unwrap();
let temp_output_path = NamedTempFile::new().unwrap().into_temp_path();
let output_path = temp_output_path.to_str().unwrap().to_string();
temp_output_path.close().unwrap();
let secrets_dir = TempDir::new().unwrap();
create_dir(secrets_dir.path().join("kubernetes")).unwrap();
create_dir(secrets_dir.path().join("kubernetes/paths")).unwrap();
std::fs::write(secrets_dir.path().join("kubernetes/paths/input"), temp_input_file.path().as_os_str().as_encoded_bytes()).unwrap();
std::fs::write(secrets_dir.path().join("kubernetes/paths/output"), &output_path).unwrap();
let config: PipelineConfig = serde_json::from_value(json!({
"secrets_dir": secrets_dir.path(),
"min_batch_size_records": min_batch_size_records,
"max_buffering_delay_usecs": max_buffering_delay_usecs,
"name": "test",
"workers": 4,
"inputs": {
"test_input1": {
"stream": "test_input1",
"transport": {
"name": "file_input",
"config": {
"path": "${secret:kubernetes:paths/input}",
"buffer_size_bytes": input_buffer_size_bytes,
"follow": false
}
},
"format": {
"name": "csv"
}
}
},
"outputs": {
"test_output1": {
"stream": "test_output1",
"transport": {
"name": "file_output",
"config": {
"path": "${secret:kubernetes:paths/output}"
}
},
"format": {
"name": "csv",
"config": {
"buffer_size_records": output_buffer_size_records,
}
}
}
}
})).unwrap();
info!("input file: {}", temp_input_file.path().display());
info!("output file: {output_path}");
let controller = Controller::with_test_config(
|circuit_config| Ok(test_circuit::<TestStruct>(circuit_config, &[], &[None])),
&config,
Box::new(|e, _| panic!("error: {e}")),
)
.unwrap();
let mut writer = CsvWriterBuilder::new()
.has_headers(false)
.from_writer(temp_input_file.as_file());
for val in data.iter().cloned() {
writer.serialize(val).unwrap();
}
writer.flush().unwrap();
println!("wait for {} records", data.len());
controller.start();
// Wait for the pipeline to output all records.
wait(|| controller.pipeline_complete(), DEFAULT_TIMEOUT_MS).unwrap();
assert_eq!(controller.status().output_status().get(&0).unwrap().transmitted_records(), data.len() as u64);
controller.stop().unwrap();
let mut expected = data;
expected.sort();
let mut actual: Vec<_> = CsvReaderBuilder::new()
.has_headers(false)
.from_path(&output_path)
.unwrap()
.deserialize::<(TestStruct, i32)>()
.map(|res| {
let (val, weight) = res.unwrap();
assert_eq!(weight, 1);
val
})
.collect();
actual.sort();
// Don't leave garbage in the FS.
remove_file(&output_path).unwrap();
assert_eq!(actual, expected);
}
}
#[derive(Clone)]
struct FtTestRound {
n_records: usize,
do_checkpoint: bool,
pause_afterward: bool,
immediate_checkpoint: bool,
/// Apply function to modify pipeline configuration before starting the pipeline.
/// Modified config prevents the pipeline from replaying the journal; however it
/// should still produce the same result by replaying inputs from the last checkpointed
/// offset.
modify_config: Option<fn(PipelineConfig) -> PipelineConfig>,
}
impl FtTestRound {
fn with_checkpoint(n_records: usize) -> Self {
Self {
n_records,
do_checkpoint: true,
pause_afterward: false,
immediate_checkpoint: false,
modify_config: None,
}
}
fn without_checkpoint(n_records: usize) -> Self {
Self {
n_records,
do_checkpoint: false,
pause_afterward: false,
immediate_checkpoint: false,
modify_config: None,
}
}
fn with_pause_afterward(self) -> Self {
Self {
pause_afterward: true,
..self
}
}
fn with_modify_config(self, f: fn(PipelineConfig) -> PipelineConfig) -> Self {
Self {
modify_config: Some(f),
..self
}
}
/// Requests a checkpoint immediately upon resume, without waiting for
/// records to be replayed. This helps catch regression for bugs in
/// handling this case (usually because the initial input positions are
/// written as empty instead of as a copy of the previous positions).
fn immediate_checkpoint() -> Self {
Self {
n_records: 0,
do_checkpoint: false,
pause_afterward: false,
immediate_checkpoint: true,
modify_config: None,
}
}
}
/// Reads `path` and ensures that it contains the [TestStruct] records in
/// `expect`.
#[track_caller]
fn check_file_contents(path: &Path, expect: Range<usize>) {
let mut actual = CsvReaderBuilder::new()
.has_headers(false)
.from_path(path)
.unwrap()
.deserialize::<(TestStruct, i32)>()
.map(|res| {
let (val, weight) = res.unwrap();
assert_eq!(weight, 1);
val
})
.collect::<Vec<_>>();
actual.sort();
assert_eq!(actual.len(), expect.len());
for (record, expect_record) in actual
.into_iter()
.zip(expect.map(|id| TestStruct::for_id(id as u32)))
{
assert_eq!(record, expect_record);
}
}
fn count_endpoint_records(controller: &Controller, output_index: usize) -> u64 {
let endpoint_id = controller
.inner
.output_endpoint_id_by_name(&format!("test_output{}", output_index + 1))
.unwrap();
controller
.status()
.output_status()
.get(&endpoint_id)
.unwrap()
.transmitted_records()
}
fn collect_endpoint_records(controller: &Controller, n: usize) -> Vec<usize> {
(0..n)
.map(|i| count_endpoint_records(controller, i) as usize)
.collect()
}
#[track_caller]
fn wait_for_records(controller: &Controller, expect_n: &[usize]) {
println!("waiting for {expect_n:?} records...");
let n = expect_n.len();
let mut last_n = repeat_n(0, n).collect::<Vec<_>>();
wait(
|| {
let new_n = collect_endpoint_records(controller, n);
for i in 0..n {
if new_n[i] > last_n[i] {
println!("received {} records on test_output{}", new_n[i], i + 1);
}
}
last_n = new_n;
last_n
.iter()
.zip(expect_n.iter())
.all(|(&last, &expect)| last >= expect)
},
10_000,
)
.unwrap();
// No more records should arrive, but give the controller some time
// to send some more in case there's a bug.
sleep(Duration::from_millis(100));
// Then verify that the number is as expected.
assert_eq!(&collect_endpoint_records(controller, n), expect_n);
}
/// Runs a basic test of fault tolerance.
///
/// The test proceeds in multiple rounds. For each element of `rounds`, the
/// test writes `n_records` records to the input file, and starts the
/// pipeline and waits for it to process the data. If `do_checkpoint` is
/// true, it creates a new checkpoint. Then it stops the pipeline, checks
/// that the output is as expected, and goes on to the next round.
///
/// This also tests that the controller resolves secrets and that it freshly
/// resolves them every time it resumes from a checkpoint, by using a secret for
/// the location of its input and output files and renaming these files before
/// each round. If the controller did not re-resolve the secrets when it
/// resumes, then it would try to read an input file that was no longer there,
/// or it would try to write output to an old location, and in either case that
/// would cause an error.
fn test_ft(rounds: &[FtTestRound]) {
init_test_logger();
let tempdir = TempDir::new().unwrap();
// This allows the temporary directory to be deleted when we finish. If
// you want to keep it for inspection instead, comment out the following
// line and then remove the comment markers on the two lines after that.
let tempdir_path = tempdir.path();
//let tempdir_path = tempdir.into_path();
//println!("{}", tempdir_path.display());
let storage_dir = tempdir_path.join("storage");
create_dir(&storage_dir).unwrap();
create_dir(tempdir.path().join("kubernetes")).unwrap();
create_dir(tempdir.path().join("kubernetes/paths")).unwrap();
const INPUT_SECRET_REFERENCE: &str = "${secret:kubernetes:paths/input}";
const OUTPUT_SECRET_REFERENCE: &str = "${secret:kubernetes:paths/output}";
let mut config: PipelineConfig = serde_json::from_value(json!({
"name": "test",
"workers": 4,
"storage_config": {
"path": storage_dir,
},
"storage": true,
"fault_tolerance": {},
"clock_resolution_usecs": null,
"secrets_dir": tempdir_path,
"inputs": {
"test_input1": {
"stream": "test_input1",
"transport": {
"name": "file_input",
"config": {
"path": INPUT_SECRET_REFERENCE,
"follow": true
}
},
"format": {
"name": "csv"
}
}
},
"outputs": {
"test_output1": {
"stream": "test_output1",
"transport": {
"name": "file_output",
"config": {
"path": OUTPUT_SECRET_REFERENCE,
}
},
"format": {
"name": "csv",
"config": {}
}
}
}
}))
.unwrap();
// Number of records written to the input.
let mut total_records = 0usize;
// Number of input records included in the latest checkpoint (always <=
// total_records).
let mut checkpointed_records = 0usize;
let mut paused = false;
let mut prev_input_path = None;
let mut prev_output_path = None;
const TABOO: &str = "TABOO";
for (
round,
FtTestRound {
n_records,
do_checkpoint,
pause_afterward,
immediate_checkpoint,
modify_config,
},
) in rounds.iter().cloned().enumerate()
{
// Create input file, or move it from its previous location.
let input_path = tempdir_path.join(format!("{TABOO}-input{round}.csv"));
let input_file = if let Some(prev_input_path) = &prev_input_path {
std::fs::rename(prev_input_path, &input_path).unwrap();
File::options().append(true).open(&input_path).unwrap()
} else {
File::create_new(&input_path).unwrap()
};
let mut writer = CsvWriterBuilder::new()
.has_headers(false)
.from_writer(&input_file);
// Move output file from its previous location, if any.
let output_path = tempdir_path.join(format!("{TABOO}-output{round}.csv"));
if let Some(prev_output_path) = &prev_output_path {
std::fs::rename(prev_output_path, &output_path).unwrap();
};
// Update secrets to point to new locations.
for (name, path) in [("input", &input_path), ("output", &output_path)] {
std::fs::write(
tempdir.path().join("kubernetes/paths").join(name),
path.as_os_str().as_encoded_bytes(),
)
.unwrap();
}
std::fs::write(
tempdir.path().join("kubernetes/paths/input"),
input_path.as_os_str().as_encoded_bytes(),
)
.unwrap();
std::fs::write(
tempdir.path().join("kubernetes/paths/output"),
output_path.as_os_str().as_encoded_bytes(),
)
.unwrap();
println!(
"--- round {round}: {}{}{}add {n_records} records{}, {} --- ",
if modify_config.is_some() {
"run pipeline with modified config, "
} else {
""
},
if paused { "unpause the input, " } else { "" },
if immediate_checkpoint {
"immediately initiate a checkpoint, "
} else {
""
},
if pause_afterward {
", then pause the input"
} else {
""
},
if do_checkpoint {
"and checkpoint"
} else {
"no checkpoint"
},
);
// Write records to the input file.
println!(
"Writing records {total_records}..{}",
total_records + n_records
);
if n_records > 0 {
for id in total_records..total_records + n_records {
writer.serialize(TestStruct::for_id(id as u32)).unwrap();
}
writer.flush().unwrap();
total_records += n_records;
}
// Start pipeline.
println!("start pipeline");
if let Some(modify_config) = modify_config {
config = modify_config(config);
}
let controller = Controller::with_test_config(
|circuit_config| {
Ok(test_circuit::<TestStruct>(
circuit_config,
&[],
&[Some("output")],
))
},
&config,
Box::new(|e, _| panic!("error: {e}")),
)
.unwrap();
controller.start();
let (sender, receiver) = oneshot::channel();
if immediate_checkpoint {
println!("start checkpoint in background");
controller.start_checkpoint(Box::new(move |result| sender.send(result).unwrap()));
} else {
// Wait for replay for finish and then check that the input endpoint's
// pause state matches what it should be.
wait(|| !controller.is_replaying(), 1000).unwrap();
assert_eq!(
controller.is_input_endpoint_paused("test_input1").unwrap(),
paused
);
}
// Wait for the records that are not in the checkpoint to be
// processed or replayed.
let expect_n = total_records - checkpointed_records;
if paused && expect_n > 0 {
controller.start_input_endpoint("test_input1").unwrap();
paused = false;
}
println!(
"wait for {} records {checkpointed_records}..{total_records}",
expect_n
);
wait_for_records(&controller, &[total_records]);
if pause_afterward {
controller.pause_input_endpoint("test_input1").unwrap();
paused = true;
// Wait to journal the pause.
wait(
|| {
!controller
.status()
.global_metrics
.step_requested
.load(Ordering::Relaxed)
},
1000,
)
.unwrap();
// Make sure the step gets executed.
sleep(Duration::from_millis(1000));
}
// Checkpoint, if requested.
if immediate_checkpoint {
println!("wait for checkpoint to complete");
receiver.blocking_recv().unwrap().unwrap();
} else if do_checkpoint {
println!("checkpoint");
controller.checkpoint().unwrap();
}
// Stop controller.
println!("stop controller");
controller.stop().unwrap();
// Read output and compare. Our output adapter, which is not
// fault-tolerant, truncates the output file to length 0 each
// time. Therefore, the output file should contain all the records
// in `checkpointed_records..total_records`.
check_file_contents(&output_path, checkpointed_records..total_records);
if do_checkpoint || immediate_checkpoint {
checkpointed_records = total_records;
// Read the checkpoint file and make sure that:
//
// - The TABOO string does not appear in it. It must not be in
// there because it appears only in the expanded version of the
// secret, not in the name of the secret.
//
// - The INPUT_SECRET_REFERENCE and OUTPUT_SECRET_REFERENCE strings
// do appear in it. These must be there because they are what
// expands to the secrets.
//
// It is valuable to check for these because this gives us some
// confidence that the file isn't encoded in some form such that
// TABOO appears but just not literally. That is, our check for
// TABOO would fail if TABOO were to be base64-encoded, but in
// that case it's likely that INPUT_SECRET_REFERENCE and
// OUTPUT_SECRET_REFERENCE are also base64-encoded, so that these
// tests would fail.
//
// (As of this writing, the checkpoint file is encoded in
// plaintext JSON, but this check will alert us if that changes
// without updating this test.)
let checkpoint = std::fs::read(storage_dir.join(STATE_FILE)).unwrap();
assert!(!contains_subslice(&checkpoint, TABOO.as_bytes()));
assert!(contains_subslice(
&checkpoint,
INPUT_SECRET_REFERENCE.as_bytes()
));
assert!(contains_subslice(
&checkpoint,
OUTPUT_SECRET_REFERENCE.as_bytes()
));
}
prev_input_path = Some(input_path);
prev_output_path = Some(output_path);
}
}
/// Returns true if `needle` is present as any subslice of `haystack`.
///
/// Yes it's appalling that this isn't part of the standard library, see
/// https://github.com/rust-lang/rust/issues/54961
fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool {
haystack
.windows(needle.len())
.any(|window| window == needle)
}
fn multiple_input_files(
n: usize,
) -> (
Vec<NamedTempFile>,
BTreeMap<Cow<'static, str>, InputEndpointConfig>,
) {
let mut temp_input_files = Vec::new();
let mut inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig> = BTreeMap::new();
for i in 0..n {
let file = NamedTempFile::new().unwrap();
file.as_file()
.write_all(&format!(r#"[{{"id": {i}, "b": true, "s": "foo"}}]"#).into_bytes())
.unwrap();
let config: InputEndpointConfig = serde_json::from_value(json!({
"stream": "test_input1",
"transport": {
"name": "file_input",
"config": {
"path": file.path(),
}
},
"format": {
"name": "json",
"config": {
"array": true,
"update_format": "raw"
}
}
}))
.unwrap();
inputs.insert(format!("test_input1.endpoint{i}").into(), config);
temp_input_files.push(file);
}
(temp_input_files, inputs)
}
fn _test_concurrent_init(max_parallel_connector_init: u64) {
init_test_logger();
let (_temp_input_files, inputs) = multiple_input_files(100);
// Controller configuration with 100 input connectors.
let config: PipelineConfig = serde_json::from_value(json!({
"name": "test",
"workers": 4,
"max_parallel_connector_init": max_parallel_connector_init,
"inputs": inputs,
}))
.unwrap();
let controller = Controller::with_test_config(
|circuit_config| {
Ok(test_circuit::<TestStruct>(
circuit_config,
&TestStruct::schema(),
&[None],
))
},
&config,
Box::new(|e, _| panic!("error: {e}")),
)
.unwrap();
controller.start();
wait(|| controller.pipeline_complete(), DEFAULT_TIMEOUT_MS).unwrap();
let result = controller
.execute_query_text_sync("select count(*) from test_output1")
.unwrap();
let expected = r#"+----------+
| count(*) |
+----------+
| 100 |
+----------+"#;
assert_eq!(&result, expected);
controller.stop().unwrap();
}
#[test]
fn test_concurrent_init() {
_test_concurrent_init(1);
_test_concurrent_init(10);
_test_concurrent_init(100);
}
#[test]
fn test_connector_init_error() {
init_test_logger();
let (_temp_input_files, mut connectors) = multiple_input_files(20);
connectors.insert(
Cow::from("test_input1.error_endpoint"),
serde_json::from_value(json!({
"stream": "test_input1",
"transport": {
"name": "file_input",
"config": {
"path": "path_does_not_exist"
}
},
"format": {
"name": "json",
"config": {
"array": true,
"update_format": "raw"
}
}
}))
.unwrap(),
);
// Controller configuration with two input connectors;
// the second starts after the first one finishes.
let config: PipelineConfig = serde_json::from_value(json!({
"name": "test",
"workers": 4,
"inputs": connectors,
}))
.unwrap();
let result = Controller::with_test_config(
|circuit_config| {
Ok(test_circuit::<TestStruct>(
circuit_config,
&TestStruct::schema(),
&[None],
))
},
&config,
Box::new(|e, _| panic!("error: {e}")),
);
assert!(result.is_err());
}
#[test]
fn ft_with_checkpoints() {
test_ft(&[
FtTestRound::with_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
]);
}
#[test]
fn ft_immediate_checkpoints() {
test_ft(&[
FtTestRound::with_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::immediate_checkpoint(),
FtTestRound::without_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
FtTestRound::immediate_checkpoint(),
FtTestRound::without_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::immediate_checkpoint(),
FtTestRound::with_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
FtTestRound::immediate_checkpoint(),
FtTestRound::with_checkpoint(2500),
]);
}
#[test]
fn ft_without_checkpoints() {
test_ft(&[
FtTestRound::without_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
]);
}
#[test]
fn ft_with_checkpoints_with_pauses() {
test_ft(&[
FtTestRound::with_checkpoint(2500).with_pause_afterward(),
FtTestRound::with_checkpoint(2500),
FtTestRound::with_checkpoint(2500).with_pause_afterward(),
FtTestRound::with_checkpoint(2500),
FtTestRound::with_checkpoint(2500).with_pause_afterward(),
]);
}
#[test]
fn ft_without_checkpoints_with_pauses() {
test_ft(&[
FtTestRound::without_checkpoint(2500).with_pause_afterward(),
FtTestRound::without_checkpoint(2500),
FtTestRound::without_checkpoint(2500).with_pause_afterward(),
FtTestRound::without_checkpoint(2500),
FtTestRound::without_checkpoint(2500).with_pause_afterward(),
]);
}
#[test]
fn ft_alternating() {
test_ft(&[
FtTestRound::with_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
FtTestRound::with_checkpoint(2500),
FtTestRound::without_checkpoint(2500),
]);
}
#[test]
fn ft_initially_zero_without_checkpoint() {
test_ft(&[
FtTestRound::without_checkpoint(0),