1use 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
20const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
22
23#[derive(Debug)]
25pub struct Navree;
26
27impl Navree {
28 pub fn app() -> AppBuilder {
30 AppBuilder::default()
31 }
32}
33
34pub 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 pub fn module(mut self, m: impl Module) -> Self {
56 self.modules.push(Box::new(m));
57 self
58 }
59
60 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 pub fn shutdown_timeout(mut self, d: Duration) -> Self {
72 self.shutdown_timeout = d;
73 self
74 }
75
76 pub fn validate(&self) -> Result<GraphReport, BootErrors> {
78 self.graph().map(|graph| graph.report())
79 }
80
81 pub async fn boot(self) -> Result<App, BootErrors> {
84 let graph = self.graph()?;
85 self.boot_graph(graph, None).await
86 }
87
88 fn graph(&self) -> Result<Graph, BootErrors> {
90 Graph::build(&self.modules, &self.overrides)
91 }
92
93 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 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 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 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 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
228async 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 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
281type Hook = (&'static str, Arc<dyn Lifecycle>);
283
284pub struct App {
287 ctx: AppContext,
288 hooks: Vec<Hook>,
289 shutdown_timeout: Duration,
290}
291
292impl App {
293 pub fn ctx(&self) -> &AppContext {
295 &self.ctx
296 }
297
298 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 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
373pub struct Contributed<C> {
376 pub module: ModuleInfo,
378 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#[derive(Clone, Debug)]
402pub struct ModuleInfo {
403 pub id: ModuleId,
405 pub name: &'static str,
407 pub global: bool,
409}
410
411#[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 pub fn downgrade(&self) -> WeakAppContext {
426 WeakAppContext {
427 inner: Arc::downgrade(&self.inner),
428 }
429 }
430
431 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 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 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 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 pub fn multi_count<T: ?Sized + 'static>(&self) -> usize {
474 self.inner.graph.multi_of(std::any::TypeId::of::<T>()).len()
475 }
476
477 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 pub fn resolver_for(&self, module: ModuleId) -> Resolver {
499 Resolver::new(self.inner.clone(), module, None)
500 }
501
502 pub fn request_resolver(&self, module: ModuleId, scope: RequestScope) -> Resolver {
505 Resolver::new(self.inner.clone(), module, Some(scope))
506 }
507
508 pub fn commands(&self) -> Vec<CommandSpec> {
510 self.inner.graph.commands().cloned().collect()
511 }
512
513 pub fn command(&self) -> Option<&CommandSpec> {
519 self.inner.command.as_ref()
520 }
521
522 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 pub fn shutdown_token(&self) -> CancellationToken {
535 self.inner.shutdown.clone()
536 }
537
538 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 fn root_resolver(&self) -> Resolver {
562 Resolver::new(self.inner.clone(), self.inner.graph.modules[ROOT].id, None)
563 }
564
565 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#[derive(Clone)]
621pub struct WeakAppContext {
622 inner: Weak<AppInner>,
623}
624
625impl WeakAppContext {
626 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}