use crate::Context;
use core::{convert::Infallible, error::Error, time::Duration};
use std::{
sync::{Arc, Mutex},
thread,
time::Instant,
};
use crate::{
AckMode, AsyncResource, ChannelGraph, Delivery, DriverKind, EdgeId, EdgeTypeError, Effect,
Emitter, Enablement, FanoutKind, Feeder, GraphBuilder, Item, ItemId, LaunchError, Listen, NodeId,
NodeWiring, Operator, Party, Payload, Plan, PollUpstream, RecordingTap, Resources, Shared,
TakenInboxError, Taps, UpstreamWiring, Wired, Wiring, ack_channel,
};
use crate::drive::Drives;
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 {
seen: Arc<Mutex<Vec<String>>>,
}
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();
self.seen.lock().expect("the walk's record").push(item);
}
Ok(())
}
}
struct Counting;
declared!(Counting);
impl Operator for Counting {
type Error = Infallible;
type In = u8;
type Out = u8;
fn accept(
&mut self,
_ctx: &Context,
delivery: Delivery<Self::In>,
emitter: &mut Emitter<u8>,
) -> Result<(), Self::Error> {
for item in delivery.into_items() {
let item = item.into_value();
emitter.emit(item);
}
Ok(())
}
}
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 pair_plan(driver: DriverKind) -> Plan {
Plan::new(pair(driver))
.with_enablement(Enablement::new().launching("shout").launching("titles"))
.wiring(NodeId::new(1), NodeWiring::new(Effect::Lands).landing())
}
const REAP: Duration = Duration::from_millis(10);
const COMPACT: Duration = Duration::from_secs(3600);
fn reaper_plan(driver: DriverKind) -> Plan {
let mut builder = GraphBuilder::new();
let scenes = builder.source::<Shout>("scenes", driver);
let media = builder.source::<Shout>("media", driver);
let reaper = builder.node::<Shout>("reaper", driver);
builder.edge(&scenes, &reaper, FanoutKind::Broadcast);
builder.edge(&media, &reaper, FanoutKind::Broadcast);
let graph = builder.validate().expect("two edges validate");
Plan::new(graph)
.with_enablement(
Enablement::new()
.launching("scenes")
.launching("media")
.launching("reaper"),
)
.upstream(
EdgeId::new(0),
UpstreamWiring::new(Listen::Poll(REAP), AckMode::Local),
)
.upstream(
EdgeId::new(1),
UpstreamWiring::new(Listen::Poll(COMPACT), AckMode::Local),
)
}
fn wired(plan: Plan) -> Wired {
plan.validate().expect("the deployment checks out")
}
fn refused<E>(error: &LaunchError) -> (&str, &E)
where
E: core::error::Error + 'static,
{
let LaunchError::Wiring { node, error } = error else {
panic!("a wiring refusal was expected: {error}")
};
(
node.as_str(),
error
.source()
.and_then(|source| source.downcast_ref::<E>())
.expect("the typed refusal survives its erasure"),
)
}
#[test]
fn each_node_gets_one_inbox_and_a_second_ask_is_refused_by_name() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
assert!(
wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.is_some()
);
let twice = wiring
.inbox::<String>(NodeId::new(1))
.expect_err("one inbox per node");
let (node, taken) = refused::<TakenInboxError>(&twice);
assert_eq!(node, "titles");
assert!(taken.inbox().contains("Inbox"), "{}", taken.inbox());
}
#[test]
fn a_node_this_deployment_does_not_launch_has_no_edge_at_all() {
let plan = Plan::new(pair(DriverKind::Thread))
.with_enablement(Enablement::new().launching("shout"))
.wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
let wired = wired(plan);
let mut wiring = wired.create().wire();
assert!(
wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.is_none()
);
assert!(
wiring
.outbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.is_none()
);
assert_eq!(wiring.into_assembly().senders(), 0);
}
#[test]
fn the_edge_is_minted_by_whichever_end_reaches_it_first() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
let outbox = wiring
.outbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (ack, _answers) = ack_channel();
outbox
.deliver(Delivery::new(
Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
ack,
))
.expect("the consumer is listening");
assert_eq!(inbox.len(), 1, "the two halves are one edge");
}
#[test]
fn an_edge_asked_for_under_the_wrong_type_names_both_of_them() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse");
let mismatch = wiring
.outbox::<u8>(NodeId::new(1))
.expect_err("the edge carries strings");
let (node, error) = refused::<EdgeTypeError>(&mismatch);
assert_eq!(node, "titles");
assert!(error.carries().contains("String"), "{}", error.carries());
assert!(error.wanted().contains("u8"), "{}", error.wanted());
}
#[test]
fn a_data_edge_is_opened_at_the_shipped_capacity_and_backpressures_past_it() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
let outbox = wiring
.outbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let producer = thread::spawn(move || {
for seq in 0..=Wiring::CAPACITY {
let (ack, _answers) = ack_channel();
if outbox
.deliver(Delivery::new(
Payload::One(Item::new(ItemId::new(seq as u64), "one".to_owned())),
ack,
))
.is_err()
{
return;
}
}
});
let deadline = Instant::now() + Duration::from_secs(10);
while inbox.len() < Wiring::CAPACITY {
assert!(
Instant::now() < deadline,
"the edge filled to {}",
inbox.len()
);
thread::yield_now();
}
assert_eq!(inbox.len(), Wiring::CAPACITY);
assert!(
!producer.is_finished(),
"the delivery past the capacity waits for room"
);
drop(inbox);
producer.join().expect("the producer thread");
}
#[test]
fn a_resident_comes_back_publishing_over_its_declared_channel_edges() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _enrolled) = wiring
.resident(NodeId::new(0), Shout, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert_eq!(resident.name().as_str(), "shout");
assert_eq!(resident.nudges().len(), 1, "one declared consumer");
assert!(resident.effect().is_pure(), "what the declaration says");
assert!(resident.ack().is_local());
}
#[test]
fn the_effect_a_resident_declares_is_the_one_the_plan_wired() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _enrolled) = wiring
.resident(NodeId::new(1), Shout, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert!(resident.effect().is_lands());
assert_eq!(resident.nudges().len(), 0, "nothing declared downstream");
}
#[test]
fn a_resident_does_not_publish_to_a_consumer_this_deployment_leaves_dark() {
let plan = Plan::new(pair(DriverKind::Thread))
.with_enablement(Enablement::new().launching("shout"))
.wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
let wired = wired(plan);
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _enrolled) = wiring
.resident(NodeId::new(0), Shout, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert_eq!(
resident.nudges().len(),
0,
"an enabled producer with a dark consumer has one edge fewer"
);
}
#[test]
fn only_a_channel_out_edge_is_something_a_resident_sends_over() {
for listen in [
Listen::Changes(Feeder::InGraph),
Listen::Poll(Duration::from_millis(5)),
Listen::Transient,
] {
let plan = pair_plan(DriverKind::Thread)
.upstream(EdgeId::new(0), UpstreamWiring::new(listen, AckMode::Local))
.wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
let wired = wired(plan);
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _enrolled) = wiring
.resident(NodeId::new(0), Shout, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert_eq!(resident.nudges().len(), 0, "{listen} is not a send");
}
}
#[test]
fn the_ack_mode_folds_toward_the_source_that_asked_to_be_chained() {
let plan = pair_plan(DriverKind::Thread).upstream(
EdgeId::new(0),
UpstreamWiring::new(Listen::Channel, AckMode::Chained),
);
let wired = wired(plan);
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _enrolled) = wiring
.resident(NodeId::new(1), Shout, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert!(
resident.ack().is_chained(),
"releasing early would break what the upstream was promised"
);
}
#[test]
fn a_poll_source_carries_an_ack_word_nothing_reads() {
let plan = pair_plan(DriverKind::Thread)
.upstream(
EdgeId::new(0),
UpstreamWiring::new(Listen::Poll(Duration::from_millis(5)), AckMode::Chained),
)
.wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
let wired = wired(plan);
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _enrolled) = wiring
.resident(NodeId::new(1), Shout, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert!(resident.ack().is_local());
}
#[test]
fn every_resident_the_walk_builds_observes_through_the_taps_it_was_assembled_with() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire().with_taps(
Taps::new()
.with(Arc::new(RecordingTap::new()))
.with(Arc::new(RecordingTap::new())),
);
assert_eq!(wiring.taps().len(), 2);
let inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _enrolled) = wiring
.resident(NodeId::new(0), Shout, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert_eq!(resident.taps().len(), 2);
}
#[test]
fn a_body_that_will_be_running_is_a_party_the_shutdown_waits_for() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
for index in [0, 1] {
let inbox = wiring
.inbox::<String>(NodeId::new(index))
.expect("nothing to refuse")
.expect("the deployment launches it");
wiring
.resident(NodeId::new(index), Shout, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
}
let assembly = wiring.into_assembly();
assert_eq!(assembly.shutdown().len(), 2, "N is exact at wiring");
let named: Vec<&str> = assembly
.shutdown()
.parties()
.iter()
.map(|party| party.name().as_str())
.collect();
assert_eq!(named, ["shout", "titles"]);
}
#[test]
fn the_schedule_a_node_runs_on_is_read_off_its_declared_poll_sources() {
let wired = wired(reaper_plan(DriverKind::Async));
let wiring = wired.create().wire();
let schedule = wiring.schedule(NodeId::new(2));
assert_eq!(schedule.len(), 2, "one entry per declared poll upstream");
assert_eq!(
schedule.interval(PollUpstream::new(0)),
Some(REAP),
"declaration order is what a poll upstream's position means"
);
assert_eq!(schedule.interval(PollUpstream::new(1)), Some(COMPACT));
assert!(
wiring.schedule(NodeId::new(0)).is_empty(),
"a node that declared none has none"
);
}
#[test]
fn a_channel_source_is_not_a_clock() {
let wired = wired(pair_plan(DriverKind::Async));
let wiring = wired.create().wire();
assert!(wiring.schedule(NodeId::new(1)).is_empty());
}
#[test]
fn a_thread_node_needs_no_cadence_because_it_times_itself() {
let wired = wired(reaper_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
assert_eq!(
wiring.schedule(NodeId::new(2)).len(),
2,
"it declared the upstreams all the same"
);
let clocks = wiring
.clock::<String>(NodeId::new(2), Duration::from_secs(1))
.expect("nothing to refuse");
assert_eq!(clocks, 0);
assert!(wiring.into_assembly().cadences().is_empty());
}
#[test]
fn an_async_node_gets_one_cadence_per_poll_source_and_one_for_the_sweep() {
let wired = wired(reaper_plan(DriverKind::Async));
let mut wiring = wired.create().wire();
let clocks = wiring
.clock::<String>(NodeId::new(2), Duration::from_secs(1))
.expect("nothing to refuse");
assert_eq!(clocks, 3, "two declared upstreams plus the liveness floor");
let mut assembly = wiring.into_assembly();
let cadences = assembly.take_cadences();
let intervals: Vec<Duration> = cadences
.iter()
.map(|cadence| {
cadence
.until_next()
.expect("an interval is always due again")
})
.collect();
assert_eq!(intervals, [REAP, COMPACT, Duration::from_secs(1)]);
assert!(assembly.cadences().is_empty(), "taken, not copied");
}
#[test]
fn an_async_node_this_deployment_leaves_dark_gets_no_clock() {
let plan = Plan::new(pair(DriverKind::Async))
.with_enablement(Enablement::new().launching("shout"))
.wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
let wired = wired(plan);
let mut wiring = wired.create().wire();
assert_eq!(
wiring
.clock::<String>(NodeId::new(1), Duration::from_secs(1))
.expect("nothing to refuse"),
0
);
}
#[test]
fn the_assembly_holds_the_edges_open_until_it_closes_them() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let mut assembly = wiring.into_assembly();
assert_eq!(assembly.senders(), 1);
assert!(
!inbox.is_disconnected(),
"a body with no producer must not stop before it starts"
);
assembly.close();
assert_eq!(assembly.senders(), 0);
assert!(
inbox.is_disconnected(),
"closing the framework's own halves is the wave's first domino"
);
}
#[test]
fn an_edge_nobody_took_a_reader_from_is_an_edge_this_deployment_does_not_have() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
let outbox = wiring
.outbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let assembly = wiring.into_assembly();
assert_eq!(assembly.senders(), 0);
assert!(outbox.is_disconnected());
}
#[test]
fn a_query_door_is_the_same_two_halves_over_a_transient_edge() {
let plan = pair_plan(DriverKind::Thread)
.upstream(
EdgeId::new(0),
UpstreamWiring::new(Listen::Transient, AckMode::Local),
)
.wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
let wired = wired(plan);
let mut wiring = wired.create().wire();
let door = wiring
.door::<String, u8>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let invokes = wiring
.invokes::<String, u8>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let _awaiting = door.invoke("ask".to_owned()).expect("the arm is listening");
assert_eq!(invokes.len(), 1);
let twice = wiring
.invokes::<String, u8>(NodeId::new(1))
.expect_err("one transient inbox per node");
let (node, taken) = refused::<TakenInboxError>(&twice);
assert_eq!(node, "titles");
assert!(taken.inbox().contains("Invokes"), "{}", taken.inbox());
}
#[test]
fn a_door_asked_for_under_the_wrong_pair_of_types_names_both() {
let plan = pair_plan(DriverKind::Thread)
.upstream(
EdgeId::new(0),
UpstreamWiring::new(Listen::Transient, AckMode::Local),
)
.wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
let wired = wired(plan);
let mut wiring = wired.create().wire();
wiring
.door::<String, u8>(NodeId::new(1))
.expect("nothing to refuse");
let mismatch = wiring
.invokes::<String, u16>(NodeId::new(1))
.expect_err("the door answers with a u8");
let (_node, error) = refused::<EdgeTypeError>(&mismatch);
assert!(error.carries().contains("u8"), "{}", error.carries());
assert!(error.wanted().contains("u16"), "{}", error.wanted());
}
#[test]
fn a_door_and_a_data_edge_on_one_node_are_two_edges() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
let _inbox = wiring
.inbox::<String>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
let _invokes = wiring
.invokes::<String, u8>(NodeId::new(1))
.expect("nothing to refuse")
.expect("the deployment launches it");
assert_eq!(wiring.into_assembly().senders(), 2);
}
#[test]
fn a_party_that_is_not_a_node_enrols_through_the_same_door() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
let intake = wiring.enrol("shout/intake");
assert_eq!(wiring.shutdown().len(), 1);
let assembly = wiring.into_assembly();
assert!(!assembly.shutdown().parties()[0].settled());
intake.settle();
assert!(assembly.shutdown().parties()[0].settled());
}
#[test]
fn the_walk_carries_the_context_the_create_walk_filled() {
let wired = wired(pair_plan(DriverKind::Thread));
let wiring = wired.create().wire();
assert!(wiring.context().is_empty(), "this plan demands no resource");
assert_eq!(wiring.into_assembly().context().len(), 0);
}
#[test]
fn the_two_capacities_are_shipped_constants_and_the_door_is_the_shallower_one() {
const {
assert!(Wiring::CAPACITY > 0);
assert!(Wiring::DOOR_CAPACITY > 0);
assert!(Wiring::DOOR_CAPACITY < Wiring::CAPACITY);
}
}
#[test]
fn an_operator_whose_types_are_not_the_edge_s_is_refused_at_the_wiring() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
wiring
.outbox::<u8>(NodeId::new(1))
.expect("nothing to refuse");
let inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let Err(mismatch) = wiring.resident(NodeId::new(0), Shout, inbox) else {
panic!("its consumer's edge carries bytes")
};
let (node, error) = refused::<EdgeTypeError>(&mismatch);
assert_eq!(node, "titles", "the edge that did not fit");
assert!(error.carries().contains("u8"));
assert!(error.wanted().contains("String"));
}
#[test]
fn the_walk_hands_back_an_assembly_that_runs() {
let seen = Arc::new(Mutex::new(Vec::new()));
let wired = wired(pair_plan(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 (mut head, head_party) = wiring
.resident(NodeId::new(0), Shout, head_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let (mut leaf, leaf_party) = wiring
.resident(NodeId::new(1), Keeping { seen: seen.clone() }, leaf_inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
let mut assembly = wiring.into_assembly();
let head_engine = thread::spawn(move || {
let report = head.run();
head_party.settle();
report
});
let leaf_engine = thread::spawn(move || {
let report = leaf.run();
leaf_party.settle();
report
});
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);
assembly.close();
let head_report = head_engine.join().expect("the head's engine");
let leaf_report = leaf_engine.join().expect("the leaf's engine");
assert_eq!(head_report.items(), 1);
assert_eq!(
leaf_report.items(),
1,
"the edge the walk minted carried it"
);
assert_eq!(*seen.lock().expect("the walk's record"), ["ONE"]);
assert!(
assembly.shutdown().parties().iter().all(Party::settled),
"every party the walk counted answered"
);
}
#[test]
fn a_second_operator_type_is_wired_the_same_way() {
let mut builder = GraphBuilder::new();
let counter = builder.source::<Counting>("counter", DriverKind::Thread);
let sink = builder.node::<Counting>("sink", DriverKind::Thread);
builder.edge(&counter, &sink, FanoutKind::Broadcast);
let graph = builder.validate().expect("one edge validates");
let wired = wired(
Plan::new(graph)
.with_enablement(Enablement::new().launching("counter").launching("sink"))
.wiring(NodeId::new(1), NodeWiring::new(Effect::Lands).landing()),
);
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<u8>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _enrolled) = wiring
.resident(NodeId::new(0), Counting, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert_eq!(resident.nudges().len(), 1);
}
struct Vocabulary {
banner: String,
}
impl AsyncResource for Vocabulary {
type Error = Infallible;
type Options = String;
async fn build(_ctx: &Resources, banner: String) -> Result<Self, Self::Error> {
Ok(Self { banner })
}
}
struct Announcing;
declared!(Announcing);
impl Operator for Announcing {
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> {
let banner = ctx
.shared::<Vocabulary>()
.expect("the launch built one")
.banner
.clone();
for item in delivery.into_items() {
emitter.emit(format!("{banner}{}", item.into_value()));
}
Ok(())
}
}
#[test]
fn an_operator_reaches_the_launch_s_resources_from_inside_accept() {
let wired = wired(pair_plan(DriverKind::Thread));
let ctx = Resources::new().with(Shared::new(Vocabulary {
banner: ">> ".to_owned(),
}));
let mut wiring = Wiring::new(&wired, ctx, Taps::new());
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 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), Announcing, head)
.expect("nothing to refuse")
.expect("the deployment launches it");
let seen: Arc<Mutex<Vec<String>>> = Arc::default();
let (leaf, _leaf_party) = wiring
.resident(NodeId::new(1), Keeping { seen: seen.clone() }, leaf)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert!(
head
.resources()
.expect("the walk wired its map")
.holds::<Vocabulary>(),
"every node gets the ONE map"
);
drop(wiring);
let engines = [
thread::spawn(move || {
let mut head = head;
head.run();
}),
thread::spawn(move || {
let mut leaf = leaf;
leaf.run();
}),
];
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);
for engine in engines {
engine.join().expect("the engine thread");
}
assert_eq!(
seen.lock().expect("the walk's record").as_slice(),
[">> one".to_owned()],
"the banner came from the resource the operator asked for mid-call"
);
}
#[test]
fn a_resident_with_no_map_refuses_by_name_rather_than_silently() {
let ctx = Resources::new();
assert_eq!(
ctx
.shared::<Vocabulary>()
.expect_err("nothing built one")
.resource()
.as_str(),
core::any::type_name::<Vocabulary>()
);
}
fn two_producers(apart: bool) -> Plan {
let mut builder = GraphBuilder::new();
let left = builder.source::<Shout>("left", DriverKind::Thread);
let right = builder.source::<Shout>("right", DriverKind::Thread);
let sink = builder.node::<Shout>("sink", DriverKind::Thread);
builder.edge(&left, &sink, FanoutKind::Broadcast);
builder.edge(&right, &sink, FanoutKind::Broadcast);
let graph = builder.validate().expect("two edges validate");
let declared = NodeWiring::new(Effect::Lands).landing();
Plan::new(graph)
.with_enablement(
Enablement::new()
.launching("left")
.launching("right")
.launching("sink"),
)
.wiring(
NodeId::new(2),
if apart { declared.drawing() } else { declared },
)
}
fn put(outbox: &crate::Outbox<ItemId, String>, said: &str) {
let (ack, _answers) = ack_channel::<ItemId>();
outbox
.deliver(Delivery::new(
Payload::One(Item::new(ItemId::new(0), said.to_owned())),
ack,
))
.map_err(|_| "the consumer is here")
.expect("delivered");
}
fn queued(inbox: &crate::Inbox<ItemId, String>) -> Vec<String> {
inbox
.drain()
.filter_map(|wake| match wake {
crate::Wake::Delivered(delivery) => Some(delivery),
crate::Wake::Sweep | crate::Wake::Tick(_) => None,
})
.flat_map(|delivery| delivery.into_items())
.map(Item::into_value)
.collect()
}
#[test]
fn a_source_position_is_the_place_among_the_consumer_s_channel_edges() {
let wired = wired(two_producers(true));
let wiring = wired.create().wire();
let sink = NodeId::new(2);
assert_eq!(wiring.source_of(sink, EdgeId::new(0)), Some(0));
assert_eq!(wiring.source_of(sink, EdgeId::new(1)), Some(1));
assert_eq!(wiring.source_of(NodeId::new(0), EdgeId::new(0)), None);
}
#[test]
fn a_poll_edge_takes_no_source_position_because_it_delivers_nothing() {
let wired = wired(reaper_plan(DriverKind::Thread));
let wiring = wired.create().wire();
let reaper = NodeId::new(2);
assert_eq!(wiring.source_of(reaper, EdgeId::new(0)), None);
assert_eq!(wiring.source_of(reaper, EdgeId::new(1)), None);
}
#[test]
fn a_node_that_draws_apart_takes_each_producer_on_its_own_edge() {
let wired = wired(two_producers(true));
let mut wiring = wired.create().wire();
let sink = NodeId::new(2);
let first = wiring
.source_inbox::<String>(sink, 0)
.expect("nothing to refuse")
.expect("launched");
let second = wiring
.source_inbox::<String>(sink, 1)
.expect("nothing to refuse")
.expect("launched");
assert!(
wiring.source_inbox::<String>(sink, 0).is_err(),
"one receiver per upstream, exactly as one per node"
);
let mut residents = Vec::new();
let mut senders = Vec::new();
for producer in [NodeId::new(0), NodeId::new(1)] {
senders.push(
wiring
.outbox::<String>(producer)
.expect("nothing to refuse")
.expect("launched"),
);
let inbox = wiring
.inbox::<String>(producer)
.expect("nothing to refuse")
.expect("launched");
let (resident, _enrolled) = wiring
.resident(producer, Shout, inbox)
.expect("nothing to refuse")
.expect("launched");
residents.push(resident);
}
drop(wiring);
for (resident, sender) in residents.into_iter().zip(senders) {
let said = if resident.name().as_str() == "left" {
"from-left"
} else {
"from-right"
};
put(&sender, said);
drop(sender);
let mut resident = resident;
resident.run();
}
assert_eq!(queued(&first), ["FROM-LEFT"]);
assert_eq!(
queued(&second),
["FROM-RIGHT"],
"and nothing of the other upstream's, which is the whole of what per-upstream channels buy"
);
}
#[test]
fn a_fan_in_node_still_takes_every_producer_on_one_inbox() {
let wired = wired(two_producers(false));
let mut wiring = wired.create().wire();
let only = wiring
.inbox::<String>(NodeId::new(2))
.expect("nothing to refuse")
.expect("launched");
let mut residents = Vec::new();
let mut senders = Vec::new();
for producer in [NodeId::new(0), NodeId::new(1)] {
senders.push(
wiring
.outbox::<String>(producer)
.expect("nothing to refuse")
.expect("launched"),
);
let inbox = wiring
.inbox::<String>(producer)
.expect("nothing to refuse")
.expect("launched");
let (resident, _enrolled) = wiring
.resident(producer, Shout, inbox)
.expect("nothing to refuse")
.expect("launched");
residents.push(resident);
}
drop(wiring);
for (resident, sender) in residents.into_iter().zip(senders) {
put(&sender, "said");
drop(sender);
let mut resident = resident;
resident.run();
}
assert_eq!(
queued(&only).len(),
2,
"both producers meet on the one inbox a fan-in node has always had"
);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct MediaId(u64);
#[test]
fn the_walk_hands_its_registries_to_the_residents_and_to_the_running_world() {
let quiet = Duration::from_millis(7);
let wired = wired(pair_plan(DriverKind::Thread));
let registries = Arc::new(crate::Registries::new(
crate::RegistryOptions::new().with_debounce(quiet),
));
let mut wiring = wired
.create()
.wire()
.with_registries(Arc::clone(®istries));
assert!(Arc::ptr_eq(wiring.registries(), ®istries));
let upstream = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _enrolled) = wiring
.resident(NodeId::new(0), Shout, upstream)
.expect("nothing to refuse")
.expect("the deployment launches it");
let held = resident.registries().expect("the walk wired one");
assert_eq!(held.options().debounce(), quiet);
let opened = held.open::<MediaId>("media");
assert_eq!(opened.options().debounce(), quiet);
assert_eq!(
opened.retire(&MediaId(1), crate::RetireOrigin::User, crate::Stamp::now()),
crate::RootAdvance::Moved
);
let assembly = wiring.into_assembly();
assert!(Arc::ptr_eq(assembly.registries(), ®istries));
let app = assembly.ignite().into_app::<()>();
let seen = app
.registries()
.of::<MediaId>()
.expect("the world's tables are the resident's");
assert!(Arc::ptr_eq(&opened, &seen));
assert!(matches!(
seen.state(&MediaId(1)),
crate::RootState::Retired {
origin: crate::RetireOrigin::User,
..
}
));
drop(app.abort());
}
#[test]
fn a_walk_that_names_no_registries_runs_the_shipped_ones() {
let wired = wired(pair_plan(DriverKind::Thread));
let wiring = wired.create().wire();
assert_eq!(
wiring.registries().options(),
&crate::RegistryOptions::new()
);
assert!(
wiring.registries().is_empty(),
"nothing is open until something opens it"
);
}
static PROJECTED: Mutex<Vec<String>> = Mutex::new(Vec::new());
#[derive(Default)]
struct Projecting;
impl crate::Attributes<String> for Projecting {
type Root = String;
fn root(&self, record: &String) -> Self::Root {
PROJECTED
.lock()
.expect("the walk's record")
.push(record.clone());
record.clone()
}
fn observe(&self, _root: &Self::Root, _worker: &crate::NodeName, _arrival: &crate::Arrival) {}
}
struct Attributed;
impl crate::Declared for Attributed {
const EFFECT: crate::Effect = crate::Effect::Pure;
type Attribution<O> = Projecting;
type Channels = crate::Unchanneled;
type Mode = crate::Block;
type Options = ();
type Pair = crate::Buffered;
type Wires<O> = crate::Downstream<O>;
}
impl Operator for Attributed {
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() {
emitter.emit(item.into_value());
}
Ok(())
}
}
#[test]
fn a_declarations_own_projection_reaches_its_running_node() {
PROJECTED.lock().expect("the walk's record").clear();
let wired = wired(pair_plan(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 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), Attributed, head)
.expect("nothing to refuse")
.expect("the deployment launches it");
let seen: Arc<Mutex<Vec<String>>> = Arc::default();
let (leaf, _leaf_party) = wiring
.resident(NodeId::new(1), Keeping { seen: seen.clone() }, leaf)
.expect("nothing to refuse")
.expect("the deployment launches it");
drop(wiring);
let engines = [
thread::spawn(move || {
let mut head = head;
head.run();
}),
thread::spawn(move || {
let mut leaf = leaf;
leaf.run();
}),
];
let (ack, _answers) = ack_channel();
feed
.deliver(Delivery::new(
Payload::One(Item::new(ItemId::new(0), "keyframe".to_owned())),
ack,
))
.expect("the head is listening");
drop(feed);
for engine in engines {
engine.join().expect("the engine thread");
}
assert_eq!(
seen.lock().expect("the walk's record").as_slice(),
["keyframe".to_owned()],
"the output reached the leaf"
);
assert_eq!(
PROJECTED.lock().expect("the walk's record").as_slice(),
["keyframe".to_owned()],
"and the DECLARED projection is what the node attributed it through"
);
}
#[test]
fn a_declaration_that_seats_nothing_is_wired_by_the_same_line() {
let wired = wired(pair_plan(DriverKind::Thread));
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<String>(NodeId::new(0))
.expect("nothing to refuse")
.expect("the deployment launches it");
let (resident, _party) = wiring
.resident(NodeId::new(0), Shout, inbox)
.expect("nothing to refuse")
.expect("the deployment launches it");
assert_eq!(resident.name().as_str(), "shout");
}