Skip to main content

cosmic_applet_avestruz/nostr/
feed.rs

1// SPDX-License-Identifier: MIT
2
3//! A list of notes, newest first: the feed, and the notes on a profile.
4//!
5//! A list is read in one of two ways, [`FeedMode`]: the notes that start a
6//! conversation, or those and the replies among them. Both are kept in
7//! order, so that changing the way is showing the other.
8//!
9//! What a list shows only changes when its reader says so. Notes that turn
10//! up after it was first filled wait beside it, as [`Pending`], until they
11//! are asked for.
12//!
13//! ```mermaid
14//! flowchart TD
15//!     page["A look at the relays brings the newest page"] --> fresh{"Any note the list doesn't have?"}
16//!     fresh -->|"no"| nothing["Nothing waits"]
17//!     fresh -->|"yes"| reach{"Does the page reach back to the list's newest note?"}
18//!     reach -->|"yes, or the page was not full"| joined["They wait, joined to the list: shown, they go in above it"]
19//!     reach -->|"no: more than a page turned up"| detached["They wait, detached: shown, the list starts over from them"]
20//! ```
21//!
22//! A list has no holes: from its newest note to its oldest it has every
23//! note the relays gave. Notes that wait and don't reach down to the list
24//! would leave one, so showing them starts the list over, and what is
25//! older comes back as it is scrolled to its end.
26//!
27//! How this fits with looking for new notes on a timer is in
28//! [`crate::guide::flows`].
29
30use std::cmp::Reverse;
31use std::collections::{HashMap, HashSet};
32
33use nostr_sdk::prelude::{EventId, PublicKey};
34use serde::{Deserialize, Serialize};
35
36use crate::nostr::models::Note;
37
38/// Which of a list's notes are shown.
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub enum FeedMode {
41    /// The notes that start a conversation: no replies.
42    #[default]
43    Notes,
44    /// Those, and the replies among them: everything.
45    Replies,
46}
47
48impl FeedMode {
49    /// Both ways, in the order they are offered.
50    pub const ALL: [Self; 2] = [Self::Notes, Self::Replies];
51}
52
53/// Which page of a feed was asked of the relays.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum FeedPage {
56    /// The newest notes there are.
57    Newest,
58    /// The notes before the oldest one in the feed.
59    Older,
60}
61
62/// The order of a feed: newest first, and by id among notes of the same
63/// second, so the order is the same however the notes arrived.
64fn feed_order(note: &Note) -> (Reverse<u64>, EventId) {
65    (Reverse(note.created_at), note.id)
66}
67
68/// The `limit` newest of `notes`, newest first, each note once.
69///
70/// A page asked of several relays comes back as each relay's newest `limit`,
71/// which reach different distances into the past. Keeping only the newest
72/// `limit` of them all cuts the page where the busiest relay's answer ends, so
73/// the next page, asked from that cut down, leaves no gap in any relay's
74/// notes.
75pub fn newest(notes: impl IntoIterator<Item = Note>, limit: usize) -> Vec<Note> {
76    let mut notes: Vec<Note> = notes.into_iter().collect();
77    notes.sort_by_key(feed_order);
78    notes.dedup_by_key(|note| note.id);
79    notes.truncate(limit);
80    notes
81}
82
83/// A feed's notes, newest first, each note once.
84#[derive(Debug, Default)]
85pub struct Feed {
86    /// Every note.
87    notes: Vec<Note>,
88    /// Those of them that answer nothing, over again: a list shows a
89    /// run of notes, and these are not one among the others.
90    starters: Vec<Note>,
91    ids: HashSet<EventId>,
92}
93
94impl Feed {
95    /// The notes `mode` shows, newest first.
96    pub fn notes(&self, mode: FeedMode) -> &[Note] {
97        match mode {
98            FeedMode::Notes => &self.starters,
99            FeedMode::Replies => &self.notes,
100        }
101    }
102
103    /// Every note, whichever way the feed is read.
104    pub fn all(&self) -> &[Note] {
105        &self.notes
106    }
107
108    /// How many notes there are, of every kind.
109    pub fn len(&self) -> usize {
110        self.notes.len()
111    }
112
113    /// Whether there is no note at all.
114    pub fn is_empty(&self) -> bool {
115        self.notes.is_empty()
116    }
117
118    /// When the oldest note was written; where the next older page starts.
119    pub fn oldest(&self) -> Option<u64> {
120        self.notes.last().map(|note| note.created_at)
121    }
122
123    /// When the newest note was written.
124    pub fn newest(&self) -> Option<u64> {
125        self.notes.first().map(|note| note.created_at)
126    }
127
128    /// Whether the note `id` is among these.
129    pub fn contains(&self, id: EventId) -> bool {
130        self.ids.contains(&id)
131    }
132
133    /// Keep the `count` newest notes, and let go of the rest.
134    fn truncate(&mut self, count: usize) {
135        for dropped in self.notes.drain(count.min(self.notes.len())..) {
136            self.ids.remove(&dropped.id);
137        }
138        let ids = &self.ids;
139        self.starters.retain(|note| ids.contains(&note.id));
140    }
141
142    /// Show those of the notes already here that come again in `notes`
143    /// with more of the notes they quote as they come now. Only for a list
144    /// nobody can have been reading: a note that gains what it quotes gets
145    /// taller. Returns the people the notes that changed are shown with.
146    pub fn take_quotes_from(&mut self, notes: &[Note]) -> Vec<PublicKey> {
147        let better: HashMap<EventId, &Note> = notes
148            .iter()
149            .filter(|note| self.ids.contains(&note.id))
150            .filter(|note| self.notes.iter().any(|known| known.id == note.id && known.quoted_count() < note.quoted_count()))
151            .map(|note| (note.id, note))
152            .collect();
153        for known in self.notes.iter_mut().chain(self.starters.iter_mut()) {
154            if let Some(note) = better.get(&known.id) {
155                known.quoted.clone_from(&note.quoted);
156            }
157        }
158        let mut seen = HashSet::new();
159        better.values().flat_map(|note| note.people()).filter(|person| seen.insert(*person)).collect()
160    }
161
162    /// Add `notes`, wherever in the order they belong, skipping those already
163    /// here. Returns the people the notes that were new are shown with, their
164    /// authors and those they mention, each once.
165    pub fn merge(&mut self, notes: impl IntoIterator<Item = Note>) -> Vec<PublicKey> {
166        let mut people = Vec::new();
167        let mut seen = HashSet::new();
168        let before = self.notes.len();
169        for note in notes {
170            if !self.ids.insert(note.id) {
171                continue;
172            }
173            people.extend(note.people().filter(|person| seen.insert(*person)));
174            if !note.is_reply() {
175                self.starters.push(note.clone());
176            }
177            self.notes.push(note);
178        }
179        if self.notes.len() > before {
180            self.notes.sort_by_key(feed_order);
181            self.starters.sort_by_key(feed_order);
182        }
183        people
184    }
185}
186
187/// How many notes wait to be shown at the most. Past that the oldest are
188/// let go of: the applet runs for as long as the session does, and may be
189/// left alone for all of it. Showing them asks what was made of each, so
190/// it is not many more than are worth asking about at once.
191const PENDING_MAX: usize = 200;
192
193/// The notes that turned up for a list after it was first filled: newer
194/// than its newest, or missing from among the others. They wait here until
195/// the reader asks for them, so that what is being read stays as it is.
196///
197/// A list has no holes: from its newest note down to its oldest, it has
198/// every note the relays gave. Notes that wait may not reach all the way
199/// down to the list's newest (a page from the relays is only so long, and
200/// there may have been more than a page since). They are then
201/// [detached](Self::is_detached), and showing them starts the list over
202/// from them rather than leave a hole behind.
203#[derive(Debug, Default)]
204pub struct Pending {
205    /// The notes, newest first, without a hole among them.
206    notes: Feed,
207    /// There may be notes between these and the list's newest that are not
208    /// here.
209    detached: bool,
210}
211
212impl Pending {
213    /// The notes that wait, as `mode` shows them, newest first.
214    pub fn notes(&self, mode: FeedMode) -> &[Note] {
215        self.notes.notes(mode)
216    }
217
218    /// Whether nothing waits.
219    pub fn is_empty(&self) -> bool {
220        self.notes.is_empty()
221    }
222
223    /// Whether there may be more notes between these and the list's newest
224    /// than are here: there are then at least as many new notes as wait.
225    pub fn is_detached(&self) -> bool {
226        self.detached
227    }
228
229    /// Take in `page`, the newest notes the relays have for the list whose
230    /// notes are `feed`, `full` if the relays may have had more than they
231    /// gave. Those `feed` doesn't have wait from now on. Returns the people
232    /// the ones that are new here are shown with.
233    ///
234    /// A page that is not full is everything there is. A full one reaches
235    /// as far back as its oldest note, and whatever is known to be newer
236    /// than that, it joins up with. If it stops short of the notes that
237    /// already wait, those are let go of: the page is newer, and a hole
238    /// between the two could not be shown.
239    pub fn offer(&mut self, feed: &Feed, page: Vec<Note>, full: bool) -> Vec<PublicKey> {
240        let reaches_back_to = page.iter().map(|note| note.created_at).min();
241        let fresh: Vec<Note> = page.into_iter().filter(|note| !feed.contains(note.id)).collect();
242        if fresh.is_empty() {
243            return Vec::new();
244        }
245        let joins = |known: Option<u64>| !full || known.is_none_or(|known| reaches_back_to.is_some_and(|oldest| oldest <= known));
246        if joins(feed.newest()) {
247            self.detached = false;
248        } else if !joins(self.notes.newest()) {
249            self.notes = Feed::default();
250            self.detached = true;
251        } else if self.notes.is_empty() {
252            self.detached = true;
253        }
254        let people = self.notes.merge(fresh);
255        if self.notes.len() > PENDING_MAX {
256            self.notes.truncate(PENDING_MAX);
257            self.detached = true;
258        }
259        people
260    }
261
262    /// Have `note` wait with the rest: one the reader wrote, on its way to
263    /// being shown with them.
264    pub fn add(&mut self, note: Note) {
265        self.notes.merge([note]);
266    }
267
268    /// Stop waiting: the notes, newest first, and whether they were
269    /// detached from the list they are for.
270    pub fn take(&mut self) -> (Vec<Note>, bool) {
271        let taken = std::mem::take(self);
272        (taken.notes.notes, taken.detached)
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::{Feed, FeedMode, PENDING_MAX, Pending, newest};
279    use crate::nostr::content;
280    use crate::nostr::models::{Note, ReplyTo};
281    use nostr_sdk::prelude::{EventId, Keys, Kind, PublicKey, ToBech32};
282
283    fn author() -> PublicKey {
284        Keys::generate().public_key()
285    }
286
287    /// A note whose id is `id` repeated, written at `created_at`.
288    fn note(id: u8, created_at: u64, author: PublicKey) -> Note {
289        Note {
290            id: EventId::from_byte_array([id; 32]),
291            kind: Kind::TextNote,
292            author,
293            created_at,
294            content: content::parse(&format!("note {id}"), 100),
295            reply_to: None,
296            quoted: Vec::new(),
297        }
298    }
299
300    fn ids(notes: &[Note]) -> Vec<u8> {
301        notes.iter().map(|note| note.id.as_bytes()[0]).collect()
302    }
303
304    #[test]
305    fn a_note_that_comes_again_with_what_it_quotes_is_shown_with_it() {
306        let (a, b) = (author(), author());
307        let mut feed = Feed::default();
308        let answer = Note {
309            reply_to: Some(ReplyTo { root: EventId::from_byte_array([9; 32]), parent: EventId::from_byte_array([9; 32]) }),
310            ..note(2, 20, a)
311        };
312        feed.merge([note(1, 10, a), answer.clone(), note(3, 30, a)]);
313
314        // The same notes from the relays: the first with the note it
315        // quotes, the others as they were; and one the feed doesn't have.
316        let quoting = Note { quoted: vec![note(7, 5, b)], ..note(1, 10, a) };
317        let people = feed.take_quotes_from(&[
318            quoting.clone(),
319            answer,
320            note(3, 30, a),
321            Note { quoted: vec![note(8, 6, b)], ..note(4, 40, a) },
322        ]);
323
324        assert_eq!(people, [a, b], "whoever the note that changed is shown with");
325        assert_eq!(ids(feed.all()), [3, 2, 1], "nothing is added, and nothing moves");
326        for shown in [feed.notes(FeedMode::Replies), feed.notes(FeedMode::Notes)] {
327            assert_eq!(shown.iter().find(|note| note.id == quoting.id), Some(&quoting), "in every way the list is read");
328        }
329
330        // A copy that has no more to show changes nothing, and nobody.
331        assert!(feed.take_quotes_from(&[quoting, note(3, 30, a)]).is_empty());
332        assert!(feed.take_quotes_from(&[note(1, 10, a)]).is_empty(), "nor does one with less take anything away");
333        assert_eq!(feed.all().iter().map(|note| note.quoted.len()).collect::<Vec<_>>(), [0, 0, 1]);
334    }
335
336    #[test]
337    fn a_page_is_its_newest_notes_each_once() {
338        let a = author();
339        // Two relays answer: one busy (recent notes), one quiet (older ones),
340        // and both know note 5.
341        let busy = [note(5, 500, a), note(4, 400, a), note(3, 300, a)];
342        let quiet = [note(5, 500, a), note(2, 200, a), note(1, 100, a)];
343
344        let page = newest(busy.into_iter().chain(quiet), 3);
345
346        // Cut where the busy relay's answer ends: 2 and 1 wait for the next page.
347        assert_eq!(ids(&page), [5, 4, 3]);
348    }
349
350    #[test]
351    fn notes_of_the_same_second_keep_one_order() {
352        let a = author();
353        let one_way = newest([note(1, 100, a), note(2, 100, a), note(3, 100, a)], 10);
354        let another = newest([note(3, 100, a), note(1, 100, a), note(2, 100, a)], 10);
355        assert_eq!(ids(&one_way), ids(&another));
356    }
357
358    #[test]
359    fn merging_keeps_the_feed_newest_first_and_skips_known_notes() {
360        let (a, b) = (author(), author());
361        let mut feed = Feed::default();
362
363        assert_eq!(feed.merge([note(2, 200, a), note(4, 400, a)]), [a]);
364        assert_eq!(ids(feed.notes(FeedMode::Replies)), [4, 2]);
365
366        // An older page and a newer note arrive together; note 2 is known.
367        let new_authors = feed.merge([note(1, 100, b), note(2, 200, a), note(5, 500, b)]);
368        assert_eq!(ids(feed.notes(FeedMode::Replies)), [5, 4, 2, 1]);
369        assert_eq!(new_authors, [b], "only the authors of new notes, each once");
370        assert_eq!(feed.oldest(), Some(100));
371        assert_eq!(feed.len(), 4);
372    }
373
374    #[test]
375    fn merging_reports_the_people_new_notes_mention_too() {
376        let (a, b, mentioned) = (author(), author(), author());
377        let mut feed = Feed::default();
378        let mut reply = note(1, 100, a);
379        reply.content =
380            content::parse(&format!("hey nostr:{} and nostr:{}", mentioned.to_bech32().unwrap(), b.to_bech32().unwrap()), 100);
381
382        assert_eq!(feed.merge([reply, note(2, 200, b)]), [a, mentioned, b], "each person once, in the order met");
383    }
384
385    #[test]
386    fn replies_show_among_the_notes_or_not_at_all() {
387        let a = author();
388        let mut feed = Feed::default();
389        let answer = |id: u8, created_at: u64, to: u8| {
390            let parent = EventId::from_byte_array([to; 32]);
391            Note { reply_to: Some(ReplyTo { root: parent, parent }), ..note(id, created_at, a) }
392        };
393
394        feed.merge([note(1, 100, a), answer(2, 200, 1), note(3, 300, a)]);
395        // An older page, with a reply and a note in it.
396        feed.merge([answer(4, 50, 1), note(5, 40, a)]);
397
398        assert_eq!(ids(feed.notes(FeedMode::Replies)), [3, 2, 1, 4, 5], "everything, in order");
399        assert_eq!(ids(feed.notes(FeedMode::Notes)), [3, 1, 5], "what starts a conversation, in order");
400        assert_eq!(ids(feed.all()), [3, 2, 1, 4, 5]);
401        assert_eq!((feed.len(), feed.oldest()), (5, Some(40)));
402
403        // A comment is a reply whatever it is about, even something that
404        // can't be named as a note is.
405        feed.merge([Note { kind: Kind::Comment, ..note(6, 400, a) }]);
406        assert_eq!(ids(feed.notes(FeedMode::Replies)), [6, 3, 2, 1, 4, 5]);
407        assert_eq!(ids(feed.notes(FeedMode::Notes)), [3, 1, 5]);
408    }
409
410    #[test]
411    fn merging_nothing_new_reports_no_authors() {
412        let a = author();
413        let mut feed = Feed::default();
414        feed.merge([note(1, 100, a)]);
415        assert!(feed.merge([note(1, 100, a)]).is_empty());
416        assert!(Feed::default().oldest().is_none());
417    }
418
419    /// A feed of the notes `ids`, each written at ten times its id.
420    fn feed_of(ids: impl IntoIterator<Item = u8>, author: PublicKey) -> Feed {
421        let mut feed = Feed::default();
422        feed.merge(ids.into_iter().map(|id| note(id, u64::from(id) * 10, author)));
423        feed
424    }
425
426    /// The notes `ids` as a page from the relays, each written at ten times
427    /// its id.
428    fn page(ids: impl IntoIterator<Item = u8>, author: PublicKey) -> Vec<Note> {
429        ids.into_iter().map(|id| note(id, u64::from(id) * 10, author)).collect()
430    }
431
432    #[test]
433    fn notes_a_list_does_not_have_wait_and_the_list_stays_as_it_is() {
434        let a = author();
435        let feed = feed_of([1, 2, 3], a);
436        let mut pending = Pending::default();
437
438        // The relays' newest page: two notes the feed has, two it hasn't.
439        let people = pending.offer(&feed, page([2, 3, 4, 5], a), false);
440
441        assert_eq!(ids(pending.notes(FeedMode::Replies)), [5, 4]);
442        assert_eq!(people, [a]);
443        assert!(!pending.is_detached());
444        assert_eq!(ids(feed.all()), [3, 2, 1], "nothing was added to the feed");
445
446        // The same page again brings nothing new, and one more note joins.
447        assert!(pending.offer(&feed, page([2, 3, 4, 5], a), false).is_empty());
448        pending.offer(&feed, page([4, 5, 6], a), false);
449        assert_eq!(ids(pending.notes(FeedMode::Replies)), [6, 5, 4]);
450
451        let (notes, detached) = pending.take();
452        assert_eq!((ids(&notes), detached), (vec![6, 5, 4], false));
453        assert!(pending.is_empty());
454    }
455
456    #[test]
457    fn a_note_that_arrives_late_waits_too() {
458        let a = author();
459        // The feed has 1, 3 and 5; a relay that was behind now has 2.
460        let feed = feed_of([1, 3, 5], a);
461        let mut pending = Pending::default();
462        pending.offer(&feed, page([1, 2, 3, 5], a), false);
463        assert_eq!(ids(pending.notes(FeedMode::Replies)), [2]);
464        assert!(!pending.is_detached());
465    }
466
467    #[test]
468    fn a_full_page_that_stops_short_of_the_list_is_detached_from_it() {
469        let a = author();
470        let feed = feed_of([1, 2, 3], a);
471        let mut pending = Pending::default();
472
473        // A full page of notes all newer than the feed's newest: there may
474        // have been more in between.
475        pending.offer(&feed, page([7, 8, 9], a), true);
476        assert!(pending.is_detached());
477        assert_eq!(ids(pending.notes(FeedMode::Replies)), [9, 8, 7]);
478
479        // The next full page reaches back among those that wait: it joins
480        // them, and they are still short of the feed.
481        pending.offer(&feed, page([9, 10, 11], a), true);
482        assert_eq!(ids(pending.notes(FeedMode::Replies)), [11, 10, 9, 8, 7]);
483        assert!(pending.is_detached());
484
485        // One that stops short of those that wait takes their place.
486        pending.offer(&feed, page([20, 21], a), true);
487        assert_eq!(ids(pending.notes(FeedMode::Replies)), [21, 20]);
488        assert!(pending.is_detached());
489    }
490
491    #[test]
492    fn a_page_that_reaches_the_list_joins_what_waits_to_it() {
493        let a = author();
494        let feed = feed_of([1, 2, 3], a);
495        let mut pending = Pending::default();
496
497        // Full, and its oldest note is one the feed has: no hole.
498        pending.offer(&feed, page([3, 4, 5], a), true);
499        assert!(!pending.is_detached());
500
501        // Detached, and then a page that is all there is: joined up again.
502        pending.offer(&feed, page([8, 9], a), true);
503        assert!(pending.is_detached());
504        pending.offer(&feed, page([1, 2, 3, 4, 5, 6, 7, 8, 9], a), false);
505        assert!(!pending.is_detached());
506        assert_eq!(ids(pending.notes(FeedMode::Replies)), [9, 8, 7, 6, 5, 4]);
507    }
508
509    #[test]
510    fn what_waits_is_counted_as_the_list_is_read() {
511        let a = author();
512        let feed = feed_of([1], a);
513        let mut pending = Pending::default();
514        let parent = EventId::from_byte_array([1; 32]);
515        let answer = Note { reply_to: Some(ReplyTo { root: parent, parent }), ..note(3, 30, a) };
516
517        pending.offer(&feed, vec![note(2, 20, a), answer, note(4, 40, a)], false);
518
519        assert_eq!(ids(pending.notes(FeedMode::Replies)), [4, 3, 2]);
520        assert_eq!(ids(pending.notes(FeedMode::Notes)), [4, 2]);
521    }
522
523    #[test]
524    fn only_so_many_notes_wait() {
525        let a = author();
526        let feed = Feed::default();
527        let mut pending = Pending::default();
528        let many = (0..PENDING_MAX as u64 + 20).map(|at| {
529            let mut bytes = [0; 32];
530            bytes[..8].copy_from_slice(&at.to_be_bytes());
531            Note { id: EventId::from_byte_array(bytes), ..note(0, 1_000 + at, a) }
532        });
533
534        pending.offer(&feed, many.collect(), false);
535
536        let waiting = pending.notes(FeedMode::Replies);
537        assert_eq!(waiting.len(), PENDING_MAX);
538        assert_eq!(waiting.first().map(|note| note.created_at), Some(1_000 + PENDING_MAX as u64 + 19), "the newest stay");
539        assert!(pending.is_detached(), "the oldest were let go of: a hole");
540        assert_eq!(pending.notes(FeedMode::Notes).len(), PENDING_MAX);
541    }
542
543    #[test]
544    fn a_note_of_ones_own_waits_with_the_rest() {
545        let a = author();
546        let mut pending = Pending::default();
547        pending.offer(&feed_of([1], a), page([2], a), false);
548        pending.add(note(3, 30, a));
549        assert_eq!(ids(&pending.take().0), [3, 2]);
550    }
551}