use crate::Context;
use core::convert::Infallible;
use std::{rc::Rc, sync::Arc};
use super::{drive_awaited_origin, drive_origin, observed};
use crate::{
AsyncSource, Control, Enablement, Feed, Fin, GraphBuilder, LifecycleTap, NodeId, NodeName,
NodeWiring, Plan, RecordingTap, Resources, Source, Station, Taps, Wired, control, feed,
shutdown_signal,
};
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)
}
}
#[derive(Debug)]
struct SocketGone;
impl core::fmt::Display for SocketGone {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("the socket went away")
}
}
impl core::error::Error for SocketGone {}
struct Dying;
impl Source for Dying {
type Options = ();
type Yield = u64;
type Mutation = ();
type Error = SocketGone;
fn build(_ctx: &Resources, (): ()) -> Result<Self, Self::Error> {
Ok(Self)
}
fn run(
self,
_ctx: Context,
giving: Feed<u64>,
_eating: Control<Infallible>,
) -> Result<Fin, Self::Error> {
let _ = giving.give(1);
Err(SocketGone)
}
}
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)
}
}
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)
}
#[test]
fn a_blocking_origin_is_driven_to_its_ending() {
let (giving, yielded) = feed(8);
let (_commands, eating) = control(1);
let (_stopper, halt) = shutdown_signal();
let counting = Counting::build(&Resources::new(), 3).expect("nothing refuses");
let ctx = Context::new("counting").halting(halt);
assert_eq!(drive_origin(counting, ctx, giving, eating), Ok(Fin::Spent));
assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![3, 2, 1]);
}
#[test]
fn a_pinned_origin_is_driven_where_it_was_built() {
let (giving, yielded) = feed(4);
let (_commands, eating) = control(1);
let (_stopper, halt) = shutdown_signal();
let pinned = drive_awaited_origin(
Pinned { seed: 5 },
Context::new("pinned").halting(halt),
giving,
eating,
);
assert_eq!(pinned, Ok(Fin::Spent));
assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![5, 6]);
}
#[test]
fn an_ordinary_ending_reaches_the_taps_as_the_pure_station() {
let (tap, taps) = watching();
observed::<Infallible>(&taps, NodeName::new("walk"), Ok(Fin::Spent));
observed::<Infallible>(&taps, NodeName::new("watch"), Ok(Fin::Stopped));
assert_eq!(
tap.seen(),
vec![
("walk".to_owned(), Station::Processed),
("watch".to_owned(), Station::Processed),
]
);
}
#[test]
fn a_death_reaches_the_taps_as_a_failure() {
let (tap, taps) = watching();
observed(&taps, NodeName::new("watch"), Err(SocketGone));
assert_eq!(tap.seen(), vec![("watch".to_owned(), Station::Failed)]);
}
fn wired() -> Wired {
let mut builder = GraphBuilder::new();
let _ = builder.source::<Keeping>("keeping", crate::DriverKind::Thread);
let graph = builder.validate().expect("one node validates");
Plan::new(graph)
.with_enablement(Enablement::new().launching("keeping"))
.wiring(
NodeId::new(0),
NodeWiring::new(crate::Effect::Lands).landing(),
)
.validate()
.expect("the deployment checks out")
}
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: crate::Effect = crate::Effect::Lands;
type Channels = crate::Unchanneled;
type Mode = crate::Block;
type Options = ();
type Pair = crate::Buffered;
type Wires<O> = crate::Downstream<O>;
type Attribution<O> = ();
}
#[test]
fn a_launched_origin_lives_on_its_own_thread_and_settles_its_party() {
let (tap, taps) = watching();
let plan = wired();
let mut wiring = plan.create().with_taps(taps).wire();
let enrolled = wiring.enrol("counting");
let mut ignition = wiring.into_assembly().ignite();
let (giving, yielded) = feed(8);
let (_commands, eating) = control(1);
let (_stopper, halt) = shutdown_signal();
ignition
.origin(
"counting",
Counting { remaining: 3 },
giving,
eating,
halt,
enrolled,
)
.expect("its engine");
let stopped = ignition.into_app::<()>().shutdown(None);
assert_eq!(stopped.settled(), 1, "a finished origin settles its party");
assert!(stopped.is_clean());
assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![3, 2, 1]);
assert_eq!(
tap.seen(),
vec![("counting".to_owned(), Station::Processed)]
);
}
#[test]
fn a_launched_origin_that_dies_is_observed_and_settles_anyway() {
let (tap, taps) = watching();
let plan = wired();
let mut wiring = plan.create().with_taps(taps).wire();
let enrolled = wiring.enrol("dying");
let mut ignition = wiring.into_assembly().ignite();
let (giving, yielded) = feed(8);
let (_commands, eating) = control(1);
let (_stopper, halt) = shutdown_signal();
ignition
.origin("dying", Dying, giving, eating, halt, enrolled)
.expect("its engine");
let stopped = ignition.into_app::<()>().shutdown(None);
assert_eq!(stopped.settled(), 1);
assert!(stopped.is_clean());
assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![1]);
assert_eq!(tap.seen(), vec![("dying".to_owned(), Station::Failed)]);
}
#[test]
fn an_awaited_origin_is_launched_pinned_on_a_thread_of_its_own() {
let (tap, taps) = watching();
let plan = wired();
let mut wiring = plan.create().with_taps(taps).wire();
let enrolled = wiring.enrol("pinned");
let mut ignition = wiring.into_assembly().ignite();
let (giving, yielded) = feed(4);
let (_commands, eating) = control(1);
let (_stopper, halt) = shutdown_signal();
ignition
.awaited_origin("pinned", Pinned { seed: 5 }, giving, eating, halt, enrolled)
.expect("its engine");
let stopped = ignition.into_app::<()>().shutdown(None);
assert_eq!(stopped.settled(), 1);
assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![5, 6]);
assert_eq!(tap.seen(), vec![("pinned".to_owned(), Station::Processed)]);
}