shotover 0.7.2

Shotover API for building custom transforms
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
use crate::sources::{Source, SourceConfig};
use anyhow::{Context, Result, anyhow};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Write;
use tokio::net::TcpListener;
use tokio::sync::watch;
use tracing::info;

#[derive(Serialize, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct Topology {
    pub sources: Vec<SourceConfig>,
}

impl Topology {
    /// Load the topology.yaml from the provided path into a Topology instance
    pub fn from_file(filepath: &str) -> Result<Topology> {
        let file = std::fs::File::open(filepath)
            .with_context(|| format!("Couldn't open the topology file {}", filepath))?;

        let deserializer = serde_yaml::Deserializer::from_reader(file);
        serde_yaml::with::singleton_map_recursive::deserialize(deserializer)
            .with_context(|| format!("Failed to parse topology file {}", filepath))
    }

    /// Generate the yaml representation of this instance
    pub fn serialize(&self) -> Result<String> {
        let mut output = vec![];
        let mut serializer = serde_yaml::Serializer::new(&mut output);
        serde_yaml::with::singleton_map_recursive::serialize(self, &mut serializer)?;
        Ok(String::from_utf8(output).unwrap())
    }

    pub async fn run_chains(
        &self,
        trigger_shutdown_rx: watch::Receiver<bool>,
        mut hot_reload_listeners: HashMap<u16, TcpListener>,
    ) -> Result<Vec<Source>> {
        let mut sources: Vec<Source> = Vec::new();

        let mut topology_errors = String::new();

        let mut duplicated_names = vec![];
        for source in &self.sources {
            let name = source.get_name();
            if self.sources.iter().filter(|x| x.get_name() == name).count() > 1 {
                duplicated_names.push(name);
            }
        }
        for name in duplicated_names.iter().unique() {
            writeln!(
                topology_errors,
                "Source name {name:?} occurred more than once. Make sure all source names are unique. The names will be used in logging and metrics."
            )?;
        }

        for source in &self.sources {
            match source
                .build(trigger_shutdown_rx.clone(), &mut hot_reload_listeners)
                .await
            {
                Ok(source) => sources.push(source),
                Err(source_errors) => {
                    if !source_errors.is_empty() {
                        topology_errors.push_str(&source_errors.join("\n"));
                        topology_errors.push('\n');
                    }
                }
            };
        }

        if !topology_errors.is_empty() {
            return Err(anyhow!("Topology errors\n{topology_errors}"));
        }

        // This info log is considered part of our external API.
        // Users rely on this to know when shotover is ready in their integration tests.
        // In production they would probably just have some kind of retry mechanism though.
        info!("Shotover is now accepting inbound connections");
        Ok(sources)
    }
}

#[cfg(all(test, feature = "valkey", feature = "cassandra"))]
mod topology_tests {
    use crate::config::chain::TransformChainConfig;
    use crate::config::topology::Topology;
    use crate::sources::cassandra::CassandraConfig;
    use crate::transforms::TransformConfig;
    use crate::transforms::coalesce::CoalesceConfig;
    use crate::transforms::debug::printer::DebugPrinterConfig;
    use crate::transforms::null::NullSinkConfig;
    use crate::{
        sources::{Source, SourceConfig, valkey::ValkeyConfig},
        transforms::{
            parallel_map::ParallelMapConfig, valkey::cache::ValkeyConfig as ValkeyCacheConfig,
        },
    };
    use pretty_assertions::assert_eq;
    use std::collections::HashMap;
    use tokio::sync::watch;

    fn create_source_from_chain_valkey(chain: Vec<Box<dyn TransformConfig>>) -> Vec<SourceConfig> {
        vec![SourceConfig::Valkey(ValkeyConfig {
            name: "foo".to_string(),
            listen_addr: "127.0.0.1:0".to_string(),
            connection_limit: None,
            hard_connection_limit: None,
            tls: None,
            timeout: None,
            chain: TransformChainConfig(chain),
        })]
    }

    fn create_source_from_chain_cassandra(
        chain: Vec<Box<dyn TransformConfig>>,
    ) -> Vec<SourceConfig> {
        vec![SourceConfig::Cassandra(CassandraConfig {
            name: "foo".to_string(),
            listen_addr: "127.0.0.1:0".to_string(),
            connection_limit: None,
            hard_connection_limit: None,
            tls: None,
            timeout: None,
            chain: TransformChainConfig(chain),
            transport: None,
        })]
    }

    async fn run_test_topology_valkey(
        chain: Vec<Box<dyn TransformConfig>>,
    ) -> anyhow::Result<Vec<Source>> {
        let sources = create_source_from_chain_valkey(chain);

        let topology = Topology { sources };

        let (_sender, trigger_shutdown_rx) = watch::channel::<bool>(false);

        topology
            .run_chains(trigger_shutdown_rx, HashMap::new())
            .await
    }

    async fn run_test_topology_cassandra(
        chain: Vec<Box<dyn TransformConfig>>,
    ) -> anyhow::Result<Vec<Source>> {
        let sources = create_source_from_chain_cassandra(chain);

        let topology = Topology { sources };

        let (_sender, trigger_shutdown_rx) = watch::channel::<bool>(false);

        topology
            .run_chains(trigger_shutdown_rx, HashMap::new())
            .await
    }

    #[tokio::test]
    async fn test_validate_chain_empty_chain() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    Chain cannot be empty
"#;

        let error = run_test_topology_valkey(vec![])
            .await
            .unwrap_err()
            .to_string();
        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_valid_chain() {
        run_test_topology_valkey(vec![Box::new(DebugPrinterConfig), Box::new(NullSinkConfig)])
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_validate_coalesce() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    Coalesce:
      Need to provide at least one of these fields:
      * flush_when_buffered_message_count
      * flush_when_millis_since_last_flush
    
      But none of them were provided.
      Check https://shotover.io/docs/latest/transforms.html#coalesce for more information.
"#;

        let error = run_test_topology_valkey(vec![
            Box::new(CoalesceConfig {
                flush_when_buffered_message_count: None,
                flush_when_millis_since_last_flush: None,
            }),
            Box::new(NullSinkConfig),
        ])
        .await
        .unwrap_err()
        .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_terminating_in_middle() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    Terminating transform "NullSink" is not last in chain. Terminating transform must be last in chain.
"#;

        let error = run_test_topology_valkey(vec![
            Box::new(DebugPrinterConfig),
            Box::new(NullSinkConfig),
            Box::new(NullSinkConfig),
        ])
        .await
        .unwrap_err()
        .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_non_terminating_at_end() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    Non-terminating transform "DebugPrinter" is last in chain. Last transform must be terminating.
"#;

        let error = run_test_topology_valkey(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
        ])
        .await
        .unwrap_err()
        .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_terminating_middle_non_terminating_at_end() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    Terminating transform "NullSink" is not last in chain. Terminating transform must be last in chain.
    Non-terminating transform "DebugPrinter" is last in chain. Last transform must be terminating.
"#;

        let error = run_test_topology_valkey(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
            Box::new(NullSinkConfig),
            Box::new(DebugPrinterConfig),
        ])
        .await
        .unwrap_err()
        .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_valid_subchain_cassandra_valkey_cache() {
        let caching_schema = HashMap::new();

        run_test_topology_cassandra(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
            Box::new(ValkeyCacheConfig {
                chain: TransformChainConfig(vec![
                    Box::new(DebugPrinterConfig),
                    Box::new(DebugPrinterConfig),
                    Box::new(NullSinkConfig),
                ]),
                caching_schema,
            }),
            Box::new(NullSinkConfig),
        ])
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn test_validate_chain_invalid_subchain_cassandra_valkey_cache() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    ValkeyCache:
      cache_chain chain:
        Terminating transform "NullSink" is not last in chain. Terminating transform must be last in chain.
"#;

        let error = run_test_topology_cassandra(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
            Box::new(ValkeyCacheConfig {
                chain: TransformChainConfig(vec![
                    Box::new(DebugPrinterConfig),
                    Box::new(NullSinkConfig),
                    Box::new(DebugPrinterConfig),
                    Box::new(NullSinkConfig),
                ]),
                caching_schema: HashMap::new(),
            }),
            Box::new(NullSinkConfig),
        ])
        .await
        .unwrap_err()
        .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_valid_subchain_parallel_map() {
        run_test_topology_valkey(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
            Box::new(ParallelMapConfig {
                parallelism: 1,
                chain: TransformChainConfig(vec![
                    Box::new(DebugPrinterConfig),
                    Box::new(DebugPrinterConfig),
                    Box::new(NullSinkConfig),
                ]),
                ordered_results: false,
            }),
        ])
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn test_validate_chain_invalid_subchain_parallel_map() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    ParallelMap:
      parallel_map_chain chain:
        Terminating transform "NullSink" is not last in chain. Terminating transform must be last in chain.
"#;

        let error = run_test_topology_valkey(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
            Box::new(ParallelMapConfig {
                parallelism: 1,
                chain: TransformChainConfig(vec![
                    Box::new(DebugPrinterConfig),
                    Box::new(NullSinkConfig),
                    Box::new(DebugPrinterConfig),
                    Box::new(NullSinkConfig),
                ]),
                ordered_results: false,
            }),
        ])
        .await
        .unwrap_err()
        .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_subchain_terminating_in_middle() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    ParallelMap:
      parallel_map_chain chain:
        Terminating transform "NullSink" is not last in chain. Terminating transform must be last in chain.
"#;

        let subchain = TransformChainConfig(vec![
            Box::new(DebugPrinterConfig),
            Box::new(NullSinkConfig),
            Box::new(DebugPrinterConfig),
            Box::new(NullSinkConfig),
        ]);

        let error = run_test_topology_valkey(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
            Box::new(ParallelMapConfig {
                parallelism: 1,
                chain: subchain,
                ordered_results: true,
            }),
        ])
        .await
        .unwrap_err()
        .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_subchain_non_terminating_at_end() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    ParallelMap:
      parallel_map_chain chain:
        Non-terminating transform "DebugPrinter" is last in chain. Last transform must be terminating.
"#;

        let subchain = TransformChainConfig(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
        ]);

        let error = run_test_topology_valkey(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
            Box::new(ParallelMapConfig {
                parallelism: 1,
                chain: subchain,
                ordered_results: true,
            }),
        ])
        .await
        .unwrap_err()
        .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_subchain_terminating_middle_non_terminating_at_end() {
        let expected = r#"Topology errors
foo source:
  foo chain:
    ParallelMap:
      parallel_map_chain chain:
        Terminating transform "NullSink" is not last in chain. Terminating transform must be last in chain.
        Non-terminating transform "DebugPrinter" is last in chain. Last transform must be terminating.
"#;

        let subchain = TransformChainConfig(vec![
            Box::new(DebugPrinterConfig),
            Box::new(NullSinkConfig),
            Box::new(DebugPrinterConfig),
        ]);

        let error = run_test_topology_valkey(vec![
            Box::new(DebugPrinterConfig),
            Box::new(DebugPrinterConfig),
            Box::new(ParallelMapConfig {
                parallelism: 1,
                chain: subchain,
                ordered_results: true,
            }),
        ])
        .await
        .unwrap_err()
        .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_repeated_source_names() {
        let expected = r#"Topology errors
Source name "foo" occurred more than once. Make sure all source names are unique. The names will be used in logging and metrics.
"#;

        let mut sources = create_source_from_chain_valkey(vec![Box::new(NullSinkConfig)]);
        sources.extend(create_source_from_chain_valkey(vec![Box::new(
            NullSinkConfig,
        )]));

        let topology = Topology { sources };
        let (_sender, trigger_shutdown_rx) = watch::channel::<bool>(false);
        let error = topology
            .run_chains(trigger_shutdown_rx, HashMap::new())
            .await
            .unwrap_err()
            .to_string();

        assert_eq!(error, expected);
    }

    #[tokio::test]
    async fn test_validate_chain_multiple_subchains() {
        let (_sender, trigger_shutdown_rx) = watch::channel::<bool>(false);

        let topology =
            Topology::from_file("../shotover-proxy/tests/test-configs/invalid_subchains.yaml")
                .unwrap();
        let error = topology
            .run_chains(trigger_shutdown_rx, HashMap::new())
            .await
            .unwrap_err()
            .to_string();

        let expected = r#"Topology errors
valkey1 source:
  valkey1 chain:
    Terminating transform "NullSink" is not last in chain. Terminating transform must be last in chain.
    Terminating transform "NullSink" is not last in chain. Terminating transform must be last in chain.
    Non-terminating transform "DebugPrinter" is last in chain. Last transform must be terminating.
valkey2 source:
  valkey2 chain:
    ParallelMap:
      parallel_map_chain chain:
        Terminating transform "NullSink" is not last in chain. Terminating transform must be last in chain.
        Non-terminating transform "DebugPrinter" is last in chain. Last transform must be terminating.
"#;

        assert_eq!(error, expected);
    }
}