use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};
use tokio::sync::OnceCell;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use crate::CommandSpec;
use crate::builder::Instance;
use crate::graph::Graph;
pub(crate) struct AppInner {
pub(crate) graph: Graph,
pub(crate) singletons: Vec<OnceCell<Instance>>,
pub(crate) shutdown: CancellationToken,
pub(crate) tracker: TaskTracker,
pub(crate) command: Option<CommandSpec>,
}
impl AppInner {
pub(crate) fn new(
graph: Graph,
shutdown: CancellationToken,
command: Option<CommandSpec>,
) -> Self {
let singletons = graph.providers.iter().map(|_| OnceCell::new()).collect();
Self {
graph,
singletons,
shutdown,
tracker: TaskTracker::new(),
command,
}
}
}
pub(crate) fn app_identity(inner: &Arc<AppInner>) -> usize {
Arc::as_ptr(inner).addr()
}
#[derive(Clone, Default)]
pub struct RequestScope {
cells: Arc<Mutex<ScopeCells>>,
}
type ScopeCells = HashMap<(usize, usize), Arc<OnceCell<Instance>>>;
impl RequestScope {
pub fn new() -> Self {
Self::default()
}
pub(crate) fn cell(&self, app: usize, provider: usize) -> Arc<OnceCell<Instance>> {
let mut cells = self.cells.lock().unwrap_or_else(PoisonError::into_inner);
cells.entry((app, provider)).or_default().clone()
}
}
impl fmt::Debug for RequestScope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let len = self.cells.lock().map_or(0, |cells| cells.len());
f.debug_struct("RequestScope")
.field("cached", &len)
.finish()
}
}