continuo 0.12.0

Runtime service composition for multi-service Rust applications: typed component resolution, dependency-ordered lifecycle, reload, runnable tasks, graceful drain, and finalization.
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
use std::sync::Mutex;

use async_trait::async_trait;

use super::*;

#[derive(Clone, Default)]
struct TestState {
    seen: Arc<Mutex<Vec<&'static str>>>,
}

#[async_trait]
impl ReloadState for TestState {
    async fn reload(&self) -> Result<()> {
        Ok(())
    }
}

struct DbComponent;
struct CacheComponent;
struct ApiComponent;
struct MetricsComponent;
struct FailsValidation;

#[async_trait]
impl Component<TestState> for DbComponent {
    type Deps = ();
    fn name(&self) -> &str {
        "db"
    }

    fn validate(
        &self,
        state: &TestState,
    ) -> Result<()> {
        state.seen.lock().expect("test log poisoned").push("db");
        Ok(())
    }
}

#[async_trait]
impl Component<TestState> for CacheComponent {
    type Deps = (Arc<DbComponent>,);
    fn name(&self) -> &str {
        "cache"
    }

    fn validate(
        &self,
        state: &TestState,
    ) -> Result<()> {
        state.seen.lock().expect("test log poisoned").push("cache");
        Ok(())
    }
}

#[async_trait]
impl Component<TestState> for ApiComponent {
    type Deps = (Arc<CacheComponent>,);
    fn name(&self) -> &str {
        "api"
    }

    fn validate(
        &self,
        state: &TestState,
    ) -> Result<()> {
        state.seen.lock().expect("test log poisoned").push("api");
        Ok(())
    }
}

#[async_trait]
impl Component<TestState> for MetricsComponent {
    type Deps = ();
    fn name(&self) -> &str {
        "metrics"
    }

    fn order(&self) -> ComponentOrder {
        ComponentOrder::new().before::<ApiComponent>()
    }

    fn validate(
        &self,
        state: &TestState,
    ) -> Result<()> {
        state.seen.lock().expect("test log poisoned").push("metrics");
        Ok(())
    }
}

#[async_trait]
impl Component<TestState> for FailsValidation {
    type Deps = ();
    fn name(&self) -> &str {
        "fails-validation"
    }

    fn validate(
        &self,
        _: &TestState,
    ) -> Result<()> {
        Err(Error::msg("validation rejected"))
    }
}

#[test]
fn lifecycle_order_uses_type_dependencies() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();

    registry
        .register(Arc::new(ApiComponent))
        .expect("api registration should succeed")
        .register(Arc::new(CacheComponent))
        .expect("cache registration should succeed")
        .register(Arc::new(DbComponent))
        .expect("database registration should succeed");

    let outcome = registry.validate_all(&state).expect("validation should run");
    assert!(outcome.is_valid());
    assert_eq!(outcome.validated_count(), 3);

    let seen = state.seen.lock().expect("test log poisoned").clone();
    assert_eq!(seen, vec!["db", "cache", "api"]);
}

#[test]
fn duplicate_component_registration_is_rejected_without_replacement() {
    let registry = Registry::<TestState>::new();
    let original = Arc::new(ApiComponent);

    registry
        .register(original.clone())
        .expect("first registration should succeed");
    let error = match registry.register(Arc::new(ApiComponent)) {
        Err(error) => error,
        Ok(_) => panic!("duplicate registration must be rejected"),
    };

    assert!(matches!(
        error,
        Error::DuplicateComponent { type_name }
            if type_name == std::any::type_name::<ApiComponent>()
    ));
    let resolved = registry
        .resolve::<ApiComponent>()
        .expect("original component should remain");
    assert!(Arc::ptr_eq(&resolved, &original));
}

#[test]
fn lifecycle_order_supports_before_edges_and_diagnostics() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();

    registry
        .register(Arc::new(ApiComponent))
        .expect("api registration should succeed")
        .register(Arc::new(MetricsComponent))
        .expect("metrics registration should succeed")
        .register(Arc::new(CacheComponent))
        .expect("cache registration should succeed")
        .register(Arc::new(DbComponent))
        .expect("database registration should succeed");

    let names = registry.lifecycle_names().expect("plan should build");
    assert_eq!(
        names.iter().map(AsRef::as_ref).collect::<Vec<&str>>(),
        vec!["metrics", "db", "cache", "api"]
    );

    let outcome = registry.validate_all(&state).expect("validation should run");
    assert!(outcome.is_valid());
    assert_eq!(outcome.validated_count(), 4);

    let seen = state.seen.lock().expect("test log poisoned").clone();
    assert_eq!(seen, vec!["metrics", "db", "cache", "api"]);
}

#[test]
fn validate_all_retains_component_failures_and_continues() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();
    registry
        .register(Arc::new(FailsValidation))
        .expect("failing validator should register")
        .register(Arc::new(DbComponent))
        .expect("successful validator should register");

    let outcome =
        registry.validate_all(&state).expect("validation should complete");

    assert!(!outcome.is_valid());
    assert_eq!(outcome.validated_count(), 1);
    assert_eq!(outcome.failed_count(), 1);
    let failure = &outcome.failures()[0];
    assert_eq!(failure.component(), "fails-validation");
    assert!(matches!(
        failure.error(),
        Error::Validate { name, .. } if name.as_ref() == "fails-validation"
    ));
    assert_eq!(
        failure.error().to_string(),
        "component 'fails-validation' failed during validate: validation rejected"
    );
    assert_eq!(
        state.seen.lock().expect("test log poisoned").as_slice(),
        &["db"]
    );
}

trait LogSink: Send + Sync {
    fn line(&self) -> &'static str;
}

struct ConsoleLogger;
struct FileLogger;

impl LogSink for ConsoleLogger {
    fn line(&self) -> &'static str {
        "console"
    }
}

impl LogSink for FileLogger {
    fn line(&self) -> &'static str {
        "file"
    }
}

#[async_trait]
impl Component<TestState> for ConsoleLogger {
    type Deps = ();
    fn name(&self) -> &str {
        "console-logger"
    }

    fn as_bootable(&self) -> Option<&dyn Bootable<TestState>> {
        Some(self)
    }
}

#[async_trait]
impl Bootable<TestState> for ConsoleLogger {
    async fn boot(
        &self,
        _deps: (),
        state: &TestState,
    ) -> Result<()> {
        state.seen.lock().expect("test log poisoned").push("console-logger");
        Ok(())
    }
}

#[async_trait]
impl Component<TestState> for FileLogger {
    type Deps = ();
    fn name(&self) -> &str {
        "file-logger"
    }

    fn as_bootable(&self) -> Option<&dyn Bootable<TestState>> {
        Some(self)
    }
}

#[async_trait]
impl Bootable<TestState> for FileLogger {
    async fn boot(
        &self,
        _deps: (),
        state: &TestState,
    ) -> Result<()> {
        state.seen.lock().expect("test log poisoned").push("file-logger");
        Ok(())
    }
}

#[tokio::test]
async fn bind_dyn_resolves_trait_object_and_allows_replacement() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();

    registry
        .register(Arc::new(ConsoleLogger))
        .expect("console logger should register");
    registry
        .bind_dyn::<dyn LogSink, ConsoleLogger>(|logger| logger)
        .expect("dyn binding should succeed");

    let sink =
        registry.resolve_dyn::<dyn LogSink>().expect("LogSink should be bound");
    assert_eq!(sink.line(), "console");

    registry
        .register(Arc::new(FileLogger))
        .expect("file logger should register");
    registry
        .bind_dyn::<dyn LogSink, FileLogger>(|logger| logger)
        .expect("dyn binding replacement should succeed");

    let sink = registry
        .resolve_dyn::<dyn LogSink>()
        .expect("LogSink should be rebound");
    assert_eq!(sink.line(), "file");

    registry.boot_all(&state).await.expect("boot should succeed");

    let seen = state.seen.lock().expect("test log poisoned").clone();
    assert_eq!(seen, vec!["console-logger", "file-logger"]);
}

struct BootRecorder;
struct BootDependency;

#[async_trait]
impl Component<TestState> for BootRecorder {
    type Deps = (Arc<BootDependency>,);
    fn name(&self) -> &str {
        "boot-recorder"
    }

    fn as_bootable(&self) -> Option<&dyn Bootable<TestState, Self::Deps>> {
        Some(self)
    }

    fn as_finalizable(&self) -> Option<&dyn Finalizable<TestState>> {
        Some(self)
    }
}

#[async_trait]
impl Bootable<TestState, (Arc<BootDependency>,)> for BootRecorder {
    async fn boot(
        &self,
        (dependency,): (Arc<BootDependency>,),
        state: &TestState,
    ) -> Result<()> {
        // The dependency arrives resolved and already booted.
        assert_eq!(Component::name(dependency.as_ref()), "boot-dependency");
        state.seen.lock().expect("test log poisoned").push("boot-recorder");
        Ok(())
    }
}

#[async_trait]
impl Finalizable<TestState> for BootRecorder {
    async fn finalize(
        &self,
        state: &TestState,
    ) -> Result<()> {
        state.seen.lock().expect("test log poisoned").push("finalize-recorder");
        Ok(())
    }
}

#[async_trait]
impl Component<TestState> for BootDependency {
    type Deps = ();
    fn name(&self) -> &str {
        "boot-dependency"
    }

    fn as_bootable(&self) -> Option<&dyn Bootable<TestState>> {
        Some(self)
    }

    fn as_finalizable(&self) -> Option<&dyn Finalizable<TestState>> {
        Some(self)
    }
}

#[async_trait]
impl Bootable<TestState> for BootDependency {
    async fn boot(
        &self,
        _deps: (),
        state: &TestState,
    ) -> Result<()> {
        state.seen.lock().expect("test log poisoned").push("boot-dependency");
        Ok(())
    }
}

#[async_trait]
impl Finalizable<TestState> for BootDependency {
    async fn finalize(
        &self,
        state: &TestState,
    ) -> Result<()> {
        state
            .seen
            .lock()
            .expect("test log poisoned")
            .push("finalize-dependency");
        Ok(())
    }
}

#[tokio::test]
async fn boot_and_finalize_share_lifecycle_plan() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();

    registry
        .register(Arc::new(BootRecorder))
        .expect("boot recorder should register")
        .register(Arc::new(BootDependency))
        .expect("boot dependency should register");

    registry.boot_all(&state).await.expect("boot should succeed");
    let outcome =
        registry.finalize_all(&state).await.expect("finalize should succeed");
    assert!(outcome.is_complete());
    assert_eq!(outcome.finalized_count(), 2);

    let seen = state.seen.lock().expect("test log poisoned").clone();
    assert_eq!(
        seen,
        vec![
            "boot-dependency",
            "boot-recorder",
            "finalize-recorder",
            "finalize-dependency",
        ]
    );
}

/// A layer: never registered, only named in `order()`.
struct Network;
struct Dns;
struct Edge;

impl Component<TestState> for Dns {
    type Deps = ();
    fn name(&self) -> &str {
        "dns"
    }

    fn order(&self) -> ComponentOrder {
        ComponentOrder::new().before::<Network>()
    }
}

impl Component<TestState> for Edge {
    type Deps = ();
    fn name(&self) -> &str {
        "edge"
    }

    fn order(&self) -> ComponentOrder {
        ComponentOrder::new().after::<Network>()
    }
}

#[test]
fn targets_order_layers_without_naming_their_members() {
    let registry = Registry::<TestState>::new();
    registry
        .register(Arc::new(Edge))
        .expect("edge should register")
        .register(Arc::new(Dns))
        .expect("dns should register");

    let names = registry.lifecycle_names().expect("plan should build");
    assert_eq!(
        names.iter().map(AsRef::as_ref).collect::<Vec<&str>>(),
        vec!["dns", "edge"]
    );
}

struct MarkerCycle;

impl Component<TestState> for MarkerCycle {
    type Deps = ();

    fn name(&self) -> &str {
        "marker-cycle"
    }

    fn order(&self) -> ComponentOrder {
        ComponentOrder::new().before::<Network>().after::<Network>()
    }
}

#[test]
fn marker_cycle_returns_a_named_error_instead_of_panicking() {
    let registry = Registry::<TestState>::new();
    registry.register(Arc::new(MarkerCycle)).unwrap();
    let error = registry.lifecycle_names().unwrap_err();
    assert!(error.to_string().contains("cycle detected: marker-cycle"));
    assert!(registry.runnable_entries().is_err());
}

struct Absent;
struct NeedsAbsent;

impl Component<TestState> for NeedsAbsent {
    type Deps = (Arc<Absent>,);
    fn name(&self) -> &str {
        "needs-absent"
    }

    fn as_bootable(&self) -> Option<&dyn Bootable<TestState, Self::Deps>> {
        Some(self)
    }

    fn as_runnable(
        self: Arc<Self>
    ) -> Option<Arc<dyn Runnable<TestState, Self::Deps>>> {
        Some(self)
    }
}

#[async_trait]
impl Bootable<TestState, (Arc<Absent>,)> for NeedsAbsent {
    async fn boot(
        &self,
        _: (Arc<Absent>,),
        _: &TestState,
    ) -> Result<()> {
        unreachable!("boot must not run without its dependency")
    }
}

#[async_trait]
impl Runnable<TestState, (Arc<Absent>,)> for NeedsAbsent {
    async fn run(
        self: Arc<Self>,
        _: (Arc<Absent>,),
        _: TestState,
        _: crate::RunContext,
    ) -> Result<()> {
        unreachable!("run must not start without its dependency")
    }
}

#[tokio::test]
async fn missing_dependency_names_the_component_and_the_type() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();
    registry.register(Arc::new(NeedsAbsent)).expect("should register");

    let error = registry.boot_all(&state).await.expect_err("boot must fail");
    assert!(
        matches!(error, Error::Dependency { ref name, .. } if name.as_ref() == "needs-absent")
    );
    assert!(error.to_string().contains("Absent"));

    let entries =
        registry.runnable_entries().expect("discovery needs no dependencies");
    let error = entries[0]
        .runnable
        .clone()
        .bind(&registry)
        .err()
        .expect("activation must fail");
    assert!(
        matches!(error, Error::Dependency { ref name, .. } if name.as_ref() == "needs-absent")
    );

    registry.insert(Arc::new(Absent)).expect("dependency should insert");
    entries[0]
        .runnable
        .clone()
        .bind(&registry)
        .expect("published dependency is visible");
    assert_eq!(
        registry.runnable_entries().expect("resolved").len(),
        1,
        "once the dependency exists the runnable is submitted"
    );
}

struct CycleA;
struct CycleB;

#[async_trait]
impl Component<TestState> for CycleA {
    type Deps = ();
    fn name(&self) -> &str {
        "cycle-a"
    }

    fn order(&self) -> ComponentOrder {
        ComponentOrder::new().after::<CycleB>()
    }
}

#[async_trait]
impl Component<TestState> for CycleB {
    type Deps = ();
    fn name(&self) -> &str {
        "cycle-b"
    }

    fn order(&self) -> ComponentOrder {
        ComponentOrder::new().after::<CycleA>()
    }
}

#[test]
fn lifecycle_order_rejects_cycles() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();

    registry
        .register(Arc::new(CycleA))
        .expect("cycle A should register")
        .register(Arc::new(CycleB))
        .expect("cycle B should register");

    let err =
        registry.validate_all(&state).expect_err("cycle must be rejected");
    assert!(
        err.to_string().contains("component lifecycle order cycle detected")
    );
}

struct Reloads;
struct FailsReload;
struct Finalizes;
struct FailsFinalize;

#[async_trait]
impl Component<TestState> for Finalizes {
    type Deps = ();
    fn name(&self) -> &str {
        "finalizes"
    }

    fn as_finalizable(&self) -> Option<&dyn Finalizable<TestState>> {
        Some(self)
    }
}

#[async_trait]
impl Finalizable<TestState> for Finalizes {
    async fn finalize(
        &self,
        _: &TestState,
    ) -> Result<()> {
        Ok(())
    }
}

#[async_trait]
impl Component<TestState> for FailsFinalize {
    type Deps = ();
    fn name(&self) -> &str {
        "fails-finalize"
    }

    fn as_finalizable(&self) -> Option<&dyn Finalizable<TestState>> {
        Some(self)
    }
}

#[async_trait]
impl Finalizable<TestState> for FailsFinalize {
    async fn finalize(
        &self,
        _: &TestState,
    ) -> Result<()> {
        Err(Error::msg("finalize rejected"))
    }
}

#[async_trait]
impl Component<TestState> for Reloads {
    type Deps = ();
    fn name(&self) -> &str {
        "reloads"
    }

    fn as_reloadable(&self) -> Option<&dyn Reloadable<TestState>> {
        Some(self)
    }
}

#[async_trait]
impl Reloadable<TestState> for Reloads {
    async fn reload(
        &self,
        _: &TestState,
    ) -> Result<()> {
        Ok(())
    }
}

#[async_trait]
impl Component<TestState> for FailsReload {
    type Deps = ();
    fn name(&self) -> &str {
        "fails-reload"
    }

    fn as_reloadable(&self) -> Option<&dyn Reloadable<TestState>> {
        Some(self)
    }
}

#[async_trait]
impl Reloadable<TestState> for FailsReload {
    async fn reload(
        &self,
        _: &TestState,
    ) -> Result<()> {
        Err(Error::msg("reload rejected"))
    }
}

#[tokio::test]
async fn reload_all_retains_component_failures_and_continues() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();
    registry
        .register(Arc::new(FailsReload))
        .expect("failing reloader should register")
        .register(Arc::new(Reloads))
        .expect("successful reloader should register");

    let outcome =
        registry.reload_all(&state).await.expect("broadcast should complete");

    assert!(!outcome.is_complete());
    assert_eq!(outcome.reloaded_count(), 1);
    assert_eq!(outcome.failed_count(), 1);
    let failure = &outcome.failures()[0];
    assert_eq!(failure.component(), "fails-reload");
    assert!(matches!(
        failure.error(),
        Error::Reload { name, .. } if name.as_ref() == "fails-reload"
    ));
    assert_eq!(
        failure.error().to_string(),
        "reload of 'fails-reload' failed: reload rejected"
    );
}

#[tokio::test]
async fn finalize_all_retains_component_failures_and_continues() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();
    registry
        .register(Arc::new(Finalizes))
        .expect("successful finalizer should register")
        .register(Arc::new(FailsFinalize))
        .expect("failing finalizer should register");

    let outcome = registry
        .finalize_all(&state)
        .await
        .expect("finalization should complete");

    assert!(!outcome.is_complete());
    assert_eq!(outcome.finalized_count(), 1);
    assert_eq!(outcome.failed_count(), 1);
    let failure = &outcome.failures()[0];
    assert_eq!(failure.component(), "fails-finalize");
    assert!(matches!(
        failure.error(),
        Error::Finalize { name, .. } if name.as_ref() == "fails-finalize"
    ));
    assert_eq!(
        failure.error().to_string(),
        "finalize of 'fails-finalize' failed: finalize rejected"
    );
}

#[tokio::test]
async fn targeted_reload_without_configuration_keeps_lifecycle_behavior() {
    let state = TestState::default();
    let registry = Registry::<TestState>::new();
    registry.register(Arc::new(Reloads)).unwrap();
    registry.register(Arc::new(FailsReload)).unwrap();
    registry.reload_one("reloads", &state).await.unwrap();
    registry.reload_hook_one("reloads", &state).await.unwrap();
    assert!(registry.reload_one("missing", &state).await.is_err());
    assert!(matches!(
        registry.reload_one("fails-reload", &state).await,
        Err(Error::Reload { name, .. }) if name.as_ref() == "fails-reload"
    ));
}