use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use nostr_sdk::prelude::PublicKey;
pub const HEARTBEAT_MS: u64 = 30_000;
pub const FRESH_MS: u64 = 90_000;
const AHEAD_MS: u64 = 60_000;
const BEHIND_MS: u64 = 300_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Directive {
Mute,
Unmute,
Deafen,
Undeafen,
Move,
Disconnect,
}
impl Directive {
pub fn as_str(self) -> &'static str {
match self {
Directive::Mute => "mute",
Directive::Unmute => "unmute",
Directive::Deafen => "deafen",
Directive::Undeafen => "undeafen",
Directive::Move => "move",
Directive::Disconnect => "disconnect",
}
}
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"mute" => Directive::Mute,
"unmute" => Directive::Unmute,
"deafen" => Directive::Deafen,
"undeafen" => Directive::Undeafen,
"move" => Directive::Move,
"disconnect" => Directive::Disconnect,
_ => return None,
})
}
pub fn permission(self) -> u64 {
use crate::community::roles::Permissions;
match self {
Directive::Mute | Directive::Unmute => Permissions::MUTE_MEMBERS,
Directive::Deafen | Directive::Undeafen => Permissions::DEAFEN_MEMBERS,
Directive::Move | Directive::Disconnect => Permissions::MOVE_MEMBERS,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Heard {
pub joined: bool,
pub transport: Option<String>,
pub endpoint: Option<[u8; 32]>,
pub relay: Option<String>,
pub muted: bool,
pub deafened: bool,
pub screen: bool,
pub camera: bool,
}
impl Heard {
pub fn announcing(endpoint: Option<([u8; 32], Option<String>)>, showing: Showing) -> Heard {
let (endpoint, relay) = endpoint.map_or((None, None), |(e, r)| (Some(e), r));
let joined = endpoint.is_some();
Heard {
joined,
transport: joined.then(|| super::chat::TRANSPORT_IROH.to_string()),
endpoint,
relay,
muted: showing.muted && joined,
deafened: showing.deafened && joined,
screen: showing.screen && joined,
camera: showing.camera && joined,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Showing {
pub muted: bool,
pub deafened: bool,
pub screen: bool,
pub camera: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Present {
pub author: PublicKey,
pub at_ms: u64,
pub transport: Option<String>,
pub endpoint: Option<[u8; 32]>,
pub relay: Option<String>,
pub muted: bool,
pub deafened: bool,
pub screen: bool,
pub camera: bool,
pub server_muted: bool,
pub server_deafened: bool,
}
#[derive(Clone)]
struct Entry {
at_ms: u64,
heard_at: u64,
since_ms: u64,
since_heard: u64,
heard: Heard,
server_muted: bool,
server_deafened: bool,
muted_at: u64,
deafened_at: u64,
}
impl Entry {
fn live(&self, now_ms: u64) -> bool {
self.heard.joined && now_ms.saturating_sub(self.heard_at) < FRESH_MS
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Noted {
pub changed: bool,
pub reached: bool,
}
struct Calls;
fn calls() -> Arc<Mutex<HashMap<String, HashMap<PublicKey, Entry>>>> {
crate::db::current_session().scoped::<Calls, _>()
}
pub fn note(channel: &str, author: PublicKey, at_ms: u64, heard: Heard, now_ms: u64) -> Noted {
if at_ms > now_ms.saturating_add(AHEAD_MS) || at_ms.saturating_add(BEHIND_MS) < now_ms {
return Noted::default();
}
let store = calls();
let mut all = store.lock().unwrap_or_else(|e| e.into_inner());
let room = all.entry(channel.to_ascii_lowercase()).or_default();
if room.get(&author).is_some_and(|e| e.at_ms >= at_ms) {
return Noted::default();
}
let fresh = |e: &Entry| e.live(now_ms);
let was = room.get(&author).filter(|e| fresh(e)).cloned();
let reached = heard.joined && was.as_ref().is_none_or(|e| e.heard.endpoint != heard.endpoint);
let changed = was.as_ref().map(|e| &e.heard) != Some(&heard);
let (server_muted, server_deafened, muted_at, deafened_at) = match &was {
Some(e) if heard.joined => (e.server_muted, e.server_deafened, e.muted_at, e.deafened_at),
_ => (false, false, 0, 0),
};
let since_ms = was.as_ref().filter(|_| heard.joined).map_or(at_ms, |e| e.since_ms);
let since_heard = was.as_ref().filter(|_| heard.joined).map_or(now_ms, |e| e.since_heard);
room.insert(author, Entry { at_ms, heard_at: now_ms, since_ms, since_heard, heard, server_muted, server_deafened, muted_at, deafened_at });
Noted { changed, reached }
}
const STAY_SKEW_MS: u64 = 10_000;
pub fn directive_in_window(channel: &str, target: &PublicKey, at_ms: u64, now_ms: u64) -> bool {
if at_ms > now_ms.saturating_add(AHEAD_MS) || at_ms.saturating_add(BEHIND_MS) < now_ms {
return false;
}
let store = calls();
let all = store.lock().unwrap_or_else(|e| e.into_inner());
all.get(&channel.to_ascii_lowercase())
.and_then(|r| r.get(target))
.is_some_and(|e| e.live(now_ms) && at_ms.saturating_add(STAY_SKEW_MS) >= e.since_ms.min(e.since_heard))
}
pub fn apply_directive(channel: &str, target: &PublicKey, directive: Directive, at_ms: u64, now_ms: u64) -> bool {
let store = calls();
let mut all = store.lock().unwrap_or_else(|e| e.into_inner());
let Some(e) = all.get_mut(&channel.to_ascii_lowercase()).and_then(|r| r.get_mut(target)) else { return false };
if !e.live(now_ms) {
return false;
}
let before = (e.server_muted, e.server_deafened);
let newer = |set_at: u64, on: bool| at_ms > set_at || (at_ms == set_at && on);
match directive {
Directive::Mute | Directive::Unmute if newer(e.muted_at, directive == Directive::Mute) => {
e.server_muted = directive == Directive::Mute;
e.muted_at = at_ms;
}
Directive::Deafen | Directive::Undeafen if newer(e.deafened_at, directive == Directive::Deafen) => {
e.server_deafened = directive == Directive::Deafen;
e.deafened_at = at_ms;
}
_ => {}
}
before != (e.server_muted, e.server_deafened)
}
pub fn server_state(channel: &str, member: &PublicKey) -> (bool, bool) {
let store = calls();
let all = store.lock().unwrap_or_else(|e| e.into_inner());
all.get(&channel.to_ascii_lowercase()).and_then(|r| r.get(member)).map_or((false, false), |e| (e.server_muted, e.server_deafened))
}
pub fn present(channel: &str, now_ms: u64) -> Vec<Present> {
let store = calls();
let all = store.lock().unwrap_or_else(|e| e.into_inner());
let Some(room) = all.get(&channel.to_ascii_lowercase()) else { return Vec::new() };
let mut live: Vec<(&PublicKey, &Entry)> = room.iter().filter(|(_, e)| e.live(now_ms)).collect();
live.sort_by_key(|(a, e)| (e.since_ms, a.to_bytes()));
let claims = |ep: &[u8; 32]| live.iter().filter(|(_, e)| e.heard.endpoint.as_ref() == Some(ep)).count();
live.iter()
.map(|(a, e)| {
let h = &e.heard;
let endpoint = h.endpoint.filter(|ep| claims(ep) == 1);
Present {
author: **a,
at_ms: e.at_ms,
transport: h.transport.clone(),
endpoint,
relay: endpoint.and(h.relay.clone()),
muted: h.muted,
deafened: h.deafened,
screen: h.screen,
camera: h.camera,
server_muted: e.server_muted,
server_deafened: e.server_deafened,
}
})
.collect()
}
pub fn author_of(channel: &str, endpoint: &[u8; 32], now_ms: u64) -> Option<PublicKey> {
present(channel, now_ms).into_iter().find(|p| p.endpoint.as_ref() == Some(endpoint)).map(|p| p.author)
}
pub fn occupied(now_ms: u64) -> Vec<String> {
let store = calls();
let rooms: Vec<String> = store.lock().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect();
rooms.into_iter().filter(|r| !present(r, now_ms).is_empty()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use nostr_sdk::prelude::Keys;
#[test]
fn a_directive_acts_only_on_the_stay_it_was_sent_into() {
let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let (ch, a) = ("ab".repeat(32), Keys::generate().public_key());
let joined = Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([2u8; 32]), ..Default::default() };
note(&ch, a, 1_000_000, joined, 1_000_000);
assert!(directive_in_window(&ch, &a, 1_000_500, 1_001_000));
assert!(directive_in_window(&ch, &a, 1_000_000 - STAY_SKEW_MS, 1_001_000), "a moderator's clock a little behind");
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");
assert!(!directive_in_window(&ch, &a, 1_001_000 + AHEAD_MS + 1, 1_001_000), "nor one from the future");
assert!(!directive_in_window(&ch, &Keys::generate().public_key(), 1_000_500, 1_001_000), "nor on someone not in the call");
let (fast, ahead) = (Keys::generate().public_key(), 50_000);
note(&ch, fast, 2_000_000 + ahead, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([3u8; 32]), ..Default::default() }, 2_000_000);
assert!(directive_in_window(&ch, &fast, 2_000_100, 2_000_200));
}
#[test]
fn the_latest_presence_per_author_stands_while_fresh() {
let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let (ch, a) = ("aa".repeat(32), Keys::generate().public_key());
let ep = [1u8; 32];
assert!(note(&ch, a, 10_000, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some(ep), ..Default::default() }, 10_000).reached);
assert_eq!(present(&ch, 10_000).len(), 1);
assert!(!note(&ch, a, 9_000, Heard { joined: false, transport: None, endpoint: None, ..Default::default() }, 10_000).changed, "an older left changes nothing");
assert_eq!(present(&ch, 10_000 + FRESH_MS - 1).len(), 1, "fresh until three heartbeats go missing");
assert!(present(&ch, 10_000 + FRESH_MS).is_empty(), "then absent");
let muted = Heard { joined: true, transport: Some("iroh".into()), endpoint: Some(ep), muted: true, ..Default::default() };
let n = note(&ch, a, 15_000, muted.clone(), 15_000);
assert!(n.changed && !n.reached, "a mute alone is news, not an arrival");
assert!(present(&ch, 15_000)[0].muted);
assert!(!note(&ch, a, 16_000, muted, 16_000).changed, "a heartbeat that says the same is not");
assert!(note(&ch, a, 20_000, Heard { joined: false, transport: None, endpoint: None, ..Default::default() }, 20_000).changed);
assert!(present(&ch, 20_000).is_empty(), "a newer left ends it");
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");
}
#[test]
fn a_moderators_mute_lasts_while_they_stay_and_ends_when_they_leave() {
let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let (ch, a) = ("cc".repeat(32), Keys::generate().public_key());
let joined = |_at: u64| Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([3u8; 32]), ..Default::default() };
assert!(!apply_directive(&ch, &a, Directive::Mute, 1_000, 1_000), "nobody to mute yet");
note(&ch, a, 1_000, joined(1_000), 1_000);
assert!(apply_directive(&ch, &a, Directive::Mute, 1_000, 1_000));
assert!(!apply_directive(&ch, &a, Directive::Mute, 1_000, 1_000), "once");
note(&ch, a, 31_000, joined(31_000), 31_000);
assert_eq!(server_state(&ch, &a), (true, false), "a heartbeat keeps it");
assert!(present(&ch, 31_000)[0].server_muted);
let back = Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([4u8; 32]), ..Default::default() };
assert!(note(&ch, a, 32_000, back, 32_000).reached, "back on a new endpoint: reachable anew, to be told who is here");
assert_eq!(server_state(&ch, &a), (true, false), "and still muted: they never left");
note(&ch, a, 40_000, Heard::default(), 40_000);
note(&ch, a, 41_000, joined(41_000), 41_000);
assert_eq!(server_state(&ch, &a), (false, false), "leaving ends it: a moderator re-asserts on return");
assert!(apply_directive(&ch, &a, Directive::Deafen, 41_000, 41_000) && apply_directive(&ch, &a, Directive::Undeafen, 41_001, 41_001));
assert!(apply_directive(&ch, &a, Directive::Unmute, 43_000, 44_000) == false, "already unmuted");
assert!(apply_directive(&ch, &a, Directive::Mute, 42_000, 44_000) == false, "an older mute arriving late changes nothing");
assert!(apply_directive(&ch, &a, Directive::Mute, 45_000, 45_000));
assert!(!apply_directive(&ch, &a, Directive::Unmute, 45_000, 45_000), "a same-ms tie keeps them muted");
assert_eq!(server_state(&ch, &a), (true, false));
}
#[test]
fn a_member_whose_clock_lags_stays_while_their_heartbeats_arrive() {
let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let (ch, a) = ("ee".repeat(32), Keys::generate().public_key());
let joined = Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([5u8; 32]), ..Default::default() };
let lag = 80_000;
for beat in 0..6u64 {
let now = 1_000_000 + beat * HEARTBEAT_MS;
note(&ch, a, now - lag, joined.clone(), now);
assert_eq!(present(&ch, now + HEARTBEAT_MS - 1).len(), 1, "still in the call just before heartbeat {}", beat + 1);
}
let last = 1_000_000 + 5 * HEARTBEAT_MS;
assert!(present(&ch, last + FRESH_MS).is_empty(), "three missed heartbeats still age them out");
let b = Keys::generate().public_key();
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");
assert!(present(&ch, 2_000_000).is_empty());
}
#[test]
fn heartbeats_keep_everyone_where_they_arrived() {
let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let ch = "dd".repeat(32);
let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
let joined = |ep: u8| Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([ep; 32]), ..Default::default() };
note(&ch, a, 1_000, joined(1), 1_000);
note(&ch, b, 2_000, joined(2), 2_000);
for beat in 1..=4u64 {
let at = 2_000 + beat * 30_000;
note(&ch, b, at, joined(2), at);
note(&ch, a, at + 500, joined(1), at + 500);
let order: Vec<_> = present(&ch, at + 500).iter().map(|p| p.author).collect();
assert_eq!(order, vec![a, b], "a's newer heartbeat must not move them behind b");
}
note(&ch, a, 130_000, Heard::default(), 130_000);
note(&ch, a, 131_000, joined(1), 131_000);
note(&ch, b, 132_000, joined(2), 132_000);
let order: Vec<_> = present(&ch, 132_000).iter().map(|p| p.author).collect();
assert_eq!(order, vec![b, a], "leaving and coming back joins the end");
}
#[test]
fn an_endpoint_two_authors_claim_is_given_to_neither() {
let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let ch = "bb".repeat(32);
let (a, b, c) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
note(&ch, a, 1_000, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([7u8; 32]), ..Default::default() }, 1_000);
note(&ch, b, 1_001, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([7u8; 32]), ..Default::default() }, 1_001);
note(&ch, c, 1_002, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some([8u8; 32]), ..Default::default() }, 1_002);
let now = present(&ch, 1_002);
assert_eq!(now.len(), 3, "all three are in the call");
assert!(now.iter().filter(|p| p.author == a || p.author == b).all(|p| p.endpoint.is_none()), "the contested endpoint dials no one");
assert_eq!(author_of(&ch, &[8u8; 32], 1_002), Some(c));
assert_eq!(author_of(&ch, &[7u8; 32], 1_002), None);
}
}