Skip to main content

vector_core/
early.rs

1//! A message dated ahead of this device's (corrected) clock waits until its time instead of
2//! showing at once: shown early, it would sit below everything sent after it, holding the bottom
3//! of the chat. Held in memory and never marked handled, so one cut short by a restart comes back
4//! through the next sync or history read, and released through the normal path, which judges it
5//! afresh, notifies and counts it unread as if it arrived then.
6
7use std::collections::HashSet;
8use std::sync::{Arc, Mutex, RwLock};
9
10use nostr_sdk::prelude::{Event, EventId};
11
12use crate::event_handler::InboundEventHandler;
13
14/// How far ahead of this device a message may be dated and still show at once.
15pub const TOLERANCE_MS: u64 = 5_000;
16
17/// How far ahead a message may be dated and still be held. One further out isn't: it stays on
18/// the relays for a later read once its date nears (CORD-02 §5's horizon, CORD-03 §1).
19pub const HORIZON_MS: u64 = 60 * 60 * 1000;
20
21/// How long a wait sleeps before reading the clock again, which a correction may have moved.
22const RECHECK: std::time::Duration = std::time::Duration::from_secs(60);
23
24/// Whether a message dated `at_ms` must wait.
25pub fn is_early(at_ms: u64) -> bool {
26    at_ms > crate::clock::now_ms().saturating_add(TOLERANCE_MS)
27}
28
29/// Which path a held wrap goes back through.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum Via {
32    /// A NIP-17 gift wrap.
33    Dm,
34    /// A Concord Chat Plane wrap.
35    Community,
36}
37
38struct Releaser;
39
40/// The handler of this account's live session, which released wraps go through.
41fn releaser() -> Arc<RwLock<Option<Arc<dyn InboundEventHandler>>>> {
42    crate::db::current_session().scoped::<Releaser, _>()
43}
44
45struct Holding;
46
47/// The wraps this account holds, so one delivered again doesn't wait twice.
48fn holding() -> Arc<Mutex<HashSet<EventId>>> {
49    crate::db::current_session().scoped::<Holding, _>()
50}
51
52/// Start this account's live session: held wraps are released through `handler`, and the clock
53/// is checked against the relays now, every `clock::RESYNC`, and whenever a server says
54/// it is off.
55pub fn start(handler: Arc<dyn InboundEventHandler>) {
56    let first = releaser().write().unwrap_or_else(|e| e.into_inner()).replace(handler).is_none();
57    if !first {
58        return;
59    }
60    crate::clock::load_setting();
61    crate::db::spawn_bound(async move {
62        loop {
63            let Some(client) = crate::state::nostr_client() else { return };
64            if !crate::db::current_session().is_live() {
65                return;
66            }
67            let relays: Vec<String> = client.relays().await.keys().map(|u| u.to_string()).collect();
68            crate::clock::sync_with(&relays).await;
69            crate::clock::until_next_check().await;
70        }
71    });
72}
73
74/// Hold `wrap`, a message dated `at_ms`, until it is due, then release it through `via`. One dated
75/// past [`HORIZON_MS`] is let go, to be read again once its date nears.
76pub fn hold(wrap: Event, via: Via, at_ms: u64) {
77    if at_ms > crate::clock::now_ms().saturating_add(HORIZON_MS) || !holding().lock().unwrap_or_else(|e| e.into_inner()).insert(wrap.id) {
78        return;
79    }
80    crate::db::spawn_bound(async move {
81        loop {
82            let (due, now) = (at_ms.saturating_sub(TOLERANCE_MS), crate::clock::now_ms());
83            if due <= now {
84                break;
85            }
86            crate::rt::time::sleep(std::time::Duration::from_millis(due - now).min(RECHECK)).await;
87        }
88        while !crate::state::is_processing_allowed() {
89            crate::rt::time::sleep(std::time::Duration::from_secs(1)).await;
90        }
91        holding().lock().unwrap_or_else(|e| e.into_inner()).remove(&wrap.id);
92        if !crate::db::current_session().is_live() {
93            return;
94        }
95        // No live session to show it in: a later sync or history read finds it.
96        let Some(handler) = releaser().read().unwrap_or_else(|e| e.into_inner()).clone() else { return };
97        match via {
98            Via::Dm => {
99                let _ = crate::event_handler::process_event(wrap, true, &*handler).await;
100            }
101            Via::Community => crate::community::v2::realtime::dispatch_event(wrap, handler).await,
102        }
103    });
104}
105
106#[cfg(test)]
107pub(crate) fn held(id: &EventId) -> bool {
108    holding().lock().unwrap_or_else(|e| e.into_inner()).contains(id)
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn a_message_waits_only_past_the_tolerance() {
117        let now = crate::clock::now_ms();
118        assert!(!is_early(now));
119        assert!(!is_early(now + TOLERANCE_MS - 1_000), "a few seconds fast still shows at once");
120        assert!(is_early(now + TOLERANCE_MS + 2_000));
121        assert!(is_early(now + 4 * 60 * 1000), "minutes ahead waits");
122    }
123
124    #[test]
125    fn a_message_past_the_horizon_is_never_held() {
126        use nostr_sdk::prelude::{EventBuilder, FinalizeEvent, Keys, Kind};
127        let wrap = EventBuilder::new(Kind::GiftWrap, "").finalize(&Keys::generate()).unwrap();
128        hold(wrap.clone(), Via::Dm, crate::clock::now_ms() + HORIZON_MS + 60_000);
129        assert!(!held(&wrap.id), "left for a read once its date nears");
130    }
131}