use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use bytes::{Bytes, BytesMut};
use dashmap::DashMap;
use tokio::sync::{mpsc, oneshot};
use super::protocol::encode_producer_query;
use crate::server::Decided;
type Answer = Option<Decided>;
#[derive(Default)]
pub(crate) struct ProducerLinks {
routes: DashMap<String, (mpsc::Sender<Bytes>, u64)>,
next: AtomicU64,
waiting: DashMap<u64, oneshot::Sender<Answer>>,
}
struct Question<'a> {
links: &'a ProducerLinks,
id: u64,
}
impl Drop for Question<'_> {
fn drop(&mut self) {
self.links.waiting.remove(&self.id);
}
}
impl ProducerLinks {
pub(crate) fn register(&self, peer: &str, tx: mpsc::Sender<Bytes>, session: u64) {
self.routes.insert(peer.to_owned(), (tx, session));
}
pub(crate) fn release(&self, peer: &str, session: u64) {
self.routes.remove_if(peer, |_, (_, s)| *s == session);
}
pub(crate) fn reaches(&self, peer: &str) -> bool {
self.routes.contains_key(peer)
}
pub(crate) async fn ask(
&self,
peer: &str,
user: Option<&str>,
producer: &str,
within: Duration,
) -> Answer {
let tx = self.routes.get(peer).map(|route| route.0.clone())?;
let id = self.next.fetch_add(1, Ordering::Relaxed);
let (answer, answered) = oneshot::channel();
self.waiting.insert(id, answer);
let _question = Question { links: self, id };
let mut frame = BytesMut::new();
encode_producer_query(&mut frame, id, user, producer);
tokio::time::timeout(within, async {
tx.send(frame.freeze()).await.ok()?;
answered.await.ok().flatten()
})
.await
.ok()
.flatten()
}
pub(crate) fn answer(&self, id: u64, decided: Answer) {
if let Some((_, waiting)) = self.waiting.remove(&id) {
let _ = waiting.send(decided);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn a_peer_whose_queue_is_full_is_not_waited_for_past_the_deadline() {
let links = ProducerLinks::default();
let (tx, _rx) = mpsc::channel(1);
tx.try_send(Bytes::from_static(b"full")).unwrap();
links.register("peer", tx, 1);
let asked = links.ask("peer", None, "p", Duration::from_millis(5));
let decided = tokio::time::timeout(Duration::from_secs(2), asked)
.await
.expect("not waited for past its deadline");
assert!(decided.is_none());
assert!(links.waiting.is_empty(), "the question is let go");
}
#[tokio::test]
async fn a_question_dropped_while_it_waits_is_let_go() {
let links = ProducerLinks::default();
let (tx, _rx) = mpsc::channel(4);
links.register("peer", tx, 1);
let asked = links.ask("peer", None, "p", Duration::from_secs(60));
assert!(
tokio::time::timeout(Duration::from_millis(5), asked)
.await
.is_err()
);
assert!(links.waiting.is_empty(), "the question is let go");
}
}