use std::collections::HashMap;
use std::future::Future;
use std::hash::Hash;
use std::panic::AssertUnwindSafe;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use futures_util::FutureExt;
use futures_util::future::{BoxFuture, WeakShared};
use crate::client::AccountClient;
use crate::error::{Error, ErrorCode};
use crate::generated::services::campfires::ListCampfiresParams;
use crate::generated::types::DockItem;
pub const CAMPFIRE_INDEX_TTL: Duration = Duration::from_secs(10 * 60);
pub const CAMPFIRE_INDEX_MIN_REFRESH: Duration = Duration::from_secs(30);
pub const MAX_CAMPFIRE_CANDIDATES: usize = 50;
pub const MAX_CAMPFIRE_LISTING: usize = 1000;
const CAMPFIRE_INDEX_MAX_ITEMS: usize = 1024;
const CHAT_DOCK_TOOL: &str = "chat";
fn campfire_id_from_room_url(room_url: &str) -> Option<i64> {
let path = match url::Url::parse(room_url) {
Ok(parsed) if !parsed.cannot_be_a_base() => parsed.path().to_string(),
_ => room_url
.split(['?', '#'])
.next()
.unwrap_or_default()
.to_string(),
};
let last = path.strip_suffix(".json").unwrap_or(&path);
let (head, id) = last.rsplit_once('/')?;
if !head.ends_with("/chats") && head != "chats" {
return None;
}
if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
id.parse().ok().filter(|id| *id != 0)
}
pub(crate) type Clock = Arc<dyn Fn() -> Instant + Send + Sync>;
pub(crate) struct Hit<V> {
pub(crate) value: Arc<V>,
pub(crate) fetched: Instant,
pub(crate) cached: bool,
}
struct Entry<V> {
value: Arc<V>,
fetched: Instant,
seq: u64,
}
type Loaded<V> = Result<(Arc<V>, Instant), Arc<Error>>;
type PendingSlot<V> = WeakShared<BoxFuture<'static, Loaded<V>>>;
struct Registration<V> {
id: u64,
slot: PendingSlot<V>,
}
struct CacheState<K, V> {
seq: u64,
loads: u64,
entries: HashMap<K, Entry<V>>,
inflight: HashMap<K, Registration<V>>,
}
pub(crate) struct TtlCache<K, V> {
state: Mutex<CacheState<K, V>>,
clock: Clock,
ttl: Duration,
floor: Duration,
max_items: usize,
}
impl<K, V> TtlCache<K, V>
where
K: Eq + Hash + Clone + Send + Sync + 'static,
V: Send + Sync + 'static,
{
fn new(clock: Clock, ttl: Duration, floor: Duration, max_items: usize) -> TtlCache<K, V> {
TtlCache {
state: Mutex::new(CacheState {
seq: 0,
loads: 0,
entries: HashMap::new(),
inflight: HashMap::new(),
}),
clock,
ttl,
floor,
max_items,
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, CacheState<K, V>> {
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) async fn get<F, Fut>(
self: &Arc<Self>,
key: &K,
refresh: bool,
load: F,
) -> Result<Hit<V>, Error>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<V, Error>> + Send + 'static,
{
let pending = {
let mut state = self.lock();
if let Some(entry) = state.entries.get(key) {
let age = (self.clock)().saturating_duration_since(entry.fetched);
if age < self.ttl && (!refresh || age < self.floor) {
return Ok(Hit {
value: Arc::clone(&entry.value),
fetched: entry.fetched,
cached: true,
});
}
}
if let Some(pending) = state
.inflight
.get(key)
.and_then(|registered| registered.slot.upgrade())
{
pending
} else {
Self::sweep_inflight_locked(&mut state);
state.loads += 1;
let load_id = state.loads;
let cache = Arc::downgrade(self);
let owned = key.clone();
let loading = load();
let pending = async move {
let outcome = match AssertUnwindSafe(loading).catch_unwind().await {
Ok(result) => result.map_err(Arc::new),
Err(_) => Err(Arc::new(Error::new(
ErrorCode::ApiError,
"campfire discovery source panicked while loading",
))),
};
match cache.upgrade() {
Some(cache) => cache.publish(&owned, load_id, outcome),
None => outcome.map(|value| (Arc::new(value), Instant::now())),
}
}
.boxed()
.shared();
if let Some(slot) = pending.downgrade() {
state
.inflight
.insert(key.clone(), Registration { id: load_id, slot });
}
pending
}
};
match pending.await {
Ok((value, fetched)) => Ok(Hit {
value,
fetched,
cached: false,
}),
Err(error) => Err(project(&error)),
}
}
pub(crate) fn peek(&self, key: &K) -> Option<Hit<V>> {
let state = self.lock();
let entry = state.entries.get(key)?;
((self.clock)().saturating_duration_since(entry.fetched) < self.ttl).then(|| Hit {
value: Arc::clone(&entry.value),
fetched: entry.fetched,
cached: true,
})
}
fn publish(&self, key: &K, load_id: u64, outcome: Result<V, Arc<Error>>) -> Loaded<V> {
let mut state = self.lock();
if state
.inflight
.get(key)
.is_some_and(|registered| registered.id == load_id)
{
state.inflight.remove(key);
}
let value = Arc::new(outcome?);
let fetched = (self.clock)();
Self::sweep_inflight_locked(&mut state);
self.sweep_locked(&mut state, fetched);
self.make_room_locked(&mut state, key);
state.seq += 1;
let seq = state.seq;
state.entries.insert(
key.clone(),
Entry {
value: Arc::clone(&value),
fetched,
seq,
},
);
Ok((value, fetched))
}
fn sweep_inflight_locked(state: &mut CacheState<K, V>) {
state
.inflight
.retain(|_, registered| registered.slot.upgrade().is_some());
}
fn sweep_locked(&self, state: &mut CacheState<K, V>, now: Instant) {
state
.entries
.retain(|_, entry| now.saturating_duration_since(entry.fetched) < self.ttl);
}
fn make_room_locked(&self, state: &mut CacheState<K, V>, key: &K) {
if self.max_items == 0 || state.entries.contains_key(key) {
return; }
while state.entries.len() >= self.max_items {
let oldest = state
.entries
.iter()
.min_by_key(|(_, entry)| (entry.fetched, entry.seq))
.map(|(key, _)| key.clone());
match oldest {
Some(oldest) => {
state.entries.remove(&oldest);
}
None => break,
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct BucketKey {
pub(crate) account_id: String,
pub(crate) bucket_id: i64,
}
pub(crate) struct SourceRead {
pub(crate) ids: Vec<i64>,
pub(crate) fetched: Instant,
pub(crate) cached: bool,
}
pub(crate) struct CampfireIndex {
docks: Arc<TtlCache<BucketKey, Vec<i64>>>,
listings: Arc<TtlCache<String, HashMap<i64, Vec<i64>>>>,
}
impl std::fmt::Debug for CampfireIndex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CampfireIndex").finish_non_exhaustive()
}
}
impl CampfireIndex {
pub(crate) fn new() -> CampfireIndex {
CampfireIndex::with_clock(Arc::new(Instant::now))
}
pub(crate) fn with_clock(clock: Clock) -> CampfireIndex {
CampfireIndex {
docks: Arc::new(TtlCache::new(
Arc::clone(&clock),
CAMPFIRE_INDEX_TTL,
CAMPFIRE_INDEX_MIN_REFRESH,
CAMPFIRE_INDEX_MAX_ITEMS,
)),
listings: Arc::new(TtlCache::new(
clock,
CAMPFIRE_INDEX_TTL,
CAMPFIRE_INDEX_MIN_REFRESH,
CAMPFIRE_INDEX_MAX_ITEMS,
)),
}
}
pub(crate) async fn dock_campfires(
&self,
account: &AccountClient,
bucket_id: i64,
refresh: bool,
) -> Result<SourceRead, Error> {
let key = BucketKey {
account_id: account.account_id().to_string(),
bucket_id,
};
let reader = account.clone();
let hit = self
.docks
.get(&key, refresh, move || async move {
match reader.projects().get(bucket_id).await {
Ok(project) => Ok(project
.dock
.unwrap_or_default()
.iter()
.filter(|item: &&DockItem| item.name == CHAT_DOCK_TOOL && item.id != 0)
.map(|item| item.id)
.collect()),
Err(error) if error.code() == ErrorCode::NotFound => {
match reader.pings().get(bucket_id).await {
Ok(ping) => Ok(campfire_id_from_room_url(&ping.room_url)
.into_iter()
.collect()),
Err(error) if error.code() == ErrorCode::NotFound => Ok(Vec::new()),
Err(error) => Err(error),
}
}
Err(error) => Err(error),
}
})
.await?;
Ok(SourceRead {
ids: hit.value.as_ref().clone(),
fetched: hit.fetched,
cached: hit.cached,
})
}
pub(crate) fn cached_listed_campfires(
&self,
account_id: &str,
bucket_id: i64,
) -> Option<SourceRead> {
let hit = self.listings.peek(&account_id.to_string())?;
Some(SourceRead {
ids: hit.value.get(&bucket_id).cloned().unwrap_or_default(),
fetched: hit.fetched,
cached: true,
})
}
pub(crate) async fn listed_campfires(
&self,
account: &AccountClient,
bucket_id: i64,
refresh: bool,
) -> Result<SourceRead, Error> {
let key = account.account_id().to_string();
let reader = account.clone();
let hit = self
.listings
.get(&key, refresh, move || async move {
let first = reader
.campfires()
.list(&ListCampfiresParams::default())
.await?;
let listed = reader
.collect_all(first, Some(MAX_CAMPFIRE_LISTING))
.await?;
if listed.meta.truncated {
return Err(listing_overflow());
}
let mut by_bucket: HashMap<i64, Vec<i64>> = HashMap::new();
for campfire in listed.items {
if campfire.bucket.id == 0 {
continue;
}
by_bucket
.entry(campfire.bucket.id)
.or_default()
.push(campfire.id);
}
Ok(by_bucket)
})
.await?;
Ok(SourceRead {
ids: hit.value.get(&bucket_id).cloned().unwrap_or_default(),
fetched: hit.fetched,
cached: hit.cached,
})
}
}
#[derive(Debug)]
struct ListingOverflow;
impl std::fmt::Display for ListingOverflow {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "campfire listing exceeds {MAX_CAMPFIRE_LISTING}")
}
}
impl std::error::Error for ListingOverflow {}
fn project(error: &Arc<Error>) -> Error {
error.duplicate().with_source(Arc::clone(error))
}
fn listing_overflow() -> Error {
Error::new(
ErrorCode::ApiError,
"campfire listing is too large to cache",
)
.with_hint(ListingOverflow.to_string())
.with_source(ListingOverflow)
}
pub(crate) fn is_listing_overflow(error: &Error) -> bool {
error.find_source::<ListingOverflow>().is_some()
}
#[cfg(test)]
pub(crate) struct TestClock {
base: Instant,
offset: std::sync::atomic::AtomicU64,
}
#[cfg(test)]
impl TestClock {
pub(crate) fn new() -> Arc<TestClock> {
Arc::new(TestClock {
base: Instant::now(),
offset: std::sync::atomic::AtomicU64::new(0),
})
}
pub(crate) fn clock(self: &Arc<Self>) -> Clock {
let clock = Arc::clone(self);
Arc::new(move || {
clock.base
+ Duration::from_millis(clock.offset.load(std::sync::atomic::Ordering::SeqCst))
})
}
pub(crate) fn advance(&self, by: Duration) {
let millis = u64::try_from(by.as_millis()).unwrap_or(u64::MAX);
self.offset
.fetch_add(millis, std::sync::atomic::Ordering::SeqCst);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
fn cache<V: Send + Sync + 'static>(
clock: &Arc<TestClock>,
max_items: usize,
) -> Arc<TtlCache<i64, V>> {
Arc::new(TtlCache::new(
clock.clock(),
CAMPFIRE_INDEX_TTL,
CAMPFIRE_INDEX_MIN_REFRESH,
max_items,
))
}
#[tokio::test]
async fn a_value_inside_the_ttl_is_served_without_loading() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let loads = Arc::new(AtomicU64::new(0));
for _ in 0..3 {
let counter = Arc::clone(&loads);
let hit = cache
.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
Ok(7)
})
.await
.unwrap();
assert_eq!(*hit.value, 7);
}
assert_eq!(loads.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn a_refresh_is_declined_under_the_floor_and_honoured_past_it() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let loads = Arc::new(AtomicU64::new(0));
let load = || {
let counter = Arc::clone(&loads);
move || async move {
counter.fetch_add(1, Ordering::SeqCst);
Ok(1)
}
};
cache.get(&1, false, load()).await.unwrap();
clock.advance(Duration::from_secs(5));
let under = cache.get(&1, true, load()).await.unwrap();
assert!(under.cached, "the floor declines the refresh");
clock.advance(CAMPFIRE_INDEX_MIN_REFRESH);
let past = cache.get(&1, true, load()).await.unwrap();
assert!(!past.cached, "past the floor the source is re-read");
assert_eq!(loads.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn a_value_past_the_ttl_is_loaded_again() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
cache.get(&1, false, || async { Ok(1) }).await.unwrap();
clock.advance(CAMPFIRE_INDEX_TTL);
assert!(cache.peek(&1).is_none());
let hit = cache.get(&1, false, || async { Ok(2) }).await.unwrap();
assert_eq!(*hit.value, 2);
}
#[tokio::test]
async fn a_failed_load_leaves_the_previous_value_in_place() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
cache.get(&1, false, || async { Ok(1) }).await.unwrap();
clock.advance(CAMPFIRE_INDEX_MIN_REFRESH);
let failed = cache
.get(&1, true, || async { Err(Error::usage("nope")) })
.await;
assert!(failed.is_err());
let still_there = cache.peek(&1).expect("the old snapshot survives");
assert_eq!(*still_there.value, 1);
}
#[tokio::test]
async fn the_bound_evicts_the_oldest_fetched_entry_first() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 2);
cache.get(&1, false, || async { Ok(1) }).await.unwrap();
clock.advance(Duration::from_secs(1));
cache.get(&2, false, || async { Ok(2) }).await.unwrap();
clock.advance(Duration::from_secs(1));
cache.get(&3, false, || async { Ok(3) }).await.unwrap();
assert!(cache.peek(&1).is_none(), "the oldest went first");
assert!(cache.peek(&2).is_some());
assert!(cache.peek(&3).is_some());
}
#[tokio::test]
async fn expired_entries_are_swept_at_the_next_publication() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
cache.get(&1, false, || async { Ok(1) }).await.unwrap();
clock.advance(CAMPFIRE_INDEX_TTL);
cache.get(&2, false, || async { Ok(2) }).await.unwrap();
let state = cache.lock();
assert_eq!(state.entries.len(), 1, "the expired key was swept");
assert!(state.entries.contains_key(&2));
}
#[tokio::test]
async fn concurrent_callers_share_one_load() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let loads = Arc::new(AtomicU64::new(0));
let (release, held) = tokio::sync::oneshot::channel::<()>();
let first = {
let counter = Arc::clone(&loads);
cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
let _ = held.await;
Ok(9)
})
};
let second = {
let counter = Arc::clone(&loads);
cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
Ok(0)
})
};
let releaser = async {
tokio::task::yield_now().await;
let _ = release.send(());
};
let (first, second, ()) = futures_util::join!(first, second, releaser);
assert_eq!(*first.unwrap().value, 9);
let second = second.unwrap();
assert_eq!(*second.value, 9, "the waiter shares the loaded value");
assert!(
!second.cached,
"and reads it as fresh, not as a prior snapshot"
);
assert_eq!(loads.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn one_failed_load_is_one_failure_shared_by_every_waiter() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let loads = Arc::new(AtomicU64::new(0));
let (release, held) = tokio::sync::oneshot::channel::<()>();
let first = {
let counter = Arc::clone(&loads);
cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
let _ = held.await;
Err(Error::new(ErrorCode::Forbidden, "no").with_status(403))
})
};
let second = {
let counter = Arc::clone(&loads);
cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
Ok(0)
})
};
let releaser = async {
tokio::task::yield_now().await;
let _ = release.send(());
};
let (first, second, ()) = futures_util::join!(first, second, releaser);
for outcome in [first, second] {
let error = outcome.err().expect("the shared load failed");
assert_eq!(error.code(), ErrorCode::Forbidden);
assert_eq!(error.http_status(), Some(403));
}
assert_eq!(loads.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn a_load_every_caller_dropped_leaves_no_slot_behind() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let (_release, held) = tokio::sync::oneshot::channel::<()>();
let abandoned = cache.get(&1, false, move || async move {
let _ = held.await;
Ok(1)
});
assert!(abandoned.now_or_never().is_none());
assert_eq!(
cache.lock().inflight.len(),
1,
"the map still holds the slot"
);
cache.get(&2, false, || async { Ok(2) }).await.unwrap();
let state = cache.lock();
assert!(!state.inflight.contains_key(&1));
assert!(state.inflight.is_empty());
}
#[tokio::test]
async fn a_live_load_is_not_swept_out_from_under_its_waiter() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let (release, held) = tokio::sync::oneshot::channel::<()>();
let waiting = cache.get(&1, false, move || async move {
let _ = held.await;
Ok(1)
});
let other = cache.get(&2, false, || async { Ok(2) });
let releaser = async {
tokio::task::yield_now().await;
let _ = release.send(());
};
let (waiting, other, ()) = futures_util::join!(waiting, other, releaser);
assert_eq!(*waiting.unwrap().value, 1);
assert_eq!(*other.unwrap().value, 2);
}
#[tokio::test]
async fn a_shared_failure_reaches_every_caller_with_nothing_classifiable_lost() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let (release, held) = tokio::sync::oneshot::channel::<()>();
let first = cache.get(&1, false, move || async move {
let _ = held.await;
Err(Error::network_timeout(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"the listing stalled",
))
.with_status(504)
.with_request_id("req-1"))
});
let second = cache.get(&1, false, || async { Ok(0) });
let releaser = async {
tokio::task::yield_now().await;
let _ = release.send(());
};
let (first, second, ()) = futures_util::join!(first, second, releaser);
for outcome in [first, second] {
let error = outcome.err().expect("the shared load failed");
assert!(error.is_timeout(), "{error}");
assert!(error.is_retryable());
assert_eq!(error.code(), ErrorCode::Network);
assert_eq!(error.http_status(), Some(504));
assert_eq!(error.request_id(), Some("req-1"));
assert!(error.hint().is_some());
}
}
#[tokio::test]
async fn a_deadline_that_ended_the_load_is_shared_and_never_re_run_per_waiter() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let loads = Arc::new(AtomicU64::new(0));
let (release, held) = tokio::sync::oneshot::channel::<()>();
let starter = {
let counter = Arc::clone(&loads);
cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
let _ = held.await;
Err(Error::deadline_exceeded(Duration::from_millis(1)))
})
};
let waiters: Vec<_> = (0..3)
.map(|_| {
let counter = Arc::clone(&loads);
cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
Ok(7)
})
})
.collect();
let releaser = async {
tokio::task::yield_now().await;
let _ = release.send(());
};
let (starter, waiters, ()) =
futures_util::join!(starter, futures_util::future::join_all(waiters), releaser);
for outcome in std::iter::once(starter).chain(waiters) {
let error = outcome.err().expect("the shared load failed");
assert!(error.is_deadline_exceeded(), "{error}");
}
assert_eq!(
loads.load(Ordering::SeqCst),
1,
"one load, one failure, four callers"
);
}
#[tokio::test]
async fn a_transport_timeout_is_shared_too_and_never_re_run_per_waiter() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let loads = Arc::new(AtomicU64::new(0));
let (release, held) = tokio::sync::oneshot::channel::<()>();
let starter = {
let counter = Arc::clone(&loads);
cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
let _ = held.await;
Err(Error::network_timeout(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"stalled",
)))
})
};
let waiter = {
let counter = Arc::clone(&loads);
cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
Ok(7)
})
};
let releaser = async {
tokio::task::yield_now().await;
let _ = release.send(());
};
let (starter, waiter, ()) = futures_util::join!(starter, waiter, releaser);
assert!(starter.err().expect("the load timed out").is_timeout());
assert!(waiter.err().expect("the waiter shares it").is_timeout());
assert_eq!(loads.load(Ordering::SeqCst), 1, "one load, one failure");
}
#[tokio::test]
async fn a_load_that_panics_releases_its_key_and_the_next_caller_is_served() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let panicked = cache
.get(&1, false, || async { panic!("a hook exploded") })
.await;
let error = panicked
.err()
.expect("a panicking loader is a failure, not a hang");
assert_eq!(error.code(), ErrorCode::ApiError);
assert!(
cache.lock().inflight.is_empty(),
"publication still ran, so the key is free"
);
let after = cache.get(&1, false, || async { Ok(5) }).await.unwrap();
assert_eq!(*after.value, 5);
}
#[tokio::test]
async fn a_load_every_caller_abandoned_is_dropped_and_the_next_caller_is_served() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let loads = Arc::new(AtomicU64::new(0));
let (release, held) = tokio::sync::oneshot::channel::<()>();
let counter = Arc::clone(&loads);
let abandoned = cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
let _ = held.await;
Ok(11)
});
assert!(abandoned.now_or_never().is_none());
let _ = release.send(());
assert!(
cache
.lock()
.inflight
.get(&1)
.and_then(|registered| registered.slot.upgrade())
.is_none(),
"the abandoned load was dropped, not left running"
);
let later = cache.get(&1, false, || async { Ok(99) }).await.unwrap();
assert_eq!(*later.value, 99);
assert_eq!(
loads.load(Ordering::SeqCst),
1,
"the abandoned load never finished"
);
assert!(cache.lock().inflight.is_empty());
}
#[tokio::test]
async fn a_publication_retires_only_its_own_registration() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let (release, held) = tokio::sync::oneshot::channel::<()>();
let mut live = Box::pin(cache.get(&1, false, move || async move {
let _ = held.await;
Ok(7)
}));
assert!(futures_util::poll!(live.as_mut()).is_pending());
let registered = cache.lock().inflight.get(&1).map(|entry| entry.id);
assert!(registered.is_some(), "the live load is registered");
let stale = cache.publish(&1, registered.unwrap_or_default() + 1, Ok(99));
assert!(stale.is_ok());
assert_eq!(
cache.lock().inflight.get(&1).map(|entry| entry.id),
registered,
"the live load kept its slot"
);
let _ = release.send(());
assert_eq!(*live.await.unwrap().value, 7);
assert!(
cache.lock().inflight.is_empty(),
"its own publication did retire it"
);
}
#[tokio::test]
async fn a_caller_still_waiting_keeps_the_load_alive_when_its_starter_leaves() {
let clock = TestClock::new();
let cache = cache::<i64>(&clock, 16);
let loads = Arc::new(AtomicU64::new(0));
let (release, held) = tokio::sync::oneshot::channel::<()>();
let counter = Arc::clone(&loads);
let mut starter = Box::pin(cache.get(&1, false, move || async move {
counter.fetch_add(1, Ordering::SeqCst);
let _ = held.await;
Ok(11)
}));
assert!(futures_util::poll!(starter.as_mut()).is_pending());
let mut second = Box::pin(cache.get(&1, false, || async { Ok(99) }));
assert!(futures_util::poll!(second.as_mut()).is_pending());
drop(starter);
let releaser = async {
tokio::task::yield_now().await;
let _ = release.send(());
};
let (joined, ()) = futures_util::join!(second, releaser);
assert_eq!(*joined.unwrap().value, 11);
assert_eq!(loads.load(Ordering::SeqCst), 1, "no second load");
}
#[test]
fn a_room_url_names_the_campfire_it_ends_in() {
for (url, id) in [
(
"https://3.basecampapi.com/195539477/buckets/2085958600/chats/1069479600.json",
Some(1_069_479_600),
),
("/buckets/7/chats/42", Some(42)),
("/chats/42.json", Some(42)),
("chats/42", Some(42)),
("https://x.test/9/buckets/7/chats/42.json?a=1#b", Some(42)),
("https://x.test/9/buckets/7/chats/42/lines.json", None),
("https://x.test/9/buckets/7/chats/42/lines/5.json", None),
("https://x.test/9/buckets/7/todos/42.json", None),
("/buckets/7/chats/", None),
("/buckets/7/chats/abc.json", None),
("/buckets/7/chats/0.json", None),
("/buckets/7/chats/99999999999999999999.json", None),
("/buckets/7/mychats/42.json", None),
("", None),
] {
assert_eq!(campfire_id_from_room_url(url), id, "{url:?}");
}
}
#[test]
fn the_listing_overflow_marker_survives_the_cache_projection() {
let overflow = Arc::new(listing_overflow());
assert!(is_listing_overflow(&overflow));
assert!(is_listing_overflow(&project(&overflow)));
assert!(!is_listing_overflow(&Error::usage("something else")));
}
#[test]
fn the_marker_cannot_be_forged_from_anything_the_wire_carries() {
let forged = Error::new(ErrorCode::AuthRequired, "invalid_grant")
.with_hint(ListingOverflow.to_string());
assert!(!is_listing_overflow(&forged));
assert!(!is_listing_overflow(&project(&Arc::new(forged))));
}
}