use crate::Context;
use core::{convert::Infallible, error::Error, time::Duration};
use std::{
io,
sync::{Arc, Mutex},
time::Instant,
};
use crate::{
AsyncTeardown, ChannelGraph, Delivery, DriverKind, Effect, Emitter, Enablement, FanoutKind,
GraphBuilder, Item, ItemId, LaunchError, LifecycleTap, NodeId, NodeWiring, Operator, Party,
Payload, Plan, RecordingTap, Station, Taps, Wired, ack_channel,
};
use super::Ignition;
type Record = Arc<Mutex<Vec<String>>>;
fn record() -> Record {
Arc::new(Mutex::new(Vec::new()))
}
fn note(record: &Record, what: impl Into<String>) {
record.lock().expect("the world's record").push(what.into());
}
fn seen(record: &Record) -> Vec<String> {
record.lock().expect("the world's record").clone()
}
struct Shout;
macro_rules! declared {
($name:ident) => {
impl crate::Declared for $name {
const EFFECT: crate::Effect = crate::Effect::Pure;
type Channels = crate::Unchanneled;
type Mode = crate::Block;
type Options = ();
type Pair = crate::Buffered;
type Wires<O> = crate::Downstream<O>;
type Attribution<O> = ();
}
};
}
declared!(Shout);
impl Operator for Shout {
type Error = Infallible;
type In = String;
type Out = String;
fn accept(
&mut self,
_ctx: &Context,
delivery: Delivery<Self::In>,
emitter: &mut Emitter<String>,
) -> Result<(), Self::Error> {
for item in delivery.into_items() {
let item = item.into_value();
emitter.emit(item.to_uppercase());
}
Ok(())
}
}
struct Keeping {
record: Record,
}
declared!(Keeping);
impl Operator for Keeping {
type Error = Infallible;
type In = String;
type Out = String;
fn accept(
&mut self,
_ctx: &Context,
delivery: Delivery<Self::In>,
_emitter: &mut Emitter<String>,
) -> Result<(), Self::Error> {
for item in delivery.into_items() {
let item = item.into_value();
note(&self.record, item);
}
Ok(())
}
}
struct Passing {
name: &'static str,
record: Record,
}
declared!(Passing);
impl Operator for Passing {
type Error = Infallible;
type In = String;
type Out = String;
fn accept(
&mut self,
_ctx: &Context,
delivery: Delivery<Self::In>,
emitter: &mut Emitter<String>,
) -> Result<(), Self::Error> {
for item in delivery.into_items() {
let item = item.into_value();
emitter.emit(item);
}
Ok(())
}
}
impl Drop for Passing {
fn drop(&mut self) {
note(&self.record, format!("gone {}", self.name));
}
}
fn passing(name: &'static str, record: &Record) -> Passing {
Passing {
name,
record: Arc::clone(record),
}
}
struct Says {
name: &'static str,
record: Record,
}
impl AsyncTeardown for Says {
async fn teardown(self) -> Result<(), Box<dyn Error + Send + Sync>> {
note(&self.record, format!("goodbye {}", self.name));
Ok(())
}
}
struct Admitting {
name: &'static str,
record: Record,
}
impl Drop for Admitting {
fn drop(&mut self) {
note(&self.record, format!("stopped {}", self.name));
}
}
fn admitting(name: &'static str, record: &Record) -> Admitting {
note(record, format!("started {name}"));
Admitting {
name,
record: Arc::clone(record),
}
}
fn pair(driver: DriverKind) -> ChannelGraph {
let mut builder = GraphBuilder::new();
let shout = builder.source::<Shout>("shout", driver);
let titles = builder.node::<Shout>("titles", driver);
builder.edge(&shout, &titles, FanoutKind::Broadcast);
builder.validate().expect("one edge validates")
}
fn wired(driver: DriverKind) -> Wired {
Plan::new(pair(driver))
.with_enablement(Enablement::new().launching("shout").launching("titles"))
.wiring(NodeId::new(1), NodeWiring::new(Effect::Lands).landing())
.validate()
.expect("the deployment checks out")
}
fn watching() -> (Arc<RecordingTap>, Taps) {
let tap = Arc::new(RecordingTap::new());
let taps = Taps::new().with(Arc::clone(&tap) as Arc<dyn LifecycleTap>);
(tap, taps)
}
fn refused_engine() -> LaunchError {
LaunchError::ignition("titles", io::Error::from(io::ErrorKind::WouldBlock))
}
#[test]
fn the_bodies_get_their_engines_and_the_sources_start_last() {
let record = record();
let wired = wired(DriverKind::Thread);
let mut wiring = wired.create().wire();
let head = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (head, head_party) = wiring
.resident(NodeId::new(0), Shout, head)
.expect("nothing to refuse")
.expect("the deployment launches it");
let (leaf, leaf_party) = wiring
.resident(
NodeId::new(1),
Keeping {
record: Arc::clone(&record),
},
leaf,
)
.expect("nothing to refuse")
.expect("the deployment launches it");
let mut ignition = wiring.into_assembly().ignite();
let intake = Arc::clone(&record);
ignition.source(move || admitting("intake", &intake));
let clock = Arc::clone(&record);
ignition.source(move || admitting("clock", &clock));
ignition.resident(head, head_party).expect("its engine");
ignition.resident(leaf, leaf_party).expect("its engine");
assert_eq!(ignition.bodies(), 2);
assert_eq!(ignition.sources(), 2);
assert!(
seen(&record).is_empty(),
"a source registered before the bodies still has not started"
);
let running = ignition.into_app::<()>();
assert_eq!(
seen(&record),
["started intake", "started clock"],
"and they start here, in registration order, once every body has an engine"
);
assert_eq!(running.sources(), 2);
let stopped = running.shutdown(None);
assert!(stopped.is_clean());
assert_eq!(
seen(&record),
[
"started intake",
"started clock",
"stopped clock",
"stopped intake"
],
"last on, first off"
);
}
#[test]
fn a_fed_world_settles_by_closure_alone_and_loses_nothing_that_was_in_flight() {
let record = record();
let wired = wired(DriverKind::Thread);
let mut wiring = wired.create().wire();
let head_inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf_inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let feed = wiring
.outbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (head, head_party) = wiring
.resident(NodeId::new(0), Shout, head_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let (leaf, leaf_party) = wiring
.resident(
NodeId::new(1),
Keeping {
record: Arc::clone(&record),
},
leaf_inbox,
)
.expect("nothing to refuse")
.expect("the deployment launches it");
let mut ignition = wiring.into_assembly().ignite();
ignition.resident(head, head_party).expect("its engine");
ignition.resident(leaf, leaf_party).expect("its engine");
ignition.teardown(
"pool",
Says {
name: "pool",
record: Arc::clone(&record),
},
);
ignition.teardown(
"device",
Says {
name: "device",
record: Arc::clone(&record),
},
);
let running = ignition.into_app::<()>();
for item in 0..5u64 {
let (ack, _answers) = ack_channel();
feed
.deliver(Delivery::new(
Payload::One(Item::new(ItemId::new(item), format!("item-{item}"))),
ack,
))
.expect("the head is listening");
}
drop(feed);
let stopped = running.shutdown(None);
assert_eq!(stopped.settled(), 2, "both bodies answered");
assert!(stopped.is_clean());
let seen = seen(&record);
assert_eq!(
seen[..5],
["ITEM-0", "ITEM-1", "ITEM-2", "ITEM-3", "ITEM-4"],
"everything in flight when the wave began still reached the far end"
);
assert_eq!(
seen[5..],
["goodbye device", "goodbye pool"],
"and the goodbyes come after the last party settled, last enrolled first"
);
}
#[test]
fn a_world_nobody_is_feeding_ends_of_itself() {
let wired = wired(DriverKind::Thread);
let mut wiring = wired.create().wire();
let head = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (head, head_party) = wiring
.resident(NodeId::new(0), Shout, head)
.expect("nothing to refuse")
.expect("the deployment launches it");
let (leaf, leaf_party) = wiring
.resident(NodeId::new(1), Shout, leaf)
.expect("nothing to refuse")
.expect("the deployment launches it");
let mut assembly = wiring.into_assembly();
assembly.close();
let mut ignition = assembly.ignite();
ignition.resident(head, head_party).expect("its engine");
ignition.resident(leaf, leaf_party).expect("its engine");
let running = ignition.into_app::<()>();
let began = Instant::now();
running.until_stopped();
assert!(
began.elapsed() < Duration::from_secs(5),
"the wave needs nobody to conduct it"
);
assert!(running.parties().iter().all(Party::settled));
assert!(running.shutdown(None).is_clean());
}
#[test]
fn the_order_emerges_from_the_edges_rather_than_from_a_list() {
let record = record();
let wired = wired(DriverKind::Thread);
let mut wiring = wired.create().wire();
let head_inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf_inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let feed = wiring
.outbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (head, head_party) = wiring
.resident(NodeId::new(0), passing("head", &record), head_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let (leaf, leaf_party) = wiring
.resident(NodeId::new(1), passing("leaf", &record), leaf_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let mut ignition = wiring.into_assembly().ignite();
ignition.resident(head, head_party).expect("its engine");
ignition.resident(leaf, leaf_party).expect("its engine");
let running = ignition.into_app::<()>();
let (ack, _answers) = ack_channel();
feed
.deliver(Delivery::new(
Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
ack,
))
.expect("the head is listening");
drop(feed);
assert!(running.shutdown(None).is_clean());
assert_eq!(
seen(&record),
["gone head", "gone leaf"],
"upstream closure is what ends the node below it"
);
}
#[test]
fn a_launch_that_fails_after_the_first_body_started_stops_it_before_it_reports() {
let record = record();
let (tap, taps) = watching();
let wired = wired(DriverKind::Thread);
let mut wiring = wired.create().wire().with_taps(taps);
let head_inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf_inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (head, head_party) = wiring
.resident(NodeId::new(0), passing("head", &record), head_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let (leaf, leaf_party) = wiring
.resident(NodeId::new(1), Shout, leaf_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let intake = wiring.enrol("intake");
let mut ignition = wiring.into_assembly().ignite();
ignition
.resident(head, head_party)
.expect("the first engine started");
let clock = Arc::clone(&record);
ignition.source(move || admitting("clock", &clock));
drop(leaf);
drop(leaf_party);
let began = Instant::now();
let refusal = ignition.unwind(refused_engine());
let waited = began.elapsed();
assert_eq!(
seen(&record),
["gone head"],
"the started body wound down before the error came back, and the source never started at all"
);
assert!(intake.winding(), "the party the caller runs heard it too");
assert!(
waited < Ignition::PATIENCE,
"and it was not waited for: {waited:?}"
);
assert!(
ignition.shutdown().parties()[0].settled(),
"and it answered rather than merely stopping"
);
assert_eq!(
ignition.bodies(),
0,
"every party settled, so the engines were joined: they are gone, not merely finished"
);
assert_eq!(ignition.sources(), 0, "the unspent start was dropped");
assert!(
!ignition.shutdown().parties()[1].ignited(),
"the party whose engine was refused never began"
);
assert!(refusal.is_ignition(), "{refusal}");
let rendered = refusal.to_string();
assert!(rendered.contains("titles"), "{rendered}");
assert!(rendered.contains("could not be started"), "{rendered}");
assert_eq!(tap.seen(), [("shout".to_owned(), Station::Processed)]);
}
#[test]
fn a_party_that_will_not_settle_is_abandoned_when_the_patience_runs_out() {
let (tap, taps) = watching();
let wired = wired(DriverKind::Async);
let mut wiring = wired.create().wire().with_taps(taps);
let head_inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf_inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (head, head_party) = wiring
.resident(NodeId::new(0), Shout, head_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let (leaf, leaf_party) = wiring
.resident(NodeId::new(1), Shout, leaf_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let mut ignition = wiring.into_assembly().ignite();
let body = Ignition::task(head, head_party);
drop(leaf);
drop(leaf_party);
let began = Instant::now();
let refusal = ignition.unwind(refused_engine());
let waited = began.elapsed();
assert!(
waited >= Ignition::PATIENCE,
"the wait was the shipped one and it ran out: {waited:?}"
);
assert!(
waited < Ignition::PATIENCE * 3,
"and it ended there rather than waiting on a party that will never answer: {waited:?}"
);
assert!(
!ignition.shutdown().parties()[0].settled(),
"it was abandoned where it stood"
);
assert!(
refusal.is_ignition(),
"and the caller still gets the original refusal: {refusal}"
);
assert_eq!(
tap.seen(),
[("shout".to_owned(), Station::Failed)],
"the tap is where an abandoned party is reported, never a second error"
);
drop(body);
}
#[test]
fn an_ignition_that_started_nothing_hands_the_error_straight_back() {
let (tap, taps) = watching();
let wired = wired(DriverKind::Thread);
let mut wiring = wired.create().wire().with_taps(taps);
let head_inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf_inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let head = wiring
.resident(NodeId::new(0), Shout, head_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf = wiring
.resident(NodeId::new(1), Shout, leaf_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let mut ignition = wiring.into_assembly().ignite();
drop((head, leaf));
let began = Instant::now();
let refusal = ignition.unwind(refused_engine());
assert!(
began.elapsed() < Ignition::PATIENCE,
"an empty set is not something to wait for"
);
assert!(refusal.is_ignition(), "{refusal}");
assert!(
tap.is_empty(),
"nothing began, so nothing has an outcome to report"
);
}
#[tokio::test]
async fn the_async_engine_s_body_is_composed_for_whoever_holds_a_runtime() {
let record = record();
let wired = wired(DriverKind::Async);
let mut wiring = wired.create().wire();
let head_inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf_inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let feed = wiring
.outbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let clocks = wiring
.clock::<String>(NodeId::new(1), Duration::from_millis(20))
.expect("nothing to refuse");
assert_eq!(clocks, 1, "the sweep nudge");
let (head, head_party) = wiring
.resident(NodeId::new(0), Shout, head_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let (leaf, leaf_party) = wiring
.resident(
NodeId::new(1),
Keeping {
record: Arc::clone(&record),
},
leaf_inbox,
)
.expect("nothing to refuse")
.expect("the deployment launches it");
let ignition = wiring.into_assembly().ignite();
tokio::spawn(Ignition::task(head, head_party));
tokio::spawn(Ignition::task(leaf, leaf_party));
let running = ignition.into_app::<()>();
assert_eq!(running.sources(), 1, "the cadence clock, and it is started");
let (ack, _answers) = ack_channel();
feed
.deliver_async(Delivery::new(
Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
ack,
))
.await
.expect("the head is listening");
drop(feed);
let stopped = tokio::task::spawn_blocking(move || running.shutdown(None))
.await
.expect("the shutdown's own thread");
assert_eq!(stopped.settled(), 2);
assert!(stopped.is_clean());
assert_eq!(seen(&record), ["ONE"]);
}
struct Parking {
entered: crate::conduit::Sender<()>,
record: Record,
}
declared!(Parking);
impl Operator for Parking {
type Error = Infallible;
type In = String;
type Out = String;
fn accept(
&mut self,
ctx: &Context,
delivery: Delivery<Self::In>,
_emitter: &mut Emitter<String>,
) -> Result<(), Self::Error> {
for item in delivery.into_items() {
note(&self.record, format!("entered {}", item.into_value()));
let _ = self.entered.try_send(());
ctx.shutdown().heard();
note(&self.record, format!("heard it at {}", ctx.node().as_str()));
}
Ok(())
}
}
#[test]
fn a_body_inside_accept_hears_the_deployment_broadcast_on_its_own_window() {
let record = record();
let wired = wired(DriverKind::Thread);
let mut wiring = wired.create().wire();
let head_inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let leaf_inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let feed = wiring
.outbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (entered, in_the_park) = crate::conduit::bounded::<()>(1);
let (head, head_party) = wiring
.resident(
NodeId::new(0),
Parking {
entered,
record: Arc::clone(&record),
},
head_inbox,
)
.expect("nothing to refuse")
.expect("the deployment launches it");
let (leaf, leaf_party) = wiring
.resident(
NodeId::new(1),
Keeping {
record: Arc::clone(&record),
},
leaf_inbox,
)
.expect("nothing to refuse")
.expect("the deployment launches it");
let mut ignition = wiring.into_assembly().ignite();
ignition.resident(head, head_party).expect("its engine");
ignition.resident(leaf, leaf_party).expect("its engine");
let running = ignition.into_app::<()>();
let (ack, _answers) = ack_channel();
feed
.deliver(Delivery::new(
Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
ack,
))
.expect("the head is listening");
drop(feed);
assert!(
in_the_park.recv().is_some(),
"the body reached its own accept"
);
assert_eq!(
seen(&record),
["entered one"],
"and it has not come out of the park"
);
let stopped = running.shutdown(None);
assert!(stopped.is_clean(), "{stopped}");
assert_eq!(
seen(&record),
["entered one", "heard it at shout"],
"the broadcast reached the body's own stack, under the body's own name"
);
}