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};
58use crate::transfer::TransferConfig;
59
60/// The default Backblaze B2 region used when none is configured. Backblaze
61/// requires a region in the S3-compatible endpoint host; `us-west-004` is a
62/// common default, but a real deployment should set `SNAPDIR_B2_REGION` /
63/// `AWS_REGION` (or pass one explicitly) to match its bucket's region.
64const DEFAULT_B2_REGION: &str = "us-west-004";
65
66/// Builds the Backblaze S3-compatible endpoint URL for a region, i.e.
67/// `https://s3.<region>.backblazeb2.com`.
68#[must_use]
69pub fn endpoint_for_region(region: &str) -> String {
70    format!("https://s3.{region}.backblazeb2.com")
71}
72
73/// A content-addressable store backed by Backblaze B2 via its S3-compatible
74/// endpoint. Thin wrapper over [`S3Store`] configured with the B2 endpoint.
75pub struct B2Store {
76    inner: S3Store,
77}
78
79impl B2Store {
80    /// Connects to a `b2://bucket/prefix` store using Backblaze's
81    /// S3-compatible API.
82    ///
83    /// `endpoint_url` overrides the endpoint outright (handy for emulators or
84    /// an already-known regional host). When `None`, the endpoint is taken from
85    /// `SNAPDIR_B2_TEST_ENDPOINT`, and failing that derived from `region` (or
86    /// the `SNAPDIR_B2_REGION` / `AWS_REGION` env vars, else
87    /// [`DEFAULT_B2_REGION`]) as `https://s3.<region>.backblazeb2.com`.
88    ///
89    /// Credentials and signing are handled by the standard AWS chain; the B2
90    /// application key id/secret map to the AWS access-key/secret-key.
91    ///
92    /// # Errors
93    ///
94    /// [`StoreError::Backend`] if the tokio runtime cannot be created or the
95    /// AWS configuration cannot be loaded (propagated from [`S3Store::connect`]).
96    pub fn connect(
97        store_url: &str,
98        endpoint_url: Option<&str>,
99        region: Option<&str>,
100    ) -> Result<Self, StoreError> {
101        Self::connect_with(store_url, endpoint_url, region, TransferConfig::default())
102    }
103
104    /// Like [`connect`](Self::connect), but carries a [`TransferConfig`] for
105    /// concurrency / bandwidth control. The config lives on the wrapped
106    /// [`S3Store`]; [`connect`](Self::connect) delegates here with
107    /// [`TransferConfig::default`].
108    ///
109    /// # Errors
110    ///
111    /// [`StoreError::Backend`] if the tokio runtime cannot be created or the
112    /// AWS configuration cannot be loaded (propagated from
113    /// [`S3Store::connect_with`]).
114    pub fn connect_with(
115        store_url: &str,
116        endpoint_url: Option<&str>,
117        region: Option<&str>,
118        config: TransferConfig,
119    ) -> Result<Self, StoreError> {
120        let endpoint = resolve_endpoint(endpoint_url, region);
121        // S3Store::connect parses the URL with S3Location::parse, which derives
122        // bucket/prefix identically for b2:// and s3:// (oracle cut -f3 / -f4-).
123        let inner = S3Store::connect_with(store_url, Some(endpoint.as_str()), config)?;
124        Ok(Self { inner })
125    }
126
127    /// Builds a `B2Store` from an already-configured [`S3Store`] (intended for
128    /// tests wiring a client at an emulator/B2 endpoint).
129    #[must_use]
130    pub fn from_s3_store(inner: S3Store) -> Self {
131        Self { inner }
132    }
133
134    /// The parsed bucket/prefix this store targets (shared with [`S3Store`]).
135    #[must_use]
136    pub fn location(&self) -> &S3Location {
137        self.inner.location()
138    }
139
140    /// The [`TransferConfig`] (concurrency / bandwidth) this store was built
141    /// with, carried on the wrapped [`S3Store`]. Consumed by the transfer loops
142    /// in later gates.
143    #[must_use]
144    pub fn transfer_config(&self) -> &TransferConfig {
145        self.inner.transfer_config()
146    }
147}
148
149impl Store for B2Store {
150    fn get_manifest(&self, id: &str) -> Result<Manifest, StoreError> {
151        self.inner.get_manifest(id)
152    }
153
154    fn fetch_files(&self, manifest: &Manifest, dest: &Path) -> Result<(), StoreError> {
155        self.inner.fetch_files(manifest, dest)
156    }
157
158    fn push(&self, manifest: &Manifest, source: &Path) -> Result<(), StoreError> {
159        self.inner.push(manifest, source)
160    }
161}
162
163/// Resolves the S3-compatible endpoint to use, applying the precedence
164/// documented on [`B2Store::connect`]: explicit endpoint > `SNAPDIR_B2_TEST_ENDPOINT`
165/// > endpoint derived from the resolved region.
166fn resolve_endpoint(endpoint_url: Option<&str>, region: Option<&str>) -> String {
167    if let Some(ep) = endpoint_url {
168        return ep.to_owned();
169    }
170    if let Ok(ep) = std::env::var("SNAPDIR_B2_TEST_ENDPOINT") {
171        if !ep.is_empty() {
172            return ep;
173        }
174    }
175    endpoint_for_region(&resolve_region(region))
176}
177
178/// Resolves the B2 region: an explicit argument, else `SNAPDIR_B2_REGION`, else
179/// `AWS_REGION`, else [`DEFAULT_B2_REGION`].
180fn resolve_region(region: Option<&str>) -> String {
181    if let Some(r) = region {
182        if !r.is_empty() {
183            return r.to_owned();
184        }
185    }
186    for var in ["SNAPDIR_B2_REGION", "AWS_REGION"] {
187        if let Ok(r) = std::env::var(var) {
188            if !r.is_empty() {
189                return r;
190            }
191        }
192    }
193    DEFAULT_B2_REGION.to_owned()
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    // The canonical content-addressable fixtures from the b2 store test suite.
201    const FOO_CHECKSUM: &str = "49dc870df1de7fd60794cebce449f5ccdae575affaa67a24b62acb03e039db92";
202    const FOO_SHARDED: &str = "49d/c87/0df/1de7fd60794cebce449f5ccdae575affaa67a24b62acb03e039db92";
203    const MANIFEST_ID: &str = "aa91e498f401ea9e6ddbaa1138a0dbeb030fab8defc1252d80c77ebefafbc70d";
204    const MANIFEST_SHARDED: &str =
205        "aa9/1e4/98f/401ea9e6ddbaa1138a0dbeb030fab8defc1252d80c77ebefafbc70d";
206
207    #[test]
208    fn b2_store_parses_bucket_and_prefix_like_oracle() {
209        // Oracle (`_snapdir_export_store_vars`): bucket = cut -f3,
210        // base_dir = cut -f4-. For "b2://my-bucket/my/directory".
211        let loc = S3Location::parse("b2://my-bucket/my/directory");
212        assert_eq!(loc.bucket, "my-bucket");
213        assert_eq!(loc.prefix, "my/directory");
214    }
215
216    #[test]
217    fn b2_store_parse_strips_trailing_slash() {
218        // `_snapdir_b2_store_get_remote_prefix` strips the trailing slash.
219        let loc = S3Location::parse("b2://bucket/long/term/storage/");
220        assert_eq!(loc.bucket, "bucket");
221        assert_eq!(loc.prefix, "long/term/storage");
222    }
223
224    #[test]
225    fn b2_store_parse_bucket_root_has_empty_prefix() {
226        let loc = S3Location::parse("b2://bucket");
227        assert_eq!(loc.bucket, "bucket");
228        assert_eq!(loc.prefix, "");
229
230        let loc_slash = S3Location::parse("b2://bucket/");
231        assert_eq!(loc_slash.bucket, "bucket");
232        assert_eq!(loc_slash.prefix, "");
233    }
234
235    #[test]
236    fn b2_store_object_key_matches_sharded_scheme() {
237        // Key layout must be byte-identical to the frozen S3 sharded scheme so
238        // the bucket is interchangeable across tools.
239        let loc = S3Location::parse("b2://b/long/term/storage");
240        assert_eq!(
241            loc.object_key(FOO_CHECKSUM),
242            format!("long/term/storage/.objects/{FOO_SHARDED}")
243        );
244    }
245
246    #[test]
247    fn b2_store_manifest_key_matches_sharded_scheme() {
248        let loc = S3Location::parse("b2://b/long/term/storage");
249        assert_eq!(
250            loc.manifest_key(MANIFEST_ID),
251            format!("long/term/storage/.manifests/{MANIFEST_SHARDED}")
252        );
253    }
254
255    #[test]
256    fn b2_store_keys_have_no_leading_slash_at_bucket_root() {
257        let loc = S3Location::parse("b2://bucket");
258        assert_eq!(
259            loc.object_key(FOO_CHECKSUM),
260            format!(".objects/{FOO_SHARDED}")
261        );
262        assert_eq!(
263            loc.manifest_key(MANIFEST_ID),
264            format!(".manifests/{MANIFEST_SHARDED}")
265        );
266    }
267
268    #[test]
269    fn b2_store_endpoint_for_region_uses_backblaze_host() {
270        assert_eq!(
271            endpoint_for_region("us-west-004"),
272            "https://s3.us-west-004.backblazeb2.com"
273        );
274        assert_eq!(
275            endpoint_for_region("eu-central-003"),
276            "https://s3.eu-central-003.backblazeb2.com"
277        );
278    }
279
280    #[test]
281    fn b2_store_explicit_endpoint_takes_precedence() {
282        let ep = resolve_endpoint(Some("https://emulator.local:9000"), Some("us-west-004"));
283        assert_eq!(ep, "https://emulator.local:9000");
284    }
285
286    #[test]
287    fn b2_store_endpoint_derived_from_explicit_region() {
288        // With no explicit endpoint and no SNAPDIR_B2_TEST_ENDPOINT set, the
289        // endpoint is derived from the explicit region argument.
290        std::env::remove_var("SNAPDIR_B2_TEST_ENDPOINT");
291        let ep = resolve_endpoint(None, Some("us-west-002"));
292        assert_eq!(ep, "https://s3.us-west-002.backblazeb2.com");
293    }
294
295    #[test]
296    fn b2_store_region_resolution_prefers_explicit_then_default() {
297        // Explicit region wins.
298        assert_eq!(resolve_region(Some("eu-central-003")), "eu-central-003");
299        // Empty explicit region falls through; with no env override set we get
300        // the documented default (guard the env to keep the test hermetic).
301        let saved_b2 = std::env::var("SNAPDIR_B2_REGION").ok();
302        let saved_aws = std::env::var("AWS_REGION").ok();
303        std::env::remove_var("SNAPDIR_B2_REGION");
304        std::env::remove_var("AWS_REGION");
305        assert_eq!(resolve_region(Some("")), DEFAULT_B2_REGION);
306        assert_eq!(resolve_region(None), DEFAULT_B2_REGION);
307        if let Some(v) = saved_b2 {
308            std::env::set_var("SNAPDIR_B2_REGION", v);
309        }
310        if let Some(v) = saved_aws {
311            std::env::set_var("AWS_REGION", v);
312        }
313    }
314
315    // --- Live round-trip, skipped by default --------------------------------
316    //
317    // Requires a Backblaze B2 (or S3-compatible) endpoint plus AWS credentials
318    // (the B2 application key id/secret as AWS access-key/secret-key) in the
319    // environment. Gated behind `SNAPDIR_B2_TEST_ENDPOINT` and
320    // `SNAPDIR_B2_TEST_STORE` (a `b2://bucket/prefix` URL) so it is skipped
321    // unless explicitly configured. Real Backblaze round-trips are exercised by
322    // the later `remote-interop` gate.
323    #[test]
324    fn b2_store_live_round_trip_when_configured() {
325        use snapdir_core::manifest::{ManifestEntry, PathType};
326        use snapdir_core::merkle::{Blake3Hasher, Hasher};
327
328        let (Ok(endpoint), Ok(store)) = (
329            std::env::var("SNAPDIR_B2_TEST_ENDPOINT"),
330            std::env::var("SNAPDIR_B2_TEST_STORE"),
331        ) else {
332            eprintln!(
333                "skipping b2_store live round-trip: set SNAPDIR_B2_TEST_ENDPOINT \
334                 and SNAPDIR_B2_TEST_STORE (b2://bucket/prefix) to run it"
335            );
336            return;
337        };
338
339        let hasher = Blake3Hasher::new();
340
341        let src = std::env::temp_dir().join(format!("snapdir-b2-live-{}", std::process::id()));
342        std::fs::create_dir_all(&src).unwrap();
343        std::fs::write(src.join("foo"), b"foo\n").unwrap();
344        let foo_sum = hasher.hash_hex(b"foo\n");
345        let root_sum = snapdir_core::merkle::directory_checksum([foo_sum.as_str()], &hasher);
346        let mut manifest = Manifest::new();
347        manifest.push(ManifestEntry::new(
348            PathType::Directory,
349            "700",
350            root_sum,
351            4,
352            "./",
353        ));
354        manifest.push(ManifestEntry::new(
355            PathType::File,
356            "600",
357            foo_sum,
358            4,
359            "./foo",
360        ));
361        let manifest = Manifest::from_entries(manifest.entries().to_vec());
362        let id = snapdir_core::merkle::snapshot_id(&manifest, &hasher);
363
364        let b2 = B2Store::connect(&store, Some(&endpoint), None).expect("connect");
365        b2.push(&manifest, &src).expect("push");
366        let read_back = b2.get_manifest(&id).expect("get_manifest");
367        assert_eq!(read_back, manifest);
368
369        let dest = std::env::temp_dir().join(format!("snapdir-b2-dest-{}", std::process::id()));
370        std::fs::create_dir_all(&dest).unwrap();
371        b2.fetch_files(&read_back, &dest).expect("fetch_files");
372        assert_eq!(std::fs::read(dest.join("foo")).unwrap(), b"foo\n");
373
374        let _ = std::fs::remove_dir_all(&src);
375        let _ = std::fs::remove_dir_all(&dest);
376    }
377}