Skip to main content

navree_kernel/
app.rs

1//! [`Navree`], [`AppBuilder`], [`App`] and [`AppContext`].
2
3use std::any::TypeId;
4use std::fmt;
5use std::sync::{Arc, Weak};
6use std::time::Duration;
7
8use tokio_util::sync::CancellationToken;
9use tokio_util::task::TaskTracker;
10
11use crate::builder::{ProviderDef, value_def};
12use crate::command::help_text;
13use crate::container::{AppInner, RequestScope};
14use crate::graph::{Graph, GraphReport, ROOT};
15use crate::{
16    BootErrors, BoxError, CommandSpec, KernelError, Lifecycle, Module, ModuleId, ProviderKey,
17    Resolver, Scope,
18};
19
20/// Default time allowed for each phase of a graceful shutdown.
21const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
22
23/// Entry point: `Navree::app().module(...).run()`.
24#[derive(Debug)]
25pub struct Navree;
26
27impl Navree {
28    /// Starts building an app.
29    pub fn app() -> AppBuilder {
30        AppBuilder::default()
31    }
32}
33
34/// Collects the root modules of an app, then validates, boots or runs it.
35pub struct AppBuilder {
36    modules: Vec<Box<dyn Module>>,
37    overrides: Vec<ProviderDef>,
38    shutdown: CancellationToken,
39    shutdown_timeout: Duration,
40}
41
42impl Default for AppBuilder {
43    fn default() -> Self {
44        Self {
45            modules: Vec::new(),
46            overrides: Vec::new(),
47            shutdown: CancellationToken::new(),
48            shutdown_timeout: DEFAULT_SHUTDOWN_TIMEOUT,
49        }
50    }
51}
52
53impl AppBuilder {
54    /// Adds a root module (imported by the implicit app root).
55    pub fn module(mut self, m: impl Module) -> Self {
56        self.modules.push(Box::new(m));
57        self
58    }
59
60    /// Replaces the unnamed provider of `T` wherever it is registered with
61    /// `value` (its factory never runs); registers `value` globally if no
62    /// module provides `T`. Meant for tests and fakes.
63    pub fn override_value<T: ?Sized + Send + Sync + 'static>(mut self, value: Arc<T>) -> Self {
64        self.overrides
65            .push(value_def(ProviderKey::of::<T>(), value));
66        self
67    }
68
69    /// How long graceful shutdown waits for tracked tasks, and then for the
70    /// `on_shutdown` hooks (default 30 s each).
71    pub fn shutdown_timeout(mut self, d: Duration) -> Self {
72        self.shutdown_timeout = d;
73        self
74    }
75
76    /// Validates the module graph without constructing any provider.
77    pub fn validate(&self) -> Result<GraphReport, BootErrors> {
78        self.graph().map(|graph| graph.report())
79    }
80
81    /// Validates the graph, constructs every singleton (modules in dependency
82    /// order), then runs `on_init` and `on_bootstrap` hooks.
83    pub async fn boot(self) -> Result<App, BootErrors> {
84        let graph = self.graph()?;
85        self.boot_graph(graph, None).await
86    }
87
88    /// Walks and validates the modules (calls every `register` once).
89    fn graph(&self) -> Result<Graph, BootErrors> {
90        Graph::build(&self.modules, &self.overrides)
91    }
92
93    /// Boots from an already validated graph, so `register` is not called
94    /// again; `command` is the command the app is booted to run.
95    async fn boot_graph(
96        self,
97        graph: Graph,
98        command: Option<CommandSpec>,
99    ) -> Result<App, BootErrors> {
100        let ctx = AppContext::from_inner(Arc::new(AppInner::new(
101            graph,
102            self.shutdown.clone(),
103            command,
104        )));
105        match ctx.start().await {
106            Ok(hooks) => {
107                tracing::debug!(modules = ctx.inner.graph.modules.len(), "navree app booted");
108                Ok(App {
109                    ctx,
110                    hooks,
111                    shutdown_timeout: self.shutdown_timeout,
112                })
113            }
114            Err(error) => {
115                ctx.inner.shutdown.cancel();
116                Err(error.into())
117            }
118        }
119    }
120}
121
122impl AppBuilder {
123    /// Runs a command line (without the program name):
124    ///
125    /// - `check [--graph]` validates the graph without constructing anything
126    ///   and prints a summary (or the module tree);
127    /// - `help` / `list` prints the commands;
128    /// - `introspect [--json]` validates the graph without constructing
129    ///   anything and prints it as JSON ([`GraphReport::to_json`]);
130    /// - `<name> [args...]` boots the app, runs the registered command, then
131    ///   shuts the app down gracefully; a command marked
132    ///   [offline](CommandSpec::offline) skips the boot and the shutdown hooks;
133    /// - no command runs `serve` if a module registers it, else `help`.
134    pub async fn run_with_args(self, args: Vec<String>) -> Result<(), BoxError> {
135        let mut args = args.into_iter();
136        let command = args.next();
137        let rest: Vec<String> = args.collect();
138        match command.as_deref() {
139            Some("check") => {
140                let report = self.validate()?;
141                if rest.iter().any(|a| a == "--graph") {
142                    println!("{report}");
143                } else {
144                    let providers: usize = report.modules.iter().map(|m| m.providers.len()).sum();
145                    println!(
146                        "module graph OK: {} modules, {providers} providers",
147                        report.modules.len().saturating_sub(1)
148                    );
149                }
150                Ok(())
151            }
152            Some("introspect") => {
153                println!("{}", self.validate()?.to_json());
154                Ok(())
155            }
156            Some("help" | "list" | "--help" | "-h") => {
157                print!("{}", help_text(&self.validate()?));
158                Ok(())
159            }
160            Some(name) => {
161                let name = name.to_owned();
162                let graph = self.graph()?;
163                self.boot_and_run(graph, name, rest).await
164            }
165            None => {
166                let graph = self.graph()?;
167                if graph.has_command("serve") {
168                    self.boot_and_run(graph, "serve".to_owned(), rest).await
169                } else {
170                    print!("{}", help_text(&graph.report()));
171                    Ok(())
172                }
173            }
174        }
175    }
176
177    /// Runs the app from `std::env::args` on a new multi-threaded runtime.
178    /// Ctrl-C (and SIGTERM on Unix) cancels the shutdown token, so `serve`
179    /// and workers stop; the app then shuts down within the shutdown timeout.
180    pub fn run(self) -> Result<(), BoxError> {
181        let runtime = tokio::runtime::Builder::new_multi_thread()
182            .enable_all()
183            .build()?;
184        let args = std::env::args_os()
185            .skip(1)
186            .map(|arg| arg.to_string_lossy().into_owned())
187            .collect();
188        let token = self.shutdown.clone();
189        runtime.block_on(async move {
190            let signals = tokio::spawn(cancel_on_signal(token));
191            let result = self.run_with_args(args).await;
192            signals.abort();
193            result
194        })
195    }
196
197    /// Checks the command exists (without constructing anything), boots from
198    /// `graph`, runs the command and shuts down. The command's error wins over
199    /// a shutdown error.
200    async fn boot_and_run(
201        self,
202        graph: Graph,
203        name: String,
204        args: Vec<String>,
205    ) -> Result<(), BoxError> {
206        let Some(command) = graph.commands().find(|c| c.name == name).cloned() else {
207            return Err(KernelError::UnknownCommand { name }.into());
208        };
209        if command.offline {
210            // No boot: the command builds what it asks for, and nothing runs
211            // at start or at shutdown.
212            let ctx = AppContext::from_inner(Arc::new(AppInner::new(
213                graph,
214                self.shutdown.clone(),
215                Some(command.clone()),
216            )));
217            let result = (command.run)(ctx.clone(), args).await;
218            ctx.inner.shutdown.cancel();
219            return result;
220        }
221        let app = self.boot_graph(graph, Some(command)).await?;
222        let result = app.run_command(&name, args).await;
223        let shutdown = app.shutdown().await;
224        result.and(shutdown)
225    }
226}
227
228/// Waits for a shutdown signal, then cancels `token`.
229async fn cancel_on_signal(token: CancellationToken) {
230    shutdown_signal().await;
231    tracing::info!("shutdown signal received, stopping");
232    token.cancel();
233}
234
235#[cfg(unix)]
236async fn shutdown_signal() {
237    use tokio::signal::unix::{SignalKind, signal};
238    match signal(SignalKind::terminate()) {
239        Ok(mut terminate) => {
240            tokio::select! {
241                result = tokio::signal::ctrl_c() => if result.is_err() { std::future::pending::<()>().await },
242                _ = terminate.recv() => {}
243            }
244        }
245        Err(_) => {
246            if tokio::signal::ctrl_c().await.is_err() {
247                std::future::pending::<()>().await;
248            }
249        }
250    }
251}
252
253#[cfg(not(unix))]
254async fn shutdown_signal() {
255    if tokio::signal::ctrl_c().await.is_err() {
256        // No console to listen on: only an explicit cancel stops the app.
257        std::future::pending::<()>().await;
258    }
259}
260
261impl fmt::Debug for AppBuilder {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        f.debug_struct("AppBuilder")
264            .field(
265                "modules",
266                &self.modules.iter().map(|m| m.name()).collect::<Vec<_>>(),
267            )
268            .field(
269                "overrides",
270                &self
271                    .overrides
272                    .iter()
273                    .map(|o| o.key.to_string())
274                    .collect::<Vec<_>>(),
275            )
276            .field("shutdown_timeout", &self.shutdown_timeout)
277            .finish()
278    }
279}
280
281/// A registered lifecycle provider and the name of its module.
282type Hook = (&'static str, Arc<dyn Lifecycle>);
283
284/// A booted app. Dropping it without [`shutdown`](App::shutdown) cancels the
285/// shutdown token but runs no hooks.
286pub struct App {
287    ctx: AppContext,
288    hooks: Vec<Hook>,
289    shutdown_timeout: Duration,
290}
291
292impl App {
293    /// The app context.
294    pub fn ctx(&self) -> &AppContext {
295        &self.ctx
296    }
297
298    /// Runs the registered command `name` against this app.
299    pub async fn run_command(&self, name: &str, args: Vec<String>) -> Result<(), BoxError> {
300        let command = self
301            .ctx
302            .inner
303            .graph
304            .commands()
305            .find(|c| c.name == name)
306            .cloned()
307            .ok_or_else(|| KernelError::UnknownCommand {
308                name: name.to_owned(),
309            })?;
310        tracing::debug!(command = name, "running command");
311        (command.run)(self.ctx.clone(), args).await
312    }
313
314    /// Graceful shutdown: cancels the shutdown token, waits for tasks spawned
315    /// on the [tracker](AppContext::tracker), then runs `on_shutdown` hooks in
316    /// reverse dependency order. Each phase is bounded by the shutdown timeout.
317    pub async fn shutdown(mut self) -> Result<(), BoxError> {
318        let hooks = std::mem::take(&mut self.hooks);
319        let ctx = self.ctx.clone();
320        let timeout = self.shutdown_timeout;
321        ctx.inner.shutdown.cancel();
322        ctx.inner.tracker.close();
323
324        let drained = tokio::time::timeout(timeout, ctx.inner.tracker.wait())
325            .await
326            .is_ok();
327        let run_hooks = async {
328            let mut errors = Vec::new();
329            for (module, hooks) in hooks.iter().rev() {
330                if let Err(source) = hooks.on_shutdown(ctx.clone()).await {
331                    errors.push(KernelError::Lifecycle {
332                        module,
333                        hook: "on_shutdown",
334                        source,
335                    });
336                }
337            }
338            errors
339        };
340        let errors = tokio::time::timeout(timeout, run_hooks).await;
341
342        if !drained {
343            return Err(format!(
344                "graceful shutdown timed out after {timeout:?} waiting for tracked tasks"
345            )
346            .into());
347        }
348        match errors {
349            Err(_) => Err(format!(
350                "graceful shutdown timed out after {timeout:?} in on_shutdown hooks"
351            )
352            .into()),
353            Ok(errors) if errors.is_empty() => Ok(()),
354            Ok(errors) => Err(Box::new(BootErrors(errors))),
355        }
356    }
357}
358
359impl Drop for App {
360    fn drop(&mut self) {
361        self.ctx.inner.shutdown.cancel();
362    }
363}
364
365impl fmt::Debug for App {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        f.debug_struct("App")
368            .field("ctx", &self.ctx)
369            .finish_non_exhaustive()
370    }
371}
372
373/// A value contributed with [`ModuleBuilder::contribute`](crate::ModuleBuilder::contribute)
374/// and the module that contributed it.
375pub struct Contributed<C> {
376    /// The contributing module.
377    pub module: ModuleInfo,
378    /// The contributed value.
379    pub value: Arc<C>,
380}
381
382impl<C> Clone for Contributed<C> {
383    fn clone(&self) -> Self {
384        Self {
385            module: self.module.clone(),
386            value: self.value.clone(),
387        }
388    }
389}
390
391impl<C: fmt::Debug> fmt::Debug for Contributed<C> {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        f.debug_struct("Contributed")
394            .field("module", &self.module.name)
395            .field("value", &self.value)
396            .finish()
397    }
398}
399
400/// A module of a booted app.
401#[derive(Clone, Debug)]
402pub struct ModuleInfo {
403    /// The module id.
404    pub id: ModuleId,
405    /// The module name.
406    pub name: &'static str,
407    /// Whether the module's exports are visible everywhere.
408    pub global: bool,
409}
410
411/// A cheap, cloneable handle to a booted app.
412#[derive(Clone)]
413pub struct AppContext {
414    pub(crate) inner: Arc<AppInner>,
415}
416
417impl AppContext {
418    pub(crate) fn from_inner(inner: Arc<AppInner>) -> Self {
419        Self { inner }
420    }
421
422    /// A handle that does not keep the app alive. Providers that need the
423    /// app after boot (an event bus, a scheduler) hold this instead of an
424    /// `AppContext`, so an app dropped without `shutdown` is still freed.
425    pub fn downgrade(&self) -> WeakAppContext {
426        WeakAppContext {
427            inner: Arc::downgrade(&self.inner),
428        }
429    }
430
431    /// Service locator: resolves the unnamed provider of `T` from any module,
432    /// ignoring visibility. Meant for lifecycle hooks, commands and glue code;
433    /// providers use constructor injection instead.
434    pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Arc<T>, KernelError> {
435        self.locate::<T>(ProviderKey::of::<T>()).await
436    }
437
438    /// Like [`get`](AppContext::get), but `None` when no provider of `T` exists
439    /// (or it cannot be built; that failure is logged).
440    pub async fn try_get<T: ?Sized + Send + Sync + 'static>(&self) -> Option<Arc<T>> {
441        match self.get::<T>().await {
442            Ok(value) => Some(value),
443            Err(KernelError::MissingProvider { .. }) => None,
444            Err(error) => {
445                tracing::warn!(error = %error, "optional provider could not be resolved");
446                None
447            }
448        }
449    }
450
451    /// Service locator for the provider of `T` registered under `name`.
452    pub async fn get_named<T: ?Sized + Send + Sync + 'static>(
453        &self,
454        name: &str,
455    ) -> Result<Arc<T>, KernelError> {
456        self.locate::<T>(ProviderKey::named::<T>(name.to_owned()))
457            .await
458    }
459
460    /// Resolves every multi-binding of `T` (see [`ModuleBuilder::multi`](crate::ModuleBuilder::multi)),
461    /// in module dependency order.
462    pub async fn get_all<T: ?Sized + Send + Sync + 'static>(
463        &self,
464    ) -> Result<Vec<Arc<T>>, KernelError> {
465        self.root_resolver().get_all::<T>().await
466    }
467
468    /// How many multi-bindings of `T` the app registers, read from the
469    /// module graph without resolving any (so a provider's factory can call
470    /// it even when those multi-bindings depend on the provider). A module
471    /// decides with it, once at boot, whether anybody listens: navree-db
472    /// skips preparing change events in an app with no `dyn ChangeObserver`.
473    pub fn multi_count<T: ?Sized + 'static>(&self) -> usize {
474        self.inner.graph.multi_of(std::any::TypeId::of::<T>()).len()
475    }
476
477    /// Every value of type `C` contributed by any module, modules in dependency
478    /// order, then in registration order.
479    pub fn contributions<C: Send + Sync + 'static>(&self) -> Vec<Contributed<C>> {
480        let graph = &self.inner.graph;
481        let mut collected = Vec::new();
482        for &m in &graph.order {
483            for (type_id, value) in &graph.modules[m].contributions {
484                if *type_id == TypeId::of::<C>()
485                    && let Ok(value) = value.clone().downcast::<C>()
486                {
487                    collected.push(Contributed {
488                        module: self.module_info(m),
489                        value,
490                    });
491                }
492            }
493        }
494        collected
495    }
496
497    /// A resolver with the visibility of `module` (no request scope).
498    pub fn resolver_for(&self, module: ModuleId) -> Resolver {
499        Resolver::new(self.inner.clone(), module, None)
500    }
501
502    /// A resolver with the visibility of `module` that memoizes request-scoped
503    /// providers in `scope` (one scope per HTTP request, job run, command, ...).
504    pub fn request_resolver(&self, module: ModuleId, scope: RequestScope) -> Resolver {
505        Resolver::new(self.inner.clone(), module, Some(scope))
506    }
507
508    /// Every registered command, modules in dependency order.
509    pub fn commands(&self) -> Vec<CommandSpec> {
510        self.inner.graph.commands().cloned().collect()
511    }
512
513    /// The command this app was booted to run by
514    /// [`AppBuilder::run_with_args`] (or [`AppBuilder::run`]), known from
515    /// the first provider built on; `None` after a plain
516    /// [`boot`](AppBuilder::boot). Providers check
517    /// [`CommandSpec::stdio`] here before writing to standard output.
518    pub fn command(&self) -> Option<&CommandSpec> {
519        self.inner.command.as_ref()
520    }
521
522    /// Every module of the app in dependency order (imports first).
523    pub fn modules(&self) -> Vec<ModuleInfo> {
524        self.inner
525            .graph
526            .order
527            .iter()
528            .filter(|&&m| m != ROOT)
529            .map(|&m| self.module_info(m))
530            .collect()
531    }
532
533    /// Cancelled when the app shuts down; long-running tasks should watch it.
534    pub fn shutdown_token(&self) -> CancellationToken {
535        self.inner.shutdown.clone()
536    }
537
538    /// Spawn background tasks here; graceful shutdown waits for them.
539    pub fn tracker(&self) -> TaskTracker {
540        self.inner.tracker.clone()
541    }
542
543    fn module_info(&self, m: usize) -> ModuleInfo {
544        let module = &self.inner.graph.modules[m];
545        ModuleInfo {
546            id: module.id,
547            name: module.name,
548            global: module.global,
549        }
550    }
551
552    async fn locate<T: ?Sized + Send + Sync + 'static>(
553        &self,
554        key: ProviderKey,
555    ) -> Result<Arc<T>, KernelError> {
556        let index = self.inner.graph.locate(&key, "`AppContext`")?;
557        self.root_resolver().resolve_as::<T>(index, &key).await
558    }
559
560    /// A resolver with the visibility of the implicit app root.
561    fn root_resolver(&self) -> Resolver {
562        Resolver::new(self.inner.clone(), self.inner.graph.modules[ROOT].id, None)
563    }
564
565    /// Constructs every singleton (modules in dependency order), then runs
566    /// `on_init` and `on_bootstrap`. Returns the lifecycle providers.
567    async fn start(&self) -> Result<Vec<Hook>, KernelError> {
568        let graph = &self.inner.graph;
569        let mut hooks = Vec::new();
570        for &m in &graph.order {
571            let resolver = self.resolver_for(graph.modules[m].id);
572            for &p in &graph.modules[m].providers {
573                if graph.providers[p].def.scope == Scope::Singleton {
574                    resolver.resolve_index(p).await?;
575                }
576            }
577            for registration in &graph.modules[m].lifecycles {
578                hooks.push((
579                    graph.modules[m].name,
580                    (registration.resolve)(resolver.clone()).await?,
581                ));
582            }
583        }
584        for (module, hooks) in &hooks {
585            hooks
586                .on_init(self.clone())
587                .await
588                .map_err(|source| KernelError::Lifecycle {
589                    module,
590                    hook: "on_init",
591                    source,
592                })?;
593        }
594        for (module, hooks) in &hooks {
595            hooks
596                .on_bootstrap(self.clone())
597                .await
598                .map_err(|source| KernelError::Lifecycle {
599                    module,
600                    hook: "on_bootstrap",
601                    source,
602                })?;
603        }
604        Ok(hooks)
605    }
606}
607
608impl fmt::Debug for AppContext {
609    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610        f.debug_struct("AppContext")
611            .field("modules", &self.inner.graph.modules.len())
612            .field("providers", &self.inner.graph.providers.len())
613            .finish()
614    }
615}
616
617/// A weak handle to a booted app ([`AppContext::downgrade`]): it does not
618/// keep the app alive, and [`upgrade`](WeakAppContext::upgrade) returns
619/// `None` once the app is dropped.
620#[derive(Clone)]
621pub struct WeakAppContext {
622    inner: Weak<AppInner>,
623}
624
625impl WeakAppContext {
626    /// The app, if it is still alive.
627    pub fn upgrade(&self) -> Option<AppContext> {
628        self.inner.upgrade().map(AppContext::from_inner)
629    }
630}
631
632impl fmt::Debug for WeakAppContext {
633    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634        f.debug_struct("WeakAppContext")
635            .field("alive", &(self.inner.strong_count() > 0))
636            .finish()
637    }
638}