use core::{
any::{Any, type_name},
time::Duration,
};
use std::{collections::BTreeMap, sync::Arc};
use agnostic_lite::RuntimeLite;
use smol_bytes::Utf8Bytes;
use crate::{
Block, Driven, Operator,
arrange::{EdgeId, NodeId},
drive::{
AckMode, Attached, Attaches, Attributes, Cadence, ChannelOptions, Door, Downstream, Helm,
Inbox, Invokes, ItemId, Listen, Outbox, Policies, Registries, Resident, Runs, Schedule, Socket,
StreamLane, StreamOptions, Streams, Taps, Thread, Unpolled, Upstreams, door, engine,
lane::block_on, open,
},
};
use super::{
Context, Declared, Enrolled, Ignition, LaunchError, Resources, Shutdown, Staging, Wired,
resources::released, teardown::farewell,
};
#[cfg(test)]
mod tests;
pub type NodeBody<O, I = Inbox<ItemId, <O as Operator>::In>, M = Block> =
(DeclaredResident<O, I, M>, Enrolled);
pub type DeclaredResident<O, I = Inbox<ItemId, <O as Operator>::In>, M = Block> =
Resident<O, (), NodeAttribution<O, M>, (), Unpolled, Downstream<<O as Driven<M>>::Out>, I, M>;
pub type NodeAttribution<O, M> = <O as Declared>::Attribution<<O as Driven<M>>::Out>;
pub type StreamBody<O, X = Thread, M = Block> = (StreamLane<O, StreamWires<O, M>, X, M>, Enrolled);
pub type StreamWires<O, M> = <O as Declared>::Wires<<O as Streams<M>>::Out>;
pub type MountedLane<O, X = Thread, M = Block> = (
StreamLane<O, StreamWires<O, M>, X, M>,
Inbox<ItemId, <O as Streams<M>>::In>,
Enrolled,
);
pub type AutonomousBody<O, M = Block> = (Helm<O, M>, crate::Stopper, Enrolled);
pub type MountBody<O, X = Thread, M = Block> = (LaneMount<O, X, M>, Enrolled);
pub struct LaneMount<O, X = Thread, M = Block>
where
O: Declared + Streams<M>,
{
instances: Vec<O>,
build: Box<dyn FnOnce(Vec<O>) -> Built<O, X, M> + Send>,
}
type Built<O, X, M> = (
StreamLane<O, StreamWires<O, M>, X, M>,
Inbox<ItemId, <O as Streams<M>>::In>,
);
type LaneParts<O> = (StreamWires<O, <O as Declared>::Mode>, crate::Effect);
impl<O, X, M> core::fmt::Debug for LaneMount<O, X, M>
where
O: Declared + Streams<M>,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("LaneMount")
.field("instances", &self.instances.len())
.finish_non_exhaustive()
}
}
impl<O, X, M> LaneMount<O, X, M>
where
O: Declared + Streams<M>,
{
#[inline]
#[must_use]
pub fn instances(&self) -> usize {
self.instances.len()
}
#[inline]
#[must_use]
pub fn into_instances(self) -> Vec<O> {
self.instances
}
#[must_use]
pub fn build(self, enrolled: Enrolled) -> MountedLane<O, X, M> {
let Self { instances, build } = self;
let (lane, intake) = build(instances);
(lane, intake, enrolled)
}
}
struct Wire {
carries: &'static str,
sender: Box<dyn Any + Send>,
receiver: Option<Box<dyn Any + Send>>,
}
impl Wire {
fn data<T: Send + 'static>(spec: ChannelOptions) -> Self {
let (outbox, inbox) = open::<ItemId, T>(spec);
Self {
carries: type_name::<Outbox<ItemId, T>>(),
sender: Box::new(outbox),
receiver: Some(Box::new(inbox)),
}
}
fn query<T: Send + 'static, R: Send + 'static>(capacity: usize) -> Self {
let (door, invokes) = door::<T, R>(capacity);
Self {
carries: type_name::<Door<T, R>>(),
sender: Box::new(door),
receiver: Some(Box::new(invokes)),
}
}
fn sender<S: Clone + 'static>(&self) -> Result<S, EdgeTypeError> {
self
.sender
.downcast_ref::<S>()
.cloned()
.ok_or_else(|| EdgeTypeError::new(self.carries, type_name::<S>()))
}
fn carries<S: 'static>(&self) -> Result<(), EdgeTypeError> {
if self.sender.downcast_ref::<S>().is_some() {
return Ok(());
}
Err(EdgeTypeError::new(self.carries, type_name::<S>()))
}
fn receiver<R: 'static>(&mut self) -> Result<R, TakenInboxError> {
self
.receiver
.take()
.map(|receiver| {
*receiver
.downcast::<R>()
.expect("both halves were minted together")
})
.ok_or_else(TakenInboxError::of::<R>)
}
}
struct EdgeSocket<'w> {
wires: &'w mut BTreeMap<(usize, usize), Wire>,
key: (usize, usize),
spec: ChannelOptions,
}
impl Socket for EdgeSocket<'_> {
type Refusal = EdgeTypeError;
#[inline]
fn open<T>(&mut self) -> Result<Outbox<ItemId, T>, EdgeTypeError>
where
T: Send + 'static,
{
self
.wires
.entry(self.key)
.or_insert_with(|| Wire::data::<T>(self.spec))
.sender::<Outbox<ItemId, T>>()
}
#[inline]
fn opened<T>(&mut self) -> Option<Outbox<ItemId, T>>
where
T: Send + 'static,
{
self
.wires
.get(&self.key)?
.sender::<Outbox<ItemId, T>>()
.ok()
}
}
#[derive(Debug)]
pub struct Wiring<'a> {
wired: &'a Wired,
ctx: Arc<Resources>,
taps: Taps,
registries: Arc<Registries>,
wires: BTreeMap<(usize, usize), Wire>,
doors: BTreeMap<usize, Wire>,
cadences: Vec<Cadence>,
shutdown: Shutdown,
}
impl<'a> Wiring<'a> {
pub const CAPACITY: usize = 32;
pub const SHIPPED: ChannelOptions = ChannelOptions::Bounded(Self::CAPACITY);
pub const DOOR_CAPACITY: usize = 8;
#[inline]
pub(super) fn new(wired: &'a Wired, ctx: Resources, taps: Taps) -> Self {
Self {
wired,
ctx: Arc::new(ctx),
taps,
registries: Arc::new(Registries::default()),
wires: BTreeMap::new(),
doors: BTreeMap::new(),
cadences: Vec::new(),
shutdown: Shutdown::new(),
}
}
#[inline]
#[must_use]
pub fn with_taps(mut self, taps: Taps) -> Self {
self.set_taps(taps);
self
}
#[inline]
pub fn set_taps(&mut self, taps: Taps) -> &mut Self {
self.taps = taps;
self
}
#[inline]
#[must_use]
pub const fn taps(&self) -> &Taps {
&self.taps
}
#[inline]
#[must_use]
pub fn with_registries(mut self, registries: Arc<Registries>) -> Self {
self.set_registries(registries);
self
}
#[inline]
pub fn set_registries(&mut self, registries: Arc<Registries>) -> &mut Self {
self.registries = registries;
self
}
#[inline]
#[must_use]
pub fn registries(&self) -> &Arc<Registries> {
&self.registries
}
#[inline]
#[must_use]
pub const fn policies(&self) -> &Policies {
self.wired.policies()
}
pub fn inbox<T>(&mut self, node: NodeId) -> Result<Option<Inbox<ItemId, T>>, LaunchError>
where
T: Send + 'static,
{
self.source_inbox(node, 0)
}
pub fn source_inbox<T>(
&mut self,
node: NodeId,
upstream: usize,
) -> Result<Option<Inbox<ItemId, T>>, LaunchError>
where
T: Send + 'static,
{
let wired = self.wired;
if !wired.is_enabled(node) {
return Ok(None);
}
let spec = wired.channel(node, upstream);
let wire = self
.wires
.entry((node.index(), upstream))
.or_insert_with(|| Wire::data::<T>(spec));
wire
.carries::<Outbox<ItemId, T>>()
.map_err(|error| LaunchError::wiring(name(wired, node), error))?;
wire
.receiver::<Inbox<ItemId, T>>()
.map(Some)
.map_err(|error| LaunchError::wiring(name(wired, node), error))
}
pub fn upstreams<T>(&mut self, node: NodeId) -> Result<Option<Upstreams<T>>, LaunchError>
where
T: Send + 'static,
{
if !self.wired.is_enabled(node) {
return Ok(None);
}
let arms = if self.apart(node) {
self.arms(node).max(1)
} else {
1
};
let mut upstreams = Upstreams::new();
for upstream in 0..arms {
let Some(inbox) = self.source_inbox::<T>(node, upstream)? else {
return Ok(None);
};
upstreams.attach(inbox);
}
Ok(Some(upstreams))
}
pub fn outbox<T>(&mut self, consumer: NodeId) -> Result<Option<Outbox<ItemId, T>>, LaunchError>
where
T: Send + 'static,
{
self.source_outbox(consumer, 0)
}
pub fn source_outbox<T>(
&mut self,
consumer: NodeId,
upstream: usize,
) -> Result<Option<Outbox<ItemId, T>>, LaunchError>
where
T: Send + 'static,
{
let wired = self.wired;
if !wired.is_enabled(consumer) {
return Ok(None);
}
let spec = wired.channel(consumer, upstream);
self
.wires
.entry((consumer.index(), upstream))
.or_insert_with(|| Wire::data::<T>(spec))
.sender::<Outbox<ItemId, T>>()
.map(Some)
.map_err(|error| LaunchError::wiring(name(wired, consumer), error))
}
#[must_use]
pub fn source_of(&self, consumer: NodeId, edge: EdgeId) -> Option<usize> {
self
.wired
.graph()
.edges()
.iter()
.enumerate()
.filter(|&(_, wire)| wire.to() == consumer)
.filter(|&(index, _)| {
self
.wired
.upstream(EdgeId::new(index))
.is_some_and(|upstream| upstream.listen().is_channel())
})
.position(|(index, _)| EdgeId::new(index) == edge)
}
#[must_use]
pub fn arms(&self, consumer: NodeId) -> usize {
self
.wired
.graph()
.edges()
.iter()
.enumerate()
.filter(|&(_, wire)| wire.to() == consumer)
.filter(|&(index, _)| {
self
.wired
.upstream(EdgeId::new(index))
.is_some_and(|upstream| upstream.listen().is_channel())
})
.count()
}
pub fn bridge<T>(&mut self, origin: NodeId) -> Result<Option<Outbox<ItemId, T>>, LaunchError>
where
T: Send + 'static,
{
if !self.wired.is_enabled(origin) {
return Ok(None);
}
let mut out = self
.wired
.graph()
.edges()
.iter()
.enumerate()
.filter(|&(_, wire)| wire.from() == origin)
.filter(|&(index, _)| {
self
.wired
.upstream(EdgeId::new(index))
.is_some_and(|upstream| upstream.listen().is_channel())
});
let Some((index, wire)) = out.next() else {
return Ok(None);
};
if out.next().is_some() {
return Ok(None);
}
let consumer = wire.to();
let Some(slot) = self.source_of(consumer, EdgeId::new(index)) else {
return Ok(None);
};
self.source_outbox::<T>(consumer, slot)
}
pub fn invokes<T, R>(&mut self, node: NodeId) -> Result<Option<Invokes<T, R>>, LaunchError>
where
T: Send + 'static,
R: Send + 'static,
{
let wired = self.wired;
if !wired.is_enabled(node) {
return Ok(None);
}
let capacity = Self::DOOR_CAPACITY;
let gate = self
.doors
.entry(node.index())
.or_insert_with(|| Wire::query::<T, R>(capacity));
gate
.carries::<Door<T, R>>()
.map_err(|error| LaunchError::wiring(name(wired, node), error))?;
gate
.receiver::<Invokes<T, R>>()
.map(Some)
.map_err(|error| LaunchError::wiring(name(wired, node), error))
}
pub fn door<T, R>(&mut self, node: NodeId) -> Result<Option<Door<T, R>>, LaunchError>
where
T: Send + 'static,
R: Send + 'static,
{
let wired = self.wired;
if !wired.is_enabled(node) {
return Ok(None);
}
let capacity = Self::DOOR_CAPACITY;
self
.doors
.entry(node.index())
.or_insert_with(|| Wire::query::<T, R>(capacity))
.sender::<Door<T, R>>()
.map(Some)
.map_err(|error| LaunchError::wiring(name(wired, node), error))
}
pub fn resident<O, I>(
&mut self,
node: NodeId,
operator: O,
intake: I,
) -> Result<Option<NodeBody<O, I, <O as Declared>::Mode>>, LaunchError>
where
O: Declared + Driven<<O as Declared>::Mode>,
<O as Driven<<O as Declared>::Mode>>::Out: Send + 'static,
NodeAttribution<O, <O as Declared>::Mode>:
Attributes<<O as Driven<<O as Declared>::Mode>>::Out>,
{
let Some(declared) = self
.wired
.node(node)
.filter(|_| self.wired.is_enabled(node))
else {
return Ok(None);
};
let wired = self.wired;
let mount = name(wired, node);
let mut resident = Resident::new(mount, operator, intake)
.with_effect(declared.effect())
.with_ack(fold_ack(wired, node))
.with_taps(self.taps.clone())
.with_policies(wired.policies().clone())
.with_registries(Arc::clone(&self.registries))
.with_resources(Arc::clone(&self.ctx))
.with_tracing_level(declared.tracing_level())
.attributing(<NodeAttribution<O, <O as Declared>::Mode> as Default>::default());
for (index, edge) in wired.graph().edges().iter().enumerate() {
if edge.from() != node {
continue;
}
let sends = wired
.upstream(EdgeId::new(index))
.is_some_and(|upstream| upstream.listen().is_channel());
if !sends {
continue;
}
let slot = self
.apart(edge.to())
.then(|| self.source_of(edge.to(), EdgeId::new(index)))
.flatten()
.unwrap_or(0);
if let Some(outbox) =
self.source_outbox::<<O as Driven<<O as Declared>::Mode>>::Out>(edge.to(), slot)?
{
resident = resident.publish(outbox);
}
}
let enrolled = self.shutdown.register(mount);
Ok(Some((resident, enrolled)))
}
pub fn lane<O, I, X>(
&mut self,
node: NodeId,
instances: I,
options: StreamOptions,
spawner: X,
) -> Result<Option<StreamBody<O, X, <O as Declared>::Mode>>, LaunchError>
where
O: Declared + Streams<<O as Declared>::Mode>,
I: IntoIterator<Item = O>,
<O as Streams<<O as Declared>::Mode>>::Out: Send + 'static,
StreamWires<O, <O as Declared>::Mode>: Attaches,
{
let Some((downstream, effect)) = self.lane_parts::<O>(node)? else {
return Ok(None);
};
let mount = name(self.wired, node);
let lane = StreamLane::new(self.window(mount), options, instances, downstream, spawner)
.with_effect(effect)
.with_taps(self.taps.clone());
let enrolled = self.shutdown.register(mount);
Ok(Some((lane, enrolled)))
}
pub fn lane_mount<O, I, X>(
&mut self,
node: NodeId,
instances: I,
options: StreamOptions,
spawner: X,
intake: Inbox<ItemId, <O as Streams<<O as Declared>::Mode>>::In>,
) -> Result<Option<MountBody<O, X, <O as Declared>::Mode>>, LaunchError>
where
O: Declared + Streams<<O as Declared>::Mode> + Send + 'static,
I: IntoIterator<Item = O>,
X: Send + 'static,
<O as Streams<<O as Declared>::Mode>>::In: Send + 'static,
<O as Streams<<O as Declared>::Mode>>::Out: Send + 'static,
StreamWires<O, <O as Declared>::Mode>: Attaches + Send + 'static,
{
let Some((downstream, effect)) = self.lane_parts::<O>(node)? else {
return Ok(None);
};
let mount = Utf8Bytes::from(name(self.wired, node).to_owned());
let taps = self.taps.clone();
let enrolled = self.shutdown.register(mount.clone());
let window = self.window(mount);
Ok(Some((
LaneMount {
instances: instances.into_iter().collect(),
build: Box::new(move |warm| {
let lane = StreamLane::new(window, options, warm, downstream, spawner)
.with_effect(effect)
.with_taps(taps);
(lane, intake)
}),
},
enrolled,
)))
}
pub fn autonomous<O>(
&mut self,
node: NodeId,
operator: O,
upstreams: Upstreams<<O as Runs<<O as Declared>::Mode>>::In>,
) -> Result<Option<AutonomousBody<O, <O as Declared>::Mode>>, LaunchError>
where
O: Declared + Runs<<O as Declared>::Mode>,
<O as Runs<<O as Declared>::Mode>>::Out: Send + 'static,
{
let Some((downstream, _effect)) =
self.publishing::<Downstream<<O as Runs<<O as Declared>::Mode>>::Out>>(node)?
else {
return Ok(None);
};
let mount = Utf8Bytes::from(name(self.wired, node).to_owned());
let enrolled = self.shutdown.register(mount.clone());
let (stopper, halt) = crate::shutdown_signal();
let helm = Helm::new(
self.window(mount).halting(halt),
operator,
upstreams,
downstream,
);
Ok(Some((helm, stopper, enrolled)))
}
fn window(&self, mount: impl Into<Utf8Bytes>) -> Context {
Context::new(mount).sharing(Arc::clone(&self.ctx))
}
fn lane_parts<O>(&mut self, node: NodeId) -> Result<Option<LaneParts<O>>, LaunchError>
where
O: Declared + Streams<<O as Declared>::Mode>,
<O as Streams<<O as Declared>::Mode>>::Out: Send + 'static,
StreamWires<O, <O as Declared>::Mode>: Attaches,
{
self.publishing::<StreamWires<O, <O as Declared>::Mode>>(node)
}
fn publishing<W>(&mut self, node: NodeId) -> Result<Option<(W, crate::Effect)>, LaunchError>
where
W: Attaches,
{
let Some(declared) = self
.wired
.node(node)
.filter(|_| self.wired.is_enabled(node))
else {
return Ok(None);
};
let effect = declared.effect();
let wired = self.wired;
let mut wires = W::default();
for (index, edge) in wired.graph().edges().iter().enumerate() {
if edge.from() != node {
continue;
}
let sends = wired
.upstream(EdgeId::new(index))
.is_some_and(|upstream| upstream.listen().is_channel());
if !sends {
continue;
}
let consumer = edge.to();
if !wired.is_enabled(consumer) {
continue;
}
let slot = self
.apart(consumer)
.then(|| self.source_of(consumer, EdgeId::new(index)))
.flatten()
.unwrap_or(0);
let key = (consumer.index(), slot);
let opened = self.wires.get(&key).map(|wire| wire.carries);
let mut socket = EdgeSocket {
wires: &mut self.wires,
key,
spec: wired.channel(consumer, slot),
};
let seated = wires
.attach(&mut socket)
.map_err(|error| LaunchError::wiring(name(wired, node), error))?;
match seated {
Attached::Seated(_) => {}
Attached::Occupied(product) => {
return Err(LaunchError::wiring(
name(wired, node),
ProductSeatError::Occupied {
set: type_name::<W>(),
product,
},
));
}
Attached::Foreign => {
return Err(LaunchError::wiring(
name(wired, node),
match opened {
Some(carries) => ProductSeatError::Foreign {
set: type_name::<W>(),
carries,
},
None => ProductSeatError::Unopened {
set: type_name::<W>(),
consumer: name(wired, consumer).to_owned().into(),
},
},
));
}
}
}
Ok(Some((wires, effect)))
}
fn apart(&self, consumer: NodeId) -> bool {
self
.wired
.node(consumer)
.is_some_and(|node| node.holds_intake())
}
#[must_use]
pub fn schedule(&self, node: NodeId) -> Schedule {
self
.wired
.graph()
.edges()
.iter()
.enumerate()
.filter(|&(_, edge)| edge.to() == node)
.filter_map(
|(index, _)| match self.wired.upstream(EdgeId::new(index))?.listen() {
Listen::Poll(every) => Some(every),
Listen::Channel | Listen::Changes(_) | Listen::Transient => None,
},
)
.fold(Schedule::new(), Schedule::every)
}
pub fn clock<T>(&mut self, node: NodeId, sweep: Duration) -> Result<usize, LaunchError>
where
T: Send + 'static,
{
if !self.wired.is_enabled(node)
|| self.wired.graph().nodes()[node.index()]
.driver()
.is_thread()
{
return Ok(0);
}
let schedule = self.schedule(node);
let Some(outbox) = self.outbox::<T>(node)? else {
return Ok(0);
};
let before = self.cadences.len();
self.cadences.extend(schedule.cadences(&outbox));
self
.cadences
.push(Cadence::new(sweep, Box::new(outbox.nudge())));
Ok(self.cadences.len() - before)
}
#[inline]
pub fn enrol(&mut self, name: &str) -> Enrolled {
self.shutdown.register(name)
}
#[inline]
#[must_use]
pub fn context(&self) -> &Resources {
&self.ctx
}
#[inline]
#[must_use]
pub const fn shutdown(&self) -> &Shutdown {
&self.shutdown
}
#[must_use]
pub fn into_assembly(self) -> Assembly {
let senders = self
.wires
.into_values()
.chain(self.doors.into_values())
.filter(|wire| wire.receiver.is_none())
.map(|wire| wire.sender)
.collect();
Assembly {
ctx: self.ctx,
cadences: self.cadences,
shutdown: self.shutdown,
taps: self.taps,
policies: self.wired.policies().clone(),
registries: self.registries,
senders,
}
}
#[must_use]
pub fn unwind(self, staged: Staging, error: LaunchError) -> LaunchError {
let Self { ctx, taps, .. } = self;
block_on(async {
drop(farewell(staged.into_farewells(), &taps).await);
drop(released(ctx, &taps).await);
});
error
}
}
pub struct Assembly {
ctx: Arc<Resources>,
cadences: Vec<Cadence>,
shutdown: Shutdown,
taps: Taps,
policies: Policies,
registries: Arc<Registries>,
senders: Vec<Box<dyn Any + Send>>,
}
impl Assembly {
#[inline]
#[must_use]
pub fn ignite(self) -> Ignition {
Ignition::new(
self.ctx,
self.cadences,
engine::hand_timer,
self.shutdown,
self.taps,
self.registries,
self.senders,
)
}
#[inline]
#[must_use]
pub fn ignite_on<R>(self) -> Ignition<R>
where
R: RuntimeLite,
{
Ignition::new(
self.ctx,
self.cadences,
engine::after_clock::<R::AfterSpawner>,
self.shutdown,
self.taps,
self.registries,
self.senders,
)
}
#[inline]
#[must_use]
pub fn context(&self) -> &Resources {
&self.ctx
}
#[inline]
#[must_use]
pub const fn taps(&self) -> &Taps {
&self.taps
}
#[inline]
#[must_use]
pub const fn policies(&self) -> &Policies {
&self.policies
}
#[inline]
#[must_use]
pub fn registries(&self) -> &Arc<Registries> {
&self.registries
}
#[inline]
#[must_use]
pub fn cadences(&self) -> &[Cadence] {
&self.cadences
}
#[inline]
#[must_use]
pub fn take_cadences(&mut self) -> Vec<Cadence> {
core::mem::take(&mut self.cadences)
}
#[inline]
#[must_use]
pub const fn shutdown(&self) -> &Shutdown {
&self.shutdown
}
#[inline]
pub const fn shutdown_mut(&mut self) -> &mut Shutdown {
&mut self.shutdown
}
#[inline]
#[must_use]
pub fn senders(&self) -> usize {
self.senders.len()
}
#[inline]
pub fn close(&mut self) {
self.senders.clear();
}
}
impl core::fmt::Debug for Assembly {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Assembly")
.field("resources", &self.ctx.len())
.field("cadences", &self.cadences.len())
.field("parties", &self.shutdown.len())
.field("senders", &self.senders.len())
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
#[display(
"its edge is `{carries}` and this wiring asked for `{wanted}`; a producer's output type and its \
consumer's input type are one type"
)]
pub struct EdgeTypeError {
carries: &'static str,
wanted: &'static str,
}
impl EdgeTypeError {
#[inline]
const fn new(carries: &'static str, wanted: &'static str) -> Self {
Self { carries, wanted }
}
#[inline]
#[must_use]
pub const fn carries(&self) -> &'static str {
self.carries
}
#[inline]
#[must_use]
pub const fn wanted(&self) -> &'static str {
self.wanted
}
}
impl core::error::Error for EdgeTypeError {}
#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display, derive_more::IsVariant)]
pub enum ProductSeatError {
#[display(
"its edge is `{carries}` and no product of `{set}` carries it; an edge is a subscription to ONE \
product, so a consumer's input type is the product its `out` word named"
)]
Foreign {
set: &'static str,
carries: &'static str,
},
#[display(
"its product at {product} of `{set}` already has a subscriber and that product's payload does \
not copy, so a second one would have nothing to receive; several subscribers to one product is \
the ordinary road and each one past the first is served a COPY — make that payload `Clone`, \
which for a decoded buffer or an open handle usually means an `Arc` or another refcounted \
carrier"
)]
Occupied {
set: &'static str,
product: usize,
},
#[display(
"its edge into `{consumer}` has not been opened, and `{set}` seats the product that \
consumer's own inbox names — take the consumer's receiving half before wiring this node"
)]
Unopened {
set: &'static str,
consumer: Utf8Bytes,
},
}
impl core::error::Error for ProductSeatError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
#[display(
"its `{inbox}` has already been taken; a node has one receiving half however many producers, and \
fan-in is several sending halves of it"
)]
pub struct TakenInboxError {
inbox: &'static str,
}
impl TakenInboxError {
#[inline]
fn of<R>() -> Self {
Self {
inbox: type_name::<R>(),
}
}
#[inline]
#[must_use]
pub const fn inbox(&self) -> &'static str {
self.inbox
}
}
impl core::error::Error for TakenInboxError {}
fn fold_ack(wired: &Wired, node: NodeId) -> AckMode {
for (index, edge) in wired.graph().edges().iter().enumerate() {
if edge.to() != node {
continue;
}
let Some(upstream) = wired.upstream(EdgeId::new(index)) else {
continue;
};
if matches!(upstream.listen(), Listen::Channel | Listen::Changes(_))
&& upstream.ack().is_chained()
{
return AckMode::Chained;
}
}
AckMode::Local
}
impl core::fmt::Debug for Wire {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Wire")
.field("carries", &self.carries)
.field("taken", &self.receiver.is_none())
.finish()
}
}
fn name(wired: &Wired, node: NodeId) -> &str {
wired.graph().nodes()[node.index()].name()
}