//! In-process chat routing (ADR-028). Keyed by `avatar_id` (one per connection). //! //! Global delivery reuses one encoded frame; proximity (`Local`) encodes //! per recipient because each carries its own `distance_m`. This is the concrete //! form of the ADR's `ChatBus` seam — a trait can wrap it when multi-sim lands. //! //! It carries **voice as well as text**, and needed no generalising to do so: it //! deals in already-encoded frames (`Bytes`), so the payload was always opaque //! to it. Proximity voice is the text path with an audio frame in place of the //! string — including the per-recipient encode, which distance attenuation needs //! for exactly the reason `distance_m` already needed it. //! //! `Bytes` and not `Vec` for the fan-out's sake: a global line is handed to every //! connection, and cloning a `Vec` there is a copy of //! the whole frame per recipient where a `Bytes` is a reference count. //! //! # Why every outbox is bounded, and why there are two of them //! //! A connection's outbox is written by *other* connections' tasks and drained by //! its own. When the two rates differ, something has to give, and an unbounded //! queue answers "the server's memory" — one client whose TCP window has closed //! stalls its `select!` on a `framed.send`, while nearby speakers keep pushing //! ~100 KB/s of voice into a queue nobody is reading, and `send` on an unbounded //! channel cannot fail, so nothing anywhere reports it. The snapshot path had the //! answer already: a bounded `broadcast::channel(256)` whose `Lagged` is handled //! and shrugged off. These are the same shape, with [`Lane`] deciding what //! "handled" means for a frame that does not fit. use bytes::Bytes; use std::collections::{HashMap, HashSet}; use std::sync::Mutex; use crate::reach::Place; use cartopolis_core::permissions::PermissionSet; use tokio::sync::mpsc; /// Proximity radii in metres over the ground. `say` is default; `shout` /// widens it. pub const SAY_RADIUS_M: f32 = 50.0; pub const SHOUT_RADIUS_M: f32 = 300.0; /// Recipients of a proximity send, each with its own distance to the sender. /// /// Text and voice share this: both fan out by distance and both encode per /// recipient, differing only in what they put in the frame. `sender` is not /// filtered here — text echoes to the sender and voice must not, so that call /// belongs to the caller. /// /// Places on Earth (`reach::Place`), since protocol 47: a distance between two /// avatars used to be measured in metres of their own clients' map frames, /// which agreed only while the two happened to share an anchor. #[must_use] pub fn within_radius(origin: Place, candidates: &[(u64, Place)], radius: f32) -> Vec<(u64, f32)> { candidates .iter() .filter_map(|(id, p)| { let d = origin.distance_m(*p); (d <= radius).then_some((*id, d)) }) .collect() } /// Which of a connection's two outboxes a frame belongs in. /// /// The split exists because the two have opposite failure policies, not because /// they carry different bytes — the hub still deals in opaque encoded frames. A /// dropped voice frame is 20 ms of audio nobody will miss; a dropped chat line is /// something a person typed and believes was delivered. One queue could only have /// one policy, and whichever it was would be wrong for the other half. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Lane { Text, Voice, } /// Chat frames a connection may be behind before lines are dropped. /// /// Text is rate limited *per sender* (`net::MIN_LOCAL_INTERVAL` and friends), so /// filling 256 slots takes a crowd, not a flood — a client this far behind is not /// reading its socket at all. const TEXT_BACKLOG: usize = 256; /// Voice frames a connection may be behind. Deliberately about a second of audio /// at the 20 ms frame cadence: an unbounded queue was the bug, but a *large* /// bounded one is barely better, because everything in it is stale by the time it /// is sent. Keeping the queue shorter than human patience is what makes dropping /// the newest frame equivalent, in effect, to the client's own drop-the-oldest /// backlog policy (`platform::audio::MAX_BACKLOG`). const VOICE_BACKLOG: usize = 64; struct Client { text: mpsc::Sender, voice: mpsc::Sender, /// Usernames this connection refuses to hear, lowercased. Loaded from /// `blocks` at register time and updated in place by [`ChatHub::set_blocked`]. /// /// It lives here, on the *recipient*, because that is where the decision is: /// a block is one person's choice about their own client, not a sanction on /// the speaker. Keeping it beside the outbox is also what makes enforcement /// free — the fan-out already walks every connection, and skipping one costs /// a set lookup rather than a second encode or a database round trip on a /// path that runs at conversation speed. blocked: HashSet, /// The account behind this connection (`accounts.id`), which is what a /// private chat's membership is keyed by. account: String, /// This installation's private-chat device, once it has registered one /// (`NetMessage::E2eeRegisterDevice`). A connection with none gets no /// private-chat traffic: it has no keys to read it with. device: Option, } impl Client { /// Hand a frame to one of this connection's outboxes, never blocking. /// /// `try_send` rather than `send().await` is the whole point: this is called /// from *other* clients' tasks, while the hub's mutex is held. An `.await` /// here would park a speaker's connection task on a listener's socket. fn enqueue(&self, avatar_id: u64, lane: Lane, frame: Bytes) { let tx = match lane { Lane::Text => &self.text, Lane::Voice => &self.voice, }; match tx.try_send(frame) { Ok(()) => {} Err(mpsc::error::TrySendError::Full(_)) => match lane { // Worth a line: someone's words went missing, and the operator is // the only one who can see that it happened. Lane::Text => tracing::warn!( avatar_id, "chat backlog full; dropped a message for this client" ), Lane::Voice => tracing::trace!(avatar_id, "voice backlog full; dropped a frame"), }, // The connection is on its way out and has not called `unregister` // yet. Nothing to say and nothing to do. Err(mpsc::error::TrySendError::Closed(_)) => {} } } } #[derive(Default)] pub struct ChatHub { clients: Mutex>, /// What each connected account may do, one watch per account that every /// connection signed in as it subscribes to. Here because this hub is the /// one thing both the connections and the HTTP routes that change roles /// already share (`roles::refresh_grants`). grants: Mutex>>, /// Where a private message for somebody with no device connected goes to /// wake their closed app (`crate::push`); unset in tests that start none. wake: std::sync::OnceLock>, /// Calls in chats whose hub is another server, both sides of them /// (`crate::remote::calls`): the connections, the HTTP routes and the /// calls task all reach them, and this hub is what they share. pub elsewhere: crate::remote::calls::Elsewhere, } /// Lock the hub, surviving poisoning. `connected_ids` runs inside the tick loop, /// so a panic under this lock must not become a panic in every subsequent tick — /// that turns one bad message into a world that stops advancing. The map carries /// no multi-step invariant; the worst a mid-panic value can be is one client's /// entry in a stale state, which the next register/unregister corrects. fn locked(m: &Mutex>) -> std::sync::MutexGuard<'_, HashMap> { m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } impl ChatHub { pub fn new() -> Self { Self::default() } /// Register a connection's personal chat outboxes and return the receiving /// ends, which the connection task drains. /// /// The hub creates them rather than taking them, so the capacities — and the /// fact that there are two — live next to the policy that enforces them. /// `blocked` is the connection's persisted block list (see the `blocks` /// table); it is passed in at register time rather than fetched here so the /// hub keeps no database handle. pub fn register( &self, avatar_id: u64, account: &str, blocked: impl IntoIterator, ) -> (mpsc::Receiver, mpsc::Receiver) { let (text, text_rx) = mpsc::channel(TEXT_BACKLOG); let (voice, voice_rx) = mpsc::channel(VOICE_BACKLOG); locked(&self.clients).insert( avatar_id, Client { text, voice, blocked: blocked.into_iter().map(|u| u.to_lowercase()).collect(), account: account.to_string(), device: None, }, ); (text_rx, voice_rx) } /// Record the private-chat device a connection registered. pub fn set_device(&self, avatar_id: u64, device: uuid::Uuid) { if let Some(c) = locked(&self.clients).get_mut(&avatar_id) { c.device = Some(device); } } /// Deliver a private-chat log entry to every connected device of `accounts`. /// /// A block withholds a blocked sender's *messages* but never their /// *commits*: a device that misses a membership change can read nothing in /// that chat again (`e2ee`'s rule 4). The sender's own connection gets it /// too — its other devices need it, and the sending device skips its own. pub fn deliver_private(&self, accounts: &[String], from: &str, is_commit: bool, frame: &Bytes) { let from = from.to_lowercase(); for (id, c) in locked(&self.clients).iter() { if c.device.is_none() || !accounts.contains(&c.account) { continue; } if !is_commit && c.blocked.contains(&from) { continue; } c.enqueue(*id, Lane::Text, frame.clone()); } } /// Wake pushes go to `push` from now on (`crate::push::spawn`). pub fn set_wake(&self, push: tokio::sync::mpsc::UnboundedSender) { let _ = self.wake.set(push); } /// A message was written in a private chat or topic: wake the closed apps /// of those of `accounts` with no private-chat device connected here, who /// therefore did not get it from [`Self::deliver_private`]. `from` is the /// writer's `accounts.id` (empty for somebody elsewhere), `from_name` what /// blocks are kept against. Commits are not messages and wake nobody. pub fn wake_for_message(&self, accounts: &[String], from: &str, from_name: &str) { let Some(wake) = self.wake.get() else { return }; let offline: Vec = { let clients = locked(&self.clients); accounts .iter() .filter(|a| *a != from) .filter(|a| { !clients .values() .any(|c| c.device.is_some() && &c.account == *a) }) .cloned() .collect() }; if offline.is_empty() { return; } let _ = wake.send(crate::push::Ring { kind: crate::push::Kind::Message, caller: from.to_owned(), caller_name: from_name.to_owned(), members: offline, }); } /// A call started in a chat another server is the hub of: wake the closed /// apps of `accounts`, as the calls task does for a call here. Every one /// but the caller, connected or not, because a call's push is what the /// app's receiver shows as ringing whether the app is open or shut. /// `caller` is their `accounts.id` when they live here, else empty. pub fn wake_for_call(&self, accounts: &[String], caller: &str, caller_name: &str) { let Some(wake) = self.wake.get() else { return }; if accounts.iter().all(|a| a == caller) { return; } let _ = wake.send(crate::push::Ring { kind: crate::push::Kind::Call, caller: caller.to_owned(), caller_name: caller_name.to_owned(), members: accounts.to_vec(), }); } /// Deliver a frame to **one** connected private-chat device of any of /// `accounts`, and say whether there was one. For a job one device should /// do rather than every device racing to (`ChannelJoinRequest`: each /// device that tried would spend one of the joiner's key packages). pub fn deliver_to_one_device(&self, accounts: &[String], frame: &Bytes) -> bool { let clients = locked(&self.clients); let Some((id, c)) = clients .iter() .find(|(_, c)| c.device.is_some() && accounts.contains(&c.account)) else { return false; }; c.enqueue(*id, Lane::Text, frame.clone()); true } /// The first of `devices` that has a connection right now. pub fn connected_device_among(&self, devices: &[uuid::Uuid]) -> Option { let clients = locked(&self.clients); devices .iter() .find(|d| clients.values().any(|c| c.device == Some(**d))) .copied() } /// Deliver a frame to whichever connection has registered `device`. pub fn deliver_to_device(&self, device: uuid::Uuid, frame: &Bytes) { for (id, c) in locked(&self.clients).iter() { if c.device == Some(device) { c.enqueue(*id, Lane::Text, frame.clone()); } } } /// Subscribe a new connection to its account's permissions, recording /// `now` (just read from the database) as the current value. Another /// connection of the same account is told too if `now` differs from what it /// holds — it is the newer reading. pub fn watch_grants( &self, account: &str, now: PermissionSet, ) -> tokio::sync::watch::Receiver { let mut grants = self .grants .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let tx = grants .entry(account.to_string()) .or_insert_with(|| tokio::sync::watch::channel(now).0); tx.send_if_modified(|held| std::mem::replace(held, now) != now); tx.subscribe() } /// The accounts with a connection watching their permissions — the ones a /// role change has to be re-read for. Drops accounts nobody watches any more. pub fn granted_accounts(&self) -> Vec { let mut grants = self .grants .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); grants.retain(|_, tx| tx.receiver_count() > 0); grants.keys().cloned().collect() } /// Tell every connection of `account` what it may do now. Nothing is sent /// when nothing changed, so republishing everyone after any role edit is /// cheap. pub fn publish_grants(&self, account: &str, now: PermissionSet) { let grants = self .grants .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); if let Some(tx) = grants.get(account) { tx.send_if_modified(|held| std::mem::replace(held, now) != now); } } /// Deliver a frame to every connection signed in as `account` /// (`accounts.id`), whether or not it has a private-chat device — a /// contact list is not sealed. pub fn deliver_to_account(&self, account: &str, frame: &Bytes) { for (id, c) in locked(&self.clients).iter() { if c.account == account { c.enqueue(*id, Lane::Text, frame.clone()); } } } /// Whether any connection is signed in as `account`. #[must_use] pub fn account_online(&self, account: &str) -> bool { locked(&self.clients).values().any(|c| c.account == account) } /// Add or remove a block for a live connection, so it takes effect on the /// next message rather than the next login. pub fn set_blocked(&self, avatar_id: u64, username: &str, blocked: bool) { if let Some(c) = locked(&self.clients).get_mut(&avatar_id) { let key = username.to_lowercase(); if blocked { c.blocked.insert(key); } else { c.blocked.remove(&key); } } } /// Whether either of two connected people has blocked the other: `a` is /// avatar `a_id` signed in as `a_name`, and `b` likewise. For acts two /// people do *together* (a greeting, protocol 49), where a block either /// way ends it — unlike a message, which the blocked one may still send /// into the void. #[must_use] pub fn blocked_between(&self, a_id: u64, a_name: &str, b_id: u64, b_name: &str) -> bool { let clients = locked(&self.clients); let blocks = |id: u64, name: &str| { clients .get(&id) .is_some_and(|c| c.blocked.contains(&name.to_lowercase())) }; blocks(a_id, b_name) || blocks(b_id, a_name) } pub fn unregister(&self, avatar_id: u64) { locked(&self.clients).remove(&avatar_id); } /// Deliver one encoded frame to every connected client (Global). /// /// Text only: global voice is deliberately not carried (see `net`'s /// `VoiceFrame` arm), so there is no lane to choose. /// /// `from` is the *speaker's* username, and every delivery entry point takes /// it for one reason: it is what a recipient's block list is checked against. /// Passing it rather than deriving it from the frame keeps the hub's "opaque /// encoded bytes" property — it never has to decode a message to route it. pub fn deliver_all(&self, from: &str, frame: &Bytes) { let from = from.to_lowercase(); for (id, c) in locked(&self.clients).iter() { if c.blocked.contains(&from) { continue; } c.enqueue(*id, Lane::Text, frame.clone()); } } /// Deliver a per-recipient frame to a specific avatar (proximity). /// /// The block is applied here too, and it must be: proximity is the tier where /// somebody you have blocked can still walk up to you. pub fn deliver_to(&self, avatar_id: u64, from: &str, lane: Lane, frame: Bytes) { if let Some(c) = locked(&self.clients).get(&avatar_id) { if c.blocked.contains(&from.to_lowercase()) { return; } c.enqueue(avatar_id, lane, frame); } } /// Connected avatar ids — the candidate set for a proximity send. pub fn connected_ids(&self) -> Vec { locked(&self.clients).keys().copied().collect() } } #[cfg(test)] mod tests { use super::*; const LAT: f64 = 53.2194; const LNG: f64 = 6.5665; /// `x` metres east of the origin, on the ground. fn at(x: f32) -> Place { let (_, per_lng) = cartopolis_core::degree_scale_m(LAT); Place::new(LAT, LNG + f64::from(x) / per_lng, 0.0) } fn origin() -> Place { Place::new(LAT, LNG, 0.0) } #[test] fn say_radius_excludes_beyond_and_keeps_distance() { let candidates = [(1, at(10.0)), (2, at(49.0)), (3, at(51.0))]; let got = within_radius(origin(), &candidates, SAY_RADIUS_M); let ids: Vec = got.iter().map(|(id, _)| *id).collect(); assert_eq!(ids, vec![1, 2], "3 is beyond say radius"); // Each recipient carries its own distance — what attenuation reads. assert!((got[0].1 - 10.0).abs() < 0.05); assert!((got[1].1 - 49.0).abs() < 0.05); } #[test] fn shout_reaches_what_say_cannot() { let candidates = [(1, at(200.0))]; assert!(within_radius(origin(), &candidates, SAY_RADIUS_M).is_empty()); assert_eq!( within_radius(origin(), &candidates, SHOUT_RADIUS_M).len(), 1 ); } /// A client that never reads costs a bounded amount of memory, and says so. /// /// The unbounded version of this test could not exist: there was no number to /// assert against, which is exactly why the problem was invisible. #[test] fn a_client_that_never_reads_bounds_the_queue_instead_of_the_heap() { let hub = ChatHub::new(); let (_text_rx, mut voice_rx) = hub.register(1, "a", []); // Ten times the backlog, from a "speaker" that is not this connection. for _ in 0..VOICE_BACKLOG * 10 { hub.deliver_to(1, "speaker", Lane::Voice, Bytes::from(vec![0u8; 1500])); } let mut queued = 0; while voice_rx.try_recv().is_ok() { queued += 1; } assert_eq!(queued, VOICE_BACKLOG, "the voice queue grew past its bound"); } /// The lanes are independent: a client drowning in voice still gets its chat. /// /// This is the reason for two channels rather than one bounded channel. With a /// shared queue, a burst of proximity voice is what decides whether a typed /// line survives, and the person who typed it is told nothing. #[test] fn a_voice_flood_does_not_drop_text() { let hub = ChatHub::new(); let (mut text_rx, _voice_rx) = hub.register(1, "a", []); for _ in 0..VOICE_BACKLOG * 4 { hub.deliver_to(1, "speaker", Lane::Voice, Bytes::from(vec![0u8; 1500])); } hub.deliver_to(1, "speaker", Lane::Text, Bytes::from_static(b"hello")); assert_eq!( text_rx.try_recv().ok(), Some(Bytes::from_static(b"hello")), "the text lane was consumed by voice" ); } /// The block has to hold on every tier a person can be heard on, which is the /// whole reason `from` threads through every delivery entry point. #[test] fn a_blocked_speaker_reaches_none_of_the_channels() { let hub = ChatHub::new(); let (mut rx, _v) = hub.register(1, "a", ["loud".to_string()]); hub.deliver_all("loud", &Bytes::from_static(b"global")); hub.deliver_to(1, "loud", Lane::Text, Bytes::from_static(b"local")); hub.deliver_to(1, "loud", Lane::Voice, Bytes::from_static(b"voice")); assert!(rx.try_recv().is_err(), "a blocked speaker got through"); // …and everyone else still arrives. hub.deliver_all("quiet", &Bytes::from_static(b"global")); assert_eq!(rx.try_recv().ok(), Some(Bytes::from_static(b"global"))); } /// A block is stored and compared lowercased, so it cannot be walked around /// by the shift key. #[test] fn blocking_ignores_case_on_both_sides() { let hub = ChatHub::new(); let (mut rx, _v) = hub.register(1, "a", ["LoUd".to_string()]); hub.deliver_all("lOuD", &Bytes::from_static(b"x")); assert!(rx.try_recv().is_err()); } /// Unblocking takes effect on the next message, not the next login: the hub /// entry is edited in place beside the database write. #[test] fn unblocking_lands_on_the_live_connection() { let hub = ChatHub::new(); let (mut rx, _v) = hub.register(1, "a", ["loud".to_string()]); hub.deliver_all("loud", &Bytes::from_static(b"before")); assert!(rx.try_recv().is_err()); hub.set_blocked(1, "Loud", false); hub.deliver_all("loud", &Bytes::from_static(b"after")); assert_eq!(rx.try_recv().ok(), Some(Bytes::from_static(b"after"))); hub.set_blocked(1, "loud", true); hub.deliver_all("loud", &Bytes::from_static(b"again")); assert!(rx.try_recv().is_err()); } /// A message wakes only the members it could not reach: not the writer, /// not somebody with a chat device connected — but somebody connected /// without one (a page that is not the chat) is woken. #[test] fn a_message_wakes_only_members_with_no_device_here() { let hub = ChatHub::new(); let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); hub.set_wake(tx); let _ann = hub.register(1, "ann", []); hub.set_device(1, uuid::Uuid::from_u128(1)); let _bob = hub.register(2, "bob", []); hub.set_device(2, uuid::Uuid::from_u128(2)); let _cy = hub.register(3, "cy", []); let members: Vec = ["ann", "bob", "cy", "dee"].map(String::from).to_vec(); hub.wake_for_message(&members, "ann", "ann"); let ring = rx.try_recv().unwrap(); assert_eq!(ring.kind, crate::push::Kind::Message); assert_eq!(ring.members, ["cy", "dee"]); // Everybody there: nothing is sent at all. hub.wake_for_message(&members[..2], "ann", "ann"); assert!(rx.try_recv().is_err()); } /// A call from elsewhere rings like one here: every member named, and /// nothing when the only one named is the caller. #[test] fn a_call_from_elsewhere_wakes_the_members_here() { let hub = ChatHub::new(); let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); hub.set_wake(tx); let members: Vec = ["ann", "bob"].map(String::from).to_vec(); hub.wake_for_call(&members, "", "cy@rug.example"); let ring = rx.try_recv().unwrap(); assert_eq!(ring.kind, crate::push::Kind::Call); assert_eq!(ring.members, ["ann", "bob"]); assert_eq!(ring.caller_name, "cy@rug.example"); hub.wake_for_call(&members[..1], "ann", "ann"); assert!(rx.try_recv().is_err()); } #[test] fn radius_is_a_sphere_not_an_axis() { // A listener directly above is as far as one to the side. let (per_lat, per_lng) = cartopolis_core::degree_scale_m(LAT); let candidates = [ (1, Place::new(LAT, LNG, 60.0)), ( 2, Place::new(LAT - 30.0 / per_lat, LNG + 30.0 / per_lng, 0.0), ), ]; let ids: Vec = within_radius(origin(), &candidates, SAY_RADIUS_M) .iter() .map(|(id, _)| *id) .collect(); assert_eq!( ids, vec![2], "60 m up is out of say range; 42 m diagonal is in" ); } }