1use std::collections::BTreeMap;
23use std::path::Path;
24use std::time::Duration;
25
26use lean_ctx_time::UtcDateTime;
27use serde::de::DeserializeOwned;
28use serde::{Deserialize, Serialize};
29
30use crate::CloudError;
31use crate::state::{load_or_quarantine, lock_state, lock_state_within, write_private};
32
33const READS_FILE: &str = "task-reads.json";
34pub const READ_TTL: Duration = Duration::from_secs(15);
36pub const DEFAULT_HOLD: Duration = Duration::from_secs(60);
38const MAX_HOLD: Duration = Duration::from_mins(15);
40const FLIGHT_WAIT: Duration = Duration::from_secs(7);
42const KEEP: Duration = Duration::from_hours(24);
44
45const FLIGHT_SLOTS: u64 = 64;
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
50struct Stamped {
51 at: UtcDateTime,
54 #[serde(default)]
56 outdated: bool,
57 value: serde_json::Value,
58}
59
60#[derive(Debug, Clone, Default, Serialize, Deserialize)]
61struct Reads {
62 #[serde(default)]
64 holds: BTreeMap<String, UtcDateTime>,
65 #[serde(default)]
69 outdated_at: BTreeMap<String, UtcDateTime>,
70 #[serde(default)]
72 vaults: BTreeMap<String, BTreeMap<String, Stamped>>,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
77pub struct Stale {
78 pub age_s: u64,
80 pub reason: &'static str,
82 #[serde(skip_serializing_if = "Option::is_none")]
84 pub retry_after_s: Option<u64>,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct Read<T> {
90 pub value: T,
91 pub stale: Option<Stale>,
92}
93
94impl<T> Read<T> {
95 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Read<U> {
96 Read {
97 value: f(self.value),
98 stale: self.stale,
99 }
100 }
101}
102
103pub fn current<T>(read: Read<T>) -> Result<T, CloudError> {
107 match read.stale {
108 None => Ok(read.value),
109 Some(Stale {
110 reason: "rate_limited",
111 retry_after_s,
112 ..
113 }) => Err(CloudError::RateLimited {
114 retry_after: retry_after_s,
115 }),
116 Some(stale) => Err(CloudError::Offline(format!(
117 "LeanCTX Cloud not reachable; the last task answer is {}s old",
118 stale.age_s
119 ))),
120 }
121}
122
123impl Stale {
124 #[must_use]
127 pub fn note(&self) -> String {
128 let why = match (self.reason, self.retry_after_s) {
129 ("rate_limited", Some(s)) => format!("rate limited, reads again in {s}s"),
130 ("rate_limited", None) => "rate limited".to_string(),
131 _ => "LeanCTX Cloud not reachable".to_string(),
132 };
133 format!(
134 "stale: LeanCTX Cloud's answer from {}s ago ({why})",
135 self.age_s
136 )
137 }
138}
139
140fn load(data_dir: &Path) -> Reads {
141 load_or_quarantine(&data_dir.join(READS_FILE), |_: &Reads| true)
142 .unwrap_or_else(|error| {
143 tracing::warn!("cloud task reads: {error}");
144 None
145 })
146 .unwrap_or_default()
147}
148
149fn mutate(data_dir: &Path, change: impl FnOnce(&mut Reads)) {
151 let saved = lock_state(data_dir, READS_FILE).and_then(|_lock| {
152 let mut reads = load(data_dir);
153 change(&mut reads);
154 let keep = lean_ctx_time::Duration::from_std(KEEP)
155 .unwrap_or_else(|_| lean_ctx_time::Duration::days(1));
156 let oldest = UtcDateTime::now() - keep;
157 for entries in reads.vaults.values_mut() {
158 entries.retain(|_, e| e.at > oldest);
159 }
160 reads.vaults.retain(|_, entries| !entries.is_empty());
161 let now = UtcDateTime::now();
162 reads.outdated_at.retain(|_, at| *at > oldest);
163 reads.holds.retain(|_, until| *until > now);
164 let bytes = serde_json::to_vec(&reads).map_err(|e| CloudError::Local(e.to_string()))?;
165 write_private(data_dir, READS_FILE, &bytes)
166 });
167 if let Err(error) = saved {
168 tracing::debug!("cloud task reads not saved: {error}");
169 }
170}
171
172pub(crate) fn outdate(data_dir: &Path, vault_id: &str) {
176 mutate(data_dir, |reads| {
177 reads
178 .outdated_at
179 .insert(vault_id.to_string(), UtcDateTime::now());
180 if let Some(entries) = reads.vaults.get_mut(vault_id) {
181 for e in entries.values_mut() {
182 e.outdated = true;
183 }
184 }
185 });
186}
187
188fn held(reads: &Reads, cloud: &str, now: UtcDateTime) -> Option<u64> {
190 let until = *reads.holds.get(cloud)?;
191 (until > now).then(|| {
192 u64::try_from((until - now).num_seconds())
193 .unwrap_or(0)
194 .max(1)
195 })
196}
197
198fn age_s(entry: &Stamped, now: UtcDateTime) -> u64 {
199 u64::try_from((now - entry.at).num_seconds()).unwrap_or(0)
200}
201
202fn fresh(entry: &Stamped, outdated_at: Option<UtcDateTime>, now: UtcDateTime) -> bool {
205 !entry.outdated
206 && outdated_at.is_none_or(|changed| entry.at > changed)
207 && lean_ctx_time::Duration::from_std(READ_TTL).is_ok_and(|ttl| entry.at + ttl > now)
208 && entry.at <= now + lean_ctx_time::Duration::seconds(5)
209}
210
211fn decode<T: DeserializeOwned>(entry: &Stamped) -> Option<T> {
212 serde_json::from_value(entry.value.clone()).ok()
213}
214
215fn stale<T: DeserializeOwned>(
217 entry: Option<&Stamped>,
218 now: UtcDateTime,
219 reason: &'static str,
220 retry_after_s: Option<u64>,
221) -> Option<Read<T>> {
222 let entry = entry?;
223 Some(Read {
224 value: decode(entry)?,
225 stale: Some(Stale {
226 age_s: age_s(entry, now),
227 reason,
228 retry_after_s,
229 }),
230 })
231}
232
233fn flight(vault_id: &str, key: &str) -> String {
237 let digest = blake3::hash(format!("{vault_id}\n{key}").as_bytes());
238 let mut first = [0u8; 8];
239 first.copy_from_slice(&digest.as_bytes()[..8]);
240 format!("task-fetch-{}", u64::from_le_bytes(first) % FLIGHT_SLOTS)
241}
242
243pub(crate) fn read_through<T: Serialize + DeserializeOwned>(
248 data_dir: &Path,
249 cloud: &str,
250 vault_id: &str,
251 key: &str,
252 fetch: impl FnOnce() -> Result<T, CloudError>,
253) -> Result<Read<T>, CloudError> {
254 let lookup = |reads: &Reads| {
255 reads
256 .vaults
257 .get(vault_id)
258 .and_then(|entries| entries.get(key))
259 .cloned()
260 };
261 let current = |reads: &Reads, now| -> Option<Read<T>> {
262 let entry = lookup(reads)?;
263 fresh(&entry, reads.outdated_at.get(vault_id).copied(), now)
264 .then(|| decode(&entry))
265 .flatten()
266 .map(|value| Read { value, stale: None })
267 };
268 let held_answer = |reads: &Reads, now, left: u64| -> Result<Read<T>, CloudError> {
269 stale(lookup(reads).as_ref(), now, "rate_limited", Some(left)).ok_or(
270 CloudError::RateLimited {
271 retry_after: Some(left),
272 },
273 )
274 };
275
276 let reads = load(data_dir);
277 let now = UtcDateTime::now();
278 if let Some(answer) = current(&reads, now) {
279 return Ok(answer);
280 }
281 if let Some(left) = held(&reads, cloud, now) {
282 return held_answer(&reads, now, left);
283 }
284 let _flight = lock_state_within(data_dir, &flight(vault_id, key), FLIGHT_WAIT);
288 let reads = load(data_dir);
289 let now = UtcDateTime::now();
290 if let Some(answer) = current(&reads, now) {
291 return Ok(answer);
292 }
293 if let Some(left) = held(&reads, cloud, now) {
294 return held_answer(&reads, now, left);
295 }
296 let started = UtcDateTime::now();
299 match fetch() {
300 Ok(value) => {
301 if let Ok(json) = serde_json::to_value(&value) {
302 mutate(data_dir, |reads| {
303 reads
304 .vaults
305 .entry(vault_id.to_string())
306 .or_default()
307 .insert(
308 key.to_string(),
309 Stamped {
310 at: started,
311 outdated: false,
312 value: json,
313 },
314 );
315 });
316 }
317 Ok(Read { value, stale: None })
318 }
319 Err(CloudError::RateLimited { retry_after }) => {
320 let hold = retry_after
321 .map(Duration::from_secs)
322 .unwrap_or(DEFAULT_HOLD)
323 .clamp(Duration::from_secs(1), MAX_HOLD);
324 let until = UtcDateTime::now()
325 + lean_ctx_time::Duration::from_std(hold)
326 .unwrap_or_else(|_| lean_ctx_time::Duration::seconds(60));
327 mutate(data_dir, |reads| {
328 let hold = reads.holds.entry(cloud.to_string()).or_insert(until);
329 *hold = (*hold).max(until);
330 });
331 let left = hold.as_secs().max(1);
332 held_answer(&reads, UtcDateTime::now(), left)
333 }
334 Err(error) if error.is_transient() => stale(
335 lookup(&reads).as_ref(),
336 UtcDateTime::now(),
337 "unavailable",
338 None,
339 )
340 .ok_or(error),
341 Err(error) => Err(error),
342 }
343}
344
345pub fn hold_left(data_dir: &Path, cloud: &str) -> Option<u64> {
348 held(&load(data_dir), cloud, UtcDateTime::now())
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354 use std::sync::atomic::{AtomicUsize, Ordering};
355 use std::sync::{Arc, Barrier};
356
357 const CLOUD: &str = "https://cloud.example";
358
359 fn age(dir: &Path, vault: &str, key: &str, secs: i64) {
360 mutate(dir, |reads| {
361 let e = reads.vaults.get_mut(vault).unwrap().get_mut(key).unwrap();
362 e.at -= lean_ctx_time::Duration::seconds(secs);
363 });
364 }
365
366 #[test]
367 fn a_fresh_answer_is_served_without_a_request() {
368 let dir = tempfile::tempdir().unwrap();
369 let asked = AtomicUsize::new(0);
370 let fetch = || {
371 asked.fetch_add(1, Ordering::SeqCst);
372 Ok::<_, CloudError>(vec![1u64, 2])
373 };
374 let first = read_through(dir.path(), CLOUD, "vlt_a", "list", fetch).unwrap();
375 let second = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
376 asked.fetch_add(1, Ordering::SeqCst);
377 Ok::<_, CloudError>(vec![9u64])
378 })
379 .unwrap();
380 assert_eq!(first.value, vec![1, 2]);
381 assert_eq!(
382 second,
383 Read {
384 value: vec![1, 2],
385 stale: None
386 }
387 );
388 assert_eq!(
389 asked.load(Ordering::SeqCst),
390 1,
391 "the second read asked LeanCTX Cloud again"
392 );
393 age(dir.path(), "vlt_a", "list", 16);
395 read_through(dir.path(), CLOUD, "vlt_a", "list", || {
396 Ok::<_, CloudError>(vec![3u64])
397 })
398 .unwrap();
399 outdate(dir.path(), "vlt_a");
400 let after = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
401 Ok::<_, CloudError>(vec![4u64])
402 })
403 .unwrap();
404 assert_eq!(after.value, vec![4]);
405 }
406
407 #[test]
408 fn callers_at_the_same_time_share_one_request() {
409 let dir = Arc::new(tempfile::tempdir().unwrap());
410 let asked = Arc::new(AtomicUsize::new(0));
411 let start = Arc::new(Barrier::new(8));
412 let handles: Vec<_> = (0..8)
413 .map(|_| {
414 let (dir, asked, start) = (dir.clone(), asked.clone(), start.clone());
415 std::thread::spawn(move || {
416 start.wait();
417 read_through(dir.path(), CLOUD, "vlt_a", "list?state=open", || {
418 asked.fetch_add(1, Ordering::SeqCst);
419 std::thread::sleep(Duration::from_millis(300));
420 Ok::<_, CloudError>(vec![7u64])
421 })
422 .unwrap()
423 })
424 })
425 .collect();
426 for handle in handles {
427 assert_eq!(handle.join().unwrap().value, vec![7]);
428 }
429 assert_eq!(
430 asked.load(Ordering::SeqCst),
431 1,
432 "eight callers, one request"
433 );
434 }
435
436 #[test]
437 fn a_429_serves_the_last_good_answer_stale_and_holds_reads() {
438 let dir = tempfile::tempdir().unwrap();
439 read_through(dir.path(), CLOUD, "vlt_a", "task#376", || {
440 Ok::<_, CloudError>(376u64)
441 })
442 .unwrap();
443 age(dir.path(), "vlt_a", "task#376", 40);
444 let limited = read_through(dir.path(), CLOUD, "vlt_a", "task#376", || {
445 Err::<u64, _>(CloudError::RateLimited {
446 retry_after: Some(320),
447 })
448 })
449 .unwrap();
450 assert_eq!(limited.value, 376, "the last good answer, not an error");
451 let why = limited.stale.expect("marked stale");
452 assert_eq!(why.reason, "rate_limited");
453 assert!(why.age_s >= 40);
454 assert_eq!(why.retry_after_s, Some(320));
455 let asked = AtomicUsize::new(0);
457 let held = read_through(dir.path(), CLOUD, "vlt_b", "list", || {
458 asked.fetch_add(1, Ordering::SeqCst);
459 Ok::<_, CloudError>(1u64)
460 });
461 assert_eq!(asked.load(Ordering::SeqCst), 0);
462 match held {
463 Err(CloudError::RateLimited {
464 retry_after: Some(s),
465 }) => assert!((1..=320).contains(&s)),
466 other => panic!("expected rate limited, got {other:?}"),
467 }
468 assert!(hold_left(dir.path(), CLOUD).is_some());
469 }
470
471 #[test]
472 fn a_429_without_a_kept_answer_is_rate_limited_not_not_found() {
473 let dir = tempfile::tempdir().unwrap();
474 let answer = read_through(dir.path(), CLOUD, "vlt_a", "task#9", || {
475 Err::<u64, _>(CloudError::RateLimited { retry_after: None })
476 });
477 match answer {
478 Err(CloudError::RateLimited {
479 retry_after: Some(s),
480 }) => {
481 assert_eq!(s, DEFAULT_HOLD.as_secs());
482 }
483 other => panic!("expected rate limited, got {other:?}"),
484 }
485 let held = hold_left(dir.path(), CLOUD).expect("held");
486 assert!(held <= DEFAULT_HOLD.as_secs());
487 }
488
489 #[test]
490 fn cloud_not_reachable_serves_the_kept_answer_and_not_found_stays_an_error() {
491 let dir = tempfile::tempdir().unwrap();
492 read_through(dir.path(), CLOUD, "vlt_a", "list", || {
493 Ok::<_, CloudError>(5u64)
494 })
495 .unwrap();
496 age(dir.path(), "vlt_a", "list", 30);
497 let offline = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
498 Err::<u64, _>(CloudError::Offline("down".into()))
499 })
500 .unwrap();
501 assert_eq!(offline.value, 5);
502 assert_eq!(offline.stale.unwrap().reason, "unavailable");
503 let gone = read_through(dir.path(), CLOUD, "vlt_a", "task#1", || {
504 Err::<u64, _>(CloudError::NotFound)
505 });
506 assert!(matches!(gone, Err(CloudError::NotFound)));
507 assert_eq!(hold_left(dir.path(), CLOUD), None, "only a 429 holds reads");
508 }
509
510 #[test]
513 fn flight_lock_names_carry_no_path_characters_and_stay_bounded() {
514 let name = flight("vlt_a/../b", "list?state=open&priority=high");
515 assert!(
516 name.chars()
517 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
518 );
519 let names: std::collections::BTreeSet<String> = (0..5_000)
520 .map(|n| flight("vlt_a", &format!("task#{n}")))
521 .collect();
522 assert!(names.len() as u64 <= FLIGHT_SLOTS, "{}", names.len());
523 assert_eq!(flight("vlt_a", "task#1"), flight("vlt_a", "task#1"));
524 let dir = tempfile::tempdir().unwrap();
525 for n in 0..300u64 {
526 read_through(dir.path(), CLOUD, "vlt_a", &format!("task#{n}"), || {
527 Ok::<_, CloudError>(n)
528 })
529 .unwrap();
530 }
531 let locks = std::fs::read_dir(dir.path())
532 .unwrap()
533 .filter_map(Result::ok)
534 .filter(|e| e.file_name().to_string_lossy().starts_with("task-fetch-"))
535 .count();
536 assert!(locks as u64 <= FLIGHT_SLOTS, "{locks} lock files");
537 }
538
539 #[test]
543 fn an_outdate_during_a_fetch_is_not_lost() {
544 let dir = tempfile::tempdir().unwrap();
545 let during = read_through(dir.path(), CLOUD, "vlt_a", "task#5", || {
546 std::thread::sleep(Duration::from_millis(5));
548 outdate(dir.path(), "vlt_a");
549 Ok::<_, CloudError>("before the write".to_string())
550 })
551 .unwrap();
552 assert_eq!(during.value, "before the write");
553 let asked = AtomicUsize::new(0);
554 let next = read_through(dir.path(), CLOUD, "vlt_a", "task#5", || {
555 asked.fetch_add(1, Ordering::SeqCst);
556 Ok::<_, CloudError>("after the write".to_string())
557 })
558 .unwrap();
559 assert_eq!(
560 asked.load(Ordering::SeqCst),
561 1,
562 "served the pre-write answer"
563 );
564 assert_eq!(next.value, "after the write");
565 let cached = read_through(dir.path(), CLOUD, "vlt_a", "task#5", || {
567 Ok::<_, CloudError>("asked again".to_string())
568 })
569 .unwrap();
570 assert_eq!(cached.value, "after the write");
571 }
572
573 #[test]
577 fn a_stale_answer_is_not_current() {
578 let dir = tempfile::tempdir().unwrap();
579 read_through(dir.path(), CLOUD, "vlt_a", "list", || {
580 Ok::<_, CloudError>(1u64)
581 })
582 .unwrap();
583 outdate(dir.path(), "vlt_a");
584 let held = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
585 Err::<u64, _>(CloudError::RateLimited {
586 retry_after: Some(30),
587 })
588 })
589 .unwrap();
590 assert!(held.stale.is_some(), "the outdated answer is served stale");
591 match current(held) {
592 Err(CloudError::RateLimited {
593 retry_after: Some(30),
594 }) => {}
595 other => panic!("expected rate limited, got {other:?}"),
596 }
597 let offline = Read {
598 value: 1u64,
599 stale: Some(Stale {
600 age_s: 9,
601 reason: "unavailable",
602 retry_after_s: None,
603 }),
604 };
605 assert!(matches!(current(offline), Err(CloudError::Offline(_))));
606 assert_eq!(
607 current(Read {
608 value: 1u64,
609 stale: None
610 })
611 .unwrap(),
612 1
613 );
614 }
615
616 #[test]
618 fn a_hold_is_scoped_to_the_cloud_that_sent_it() {
619 let dir = tempfile::tempdir().unwrap();
620 let _ = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
621 Err::<u64, _>(CloudError::RateLimited {
622 retry_after: Some(300),
623 })
624 });
625 assert!(hold_left(dir.path(), CLOUD).is_some());
626 let other = "https://cloud.other.example";
627 assert_eq!(hold_left(dir.path(), other), None);
628 let answer = read_through(dir.path(), other, "vlt_b", "list", || {
629 Ok::<_, CloudError>(2u64)
630 })
631 .unwrap();
632 assert_eq!(answer.value, 2);
633 }
634}