Skip to main content

lean_ctx_cloud/tasks/
reads.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Task reads shared by every process of this Instance (owner 09.11.: Cloud
3//! takes large request volumes and does not block at the first limit).
4//!
5//! Cloud counts task reads per Instance (600 per 15 min). Thirteen Queens,
6//! their workers, the relay catch-up and the sync each used to ask on their
7//! own, every one a new process, so one busy hour used the budget up and
8//! every caller got 429. Now:
9//!
10//! - A list or task younger than [`READ_TTL`] is answered from
11//!   `<data>/cloud/task-reads.json` (0600) without a request.
12//! - One fetch per list or task at a time (single flight): callers that
13//!   arrive while it runs wait for it under a file lock and take its answer.
14//! - A 429 holds every task read of this Instance until its `Retry-After`
15//!   (or [`DEFAULT_HOLD`]); meanwhile, and when Cloud is not reachable, the
16//!   last good answer is served marked [`Stale`] with its age. Without one
17//!   the caller gets [`CloudError::RateLimited`] with the seconds left, never
18//!   "not found".
19//! - A change of this machine (claim, update, verify, propose…) or a task
20//!   event from Cloud outdates the vault's entries (`outdate`).
21
22use 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";
34/// An answer younger than this is served without a request.
35pub const READ_TTL: Duration = Duration::from_secs(15);
36/// How long a 429 without `Retry-After` holds task reads.
37pub const DEFAULT_HOLD: Duration = Duration::from_secs(60);
38/// The longest hold one 429 sets (a wrong header never parks reads longer).
39const MAX_HOLD: Duration = Duration::from_mins(15);
40/// How long a caller waits for a fetch of the same entry already running.
41const FLIGHT_WAIT: Duration = Duration::from_secs(7);
42/// Entries older than this are dropped when the file is written.
43const KEEP: Duration = Duration::from_hours(24);
44
45/// Flight locks are spread over this many files (`task-fetch-<n>.lock`),
46/// so they do not grow with every list query and task number read.
47const FLIGHT_SLOTS: u64 = 64;
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
50struct Stamped {
51    /// When the fetch that brought the answer started: Cloud may have built
52    /// it from any state since then.
53    at: UtcDateTime,
54    /// A change after `at` (this machine's write, a task event).
55    #[serde(default)]
56    outdated: bool,
57    value: serde_json::Value,
58}
59
60#[derive(Debug, Clone, Default, Serialize, Deserialize)]
61struct Reads {
62    /// Cloud URL → until when it refuses task reads of this Instance (429).
63    #[serde(default)]
64    holds: BTreeMap<String, UtcDateTime>,
65    /// Vault id → when a change last outdated its answers: an answer whose
66    /// fetch started before that is not current, also one stored after the
67    /// change by a fetch that was already running.
68    #[serde(default)]
69    outdated_at: BTreeMap<String, UtcDateTime>,
70    /// Vault id → entry key (`list?state=open`, `task#376`) → answer.
71    #[serde(default)]
72    vaults: BTreeMap<String, BTreeMap<String, Stamped>>,
73}
74
75/// Why an answer is not current.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
77pub struct Stale {
78    /// Seconds since Cloud sent it.
79    pub age_s: u64,
80    /// `rate_limited` (Cloud holds task reads) or `unavailable` (not reachable).
81    pub reason: &'static str,
82    /// Seconds until Cloud takes task reads again (`rate_limited`).
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub retry_after_s: Option<u64>,
85}
86
87/// An answer and, when it is not current, why.
88#[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
103/// The value of a current answer; a stale one is the error it stands in
104/// for (rate limited with the seconds left, or Cloud not reachable), for
105/// callers that must not act on old task state.
106pub 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    /// One line for people: `stale: Cloud's answer from 40s ago (rate
125    /// limited, reads again in 320s)`.
126    #[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
149/// Change the file under its lock; never around a request.
150fn 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
172/// Outdate every answer kept for `vault_id`, and every answer a fetch
173/// running now stores later: the next read asks Cloud. Written even when
174/// nothing is kept yet, since a first fetch may be running.
175pub(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
188/// Seconds until Cloud at `cloud` takes task reads again, `None` when it does.
189fn 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
202/// Current: not outdated, its fetch started after the vault's last change
203/// (`outdated_at`) and less than [`READ_TTL`] ago.
204fn 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
215/// The kept answer for `key`, served stale for `reason`.
216fn 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
233/// The flight lock's name for one entry: one of [`FLIGHT_SLOTS`] fixed
234/// names (`task-fetch-<n>`), so the lock files stay bounded. Two entries
235/// that share a slot only take turns; each still checks its own answer.
236fn 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
243/// The answer for `key` of `vault_id`: kept and fresh, else fetched once
244/// for every caller of this Instance, else (429, Cloud not reachable) the
245/// last good one marked stale. `cloud` (the Cloud URL) scopes a 429 hold to
246/// the Cloud that sent it.
247pub(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    // One fetch per entry: a caller arriving while it runs waits for it
285    // and takes its answer. A fetch that outlives the wait is not waited
286    // for longer: the caller serves the kept answer or asks itself.
287    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    // Stamped with the start: a change while the request runs (another
297    // process claims, `outdate`) leaves the stored answer not current.
298    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
345/// Seconds until Cloud at `cloud` takes this Instance's task reads again
346/// (`None`: now).
347pub 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        // Aged past the TTL, or outdated by a change: asked again.
394        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        // While the hold lasts nothing is asked, for any entry of the Instance.
456        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    /// Review 5!246 #6: the flight locks are a bounded set of plain file
511    /// names, not one file per list query or task number.
512    #[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    /// Review 5!246 #3: a change while a fetch runs (another process
540    /// claims) leaves the answer that fetch stores not current: the next
541    /// read asks Cloud instead of serving it for the TTL.
542    #[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            // Another process writes and outdates the vault meanwhile.
547            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        // A fetch that starts after the change is current again.
566        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    /// Review 5!246 #4: `tasks::list`/`show` (and the relay catch-up) take
574    /// only a current answer; a stale one is the error it stands in for,
575    /// never task state from before a claim or close.
576    #[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    /// Review 5!246 #7: a 429 of one Cloud does not hold reads of another.
617    #[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}