Skip to main content

menger_notes/
presence.rs

1//! **Who is on a note** (V2-29, the owner: *"we should see that they
2//! have a connection open on that document too"*). Each open connection on
3//! a note is a presence entry — its principal, its name, person or
4//! agent, a colour, and its caret and selection as the browser's Yjs
5//! awareness says them — relayed to everyone on that note through
6//! `watch` (`present`, `left`).
7//!
8//! An entry is **held** by an open `notes.watch { id, session }`: it comes
9//! with the watch and goes when the watch does (the connection closed, the
10//! page left). `notes.here` moves its caret. A writer with no watch open —
11//! an agent's `notes.save` over synapse — is present while it writes, and
12//! **idles out** [`IDLE_MS`] after its last word; a held entry idles out
13//! after [`HELD_IDLE_MS`] of silence and comes back with its next.
14
15use crate::events::Present;
16use crate::store::{now_ms, Change, NotesStore};
17use std::collections::HashMap;
18use std::sync::{Arc, Mutex};
19
20/// How long an entry no watch holds stays after its last word.
21pub const IDLE_MS: i64 = 30_000;
22/// How long a held entry stays silent before it idles out.
23pub const HELD_IDLE_MS: i64 = 10 * 60_000;
24
25/// The colours a presence is drawn in — chosen by its principal, so a
26/// person keeps theirs across notes (the carets' own, as y-codemirror
27/// draws them).
28pub const COLOURS: [&str; 8] = ["#d9480f", "#2b8a3e", "#1971c2", "#9c36b5", "#e8590c", "#0c8599", "#c2255c", "#5f3dc4"];
29
30#[derive(Debug, Clone)]
31struct Entry {
32    present: Present,
33    org: String,
34    held: u32,
35    last: i64,
36}
37
38/// Every presence entry, by note and session.
39#[derive(Debug, Default)]
40pub struct Presence {
41    entries: Mutex<HashMap<(String, String), Entry>>,
42}
43
44/// Who an entry is: what the caller's identity says.
45#[derive(Debug, Clone)]
46pub struct Who {
47    pub principal: String,
48    pub name: String,
49    pub agent: bool,
50}
51
52/// The colour of `principal`.
53pub fn colour_of(principal: &str) -> &'static str {
54    let h = principal.bytes().fold(0u32, |h, b| h.wrapping_mul(31).wrapping_add(b as u32));
55    COLOURS[(h as usize) % COLOURS.len()]
56}
57
58impl NotesStore {
59    fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<(String, String), Entry>> {
60        self.presence.entries.lock().unwrap_or_else(|p| p.into_inner())
61    }
62
63    /// `who` is on `id` (in `org`) as `session` — held by a watch when
64    /// `held`, else until it idles out; its caret as `client` and
65    /// `awareness` say, when they do. Said as `present` to everyone on it.
66    #[allow(clippy::too_many_arguments)]
67    pub fn arrive(&self, id: &str, org: &str, session: &str, who: &Who, held: bool, client: Option<u64>, awareness: Option<String>) -> Present {
68        self.sweep();
69        let key = (id.to_string(), session.to_string());
70        let mut entries = self.entries();
71        let e = entries.entry(key).or_insert_with(|| Entry {
72            present: Present { id: id.to_string(), session: session.to_string(), principal: who.principal.clone(), name: who.name.clone(), agent: who.agent, colour: colour_of(&who.principal).to_string(), client: None, awareness: None, at: now_ms() },
73            org: org.to_string(),
74            held: 0,
75            last: now_ms(),
76        });
77        if held {
78            e.held += 1;
79        }
80        if client.is_some() {
81            e.present.client = client;
82        }
83        if awareness.is_some() {
84            e.present.awareness = awareness;
85        }
86        e.last = now_ms();
87        e.present.at = e.last;
88        let present = e.present.clone();
89        drop(entries);
90        self.said(Change::Present { org: org.to_string(), present: present.clone() });
91        present
92    }
93
94    /// Whether `session` on `id` is someone else's than `principal`.
95    pub fn taken(&self, id: &str, session: &str, principal: &str) -> bool {
96        self.entries().get(&(id.to_string(), session.to_string())).is_some_and(|e| e.present.principal != principal)
97    }
98
99    /// A watch holding `session` on `id` ended: the entry goes when no
100    /// other watch holds it. Said as `left`.
101    pub fn leave(&self, id: &str, session: &str) {
102        let key = (id.to_string(), session.to_string());
103        let mut entries = self.entries();
104        let gone = match entries.get_mut(&key) {
105            Some(e) if e.held > 1 => {
106                e.held -= 1;
107                None
108            }
109            Some(_) => entries.remove(&key),
110            None => None,
111        };
112        drop(entries);
113        if let Some(e) = gone {
114            self.said(Change::Left { id: e.present.id, org: e.org, session: e.present.session, client: e.present.client });
115        }
116    }
117
118    /// Everyone on `id` now.
119    pub fn present(&self, id: &str) -> Vec<Present> {
120        self.sweep();
121        let mut out: Vec<Present> = self.entries().values().filter(|e| e.present.id == id).map(|e| e.present.clone()).collect();
122        out.sort_by(|a, b| a.at.cmp(&b.at).then(a.session.cmp(&b.session)));
123        out
124    }
125
126    /// The entries idle past their time, gone — each said as `left`.
127    pub fn sweep(&self) {
128        let now = now_ms();
129        let mut entries = self.entries();
130        let idle: Vec<(String, String)> = entries.iter().filter(|(_, e)| now - e.last > if e.held > 0 { HELD_IDLE_MS } else { IDLE_MS }).map(|(k, _)| k.clone()).collect();
131        let gone: Vec<Entry> = idle.into_iter().filter_map(|k| entries.remove(&k)).collect();
132        drop(entries);
133        for e in gone {
134            self.said(Change::Left { id: e.present.id, org: e.org, session: e.present.session, client: e.present.client });
135        }
136    }
137}
138
139/// Holds a watch's presence: the entry goes when this does (the stream
140/// dropped — its connection closed).
141pub struct Held {
142    pub(crate) store: Arc<NotesStore>,
143    pub(crate) id: String,
144    pub(crate) session: String,
145}
146
147impl Drop for Held {
148    fn drop(&mut self) {
149        self.store.leave(&self.id, &self.session);
150    }
151}