Skip to main content

vector_core/community/v2/
voice.rs

1//! Who is in each voice Channel's call (CORD-07 §4): the latest presence per author, live while
2//! fresh. Presence is ephemeral and never stored, so this lives on the session alone.
3
4use std::collections::HashMap;
5use std::sync::{Arc, Mutex};
6
7use nostr_sdk::prelude::PublicKey;
8
9/// A `joined` is re-sent this often while in the call.
10pub const HEARTBEAT_MS: u64 = 30_000;
11/// Three missed heartbeats and a `joined` counts as absent.
12pub const FRESH_MS: u64 = 90_000;
13/// A presence dated further ahead than this would outlive its author's leave; it's refused.
14const AHEAD_MS: u64 = 60_000;
15/// A presence dated further behind than this is a replay or a clock gone wrong; it's refused.
16/// Within it, freshness runs from when it arrived, so a sender's skew can't age them out.
17const BEHIND_MS: u64 = 300_000;
18
19/// A moderator's directive in a call (CORD-07 §7).
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
21#[serde(rename_all = "lowercase")]
22pub enum Directive {
23    Mute,
24    Unmute,
25    Deafen,
26    Undeafen,
27    Move,
28    Disconnect,
29}
30
31impl Directive {
32    pub fn as_str(self) -> &'static str {
33        match self {
34            Directive::Mute => "mute",
35            Directive::Unmute => "unmute",
36            Directive::Deafen => "deafen",
37            Directive::Undeafen => "undeafen",
38            Directive::Move => "move",
39            Directive::Disconnect => "disconnect",
40        }
41    }
42
43    pub fn parse(s: &str) -> Option<Self> {
44        Some(match s {
45            "mute" => Directive::Mute,
46            "unmute" => Directive::Unmute,
47            "deafen" => Directive::Deafen,
48            "undeafen" => Directive::Undeafen,
49            "move" => Directive::Move,
50            "disconnect" => Directive::Disconnect,
51            _ => return None,
52        })
53    }
54
55    /// The bit its signer holds over the target.
56    pub fn permission(self) -> u64 {
57        use crate::community::roles::Permissions;
58        match self {
59            Directive::Mute | Directive::Unmute => Permissions::MUTE_MEMBERS,
60            Directive::Deafen | Directive::Undeafen => Permissions::DEAFEN_MEMBERS,
61            Directive::Move | Directive::Disconnect => Permissions::MOVE_MEMBERS,
62        }
63    }
64}
65
66/// What one presence says.
67#[derive(Clone, Debug, Default, PartialEq, Eq)]
68pub struct Heard {
69    pub joined: bool,
70    pub transport: Option<String>,
71    pub endpoint: Option<[u8; 32]>,
72    pub relay: Option<String>,
73    pub muted: bool,
74    pub deafened: bool,
75    /// They are sharing their screen, or their camera.
76    pub screen: bool,
77    pub camera: bool,
78}
79
80impl Heard {
81    /// What our own presence says when it names `endpoint` (none is a `left`) and shows `showing`.
82    pub fn announcing(endpoint: Option<([u8; 32], Option<String>)>, showing: Showing) -> Heard {
83        let (endpoint, relay) = endpoint.map_or((None, None), |(e, r)| (Some(e), r));
84        let joined = endpoint.is_some();
85        Heard {
86            joined,
87            transport: joined.then(|| super::chat::TRANSPORT_IROH.to_string()),
88            endpoint,
89            relay,
90            muted: showing.muted && joined,
91            deafened: showing.deafened && joined,
92            screen: showing.screen && joined,
93            camera: showing.camera && joined,
94        }
95    }
96}
97
98/// What a `joined` shows of its author beyond where to reach them.
99#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
100pub struct Showing {
101    pub muted: bool,
102    pub deafened: bool,
103    pub screen: bool,
104    pub camera: bool,
105}
106
107/// One member in a call.
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub struct Present {
110    pub author: PublicKey,
111    pub at_ms: u64,
112    /// The transport they named; anything but iroh is a call this client can't join them in.
113    pub transport: Option<String>,
114    /// Their iroh endpoint, when they named one and no one else claims it too.
115    pub endpoint: Option<[u8; 32]>,
116    /// The relay that endpoint is reached through.
117    pub relay: Option<String>,
118    pub muted: bool,
119    pub deafened: bool,
120    pub screen: bool,
121    pub camera: bool,
122    /// A moderator's mute or deafen, for as long as they stay in the call.
123    pub server_muted: bool,
124    pub server_deafened: bool,
125}
126
127#[derive(Clone)]
128struct Entry {
129    at_ms: u64,
130    /// When it arrived here: what freshness is judged from.
131    heard_at: u64,
132    /// When this stay in the call began: the order everyone is listed in.
133    since_ms: u64,
134    /// When this device first heard this stay's `joined`, on its own clock.
135    since_heard: u64,
136    heard: Heard,
137    server_muted: bool,
138    server_deafened: bool,
139    /// When the directive that set each was sent: an older one arriving late changes nothing.
140    muted_at: u64,
141    deafened_at: u64,
142}
143
144impl Entry {
145    /// In the call: a `joined` heard within the last three heartbeats.
146    fn live(&self, now_ms: u64) -> bool {
147        self.heard.joined && now_ms.saturating_sub(self.heard_at) < FRESH_MS
148    }
149}
150
151/// What folding a presence did.
152#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
153pub struct Noted {
154    /// Who is in the call, or how, changed.
155    pub changed: bool,
156    /// They are reachable anew: in from outside the call, or back on a new endpoint. Who is
157    /// already in it tells them so, and any standing moderation comes back with them.
158    pub reached: bool,
159}
160
161struct Calls;
162
163fn calls() -> Arc<Mutex<HashMap<String, HashMap<PublicKey, Entry>>>> {
164    crate::db::current_session().scoped::<Calls, _>()
165}
166
167/// Fold one presence for `channel` (hex); the latest per author wins. Returns whether it changed
168/// who is in the call.
169pub fn note(channel: &str, author: PublicKey, at_ms: u64, heard: Heard, now_ms: u64) -> Noted {
170    if at_ms > now_ms.saturating_add(AHEAD_MS) || at_ms.saturating_add(BEHIND_MS) < now_ms {
171        return Noted::default();
172    }
173    let store = calls();
174    let mut all = store.lock().unwrap_or_else(|e| e.into_inner());
175    let room = all.entry(channel.to_ascii_lowercase()).or_default();
176    if room.get(&author).is_some_and(|e| e.at_ms >= at_ms) {
177        return Noted::default();
178    }
179    let fresh = |e: &Entry| e.live(now_ms);
180    let was = room.get(&author).filter(|e| fresh(e)).cloned();
181    let reached = heard.joined && was.as_ref().is_none_or(|e| e.heard.endpoint != heard.endpoint);
182    let changed = was.as_ref().map(|e| &e.heard) != Some(&heard);
183    // A moderator's mute lasts while they stay: leaving or arriving anew clears it.
184    let (server_muted, server_deafened, muted_at, deafened_at) = match &was {
185        Some(e) if heard.joined => (e.server_muted, e.server_deafened, e.muted_at, e.deafened_at),
186        _ => (false, false, 0, 0),
187    };
188    let since_ms = was.as_ref().filter(|_| heard.joined).map_or(at_ms, |e| e.since_ms);
189    let since_heard = was.as_ref().filter(|_| heard.joined).map_or(now_ms, |e| e.since_heard);
190    room.insert(author, Entry { at_ms, heard_at: now_ms, since_ms, since_heard, heard, server_muted, server_deafened, muted_at, deafened_at });
191    Noted { changed, reached }
192}
193
194/// How far before its target's current stay began a directive may be dated: a moderator's
195/// re-assertion follows the target's `joined`, from a clock a little behind theirs.
196const STAY_SKEW_MS: u64 = 10_000;
197
198/// Whether a directive sent at `at_ms` may act on `target`'s current stay in `channel`'s call:
199/// one replayed from an earlier stay, or from outside the presence clock bounds, acts on nothing.
200pub fn directive_in_window(channel: &str, target: &PublicKey, at_ms: u64, now_ms: u64) -> bool {
201    if at_ms > now_ms.saturating_add(AHEAD_MS) || at_ms.saturating_add(BEHIND_MS) < now_ms {
202        return false;
203    }
204    let store = calls();
205    let all = store.lock().unwrap_or_else(|e| e.into_inner());
206    all.get(&channel.to_ascii_lowercase())
207        .and_then(|r| r.get(target))
208        // Against the earlier of the stay's own date and when this device heard it begin, so a
209        // target whose clock runs fast can't date its stay past a moderator's re-assertion.
210        .is_some_and(|e| e.live(now_ms) && at_ms.saturating_add(STAY_SKEW_MS) >= e.since_ms.min(e.since_heard))
211}
212
213/// Apply a moderator's mute or deafen, sent at `at_ms`, to `target` if they're in the call. Per
214/// pair the newest wins, a same-ms tie keeping them muted or deafened. Returns whether it changed.
215pub fn apply_directive(channel: &str, target: &PublicKey, directive: Directive, at_ms: u64, now_ms: u64) -> bool {
216    let store = calls();
217    let mut all = store.lock().unwrap_or_else(|e| e.into_inner());
218    let Some(e) = all.get_mut(&channel.to_ascii_lowercase()).and_then(|r| r.get_mut(target)) else { return false };
219    if !e.live(now_ms) {
220        return false;
221    }
222    let before = (e.server_muted, e.server_deafened);
223    let newer = |set_at: u64, on: bool| at_ms > set_at || (at_ms == set_at && on);
224    match directive {
225        Directive::Mute | Directive::Unmute if newer(e.muted_at, directive == Directive::Mute) => {
226            e.server_muted = directive == Directive::Mute;
227            e.muted_at = at_ms;
228        }
229        Directive::Deafen | Directive::Undeafen if newer(e.deafened_at, directive == Directive::Deafen) => {
230            e.server_deafened = directive == Directive::Deafen;
231            e.deafened_at = at_ms;
232        }
233        _ => {}
234    }
235    before != (e.server_muted, e.server_deafened)
236}
237
238/// Whether a moderator has muted `member` in `channel`'s call: (muted, deafened).
239pub fn server_state(channel: &str, member: &PublicKey) -> (bool, bool) {
240    let store = calls();
241    let all = store.lock().unwrap_or_else(|e| e.into_inner());
242    all.get(&channel.to_ascii_lowercase()).and_then(|r| r.get(member)).map_or((false, false), |e| (e.server_muted, e.server_deafened))
243}
244
245/// Who is in `channel`'s call now. An endpoint two authors both claim proves nothing about
246/// either, so neither is given one (CORD-07 §4).
247pub fn present(channel: &str, now_ms: u64) -> Vec<Present> {
248    let store = calls();
249    let all = store.lock().unwrap_or_else(|e| e.into_inner());
250    let Some(room) = all.get(&channel.to_ascii_lowercase()) else { return Vec::new() };
251    let mut live: Vec<(&PublicKey, &Entry)> = room.iter().filter(|(_, e)| e.live(now_ms)).collect();
252    live.sort_by_key(|(a, e)| (e.since_ms, a.to_bytes()));
253    let claims = |ep: &[u8; 32]| live.iter().filter(|(_, e)| e.heard.endpoint.as_ref() == Some(ep)).count();
254    live.iter()
255        .map(|(a, e)| {
256            let h = &e.heard;
257            let endpoint = h.endpoint.filter(|ep| claims(ep) == 1);
258            Present {
259                author: **a,
260                at_ms: e.at_ms,
261                transport: h.transport.clone(),
262                endpoint,
263                relay: endpoint.and(h.relay.clone()),
264                muted: h.muted,
265                deafened: h.deafened,
266                screen: h.screen,
267                camera: h.camera,
268                server_muted: e.server_muted,
269                server_deafened: e.server_deafened,
270            }
271        })
272        .collect()
273}
274
275/// The member a live presence binds `endpoint` to, if exactly one does.
276pub fn author_of(channel: &str, endpoint: &[u8; 32], now_ms: u64) -> Option<PublicKey> {
277    present(channel, now_ms).into_iter().find(|p| p.endpoint.as_ref() == Some(endpoint)).map(|p| p.author)
278}
279
280/// Every Channel with someone in its call, for a sidebar that lists them.
281pub fn occupied(now_ms: u64) -> Vec<String> {
282    let store = calls();
283    let rooms: Vec<String> = store.lock().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect();
284    rooms.into_iter().filter(|r| !present(r, now_ms).is_empty()).collect()
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290    use nostr_sdk::prelude::Keys;
291
292    #[test]
293    fn a_directive_acts_only_on_the_stay_it_was_sent_into() {
294        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
295        let (ch, a) = ("ab".repeat(32), Keys::generate().public_key());
296        let joined = Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([2u8; 32]), ..Default::default() };
297        note(&ch, a, 1_000_000, joined, 1_000_000);
298        assert!(directive_in_window(&ch, &a, 1_000_500, 1_001_000));
299        assert!(directive_in_window(&ch, &a, 1_000_000 - STAY_SKEW_MS, 1_001_000), "a moderator's clock a little behind");
300        assert!(!directive_in_window(&ch, &a, 1_000_000 - STAY_SKEW_MS - 1, 1_001_000), "a replay from an earlier stay acts on nothing");
301        assert!(!directive_in_window(&ch, &a, 1_001_000 + AHEAD_MS + 1, 1_001_000), "nor one from the future");
302        assert!(!directive_in_window(&ch, &Keys::generate().public_key(), 1_000_500, 1_001_000), "nor on someone not in the call");
303        // A target dating its joined 50 s ahead of this clock still takes a re-assertion sent now.
304        let (fast, ahead) = (Keys::generate().public_key(), 50_000);
305        note(&ch, fast, 2_000_000 + ahead, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([3u8; 32]), ..Default::default() }, 2_000_000);
306        assert!(directive_in_window(&ch, &fast, 2_000_100, 2_000_200));
307    }
308
309    #[test]
310    fn the_latest_presence_per_author_stands_while_fresh() {
311        // The store is the session\'s: a bed test swapping sessions must not run beside this.
312        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
313        let (ch, a) = ("aa".repeat(32), Keys::generate().public_key());
314        let ep = [1u8; 32];
315        assert!(note(&ch, a, 10_000, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some(ep), ..Default::default() }, 10_000).reached);
316        assert_eq!(present(&ch, 10_000).len(), 1);
317        assert!(!note(&ch, a, 9_000, Heard { joined: false, transport: None, endpoint: None, ..Default::default() }, 10_000).changed, "an older left changes nothing");
318        assert_eq!(present(&ch, 10_000 + FRESH_MS - 1).len(), 1, "fresh until three heartbeats go missing");
319        assert!(present(&ch, 10_000 + FRESH_MS).is_empty(), "then absent");
320        let muted = Heard { joined: true, transport: Some("iroh".into()), endpoint: Some(ep), muted: true, ..Default::default() };
321        let n = note(&ch, a, 15_000, muted.clone(), 15_000);
322        assert!(n.changed && !n.reached, "a mute alone is news, not an arrival");
323        assert!(present(&ch, 15_000)[0].muted);
324        assert!(!note(&ch, a, 16_000, muted, 16_000).changed, "a heartbeat that says the same is not");
325        assert!(note(&ch, a, 20_000, Heard { joined: false, transport: None, endpoint: None, ..Default::default() }, 20_000).changed);
326        assert!(present(&ch, 20_000).is_empty(), "a newer left ends it");
327        assert!(!note(&ch, a, 20_000 + AHEAD_MS + 1_000, Heard { joined: true, transport: None, endpoint: None, ..Default::default() }, 20_000).changed, "nor can a joined dated far ahead stick");
328    }
329
330    #[test]
331    fn a_moderators_mute_lasts_while_they_stay_and_ends_when_they_leave() {
332        // The store is the session\'s: a bed test swapping sessions must not run beside this.
333        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
334        let (ch, a) = ("cc".repeat(32), Keys::generate().public_key());
335        let joined = |_at: u64| Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([3u8; 32]), ..Default::default() };
336        assert!(!apply_directive(&ch, &a, Directive::Mute, 1_000, 1_000), "nobody to mute yet");
337        note(&ch, a, 1_000, joined(1_000), 1_000);
338        assert!(apply_directive(&ch, &a, Directive::Mute, 1_000, 1_000));
339        assert!(!apply_directive(&ch, &a, Directive::Mute, 1_000, 1_000), "once");
340        note(&ch, a, 31_000, joined(31_000), 31_000);
341        assert_eq!(server_state(&ch, &a), (true, false), "a heartbeat keeps it");
342        assert!(present(&ch, 31_000)[0].server_muted);
343        let back = Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([4u8; 32]), ..Default::default() };
344        assert!(note(&ch, a, 32_000, back, 32_000).reached, "back on a new endpoint: reachable anew, to be told who is here");
345        assert_eq!(server_state(&ch, &a), (true, false), "and still muted: they never left");
346        note(&ch, a, 40_000, Heard::default(), 40_000);
347        note(&ch, a, 41_000, joined(41_000), 41_000);
348        assert_eq!(server_state(&ch, &a), (false, false), "leaving ends it: a moderator re-asserts on return");
349        assert!(apply_directive(&ch, &a, Directive::Deafen, 41_000, 41_000) && apply_directive(&ch, &a, Directive::Undeafen, 41_001, 41_001));
350        // Two moderators disagreeing: the newest stands, in whichever order they arrive.
351        assert!(apply_directive(&ch, &a, Directive::Unmute, 43_000, 44_000) == false, "already unmuted");
352        assert!(apply_directive(&ch, &a, Directive::Mute, 42_000, 44_000) == false, "an older mute arriving late changes nothing");
353        assert!(apply_directive(&ch, &a, Directive::Mute, 45_000, 45_000));
354        assert!(!apply_directive(&ch, &a, Directive::Unmute, 45_000, 45_000), "a same-ms tie keeps them muted");
355        assert_eq!(server_state(&ch, &a), (true, false));
356    }
357
358    #[test]
359    fn a_member_whose_clock_lags_stays_while_their_heartbeats_arrive() {
360        // The store is the session\'s: a bed test swapping sessions must not run beside this.
361        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
362        let (ch, a) = ("ee".repeat(32), Keys::generate().public_key());
363        let joined = Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([5u8; 32]), ..Default::default() };
364        // Their clock runs 80s behind ours: each heartbeat arrives already 80s old by its own date.
365        let lag = 80_000;
366        for beat in 0..6u64 {
367            let now = 1_000_000 + beat * HEARTBEAT_MS;
368            note(&ch, a, now - lag, joined.clone(), now);
369            assert_eq!(present(&ch, now + HEARTBEAT_MS - 1).len(), 1, "still in the call just before heartbeat {}", beat + 1);
370        }
371        let last = 1_000_000 + 5 * HEARTBEAT_MS;
372        assert!(present(&ch, last + FRESH_MS).is_empty(), "three missed heartbeats still age them out");
373
374        let b = Keys::generate().public_key();
375        assert!(!note(&ch, b, 2_000_000 - BEHIND_MS - 1, joined, 2_000_000).changed, "a presence from minutes ago is a replay, not a member");
376        assert!(present(&ch, 2_000_000).is_empty());
377    }
378
379    #[test]
380    fn heartbeats_keep_everyone_where_they_arrived() {
381        // The store is the session\'s: a bed test swapping sessions must not run beside this.
382        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
383        let ch = "dd".repeat(32);
384        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
385        let joined = |ep: u8| Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([ep; 32]), ..Default::default() };
386        note(&ch, a, 1_000, joined(1), 1_000);
387        note(&ch, b, 2_000, joined(2), 2_000);
388        for beat in 1..=4u64 {
389            let at = 2_000 + beat * 30_000;
390            note(&ch, b, at, joined(2), at);
391            note(&ch, a, at + 500, joined(1), at + 500);
392            let order: Vec<_> = present(&ch, at + 500).iter().map(|p| p.author).collect();
393            assert_eq!(order, vec![a, b], "a's newer heartbeat must not move them behind b");
394        }
395        note(&ch, a, 130_000, Heard::default(), 130_000);
396        note(&ch, a, 131_000, joined(1), 131_000);
397        note(&ch, b, 132_000, joined(2), 132_000);
398        let order: Vec<_> = present(&ch, 132_000).iter().map(|p| p.author).collect();
399        assert_eq!(order, vec![b, a], "leaving and coming back joins the end");
400    }
401
402    #[test]
403    fn an_endpoint_two_authors_claim_is_given_to_neither() {
404        // The store is the session\'s: a bed test swapping sessions must not run beside this.
405        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
406        let ch = "bb".repeat(32);
407        let (a, b, c) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
408        note(&ch, a, 1_000, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([7u8; 32]), ..Default::default() }, 1_000);
409        note(&ch, b, 1_001, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([7u8; 32]), ..Default::default() }, 1_001);
410        note(&ch, c, 1_002, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([8u8; 32]), ..Default::default() }, 1_002);
411        let now = present(&ch, 1_002);
412        assert_eq!(now.len(), 3, "all three are in the call");
413        assert!(now.iter().filter(|p| p.author == a || p.author == b).all(|p| p.endpoint.is_none()), "the contested endpoint dials no one");
414        assert_eq!(author_of(&ch, &[8u8; 32], 1_002), Some(c));
415        assert_eq!(author_of(&ch, &[7u8; 32], 1_002), None);
416    }
417}