Skip to main content

yah_object_store/
lib.rs

1//! Object-store trait (put/get/head/delete/list_prefix + conditional `put_if`)
2//! shared by scryer's long-tier Parquet shard storage, the cloud reconciler's
3//! R2 mirror publish, turso-backup's WAL→R2 sink, and the `yah cloud bucket`
4//! CLI + data-tab bucket viewer.
5//!
6//! Lifted from `scryer::long_tier` in R498-F1. `R2ObjectStore` landed in F2.
7//! `put_if` / `etag` (linearizable compare-and-swap on a single object) added
8//! for the W243 global tenant→cell pointer — see `.yah/docs/working/
9//! W243-multi-cell-tenant-mobility.md`.
10//!
11//! @yah:ticket(R498-F1, "lift ObjectStore trait + InMemoryObjectStore into crates/yah/object-store/")
12//! @yah:at(2026-06-09T03:37:49Z)
13//! @yah:status(review)
14//! @yah:parent(R498)
15//! @yah:handoff("Lifted ObjectStore trait + InMemoryObjectStore from scryer::long_tier into new crates/yah/object-store/ crate (yah-object-store package, yah_object_store lib). Trait gained head() with default impl over get(), and delete() (idempotent). Generic Error enum (NotFound/Io/Auth/Backend) replaces the old LongTierError::ObjectStore(String) error path. scryer/long_tier.rs now does pub use yah_object_store::{Error as ObjectStoreError, InMemoryObjectStore, ObjectStore} — every existing call site keeps working unchanged. LongTierError gained #[from] ObjectStoreError variant. cargo check --workspace exit 0; 5/5 object-store unit tests pass. NOTE: scryer's full lib test target was already broken on main (pre-existing missing-.await calls in adapters/journald.rs, adapters/containerd_logs.rs, service.rs — touching 20+ sites) — those are NOT introduced by F1; isolated long_tier tests cannot be run until that gets cleaned up separately.")
16
17pub mod http_ro;
18pub mod r2;
19
20pub use http_ro::HttpReadOnlyObjectStore;
21pub use r2::{ObjectMeta, R2ObjectStore};
22
23/// Re-exported so a caller choosing a directive for
24/// [`ObjectStore::put_cached`] never has to retype the string — two publishers
25/// spelling `no-cache, max-age=0` slightly differently is a difference no test
26/// catches and every CDN honours.
27pub use local_driver::s3_sign::{CACHE_CONTROL_IMMUTABLE, CACHE_CONTROL_NO_CACHE};
28
29use std::collections::HashMap;
30use std::sync::Mutex;
31
32use sha2::{Digest, Sha256};
33use thiserror::Error;
34
35/// Errors a backend may raise.
36///
37/// Variants are deliberately coarse — a backend reports the failure mode
38/// it can plausibly recover or message about, not every wire-level detail.
39#[derive(Debug, Error)]
40pub enum Error {
41    /// The key does not exist (read-side miss). `put` never raises this.
42    #[error("not found: {0}")]
43    NotFound(String),
44
45    /// A conditional write's precondition was not met (S3/R2 `412`). The
46    /// compare-and-swap lost the race: the object changed (or appeared, or
47    /// vanished) since the comparand was read. Re-read and retry. Only
48    /// [`ObjectStore::put_if`] raises this.
49    #[error("precondition failed: {0}")]
50    PreconditionFailed(String),
51
52    /// Network / IO / protocol error from a remote backend.
53    #[error("io: {0}")]
54    Io(String),
55
56    /// Authentication / authorization failure (e.g. SigV4 rejected).
57    #[error("auth: {0}")]
58    Auth(String),
59
60    /// Backend-specific error the caller doesn't need to discriminate.
61    #[error("backend: {0}")]
62    Backend(String),
63}
64
65/// Precondition for a conditional write ([`ObjectStore::put_if`]).
66///
67/// Maps onto S3/R2 conditional-write headers so a caller can perform a
68/// linearizable compare-and-swap on a single object — e.g. the global
69/// tenant→cell pointer in W243 — without any external lock or consensus.
70#[derive(Debug, Clone)]
71pub enum Precondition {
72    /// Write only if no object exists at the key yet (create-only).
73    /// Wire form: `If-None-Match: *`. Fails with [`Error::PreconditionFailed`]
74    /// if any object already exists at the key.
75    IfAbsent,
76
77    /// Write only if the current object's ETag equals this value (optimistic
78    /// concurrency). Wire form: `If-Match: <etag>`. Fails with
79    /// [`Error::PreconditionFailed`] if the stored ETag differs or the key is
80    /// absent. The comparand is an ETag returned by a prior [`ObjectStore::put_if`]
81    /// or [`ObjectStore::etag`].
82    IfMatch(String),
83}
84
85/// Minimal synchronous object-store surface.
86///
87/// Production impls connect to R2 / MinIO via AWS Sig V4. Tests inject
88/// [`InMemoryObjectStore`] so no network is required.
89///
90/// All methods are synchronous; async backends should block_on internally or
91/// expose a separate async trait alongside this one if the consumer is in
92/// a tokio context. (Scryer's long-tier rollover runs on a blocking thread.)
93pub trait ObjectStore: Send + Sync {
94    /// Write `data` at `key`. Overwrites any existing object unconditionally.
95    ///
96    /// Sets no `Cache-Control`. For an object a browser or CDN will re-read —
97    /// anything at a fixed, mutable key — reach for
98    /// [`put_cached`](ObjectStore::put_cached) instead.
99    fn put(&self, key: &str, data: Vec<u8>) -> Result<(), Error>;
100
101    /// Write `data` at `key` with an explicit `Cache-Control` (R703-B8).
102    ///
103    /// Every CLI-driven publish went through [`put`](ObjectStore::put), which
104    /// sets no cache directive at all — so `yah-desktop/latest.json`, the object
105    /// the Tauri updater polls forever, shipped with nothing telling a client
106    /// how long it may hold it. `.github/workflows/release.yml` has always
107    /// tagged the same objects correctly, which is why the CI-published
108    /// manifests answer `no-cache, max-age=0` and the CLI-published ones do not.
109    /// Use [`CACHE_CONTROL_IMMUTABLE`] for versioned, content-addressed keys and
110    /// [`CACHE_CONTROL_NO_CACHE`] for mutable pointers.
111    ///
112    /// The default impl **fails** rather than falling back to `put`, for the
113    /// same reason [`put_if`](ObjectStore::put_if) does: a backend that cannot
114    /// set the header must not report success as though it had. A caller that
115    /// only wants best-effort can call `put` explicitly and mean it.
116    fn put_cached(&self, _key: &str, _data: Vec<u8>, _cache_control: &str) -> Result<(), Error> {
117        Err(Error::Backend(
118            "cache-control on put (put_cached) not supported by this backend".into(),
119        ))
120    }
121
122    /// Read bytes at `key`. Returns `None` when the key does not exist —
123    /// `NotFound` is reserved for ambiguous cases (HEAD-then-GET race etc.).
124    fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error>;
125
126    /// Returns true when `key` exists. Cheaper than `get` for backends that
127    /// support HEAD; the default impl falls back to `get(...).is_some()`.
128    fn head(&self, key: &str) -> Result<bool, Error> {
129        Ok(self.get(key)?.is_some())
130    }
131
132    /// Remove `key`. Idempotent — succeeds whether or not the key existed.
133    fn delete(&self, key: &str) -> Result<(), Error>;
134
135    /// List all keys with the given prefix (prefix-match, not glob).
136    fn list_prefix(&self, prefix: &str) -> Result<Vec<String>, Error>;
137
138    /// Conditionally write `data` at `key`, returning the resulting ETag.
139    ///
140    /// An atomic compare-and-swap against `cond`. On a failed precondition the
141    /// store is left untouched and [`Error::PreconditionFailed`] is returned —
142    /// the caller re-reads ([`etag`](ObjectStore::etag)) and retries. The
143    /// returned ETag is the comparand for the next [`Precondition::IfMatch`] in
144    /// a CAS chain, so a single writer can advance a pointer without re-reading.
145    ///
146    /// The default impl returns [`Error::Backend`]: a backend that cannot offer
147    /// an atomic conditional write must **not** silently emulate it with
148    /// `get`-then-`put` — that would break the linearizability callers depend on
149    /// (W243's cross-cell pointer fence). Backends that support it override this.
150    fn put_if(&self, _key: &str, _data: Vec<u8>, _cond: Precondition) -> Result<String, Error> {
151        Err(Error::Backend(
152            "conditional put (put_if) not supported by this backend".into(),
153        ))
154    }
155
156    /// Current ETag of `key`, or `None` if absent.
157    ///
158    /// The comparand a caller reads before a [`Precondition::IfMatch`] CAS. The
159    /// default impl returns [`Error::Backend`]; backends supporting `put_if`
160    /// override it.
161    fn etag(&self, _key: &str) -> Result<Option<String>, Error> {
162        Err(Error::Backend("etag not supported by this backend".into()))
163    }
164}
165
166/// ETag for an object's bytes. S3/R2 return the quoted hex MD5 of the body for
167/// a single-part PUT; the in-memory double uses a quoted hex SHA-256 instead —
168/// the exact digest is opaque to callers, only equality across reads matters.
169fn etag_of(data: &[u8]) -> String {
170    let mut h = Sha256::new();
171    h.update(data);
172    format!("\"{}\"", hex::encode(h.finalize()))
173}
174
175/// In-memory object store for tests and local development.
176///
177/// Thread-safe; all ops hold a `Mutex` for the minimum duration. `put_if` holds
178/// the lock across the read+write so the compare-and-swap is genuinely atomic,
179/// matching R2's server-side conditional-write semantics.
180pub struct InMemoryObjectStore {
181    /// key → (bytes, etag). The etag is recomputed on every write.
182    objects: Mutex<HashMap<String, (Vec<u8>, String)>>,
183    /// key → `Cache-Control`, for the keys written through
184    /// [`ObjectStore::put_cached`] (R703-B8). Kept beside `objects` rather than
185    /// widening its tuple so the CAS paths stay untouched. Recorded at all so a
186    /// publish path can be *tested* for its cache directives — the bug this
187    /// exists for shipped precisely because nothing could assert on them.
188    cache_control: Mutex<HashMap<String, String>>,
189}
190
191impl Default for InMemoryObjectStore {
192    fn default() -> Self {
193        Self::new()
194    }
195}
196
197impl InMemoryObjectStore {
198    pub fn new() -> Self {
199        Self {
200            objects: Mutex::new(HashMap::new()),
201            cache_control: Mutex::new(HashMap::new()),
202        }
203    }
204
205    /// Returns true when `key` exists (test helper — synchronous, no Result).
206    pub fn contains_key(&self, key: &str) -> bool {
207        self.objects.lock().unwrap().contains_key(key)
208    }
209
210    /// Keys currently stored (test helper).
211    pub fn keys(&self) -> Vec<String> {
212        self.objects.lock().unwrap().keys().cloned().collect()
213    }
214
215    /// `Cache-Control` the last write to `key` carried, or `None` if it was
216    /// written through plain [`ObjectStore::put`] (test helper).
217    pub fn cache_control(&self, key: &str) -> Option<String> {
218        self.cache_control.lock().unwrap().get(key).cloned()
219    }
220}
221
222impl ObjectStore for InMemoryObjectStore {
223    fn put(&self, key: &str, data: Vec<u8>) -> Result<(), Error> {
224        let etag = etag_of(&data);
225        self.objects.lock().unwrap().insert(key.to_string(), (data, etag));
226        // An unqualified put clears any directive a prior write set: the object
227        // was replaced, and leaving the old header recorded would let a test
228        // pass on a `Cache-Control` the real store would no longer be sending.
229        self.cache_control.lock().unwrap().remove(key);
230        Ok(())
231    }
232
233    fn put_cached(&self, key: &str, data: Vec<u8>, cache_control: &str) -> Result<(), Error> {
234        self.put(key, data)?;
235        self.cache_control
236            .lock()
237            .unwrap()
238            .insert(key.to_string(), cache_control.to_string());
239        Ok(())
240    }
241
242    fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
243        Ok(self.objects.lock().unwrap().get(key).map(|(d, _)| d.clone()))
244    }
245
246    fn delete(&self, key: &str) -> Result<(), Error> {
247        self.objects.lock().unwrap().remove(key);
248        Ok(())
249    }
250
251    fn list_prefix(&self, prefix: &str) -> Result<Vec<String>, Error> {
252        let g = self.objects.lock().unwrap();
253        Ok(g.keys().filter(|k| k.starts_with(prefix)).cloned().collect())
254    }
255
256    fn etag(&self, key: &str) -> Result<Option<String>, Error> {
257        Ok(self.objects.lock().unwrap().get(key).map(|(_, e)| e.clone()))
258    }
259
260    fn put_if(&self, key: &str, data: Vec<u8>, cond: Precondition) -> Result<String, Error> {
261        // One lock across check-then-write = atomic CAS.
262        let mut g = self.objects.lock().unwrap();
263        match (&cond, g.get(key)) {
264            (Precondition::IfAbsent, Some(_)) => {
265                return Err(Error::PreconditionFailed(format!(
266                    "IfAbsent: {key} already exists"
267                )));
268            }
269            (Precondition::IfAbsent, None) => {}
270            (Precondition::IfMatch(want), Some((_, have))) if have == want => {}
271            (Precondition::IfMatch(want), Some((_, have))) => {
272                return Err(Error::PreconditionFailed(format!(
273                    "IfMatch {want} != current {have} for {key}"
274                )));
275            }
276            (Precondition::IfMatch(want), None) => {
277                return Err(Error::PreconditionFailed(format!(
278                    "IfMatch {want}: {key} absent"
279                )));
280            }
281        }
282        let etag = etag_of(&data);
283        g.insert(key.to_string(), (data, etag.clone()));
284        Ok(etag)
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    #[test]
293    fn put_get_round_trip() {
294        let s = InMemoryObjectStore::new();
295        s.put("k", b"v".to_vec()).unwrap();
296        assert_eq!(s.get("k").unwrap().as_deref(), Some(&b"v"[..]));
297    }
298
299    #[test]
300    fn get_missing_returns_none() {
301        let s = InMemoryObjectStore::new();
302        assert!(s.get("absent").unwrap().is_none());
303    }
304
305    // ── Cache-Control on put (R703-B8) ──────────────────────────────────────
306
307    #[test]
308    fn put_cached_stores_the_bytes_and_the_directive() {
309        let s = InMemoryObjectStore::new();
310        s.put_cached("yah-desktop/latest.json", b"{}".to_vec(), CACHE_CONTROL_NO_CACHE)
311            .unwrap();
312        assert_eq!(
313            s.get("yah-desktop/latest.json").unwrap().as_deref(),
314            Some(&b"{}"[..])
315        );
316        assert_eq!(
317            s.cache_control("yah-desktop/latest.json").as_deref(),
318            Some("no-cache, max-age=0")
319        );
320    }
321
322    /// A plain `put` records no directive — that IS the bug this ticket names,
323    /// so it has to stay visible rather than be papered over with a default.
324    #[test]
325    fn a_plain_put_records_no_cache_control() {
326        let s = InMemoryObjectStore::new();
327        s.put("k", b"v".to_vec()).unwrap();
328        assert_eq!(s.cache_control("k"), None);
329    }
330
331    /// Overwriting a cached object with a plain `put` must not leave the old
332    /// directive behind: the real store would now be serving those bytes with
333    /// no header, and a test asserting otherwise would be asserting a fiction.
334    #[test]
335    fn a_plain_put_clears_a_previously_set_directive() {
336        let s = InMemoryObjectStore::new();
337        s.put_cached("k", b"a".to_vec(), CACHE_CONTROL_IMMUTABLE).unwrap();
338        assert!(s.cache_control("k").is_some());
339        s.put("k", b"b".to_vec()).unwrap();
340        assert_eq!(s.cache_control("k"), None);
341    }
342
343    /// The two directives are shared constants precisely so two publishers
344    /// cannot spell them differently — a difference no test catches and every
345    /// CDN honours. Pinned against what `.github/workflows/release.yml` sends.
346    #[test]
347    fn the_shared_directives_match_what_ci_publishes() {
348        assert_eq!(CACHE_CONTROL_IMMUTABLE, "public, max-age=31536000, immutable");
349        assert_eq!(CACHE_CONTROL_NO_CACHE, "no-cache, max-age=0");
350    }
351
352    /// A backend that cannot set the header must FAIL rather than silently
353    /// falling back to a directive-less `put` — reporting success for a write
354    /// that did not carry the header is the exact shape of the original bug.
355    #[test]
356    fn a_backend_without_cache_control_support_refuses_rather_than_lying() {
357        struct Bare;
358        impl ObjectStore for Bare {
359            fn put(&self, _k: &str, _d: Vec<u8>) -> Result<(), Error> {
360                Ok(())
361            }
362            fn get(&self, _k: &str) -> Result<Option<Vec<u8>>, Error> {
363                Ok(None)
364            }
365            fn delete(&self, _k: &str) -> Result<(), Error> {
366                Ok(())
367            }
368            fn list_prefix(&self, _p: &str) -> Result<Vec<String>, Error> {
369                Ok(vec![])
370            }
371        }
372        let err = Bare
373            .put_cached("k", b"v".to_vec(), CACHE_CONTROL_NO_CACHE)
374            .unwrap_err();
375        assert!(matches!(err, Error::Backend(_)), "got {err:?}");
376        assert!(err.to_string().contains("put_cached"), "{err}");
377    }
378
379    #[test]
380    fn head_reflects_presence() {
381        let s = InMemoryObjectStore::new();
382        assert!(!s.head("k").unwrap());
383        s.put("k", b"v".to_vec()).unwrap();
384        assert!(s.head("k").unwrap());
385    }
386
387    #[test]
388    fn delete_is_idempotent() {
389        let s = InMemoryObjectStore::new();
390        s.delete("absent").unwrap();
391        s.put("k", b"v".to_vec()).unwrap();
392        s.delete("k").unwrap();
393        assert!(!s.head("k").unwrap());
394        s.delete("k").unwrap();
395    }
396
397    #[test]
398    fn list_prefix_filters() {
399        let s = InMemoryObjectStore::new();
400        s.put("a/1", vec![]).unwrap();
401        s.put("a/2", vec![]).unwrap();
402        s.put("b/1", vec![]).unwrap();
403        let mut got = s.list_prefix("a/").unwrap();
404        got.sort();
405        assert_eq!(got, vec!["a/1".to_string(), "a/2".to_string()]);
406    }
407
408    #[test]
409    fn etag_is_none_when_absent_some_after_write() {
410        let s = InMemoryObjectStore::new();
411        assert!(s.etag("k").unwrap().is_none());
412        s.put("k", b"v".to_vec()).unwrap();
413        let e = s.etag("k").unwrap();
414        assert!(e.is_some());
415        // Same bytes via the plain `put` path produce the same etag.
416        assert_eq!(e, Some(etag_of(b"v")));
417    }
418
419    #[test]
420    fn put_if_absent_creates_then_refuses_overwrite() {
421        let s = InMemoryObjectStore::new();
422        let e1 = s.put_if("p", b"gen1".to_vec(), Precondition::IfAbsent).unwrap();
423        assert_eq!(s.get("p").unwrap().as_deref(), Some(&b"gen1"[..]));
424        assert_eq!(s.etag("p").unwrap().as_deref(), Some(e1.as_str()));
425
426        // A second create-only write must lose — object already exists.
427        let err = s
428            .put_if("p", b"gen2".to_vec(), Precondition::IfAbsent)
429            .unwrap_err();
430        assert!(matches!(err, Error::PreconditionFailed(_)), "got {err:?}");
431        // Untouched.
432        assert_eq!(s.get("p").unwrap().as_deref(), Some(&b"gen1"[..]));
433    }
434
435    #[test]
436    fn put_if_match_drives_a_cas_chain() {
437        // Models the W243 global tenant→cell pointer: each generation bump is an
438        // IfMatch CAS against the prior etag.
439        let s = InMemoryObjectStore::new();
440        let e1 = s.put_if("ptr", b"cell=US,gen=1".to_vec(), Precondition::IfAbsent).unwrap();
441
442        let e2 = s
443            .put_if("ptr", b"cell=EU,gen=2".to_vec(), Precondition::IfMatch(e1.clone()))
444            .unwrap();
445        assert_ne!(e1, e2);
446        assert_eq!(s.get("ptr").unwrap().as_deref(), Some(&b"cell=EU,gen=2"[..]));
447
448        // A stale comparand (e1) must now bounce.
449        let err = s
450            .put_if("ptr", b"cell=US,gen=3".to_vec(), Precondition::IfMatch(e1))
451            .unwrap_err();
452        assert!(matches!(err, Error::PreconditionFailed(_)), "got {err:?}");
453        assert_eq!(s.get("ptr").unwrap().as_deref(), Some(&b"cell=EU,gen=2"[..]));
454
455        // The fresh comparand (e2) wins.
456        s.put_if("ptr", b"cell=US,gen=3".to_vec(), Precondition::IfMatch(e2)).unwrap();
457        assert_eq!(s.get("ptr").unwrap().as_deref(), Some(&b"cell=US,gen=3"[..]));
458    }
459
460    #[test]
461    fn put_if_match_two_writers_only_one_wins() {
462        // The cross-cell fence in miniature: source + target both read the same
463        // pointer etag; exactly one IfMatch may succeed.
464        let s = InMemoryObjectStore::new();
465        let shared = s.put_if("ptr", b"v0".to_vec(), Precondition::IfAbsent).unwrap();
466
467        let a = s.put_if("ptr", b"from-A".to_vec(), Precondition::IfMatch(shared.clone()));
468        let b = s.put_if("ptr", b"from-B".to_vec(), Precondition::IfMatch(shared));
469        assert!(a.is_ok(), "first writer should win: {a:?}");
470        assert!(
471            matches!(b, Err(Error::PreconditionFailed(_))),
472            "second writer must lose: {b:?}"
473        );
474        assert_eq!(s.get("ptr").unwrap().as_deref(), Some(&b"from-A"[..]));
475    }
476
477    #[test]
478    fn put_if_match_absent_key_fails() {
479        let s = InMemoryObjectStore::new();
480        let err = s
481            .put_if("nope", b"x".to_vec(), Precondition::IfMatch("\"whatever\"".into()))
482            .unwrap_err();
483        assert!(matches!(err, Error::PreconditionFailed(_)), "got {err:?}");
484        assert!(!s.contains_key("nope"));
485    }
486
487    /// A backend that implements only the required methods inherits the default
488    /// `put_if`/`etag` — they must report unsupported rather than silently
489    /// emulating a non-atomic CAS. Guards the non-breaking default-impl contract.
490    struct MinimalStore;
491    impl ObjectStore for MinimalStore {
492        fn put(&self, _k: &str, _d: Vec<u8>) -> Result<(), Error> {
493            Ok(())
494        }
495        fn get(&self, _k: &str) -> Result<Option<Vec<u8>>, Error> {
496            Ok(None)
497        }
498        fn delete(&self, _k: &str) -> Result<(), Error> {
499            Ok(())
500        }
501        fn list_prefix(&self, _p: &str) -> Result<Vec<String>, Error> {
502            Ok(vec![])
503        }
504    }
505
506    #[test]
507    fn default_conditional_methods_report_unsupported() {
508        let s = MinimalStore;
509        assert!(matches!(
510            s.put_if("k", vec![], Precondition::IfAbsent),
511            Err(Error::Backend(_))
512        ));
513        assert!(matches!(s.etag("k"), Err(Error::Backend(_))));
514    }
515}