Skip to main content

rostra_client_db/
self_followee.rs

1use std::ops::Bound;
2
3use bincode::Decode;
4use rostra_core::Timestamp;
5use rostra_core::event::PersonasTagsSelector;
6use rostra_core::id::RostraId;
7
8use crate::{Database, DbResult, IdsFolloweesRecord, ids_followees};
9
10/// One active direct follow in a coherent current self-follow snapshot.
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub struct SelfFollowee {
13    /// Identity currently followed by the database owner.
14    pub followee: RostraId,
15    /// Effective tag-based persona selector of the winning follow.
16    pub persona_selector: PersonasTagsSelector,
17    /// Start of the current uninterrupted follow epoch.
18    pub first_ts: Timestamp,
19}
20
21impl Database {
22    /// Gets all active direct self-follows from one current-state read
23    /// snapshot.
24    ///
25    /// An unfollow removes the relationship from this snapshot. A later
26    /// refollow creates a new uninterrupted epoch whose `first_ts` excludes
27    /// follows at or before the winning unfollow boundary. Additional
28    /// follows in the current epoch can move `first_ts` earlier, while the
29    /// effective persona selector continues to come from the winning follow
30    /// event.
31    ///
32    /// Concurrent commits fall wholly before or after the read snapshot; the
33    /// returned records never combine relationships from different database
34    /// states. The order of returned records is unspecified.
35    ///
36    /// # Errors
37    ///
38    /// Returns an error on storage or record decode failure.
39    pub async fn get_self_followees_snapshot(&self) -> DbResult<Vec<SelfFollowee>> {
40        self.read_with(|tx| {
41            let followees = tx.open_table(&ids_followees::TABLE)?;
42            let prefix = bincode::encode_to_vec(self.self_id, redb_bincode::BINCODE_CONFIG)
43                .expect("encoding a followee prefix cannot fail");
44            let prefix_end = lexicographic_successor(&prefix);
45            followees
46                .as_raw()
47                .range::<&[u8]>((
48                    Bound::Included(prefix.as_slice()),
49                    prefix_end
50                        .as_deref()
51                        .map_or(Bound::Unbounded, Bound::Excluded),
52                ))?
53                .map(|entry| {
54                    let (key, value) = entry?;
55                    let (_, followee): (RostraId, RostraId) = decode_exact(key.value())?;
56                    let record: IdsFolloweesRecord = decode_exact(value.value())?;
57                    Ok(SelfFollowee {
58                        followee,
59                        persona_selector: record.effective_tags_selector(),
60                        first_ts: record.first_ts,
61                    })
62                })
63                .collect()
64        })
65        .await
66    }
67}
68
69fn decode_exact<T: Decode<()>>(bytes: &[u8]) -> DbResult<T> {
70    let (value, consumed) =
71        bincode::decode_from_slice::<T, _>(bytes, redb_bincode::BINCODE_CONFIG)?;
72    if consumed != bytes.len() {
73        return Err(
74            bincode::error::DecodeError::Other("Trailing bytes after encoded value").into(),
75        );
76    }
77    Ok(value)
78}
79
80fn lexicographic_successor(bytes: &[u8]) -> Option<Vec<u8>> {
81    let mut successor = bytes.to_vec();
82    let index = successor.iter().rposition(|byte| *byte != u8::MAX)?;
83    successor[index] += 1;
84    successor.truncate(index + 1);
85    Some(successor)
86}