use crate::error::AlreadySubscribed;
use crate::message::Message;
use futures_channel::mpsc;
use std::cell::RefCell;
pub(crate) type NotifySlot = RefCell<Option<mpsc::UnboundedSender<Message>>>;
pub(crate) fn subscribe(
slot: &NotifySlot,
) -> Result<mpsc::UnboundedReceiver<Message>, AlreadySubscribed> {
let mut slot = slot.borrow_mut();
if let Some(existing) = slot.as_ref()
&& !existing.is_closed()
{
return Err(AlreadySubscribed);
}
let (tx, rx) = mpsc::unbounded();
*slot = Some(tx);
Ok(rx)
}
pub(crate) fn unsubscribe(slot: &NotifySlot) {
let previous = slot.borrow_mut().take();
drop(previous);
}
pub(crate) fn route_notify(slot: &NotifySlot, msg: Message) -> Option<Message> {
if msg.header.notify == 0 {
return Some(msg);
}
route(slot, msg);
None
}
fn route(slot: &NotifySlot, notify: Message) {
let Some(sender) = slot.borrow().clone() else {
return;
};
if sender.unbounded_send(notify).is_err() {
*slot.borrow_mut() = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::BodyFormat;
use futures_util::StreamExt;
use std::cell::Cell;
use std::sync::Arc;
thread_local! {
static PROBE_SLOT: NotifySlot = const { RefCell::new(None) };
static PROBE_SAW_FREE_SLOT: Cell<Option<bool>> = const { Cell::new(None) };
}
struct ReentrantProbe;
impl std::task::Wake for ReentrantProbe {
fn wake(self: Arc<Self>) {
let free = PROBE_SLOT.with(|slot| slot.try_borrow_mut().is_ok());
PROBE_SAW_FREE_SLOT.with(|seen| seen.set(Some(free)));
}
}
fn notify(query: &str) -> Message {
frame(query, true)
}
fn response(query: &str) -> Message {
frame(query, false)
}
fn frame(query: &str, notify: bool) -> Message {
Message::builder()
.query_str(query)
.notify(notify)
.body_format(BodyFormat::Json)
.body_utf8("{}")
.build()
}
#[test]
fn a_second_subscribe_is_refused_while_the_first_receiver_lives() {
let slot = NotifySlot::default();
let _first = subscribe(&slot).expect("first subscribe");
assert_eq!(subscribe(&slot).unwrap_err(), AlreadySubscribed);
}
#[test]
fn the_refused_subscribe_leaves_the_incumbent_working() {
let slot = NotifySlot::default();
let mut first = subscribe(&slot).expect("first subscribe");
let _ = subscribe(&slot);
route(&slot, notify("/still-mine"));
let received = first.try_recv().expect("a notify");
assert_eq!(received.query_utf8(), "/still-mine");
}
#[test]
fn dropping_the_receiver_frees_the_slot_for_a_new_subscriber() {
let slot = NotifySlot::default();
drop(subscribe(&slot).expect("first subscribe"));
let mut second = subscribe(&slot).expect("resubscribe over a stale slot");
route(&slot, notify("/second"));
assert_eq!(second.try_recv().expect("a notify").query_utf8(), "/second");
}
#[test]
fn unsubscribe_hands_the_slot_back() {
let slot = NotifySlot::default();
let _first = subscribe(&slot).expect("first subscribe");
unsubscribe(&slot);
subscribe(&slot).expect("subscribe after unsubscribe");
}
#[test]
fn a_notify_with_no_subscriber_is_dropped_not_queued() {
let slot = NotifySlot::default();
route(&slot, notify("/nobody-listening"));
assert!(slot.borrow().is_none(), "no sender should be installed");
let mut late = subscribe(&slot).expect("subscribe after the drop");
assert!(
late.try_recv().is_err(),
"the earlier notify must not be replayed"
);
}
#[test]
fn routing_to_a_dropped_receiver_clears_the_stale_sender() {
let slot = NotifySlot::default();
drop(subscribe(&slot).expect("first subscribe"));
route(&slot, notify("/into-the-void"));
assert!(slot.borrow().is_none());
}
#[test]
fn unsubscribe_releases_its_borrow_before_waking_the_receiver() {
let mut rx = PROBE_SLOT.with(subscribe).expect("subscribe");
let waker = std::task::Waker::from(Arc::new(ReentrantProbe));
let mut cx = std::task::Context::from_waker(&waker);
assert!(
rx.poll_next_unpin(&mut cx).is_pending(),
"an empty, open channel should park"
);
PROBE_SLOT.with(unsubscribe);
match PROBE_SAW_FREE_SLOT.with(|seen| seen.get()) {
Some(true) => {}
Some(false) => panic!("the slot was still borrowed when the receiver woke"),
None => panic!("unsubscribe did not wake the parked receiver"),
}
}
#[test]
fn route_notify_consumes_a_notify_frame() {
let slot = NotifySlot::default();
let mut rx = subscribe(&slot).expect("subscribe");
let passed_back = route_notify(&slot, notify("/pushed"));
assert!(passed_back.is_none(), "a notify must not reach correlation");
assert_eq!(rx.try_recv().expect("a notify").query_utf8(), "/pushed");
}
#[test]
fn route_notify_hands_a_response_frame_back() {
let slot = NotifySlot::default();
let mut rx = subscribe(&slot).expect("subscribe");
let passed_back = route_notify(&slot, response("/reply"));
assert_eq!(
passed_back.expect("response handed back").query_utf8(),
"/reply"
);
assert!(rx.try_recv().is_err(), "subscriber must see nothing");
}
#[test]
fn a_delivered_notify_leaves_the_subscription_intact() {
let slot = NotifySlot::default();
let mut rx = subscribe(&slot).expect("subscribe");
route(&slot, notify("/first"));
route(&slot, notify("/second"));
assert_eq!(rx.try_recv().expect("a notify").query_utf8(), "/first");
assert_eq!(rx.try_recv().expect("a notify").query_utf8(), "/second");
assert!(slot.borrow().is_some());
}
}