supervised 0.1.0

Typed supervision for long-lived Tokio services.
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
#![allow(clippy::expect_used)]

use std::{
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
    time::Duration,
};

use supervised::{
    service_fn,
    BoxFuture,
    Context,
    ErrorAction,
    ExitAction,
    FromSupervisorState,
    Options,
    ReadinessMode,
    RestartPolicy,
    ServiceExt,
    ServiceOutcome,
    ServicePolicy,
    ShutdownCause,
    SupervisedService,
    SupervisorBuilder,
    SupervisorReadiness,
};
use tokio::{
    task::yield_now,
    time::{sleep, timeout},
};

struct ManualService;

impl SupervisedService for ManualService {
    type Context = String;

    fn name(&self) -> &'static str {
        "manual"
    }

    fn run(&self, ctx: Context<Self::Context>) -> BoxFuture<ServiceOutcome> {
        Box::pin(async move {
            if ctx.ctx() == "Hyprbaric" {
                ServiceOutcome::completed()
            } else {
                ServiceOutcome::failed("unexpected manual service context")
            }
        })
    }
}

struct ManualReadyService;

impl SupervisedService for ManualReadyService {
    type Context = String;

    fn name(&self) -> &'static str {
        "manual-ready"
    }

    fn run(&self, ctx: Context<Self::Context>) -> BoxFuture<ServiceOutcome> {
        Box::pin(async move {
            if ctx.ctx() == "Hyprbaric" {
                ctx.readiness().mark_ready();
                ServiceOutcome::completed()
            } else {
                ServiceOutcome::failed("unexpected manual service context")
            }
        })
    }
}

#[tokio::test(flavor = "current_thread")]
async fn completes_without_shutdown_request() {
    let summary = SupervisorBuilder::new(())
        .add(service_fn("complete", |_ctx: Context<()>| async move {
            ServiceOutcome::completed()
        }))
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.shutdown_cause(), &ShutdownCause::Completed);
    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
    assert_eq!(
        summary
            .service("complete")
            .expect("service summary")
            .outcome(),
        &ServiceOutcome::Completed
    );
}

#[tokio::test(flavor = "current_thread")]
async fn requested_shutdown_cancels_other_services() {
    let summary = SupervisorBuilder::new(())
        .add(service_fn("watcher", |ctx: Context<()>| async move {
            ctx.token().cancelled().await;
            ServiceOutcome::cancelled()
        }))
        .add(service_fn("shutdown", |_ctx: Context<()>| async move {
            ServiceOutcome::requested_shutdown()
        }))
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ServiceRequested {
            service: "shutdown"
        }
    );
    assert_eq!(
        summary
            .service("watcher")
            .expect("watcher summary")
            .outcome(),
        &ServiceOutcome::Cancelled
    );
}

#[tokio::test(flavor = "current_thread")]
async fn restart_policy_retries_until_service_completes() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let service_attempts = Arc::clone(&attempts);

    let summary = SupervisorBuilder::new(())
        .add_with_options(
            service_fn("flaky", move |_ctx: Context<()>| {
                let attempts = Arc::clone(&service_attempts);
                async move {
                    let attempt = attempts.fetch_add(1, Ordering::SeqCst);
                    if attempt < 2 {
                        ServiceOutcome::failed(format!("attempt {attempt} failed"))
                    } else {
                        ServiceOutcome::completed()
                    }
                }
            }),
            Options::new().policy(ServicePolicy::new(
                ExitAction::Ignore,
                RestartPolicy::attempts(3, Duration::from_millis(1), ErrorAction::Shutdown),
            )),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.shutdown_cause(), &ShutdownCause::Completed);
    let flaky = summary.service("flaky").expect("flaky summary");
    assert_eq!(flaky.outcome(), &ServiceOutcome::Completed);
    assert_eq!(flaky.restarts(), 2);
    assert_eq!(attempts.load(Ordering::SeqCst), 3);
}

#[tokio::test(flavor = "current_thread")]
async fn exhausted_restart_policy_triggers_shutdown() {
    let summary = SupervisorBuilder::new(())
        .add(service_fn("observer", |ctx: Context<()>| async move {
            ctx.token().cancelled().await;
            ServiceOutcome::cancelled()
        }))
        .add_with_options(
            service_fn("fatal", |_ctx: Context<()>| async move {
                ServiceOutcome::failed("boom")
            }),
            Options::new().policy(ServicePolicy::new(
                ExitAction::Ignore,
                RestartPolicy::attempts(1, Duration::from_millis(1), ErrorAction::Shutdown),
            )),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::FatalService { service: "fatal" }
    );
    assert_eq!(
        summary.service("fatal").expect("fatal summary").restarts(),
        1
    );
    assert_eq!(
        summary
            .service("observer")
            .expect("observer summary")
            .outcome(),
        &ServiceOutcome::Cancelled
    );
}

#[tokio::test(flavor = "current_thread")]
async fn shutdown_timeout_aborts_lingering_tasks() {
    let summary = SupervisorBuilder::new(())
        .shutdown_timeout(Duration::from_millis(10))
        .add(service_fn("shutdown", |_ctx: Context<()>| async move {
            ServiceOutcome::requested_shutdown()
        }))
        .add(service_fn("linger", |_ctx: Context<()>| async move {
            sleep(Duration::from_secs(60)).await;
            ServiceOutcome::completed()
        }))
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ServiceRequested {
            service: "shutdown"
        }
    );
    assert_eq!(
        summary.service("linger").expect("linger summary").outcome(),
        &ServiceOutcome::Cancelled
    );
}

#[tokio::test(flavor = "current_thread")]
async fn service_fn_receives_typed_context() {
    let summary = SupervisorBuilder::new(String::from("Hyprbaric"))
        .add(service_fn("typed", |ctx: Context<String>| async move {
            if ctx.ctx() == "Hyprbaric" {
                ServiceOutcome::completed()
            } else {
                ServiceOutcome::failed("unexpected context")
            }
        }))
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.service("typed").expect("typed summary").outcome(),
        &ServiceOutcome::Completed
    );
}

#[test]
fn never_policy_never_restarts() {
    let policy = RestartPolicy::never(ErrorAction::Shutdown);

    assert_eq!(policy.backoff(), None);
    assert_eq!(policy.max_restarts(), None);
    assert_eq!(policy.on_error(), Some(ErrorAction::Shutdown));
}

#[derive(Clone)]
struct AppState {
    label: String,
}

#[derive(Clone)]
struct LabelContext {
    label: String,
}

impl FromSupervisorState<AppState> for LabelContext {
    fn from_state(state: &AppState) -> Self {
        Self {
            label: state.label.clone(),
        }
    }
}

#[tokio::test(flavor = "current_thread")]
async fn builder_extracts_service_context_from_root_state() {
    let summary = SupervisorBuilder::new(AppState {
        label: String::from("Hyprbaric"),
    })
    .add(service_fn(
        "subset",
        |ctx: Context<LabelContext>| async move {
            if ctx.ctx().label == "Hyprbaric" {
                ServiceOutcome::completed()
            } else {
                ServiceOutcome::failed("unexpected label")
            }
        },
    ))
    .build()
    .run()
    .await
    .expect("supervisor should run");

    assert_eq!(
        summary.service("subset").expect("subset summary").outcome(),
        &ServiceOutcome::Completed
    );
}

#[tokio::test(flavor = "current_thread")]
async fn until_cancelled_wraps_long_lived_functions() {
    let summary = SupervisorBuilder::new(())
        .add(
            service_fn("loop", |_ctx: Context<()>| async move {
                loop {
                    sleep(Duration::from_secs(60)).await;
                }
                #[allow(unreachable_code)]
                ServiceOutcome::completed()
            })
            .until_cancelled(),
        )
        .add(service_fn("shutdown", |_ctx: Context<()>| async move {
            ServiceOutcome::requested_shutdown()
        }))
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.service("loop").expect("loop summary").outcome(),
        &ServiceOutcome::Cancelled
    );
}

#[tokio::test(flavor = "current_thread")]
async fn manual_service_registration_path_works() {
    let summary = SupervisorBuilder::new(String::from("Hyprbaric"))
        .add(ManualService)
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.shutdown_cause(), &ShutdownCause::Completed);
    assert_eq!(
        summary.service("manual").expect("manual summary").outcome(),
        &ServiceOutcome::Completed
    );
}

#[tokio::test(flavor = "current_thread")]
async fn explicit_readiness_starts_pending_and_becomes_ready() {
    let supervisor = SupervisorBuilder::new(())
        .add(
            service_fn("gate", |ctx: Context<()>| async move {
                ctx.readiness().mark_ready();
                ServiceOutcome::requested_shutdown()
            })
            .when_ready(),
        )
        .build();
    let readiness = supervisor.readiness();

    assert_eq!(*readiness.borrow(), SupervisorReadiness::Pending);

    let summary = supervisor.run().await.expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ServiceRequested { service: "gate" }
    );
    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
    assert_eq!(*readiness.borrow(), SupervisorReadiness::Ready);
}

#[tokio::test(flavor = "current_thread")]
async fn startup_gated_error_before_ready_triggers_shutdown() {
    let summary = SupervisorBuilder::new(())
        .add(service_fn("observer", |ctx: Context<()>| async move {
            ctx.token().cancelled().await;
            ServiceOutcome::cancelled()
        }))
        .add(
            service_fn("gate", |_ctx: Context<()>| async move {
                ServiceOutcome::failed("startup failed")
            })
            .when_ready(),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ReadinessFailed { service: "gate" }
    );
    assert_eq!(summary.readiness(), SupervisorReadiness::Pending);
    assert_eq!(
        summary
            .service("observer")
            .expect("observer summary")
            .outcome(),
        &ServiceOutcome::Cancelled
    );
}

#[tokio::test(flavor = "current_thread")]
async fn startup_gated_requested_shutdown_before_ready_triggers_readiness_failure() {
    let summary = SupervisorBuilder::new(())
        .add(
            service_fn("gate", |_ctx: Context<()>| async move {
                ServiceOutcome::requested_shutdown()
            })
            .when_ready(),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ReadinessFailed { service: "gate" }
    );
    assert_eq!(summary.readiness(), SupervisorReadiness::Pending);
}

#[tokio::test(flavor = "current_thread")]
async fn startup_gated_cancelled_before_ready_triggers_readiness_failure() {
    let summary = SupervisorBuilder::new(())
        .add(
            service_fn("gate", |_ctx: Context<()>| async move {
                ServiceOutcome::cancelled()
            })
            .when_ready(),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ReadinessFailed { service: "gate" }
    );
    assert_eq!(summary.readiness(), SupervisorReadiness::Pending);
}

#[tokio::test(flavor = "current_thread")]
async fn startup_gated_completion_counts_as_ready() {
    let summary = SupervisorBuilder::new(())
        .add(
            service_fn("gate", |_ctx: Context<()>| async move {
                ServiceOutcome::completed()
            })
            .when_ready(),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.shutdown_cause(), &ShutdownCause::Completed);
    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
    assert_eq!(
        summary.service("gate").expect("gate summary").outcome(),
        &ServiceOutcome::Completed
    );
}

#[tokio::test(flavor = "current_thread")]
async fn readiness_waits_for_every_startup_gate() {
    let supervisor = SupervisorBuilder::new(())
        .add(
            service_fn("first", |ctx: Context<()>| async move {
                ctx.readiness().mark_ready();
                ctx.token().cancelled().await;
                ServiceOutcome::cancelled()
            })
            .when_ready(),
        )
        .add(
            service_fn("second", |ctx: Context<()>| async move {
                yield_now().await;
                ctx.readiness().mark_ready();
                ServiceOutcome::requested_shutdown()
            })
            .when_ready(),
        )
        .build();
    let mut readiness = supervisor.readiness();

    assert_eq!(*readiness.borrow(), SupervisorReadiness::Pending);

    let handle = tokio::spawn(supervisor.run());
    assert!(timeout(Duration::from_millis(50), readiness.changed())
        .await
        .expect("readiness should change")
        .is_ok());

    assert_eq!(*readiness.borrow(), SupervisorReadiness::Ready);

    let summary = handle
        .await
        .expect("supervisor task should join")
        .expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ServiceRequested { service: "second" }
    );
    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
}

#[tokio::test(flavor = "current_thread")]
async fn mark_ready_is_idempotent() {
    let summary = SupervisorBuilder::new(())
        .add(
            service_fn("gate", |ctx: Context<()>| async move {
                ctx.readiness().mark_ready();
                ctx.readiness().mark_ready();
                ServiceOutcome::requested_shutdown()
            })
            .when_ready(),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ServiceRequested { service: "gate" }
    );
}

#[tokio::test(flavor = "current_thread")]
async fn readiness_failure_ignores_restart_policy() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let service_attempts = Arc::clone(&attempts);

    let summary = SupervisorBuilder::new(())
        .add_with_options(
            service_fn("gate", move |_ctx: Context<()>| {
                let attempts = Arc::clone(&service_attempts);
                async move {
                    attempts.fetch_add(1, Ordering::SeqCst);
                    ServiceOutcome::failed("startup failed")
                }
            })
            .when_ready(),
            Options::new().policy(ServicePolicy::new(
                ExitAction::Ignore,
                RestartPolicy::always(Duration::from_millis(1)),
            )),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ReadinessFailed { service: "gate" }
    );
    assert_eq!(summary.service("gate").expect("gate summary").restarts(), 0);
    assert_eq!(attempts.load(Ordering::SeqCst), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn explicit_policy_registration_can_be_startup_gated() {
    let summary = SupervisorBuilder::new(())
        .add_with_options(
            service_fn("loop", |ctx: Context<()>| async move {
                ctx.readiness().mark_ready();
                ctx.token().cancelled().await;
                ServiceOutcome::cancelled()
            })
            .when_ready()
            .until_cancelled(),
            Options::new().policy(ServicePolicy::new(
                ExitAction::Ignore,
                RestartPolicy::never(ErrorAction::Ignore),
            )),
        )
        .add(service_fn("shutdown", |_ctx: Context<()>| async move {
            ServiceOutcome::requested_shutdown()
        }))
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
    assert_eq!(
        summary.service("loop").expect("loop summary").outcome(),
        &ServiceOutcome::Cancelled
    );
}

#[tokio::test(flavor = "current_thread")]
async fn readiness_stays_ready_after_ready_service_restarts() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let service_attempts = Arc::clone(&attempts);

    let summary = SupervisorBuilder::new(())
        .add_with_options(
            service_fn("flaky", move |ctx: Context<()>| {
                let attempts = Arc::clone(&service_attempts);
                async move {
                    ctx.readiness().mark_ready();
                    let attempt = attempts.fetch_add(1, Ordering::SeqCst);
                    if attempt == 0 {
                        ServiceOutcome::failed("after-ready failure")
                    } else {
                        ServiceOutcome::completed()
                    }
                }
            })
            .when_ready(),
            Options::new().policy(ServicePolicy::new(
                ExitAction::Ignore,
                RestartPolicy::attempts(1, Duration::from_millis(1), ErrorAction::Shutdown),
            )),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.shutdown_cause(), &ShutdownCause::Completed);
    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
    assert_eq!(
        summary.service("flaky").expect("flaky summary").restarts(),
        1
    );
}

#[tokio::test(flavor = "current_thread")]
async fn until_cancelled_service_can_be_startup_gated() {
    let summary = SupervisorBuilder::new(())
        .add(
            service_fn("loop", |ctx: Context<()>| async move {
                ctx.readiness().mark_ready();
                loop {
                    sleep(Duration::from_secs(60)).await;
                }
                #[allow(unreachable_code)]
                ServiceOutcome::completed()
            })
            .when_ready()
            .until_cancelled(),
        )
        .add(service_fn("shutdown", |_ctx: Context<()>| async move {
            ServiceOutcome::requested_shutdown()
        }))
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
    assert_eq!(
        summary.service("loop").expect("loop summary").outcome(),
        &ServiceOutcome::Cancelled
    );
}

#[tokio::test(flavor = "current_thread")]
async fn manual_service_can_use_readiness_signal() {
    let summary = SupervisorBuilder::new(String::from("Hyprbaric"))
        .add(ManualReadyService.when_ready())
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.shutdown_cause(), &ShutdownCause::Completed);
    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
    assert_eq!(
        summary
            .service("manual-ready")
            .expect("manual ready summary")
            .outcome(),
        &ServiceOutcome::Completed
    );
}

#[tokio::test(flavor = "current_thread")]
async fn options_can_override_service_readiness() {
    let summary = SupervisorBuilder::new(())
        .add_with_options(
            service_fn("gate", |_ctx: Context<()>| async move {
                ServiceOutcome::requested_shutdown()
            }),
            Options::new().readiness(ReadinessMode::Explicit),
        )
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ReadinessFailed { service: "gate" }
    );
    assert_eq!(summary.readiness(), SupervisorReadiness::Pending);
}

#[tokio::test(flavor = "current_thread")]
async fn ctrl_c_listener_is_immediately_ready_and_cancelled_by_other_shutdown() {
    let summary = SupervisorBuilder::new(())
        .shutdown_on_ctrl_c()
        .add(service_fn("shutdown", |_ctx: Context<()>| async move {
            ServiceOutcome::requested_shutdown()
        }))
        .build()
        .run()
        .await
        .expect("supervisor should run");

    assert_eq!(summary.readiness(), SupervisorReadiness::Ready);
    assert_eq!(
        summary.service("ctrl-c").expect("ctrl-c summary").outcome(),
        &ServiceOutcome::Cancelled
    );
    assert_eq!(
        summary.shutdown_cause(),
        &ShutdownCause::ServiceRequested {
            service: "shutdown",
        }
    );
}