use core::{marker::PhantomData, time::Duration};
use std::{
any::{Any, TypeId},
collections::HashMap,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
thread::JoinHandle,
time::Instant,
};
use smol_bytes::Utf8Bytes;
use crate::drive::{
ItemId, NodeName, Outbox, Party, Registries, Resources, Shutdown, Streams, Taps, Thread,
engine::Join, lane::block_on,
};
use super::{
Cell, Declared, Enrolled, Farewell, Mount, Untorn,
ignition::joined,
resources::released,
teardown::{Collected, collected, farewell},
wiring::{LaneMount, MountedLane},
};
#[cfg(test)]
mod tests;
pub struct App<I> {
feeders: HashMap<TypeId, Box<dyn Any + Send>>,
lanes: HashMap<TypeId, (Box<dyn Any + Send>, Enrolled)>,
origins: HashMap<TypeId, Box<dyn Any + Send>>,
sources: Vec<Box<dyn Any + Send>>,
halts: Vec<crate::Stopper>,
senders: Vec<Box<dyn Any + Send>>,
bodies: Vec<JoinHandle<()>>,
tasks: Vec<Join>,
teardowns: Vec<Farewell>,
shutdown: Shutdown,
halted: Arc<AtomicBool>,
taps: Taps,
ctx: Arc<Resources>,
registries: Arc<Registries>,
indexer: PhantomData<fn() -> I>,
}
impl<I> core::fmt::Debug for App<I> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("App")
.field("feeders", &self.feeders.len())
.field("lanes", &self.lanes.len())
.field("origins", &self.origins.len())
.field("sources", &self.sources.len())
.field("halts", &self.halts.len())
.field("senders", &self.senders.len())
.field("bodies", &self.bodies.len())
.field("tasks", &self.tasks.len())
.field("teardowns", &self.teardowns.len())
.field("shutdown", &self.shutdown)
.field("halted", &self.halted.load(Ordering::Acquire))
.field("taps", &self.taps)
.field("ctx", &self.ctx)
.field("registries", &self.registries)
.finish()
}
}
enum Settling {
Forever,
Within(Duration),
Never,
}
impl<I> App<I> {
#[expect(
clippy::too_many_arguments,
reason = "the running world's parts, handed over by the one stage that assembles them; a \
parameter object here would be an `Ignition` with a second name"
)]
pub(super) fn new(
ctx: Arc<Resources>,
shutdown: Shutdown,
taps: Taps,
registries: Arc<Registries>,
senders: Vec<Box<dyn Any + Send>>,
sources: Vec<Box<dyn Any + Send>>,
halts: Vec<crate::Stopper>,
bodies: Vec<JoinHandle<()>>,
tasks: Vec<Join>,
teardowns: Vec<Farewell>,
feeders: HashMap<TypeId, Box<dyn Any + Send>>,
lanes: HashMap<TypeId, (Box<dyn Any + Send>, Enrolled)>,
origins: HashMap<TypeId, Box<dyn Any + Send>>,
) -> Self {
Self {
feeders,
lanes,
origins,
sources,
halts,
senders,
bodies,
tasks,
teardowns,
shutdown,
halted: Arc::new(AtomicBool::new(false)),
taps,
ctx,
registries,
indexer: PhantomData,
}
}
pub fn halt_on(&mut self, source: crate::conduit::Receiver<()>) {
let ringer = self.shutdown.ringer();
let halted = Arc::clone(&self.halted);
let _ = std::thread::Builder::new()
.name("ingraph-halt".to_owned())
.spawn(move || {
let _ = source.recv();
halted.store(true, Ordering::Release);
ringer.ring();
});
}
#[inline]
#[must_use]
pub fn halted(&self) -> bool {
self.halted.load(Ordering::Acquire)
}
#[inline]
#[must_use]
pub fn parties(&self) -> &[Party] {
self.shutdown.parties()
}
#[inline]
#[must_use]
pub fn context(&self) -> &Resources {
&self.ctx
}
#[inline]
#[must_use]
pub fn registries(&self) -> &Registries {
&self.registries
}
#[cfg(feature = "async-graphql")]
#[must_use]
pub fn install_registries<Q, M, S>(
&self,
builder: async_graphql::SchemaBuilder<Q, M, S>,
) -> async_graphql::SchemaBuilder<Q, M, S>
where
Q: async_graphql::ObjectType + 'static,
M: async_graphql::ObjectType + 'static,
S: async_graphql::SubscriptionType + 'static,
{
builder.data(Arc::clone(&self.registries))
}
#[inline]
#[must_use]
pub fn sources(&self) -> usize {
self.sources.len()
}
#[inline]
#[must_use]
pub fn feeder<N>(&self) -> Option<Outbox<ItemId, <Cell<N> as Mount<N>>::In>>
where
N: Declared,
Cell<N>: Mount<N>,
{
self
.feeders
.get(&TypeId::of::<N>())
.and_then(|feeder| feeder.downcast_ref::<Outbox<ItemId, <Cell<N> as Mount<N>>::In>>())
.cloned()
}
#[inline]
#[must_use]
pub fn feeders(&self) -> usize {
self.feeders.len()
}
#[inline]
#[must_use]
pub fn origin<S>(&self) -> Option<&super::Bridged<super::Ordered<S>>>
where
S: crate::DeclaredOrigin + super::Lived<<S as crate::DeclaredOrigin>::Mode>,
{
self
.origins
.get(&TypeId::of::<S>())
.and_then(|origin| origin.downcast_ref::<super::Bridged<super::Ordered<S>>>())
}
#[inline]
#[must_use]
pub fn origins(&self) -> usize {
self.origins.len()
}
#[must_use]
pub fn lane<N>(&mut self) -> Option<MountedLane<N, Thread, <N as Declared>::Mode>>
where
N: Declared + Streams<<N as Declared>::Mode> + Send + 'static,
<N as Streams<<N as Declared>::Mode>>::In: Send + 'static,
<N as Streams<<N as Declared>::Mode>>::Out: Send + 'static,
{
let (held, enrolled) = self.lanes.remove(&TypeId::of::<N>())?;
let mount = held
.downcast::<LaneMount<N, Thread, <N as Declared>::Mode>>()
.ok()?;
Some(mount.build(enrolled))
}
#[inline]
#[must_use]
pub fn lanes(&self) -> usize {
self.lanes.len()
}
pub fn until_stopped(&self) {
while !self.shutdown.is_finished() && !self.halted() {
if !self.shutdown.park(None) {
break;
}
}
}
#[must_use]
pub fn shutdown(self, deadline: Option<jiff::SignedDuration>) -> Stopped {
let settling = match deadline {
Some(deadline) => Settling::Within(Duration::try_from(deadline).unwrap_or(Duration::ZERO)),
None => Settling::Forever,
};
self.stop(settling)
}
#[must_use]
pub fn abort(self) -> Stopped {
self.stop(Settling::Never)
}
fn stop(self, settling: Settling) -> Stopped {
let Self {
mut feeders,
mut lanes,
origins,
mut sources,
halts,
mut senders,
bodies,
tasks,
teardowns,
shutdown,
halted: _,
taps,
ctx,
registries: _,
indexer: _,
} = self;
for party in shutdown.parties() {
party.announce();
}
for halt in &halts {
halt.announce();
}
drop(origins);
while let Some(source) = sources.pop() {
drop(source);
}
feeders.clear();
for (_node, (mount, enrolled)) in lanes.drain() {
drop(mount);
enrolled.settle();
}
senders.clear();
let overran = !Self::settle(&shutdown, &settling) && matches!(settling, Settling::Within(_));
let Collected {
mut chain,
unsettled,
} = collected(&shutdown);
let settled = shutdown.len() - unsettled.len();
let untorn = if unsettled.is_empty() && !matches!(settling, Settling::Never) {
chain.extend(teardowns);
let untorn = block_on(async {
joined(tasks).await;
let mut untorn = farewell(chain, &taps).await;
untorn.extend(released(ctx, &taps).await);
untorn
});
for engine in bodies {
let _ = engine.join();
}
untorn
} else {
drop(tasks);
drop(bodies);
let mut untorn: Vec<Untorn> = chain
.into_iter()
.chain(teardowns)
.map(Farewell::unsaid)
.collect();
untorn.extend(
ctx
.enrolled()
.map(|resource| Untorn::untold(resource.as_str())),
);
drop(ctx);
untorn
};
Stopped {
settled,
unsettled,
untorn,
overran,
}
}
fn settle(shutdown: &Shutdown, settling: &Settling) -> bool {
match settling {
Settling::Never => shutdown.is_finished(),
Settling::Forever => {
while !shutdown.is_finished() {
if !shutdown.park(None) {
break;
}
}
shutdown.is_finished()
}
Settling::Within(within) => {
let end = Instant::now() + *within;
loop {
if shutdown.is_finished() {
return true;
}
let now = Instant::now();
let Some(left) = end.checked_duration_since(now) else {
return false;
};
if !shutdown.park(Some(left)) {
return shutdown.is_finished();
}
}
}
}
}
}
#[derive(Debug)]
pub struct Stopped {
settled: usize,
unsettled: Vec<Utf8Bytes>,
untorn: Vec<Untorn>,
overran: bool,
}
impl Stopped {
#[inline]
#[must_use]
pub const fn settled(&self) -> usize {
self.settled
}
#[inline]
pub fn unsettled(&self) -> impl ExactSizeIterator<Item = &NodeName> {
self.unsettled.iter().map(|name| NodeName::new(name))
}
#[inline]
#[must_use]
pub fn untorn(&self) -> &[Untorn] {
&self.untorn
}
#[inline]
#[must_use]
pub const fn overran(&self) -> bool {
self.overran
}
#[inline]
#[must_use]
pub fn is_clean(&self) -> bool {
self.unsettled.is_empty() && self.untorn.is_empty()
}
}
impl core::fmt::Display for Stopped {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "stopped: {} settled", self.settled)?;
if self.overran {
write!(f, ", the deadline ran out")?;
}
for name in &self.unsettled {
write!(f, "\n - `{}` did not answer", name.as_str())?;
}
for untorn in &self.untorn {
write!(f, "\n - {untorn}")?;
}
Ok(())
}
}