mod app;
mod channels;
mod constructor;
mod context;
mod create;
mod declared;
mod enablement;
mod feeder;
mod habitats;
mod ignition;
mod mount;
mod origin;
mod policies;
mod refusal;
mod resources;
mod section;
mod shutdown;
mod staging;
mod teardown;
mod wiring;
pub use app::{App, Stopped};
use channels::resolve_channels;
pub use channels::{ChannelShelf, Channels, Unchanneled};
pub use constructor::AsyncConstructor;
pub use context::Context;
pub use create::{
BareOptions, Creation, MandatoryOptionsError, MandatoryResourceOptionsError, NoDefaultOptions,
ResourceSourceError, UncataloguedResourceError,
};
pub use declared::{Blueprint, Declared, Grant, Upstream};
pub use enablement::Enablement;
pub use habitats::{
AsyncInitialize, Habitats, Initialize, Initializes, MakesNothing, UnboundCorpus,
UnbuiltTargetError,
};
pub use ignition::Ignition;
pub use mount::{Autonomous, Buffered, Cell, Mount, Streaming, Worn};
pub use resources::{MissingResourceError, Resources};
pub use origin::{
Bridged, Died, Lived, Mounted, Ordered, Produced, Tuned, drive_awaited_origin, drive_origin,
};
pub use policies::{PolicyShelf, Unpoliced};
pub use refusal::{
ArrangementError, DisabledUpstreamError, DroppingUnboundedError, FeederAbsentError,
GrantsNoStoreError, LandsNowhereError, PureLeafError, Refusal, SplitOriginError,
UnboundSlotError, UnbridgedOriginError, UndeclaredResourceError, UnknownGrantError,
UnknownNodeError, UnknownUpstreamError,
};
pub use section::NodeSection;
pub use shutdown::{Enrolled, Party, Shutdown};
pub use staging::Staging;
use teardown::Farewell;
pub use teardown::{AsyncTeardown, BoxedError, Goodbye, Posted, Untorn};
pub use wiring::{
Assembly, AutonomousBody, DeclaredResident, EdgeTypeError, LaneMount, MountBody, MountedLane,
NodeAttribution, NodeBody, ProductSeatError, StreamBody, StreamWires, TakenInboxError, Wiring,
};
pub use crate::{bare_options, bare_origin_options, bare_resource_options};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use smol_bytes::Utf8Bytes;
use crate::{
arrange::{ChannelGraph, EdgeId, NodeId},
drive::{AckMode, ChannelOptions, Effect, Failure, Feeder, Listen, Policies, TracingLevel},
resource::{AsyncResource, ResourceCatalog, ResourceDemand, ResourceKind, ResourceName},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlotBinding {
slot: Utf8Bytes,
kind: ResourceKind,
}
impl SlotBinding {
#[must_use]
pub fn new(slot: impl Into<Utf8Bytes>, kind: ResourceKind) -> Self {
Self {
slot: slot.into(),
kind,
}
}
#[inline]
#[must_use]
pub const fn slot(&self) -> &Utf8Bytes {
&self.slot
}
#[inline]
#[must_use]
pub const fn kind(&self) -> ResourceKind {
self.kind
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NodeWiring {
effect: Effect,
lane: bool,
door: bool,
intake: bool,
origin: bool,
tracing: TracingLevel,
}
impl NodeWiring {
#[inline]
#[must_use]
pub const fn new(effect: Effect) -> Self {
Self {
effect,
lane: false,
door: false,
intake: false,
origin: false,
tracing: TracingLevel::Info,
}
}
#[inline]
#[must_use]
pub const fn tracing(mut self, level: TracingLevel) -> Self {
self.tracing = level;
self
}
#[inline]
#[must_use]
pub const fn landing(mut self) -> Self {
self.effect = Effect::Lands;
self.lane = true;
self
}
#[inline]
#[must_use]
pub const fn answering(effect: Effect) -> Self {
Self {
effect,
lane: false,
door: true,
intake: false,
origin: false,
tracing: TracingLevel::Info,
}
}
#[inline]
#[must_use]
pub const fn drawing(mut self) -> Self {
self.intake = true;
self
}
#[inline]
#[must_use]
pub const fn originating(mut self) -> Self {
self.origin = true;
self
}
#[inline]
#[must_use]
pub const fn effect(&self) -> Effect {
self.effect
}
#[inline]
#[must_use]
pub const fn holds_lane(&self) -> bool {
self.lane
}
#[inline]
#[must_use]
pub const fn answers(&self) -> bool {
self.door
}
#[inline]
#[must_use]
pub const fn holds_intake(&self) -> bool {
self.intake
}
#[inline]
#[must_use]
pub const fn is_origin(&self) -> bool {
self.origin
}
#[inline]
#[must_use]
pub const fn tracing_level(&self) -> TracingLevel {
self.tracing
}
}
impl Default for NodeWiring {
#[inline]
fn default() -> Self {
Self::new(Effect::Pure)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UpstreamWiring {
listen: Listen,
ack: AckMode,
channel: Option<ChannelOptions>,
}
impl UpstreamWiring {
#[inline]
#[must_use]
pub const fn new(listen: Listen, ack: AckMode) -> Self {
Self {
listen,
ack,
channel: None,
}
}
#[inline]
#[must_use]
pub const fn with_channel(mut self, channel: ChannelOptions) -> Self {
self.channel = Some(channel);
self
}
#[inline]
#[must_use]
pub const fn channel(&self) -> Option<ChannelOptions> {
self.channel
}
#[inline]
#[must_use]
pub const fn listen(&self) -> Listen {
self.listen
}
#[inline]
#[must_use]
pub const fn ack(&self) -> AckMode {
self.ack
}
}
impl Default for UpstreamWiring {
#[inline]
fn default() -> Self {
Self::new(Listen::Channel, AckMode::Local)
}
}
#[derive(Debug)]
pub struct Plan {
graph: ChannelGraph,
nodes: Vec<NodeWiring>,
upstreams: Vec<UpstreamWiring>,
enablement: Enablement,
channels: Channels,
policies: Policies,
resources: ResourceCatalog,
demands: Vec<(NodeId, ResourceDemand)>,
mounts: Vec<ResourceDemand>,
bindings: Vec<SlotBinding>,
}
impl Plan {
#[must_use]
pub fn new(graph: ChannelGraph) -> Self {
let nodes = vec![NodeWiring::default(); graph.nodes().len()];
let upstreams = vec![UpstreamWiring::default(); graph.edges().len()];
Self {
graph,
nodes,
upstreams,
enablement: Enablement::new(),
channels: Channels::new(),
policies: Policies::new(),
resources: ResourceCatalog::new(),
demands: Vec::new(),
mounts: Vec::new(),
bindings: Vec::new(),
}
}
#[must_use]
pub fn wiring(mut self, node: NodeId, wiring: NodeWiring) -> Self {
if let Some(slot) = self.nodes.get_mut(node.index()) {
*slot = wiring;
}
self
}
#[must_use]
pub fn upstream(mut self, edge: EdgeId, wiring: UpstreamWiring) -> Self {
if let Some(slot) = self.upstreams.get_mut(edge.index()) {
*slot = wiring;
}
self
}
#[inline]
#[must_use]
pub fn with_enablement(mut self, enablement: Enablement) -> Self {
self.set_enablement(enablement);
self
}
#[inline]
pub fn set_enablement(&mut self, enablement: Enablement) -> &mut Self {
self.enablement = enablement;
self
}
#[inline]
#[must_use]
pub const fn enablement(&self) -> &Enablement {
&self.enablement
}
#[inline]
#[must_use]
pub fn with_channels(mut self, channels: Channels) -> Self {
self.set_channels(channels);
self
}
#[inline]
pub fn set_channels(&mut self, channels: Channels) -> &mut Self {
self.channels = channels;
self
}
#[inline]
#[must_use]
pub const fn channels(&self) -> &Channels {
&self.channels
}
#[inline]
#[must_use]
pub fn with_policies(mut self, policies: Policies) -> Self {
self.set_policies(policies);
self
}
#[inline]
pub fn set_policies(&mut self, policies: Policies) -> &mut Self {
self.policies = policies;
self
}
#[inline]
#[must_use]
pub const fn policies(&self) -> &Policies {
&self.policies
}
#[inline]
#[must_use]
pub fn with_resources(mut self, resources: ResourceCatalog) -> Self {
self.set_resources(resources);
self
}
#[inline]
pub fn set_resources(&mut self, resources: ResourceCatalog) -> &mut Self {
self.resources = resources;
self
}
#[inline]
#[must_use]
pub const fn resources(&self) -> &ResourceCatalog {
&self.resources
}
#[must_use]
pub fn demanding(mut self, node: NodeId, demand: ResourceDemand) -> Self {
self.demands.push((node, demand));
self
}
#[inline]
pub fn demands(&self) -> impl Iterator<Item = (NodeId, ResourceDemand)> {
self.demands.iter().copied()
}
#[must_use]
pub fn mounting(mut self, mount: ResourceDemand) -> Self {
self.mounts.push(mount);
self
}
#[inline]
pub fn mounts(&self) -> impl Iterator<Item = ResourceDemand> {
self.mounts.iter().copied()
}
#[must_use]
pub fn binding(mut self, binding: SlotBinding) -> Self {
self.bindings.push(binding);
self
}
#[inline]
pub fn bindings(&self) -> impl Iterator<Item = &SlotBinding> {
self.bindings.iter()
}
pub fn validate(self) -> Result<Wired, LaunchError> {
let Self {
graph,
nodes,
upstreams,
enablement,
channels,
policies,
resources,
demands,
mounts,
bindings,
} = self;
let mut refusals = Vec::new();
let declared: HashSet<&str> = graph.nodes().iter().map(crate::Node::name).collect();
let mut unknown: Vec<&str> = enablement
.names()
.filter(|name| !declared.contains(name))
.collect();
unknown.sort_unstable();
refusals.extend(
unknown
.into_iter()
.map(|name| Refusal::UnknownNode(UnknownNodeError::new(Utf8Bytes::from(name.to_owned())))),
);
let enabled: Vec<bool> = graph
.nodes()
.iter()
.map(|node| enablement.is_enabled(node.name()))
.collect();
let mut demanded: BTreeSet<&str> = mounts
.into_iter()
.map(|mount| mount.resource().as_str())
.collect();
for (node, demand) in demands {
if !enabled.get(node.index()).copied().unwrap_or(false) {
continue;
}
demanded.insert(demand.resource().as_str());
if !resources.declares(demand.resource()) {
refusals.push(Refusal::UndeclaredResource(Box::new(
UndeclaredResourceError::new(
node,
graph.nodes()[node.index()].name().into(),
demand.resource(),
),
)));
}
}
let mut bound: BTreeMap<Utf8Bytes, &'static ResourceName> = BTreeMap::new();
for binding in bindings {
match resources.sole(binding.kind()) {
Some(resource) => {
bound.insert(binding.slot().clone(), resource);
}
None => refusals.push(Refusal::UnboundSlot(Box::new(UnboundSlotError::new(
binding.slot().clone(),
binding.kind(),
resources.candidates(binding.kind()).collect(),
)))),
}
}
let mut publishes = vec![false; graph.nodes().len()];
let mut polls = vec![false; graph.nodes().len()];
let mut answers: Vec<bool> = nodes.iter().map(NodeWiring::answers).collect();
for (index, edge) in graph.edges().iter().enumerate() {
publishes[edge.from().index()] = true;
if upstreams[index].listen().is_poll() {
polls[edge.to().index()] = true;
}
if upstreams[index].listen().is_transient() {
answers[edge.to().index()] = true;
}
}
for (index, node) in graph.nodes().iter().enumerate() {
if !enabled[index] {
continue;
}
let wiring = nodes[index];
if wiring.effect().is_pure() && !publishes[index] && !polls[index] && !answers[index] {
refusals.push(Refusal::PureLeaf(PureLeafError::new(
NodeId::new(index),
node.name().into(),
)));
}
if wiring.effect().is_lands() && !wiring.holds_lane() && !publishes[index] {
refusals.push(Refusal::LandsNowhere(LandsNowhereError::new(
NodeId::new(index),
node.name().into(),
)));
}
}
for (index, edge) in graph.edges().iter().enumerate() {
let consumer = edge.to().index();
if !enabled[consumer] {
continue;
}
let Listen::Changes(Feeder::InGraph) = upstreams[index].listen() else {
continue;
};
let watched = edge.from().index();
if nodes[watched].effect().is_lands() {
continue;
}
refusals.push(Refusal::FeederAbsent(Box::new(FeederAbsentError::new(
EdgeId::new(index),
edge.to(),
graph.nodes()[consumer].name().into(),
edge.from(),
graph.nodes()[watched].name().into(),
))));
}
for (index, edge) in graph.edges().iter().enumerate() {
let consumer = edge.to().index();
let producer = edge.from().index();
if !enabled[consumer] || enabled[producer] {
continue;
}
let starved = upstreams[index].listen();
if starved.is_channel() || starved.is_transient() {
let producer_name = graph.nodes()[producer].name();
let refusal = Box::new(DisabledUpstreamError::new(
EdgeId::new(index),
edge.to(),
graph.nodes()[consumer].name().into(),
edge.from(),
producer_name.into(),
));
refusals.push(if starved.is_transient() {
Refusal::DisabledQueryUpstream(refusal)
} else {
Refusal::DisabledUpstream(refusal)
});
}
}
let mut listeners: Vec<Vec<Utf8Bytes>> = vec![Vec::new(); graph.nodes().len()];
for (index, edge) in graph.edges().iter().enumerate() {
let producer = edge.from().index();
let consumer = edge.to().index();
if !nodes[producer].is_origin() || !enabled[producer] || !enabled[consumer] {
continue;
}
let listen = upstreams[index].listen();
if listen.is_channel() {
listeners[producer].push(graph.nodes()[consumer].name().into());
continue;
}
refusals.push(Refusal::UnbridgedOrigin(Box::new(
UnbridgedOriginError::new(
EdgeId::new(index),
edge.from(),
graph.nodes()[producer].name().into(),
edge.to(),
graph.nodes()[consumer].name().into(),
listen.as_str(),
),
)));
}
for (index, consumers) in listeners.into_iter().enumerate() {
if consumers.len() < 2 {
continue;
}
refusals.push(Refusal::SplitOrigin(Box::new(SplitOriginError::new(
NodeId::new(index),
graph.nodes()[index].name().into(),
consumers,
))));
}
let resolved = resolve_channels(&graph, &upstreams, &channels);
if policies.overflow_policy().sheds() {
for (index, node) in graph.nodes().iter().enumerate() {
if !enabled[index] {
continue;
}
let Some(table) = resolved.get(index) else {
continue;
};
refusals.extend(
table
.iter()
.enumerate()
.filter(|(_, spec)| spec.is_unbounded())
.map(|(upstream, _)| {
Refusal::DroppingUnbounded(Box::new(DroppingUnboundedError::new(
NodeId::new(index),
node.name().into(),
upstream,
)))
}),
);
}
}
if !refusals.is_empty() {
return Err(LaunchError::Refused(refusals));
}
Ok(Wired {
graph,
nodes,
upstreams,
enabled,
channels: resolved,
policies,
resources,
demanded,
bound,
})
}
}
#[derive(Debug)]
pub struct Wired {
graph: ChannelGraph,
nodes: Vec<NodeWiring>,
upstreams: Vec<UpstreamWiring>,
enabled: Vec<bool>,
channels: Vec<Vec<ChannelOptions>>,
policies: Policies,
resources: ResourceCatalog,
demanded: BTreeSet<&'static str>,
bound: BTreeMap<Utf8Bytes, &'static ResourceName>,
}
impl Wired {
#[inline]
#[must_use]
pub const fn resources(&self) -> &ResourceCatalog {
&self.resources
}
#[inline]
#[must_use]
pub fn bound(&self, slot: &str) -> Option<&'static ResourceName> {
self.bound.get(slot).copied()
}
#[inline]
pub fn bindings(&self) -> impl Iterator<Item = (&str, &'static ResourceName)> {
self
.bound
.iter()
.map(|(slot, resource)| (slot.as_str(), *resource))
}
#[inline]
#[must_use]
pub fn create(&self) -> Creation<'_> {
Creation::new(self)
}
#[inline]
#[must_use]
pub const fn graph(&self) -> &ChannelGraph {
&self.graph
}
#[inline]
#[must_use]
pub fn demands(&self, resource: &ResourceName) -> bool {
self.demanded.contains(resource.as_str())
}
#[inline]
pub fn demanded(&self) -> impl Iterator<Item = &ResourceName> {
self.demanded.iter().copied().map(ResourceName::new)
}
#[inline]
pub fn demanded_at(&self) -> impl Iterator<Item = (&'static str, &ResourceName)> {
self.demanded.iter().copied().map(|name| {
let resource = ResourceName::new(name);
(self.resources.mount(resource).unwrap_or(name), resource)
})
}
#[inline]
#[must_use]
pub fn is_enabled(&self, node: NodeId) -> bool {
self.enabled.get(node.index()).copied().unwrap_or(false)
}
#[inline]
#[must_use]
pub fn node(&self, node: NodeId) -> Option<NodeWiring> {
self.nodes.get(node.index()).copied()
}
#[inline]
#[must_use]
pub fn upstream(&self, edge: EdgeId) -> Option<UpstreamWiring> {
self.upstreams.get(edge.index()).copied()
}
#[must_use]
pub fn channel(&self, node: NodeId, upstream: usize) -> ChannelOptions {
self
.channels
.get(node.index())
.and_then(|table| table.get(upstream))
.copied()
.unwrap_or(Wiring::SHIPPED)
}
#[inline]
#[must_use]
pub const fn policies(&self) -> &Policies {
&self.policies
}
#[inline]
pub fn running(&self) -> impl Iterator<Item = NodeId> {
self
.enabled
.iter()
.enumerate()
.filter(|&(_, on)| *on)
.map(|(index, _)| NodeId::new(index))
}
}
#[derive(Debug, derive_more::IsVariant)]
#[non_exhaustive]
pub enum LaunchError {
Refused(Vec<Refusal>),
Loading {
resource: &'static ResourceName,
error: Failure,
},
Initializing {
resource: &'static ResourceName,
error: Failure,
},
Construction {
node: Utf8Bytes,
error: Failure,
},
Wiring {
node: Utf8Bytes,
error: Failure,
},
Ignition {
node: Utf8Bytes,
error: Failure,
},
}
impl LaunchError {
#[inline]
#[must_use]
pub fn refusals(&self) -> &[Refusal] {
match self {
Self::Refused(refusals) => refusals,
Self::Loading { .. }
| Self::Initializing { .. }
| Self::Construction { .. }
| Self::Wiring { .. }
| Self::Ignition { .. } => &[],
}
}
#[inline]
pub(super) fn loading<R, E>(error: E) -> Self
where
R: AsyncResource,
E: core::error::Error + Send + Sync + 'static,
{
Self::Loading {
resource: ResourceName::of::<R>(),
error: Failure::new(error),
}
}
#[inline]
pub(super) fn initializing<R, E>(error: E) -> Self
where
R: AsyncResource,
E: core::error::Error + Send + Sync + 'static,
{
Self::Initializing {
resource: ResourceName::of::<R>(),
error: Failure::new(error),
}
}
#[inline]
pub(super) fn construction<E>(node: &str, error: E) -> Self
where
E: core::error::Error + Send + Sync + 'static,
{
Self::Construction {
node: Utf8Bytes::from(node.to_owned()),
error: Failure::new(error),
}
}
#[inline]
pub(super) fn wiring<E>(node: &str, error: E) -> Self
where
E: core::error::Error + Send + Sync + 'static,
{
Self::Wiring {
node: Utf8Bytes::from(node.to_owned()),
error: Failure::new(error),
}
}
#[inline]
pub(super) fn ignition<E>(node: &str, error: E) -> Self
where
E: core::error::Error + Send + Sync + 'static,
{
Self::Ignition {
node: Utf8Bytes::from(node.to_owned()),
error: Failure::new(error),
}
}
}
impl core::fmt::Display for LaunchError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Refused(refusals) => {
write!(f, "launch refused: {} thing(s) to fix", refusals.len())?;
for refusal in refusals {
write!(f, "\n - {refusal}")?;
}
Ok(())
}
Self::Loading { resource, error } => write!(
f,
"the resource `{}` could not be loaded: {error}",
resource.as_str()
),
Self::Initializing { resource, error } => write!(
f,
"the resource `{}` could not make the homes its declarations describe: {error}",
resource.as_str()
),
Self::Construction { node, error } => {
write!(
f,
"the node `{}` could not be built: {error}",
node.as_str()
)
}
Self::Wiring { node, error } => {
write!(
f,
"the node `{}` could not be wired: {error}",
node.as_str()
)
}
Self::Ignition { node, error } => {
write!(
f,
"the node `{}` could not be started: {error}",
node.as_str()
)
}
}
}
}
impl core::error::Error for LaunchError {
#[inline]
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Refused(_) => None,
Self::Loading { error, .. }
| Self::Initializing { error, .. }
| Self::Construction { error, .. }
| Self::Wiring { error, .. }
| Self::Ignition { error, .. } => Some(error),
}
}
}
#[cfg(test)]
mod honesty_tests;
#[cfg(test)]
mod tests;