use crate::Context;
use std::{
sync::{Arc, Mutex},
thread,
};
use super::*;
use crate::{
Emitter, Identifiable, Operator, Transformer,
drive::{
AsyncLands, Commit, Delivery, ItemId, Resident,
channel::{Inbox, channel},
lane::block_on,
message::{Item, Payload},
},
};
use crate::drive::Drives;
#[derive(Debug, Clone, PartialEq, Eq)]
struct Shot {
id: u32,
text: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ShotKey {
id: u32,
}
impl Identifiable for Shot {
type Id = u32;
fn id_ref(&self) -> &u32 {
&self.id
}
}
impl Transformer for Shot {
type Key = ShotKey;
type Lineage = ();
type Record = ();
type Graphql = ();
fn key(&self) -> ShotKey {
ShotKey { id: self.id }
}
}
fn shot(id: u32, text: &str) -> Shot {
Shot {
id,
text: text.to_owned(),
}
}
struct Passing;
impl Operator for Passing {
type In = Shot;
type Out = Shot;
type Error = core::convert::Infallible;
fn accept(
&mut self,
_ctx: &Context,
delivery: Delivery<Shot>,
emitter: &mut Emitter<Shot>,
) -> Result<(), Self::Error> {
let (payload, _) = delivery.into_parts();
for item in payload {
emitter.emit(item.into_value());
}
Ok(())
}
}
struct Half {
landed: Arc<Mutex<Vec<u32>>>,
}
#[derive(Debug)]
struct Refused;
impl core::fmt::Display for Refused {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("this store keeps odd ids only")
}
}
impl core::error::Error for Refused {}
impl AsyncLands<Shot> for Half {
type Error = Refused;
async fn land(&mut self, items: &[Shot]) -> Commit<Self::Error> {
let mut committed = Vec::new();
let mut landed = self.landed.lock().expect("the store is never poisoned");
for (position, shot) in items.iter().enumerate() {
if shot.id % 2 == 1 {
landed.push(shot.id);
committed.push(position);
}
}
if committed.len() == items.len() {
Commit::all()
} else {
Commit::only(committed, Refused)
}
}
}
#[test]
fn one_batch_reaches_two_edges_as_two_receipts() {
let (messaged, messages) = channel::<ItemId, Shot>(8);
let (notified, receipts) = channel::<ItemId, ShotKey>(8);
let mut downstream: Notified<Shot> = Notified::new();
downstream.messages().attach(messaged);
downstream.receipts().attach(notified);
assert_eq!(Sink::arity(&downstream), 2);
assert_eq!(downstream.nudges().len(), 2);
let batch = vec![
Item::new(ItemId::new(1), shot(1, "one")),
Item::new(ItemId::new(3), shot(3, "three")),
];
let (ack, _held) = crate::drive::message::ack_channel::<ItemId>();
assert!(block_on(downstream.deliver(0, batch.clone(), ack)));
let (ack, _held) = crate::drive::message::ack_channel::<ItemId>();
assert!(block_on(downstream.deliver(1, batch, ack)));
assert_eq!(drained(&messages), vec![shot(1, "one"), shot(3, "three")]);
assert_eq!(
drained(&receipts),
vec![ShotKey { id: 1 }, ShotKey { id: 3 }]
);
}
#[test]
fn both_receipts_carry_the_committed_subset_in_commit_order() {
let landed = Arc::new(Mutex::new(Vec::new()));
let (into, inbox) = channel::<ItemId, Shot>(8);
let (messaged, messages) = channel::<ItemId, Shot>(16);
let (notified, receipts) = channel::<ItemId, ShotKey>(16);
let mut downstream: Notified<Shot> = Notified::new();
downstream.messages().attach(messaged);
downstream.receipts().attach(notified);
let resident = Resident::new("shots", Passing, inbox)
.land(Half {
landed: Arc::clone(&landed),
})
.wire(downstream);
let batch: Vec<Item<Shot>> = [
(1u32, "one"),
(2, "two"),
(4, "four"),
(3, "three"),
(5, "five"),
]
.into_iter()
.map(|(id, text)| Item::new(ItemId::new(u64::from(id)), shot(id, text)))
.collect();
let (ack, _held) = crate::drive::message::ack_channel::<ItemId>();
block_on(into.deliver_async(Delivery::new(Payload::Batch(batch), ack)))
.expect("the resident is listening");
drop(into);
let engine = thread::spawn(move || {
let mut resident = resident;
resident.run()
});
engine.join().expect("the engine thread");
let committed = landed.lock().expect("the store is never poisoned").clone();
assert_eq!(committed, vec![1, 3, 5], "the store kept the odd ids");
let announced: Vec<u32> = drained(&messages).into_iter().map(|shot| shot.id).collect();
let receipted: Vec<u32> = drained(&receipts).into_iter().map(|key| key.id).collect();
assert_eq!(announced, committed);
assert_eq!(receipted, committed);
}
fn drained<T>(inbox: &Inbox<ItemId, T>) -> Vec<T> {
let mut seen = Vec::new();
for wake in inbox.drain() {
if let crate::drive::Wake::Delivered(delivery) = wake {
let (payload, _) = delivery.into_parts();
seen.extend(payload.into_iter().map(Item::into_value));
}
}
seen
}