objstore_r/lib.rs
1// Author: spicyzhug@gmail.com
2// Copyright: lituus-io, all rights reserved
3//
4//! # objstore-r
5//!
6//! Object stores with **generation preconditions**, for data that is published
7//! as immutable snapshots plus append-only segments (graph-r, link-r).
8//!
9//! Every object carries a *generation* (a `u64`, never zero) that changes on
10//! each write. Writes take a [`Cond`]:
11//!
12//! - [`Cond::CreateOnly`]: succeed only if the key does not exist. Immutable
13//! objects (snapshots, log segments) are written this way, so a retry after a
14//! lost response is harmless and a second writer can never clobber the first.
15//! - [`Cond::IfGeneration`]: succeed only if the object is still at that
16//! generation. A small `HEAD` object updated this way gives single-writer
17//! compare-and-swap across machines, with no lock service.
18//!
19//! ## Backends
20//!
21//! | Backend | Feature | Use |
22//! |---|---|---|
23//! | [`LocalDir`] | always | a directory; atomic rename, fsync, `File::lock` for conditions |
24//! | [`Mem`] | always | tests; deterministic, with scripted fault injection |
25//! | `Gcs` | `gcs` | Google Cloud Storage (JSON API), ADC tokens, retries, ranged reads |
26//!
27//! ## Design tenets
28//!
29//! - **Named futures, no boxing.** [`ObjectStore`] methods return associated
30//! future types (GATs), so callers compose them without `Box<dyn Future>`
31//! and without `Send`/`'static` bounds imposed by this crate. Futures are
32//! `Send` whenever the backend is, so multi-threaded runtimes work too.
33//! - **Enums over `dyn`.** Choose a backend at compile time, or wrap several in
34//! your own enum; nothing here needs a trait object.
35//! - **Zero-copy bodies.** Objects are [`bytes::Bytes`]; a body is read or
36//! written once and shared by reference count from there on.
37//! - **No unsafe code.**
38//!
39//! ## Content encoding
40//!
41//! Opt in per object with [`ObjectStore::put_encoded`] (feature `gzip`): the
42//! body is stored compressed and [`get`](ObjectStore::get) decodes it once
43//! into the returned buffer, bounded against decompression bombs; a ranged
44//! read of an encoded object is refused ([`Error::EncodedRange`]).
45//! [`ObjectStore::stat`] and [`ObjectStore::list_stat`] report the encoding.
46//! See [`encoding`].
47//!
48//! ## Example
49//!
50//! ```
51//! use objstore_r::{Cond, Mem, ObjectStore};
52//! # futures::executor::block_on(async {
53//! let store = Mem::default();
54//! let g1 = store.put("snap/0001", "v1".into(), Cond::CreateOnly).await?;
55//! assert!(store.put("snap/0001", "again".into(), Cond::CreateOnly).await.is_err());
56//! let head = store.put("HEAD", "0001".into(), Cond::None).await?;
57//! store.put("HEAD", "0002".into(), Cond::IfGeneration(head)).await?; // CAS
58//! assert_eq!(store.get("snap/0001").await?.unwrap().bytes, "v1");
59//! # let _ = g1;
60//! # Ok::<(), objstore_r::Error>(()) }).unwrap();
61//! ```
62
63#![cfg_attr(feature = "http", feature(impl_trait_in_assoc_type))]
64#![forbid(unsafe_code)]
65#![deny(missing_docs)]
66#![deny(missing_debug_implementations)]
67#![deny(rust_2018_idioms)]
68#![deny(unreachable_pub)]
69#![warn(clippy::all, clippy::pedantic, clippy::cargo)]
70#![allow(
71 clippy::module_name_repetitions,
72 clippy::missing_errors_doc,
73 clippy::missing_panics_doc,
74 clippy::multiple_crate_versions,
75 clippy::cast_possible_truncation
76)]
77
78pub mod encoding;
79pub mod error;
80pub mod fenced;
81pub mod join;
82pub mod key;
83pub mod local;
84pub mod mem;
85#[cfg(feature = "mirror")]
86pub mod mirror;
87pub mod net;
88pub mod sse;
89pub mod transport;
90
91#[cfg(feature = "gcs")]
92pub mod gcs;
93#[cfg(feature = "http")]
94pub mod http;
95#[cfg(feature = "http")]
96pub mod token;
97
98#[cfg(feature = "testing")]
99pub mod testing;
100
101use std::future::Future;
102use std::ops::Range;
103
104pub use bytes::Bytes;
105pub use encoding::{ContentEncoding, MAX_INFLATED_BYTES};
106pub use error::{Error, Result};
107pub use key::Key;
108pub use local::LocalDir;
109pub use mem::{Fault, Mem};
110
111#[cfg(feature = "gcs")]
112pub use gcs::{Gcs, GcsConfig};
113
114/// An object's content and generation.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct Object {
117 /// The whole body (shared, zero-copy).
118 pub bytes: Bytes,
119 /// The generation it was read at (never zero).
120 pub generation: u64,
121}
122
123/// A listed object.
124#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
125pub struct Meta {
126 /// The full key.
127 pub key: String,
128 /// Body size in bytes.
129 pub size: u64,
130 /// Current generation (never zero).
131 pub generation: u64,
132}
133
134/// [`Meta`] and the object's content encoding, from [`ObjectStore::stat`]
135/// and [`ObjectStore::list_stat`].
136#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
137pub struct Stat {
138 /// Key, generation, and the **stored** size (for an encoded object, the
139 /// encoded bytes).
140 pub meta: Meta,
141 /// How the stored bytes are encoded (`None`: as written).
142 pub content_encoding: Option<ContentEncoding>,
143}
144
145/// A write precondition.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
147pub enum Cond {
148 /// Write unconditionally (replace whatever is there).
149 #[default]
150 None,
151 /// Write only if no object exists under the key ([`Error::Conflict`] otherwise).
152 CreateOnly,
153 /// Write only if the object is at exactly this generation
154 /// ([`Error::PreconditionFailed`] otherwise, including when it does not exist).
155 IfGeneration(u64),
156}
157
158/// An object store with generation preconditions.
159///
160/// Keys are validated by [`Key::parse`]: `/`-separated segments of
161/// `[A-Za-z0-9._-]`, no empty segment, none starting with `.`, at most 1024 bytes.
162///
163/// Implementations must be linearizable per key: a successful conditional
164/// write is observed by every later read.
165pub trait ObjectStore {
166 /// Future of [`get`](ObjectStore::get).
167 type Get<'a>: Future<Output = Result<Option<Object>>> + 'a
168 where
169 Self: 'a;
170 /// Future of [`get_range`](ObjectStore::get_range).
171 type GetRange<'a>: Future<Output = Result<Bytes>> + 'a
172 where
173 Self: 'a;
174 /// Future of [`head`](ObjectStore::head).
175 type Head<'a>: Future<Output = Result<Option<Meta>>> + 'a
176 where
177 Self: 'a;
178 /// Future of [`put`](ObjectStore::put).
179 type Put<'a>: Future<Output = Result<u64>> + 'a
180 where
181 Self: 'a;
182 /// Future of [`list`](ObjectStore::list).
183 type List<'a>: Future<Output = Result<Vec<Meta>>> + 'a
184 where
185 Self: 'a;
186 /// Future of [`delete`](ObjectStore::delete).
187 type Delete<'a>: Future<Output = Result<()>> + 'a
188 where
189 Self: 'a;
190
191 /// The whole object, or `None` if it does not exist.
192 fn get<'a>(&'a self, key: &'a str) -> Self::Get<'a>;
193
194 /// Bytes `range` of the object. A range running past the end is clipped;
195 /// a range starting at or past the end is an empty body. A missing object
196 /// is [`Error::NotFound`].
197 fn get_range<'a>(&'a self, key: &'a str, range: Range<u64>) -> Self::GetRange<'a>;
198
199 /// Size and generation, without the body.
200 fn head<'a>(&'a self, key: &'a str) -> Self::Head<'a>;
201
202 /// Write `body` under `key` if `cond` holds; returns the new generation.
203 fn put<'a>(&'a self, key: &'a str, body: Bytes, cond: Cond) -> Self::Put<'a>;
204
205 /// Every object whose key starts with `prefix`, sorted by key. An empty
206 /// prefix lists everything; a non-empty prefix is validated like a key
207 /// (a trailing `/` is allowed).
208 fn list<'a>(&'a self, prefix: &'a str) -> Self::List<'a>;
209
210 /// Remove the object. Deleting a missing key succeeds.
211 fn delete<'a>(&'a self, key: &'a str) -> Self::Delete<'a>;
212
213 /// Like [`put`](ObjectStore::put), storing `body` compressed with
214 /// `encoding` and recording the encoding, so [`get`](ObjectStore::get)
215 /// returns `body` again and [`get_range`](ObjectStore::get_range) refuses
216 /// with [`Error::EncodedRange`]. Conditions behave exactly as for `put`.
217 ///
218 /// Every backend in this crate implements it (feature `gzip`). The
219 /// default, for stores that cannot record an encoding, refuses with
220 /// [`Error::UnsupportedEncoding`] and writes nothing.
221 fn put_encoded<'a>(
222 &'a self,
223 key: &'a str,
224 body: Bytes,
225 cond: Cond,
226 encoding: ContentEncoding,
227 ) -> impl Future<Output = Result<u64>> + 'a {
228 let _ = (key, body, cond);
229 std::future::ready(Err(Error::UnsupportedEncoding { encoding: encoding.as_str().into() }))
230 }
231
232 /// [`head`](ObjectStore::head) plus the content encoding. The default
233 /// reports none, which is exact for a store that cannot record one.
234 fn stat<'a>(&'a self, key: &'a str) -> impl Future<Output = Result<Option<Stat>>> + 'a {
235 let head = self.head(key);
236 async move { Ok(head.await?.map(|meta| Stat { meta, content_encoding: None })) }
237 }
238
239 /// [`list`](ObjectStore::list) plus each object's content encoding. The
240 /// default reports none, which is exact for a store that cannot record
241 /// one.
242 fn list_stat<'a>(&'a self, prefix: &'a str) -> impl Future<Output = Result<Vec<Stat>>> + 'a {
243 let list = self.list(prefix);
244 async move {
245 Ok(list.await?.into_iter().map(|meta| Stat { meta, content_encoding: None }).collect())
246 }
247 }
248}
249
250/// Clip `range` to an object of `len` bytes, as `get_range` specifies.
251pub(crate) fn clip(range: &Range<u64>, len: u64) -> Range<usize> {
252 let start = range.start.min(len);
253 let end = range.end.clamp(start, len);
254 start as usize..end as usize
255}