use std::hash::Hash;
use dashmap::mapref::entry::Entry;
use dashmap::{DashMap, DashSet};
use tokio::sync::watch;
#[derive(Debug, Clone)]
pub(crate) enum Slot<T> {
Pending,
Ready(T),
}
pub(crate) type FlightMap<K, T> = DashMap<K, watch::Receiver<Slot<T>>>;
pub(crate) trait ReleaseClaim<K> {
fn release(&self, key: &K);
}
impl<K: Hash + Eq, W> ReleaseClaim<K> for DashMap<K, W> {
fn release(&self, key: &K) {
self.remove(key);
}
}
impl<K: Hash + Eq> ReleaseClaim<K> for DashSet<K> {
fn release(&self, key: &K) {
self.remove(key);
}
}
pub(crate) struct InFlightGuard<'a, K, C: ReleaseClaim<K>> {
claims: &'a C,
key: K,
}
impl<'a, K, C: ReleaseClaim<K>> InFlightGuard<'a, K, C> {
pub(crate) const fn new(claims: &'a C, key: K) -> Self {
Self { claims, key }
}
}
impl<K, C: ReleaseClaim<K>> Drop for InFlightGuard<'_, K, C> {
fn drop(&mut self) {
self.claims.release(&self.key);
}
}
pub(crate) struct Leader<'a, K: Hash + Eq, T> {
_claim: InFlightGuard<'a, K, FlightMap<K, T>>,
sender: watch::Sender<Slot<T>>,
}
impl<K: Hash + Eq, T> Leader<'_, K, T> {
pub(crate) fn publish(self, value: T) {
self.sender.send_replace(Slot::Ready(value));
}
}
pub(crate) struct Follower<T>(watch::Receiver<Slot<T>>);
impl<T> From<watch::Receiver<Slot<T>>> for Follower<T> {
fn from(receiver: watch::Receiver<Slot<T>>) -> Self {
Self(receiver)
}
}
impl<T: Clone + Send + Sync> Follower<T> {
pub(crate) async fn wait(mut self) -> Option<T> {
loop {
if let Slot::Ready(value) = &*self.0.borrow_and_update() {
return Some(value.clone());
}
if self.0.changed().await.is_err() {
return None;
}
}
}
}
pub(crate) enum Claim<'a, K: Hash + Eq, T> {
Leader(Leader<'a, K, T>),
Follower(Follower<T>),
}
pub(crate) fn claim_or_follow<K, T>(in_flight: &FlightMap<K, T>, key: K) -> Claim<'_, K, T>
where
K: Hash + Eq + Clone,
{
match in_flight.entry(key.clone()) {
Entry::Occupied(occupied) => Claim::Follower(Follower(occupied.get().clone())),
Entry::Vacant(vacant) => {
let (sender, receiver) = watch::channel(Slot::Pending);
vacant.insert(receiver);
Claim::Leader(Leader {
_claim: InFlightGuard::new(in_flight, key),
sender,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn claims_as_leader(flights: &FlightMap<&'static str, u32>) -> bool {
matches!(claim_or_follow(flights, "key"), Claim::Leader(_))
}
type Flights = FlightMap<&'static str, u32>;
fn leader<'a>(flights: &'a Flights, key: &'static str) -> Leader<'a, &'static str, u32> {
match claim_or_follow(flights, key) {
Claim::Leader(leader) => leader,
Claim::Follower(_) => panic!("expected to lead {key}"),
}
}
fn follower(flights: &Flights, key: &'static str) -> Follower<u32> {
match claim_or_follow(flights, key) {
Claim::Follower(follower) => follower,
Claim::Leader(_) => panic!("expected to follow {key}"),
}
}
#[tokio::test]
async fn the_first_caller_leads_and_later_callers_receive_its_value() {
let flights = Flights::new();
let leader = leader(&flights, "key");
let first = follower(&flights, "key");
let second = follower(&flights, "key");
leader.publish(7);
assert_eq!(first.wait().await, Some(7));
assert_eq!(second.wait().await, Some(7));
assert!(flights.is_empty(), "publishing releases the claim");
}
#[test]
fn distinct_keys_each_get_a_leader() {
let flights = Flights::new();
let _a = leader(&flights, "a");
let _b = leader(&flights, "b");
assert_eq!(flights.len(), 2);
}
#[tokio::test]
async fn dropping_the_leader_wakes_followers_after_freeing_the_key() {
let flights = Flights::new();
let leader = leader(&flights, "key");
let follower = follower(&flights, "key");
drop(leader);
assert_eq!(
follower.wait().await,
None,
"a follower sees its leader vanish"
);
assert!(flights.is_empty(), "the claim was released");
assert!(
claims_as_leader(&flights),
"a promoted follower can claim the key again"
);
}
#[tokio::test]
async fn followers_are_woken_only_after_the_claim_is_released() {
use std::sync::mpsc;
use std::time::Duration;
let flights: &'static Flights = Box::leak(Box::new(Flights::new()));
let leader = leader(flights, "key");
let mut waiting = Box::pin(follower(flights, "key").wait());
let (held_tx, held_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel::<()>();
let reader = std::thread::spawn(move || {
let guard = flights.get(&"key");
held_tx.send(()).unwrap();
release_rx.recv().unwrap();
drop(guard);
});
held_rx.recv().unwrap();
let (started_tx, started_rx) = mpsc::channel();
let dropper = std::thread::spawn(move || {
started_tx.send(()).unwrap();
drop(leader);
});
started_rx.recv().unwrap();
tokio::select! {
woken = &mut waiting => panic!("follower woke ({woken:?}) while the claim was still held"),
() = tokio::time::sleep(Duration::from_millis(200)) => {}
}
release_tx.send(()).unwrap();
assert_eq!(waiting.await, None);
assert!(claims_as_leader(flights));
reader.join().unwrap();
dropper.join().unwrap();
}
#[test]
fn the_leader_releases_its_claim_even_when_it_panics() {
let flights = Flights::new();
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _leader = leader(&flights, "key");
panic!("leader failed");
}));
assert!(outcome.is_err());
assert!(flights.is_empty());
}
#[test]
fn a_guard_releases_a_set_claim_on_drop() {
let claims: DashSet<&str> = DashSet::new();
claims.insert("key");
{
let _guard = InFlightGuard::new(&claims, "key");
}
assert!(claims.is_empty());
}
}