use crate::Context;
use core::convert::Infallible;
use std::{rc::Rc, sync::Arc};
use crate::{
Async, AsyncSource, Block, Buffered, Control, DeclaredOrigin, Effect, Enablement, Feed, Fin,
GraphBuilder, LifecycleTap, MutationNode, NodeId, RecordingTap, Refusal, Resources, Source,
Station, Taps, Upstream,
};
struct Counting {
remaining: u64,
}
impl Source for Counting {
type Options = u64;
type Yield = u64;
type Mutation = ();
type Error = Infallible;
fn build(_ctx: &Resources, remaining: u64) -> Result<Self, Self::Error> {
Ok(Self { remaining })
}
fn run(
mut self,
ctx: Context,
giving: Feed<u64>,
_eating: Control<Infallible>,
) -> Result<Fin, Self::Error> {
while self.remaining > 0 {
if ctx.shutdown().is_shutdown() {
return Ok(Fin::Stopped);
}
if giving.give(self.remaining).is_err() {
return Ok(Fin::Stopped);
}
self.remaining -= 1;
}
Ok(Fin::Spent)
}
}
impl DeclaredOrigin for Counting {
type Mode = Block;
}
struct Pinned {
seed: u64,
}
impl AsyncSource for Pinned {
type Options = u64;
type Yield = u64;
type Mutation = ();
type Error = Infallible;
async fn build(_ctx: &Resources, seed: u64) -> Result<Self, Self::Error> {
Ok(Self { seed })
}
async fn run(
self,
_ctx: Context,
giving: Feed<u64>,
_eating: Control<Infallible>,
) -> Result<Fin, Self::Error> {
let here = Rc::new(self.seed);
let _ = giving.give_async(*here).await;
let _ = giving.give_async(*here + 1).await;
Ok(Fin::Spent)
}
}
impl DeclaredOrigin for Pinned {
type Mode = Async;
const MOUNTS: Option<&'static str> = Some("crate::Nothing");
}
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)
}
struct Keeping;
impl crate::Operator for Keeping {
type Error = Infallible;
type In = u64;
type Out = u64;
fn accept(
&mut self,
_ctx: &Context,
_delivery: crate::Delivery<u64>,
_emitter: &mut crate::Emitter<u64>,
) -> Result<(), Self::Error> {
Ok(())
}
}
impl crate::Declared for Keeping {
const EFFECT: Effect = Effect::Lands;
const HOLDS_LANE: bool = true;
const UPSTREAMS: &'static [Upstream] = &[Upstream::of::<Counting>("counting")];
type Channels = crate::Unchanneled;
type Mode = Block;
type Options = ();
type Pair = Buffered;
type Wires<O> = crate::Downstream<O>;
type Attribution<O> = ();
}
struct Watching;
impl crate::Operator for Watching {
type Error = Infallible;
type In = u64;
type Out = u64;
fn accept(
&mut self,
_ctx: &Context,
_delivery: crate::Delivery<u64>,
_emitter: &mut crate::Emitter<u64>,
) -> Result<(), Self::Error> {
Ok(())
}
}
impl crate::Declared for Watching {
const EFFECT: Effect = Effect::Lands;
const HOLDS_LANE: bool = true;
const UPSTREAMS: &'static [Upstream] = &[Upstream::of::<Pinned>("pinned")];
type Channels = crate::Unchanneled;
type Mode = Block;
type Options = ();
type Pair = Buffered;
type Wires<O> = crate::Downstream<O>;
type Attribution<O> = ();
}
#[test]
fn a_source_nobody_listens_to_is_refused_as_a_pure_leaf() {
let mut blueprint = crate::Blueprint::new();
let _ = blueprint.origin::<Counting>("counting");
let plan = blueprint
.into_plan()
.expect("one node with no edge is an arrangement")
.with_enablement(Enablement::new().launching("counting"));
let refused = plan.validate().expect_err("an origin nobody listens to");
let crate::LaunchError::Refused(refusals) = refused else {
panic!("the refusal is a validation refusal");
};
assert!(
refusals
.iter()
.any(|refusal| matches!(refusal, Refusal::PureLeaf(_))),
"{refusals:?}"
);
assert!(
refusals
.iter()
.any(|refusal| refusal.to_string().contains("counting")),
"{refusals:?}"
);
}
#[test]
fn an_origin_with_a_consumer_is_an_arrangement() {
let mut blueprint = crate::Blueprint::new();
let origin = blueprint.origin::<Counting>("counting");
let consumer = blueprint.node::<Keeping>("keeping");
assert_eq!(origin, NodeId::new(0));
assert_eq!(consumer, NodeId::new(1));
let plan = blueprint
.into_plan()
.expect("the edge joins on the origin's own identity")
.with_enablement(Enablement::new().launching("counting"));
let _: crate::Wired = plan.validate().expect("the deployment checks out");
}
#[test]
fn an_origin_is_joined_by_its_own_identity() {
let mut blueprint = crate::Blueprint::new();
let _ = blueprint.node::<Keeping>("keeping");
let refused = blueprint
.into_plan()
.expect_err("nothing mounts the origin its upstream names");
let crate::LaunchError::Refused(refusals) = refused else {
panic!("the refusal is a join refusal");
};
assert!(
refusals
.iter()
.any(|refusal| matches!(refusal, Refusal::UnknownUpstream(_))),
"{refusals:?}"
);
}
fn wired() -> crate::Wired {
let mut blueprint = crate::Blueprint::new();
let _ = blueprint.origin::<Counting>("counting");
let _ = blueprint.origin::<Pinned>("pinned");
let _ = blueprint.node::<Keeping>("keeping");
let _ = blueprint.node::<Watching>("watching");
blueprint
.into_plan()
.expect("the edges join")
.with_enablement(Enablement::new().launching("counting").launching("pinned"))
.validate()
.expect("the deployment checks out")
}
#[test]
fn one_door_mounts_both_faces_and_neither_call_names_one() {
let (tap, taps) = watching();
let plan = wired();
let mut wiring = plan.create().with_taps(taps).wire();
let counting = wiring.enrol("counting");
let pinned = wiring.enrol("pinned");
let mut ignition = wiring.into_assembly().ignite();
let blocking = ignition
.origin_declared::<Counting>("counting", Counting { remaining: 3 }, 8, counting)
.expect("its engine");
let awaited = ignition
.origin_declared::<Pinned>("pinned", Pinned { seed: 5 }, 8, pinned)
.expect("its engine");
let app = ignition.into_app::<()>();
app.until_stopped();
let stopped = app.shutdown(None);
assert_eq!(stopped.settled(), 2, "both origins settle their parties");
assert!(stopped.is_clean());
assert_eq!(
blocking.yielded().drain().collect::<Vec<_>>(),
vec![3, 2, 1]
);
assert_eq!(awaited.yielded().drain().collect::<Vec<_>>(), vec![5, 6]);
let seen = tap.seen();
assert_eq!(seen.len(), 2, "{seen:?}");
for named in ["counting", "pinned"] {
assert!(
seen
.iter()
.any(|(node, station)| node == named && *station == Station::Processed),
"{named}: {seen:?}"
);
}
}
#[test]
fn the_walk_mints_the_lines_and_hands_back_their_ends() {
let (_tap, taps) = watching();
let plan = wired();
let mut wiring = plan.create().with_taps(taps).wire();
let counting = wiring.enrol("counting");
let mut ignition = wiring.into_assembly().ignite();
let mounted = ignition
.origin_declared::<Counting>("counting", Counting { remaining: 2 }, 4, counting)
.expect("its engine");
let (commands, yielded, stopper) = mounted.into_parts();
let _: &crate::Commands<<() as MutationNode>::Command> = &commands;
let app = ignition.into_app::<()>();
app.until_stopped();
let stopped = app.shutdown(None);
assert!(stopped.is_clean());
assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![2, 1]);
assert!(!stopper.announce(), "the origin's life is over");
}
#[test]
fn the_declaration_states_its_face_and_the_node_it_mounts() {
const {
assert!(<Counting as crate::Lived<<Counting as DeclaredOrigin>::Mode>>::SYNC);
}
const {
assert!(!<Pinned as crate::Lived<<Pinned as DeclaredOrigin>::Mode>>::SYNC);
}
assert_eq!(Counting::MOUNTS, None);
assert_eq!(Pinned::MOUNTS, Some("crate::Nothing"));
}
#[test]
fn an_origin_enters_the_arrangement_as_a_head() {
let mut builder = GraphBuilder::new();
let handle = builder.origin::<Counting>("counting", crate::DriverKind::Thread);
assert_eq!(handle.id(), NodeId::new(0));
let graph = builder.validate().expect("one node validates");
assert!(graph.nodes()[0].is_source(), "an origin is a dataflow head");
}