Skip to main content

vector_core/
news.rs

1//! What a listening client is told as news: everything sent since it began listening, once,
2//! however it reached this device (live, a catch-up, a replay). What came before is history:
3//! stored, never announced.
4//!
5//! Once is anchored on the store: an event is news only the first time this device keeps it,
6//! so the paths that can carry it (the live feed, every catch-up, a replay) race harmlessly.
7
8use std::sync::{Arc, Mutex};
9
10use crate::event_handler::InboundEventHandler;
11
12/// How long before listening began an event still counts: senders' clocks drift, and what was
13/// sent while the client started reached nobody else.
14pub const ALLOWANCE_MS: u64 = crate::community::REALTIME_FRESH_WINDOW_MS;
15
16struct Listening {
17    session: u64,
18    since_ms: u64,
19    handler: Arc<dyn InboundEventHandler>,
20}
21
22// Keyed by session id rather than held on the Session: two Session objects can share an id,
23// and a catch-up running on either must find the listener.
24static LISTENING: Mutex<Option<Listening>> = Mutex::new(None);
25
26/// `handler` hears what is sent from `since_ms` (unix ms) on, for the live session.
27pub(crate) fn begin(handler: Arc<dyn InboundEventHandler>, since_ms: u64) {
28    let session = crate::db::current_session_id();
29    *LISTENING.lock().unwrap_or_else(|e| e.into_inner()) = Some(Listening { session, since_ms, handler });
30}
31
32fn current<T>(f: impl FnOnce(&Listening) -> T) -> Option<T> {
33    let held = LISTENING.lock().unwrap_or_else(|e| e.into_inner());
34    held.as_ref().filter(|l| l.session == crate::db::current_session_id()).map(f)
35}
36
37/// This session's listener ends: catch-ups stop telling it anything.
38pub(crate) fn end() {
39    let mut held = LISTENING.lock().unwrap_or_else(|e| e.into_inner());
40    if held.as_ref().is_some_and(|l| l.session == crate::db::current_session_id()) {
41        *held = None;
42    }
43    *TOLD.lock().unwrap_or_else(|e| e.into_inner()) = Told::default();
44}
45
46/// What a listener has been told, by event id: the newest [`TOLD_GEN`] to two generations of the
47/// ids' first 8 bytes. Two paths that store the same event a moment apart (overlapping catch-ups,
48/// a page and the live feed) can each think they stored it first.
49#[derive(Default)]
50struct Told {
51    session: u64,
52    cur: std::collections::HashSet<u64>,
53    prev: std::collections::HashSet<u64>,
54}
55
56const TOLD_GEN: usize = 32_768;
57
58static TOLD: std::sync::LazyLock<Mutex<Told>> = std::sync::LazyLock::new(Mutex::default);
59
60/// Whether to tell this session's listener about `id` (an event id, or any 32 bytes naming one
61/// thing that happened): true the first time, and always when nobody is listening.
62pub fn first_telling(id: &[u8; 32]) -> bool {
63    let session = crate::db::current_session_id();
64    if listening_since().is_none() {
65        return true;
66    }
67    let key = u64::from_le_bytes(id[..8].try_into().expect("8 bytes"));
68    let mut told = TOLD.lock().unwrap_or_else(|e| e.into_inner());
69    if told.session != session {
70        *told = Told { session, ..Told::default() };
71    }
72    if told.cur.contains(&key) || told.prev.contains(&key) {
73        return false;
74    }
75    if told.cur.len() >= TOLD_GEN {
76        let Told { cur, prev, .. } = &mut *told;
77        std::mem::swap(cur, prev);
78        cur.clear();
79    }
80    told.cur.insert(key);
81    true
82}
83
84/// [`first_telling`] for a hex id; anything else names itself through a hash.
85pub fn first_telling_hex(id: &str) -> bool {
86    match crate::simd::hex::hex_to_bytes_32_checked(id) {
87        Some(bytes) => first_telling(&bytes),
88        None => {
89            use sha2::Digest;
90            first_telling(&sha2::Sha256::digest(id.as_bytes()).into())
91        }
92    }
93}
94
95/// The handler listening for this session, if one is.
96pub(crate) fn listener() -> Option<Arc<dyn InboundEventHandler>> {
97    current(|l| l.handler.clone())
98}
99
100/// When this session's listener began (unix ms), if one is listening.
101pub fn listening_since() -> Option<u64> {
102    current(|l| l.since_ms)
103}
104
105/// The earliest send time (unix ms) still news to this session's listener.
106pub fn cutoff() -> Option<u64> {
107    listening_since().map(|since| since.saturating_sub(ALLOWANCE_MS))
108}
109
110/// Whether something sent at `at_ms` is news. With a listener: sent since it began. Without one
111/// (a UI paints history anyway), only what is fresh now.
112pub fn is_news(at_ms: u64) -> bool {
113    match cutoff() {
114        Some(from) => at_ms >= from,
115        None => crate::community::is_realtime_fresh(at_ms),
116    }
117}
118
119/// A listener for a test's length: it ends when this drops.
120#[cfg(test)]
121pub(crate) struct TestListener;
122
123#[cfg(test)]
124pub(crate) fn listen_for_test(handler: Arc<dyn InboundEventHandler>, since_ms: u64) -> TestListener {
125    begin(handler, since_ms);
126    TestListener
127}
128
129#[cfg(test)]
130impl Drop for TestListener {
131    fn drop(&mut self) {
132        *LISTENING.lock().unwrap_or_else(|e| e.into_inner()) = None;
133        *TOLD.lock().unwrap_or_else(|e| e.into_inner()) = Told::default();
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn a_listener_hears_what_was_sent_since_it_began_however_late_it_arrives() {
143        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
144        let now = crate::clock::now_ms();
145        *LISTENING.lock().unwrap() = None;
146        assert!(!is_news(now - 3_600_000), "an hour old, nobody listening: history");
147        assert!(is_news(now), "fresh, nobody listening: news");
148
149        begin(Arc::new(crate::event_handler::NoOpEventHandler), now - 3_600_000);
150        assert!(is_news(now - 3_000_000), "sent after listening began, arriving 50 minutes late");
151        assert!(is_news(now - 3_600_000 - ALLOWANCE_MS + 1), "within the allowance before it");
152        assert!(!is_news(now - 3_600_000 - ALLOWANCE_MS - 1), "before it: history");
153        end();
154        assert!(listening_since().is_none());
155    }
156
157    #[test]
158    fn a_listener_is_told_each_thing_once() {
159        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
160        assert!(first_telling(&[1; 32]) && first_telling(&[1; 32]), "nobody listening: nothing to remember");
161        begin(Arc::new(crate::event_handler::NoOpEventHandler), crate::clock::now_ms());
162        assert!(first_telling(&[2; 32]));
163        assert!(!first_telling(&[2; 32]), "a second path carrying it says nothing");
164        assert!(first_telling_hex("not hex") && !first_telling_hex("not hex"));
165        end();
166    }
167}