1use std::sync::{Arc, Mutex};
9
10use crate::event_handler::InboundEventHandler;
11
12pub 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
22static LISTENING: Mutex<Option<Listening>> = Mutex::new(None);
25
26pub(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
37pub(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#[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
60pub 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
84pub 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
95pub(crate) fn listener() -> Option<Arc<dyn InboundEventHandler>> {
97 current(|l| l.handler.clone())
98}
99
100pub fn listening_since() -> Option<u64> {
102 current(|l| l.since_ms)
103}
104
105pub fn cutoff() -> Option<u64> {
107 listening_since().map(|since| since.saturating_sub(ALLOWANCE_MS))
108}
109
110pub 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#[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}