[relay] Calls: a long-poll on the fetch route, TURN credentials for coturn, wakes every 10 s; the module passes the TURN secret by systemd credential
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
//! The long-poll's waiting room (`.agents/features/calls-relay.md`): who is waiting for which mailbox, in memory
|
||||
//! only, an entry only while someone waits. Nothing here is ever written to disk or logged.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tabellarius_protocol::MailboxId;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
/// Waiters relay-wide before one more is answered at once.
|
||||
pub const MAX_WAITERS: usize = 1024;
|
||||
|
||||
pub struct Arrivals {
|
||||
waiting: Mutex<HashMap<MailboxId, (Arc<Notify>, usize)>>,
|
||||
max: usize,
|
||||
}
|
||||
|
||||
/// One waiter's place; leaving it (drop) removes the entry when nobody else waits for that mailbox.
|
||||
pub struct Place<'a> {
|
||||
arrivals: &'a Arrivals,
|
||||
id: MailboxId,
|
||||
pub notify: Arc<Notify>,
|
||||
}
|
||||
|
||||
impl Arrivals {
|
||||
pub fn new(max: usize) -> Self {
|
||||
Self { waiting: Mutex::new(HashMap::new()), max }
|
||||
}
|
||||
|
||||
/// A place to wait for `id`, or `None` when the relay already holds `max` waiters.
|
||||
pub fn enter(&self, id: MailboxId) -> Option<Place<'_>> {
|
||||
let mut w = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let total: usize = w.values().map(|(_, n)| n).sum();
|
||||
if total >= self.max {
|
||||
return None;
|
||||
}
|
||||
let entry = w.entry(id).or_insert_with(|| (Arc::new(Notify::new()), 0));
|
||||
entry.1 += 1;
|
||||
Some(Place { arrivals: self, id, notify: Arc::clone(&entry.0) })
|
||||
}
|
||||
|
||||
/// A blob arrived for `id`: everyone waiting for it is answered.
|
||||
pub fn arrived(&self, id: &MailboxId) {
|
||||
let w = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((n, _)) = w.get(id) {
|
||||
n.notify_waiters();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Place<'_> {
|
||||
fn drop(&mut self) {
|
||||
let mut w = self.arrivals.waiting.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = w.get_mut(&self.id) {
|
||||
entry.1 -= 1;
|
||||
if entry.1 == 0 {
|
||||
w.remove(&self.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user