Skip to main content

vector_core/community/
cache.rs

1//! Per-account RAM state for Community sync: the in-flight page claims. Keyed by this
2//! account's channel ids, so it lives on the account's session and goes when that does.
3
4use std::collections::HashSet;
5use std::sync::{Arc, Mutex};
6
7struct InflightKey;
8
9/// A channel's page direction: `true` for an older page, `false` for the latest.
10type PageKey = ([u8; 32], bool);
11type Inflight = Mutex<HashSet<PageKey>>;
12
13/// One running page fetch, released when dropped — on return or panic alike, so a
14/// panicking fetch can't wedge every later sync of its channel. Releases into the set
15/// it claimed from, whichever account is live by then.
16pub struct PageFetchClaim {
17    set: Arc<Inflight>,
18    key: Option<PageKey>,
19}
20
21impl Drop for PageFetchClaim {
22    fn drop(&mut self) {
23        if let Some(key) = self.key {
24            self.set.lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
25        }
26    }
27}
28
29/// Claim the fetch of one channel page. `None` if one is already running — the caller
30/// should no-op. A channel id that is not canonical hex names no channel; its claim
31/// always succeeds and guards nothing.
32pub fn claim_page_fetch(channel_id: &str, older: bool) -> Option<PageFetchClaim> {
33    let set = crate::db::current_session().scoped::<InflightKey, Inflight>();
34    let Some(channel) = super::id32_from_hex(channel_id) else {
35        return Some(PageFetchClaim { set, key: None });
36    };
37    let key = (channel, older);
38    if !set.lock().unwrap_or_else(|e| e.into_inner()).insert(key) {
39        return None;
40    }
41    Some(PageFetchClaim { set, key: Some(key) })
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[tokio::test]
49    async fn a_page_is_claimed_once_until_released() {
50        // A private session: the live one is swapped by tests running alongside.
51        crate::db::with_session(crate::db::Session::empty(), async {
52            let ch = "ab".repeat(32);
53            let latest = claim_page_fetch(&ch, false).expect("first claim");
54            assert!(claim_page_fetch(&ch, false).is_none(), "a running fetch refuses a second");
55            let older = claim_page_fetch(&ch, true).expect("the other direction is its own claim");
56            drop(latest);
57            let again = claim_page_fetch(&ch, false).expect("released on drop");
58            drop((again, older));
59            assert!(claim_page_fetch(&ch, true).is_some(), "both released");
60        })
61        .await;
62    }
63}