wabot 0.2.0

Wabot framework — umbrella crate re-exporting wabot-core and wabot-macros.
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
//! Run a whole application: every subsystem, one shutdown. Port of
//! `wabot-ts/src/feature/project-runner`.
//!
//! ```ignore
//! ProjectRunner::new(container)
//!     .service("rest", run_rest_controllers(router, RestServerConfig::from_env()))
//!     .service("chat", run_chat_controllers(channels))
//!     .service("jobs", run_async_workers(container.clone(), commands, crons))
//!     .on_shutdown(ShutdownTask::new("pool", ShutdownPhase::Close, move || {
//!         let pool = pool.clone();
//!         async move { pool.close().await }
//!     }))
//!     .run()
//!     .await;
//! ```
//!
//! ## What this is, and what it deliberately isn't
//!
//! Half of the TypeScript `ProjectRunner` is **filesystem discovery**:
//! it walks the source tree and dynamically imports every module so
//! that decorators register controllers as an import-time side effect.
//! There is no Rust analogue and there shouldn't be — this port
//! decided early that registration is explicit (`register_singletons!`,
//! `Controller::register_routes(…)`), which is why a missing
//! registration is a compile error here instead of a controller that
//! silently never mounts.
//!
//! So what is left is the part that actually earns its keep: composing
//! the subsystems, giving them **one** shutdown, and making the
//! process exit for a reason a human can read.
//!
//! ## Why anything is gained over `tokio::join!`
//!
//! Three things, all of which get hand-rolled slightly differently in
//! every service otherwise:
//!
//! * **One signal handler and one drain order.** Each subsystem
//!   registering its own SIGTERM handler means they race, and the
//!   database pool can close while jobs are still running.
//! * **A service that ends stops the process.** A REST server that
//!   returns because its port was taken should not leave a process
//!   running with no listener, looking healthy to an orchestrator.
//! * **An exit code that distinguishes a clean drain from a stuck
//!   one**, which is the only signal an orchestrator can act on.

use std::future::Future;
use std::pin::Pin;

use wabot_core::injection::Container;
use wabot_core::lifecycle::{
    install_panic_reporter, systemd, Cancel, ShutdownManager, ShutdownOutcome, ShutdownTask,
};

type BoxedService = Pin<Box<dyn Future<Output = ServiceResult> + Send>>;

/// Built at [`run`](ProjectRunner::run) rather than at registration,
/// so a [`Cancel`] handed to a service is always the one the manager
/// in force will actually fire — registering a service before
/// [`with_shutdown`](ProjectRunner::with_shutdown) would otherwise
/// wire it to a manager that got replaced.
type ServiceBuilder = Box<dyn FnOnce(Cancel) -> BoxedService + Send>;

/// What a long-running subsystem reports when it stops.
pub type ServiceResult = Result<(), String>;

struct Service {
    name: String,
    build: ServiceBuilder,
}

/// Composes an application's subsystems under one lifecycle.
pub struct ProjectRunner {
    container: Container,
    shutdown: std::sync::Arc<ShutdownManager>,
    services: Vec<Service>,
    install_signals: bool,
}

impl ProjectRunner {
    pub fn new(container: Container) -> Self {
        Self {
            container,
            shutdown: std::sync::Arc::new(ShutdownManager::new()),
            services: Vec::new(),
            install_signals: true,
        }
    }

    /// Use an existing manager — for an application that registered
    /// shutdown tasks before it got here.
    pub fn with_shutdown(mut self, shutdown: std::sync::Arc<ShutdownManager>) -> Self {
        self.shutdown = shutdown;
        self
    }

    pub fn container(&self) -> &Container {
        &self.container
    }

    pub fn shutdown_manager(&self) -> &std::sync::Arc<ShutdownManager> {
        &self.shutdown
    }

    /// Add a long-running subsystem.
    ///
    /// Named because the name is what gets logged when it is the one
    /// that ended, and "something stopped" is not a debuggable line.
    /// Any error type is accepted and rendered, since each subsystem
    /// has its own.
    pub fn service<F, E>(mut self, name: impl Into<String>, future: F) -> Self
    where
        F: Future<Output = Result<(), E>> + Send + 'static,
        E: std::fmt::Display + Send + 'static,
    {
        self.services.push(Service {
            name: name.into(),
            build: Box::new(move |_cancel| {
                Box::pin(async move { future.await.map_err(|error| error.to_string()) })
            }),
        });
        self
    }

    /// Add a subsystem that can wind *itself* down.
    ///
    /// The closure receives a [`Cancel`] that fires when the shutdown
    /// starts, from whichever cause. A service built this way returns
    /// on its own, and the runner waits for that return — which is the
    /// difference between a drain and a `kill`:
    ///
    /// ```ignore
    /// runner.service_with_cancel("rest", |cancel| async move {
    ///     axum::serve(listener, app)
    ///         .with_graceful_shutdown(async move { cancel.cancelled().await })
    ///         .await
    /// })
    /// ```
    ///
    /// Prefer this over [`service`](Self::service) for anything holding
    /// a listener or a poll loop. Plain `service` is still right for a
    /// subsystem that already owns its own stop path.
    pub fn service_with_cancel<F, Fut, E>(mut self, name: impl Into<String>, build: F) -> Self
    where
        F: FnOnce(Cancel) -> Fut + Send + 'static,
        Fut: Future<Output = Result<(), E>> + Send + 'static,
        E: std::fmt::Display + Send + 'static,
    {
        self.services.push(Service {
            name: name.into(),
            build: Box::new(move |cancel| {
                Box::pin(async move { build(cancel).await.map_err(|error| error.to_string()) })
            }),
        });
        self
    }

    /// Register work to do on the way down. See [`ShutdownPhase`] for
    /// which phase to use.
    ///
    /// [`ShutdownPhase`]: wabot_core::lifecycle::ShutdownPhase
    pub fn on_shutdown(self, task: ShutdownTask) -> Self {
        self.shutdown.register(task);
        self
    }

    /// Don't trap SIGTERM/SIGINT — for a test, or for an application
    /// that owns its own signal handling.
    pub fn without_signal_handlers(mut self) -> Self {
        self.install_signals = false;
        self
    }

    /// Run until a signal arrives or a service stops, then drain.
    ///
    /// Returns the outcome rather than exiting, so the caller decides
    /// — a `main` that wants the exit code can use
    /// [`ShutdownOutcome::exit_code`].
    ///
    /// ## The order on the way down
    ///
    /// 1. Something ends the run: a signal, or a service returning.
    /// 2. The [`Cancel`] fires, so every service built with
    ///    [`service_with_cancel`](Self::service_with_cancel) starts
    ///    winding down.
    /// 3. **The services are awaited**, bounded by
    ///    [`ShutdownManager::timeout`]. Anything still running past the
    ///    deadline is aborted and named in the log.
    /// 4. The shutdown phases run — intake, drain, close.
    ///
    /// Step 3 is the one that used to be missing: the services were
    /// simply dropped, cutting their in-flight work, so the phases
    /// after them drained a system nothing was still using.
    pub async fn run(self) -> ShutdownOutcome {
        install_panic_reporter();

        let Self {
            shutdown,
            services,
            install_signals,
            ..
        } = self;

        if services.is_empty() {
            tracing::warn!("no services registered — nothing to run");
            return ShutdownOutcome::Clean;
        }

        tracing::info!(
            services = services
                .iter()
                .map(|service| service.name.as_str())
                .collect::<Vec<_>>()
                .join(", "),
            "starting"
        );

        let mut running = tokio::task::JoinSet::new();
        for service in services {
            let Service { name, build } = service;
            let future = build(shutdown.cancel_signal());
            running.spawn(async move { (name, future.await) });
        }

        start_watchdog(&shutdown);
        // Sent once the services are spawned and not a line earlier:
        // readiness that arrives before the listeners are bound is
        // worse than none, because it looks trustworthy.
        systemd::notify_ready();

        // A service ending is a reason to shut down, not something to
        // survive: a process whose REST server died because the port
        // was taken still looks healthy to an orchestrator, and that
        // is the outage nobody gets paged for.
        let reason = if install_signals {
            tokio::select! {
                Some(joined) = running.join_next() => ended(joined),
                signal = shutdown.wait_for_signal_name() => format!("received {signal}"),
            }
        } else {
            match running.join_next().await {
                Some(joined) => ended(joined),
                None => "every service ended".to_string(),
            }
        };

        drain_services(&mut running, &shutdown, install_signals).await;
        shutdown.shutdown(&reason).await
    }
}

/// Ping `WatchdogSec` for as long as the process is up. Detached on
/// purpose: it is not a service, so it must never be the task whose
/// ending takes the process down.
fn start_watchdog(shutdown: &std::sync::Arc<ShutdownManager>) {
    let Some(interval) = systemd::watchdog_interval() else {
        return;
    };
    let cancel = shutdown.cancel_signal();
    tracing::debug!(?interval, "systemd watchdog enabled");
    tokio::spawn(async move {
        let mut ticker = tokio::time::interval(interval);
        loop {
            tokio::select! {
                _ = cancel.cancelled() => break,
                _ = ticker.tick() => { systemd::notify_watchdog(); }
            }
        }
    });
}

/// Give the services the same window the phases get, then stop being
/// polite. A second signal skips the wait entirely — someone pressing
/// Ctrl+C twice has told us they are done waiting.
async fn drain_services(
    running: &mut tokio::task::JoinSet<(String, ServiceResult)>,
    shutdown: &std::sync::Arc<ShutdownManager>,
    install_signals: bool,
) {
    shutdown.cancel();

    let deadline = shutdown.timeout();
    let drain = async {
        while let Some(joined) = running.join_next().await {
            let _ = ended(joined);
        }
    };

    tokio::select! {
        outcome = tokio::time::timeout(deadline, drain) => {
            if outcome.is_err() {
                tracing::warn!(
                    timeout_seconds = deadline.as_secs(),
                    remaining = running.len(),
                    "services did not stop within the drain window — aborting them"
                );
            }
        }
        signal = shutdown.wait_for_signal_name(), if install_signals => {
            tracing::warn!(signal, "second signal during drain — not waiting for services");
        }
    }

    running.shutdown().await;
}

/// Render one finished service, whichever way it finished.
fn ended(joined: Result<(String, ServiceResult), tokio::task::JoinError>) -> String {
    match joined {
        Ok((name, Ok(()))) => {
            tracing::warn!(service = %name, "service stopped");
            format!("{name} stopped")
        }
        Ok((name, Err(error))) => {
            tracing::error!(service = %name, %error, "service failed");
            format!("{name} failed: {error}")
        }
        // A panicking service already went through the panic reporter;
        // what is added here is which subsystem it was.
        Err(error) => {
            tracing::error!(%error, "service task did not complete");
            format!("a service task did not complete: {error}")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    use std::time::Duration;
    use wabot_core::lifecycle::ShutdownPhase;

    fn runner() -> ProjectRunner {
        ProjectRunner::new(Container::new()).without_signal_handlers()
    }

    /// A manager with a drain window short enough that a test which
    /// deliberately strands a service does not pay the real one.
    fn brisk_runner() -> ProjectRunner {
        runner().with_shutdown(Arc::new(ShutdownManager::with_timeout(
            Duration::from_millis(50),
        )))
    }

    /// The property that makes this more than `tokio::join!`: one
    /// subsystem ending takes the process down instead of leaving it
    /// half-running and looking healthy.
    #[tokio::test]
    async fn one_service_stopping_shuts_everything_down() {
        let drained = Arc::new(AtomicUsize::new(0));
        let counter = drained.clone();

        let outcome = brisk_runner()
            .service("rest", async {
                Err::<(), String>("port already in use".into())
            })
            .service("jobs", async {
                // Would run forever.
                std::future::pending::<Result<(), String>>().await
            })
            .on_shutdown(ShutdownTask::new("pool", ShutdownPhase::Close, move || {
                let counter = counter.clone();
                async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                }
            }))
            .run()
            .await;

        assert_eq!(outcome, ShutdownOutcome::Clean);
        assert_eq!(drained.load(Ordering::SeqCst), 1, "the drain still ran");
    }

    /// A service that ends *successfully* is still a reason to stop —
    /// a server returning `Ok` means it is no longer serving.
    #[tokio::test]
    async fn a_service_that_returns_ok_also_ends_the_run() {
        let outcome = brisk_runner()
            .service("one-shot", async { Ok::<(), String>(()) })
            .service("forever", async {
                std::future::pending::<Result<(), String>>().await
            })
            .run()
            .await;
        assert_eq!(outcome, ShutdownOutcome::Clean);
    }

    /// The reason `service_with_cancel` exists: the service is
    /// **awaited**, so whatever it does on the way out actually
    /// happens. Before this, the future was dropped and the cleanup
    /// below would never have run.
    #[tokio::test]
    async fn a_cancel_aware_service_gets_to_finish() {
        let cleaned = Arc::new(AtomicUsize::new(0));
        let counter = cleaned.clone();

        let outcome = runner()
            .service("trigger", async { Ok::<(), String>(()) })
            .service_with_cancel("edge", move |cancel| async move {
                cancel.cancelled().await;
                // Stands in for draining an in-flight request.
                tokio::time::sleep(Duration::from_millis(20)).await;
                counter.fetch_add(1, Ordering::SeqCst);
                Ok::<(), String>(())
            })
            .run()
            .await;

        assert_eq!(outcome, ShutdownOutcome::Clean);
        assert_eq!(
            cleaned.load(Ordering::SeqCst),
            1,
            "the runner waited for the service instead of dropping it"
        );
    }

    /// The other half of the bargain: a service that ignores the
    /// signal gets the window and then gets aborted. Waiting forever
    /// for one uncooperative subsystem is how a `SIGTERM` turns into a
    /// `SIGKILL` with no logs.
    #[tokio::test]
    async fn a_service_that_ignores_cancellation_is_aborted() {
        let started = std::time::Instant::now();

        let outcome = brisk_runner()
            .service("trigger", async { Ok::<(), String>(()) })
            .service_with_cancel("stubborn", |_cancel| async {
                std::future::pending::<Result<(), String>>().await
            })
            .run()
            .await;

        assert_eq!(outcome, ShutdownOutcome::Clean);
        assert!(
            started.elapsed() < Duration::from_secs(2),
            "the drain window bounded the wait, it took {:?}",
            started.elapsed()
        );
    }

    /// `with_shutdown` after registering a service must still reach
    /// that service — the cancel is resolved at `run`, not at
    /// registration, precisely so this ordering cannot silently wire a
    /// service to a discarded manager.
    #[tokio::test]
    async fn a_replaced_manager_still_cancels_services_registered_before_it() {
        let cancelled = Arc::new(AtomicUsize::new(0));
        let counter = cancelled.clone();

        let outcome = runner()
            .service_with_cancel("early", move |cancel| async move {
                cancel.cancelled().await;
                counter.fetch_add(1, Ordering::SeqCst);
                Ok::<(), String>(())
            })
            .with_shutdown(Arc::new(ShutdownManager::with_timeout(
                Duration::from_millis(50),
            )))
            .service("trigger", async { Ok::<(), String>(()) })
            .run()
            .await;

        assert_eq!(outcome, ShutdownOutcome::Clean);
        assert_eq!(cancelled.load(Ordering::SeqCst), 1);
    }

    /// The drain order is the manager's, and the runner must not
    /// bypass it.
    #[tokio::test]
    async fn shutdown_tasks_run_in_phase_order() {
        let log = Arc::new(parking_lot::Mutex::new(Vec::<&'static str>::new()));

        let mut runner = runner().service("brief", async { Ok::<(), String>(()) });
        for (name, phase, mark) in [
            ("pool", ShutdownPhase::Close, "close"),
            ("http", ShutdownPhase::Intake, "intake"),
        ] {
            let log = log.clone();
            runner = runner.on_shutdown(ShutdownTask::new(name, phase, move || {
                let log = log.clone();
                async move { log.lock().push(mark) }
            }));
        }

        runner.run().await;
        assert_eq!(*log.lock(), vec!["intake", "close"]);
    }

    /// A stuck drain has to end in a distinguishable exit code, or an
    /// orchestrator cannot tell a clean stop from a hung one.
    #[tokio::test]
    async fn a_stuck_drain_reports_a_failure_code() {
        let shutdown = Arc::new(ShutdownManager::with_timeout(Duration::from_millis(50)));
        shutdown.register(ShutdownTask::new(
            "never-finishes",
            ShutdownPhase::Drain,
            || async {
                tokio::time::sleep(Duration::from_secs(30)).await;
            },
        ));

        let outcome = runner()
            .with_shutdown(shutdown)
            .service("brief", async { Ok::<(), String>(()) })
            .run()
            .await;

        assert_eq!(outcome.exit_code(), 1);
        match outcome {
            ShutdownOutcome::TimedOut { still_running } => {
                assert_eq!(still_running, vec!["never-finishes".to_string()]);
            }
            other => panic!("expected a timeout, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn with_no_services_it_does_nothing() {
        assert_eq!(runner().run().await, ShutdownOutcome::Clean);
    }
}