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            "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            _ => "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
146/// Change the file under its lock; never around a request.
147fn 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
169/// Outdate every answer kept for `vault_id`, and every answer a fetch
170/// running now stores later: the next read asks Cloud. Written even when
171/// nothing is kept yet, since a first fetch may be running.
172pub(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
185/// Seconds until Cloud at `cloud` takes task reads again, `None` when it does.
186fn 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
199/// Current: not outdated, its fetch started after the vault's last change
200/// (`outdated_at`) and less than [`READ_TTL`] ago.
201fn 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
212/// The kept answer for `key`, served stale for `reason`.
213fn 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
230/// The flight lock's name for one entry: one of [`FLIGHT_SLOTS`] fixed
231/// names (`task-fetch-<n>`), so the lock files stay bounded. Two entries
232/// that share a slot only take turns; each still checks its own answer.
233fn 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
240/// The answer for `key` of `vault_id`: kept and fresh, else fetched once
241/// for every caller of this Instance, else (429, Cloud not reachable) the
242/// last good one marked stale. `cloud` (the Cloud URL) scopes a 429 hold to
243/// the Cloud that sent it.
244pub(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    // One fetch per entry: a caller arriving while it runs waits for it
282    // and takes its answer. A fetch that outlives the wait is not waited
283    // for longer: the caller serves the kept answer or asks itself.
284    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    // Stamped with the start: a change while the request runs (another
294    // process claims, `outdate`) leaves the stored answer not current.
295    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
342/// Seconds until Cloud at `cloud` takes this Instance's task reads again
343/// (`None`: now).
344pub 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        // Aged past the TTL, or outdated by a change: asked again.
391        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        // While the hold lasts nothing is asked, for any entry of the Instance.
453        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    /// Review 5!246 #6: the flight locks are a bounded set of plain file
508    /// names, not one file per list query or task number.
509    #[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    /// Review 5!246 #3: a change while a fetch runs (another process
537    /// claims) leaves the answer that fetch stores not current: the next
538    /// read asks Cloud instead of serving it for the TTL.
539    #[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            // Another process writes and outdates the vault meanwhile.
544            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        // A fetch that starts after the change is current again.
563        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    /// Review 5!246 #4: `tasks::list`/`show` (and the relay catch-up) take
571    /// only a current answer; a stale one is the error it stands in for,
572    /// never task state from before a claim or close.
573    #[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    /// Review 5!246 #7: a 429 of one Cloud does not hold reads of another.
614    #[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}