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::{PassedModule, ProviderDef, value_def};
12use crate::command::help_text;
13use crate::container::{AppInner, RequestScope};
14use crate::graph::{Graph, GraphReport, ROOT};
15use crate::introspect::introspect_json;
16use crate::publish;
17use crate::resolver::Stack;
18use crate::{
19 BootErrors, BoxError, CommandSpec, KernelError, Lifecycle, Module, ModuleId, PluginInfo,
20 PluginsReport, ProviderKey, Resolver, Scope,
21};
22
23/// Default time allowed for each phase of a graceful shutdown.
24const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
25
26/// Entry point: `Navree::app().module(...).run()`.
27#[derive(Debug)]
28pub struct Navree;
29
30impl Navree {
31 /// Starts building an app.
32 pub fn app() -> AppBuilder {
33 AppBuilder::default()
34 }
35}
36
37/// Collects the root modules of an app, then validates, boots or runs it.
38pub struct AppBuilder {
39 /// The root modules, each with the type it was passed as.
40 modules: Vec<PassedModule>,
41 overrides: Vec<ProviderDef>,
42 shutdown: CancellationToken,
43 shutdown_timeout: Duration,
44}
45
46impl Default for AppBuilder {
47 fn default() -> Self {
48 Self {
49 modules: Vec::new(),
50 overrides: Vec::new(),
51 shutdown: CancellationToken::new(),
52 shutdown_timeout: DEFAULT_SHUTDOWN_TIMEOUT,
53 }
54 }
55}
56
57impl AppBuilder {
58 /// Adds a root module (imported by the implicit app root).
59 pub fn module(mut self, m: impl Module) -> Self {
60 self.modules.push(PassedModule::of(m));
61 self
62 }
63
64 /// Adds a root module that was given to another builder first (the
65 /// testing app's), with the type it was given as there. Not public API;
66 /// Navree's own crates use it.
67 #[doc(hidden)]
68 pub fn passed_module(mut self, module: PassedModule) -> Self {
69 self.modules.push(module);
70 self
71 }
72
73 /// Replaces the unnamed provider of `T` wherever it is registered with
74 /// `value` (its factory never runs); registers `value` globally if no
75 /// module provides `T`. Meant for tests and fakes.
76 pub fn override_value<T: ?Sized + Send + Sync + 'static>(mut self, value: Arc<T>) -> Self {
77 self.overrides
78 .push(value_def(ProviderKey::of::<T>(), value));
79 self
80 }
81
82 /// How long graceful shutdown waits for tracked tasks, and then for the
83 /// `on_shutdown` hooks (default 30 s each).
84 pub fn shutdown_timeout(mut self, d: Duration) -> Self {
85 self.shutdown_timeout = d;
86 self
87 }
88
89 /// Validates the module graph without constructing any provider.
90 pub fn validate(&self) -> Result<GraphReport, BootErrors> {
91 self.graph().map(|graph| graph.report())
92 }
93
94 /// Validates the module graph (as [`validate`](AppBuilder::validate)) and
95 /// reports its plugins and what each of their modules adds. Nothing is
96 /// built.
97 ///
98 /// ```no_run
99 /// use navree_kernel::{Module, ModuleBuilder, Navree};
100 ///
101 /// struct AnnouncementsModule;
102 ///
103 /// impl Module for AnnouncementsModule {
104 /// fn register(&self, m: &mut ModuleBuilder) {
105 /// m.plugin(navree_kernel::plugin_info!(title = "Announcements"));
106 /// }
107 /// }
108 ///
109 /// fn main() -> Result<(), navree_kernel::BootErrors> {
110 /// let report = Navree::app().module(AnnouncementsModule).plugin_report()?;
111 /// println!("{report}");
112 /// Ok(())
113 /// }
114 /// ```
115 pub fn plugin_report(&self) -> Result<PluginsReport, BootErrors> {
116 self.graph().map(|graph| graph.plugins_report())
117 }
118
119 /// Validates the graph, constructs every singleton (modules in dependency
120 /// order), then runs `on_init` and `on_bootstrap` hooks.
121 pub async fn boot(self) -> Result<App, BootErrors> {
122 let graph = self.graph()?;
123 self.boot_graph(graph, None).await
124 }
125
126 /// Walks and validates the modules (calls every `register` once).
127 fn graph(&self) -> Result<Graph, BootErrors> {
128 Graph::build_passed(&self.modules, &self.overrides)
129 }
130
131 /// Boots from an already validated graph, so `register` is not called
132 /// again; `command` is the command the app is booted to run.
133 async fn boot_graph(
134 self,
135 graph: Graph,
136 command: Option<CommandSpec>,
137 ) -> Result<App, BootErrors> {
138 let ctx = AppContext::from_inner(Arc::new(AppInner::new(
139 graph,
140 self.shutdown.clone(),
141 command,
142 )));
143 match ctx.start().await {
144 Ok(hooks) => {
145 tracing::debug!(modules = ctx.inner.graph.modules.len(), "navree app booted");
146 Ok(App {
147 ctx,
148 hooks,
149 shutdown_timeout: self.shutdown_timeout,
150 })
151 }
152 Err(error) => {
153 ctx.inner.shutdown.cancel();
154 Err(error.into())
155 }
156 }
157 }
158}
159
160impl AppBuilder {
161 /// Runs a command line (without the program name):
162 ///
163 /// - `check [--graph]` validates the graph without constructing anything
164 /// and prints a summary (or the module tree);
165 /// - `help` / `list` prints the commands;
166 /// - `introspect [--json]` validates the graph without constructing
167 /// anything and prints it as JSON ([`GraphReport::to_json`], with a
168 /// `"plugins"` array as [`PluginsReport::to_json`] writes it);
169 /// - `plugins [--json]` validates the graph without constructing anything
170 /// and prints its plugins and what each adds ([`PluginsReport`], or its
171 /// JSON with `--json`); when the checks refuse the graph, it prints the
172 /// listing first and fails with the refusals;
173 /// - `plugin:publish <plugin> [--tag views|locales|config|files] [--force]
174 /// [--dry-run]` validates the graph without constructing anything and
175 /// copies the files the plugin (a namespace or a plugin's name) ships
176 /// into the app's folders below the current directory, one line per
177 /// file; an existing file is kept without `--force`, every path is
178 /// checked before the first write, and `--dry-run` writes nothing. The
179 /// `config` tag (and no `--tag`) runs the app's
180 /// `config:publish --plugin <namespace>`, when the app has that command,
181 /// after the files are checked and before they are written, so a
182 /// refusal from either leaves nothing written;
183 /// - `<name> [args...]` boots the app, runs the registered command, then
184 /// shuts the app down gracefully; a command marked
185 /// [offline](CommandSpec::offline) skips the boot and the shutdown hooks;
186 /// - no command runs `serve` if a module registers it, else `help`.
187 ///
188 /// The built-ins `plugins` and `plugin:publish` yield: when a module of the
189 /// app registers a command of one of these names, that command runs
190 /// instead, with its arguments, and `help` and `introspect` no longer list
191 /// the built-in. A module of a plugin that is not one of the framework's own
192 /// may not register a command of a built-in's name.
193 pub async fn run_with_args(self, args: Vec<String>) -> Result<(), BoxError> {
194 let mut args = args.into_iter();
195 let command = args.next();
196 let rest: Vec<String> = args.collect();
197 match command.as_deref() {
198 Some("check") => {
199 let report = self.validate()?;
200 if rest.iter().any(|a| a == "--graph") {
201 println!("{report}");
202 } else {
203 let providers: usize = report.modules.iter().map(|m| m.providers.len()).sum();
204 println!(
205 "module graph OK: {} modules, {providers} providers",
206 report.modules.len().saturating_sub(1)
207 );
208 }
209 Ok(())
210 }
211 Some("introspect") => {
212 let graph = self.graph()?;
213 println!(
214 "{}",
215 introspect_json(&graph.report(), &graph.plugins_report())
216 );
217 Ok(())
218 }
219 Some("plugins") => {
220 let graph = match self.graph() {
221 Ok(graph) => graph,
222 Err(refused) => {
223 // Which module acts for which plugin matters most when the
224 // checks refuse the graph: the listing comes before the errors.
225 if let Some(report) = Graph::plugins_of_refused(&self.modules) {
226 if rest.iter().any(|arg| arg == "--json") {
227 println!("{}", report.to_json());
228 } else {
229 println!("{report}");
230 }
231 }
232 return Err(refused.into());
233 }
234 };
235 if graph.has_command("plugins") {
236 return self.boot_and_run(graph, "plugins".to_owned(), rest).await;
237 }
238 let mut json = false;
239 for arg in &rest {
240 if arg == "--json" && !json {
241 json = true;
242 } else {
243 return Err(format!(
244 "plugins: unexpected argument `{arg}`; usage: plugins [--json]"
245 )
246 .into());
247 }
248 }
249 let report = graph.plugins_report();
250 if json {
251 println!("{}", report.to_json());
252 } else {
253 println!("{report}");
254 }
255 Ok(())
256 }
257 Some("plugin:publish") => {
258 let graph = self.graph()?;
259 if graph.has_command("plugin:publish") {
260 return self
261 .boot_and_run(graph, "plugin:publish".to_owned(), rest)
262 .await;
263 }
264 let root = std::env::current_dir()?;
265 // Every file is checked first and the app's `config:publish`
266 // (which checks before it writes) runs next; the files are
267 // written last, so a refusal from either leaves nothing
268 // written.
269 let planned = publish::run(&graph, &rest, &root)?;
270 if let Some(args) = planned.config_args.clone() {
271 self.boot_and_run(graph, "config:publish".to_owned(), args)
272 .await?;
273 }
274 for line in publish::write(&root, &planned)? {
275 println!("{line}");
276 }
277 if planned.dry_run {
278 println!("Nothing was written (--dry-run).");
279 }
280 Ok(())
281 }
282 Some("help" | "list" | "--help" | "-h") => {
283 print!("{}", help_text(&self.validate()?));
284 Ok(())
285 }
286 Some(name) => {
287 let name = name.to_owned();
288 let graph = self.graph()?;
289 self.boot_and_run(graph, name, rest).await
290 }
291 None => {
292 let graph = self.graph()?;
293 if graph.has_command("serve") {
294 self.boot_and_run(graph, "serve".to_owned(), rest).await
295 } else {
296 print!("{}", help_text(&graph.report()));
297 Ok(())
298 }
299 }
300 }
301 }
302
303 /// Runs the app from `std::env::args` on a new multi-threaded runtime.
304 /// Ctrl-C (and SIGTERM on Unix) cancels the shutdown token, so `serve`
305 /// and workers stop; the app then shuts down within the shutdown timeout.
306 pub fn run(self) -> Result<(), BoxError> {
307 let runtime = tokio::runtime::Builder::new_multi_thread()
308 .enable_all()
309 .build()?;
310 let args = std::env::args_os()
311 .skip(1)
312 .map(|arg| arg.to_string_lossy().into_owned())
313 .collect();
314 let token = self.shutdown.clone();
315 runtime.block_on(async move {
316 let signals = tokio::spawn(cancel_on_signal(token));
317 let result = self.run_with_args(args).await;
318 signals.abort();
319 result
320 })
321 }
322
323 /// Checks the command exists (without constructing anything), boots from
324 /// `graph`, runs the command and shuts down. The command's error wins over
325 /// a shutdown error.
326 async fn boot_and_run(
327 self,
328 graph: Graph,
329 name: String,
330 args: Vec<String>,
331 ) -> Result<(), BoxError> {
332 let Some(command) = graph.commands().find(|c| c.name == name).cloned() else {
333 return Err(KernelError::UnknownCommand { name }.into());
334 };
335 if command.offline {
336 // No boot: the command builds what it asks for, and nothing runs
337 // at start or at shutdown.
338 let ctx = AppContext::from_inner(Arc::new(AppInner::new(
339 graph,
340 self.shutdown.clone(),
341 Some(command.clone()),
342 )));
343 let result = (command.run)(ctx.clone(), args).await;
344 ctx.inner.shutdown.cancel();
345 return result;
346 }
347 let app = self.boot_graph(graph, Some(command)).await?;
348 let result = app.run_command(&name, args).await;
349 let shutdown = app.shutdown().await;
350 result.and(shutdown)
351 }
352}
353
354/// Waits for a shutdown signal, then cancels `token`.
355async fn cancel_on_signal(token: CancellationToken) {
356 shutdown_signal().await;
357 tracing::info!("shutdown signal received, stopping");
358 token.cancel();
359}
360
361#[cfg(unix)]
362async fn shutdown_signal() {
363 use tokio::signal::unix::{SignalKind, signal};
364 match signal(SignalKind::terminate()) {
365 Ok(mut terminate) => {
366 tokio::select! {
367 result = tokio::signal::ctrl_c() => if result.is_err() { std::future::pending::<()>().await },
368 _ = terminate.recv() => {}
369 }
370 }
371 Err(_) => {
372 if tokio::signal::ctrl_c().await.is_err() {
373 std::future::pending::<()>().await;
374 }
375 }
376 }
377}
378
379#[cfg(not(unix))]
380async fn shutdown_signal() {
381 if tokio::signal::ctrl_c().await.is_err() {
382 // No console to listen on: only an explicit cancel stops the app.
383 std::future::pending::<()>().await;
384 }
385}
386
387impl fmt::Debug for AppBuilder {
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 f.debug_struct("AppBuilder")
390 .field(
391 "modules",
392 &self
393 .modules
394 .iter()
395 .map(|passed| passed.module.name())
396 .collect::<Vec<_>>(),
397 )
398 .field(
399 "overrides",
400 &self
401 .overrides
402 .iter()
403 .map(|o| o.key.to_string())
404 .collect::<Vec<_>>(),
405 )
406 .field("shutdown_timeout", &self.shutdown_timeout)
407 .finish()
408 }
409}
410
411/// A registered lifecycle provider and the name of its module.
412type Hook = (&'static str, Arc<dyn Lifecycle>);
413
414/// A booted app. Dropping it without [`shutdown`](App::shutdown) cancels the
415/// shutdown token but runs no hooks.
416pub struct App {
417 ctx: AppContext,
418 hooks: Vec<Hook>,
419 shutdown_timeout: Duration,
420}
421
422impl App {
423 /// The app context.
424 pub fn ctx(&self) -> &AppContext {
425 &self.ctx
426 }
427
428 /// Runs the registered command `name` against this app.
429 pub async fn run_command(&self, name: &str, args: Vec<String>) -> Result<(), BoxError> {
430 let command = self
431 .ctx
432 .inner
433 .graph
434 .commands()
435 .find(|c| c.name == name)
436 .cloned()
437 .ok_or_else(|| KernelError::UnknownCommand {
438 name: name.to_owned(),
439 })?;
440 tracing::debug!(command = name, "running command");
441 (command.run)(self.ctx.clone(), args).await
442 }
443
444 /// Graceful shutdown: cancels the shutdown token, waits for tasks spawned
445 /// on the [tracker](AppContext::tracker), then runs `on_shutdown` hooks in
446 /// reverse dependency order. Each phase is bounded by the shutdown timeout.
447 pub async fn shutdown(mut self) -> Result<(), BoxError> {
448 let hooks = std::mem::take(&mut self.hooks);
449 let ctx = self.ctx.clone();
450 let timeout = self.shutdown_timeout;
451 ctx.inner.shutdown.cancel();
452 ctx.inner.tracker.close();
453
454 let drained = tokio::time::timeout(timeout, ctx.inner.tracker.wait())
455 .await
456 .is_ok();
457 let run_hooks = async {
458 let mut errors = Vec::new();
459 for (module, hooks) in hooks.iter().rev() {
460 if let Err(source) = hooks.on_shutdown(ctx.clone()).await {
461 errors.push(KernelError::Lifecycle {
462 module,
463 hook: "on_shutdown",
464 source,
465 });
466 }
467 }
468 errors
469 };
470 let errors = tokio::time::timeout(timeout, run_hooks).await;
471
472 if !drained {
473 return Err(format!(
474 "graceful shutdown timed out after {timeout:?} waiting for tracked tasks"
475 )
476 .into());
477 }
478 match errors {
479 Err(_) => Err(format!(
480 "graceful shutdown timed out after {timeout:?} in on_shutdown hooks"
481 )
482 .into()),
483 Ok(errors) if errors.is_empty() => Ok(()),
484 Ok(errors) => Err(Box::new(BootErrors(errors))),
485 }
486 }
487}
488
489impl Drop for App {
490 fn drop(&mut self) {
491 self.ctx.inner.shutdown.cancel();
492 }
493}
494
495impl fmt::Debug for App {
496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497 f.debug_struct("App")
498 .field("ctx", &self.ctx)
499 .finish_non_exhaustive()
500 }
501}
502
503/// A value contributed with [`ModuleBuilder::contribute`](crate::ModuleBuilder::contribute)
504/// and the module that contributed it.
505pub struct Contributed<C> {
506 /// The contributing module.
507 pub module: ModuleInfo,
508 /// The contributed value.
509 pub value: Arc<C>,
510}
511
512impl<C> Clone for Contributed<C> {
513 fn clone(&self) -> Self {
514 Self {
515 module: self.module.clone(),
516 value: self.value.clone(),
517 }
518 }
519}
520
521impl<C: fmt::Debug> fmt::Debug for Contributed<C> {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 f.debug_struct("Contributed")
524 .field("module", &self.module.name)
525 .field("value", &self.value)
526 .finish()
527 }
528}
529
530/// A module of a booted app.
531#[derive(Clone, Debug)]
532pub struct ModuleInfo {
533 /// The module id.
534 pub id: ModuleId,
535 /// The module name.
536 pub name: &'static str,
537 /// Whether the module's exports are visible everywhere.
538 pub global: bool,
539}
540
541/// A cheap, cloneable handle to a booted app.
542#[derive(Clone)]
543pub struct AppContext {
544 pub(crate) inner: Arc<AppInner>,
545 /// The singletons that were being built when this handle was handed out
546 /// (see `app_in_chain`), which its resolutions continue; empty for every
547 /// other handle.
548 chain: Stack,
549}
550
551impl AppContext {
552 pub(crate) fn from_inner(inner: Arc<AppInner>) -> Self {
553 Self {
554 inner,
555 chain: Stack::default(),
556 }
557 }
558
559 /// A handle to the app whose resolutions continue `chain`.
560 pub(crate) fn in_chain(inner: Arc<AppInner>, chain: Stack) -> Self {
561 Self { inner, chain }
562 }
563
564 /// A handle that does not keep the app alive. Providers that need the
565 /// app after boot (an event bus, a scheduler) hold this instead of an
566 /// `AppContext`, so an app dropped without `shutdown` is still freed.
567 pub fn downgrade(&self) -> WeakAppContext {
568 WeakAppContext {
569 inner: Arc::downgrade(&self.inner),
570 }
571 }
572
573 /// Service locator: resolves the unnamed provider of `T` from any module,
574 /// ignoring visibility. Meant for lifecycle hooks, commands and glue code;
575 /// providers use constructor injection instead.
576 pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Arc<T>, KernelError> {
577 self.locate::<T>(ProviderKey::of::<T>()).await
578 }
579
580 /// Like [`get`](AppContext::get), but `None` when no provider of `T` exists
581 /// (or it cannot be built; that failure is logged).
582 pub async fn try_get<T: ?Sized + Send + Sync + 'static>(&self) -> Option<Arc<T>> {
583 match self.get::<T>().await {
584 Ok(value) => Some(value),
585 Err(KernelError::MissingProvider { .. }) => None,
586 Err(error) => {
587 tracing::warn!(error = %error, "optional provider could not be resolved");
588 None
589 }
590 }
591 }
592
593 /// Service locator for the provider of `T` registered under `name`.
594 pub async fn get_named<T: ?Sized + Send + Sync + 'static>(
595 &self,
596 name: &str,
597 ) -> Result<Arc<T>, KernelError> {
598 self.locate::<T>(ProviderKey::named::<T>(name.to_owned()))
599 .await
600 }
601
602 /// Resolves every multi-binding of `T` (see [`ModuleBuilder::multi`](crate::ModuleBuilder::multi)),
603 /// in module dependency order.
604 pub async fn get_all<T: ?Sized + Send + Sync + 'static>(
605 &self,
606 ) -> Result<Vec<Arc<T>>, KernelError> {
607 self.root_resolver().get_all::<T>().await
608 }
609
610 /// How many multi-bindings of `T` the app registers, read from the
611 /// module graph without resolving any (so a provider's factory can call
612 /// it even when those multi-bindings depend on the provider). A module
613 /// decides with it, once at boot, whether anybody listens: navree-db
614 /// skips preparing change events in an app with no `dyn ChangeObserver`.
615 pub fn multi_count<T: ?Sized + 'static>(&self) -> usize {
616 self.inner.graph.multi_of(std::any::TypeId::of::<T>()).len()
617 }
618
619 /// Every value of type `C` contributed by any module, modules in dependency
620 /// order, then in registration order.
621 pub fn contributions<C: Send + Sync + 'static>(&self) -> Vec<Contributed<C>> {
622 let graph = &self.inner.graph;
623 let mut collected = Vec::new();
624 for &m in &graph.order {
625 for contribution in &graph.modules[m].contributions {
626 if contribution.type_id == TypeId::of::<C>()
627 && let Ok(value) = contribution.value.clone().downcast::<C>()
628 {
629 collected.push(Contributed {
630 module: self.module_info(m),
631 value,
632 });
633 }
634 }
635 }
636 collected
637 }
638
639 /// A resolver with the visibility of `module` (no request scope).
640 pub fn resolver_for(&self, module: ModuleId) -> Resolver {
641 Resolver::new(self.inner.clone(), module, None)
642 }
643
644 /// A resolver with the visibility of `module` that memoizes request-scoped
645 /// providers in `scope` (one scope per HTTP request, job run, command, ...).
646 pub fn request_resolver(&self, module: ModuleId, scope: RequestScope) -> Resolver {
647 Resolver::new(self.inner.clone(), module, Some(scope))
648 }
649
650 /// Every registered command, modules in dependency order.
651 pub fn commands(&self) -> Vec<CommandSpec> {
652 self.inner.graph.commands().cloned().collect()
653 }
654
655 /// The command this app was booted to run by
656 /// [`AppBuilder::run_with_args`] (or [`AppBuilder::run`]), known from
657 /// the first provider built on; `None` after a plain
658 /// [`boot`](AppBuilder::boot). Providers check
659 /// [`CommandSpec::stdio`] here before writing to standard output.
660 pub fn command(&self) -> Option<&CommandSpec> {
661 self.inner.command.as_ref()
662 }
663
664 /// Every module of the app in dependency order (imports first).
665 pub fn modules(&self) -> Vec<ModuleInfo> {
666 self.inner
667 .graph
668 .order
669 .iter()
670 .filter(|&&m| m != ROOT)
671 .map(|&m| self.module_info(m))
672 .collect()
673 }
674
675 /// The plugin `module` names itself, if it does.
676 ///
677 /// ```no_run
678 /// use navree_kernel::{Module, ModuleBuilder, ModuleId, Navree};
679 ///
680 /// struct AnnouncementsModule;
681 ///
682 /// impl Module for AnnouncementsModule {
683 /// fn register(&self, m: &mut ModuleBuilder) {
684 /// m.plugin(navree_kernel::plugin_info!(title = "Announcements"));
685 /// }
686 /// }
687 ///
688 /// #[tokio::main]
689 /// async fn main() -> Result<(), navree_kernel::BootErrors> {
690 /// let app = Navree::app().module(AnnouncementsModule).boot().await?;
691 /// let info = app.ctx().plugin(ModuleId::of::<AnnouncementsModule>());
692 /// assert_eq!(info.and_then(|info| info.title), Some("Announcements"));
693 /// Ok(())
694 /// }
695 /// ```
696 pub fn plugin(&self, module: ModuleId) -> Option<&PluginInfo> {
697 let graph = &self.inner.graph;
698 graph
699 .module_of(module)
700 .and_then(|m| graph.modules[m].plugin.as_ref())
701 }
702
703 /// Every plugin of the app and what each of their modules adds, read
704 /// from the module graph without building anything.
705 ///
706 /// ```no_run
707 /// use navree_kernel::{Module, ModuleBuilder, Navree};
708 ///
709 /// struct AnnouncementsModule;
710 ///
711 /// impl Module for AnnouncementsModule {
712 /// fn register(&self, m: &mut ModuleBuilder) {
713 /// m.plugin(navree_kernel::plugin_info!(title = "Announcements"));
714 /// }
715 /// }
716 ///
717 /// #[tokio::main]
718 /// async fn main() -> Result<(), navree_kernel::BootErrors> {
719 /// let app = Navree::app().module(AnnouncementsModule).boot().await?;
720 /// for plugin in app.ctx().plugins().plugins {
721 /// println!("{} {}", plugin.info.name, plugin.info.version);
722 /// }
723 /// Ok(())
724 /// }
725 /// ```
726 pub fn plugins(&self) -> PluginsReport {
727 self.inner.graph.plugins_report()
728 }
729
730 /// Cancelled when the app shuts down; long-running tasks should watch it.
731 pub fn shutdown_token(&self) -> CancellationToken {
732 self.inner.shutdown.clone()
733 }
734
735 /// Spawn background tasks here; graceful shutdown waits for them.
736 pub fn tracker(&self) -> TaskTracker {
737 self.inner.tracker.clone()
738 }
739
740 fn module_info(&self, m: usize) -> ModuleInfo {
741 let module = &self.inner.graph.modules[m];
742 ModuleInfo {
743 id: module.id,
744 name: module.name,
745 global: module.global,
746 }
747 }
748
749 async fn locate<T: ?Sized + Send + Sync + 'static>(
750 &self,
751 key: ProviderKey,
752 ) -> Result<Arc<T>, KernelError> {
753 let index = self.inner.graph.locate(&key, "`AppContext`")?;
754 self.root_resolver().resolve_as::<T>(index, &key).await
755 }
756
757 /// A resolver with the visibility of the implicit app root, continuing
758 /// this handle's chain.
759 fn root_resolver(&self) -> Resolver {
760 Resolver::new(self.inner.clone(), self.inner.graph.modules[ROOT].id, None)
761 .continuing(self.chain.clone())
762 }
763
764 /// Constructs every singleton (modules in dependency order), then runs
765 /// `on_init` and `on_bootstrap`. Returns the lifecycle providers.
766 async fn start(&self) -> Result<Vec<Hook>, KernelError> {
767 let graph = &self.inner.graph;
768 let mut hooks = Vec::new();
769 for &m in &graph.order {
770 let resolver = self.resolver_for(graph.modules[m].id);
771 for &p in &graph.modules[m].providers {
772 if graph.providers[p].def.scope == Scope::Singleton {
773 resolver.resolve_index(p).await?;
774 }
775 }
776 for registration in &graph.modules[m].lifecycles {
777 hooks.push((
778 graph.modules[m].name,
779 (registration.resolve)(resolver.clone()).await?,
780 ));
781 }
782 }
783 for (module, hooks) in &hooks {
784 hooks
785 .on_init(self.clone())
786 .await
787 .map_err(|source| KernelError::Lifecycle {
788 module,
789 hook: "on_init",
790 source,
791 })?;
792 }
793 for (module, hooks) in &hooks {
794 hooks
795 .on_bootstrap(self.clone())
796 .await
797 .map_err(|source| KernelError::Lifecycle {
798 module,
799 hook: "on_bootstrap",
800 source,
801 })?;
802 }
803 Ok(hooks)
804 }
805}
806
807impl fmt::Debug for AppContext {
808 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
809 f.debug_struct("AppContext")
810 .field("modules", &self.inner.graph.modules.len())
811 .field("providers", &self.inner.graph.providers.len())
812 .finish()
813 }
814}
815
816/// A weak handle to a booted app ([`AppContext::downgrade`]): it does not
817/// keep the app alive, and [`upgrade`](WeakAppContext::upgrade) returns
818/// `None` once the app is dropped.
819#[derive(Clone)]
820pub struct WeakAppContext {
821 inner: Weak<AppInner>,
822}
823
824impl WeakAppContext {
825 /// The app, if it is still alive.
826 pub fn upgrade(&self) -> Option<AppContext> {
827 self.inner.upgrade().map(AppContext::from_inner)
828 }
829}
830
831impl fmt::Debug for WeakAppContext {
832 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
833 f.debug_struct("WeakAppContext")
834 .field("alive", &(self.inner.strong_count() > 0))
835 .finish()
836 }
837}