Skip to main content

snapdir_stores/
b2_store.rs

1//! `B2Store`: the `b2://` storage backend, backed by Backblaze B2's
2//! **S3-compatible endpoint** via the native AWS SDK.
3//!
4//! Backblaze B2 exposes an S3-compatible API at a per-region endpoint of the
5//! form `https://s3.<region>.backblazeb2.com` (for example
6//! `https://s3.us-west-004.backblazeb2.com`). A [`B2Store`] is therefore just an
7//! [`S3Store`] pointed at that custom endpoint URL with path-style addressing,
8//! so it reuses the entire S3 transfer path — the same core-sharded
9//! `.objects`/`.manifests` keys, the same push (objects-before-manifest,
10//! skip-if-present) and fetch (download → verify BLAKE3 → retry → atomic write)
11//! discipline. This module adds only the `b2://` URL handling and the
12//! endpoint/region derivation; it does **not** duplicate the store logic.
13//!
14//! ```text
15//! b2://<bucket>/<prefix>/.objects/<sharded checksum>      raw object bytes
16//! b2://<bucket>/<prefix>/.manifests/<sharded snapshot id> manifest text
17//! ```
18//!
19//! # URL parsing (frozen contract)
20//!
21//! `b2://bucket/base/dir` parses exactly like `s3://...`
22//! (`_snapdir_export_store_vars`): the bucket is the segment after the `//`
23//! (`cut -d'/' -f3`) and the prefix is everything after it (`cut -d'/' -f4-`)
24//! with a trailing slash stripped (matching `_snapdir_b2_store_get_remote_prefix`).
25//! This reuses [`S3Location::parse`] verbatim, since the derivation is identical.
26//!
27//! # Credentials
28//!
29//! Authentication is delegated to the standard AWS credential chain (see
30//! [`S3Store`]). The Backblaze **application key id** maps to the AWS access key
31//! id and the **application key** maps to the AWS secret access key — i.e. the
32//! usual `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` env vars, a profile, etc.
33//! No bespoke snapdir credential variables are introduced. (The original
34//! implementation shelled out to the `b2` CLI and read `B2_APPLICATION_KEY[_ID]`;
35//! the native S3-compatible path uses the AWS chain instead, which is what the
36//! SDK expects.)
37//!
38//! # Endpoint / region derivation
39//!
40//! The S3-compatible endpoint encodes the B2 region. It is resolved, in order:
41//!
42//! 1. an explicit `endpoint_url` passed to [`B2Store::connect`];
43//! 2. the `SNAPDIR_B2_TEST_ENDPOINT` environment variable (used to point the
44//!    gated live test at a real bucket or an S3 emulator);
45//! 3. derived from a region — an explicit `region` argument, else the
46//!    `SNAPDIR_B2_REGION` / `AWS_REGION` env vars — as
47//!    `https://s3.<region>.backblazeb2.com`.
48//!
49//! When the endpoint is derived from a region the SDK is also told that region
50//! so `SigV4` signing matches Backblaze's expectation.
51
52use std::path::Path;
53
54use snapdir_core::manifest::Manifest;
55use snapdir_core::store::{Store, StoreError};
56
57use crate::s3_store::{S3Location, S3Store};
58
59/// The default Backblaze B2 region used when none is configured. Backblaze
60/// requires a region in the S3-compatible endpoint host; `us-west-004` is a
61/// common default, but a real deployment should set `SNAPDIR_B2_REGION` /
62/// `AWS_REGION` (or pass one explicitly) to match its bucket's region.
63const DEFAULT_B2_REGION: &str = "us-west-004";
64
65/// Builds the Backblaze S3-compatible endpoint URL for a region, i.e.
66/// `https://s3.<region>.backblazeb2.com`.
67#[must_use]
68pub fn endpoint_for_region(region: &str) -> String {
69    format!("https://s3.{region}.backblazeb2.com")
70}
71
72/// A content-addressable store backed by Backblaze B2 via its S3-compatible
73/// endpoint. Thin wrapper over [`S3Store`] configured with the B2 endpoint.
74pub struct B2Store {
75    inner: S3Store,
76}
77
78impl B2Store {
79    /// Connects to a `b2://bucket/prefix` store using Backblaze's
80    /// S3-compatible API.
81    ///
82    /// `endpoint_url` overrides the endpoint outright (handy for emulators or
83    /// an already-known regional host). When `None`, the endpoint is taken from
84    /// `SNAPDIR_B2_TEST_ENDPOINT`, and failing that derived from `region` (or
85    /// the `SNAPDIR_B2_REGION` / `AWS_REGION` env vars, else
86    /// [`DEFAULT_B2_REGION`]) as `https://s3.<region>.backblazeb2.com`.
87    ///
88    /// Credentials and signing are handled by the standard AWS chain; the B2
89    /// application key id/secret map to the AWS access-key/secret-key.
90    ///
91    /// # Errors
92    ///
93    /// [`StoreError::Backend`] if the tokio runtime cannot be created or the
94    /// AWS configuration cannot be loaded (propagated from [`S3Store::connect`]).
95    pub fn connect(
96        store_url: &str,
97        endpoint_url: Option<&str>,
98        region: Option<&str>,
99    ) -> Result<Self, StoreError> {
100        let endpoint = resolve_endpoint(endpoint_url, region);
101        // S3Store::connect parses the URL with S3Location::parse, which derives
102        // bucket/prefix identically for b2:// and s3:// (oracle cut -f3 / -f4-).
103        let inner = S3Store::connect(store_url, Some(endpoint.as_str()))?;
104        Ok(Self { inner })
105    }
106
107    /// Builds a `B2Store` from an already-configured [`S3Store`] (intended for
108    /// tests wiring a client at an emulator/B2 endpoint).
109    #[must_use]
110    pub fn from_s3_store(inner: S3Store) -> Self {
111        Self { inner }
112    }
113
114    /// The parsed bucket/prefix this store targets (shared with [`S3Store`]).
115    #[must_use]
116    pub fn location(&self) -> &S3Location {
117        self.inner.location()
118    }
119}
120
121impl Store for B2Store {
122    fn get_manifest(&self, id: &str) -> Result<Manifest, StoreError> {
123        self.inner.get_manifest(id)
124    }
125
126    fn fetch_files(&self, manifest: &Manifest, dest: &Path) -> Result<(), StoreError> {
127        self.inner.fetch_files(manifest, dest)
128    }
129
130    fn push(&self, manifest: &Manifest, source: &Path) -> Result<(), StoreError> {
131        self.inner.push(manifest, source)
132    }
133}
134
135/// Resolves the S3-compatible endpoint to use, applying the precedence
136/// documented on [`B2Store::connect`]: explicit endpoint > `SNAPDIR_B2_TEST_ENDPOINT`
137/// > endpoint derived from the resolved region.
138fn resolve_endpoint(endpoint_url: Option<&str>, region: Option<&str>) -> String {
139    if let Some(ep) = endpoint_url {
140        return ep.to_owned();
141    }
142    if let Ok(ep) = std::env::var("SNAPDIR_B2_TEST_ENDPOINT") {
143        if !ep.is_empty() {
144            return ep;
145        }
146    }
147    endpoint_for_region(&resolve_region(region))
148}
149
150/// Resolves the B2 region: an explicit argument, else `SNAPDIR_B2_REGION`, else
151/// `AWS_REGION`, else [`DEFAULT_B2_REGION`].
152fn resolve_region(region: Option<&str>) -> String {
153    if let Some(r) = region {
154        if !r.is_empty() {
155            return r.to_owned();
156        }
157    }
158    for var in ["SNAPDIR_B2_REGION", "AWS_REGION"] {
159        if let Ok(r) = std::env::var(var) {
160            if !r.is_empty() {
161                return r;
162            }
163        }
164    }
165    DEFAULT_B2_REGION.to_owned()
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    // The canonical content-addressable fixtures from the b2 store test suite.
173    const FOO_CHECKSUM: &str = "49dc870df1de7fd60794cebce449f5ccdae575affaa67a24b62acb03e039db92";
174    const FOO_SHARDED: &str = "49d/c87/0df/1de7fd60794cebce449f5ccdae575affaa67a24b62acb03e039db92";
175    const MANIFEST_ID: &str = "aa91e498f401ea9e6ddbaa1138a0dbeb030fab8defc1252d80c77ebefafbc70d";
176    const MANIFEST_SHARDED: &str =
177        "aa9/1e4/98f/401ea9e6ddbaa1138a0dbeb030fab8defc1252d80c77ebefafbc70d";
178
179    #[test]
180    fn b2_store_parses_bucket_and_prefix_like_oracle() {
181        // Oracle (`_snapdir_export_store_vars`): bucket = cut -f3,
182        // base_dir = cut -f4-. For "b2://my-bucket/my/directory".
183        let loc = S3Location::parse("b2://my-bucket/my/directory");
184        assert_eq!(loc.bucket, "my-bucket");
185        assert_eq!(loc.prefix, "my/directory");
186    }
187
188    #[test]
189    fn b2_store_parse_strips_trailing_slash() {
190        // `_snapdir_b2_store_get_remote_prefix` strips the trailing slash.
191        let loc = S3Location::parse("b2://bucket/long/term/storage/");
192        assert_eq!(loc.bucket, "bucket");
193        assert_eq!(loc.prefix, "long/term/storage");
194    }
195
196    #[test]
197    fn b2_store_parse_bucket_root_has_empty_prefix() {
198        let loc = S3Location::parse("b2://bucket");
199        assert_eq!(loc.bucket, "bucket");
200        assert_eq!(loc.prefix, "");
201
202        let loc_slash = S3Location::parse("b2://bucket/");
203        assert_eq!(loc_slash.bucket, "bucket");
204        assert_eq!(loc_slash.prefix, "");
205    }
206
207    #[test]
208    fn b2_store_object_key_matches_sharded_scheme() {
209        // Key layout must be byte-identical to the frozen S3 sharded scheme so
210        // the bucket is interchangeable across tools.
211        let loc = S3Location::parse("b2://b/long/term/storage");
212        assert_eq!(
213            loc.object_key(FOO_CHECKSUM),
214            format!("long/term/storage/.objects/{FOO_SHARDED}")
215        );
216    }
217
218    #[test]
219    fn b2_store_manifest_key_matches_sharded_scheme() {
220        let loc = S3Location::parse("b2://b/long/term/storage");
221        assert_eq!(
222            loc.manifest_key(MANIFEST_ID),
223            format!("long/term/storage/.manifests/{MANIFEST_SHARDED}")
224        );
225    }
226
227    #[test]
228    fn b2_store_keys_have_no_leading_slash_at_bucket_root() {
229        let loc = S3Location::parse("b2://bucket");
230        assert_eq!(
231            loc.object_key(FOO_CHECKSUM),
232            format!(".objects/{FOO_SHARDED}")
233        );
234        assert_eq!(
235            loc.manifest_key(MANIFEST_ID),
236            format!(".manifests/{MANIFEST_SHARDED}")
237        );
238    }
239
240    #[test]
241    fn b2_store_endpoint_for_region_uses_backblaze_host() {
242        assert_eq!(
243            endpoint_for_region("us-west-004"),
244            "https://s3.us-west-004.backblazeb2.com"
245        );
246        assert_eq!(
247            endpoint_for_region("eu-central-003"),
248            "https://s3.eu-central-003.backblazeb2.com"
249        );
250    }
251
252    #[test]
253    fn b2_store_explicit_endpoint_takes_precedence() {
254        let ep = resolve_endpoint(Some("https://emulator.local:9000"), Some("us-west-004"));
255        assert_eq!(ep, "https://emulator.local:9000");
256    }
257
258    #[test]
259    fn b2_store_endpoint_derived_from_explicit_region() {
260        // With no explicit endpoint and no SNAPDIR_B2_TEST_ENDPOINT set, the
261        // endpoint is derived from the explicit region argument.
262        std::env::remove_var("SNAPDIR_B2_TEST_ENDPOINT");
263        let ep = resolve_endpoint(None, Some("us-west-002"));
264        assert_eq!(ep, "https://s3.us-west-002.backblazeb2.com");
265    }
266
267    #[test]
268    fn b2_store_region_resolution_prefers_explicit_then_default() {
269        // Explicit region wins.
270        assert_eq!(resolve_region(Some("eu-central-003")), "eu-central-003");
271        // Empty explicit region falls through; with no env override set we get
272        // the documented default (guard the env to keep the test hermetic).
273        let saved_b2 = std::env::var("SNAPDIR_B2_REGION").ok();
274        let saved_aws = std::env::var("AWS_REGION").ok();
275        std::env::remove_var("SNAPDIR_B2_REGION");
276        std::env::remove_var("AWS_REGION");
277        assert_eq!(resolve_region(Some("")), DEFAULT_B2_REGION);
278        assert_eq!(resolve_region(None), DEFAULT_B2_REGION);
279        if let Some(v) = saved_b2 {
280            std::env::set_var("SNAPDIR_B2_REGION", v);
281        }
282        if let Some(v) = saved_aws {
283            std::env::set_var("AWS_REGION", v);
284        }
285    }
286
287    // --- Live round-trip, skipped by default --------------------------------
288    //
289    // Requires a Backblaze B2 (or S3-compatible) endpoint plus AWS credentials
290    // (the B2 application key id/secret as AWS access-key/secret-key) in the
291    // environment. Gated behind `SNAPDIR_B2_TEST_ENDPOINT` and
292    // `SNAPDIR_B2_TEST_STORE` (a `b2://bucket/prefix` URL) so it is skipped
293    // unless explicitly configured. Real Backblaze round-trips are exercised by
294    // the later `remote-interop` gate.
295    #[test]
296    fn b2_store_live_round_trip_when_configured() {
297        use snapdir_core::manifest::{ManifestEntry, PathType};
298        use snapdir_core::merkle::{Blake3Hasher, Hasher};
299
300        let (Ok(endpoint), Ok(store)) = (
301            std::env::var("SNAPDIR_B2_TEST_ENDPOINT"),
302            std::env::var("SNAPDIR_B2_TEST_STORE"),
303        ) else {
304            eprintln!(
305                "skipping b2_store live round-trip: set SNAPDIR_B2_TEST_ENDPOINT \
306                 and SNAPDIR_B2_TEST_STORE (b2://bucket/prefix) to run it"
307            );
308            return;
309        };
310
311        let hasher = Blake3Hasher::new();
312
313        let src = std::env::temp_dir().join(format!("snapdir-b2-live-{}", std::process::id()));
314        std::fs::create_dir_all(&src).unwrap();
315        std::fs::write(src.join("foo"), b"foo\n").unwrap();
316        let foo_sum = hasher.hash_hex(b"foo\n");
317        let root_sum = snapdir_core::merkle::directory_checksum([foo_sum.as_str()], &hasher);
318        let mut manifest = Manifest::new();
319        manifest.push(ManifestEntry::new(
320            PathType::Directory,
321            "700",
322            root_sum,
323            4,
324            "./",
325        ));
326        manifest.push(ManifestEntry::new(
327            PathType::File,
328            "600",
329            foo_sum,
330            4,
331            "./foo",
332        ));
333        let manifest = Manifest::from_entries(manifest.entries().to_vec());
334        let id = snapdir_core::merkle::snapshot_id(&manifest, &hasher);
335
336        let b2 = B2Store::connect(&store, Some(&endpoint), None).expect("connect");
337        b2.push(&manifest, &src).expect("push");
338        let read_back = b2.get_manifest(&id).expect("get_manifest");
339        assert_eq!(read_back, manifest);
340
341        let dest = std::env::temp_dir().join(format!("snapdir-b2-dest-{}", std::process::id()));
342        std::fs::create_dir_all(&dest).unwrap();
343        b2.fetch_files(&read_back, &dest).expect("fetch_files");
344        assert_eq!(std::fs::read(dest.join("foo")).unwrap(), b"foo\n");
345
346        let _ = std::fs::remove_dir_all(&src);
347        let _ = std::fs::remove_dir_all(&dest);
348    }
349}