use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
task::{Context, Poll, Wake, Waker},
};
use futures::{StreamExt, task::noop_waker_ref};
use super::*;
use crate::bus::Bus;
use rig_core::{
effect::{EffectKind, FamilyDescriptor, HandlerDescriptor, HandlerKey, Outcome},
serve::{Dispatch, Reply, Serve},
};
struct Counting(AtomicUsize);
impl Wake for Counting {
fn wake(self: Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
fn custom() -> EffectKind {
EffectKind::Custom {
kind: Arc::from("test"),
payload: serde_json::Value::Null,
}
}
struct Handler;
impl Serve for Handler {
type Family = rig_core::effect::family::Dynamic;
fn descriptor(&self) -> HandlerDescriptor {
HandlerDescriptor {
key: HandlerKey::from("k"),
family: FamilyDescriptor::Custom {
kind: "test".into(),
},
layers: Vec::new(),
}
}
async fn serve(&self, _kind: EffectKind, _dispatch: Dispatch) -> Reply {
Reply::Outcome(Ok(Outcome::Custom {
payload: serde_json::Value::Null,
}))
}
}
fn bus_with_a_waiting_run() -> (AgentBus, Arc<Counting>) {
let policy = ServingPolicy::default();
let (dispatcher, registrar, mut driver) = Bus::channel_with(policy);
driver.register("k", Handler).expect("a fresh key");
let bus = AgentBus::owned(dispatcher, registrar, driver, "owner".to_owned(), policy);
let waiting = Arc::new(Counting(AtomicUsize::new(0)));
let slot = bus.wakers.slot();
bus.wakers
.register(slot, &Waker::from(Arc::clone(&waiting)));
(bus, waiting)
}
#[test]
fn a_finished_run_wakes_the_runs_that_registered_while_it_drove() {
let (bus, waiting) = bus_with_a_waiting_run();
let key = HandlerKey::from("k");
let mut run = bus.drive(futures::stream::once(
bus.dispatcher().dispatch(&key, custom()),
));
let mut cx = Context::from_waker(noop_waker_ref());
assert!(
matches!(run.poll_next_unpin(&mut cx), Poll::Ready(Some(Ok(_)))),
"the run served its own dispatch while it drove"
);
assert_eq!(
waiting.0.load(Ordering::SeqCst),
0,
"serving the run's own dispatch woke nobody"
);
assert!(matches!(run.poll_next_unpin(&mut cx), Poll::Ready(None)));
assert_eq!(
waiting.0.load(Ordering::SeqCst),
1,
"the run that stopped driving woke the runs still registered, once"
);
}
#[test]
fn a_dropped_run_wakes_the_runs_that_registered_while_it_drove() {
let (bus, waiting) = bus_with_a_waiting_run();
let key = HandlerKey::from("k");
let mut run = bus.drive(futures::stream::once(
bus.dispatcher().dispatch(&key, custom()),
));
let mut cx = Context::from_waker(noop_waker_ref());
assert!(matches!(
run.poll_next_unpin(&mut cx),
Poll::Ready(Some(Ok(_)))
));
assert_eq!(waiting.0.load(Ordering::SeqCst), 0);
drop(run);
assert_eq!(
waiting.0.load(Ordering::SeqCst),
1,
"the dropped run woke the runs still registered, once"
);
}