use std::collections::HashSet;
use std::sync::{Arc, Mutex};
struct InflightKey;
type PageKey = ([u8; 32], bool);
type Inflight = Mutex<HashSet<PageKey>>;
pub struct PageFetchClaim {
set: Arc<Inflight>,
key: Option<PageKey>,
}
impl Drop for PageFetchClaim {
fn drop(&mut self) {
if let Some(key) = self.key {
self.set.lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
}
}
}
pub fn claim_page_fetch(channel_id: &str, older: bool) -> Option<PageFetchClaim> {
let set = crate::db::current_session().scoped::<InflightKey, Inflight>();
let Some(channel) = super::id32_from_hex(channel_id) else {
return Some(PageFetchClaim { set, key: None });
};
let key = (channel, older);
if !set.lock().unwrap_or_else(|e| e.into_inner()).insert(key) {
return None;
}
Some(PageFetchClaim { set, key: Some(key) })
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn a_page_is_claimed_once_until_released() {
crate::db::with_session(crate::db::Session::empty(), async {
let ch = "ab".repeat(32);
let latest = claim_page_fetch(&ch, false).expect("first claim");
assert!(claim_page_fetch(&ch, false).is_none(), "a running fetch refuses a second");
let older = claim_page_fetch(&ch, true).expect("the other direction is its own claim");
drop(latest);
let again = claim_page_fetch(&ch, false).expect("released on drop");
drop((again, older));
assert!(claim_page_fetch(&ch, true).is_some(), "both released");
})
.await;
}
}