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