use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;
use lean_ctx_time::UtcDateTime;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::CloudError;
use crate::state::{load_or_quarantine, lock_state, lock_state_within, write_private};
const READS_FILE: &str = "task-reads.json";
pub const READ_TTL: Duration = Duration::from_secs(15);
pub const DEFAULT_HOLD: Duration = Duration::from_secs(60);
const MAX_HOLD: Duration = Duration::from_mins(15);
const FLIGHT_WAIT: Duration = Duration::from_secs(7);
const KEEP: Duration = Duration::from_hours(24);
const FLIGHT_SLOTS: u64 = 64;
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Stamped {
at: UtcDateTime,
#[serde(default)]
outdated: bool,
value: serde_json::Value,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct Reads {
#[serde(default)]
holds: BTreeMap<String, UtcDateTime>,
#[serde(default)]
outdated_at: BTreeMap<String, UtcDateTime>,
#[serde(default)]
vaults: BTreeMap<String, BTreeMap<String, Stamped>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Stale {
pub age_s: u64,
pub reason: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
pub retry_after_s: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Read<T> {
pub value: T,
pub stale: Option<Stale>,
}
impl<T> Read<T> {
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Read<U> {
Read {
value: f(self.value),
stale: self.stale,
}
}
}
pub fn current<T>(read: Read<T>) -> Result<T, CloudError> {
match read.stale {
None => Ok(read.value),
Some(Stale {
reason: "rate_limited",
retry_after_s,
..
}) => Err(CloudError::RateLimited {
retry_after: retry_after_s,
}),
Some(stale) => Err(CloudError::Offline(format!(
"LeanCTX Cloud not reachable; the last task answer is {}s old",
stale.age_s
))),
}
}
impl Stale {
#[must_use]
pub fn note(&self) -> String {
let why = match (self.reason, self.retry_after_s) {
("rate_limited", Some(s)) => format!("rate limited, reads again in {s}s"),
("rate_limited", None) => "rate limited".to_string(),
_ => "LeanCTX Cloud not reachable".to_string(),
};
format!(
"stale: LeanCTX Cloud's answer from {}s ago ({why})",
self.age_s
)
}
}
fn load(data_dir: &Path) -> Reads {
load_or_quarantine(&data_dir.join(READS_FILE), |_: &Reads| true)
.unwrap_or_else(|error| {
tracing::warn!("cloud task reads: {error}");
None
})
.unwrap_or_default()
}
fn mutate(data_dir: &Path, change: impl FnOnce(&mut Reads)) {
let saved = lock_state(data_dir, READS_FILE).and_then(|_lock| {
let mut reads = load(data_dir);
change(&mut reads);
let keep = lean_ctx_time::Duration::from_std(KEEP)
.unwrap_or_else(|_| lean_ctx_time::Duration::days(1));
let oldest = UtcDateTime::now() - keep;
for entries in reads.vaults.values_mut() {
entries.retain(|_, e| e.at > oldest);
}
reads.vaults.retain(|_, entries| !entries.is_empty());
let now = UtcDateTime::now();
reads.outdated_at.retain(|_, at| *at > oldest);
reads.holds.retain(|_, until| *until > now);
let bytes = serde_json::to_vec(&reads).map_err(|e| CloudError::Local(e.to_string()))?;
write_private(data_dir, READS_FILE, &bytes)
});
if let Err(error) = saved {
tracing::debug!("cloud task reads not saved: {error}");
}
}
pub(crate) fn outdate(data_dir: &Path, vault_id: &str) {
mutate(data_dir, |reads| {
reads
.outdated_at
.insert(vault_id.to_string(), UtcDateTime::now());
if let Some(entries) = reads.vaults.get_mut(vault_id) {
for e in entries.values_mut() {
e.outdated = true;
}
}
});
}
fn held(reads: &Reads, cloud: &str, now: UtcDateTime) -> Option<u64> {
let until = *reads.holds.get(cloud)?;
(until > now).then(|| {
u64::try_from((until - now).num_seconds())
.unwrap_or(0)
.max(1)
})
}
fn age_s(entry: &Stamped, now: UtcDateTime) -> u64 {
u64::try_from((now - entry.at).num_seconds()).unwrap_or(0)
}
fn fresh(entry: &Stamped, outdated_at: Option<UtcDateTime>, now: UtcDateTime) -> bool {
!entry.outdated
&& outdated_at.is_none_or(|changed| entry.at > changed)
&& lean_ctx_time::Duration::from_std(READ_TTL).is_ok_and(|ttl| entry.at + ttl > now)
&& entry.at <= now + lean_ctx_time::Duration::seconds(5)
}
fn decode<T: DeserializeOwned>(entry: &Stamped) -> Option<T> {
serde_json::from_value(entry.value.clone()).ok()
}
fn stale<T: DeserializeOwned>(
entry: Option<&Stamped>,
now: UtcDateTime,
reason: &'static str,
retry_after_s: Option<u64>,
) -> Option<Read<T>> {
let entry = entry?;
Some(Read {
value: decode(entry)?,
stale: Some(Stale {
age_s: age_s(entry, now),
reason,
retry_after_s,
}),
})
}
fn flight(vault_id: &str, key: &str) -> String {
let digest = blake3::hash(format!("{vault_id}\n{key}").as_bytes());
let mut first = [0u8; 8];
first.copy_from_slice(&digest.as_bytes()[..8]);
format!("task-fetch-{}", u64::from_le_bytes(first) % FLIGHT_SLOTS)
}
pub(crate) fn read_through<T: Serialize + DeserializeOwned>(
data_dir: &Path,
cloud: &str,
vault_id: &str,
key: &str,
fetch: impl FnOnce() -> Result<T, CloudError>,
) -> Result<Read<T>, CloudError> {
let lookup = |reads: &Reads| {
reads
.vaults
.get(vault_id)
.and_then(|entries| entries.get(key))
.cloned()
};
let current = |reads: &Reads, now| -> Option<Read<T>> {
let entry = lookup(reads)?;
fresh(&entry, reads.outdated_at.get(vault_id).copied(), now)
.then(|| decode(&entry))
.flatten()
.map(|value| Read { value, stale: None })
};
let held_answer = |reads: &Reads, now, left: u64| -> Result<Read<T>, CloudError> {
stale(lookup(reads).as_ref(), now, "rate_limited", Some(left)).ok_or(
CloudError::RateLimited {
retry_after: Some(left),
},
)
};
let reads = load(data_dir);
let now = UtcDateTime::now();
if let Some(answer) = current(&reads, now) {
return Ok(answer);
}
if let Some(left) = held(&reads, cloud, now) {
return held_answer(&reads, now, left);
}
let _flight = lock_state_within(data_dir, &flight(vault_id, key), FLIGHT_WAIT);
let reads = load(data_dir);
let now = UtcDateTime::now();
if let Some(answer) = current(&reads, now) {
return Ok(answer);
}
if let Some(left) = held(&reads, cloud, now) {
return held_answer(&reads, now, left);
}
let started = UtcDateTime::now();
match fetch() {
Ok(value) => {
if let Ok(json) = serde_json::to_value(&value) {
mutate(data_dir, |reads| {
reads
.vaults
.entry(vault_id.to_string())
.or_default()
.insert(
key.to_string(),
Stamped {
at: started,
outdated: false,
value: json,
},
);
});
}
Ok(Read { value, stale: None })
}
Err(CloudError::RateLimited { retry_after }) => {
let hold = retry_after
.map(Duration::from_secs)
.unwrap_or(DEFAULT_HOLD)
.clamp(Duration::from_secs(1), MAX_HOLD);
let until = UtcDateTime::now()
+ lean_ctx_time::Duration::from_std(hold)
.unwrap_or_else(|_| lean_ctx_time::Duration::seconds(60));
mutate(data_dir, |reads| {
let hold = reads.holds.entry(cloud.to_string()).or_insert(until);
*hold = (*hold).max(until);
});
let left = hold.as_secs().max(1);
held_answer(&reads, UtcDateTime::now(), left)
}
Err(error) if error.is_transient() => stale(
lookup(&reads).as_ref(),
UtcDateTime::now(),
"unavailable",
None,
)
.ok_or(error),
Err(error) => Err(error),
}
}
pub fn hold_left(data_dir: &Path, cloud: &str) -> Option<u64> {
held(&load(data_dir), cloud, UtcDateTime::now())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Barrier};
const CLOUD: &str = "https://cloud.example";
fn age(dir: &Path, vault: &str, key: &str, secs: i64) {
mutate(dir, |reads| {
let e = reads.vaults.get_mut(vault).unwrap().get_mut(key).unwrap();
e.at -= lean_ctx_time::Duration::seconds(secs);
});
}
#[test]
fn a_fresh_answer_is_served_without_a_request() {
let dir = tempfile::tempdir().unwrap();
let asked = AtomicUsize::new(0);
let fetch = || {
asked.fetch_add(1, Ordering::SeqCst);
Ok::<_, CloudError>(vec![1u64, 2])
};
let first = read_through(dir.path(), CLOUD, "vlt_a", "list", fetch).unwrap();
let second = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
asked.fetch_add(1, Ordering::SeqCst);
Ok::<_, CloudError>(vec![9u64])
})
.unwrap();
assert_eq!(first.value, vec![1, 2]);
assert_eq!(
second,
Read {
value: vec![1, 2],
stale: None
}
);
assert_eq!(
asked.load(Ordering::SeqCst),
1,
"the second read asked LeanCTX Cloud again"
);
age(dir.path(), "vlt_a", "list", 16);
read_through(dir.path(), CLOUD, "vlt_a", "list", || {
Ok::<_, CloudError>(vec![3u64])
})
.unwrap();
outdate(dir.path(), "vlt_a");
let after = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
Ok::<_, CloudError>(vec![4u64])
})
.unwrap();
assert_eq!(after.value, vec![4]);
}
#[test]
fn callers_at_the_same_time_share_one_request() {
let dir = Arc::new(tempfile::tempdir().unwrap());
let asked = Arc::new(AtomicUsize::new(0));
let start = Arc::new(Barrier::new(8));
let handles: Vec<_> = (0..8)
.map(|_| {
let (dir, asked, start) = (dir.clone(), asked.clone(), start.clone());
std::thread::spawn(move || {
start.wait();
read_through(dir.path(), CLOUD, "vlt_a", "list?state=open", || {
asked.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(300));
Ok::<_, CloudError>(vec![7u64])
})
.unwrap()
})
})
.collect();
for handle in handles {
assert_eq!(handle.join().unwrap().value, vec![7]);
}
assert_eq!(
asked.load(Ordering::SeqCst),
1,
"eight callers, one request"
);
}
#[test]
fn a_429_serves_the_last_good_answer_stale_and_holds_reads() {
let dir = tempfile::tempdir().unwrap();
read_through(dir.path(), CLOUD, "vlt_a", "task#376", || {
Ok::<_, CloudError>(376u64)
})
.unwrap();
age(dir.path(), "vlt_a", "task#376", 40);
let limited = read_through(dir.path(), CLOUD, "vlt_a", "task#376", || {
Err::<u64, _>(CloudError::RateLimited {
retry_after: Some(320),
})
})
.unwrap();
assert_eq!(limited.value, 376, "the last good answer, not an error");
let why = limited.stale.expect("marked stale");
assert_eq!(why.reason, "rate_limited");
assert!(why.age_s >= 40);
assert_eq!(why.retry_after_s, Some(320));
let asked = AtomicUsize::new(0);
let held = read_through(dir.path(), CLOUD, "vlt_b", "list", || {
asked.fetch_add(1, Ordering::SeqCst);
Ok::<_, CloudError>(1u64)
});
assert_eq!(asked.load(Ordering::SeqCst), 0);
match held {
Err(CloudError::RateLimited {
retry_after: Some(s),
}) => assert!((1..=320).contains(&s)),
other => panic!("expected rate limited, got {other:?}"),
}
assert!(hold_left(dir.path(), CLOUD).is_some());
}
#[test]
fn a_429_without_a_kept_answer_is_rate_limited_not_not_found() {
let dir = tempfile::tempdir().unwrap();
let answer = read_through(dir.path(), CLOUD, "vlt_a", "task#9", || {
Err::<u64, _>(CloudError::RateLimited { retry_after: None })
});
match answer {
Err(CloudError::RateLimited {
retry_after: Some(s),
}) => {
assert_eq!(s, DEFAULT_HOLD.as_secs());
}
other => panic!("expected rate limited, got {other:?}"),
}
let held = hold_left(dir.path(), CLOUD).expect("held");
assert!(held <= DEFAULT_HOLD.as_secs());
}
#[test]
fn cloud_not_reachable_serves_the_kept_answer_and_not_found_stays_an_error() {
let dir = tempfile::tempdir().unwrap();
read_through(dir.path(), CLOUD, "vlt_a", "list", || {
Ok::<_, CloudError>(5u64)
})
.unwrap();
age(dir.path(), "vlt_a", "list", 30);
let offline = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
Err::<u64, _>(CloudError::Offline("down".into()))
})
.unwrap();
assert_eq!(offline.value, 5);
assert_eq!(offline.stale.unwrap().reason, "unavailable");
let gone = read_through(dir.path(), CLOUD, "vlt_a", "task#1", || {
Err::<u64, _>(CloudError::NotFound)
});
assert!(matches!(gone, Err(CloudError::NotFound)));
assert_eq!(hold_left(dir.path(), CLOUD), None, "only a 429 holds reads");
}
#[test]
fn flight_lock_names_carry_no_path_characters_and_stay_bounded() {
let name = flight("vlt_a/../b", "list?state=open&priority=high");
assert!(
name.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
);
let names: std::collections::BTreeSet<String> = (0..5_000)
.map(|n| flight("vlt_a", &format!("task#{n}")))
.collect();
assert!(names.len() as u64 <= FLIGHT_SLOTS, "{}", names.len());
assert_eq!(flight("vlt_a", "task#1"), flight("vlt_a", "task#1"));
let dir = tempfile::tempdir().unwrap();
for n in 0..300u64 {
read_through(dir.path(), CLOUD, "vlt_a", &format!("task#{n}"), || {
Ok::<_, CloudError>(n)
})
.unwrap();
}
let locks = std::fs::read_dir(dir.path())
.unwrap()
.filter_map(Result::ok)
.filter(|e| e.file_name().to_string_lossy().starts_with("task-fetch-"))
.count();
assert!(locks as u64 <= FLIGHT_SLOTS, "{locks} lock files");
}
#[test]
fn an_outdate_during_a_fetch_is_not_lost() {
let dir = tempfile::tempdir().unwrap();
let during = read_through(dir.path(), CLOUD, "vlt_a", "task#5", || {
std::thread::sleep(Duration::from_millis(5));
outdate(dir.path(), "vlt_a");
Ok::<_, CloudError>("before the write".to_string())
})
.unwrap();
assert_eq!(during.value, "before the write");
let asked = AtomicUsize::new(0);
let next = read_through(dir.path(), CLOUD, "vlt_a", "task#5", || {
asked.fetch_add(1, Ordering::SeqCst);
Ok::<_, CloudError>("after the write".to_string())
})
.unwrap();
assert_eq!(
asked.load(Ordering::SeqCst),
1,
"served the pre-write answer"
);
assert_eq!(next.value, "after the write");
let cached = read_through(dir.path(), CLOUD, "vlt_a", "task#5", || {
Ok::<_, CloudError>("asked again".to_string())
})
.unwrap();
assert_eq!(cached.value, "after the write");
}
#[test]
fn a_stale_answer_is_not_current() {
let dir = tempfile::tempdir().unwrap();
read_through(dir.path(), CLOUD, "vlt_a", "list", || {
Ok::<_, CloudError>(1u64)
})
.unwrap();
outdate(dir.path(), "vlt_a");
let held = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
Err::<u64, _>(CloudError::RateLimited {
retry_after: Some(30),
})
})
.unwrap();
assert!(held.stale.is_some(), "the outdated answer is served stale");
match current(held) {
Err(CloudError::RateLimited {
retry_after: Some(30),
}) => {}
other => panic!("expected rate limited, got {other:?}"),
}
let offline = Read {
value: 1u64,
stale: Some(Stale {
age_s: 9,
reason: "unavailable",
retry_after_s: None,
}),
};
assert!(matches!(current(offline), Err(CloudError::Offline(_))));
assert_eq!(
current(Read {
value: 1u64,
stale: None
})
.unwrap(),
1
);
}
#[test]
fn a_hold_is_scoped_to_the_cloud_that_sent_it() {
let dir = tempfile::tempdir().unwrap();
let _ = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
Err::<u64, _>(CloudError::RateLimited {
retry_after: Some(300),
})
});
assert!(hold_left(dir.path(), CLOUD).is_some());
let other = "https://cloud.other.example";
assert_eq!(hold_left(dir.path(), other), None);
let answer = read_through(dir.path(), other, "vlt_b", "list", || {
Ok::<_, CloudError>(2u64)
})
.unwrap();
assert_eq!(answer.value, 2);
}
}