vector-core 0.13.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Who is in each voice Channel's call (CORD-07 §4): the latest presence per author, live while
//! fresh. Presence is ephemeral and never stored, so this lives on the session alone.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use nostr_sdk::prelude::PublicKey;

/// A `joined` is re-sent this often while in the call.
pub const HEARTBEAT_MS: u64 = 30_000;
/// Three missed heartbeats and a `joined` counts as absent.
pub const FRESH_MS: u64 = 90_000;
/// A presence dated further ahead than this would outlive its author's leave; it's refused.
const AHEAD_MS: u64 = 60_000;
/// A presence dated further behind than this is a replay or a clock gone wrong; it's refused.
/// Within it, freshness runs from when it arrived, so a sender's skew can't age them out.
const BEHIND_MS: u64 = 300_000;

/// A moderator's directive in a call (CORD-07 §7).
#[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,
        })
    }

    /// The bit its signer holds over the target.
    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,
        }
    }
}

/// What one presence says.
#[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,
    /// They are sharing their screen, or their camera.
    pub screen: bool,
    pub camera: bool,
}

impl Heard {
    /// What our own presence says when it names `endpoint` (none is a `left`) and shows `showing`.
    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,
        }
    }
}

/// What a `joined` shows of its author beyond where to reach them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Showing {
    pub muted: bool,
    pub deafened: bool,
    pub screen: bool,
    pub camera: bool,
}

/// One member in a call.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Present {
    pub author: PublicKey,
    pub at_ms: u64,
    /// The transport they named; anything but iroh is a call this client can't join them in.
    pub transport: Option<String>,
    /// Their iroh endpoint, when they named one and no one else claims it too.
    pub endpoint: Option<[u8; 32]>,
    /// The relay that endpoint is reached through.
    pub relay: Option<String>,
    pub muted: bool,
    pub deafened: bool,
    pub screen: bool,
    pub camera: bool,
    /// A moderator's mute or deafen, for as long as they stay in the call.
    pub server_muted: bool,
    pub server_deafened: bool,
}

#[derive(Clone)]
struct Entry {
    at_ms: u64,
    /// When it arrived here: what freshness is judged from.
    heard_at: u64,
    /// When this stay in the call began: the order everyone is listed in.
    since_ms: u64,
    /// When this device first heard this stay's `joined`, on its own clock.
    since_heard: u64,
    heard: Heard,
    server_muted: bool,
    server_deafened: bool,
    /// When the directive that set each was sent: an older one arriving late changes nothing.
    muted_at: u64,
    deafened_at: u64,
}

impl Entry {
    /// In the call: a `joined` heard within the last three heartbeats.
    fn live(&self, now_ms: u64) -> bool {
        self.heard.joined && now_ms.saturating_sub(self.heard_at) < FRESH_MS
    }
}

/// What folding a presence did.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Noted {
    /// Who is in the call, or how, changed.
    pub changed: bool,
    /// They are reachable anew: in from outside the call, or back on a new endpoint. Who is
    /// already in it tells them so, and any standing moderation comes back with them.
    pub reached: bool,
}

struct Calls;

fn calls() -> Arc<Mutex<HashMap<String, HashMap<PublicKey, Entry>>>> {
    crate::db::current_session().scoped::<Calls, _>()
}

/// Fold one presence for `channel` (hex); the latest per author wins. Returns whether it changed
/// who is in the call.
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);
    // A moderator's mute lasts while they stay: leaving or arriving anew clears it.
    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 }
}

/// How far before its target's current stay began a directive may be dated: a moderator's
/// re-assertion follows the target's `joined`, from a clock a little behind theirs.
const STAY_SKEW_MS: u64 = 10_000;

/// Whether a directive sent at `at_ms` may act on `target`'s current stay in `channel`'s call:
/// one replayed from an earlier stay, or from outside the presence clock bounds, acts on nothing.
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))
        // Against the earlier of the stay's own date and when this device heard it begin, so a
        // target whose clock runs fast can't date its stay past a moderator's re-assertion.
        .is_some_and(|e| e.live(now_ms) && at_ms.saturating_add(STAY_SKEW_MS) >= e.since_ms.min(e.since_heard))
}

/// Apply a moderator's mute or deafen, sent at `at_ms`, to `target` if they're in the call. Per
/// pair the newest wins, a same-ms tie keeping them muted or deafened. Returns whether it changed.
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)
}

/// Whether a moderator has muted `member` in `channel`'s call: (muted, 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))
}

/// Who is in `channel`'s call now. An endpoint two authors both claim proves nothing about
/// either, so neither is given one (CORD-07 §4).
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()
}

/// The member a live presence binds `endpoint` to, if exactly one does.
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)
}

/// Every Channel with someone in its call, for a sidebar that lists them.
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");
        // A target dating its joined 50 s ahead of this clock still takes a re-assertion sent now.
        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() {
        // The store is the session\'s: a bed test swapping sessions must not run beside this.
        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() {
        // The store is the session\'s: a bed test swapping sessions must not run beside this.
        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));
        // Two moderators disagreeing: the newest stands, in whichever order they arrive.
        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() {
        // The store is the session\'s: a bed test swapping sessions must not run beside this.
        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() };
        // Their clock runs 80s behind ours: each heartbeat arrives already 80s old by its own date.
        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() {
        // The store is the session\'s: a bed test swapping sessions must not run beside this.
        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() {
        // The store is the session\'s: a bed test swapping sessions must not run beside this.
        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);
    }
}