1use std::collections::HashMap;
5use std::sync::{Arc, Mutex};
6
7use nostr_sdk::prelude::PublicKey;
8
9pub const HEARTBEAT_MS: u64 = 30_000;
11pub const FRESH_MS: u64 = 90_000;
13const AHEAD_MS: u64 = 60_000;
15const BEHIND_MS: u64 = 300_000;
18
19#[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 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#[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 pub screen: bool,
77 pub camera: bool,
78}
79
80impl Heard {
81 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#[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#[derive(Clone, Debug, PartialEq, Eq)]
109pub struct Present {
110 pub author: PublicKey,
111 pub at_ms: u64,
112 pub transport: Option<String>,
114 pub endpoint: Option<[u8; 32]>,
116 pub relay: Option<String>,
118 pub muted: bool,
119 pub deafened: bool,
120 pub screen: bool,
121 pub camera: bool,
122 pub server_muted: bool,
124 pub server_deafened: bool,
125}
126
127#[derive(Clone)]
128struct Entry {
129 at_ms: u64,
130 heard_at: u64,
132 since_ms: u64,
134 since_heard: u64,
136 heard: Heard,
137 server_muted: bool,
138 server_deafened: bool,
139 muted_at: u64,
141 deafened_at: u64,
142}
143
144impl Entry {
145 fn live(&self, now_ms: u64) -> bool {
147 self.heard.joined && now_ms.saturating_sub(self.heard_at) < FRESH_MS
148 }
149}
150
151#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
153pub struct Noted {
154 pub changed: bool,
156 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
167pub 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 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
194const STAY_SKEW_MS: u64 = 10_000;
197
198pub 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 .is_some_and(|e| e.live(now_ms) && at_ms.saturating_add(STAY_SKEW_MS) >= e.since_ms.min(e.since_heard))
211}
212
213pub 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
238pub 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
245pub 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
275pub 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
280pub 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 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 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 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 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 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 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 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 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}