Skip to main content

cosmic_applet_avestruz/nostr/
sweep.rs

1// SPDX-License-Identifier: MIT
2
3//! What the event store lets go of: the notes it has had for longer than
4//! they are likely to be looked at again.
5//!
6//! Everything the relays answer with is kept in the store, which is why a
7//! feed, a thread or a profile shows at once the second time. Nothing in
8//! it was ever let go of, and it grew for as long as it was used. A sweep
9//! takes out what is older than a given moment, by the date each event
10//! says it was written: not by when it was last looked at, which the
11//! store doesn't know.
12//!
13//! What is swept is what can be asked of the relays again, and is asked
14//! again when it is looked at: other people's notes, comments, reposts,
15//! reactions and zap receipts. What is kept, however old:
16//!
17//! - what the account wrote itself, of any kind;
18//! - whatever there is one of for each person, since its date says
19//!   nothing of whether it still holds: profiles, contact lists, relay
20//!   lists and every other list (the replaceable and addressable kinds),
21//!   whoever wrote them;
22//! - the notes the account bookmarked.
23//!
24//! It goes through the store a page at a time, newest first from the
25//! moment given, and takes each page's old events out in one go, so that
26//! what the relays send meanwhile is written between two pages rather than
27//! after the whole sweep.
28//!
29//! ```mermaid
30//! flowchart TD
31//!     event["An event written before the limit"] --> mine{"Did the account write it?"}
32//!     mine -->|"yes"| stays["Stays"]
33//!     mine -->|"no"| kind{"Is there one of it for each person: replaceable, or addressable?"}
34//!     kind -->|"yes: a profile, a contact list, a relay list, an article"| stays
35//!     kind -->|"no: a note, a comment, a repost, a reaction, a zap receipt"| bookmarked{"Did the account bookmark it?"}
36//!     bookmarked -->|"yes"| stays
37//!     bookmarked -->|"no"| goes["Goes"]
38//! ```
39//!
40//! When a sweep runs, and what it waits for, is in
41//! [`crate::handlers::store`] and [`crate::guide::flows`].
42
43use std::collections::HashSet;
44
45use nostr_sdk::prelude::{Event, EventId, Filter, NostrDatabase, PublicKey, Timestamp};
46
47/// How many events are looked at, and at most taken out, at a time.
48const PAGE: usize = 500;
49
50/// Whether `event` stays in the store however old it is: `account` wrote
51/// it, or bookmarked it, or it is of a kind there is one of for each
52/// person.
53fn stays(event: &Event, account: PublicKey, bookmarked: &HashSet<EventId>) -> bool {
54    event.pubkey == account || event.kind.is_replaceable() || event.kind.is_addressable() || bookmarked.contains(&event.id)
55}
56
57/// Take out of `database` what was written at `before` or earlier and
58/// doesn't stay (see [`stays`]). Returns how many events that was.
59pub async fn sweep(
60    database: &dyn NostrDatabase,
61    account: PublicKey,
62    bookmarked: &HashSet<EventId>,
63    before: Timestamp,
64) -> Result<usize, String> {
65    let mut swept = 0;
66    let mut until = before;
67    loop {
68        let page = database.query(Filter::new().until(until).limit(PAGE)).await.map_err(|e| e.to_string())?;
69        let Some(oldest) = page.iter().map(|event| event.created_at).min() else {
70            break;
71        };
72        let old: Vec<EventId> = page.iter().filter(|event| !stays(event, account, bookmarked)).map(|event| event.id).collect();
73        let nothing_old = old.is_empty();
74        if !nothing_old {
75            swept += old.len();
76            database.delete(Filter::new().ids(old)).await.map_err(|e| e.to_string())?;
77        }
78        if page.len() < PAGE {
79            break;
80        }
81        // The next page starts at the second this one ended in: what was
82        // cut off there is on it, after what stayed. A page that is all
83        // of that one second and all staying says nothing new the second
84        // time, and the second before it is gone on to.
85        until = if nothing_old && oldest == until {
86            match oldest.as_secs().checked_sub(1) {
87                Some(earlier) => Timestamp::from_secs(earlier),
88                None => break,
89            }
90        } else {
91            oldest
92        };
93    }
94    Ok(swept)
95}
96
97#[cfg(test)]
98mod tests {
99    use super::{PAGE, sweep};
100    use nostr_lmdb::NostrLmdb;
101    use nostr_sdk::prelude::{
102        Event, EventBuilder, EventId, Filter, FinalizeEvent, IntoNostrDatabase, Keys, Kind, NostrDatabase, Tag, Timestamp,
103    };
104    use std::collections::HashSet;
105    use std::sync::Arc;
106
107    /// An event of `kind` that `keys` wrote at `at`.
108    fn event(keys: &Keys, kind: Kind, content: &str, at: u64) -> Event {
109        EventBuilder::new(kind, content).custom_created_at(Timestamp::from_secs(at)).finalize(keys).unwrap()
110    }
111
112    /// Run `test` over an empty store, which is taken away after.
113    fn with_store(name: &str, test: impl AsyncFnOnce(Arc<dyn NostrDatabase>)) {
114        let store = std::env::temp_dir().join(format!("avestruz-test-{}-sweep-{name}", std::process::id()));
115        let _ = std::fs::remove_dir_all(&store);
116        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
117        runtime.block_on(async {
118            tokio::fs::create_dir_all(&store).await.unwrap();
119            test(NostrLmdb::open(&store).await.unwrap().into_nostr_database()).await;
120        });
121        drop(runtime);
122        let _ = std::fs::remove_dir_all(&store);
123    }
124
125    async fn ids_left(database: &dyn NostrDatabase) -> HashSet<EventId> {
126        database.query(Filter::new()).await.unwrap().into_iter().map(|event| event.id).collect()
127    }
128
129    #[test]
130    fn what_is_old_and_can_be_asked_again_is_swept() {
131        with_store("kinds", async |database| {
132            let (me, other) = (Keys::generate(), Keys::generate());
133            let (old, new) = (1_000, 2_000);
134            let article = EventBuilder::new(Kind::LongFormTextNote, "an article")
135                .tag(Tag::identifier("post"))
136                .custom_created_at(Timestamp::from_secs(old))
137                .finalize(&other)
138                .unwrap();
139            let stay = [
140                event(&me, Kind::TextNote, "mine, old", old),
141                event(&me, Kind::Reaction, "+", old),
142                event(&other, Kind::Metadata, r#"{"name":"other"}"#, old),
143                event(&other, Kind::ContactList, "", old),
144                event(&other, Kind::RelayList, "", old),
145                article,
146                event(&other, Kind::TextNote, "bookmarked", old),
147                event(&other, Kind::TextNote, "new", new),
148                event(&other, Kind::Reaction, "+", new),
149                event(&other, Kind::TextNote, "written the second after", 1_501),
150            ];
151            let go = [
152                event(&other, Kind::TextNote, "old", old),
153                event(&other, Kind::Comment, "an old comment", old),
154                event(&other, Kind::Repost, "", old),
155                event(&other, Kind::Reaction, "+", old),
156                event(&other, Kind::ZapReceipt, "", old),
157                event(&other, Kind::TextNote, "written that second", 1_500),
158            ];
159            for event in stay.iter().chain(&go) {
160                database.save_event(event).await.unwrap();
161            }
162            let bookmarked = HashSet::from([stay[6].id]);
163
164            let swept = sweep(database.as_ref(), me.public_key(), &bookmarked, Timestamp::from_secs(1_500)).await;
165            assert_eq!(swept, Ok(go.len()));
166            assert_eq!(ids_left(database.as_ref()).await, stay.iter().map(|event| event.id).collect());
167
168            // A second sweep finds nothing, and what was swept can be
169            // kept again when a relay sends it.
170            assert_eq!(sweep(database.as_ref(), me.public_key(), &bookmarked, Timestamp::from_secs(1_500)).await, Ok(0));
171            assert!(database.save_event(&go[0]).await.unwrap().is_success());
172            assert_eq!(database.query(Filter::new().id(go[0].id)).await.unwrap().len(), 1);
173        });
174    }
175
176    #[test]
177    fn a_sweep_goes_through_more_than_a_page() {
178        with_store("pages", async |database| {
179            let (me, other) = (Keys::generate(), Keys::generate());
180            // More of what stays in one second than a page holds, with
181            // what goes in that second, after it and before it.
182            let mut stay = Vec::new();
183            let mut go = Vec::new();
184            for nth in 0..PAGE + 20 {
185                stay.push(event(&me, Kind::TextNote, &format!("mine {nth}"), 5_000));
186            }
187            for nth in 0..PAGE + 20 {
188                let at = 4_000 + (nth as u64 % 7);
189                go.push(event(&other, Kind::TextNote, &format!("theirs {nth}"), at));
190                stay.push(event(&me, Kind::TextNote, &format!("mine too {nth}"), at));
191            }
192            for nth in 0..30 {
193                go.push(event(&other, Kind::Reaction, &format!("{nth}"), 6_000));
194                go.push(event(&other, Kind::Reaction, &format!("{nth}"), 10));
195            }
196            for event in stay.iter().chain(&go) {
197                database.save_event(event).await.unwrap();
198            }
199
200            let swept = sweep(database.as_ref(), me.public_key(), &HashSet::new(), Timestamp::from_secs(7_000)).await;
201            assert_eq!(swept, Ok(go.len()));
202            assert_eq!(ids_left(database.as_ref()).await, stay.iter().map(|event| event.id).collect());
203        });
204    }
205}