use crate::Context;
use core::{convert::Infallible, time::Duration};
use std::sync::{Arc, Mutex};
use crate::{
Block, Buffered, ChannelOptions, Control, Declared, DeclaredOrigin, Delivery, Effect, Emitter,
Enablement, Feed, Fin, Inbox, ItemId, MutationNode, Operator, Resources, Source, Stopper,
Unchanneled, Upstream, Wake,
};
const PATIENCE: Duration = Duration::from_secs(10);
const STILLNESS: Duration = Duration::from_millis(200);
struct Counting {
count: u64,
gave: flume::Sender<u64>,
delivered: Arc<Mutex<Vec<u64>>>,
ended: Arc<Mutex<Option<Fin>>>,
}
impl Source for Counting {
type Options = ();
type Yield = u64;
type Mutation = ();
type Error = Infallible;
fn build(_ctx: &Resources, (): ()) -> Result<Self, Self::Error> {
unreachable!("this suite hands the mount a built origin, as the create walk would")
}
fn run(
self,
ctx: Context,
giving: Feed<u64>,
_eating: Control<Infallible>,
) -> Result<Fin, Self::Error> {
let mut fin = Fin::Spent;
for value in 1..=self.count {
if ctx.shutdown().is_shutdown() {
fin = Fin::Stopped;
break;
}
if giving.give(value).is_err() {
fin = Fin::Stopped;
break;
}
self
.delivered
.lock()
.expect("no test panics while holding this")
.push(value);
let _ = self.gave.send(value);
}
*self
.ended
.lock()
.expect("no test panics while holding this") = Some(fin);
Ok(fin)
}
}
impl DeclaredOrigin for Counting {
type Mode = Block;
}
struct Ledger;
impl Operator for Ledger {
type Error = Infallible;
type In = u64;
type Out = u64;
fn accept(
&mut self,
_ctx: &Context,
_delivery: Delivery<u64>,
_emitter: &mut Emitter<u64>,
) -> Result<(), Self::Error> {
Ok(())
}
}
impl Declared for Ledger {
const EFFECT: Effect = Effect::Lands;
const HOLDS_LANE: bool = true;
const UPSTREAMS: &'static [Upstream] =
&[Upstream::of::<Counting>("crate::Counting").channelled(ChannelOptions::Bounded(2))];
type Channels = Unchanneled;
type Mode = Block;
type Options = ();
type Pair = Buffered;
type Wires<O> = crate::Downstream<O>;
type Attribution<O> = ();
}
struct Running {
app: Option<crate::App<()>>,
inbox: Inbox<ItemId, u64>,
stopper: Stopper,
gave: flume::Receiver<u64>,
delivered: Arc<Mutex<Vec<u64>>>,
ended: Arc<Mutex<Option<Fin>>>,
}
impl Running {
fn start(count: u64) -> Self {
let mut blueprint = crate::Blueprint::new();
let _ = blueprint.origin::<Counting>("counting");
let ledger = blueprint.node::<Ledger>("ledger");
let wired = blueprint
.into_plan()
.expect("the edge joins on the origin's own identity")
.with_enablement(Enablement::new().launching("counting").launching("ledger"))
.validate()
.expect("the bridge opens that edge");
let mut wiring = wired.create().wire();
let inbox = wiring
.inbox::<u64>(ledger)
.expect("the consumer's input is what its declaration says")
.expect("this deployment launches the consumer");
let outbox = wiring
.outbox::<u64>(ledger)
.expect("the same edge, asked for under the same type")
.expect("this deployment launches the consumer");
let enrolled = wiring.enrol("counting");
let mut ignition = wiring.into_assembly().ignite();
let (gave, heard) = flume::unbounded();
let delivered = Arc::new(Mutex::new(Vec::new()));
let ended = Arc::new(Mutex::new(None));
let mounted: crate::Bridged<<() as MutationNode>::Command> = ignition
.origin_bridged::<Counting>(
"counting",
Counting {
count,
gave,
delivered: Arc::clone(&delivered),
ended: Arc::clone(&ended),
},
outbox,
4,
enrolled,
)
.expect("its engine");
let (_commands, stopper) = mounted.into_parts();
Self {
app: Some(ignition.into_app::<()>()),
inbox,
stopper,
gave: heard,
delivered,
ended,
}
}
fn taken(&self) -> Vec<(ItemId, u64)> {
let mut taken = Vec::new();
while let Some(wake) = self.inbox.park(Duration::ZERO) {
match wake {
Wake::Delivered(delivery) => {
let mut items = delivery.into_items();
let item = items.next().expect("a give is one item");
assert!(items.next().is_none(), "a give is ONE item, not a batch");
taken.push(item.into_parts());
}
Wake::Sweep => break,
Wake::Tick(_) => panic!("nothing rings a clock on this edge"),
}
}
taken
}
fn next_give(&self, patience: Duration) -> Option<u64> {
self.gave.recv_timeout(patience).ok()
}
fn delivered(&self) -> Vec<u64> {
self
.delivered
.lock()
.expect("no test panics while holding this")
.clone()
}
fn ended(&self) -> Option<Fin> {
*self
.ended
.lock()
.expect("no test panics while holding this")
}
fn until_stopped(&self) {
self
.app
.as_ref()
.expect("the app is still held")
.until_stopped();
}
fn shutdown(&mut self) {
let app = self.app.take().expect("shut down once");
let stopped = app.shutdown(None);
assert!(stopped.is_clean(), "{stopped:?}");
}
}
#[test]
fn a_bridged_origins_items_reach_the_consumers_inbox_as_deliveries() {
let mut running = Running::start(2);
running.until_stopped();
assert_eq!(running.ended(), Some(Fin::Spent));
let taken = running.taken();
assert_eq!(
taken.iter().map(|(_, value)| *value).collect::<Vec<_>>(),
vec![1, 2]
);
assert_eq!(
taken.iter().map(|(id, _)| *id).collect::<Vec<_>>(),
vec![ItemId::new(0), ItemId::new(1)],
"the ids are minted by this line, from zero, one per give"
);
running.shutdown();
}
#[test]
fn a_consumer_that_does_not_read_stalls_the_origin_on_the_edges_own_bound() {
let mut running = Running::start(5);
assert_eq!(running.next_give(PATIENCE), Some(1));
assert_eq!(running.next_give(PATIENCE), Some(2));
assert_eq!(
running.next_give(STILLNESS),
None,
"the third give must be waiting on a full edge"
);
assert_eq!(
running.inbox.len(),
2,
"the edge holds exactly what its declaration said it would"
);
assert_eq!(
running.delivered(),
vec![1, 2],
"and nothing beyond the bound was ever handed over"
);
let mut taken: Vec<u64> = Vec::new();
while taken.len() < 5 {
taken.extend(running.taken().into_iter().map(|(_, value)| value));
}
assert_eq!(taken, vec![1, 2, 3, 4, 5]);
running.until_stopped();
assert_eq!(running.ended(), Some(Fin::Spent));
running.shutdown();
}
#[test]
fn a_stop_mid_stream_leaves_the_consumer_exactly_what_was_delivered() {
let mut running = Running::start(1_000);
assert_eq!(running.next_give(PATIENCE), Some(1));
assert_eq!(running.next_give(PATIENCE), Some(2));
running.stopper.announce();
let mut seen: Vec<u64> = Vec::new();
while running.ended().is_none() {
seen.extend(running.taken().into_iter().map(|(_, value)| value));
let _ = running.next_give(STILLNESS);
}
running.until_stopped();
seen.extend(running.taken().into_iter().map(|(_, value)| value));
assert_eq!(running.ended(), Some(Fin::Stopped), "it heard the stop");
assert!(
!seen.is_empty(),
"the stop landed mid-stream, not before it"
);
assert_eq!(
seen,
running.delivered(),
"the consumer's tail is exactly what the origin's gives answered for"
);
running.shutdown();
}
#[test]
fn the_consumers_stream_ends_when_the_wind_down_releases_the_launchs_own_half() {
let mut running = Running::start(2);
running.until_stopped();
assert_eq!(running.ended(), Some(Fin::Spent));
assert_eq!(
running.taken().len(),
2,
"both items crossed before the life ended"
);
assert!(
!running.inbox.is_disconnected(),
"the launch still holds its own half of this edge"
);
running.shutdown();
assert!(
running.inbox.is_disconnected(),
"the wind-down released the last half but this origin's, and this origin's is long gone"
);
assert!(
!running.stopper.announce(),
"and the origin's life was over before the word was said"
);
}