Skip to main content

lfsx_server/storage/
backend.rs

1use futures_util::Stream;
2
3use super::s3::S3Store;
4use super::{Budget, CompressReport, DedupeReport, LocalStore, Object, SweepReport, VerifyReport};
5use crate::error::Error;
6use crate::namespace::Namespace;
7#[cfg(test)]
8use sha2::Digest;
9#[cfg(test)]
10use std::time::Duration;
11
12// Where the objects live. A bucket decouples capacity from the machine, at the
13// price of the things a filesystem gave for nothing — hard links, a directory
14// walk, and a rename that is atomic. Each of those is answered here or refused
15// out loud; none of them is quietly skipped.
16pub struct Store {
17    backend: Backend,
18    usage: super::usage::Usage,
19}
20
21enum Backend {
22    Local(LocalStore),
23    // Even with a bucket the local store stays, because a transfer has to land
24    // somewhere before anyone can tell whether it is the object it claims to be.
25    // It is a write buffer, not the store.
26    // Boxed because a bucket handle beside a local store makes this variant far
27    // larger than the other, and every Store in the process would pay for it.
28    Bucket {
29        bucket: Box<S3Store>,
30        staging: LocalStore,
31    },
32}
33
34impl Store {
35    pub fn local(store: LocalStore) -> Self {
36        Self::over(Backend::Local(store))
37    }
38
39    // Compression and encryption used to be stripped here, because a framed
40    // object was only readable through the file the codec opened and a bucket key
41    // is not one. The codec now reads from a bucket too, so the frames go up as
42    // they are and come back decoded: the header and the index are three ranged
43    // GETs, which is what the format was shaped for.
44    pub fn bucket(bucket: S3Store, staging: LocalStore) -> Self {
45        Self::over(Backend::Bucket {
46            bucket: Box::new(bucket),
47            staging,
48        })
49    }
50
51    fn over(backend: Backend) -> Self {
52        Self {
53            backend,
54            usage: super::usage::Usage::default(),
55        }
56    }
57
58    fn staging(&self) -> &LocalStore {
59        match &self.backend {
60            Backend::Local(store) => store,
61            Backend::Bucket { staging, .. } => staging,
62        }
63    }
64
65    // Everything an interrupted upload can leave behind, wherever it left it. A
66    // bucket deployment still stages locally, so both are swept and the figures
67    // add up to one answer.
68    pub async fn reclaim(&self, older_than: std::time::Duration) -> super::Reclaimed {
69        let mut reclaimed = self.staging().reclaim_staging(older_than).await;
70
71        if let Backend::Bucket { bucket, .. } = &self.backend {
72            match bucket.reclaim_incoming(older_than).await {
73                Ok(theirs) => {
74                    reclaimed.files += theirs.files;
75                    reclaimed.bytes += theirs.bytes;
76                }
77                Err(error) => {
78                    tracing::warn!(%error, "abandoned uploads in the bucket could not be reclaimed");
79                }
80            }
81        }
82
83        reclaimed
84    }
85
86    // Readiness has to ask the backend that actually serves. Once the objects
87    // live in a bucket the volume is a write buffer, and an instance whose
88    // credentials were rotated or whose bucket is gone passes a probe that only
89    // proves its scratch disk works — then fails every transfer it is handed.
90    //
91    // So both are asked, either failing takes the instance out, and they are
92    // named apart: a full disk and a rotated key are not the same afternoon.
93    pub async fn writable(&self) -> Result<(), Error> {
94        self.staging().writable().await.map_err(|error| {
95            Error::Storage(std::io::Error::other(format!(
96                "the staging volume is not writable: {error}"
97            )))
98        })?;
99
100        if let Backend::Bucket { bucket, .. } = &self.backend {
101            bucket.reachable().await?;
102        }
103
104        Ok(())
105    }
106
107    pub fn scans(&self) -> u64 {
108        self.staging().scans()
109    }
110
111    pub async fn exists(&self, ns: &Namespace, oid: &str) -> bool {
112        match &self.backend {
113            Backend::Local(store) => store.exists(ns, oid).await,
114            Backend::Bucket { bucket, .. } => bucket.exists(ns, oid).await,
115        }
116    }
117
118    // Where the client should fetch this object from, when that is somewhere
119    // other than this server. None for a local store, and for a bucket the
120    // operator has not asked to redirect — which is the default, because the
121    // streamed path is the one that counts the bytes and holds the ceiling.
122    //
123    // The caller is responsible for having established that this repository
124    // holds the object. This hands out a signature, not a permission.
125    pub fn redirect(&self, oid: &str) -> Option<String> {
126        match &self.backend {
127            Backend::Local(_) => None,
128            // A pre-signed URL hands over whatever sits under that key, and with
129            // a codec in the path that is a frame rather than the object. The
130            // client would hash what arrived, get a digest that is not the one it
131            // asked for, and reject it. So the redirect is given up and the
132            // download streams, which is the only path that can decode.
133            //
134            // Compression is enough on its own, even though it still lets a
135            // client upload straight to the bucket. That asymmetry is the right
136            // way round: an unframed object is a perfectly good entry, so a
137            // direct upload stays safe, while one framed object anywhere in the
138            // store makes every redirect a guess.
139            Backend::Bucket { staging, .. } if staging.frames() => None,
140            Backend::Bucket { bucket, .. } => bucket.presigned_download(oid),
141        }
142    }
143
144    // Where the client should PUT the object, when that is the bucket rather than
145    // this server. None for a local store and for a bucket the operator has not
146    // asked to redirect.
147    pub fn presigned_upload(&self, ns: &Namespace, oid: &str) -> Option<super::s3::Presigned> {
148        match &self.backend {
149            Backend::Local(_) => None,
150            // A client uploading straight to the bucket writes the object as it
151            // is, so a configured key would never touch it and the bucket would
152            // hold plaintext while an operator believed otherwise. Encryption is
153            // a promise about what the storage provider can read; a faster upload
154            // is not worth quietly breaking it. Those transfers keep coming
155            // through the server, which seals them.
156            Backend::Bucket { staging, .. } if staging.encrypts() => None,
157            Backend::Bucket { bucket, .. } => bucket.presigned_upload(ns, oid),
158        }
159    }
160
161    // How big an object waiting under this repository's own upload key is. None
162    // when there is nothing waiting, which is every local deployment and every
163    // client that has not used its URL.
164    pub async fn uploaded_size(&self, ns: &Namespace, oid: &str) -> Result<Option<u64>, Error> {
165        match &self.backend {
166            Backend::Local(_) => Ok(None),
167            Backend::Bucket { bucket, .. } => Ok(bucket.uploaded_size(ns, oid).await.ok()),
168        }
169    }
170
171    // Take an upload this repository made into the shared keyspace. Only reachable
172    // for a bucket, because only there does a client write anywhere this server
173    // did not.
174    pub async fn adopt(&self, ns: &Namespace, oid: &str, arrived: u64) -> Result<(), Error> {
175        let outcome = match &self.backend {
176            Backend::Local(_) => Err(Error::Unsupported(
177                "objects are written through this server, so there is nothing to adopt",
178            )),
179            Backend::Bucket { bucket, .. } => bucket.adopt(ns, oid).await,
180        };
181
182        // Same reason as a write: verify is called once per object, so dropping
183        // what is remembered here would make every one of them re-measure.
184        if outcome.is_ok() {
185            self.usage.stored(ns, arrived).await;
186        }
187
188        outcome
189    }
190
191    pub async fn open(&self, ns: &Namespace, oid: &str) -> Result<Object, Error> {
192        match &self.backend {
193            Backend::Local(store) => store.open(ns, oid).await,
194            Backend::Bucket { bucket, staging } => {
195                // The marker is the proof of possession and is checked before
196                // anything is read, exactly as a local open checks the link.
197                if !bucket.exists(ns, oid).await {
198                    return Err(Error::NotFound);
199                }
200
201                let size = bucket.size_of(oid).await?;
202                let reader = super::codec::Reader::Bucket {
203                    bucket: (**bucket).clone(),
204                    oid: oid.to_owned(),
205                };
206
207                match super::codec::Framed::open(
208                    reader,
209                    size,
210                    staging.keyring().map(AsRef::as_ref),
211                    oid,
212                )
213                .await?
214                {
215                    Some(framed) => Ok(Object::Framed(framed)),
216                    // Not one of ours: the object is the bytes, and streaming
217                    // them straight through costs no extra round trip.
218                    None => Ok(Object::Remote {
219                        bucket: (**bucket).clone(),
220                        oid: oid.to_owned(),
221                        size,
222                    }),
223                }
224            }
225        }
226    }
227
228    pub async fn write<S, E>(
229        &self,
230        ns: &Namespace,
231        oid: &str,
232        expected_size: Option<u64>,
233        budget: Option<Budget>,
234        chunks: S,
235    ) -> Result<u64, Error>
236    where
237        S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
238        E: std::error::Error + Send + Sync + 'static,
239    {
240        let written = match &self.backend {
241            Backend::Local(store) => store.write(ns, oid, expected_size, budget, chunks).await?,
242            Backend::Bucket { bucket, staging } => {
243                // Asked of the bucket, because the staging store answers about a
244                // local layout a bucket deployment never fills in: it would call
245                // every upload fresh, and re-pushing an object the repository
246                // already holds would grow what is remembered without anything
247                // being stored.
248                let fresh = !bucket.exists(ns, oid).await;
249
250                let staged = staging
251                    .stage(ns, oid, expected_size, budget, chunks)
252                    .await?;
253                let outcome = bucket.store(ns, oid, &staged.path).await;
254
255                // The staging file has served its purpose either way. Leaving it
256                // would be a leak the reclaimer only notices a day later.
257                let _ = tokio::fs::remove_file(&staged.path).await;
258                outcome?;
259
260                super::Written {
261                    bytes: staged.written,
262                    fresh,
263                }
264            }
265        };
266
267        // Added to what is remembered rather than dropping it: a client pushing
268        // a hundred objects would otherwise make the next negotiation measure
269        // the repository again, which on a bucket is what this cache exists to
270        // avoid.
271        if written.fresh {
272            self.usage.stored(ns, written.bytes).await;
273        }
274
275        Ok(written.bytes)
276    }
277
278    // None rather than zero: a bucket has no cheap answer for what the whole
279    // store holds, and building one from a full listing would cost a request per
280    // object on every scrape. Zero would be read as an empty bucket by every
281    // dashboard that averages it, which is the one lie this seam otherwise
282    // refuses to tell — everything else it cannot do answers 501.
283    pub async fn capacity(&self) -> Option<(u64, u64)> {
284        match &self.backend {
285            Backend::Local(store) => Some(store.usage().await),
286            Backend::Bucket { .. } => None,
287        }
288    }
289
290    // Measured at most once a minute per repository, whichever backend is
291    // behind it. A bucket answers this by listing the repository's markers and
292    // asking the size of each, so one uncached call per object in a batch made
293    // a hundred-object push cost a hundred listings — the product, not the sum.
294    pub async fn usage_of(&self, ns: &Namespace) -> (u64, u64) {
295        if let Some(cached) = self.usage.cached(ns).await {
296            return cached;
297        }
298
299        let measured = match &self.backend {
300            Backend::Local(store) => store.measure_of(ns).await,
301            Backend::Bucket { bucket, .. } => bucket.usage_of(ns).await,
302        };
303
304        self.usage.remember(ns, measured.0, measured.1).await;
305
306        measured
307    }
308
309    pub async fn sweep(
310        &self,
311        ns: &Namespace,
312        retained: &std::collections::HashSet<String>,
313        grace: std::time::Duration,
314        dry_run: bool,
315    ) -> Result<SweepReport, Error> {
316        match &self.backend {
317            Backend::Local(store) => {
318                let report = store.sweep(ns, retained, grace, dry_run).await;
319
320                // Freeing gigabytes and then answering the next quota check from
321                // the figure measured before is how a client is refused space it
322                // has just been told it reclaimed.
323                self.usage.forget(ns).await;
324
325                report
326            }
327            Backend::Bucket { bucket, .. } => {
328                let report = bucket.sweep(ns, retained, grace, dry_run).await;
329
330                if report.is_ok() && !dry_run {
331                    self.usage.forget(ns).await;
332                }
333
334                report
335            }
336        }
337    }
338
339    pub async fn dedupe(&self, ns: &Namespace, dry_run: bool) -> Result<DedupeReport, Error> {
340        match &self.backend {
341            Backend::Local(store) => {
342                let report = store.dedupe(ns, dry_run).await;
343
344                // Freeing gigabytes and then answering the next quota check from
345                // the figure measured before is how a client is refused space it
346                // has just been told it reclaimed.
347                self.usage.forget(ns).await;
348
349                report
350            }
351            // Content addressing already gives this: two repositories pushing the
352            // same object write the same key, and each holds a marker beside it.
353            // There is nothing left to fold in.
354            Backend::Bucket { .. } => Err(Error::Unsupported(
355                "a bucket stores each object once already, so there is nothing to deduplicate",
356            )),
357        }
358    }
359
360    pub async fn compress(&self, ns: &Namespace, dry_run: bool) -> Result<CompressReport, Error> {
361        match &self.backend {
362            Backend::Local(store) => {
363                let report = store.compress(ns, dry_run).await;
364
365                // Freeing gigabytes and then answering the next quota check from
366                // the figure measured before is how a client is refused space it
367                // has just been told it reclaimed.
368                self.usage.forget(ns).await;
369
370                report
371            }
372            // Objects arriving now are compressed if the server is configured to;
373            // rewriting the ones already in the bucket means walking it and
374            // reuploading, which is a different piece of work.
375            Backend::Bucket { .. } => Err(Error::Unsupported(
376                "rewriting objects already in a bucket is not implemented",
377            )),
378        }
379    }
380
381    pub async fn verify(&self, ns: &Namespace) -> Result<VerifyReport, Error> {
382        match &self.backend {
383            Backend::Local(store) => store.verify(ns).await,
384            Backend::Bucket { .. } => Err(Error::Unsupported(
385                "verification is not implemented for a bucket yet",
386            )),
387        }
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use futures_util::StreamExt;
394
395    use super::*;
396    use crate::storage::crypt::Keyring;
397    use crate::storage::s3::tests::{bucket, redirecting, store};
398
399    fn keyring() -> std::sync::Arc<Keyring> {
400        std::sync::Arc::new(
401            Keyring::parse(&hex::encode([7u8; crate::storage::crypt::KEY])).unwrap(),
402        )
403    }
404
405    fn namespace() -> Namespace {
406        Namespace::new("FerrLabs", "Blastlands").unwrap()
407    }
408
409    fn bucket_store(root: &tempfile::TempDir, endpoint: &str) -> Store {
410        Store::bucket(store(endpoint), LocalStore::new(root.path()))
411    }
412
413    async fn read_back(store: &Store, ns: &Namespace, oid: &str) -> Vec<u8> {
414        let object = store.open(ns, oid).await.unwrap();
415        let size = object.size();
416        let mut chunks = object.stream(0, size).await.unwrap();
417        let mut out = Vec::new();
418
419        while let Some(chunk) = chunks.next().await {
420            out.extend_from_slice(&chunk.unwrap());
421        }
422
423        out
424    }
425
426    #[tokio::test]
427    async fn an_upload_lands_in_the_bucket_and_reads_back_through_the_same_seam() {
428        let root = tempfile::tempdir().unwrap();
429        let (endpoint, _objects) = bucket().await;
430        let store = bucket_store(&root, &endpoint);
431        let payload = b"an asset that never touches this disk for long".repeat(32);
432        let oid = hex::encode(sha2::Sha256::digest(&payload));
433
434        let written = store
435            .write(
436                &namespace(),
437                &oid,
438                Some(payload.len() as u64),
439                None,
440                futures_util::stream::iter([Ok::<_, std::io::Error>(axum::body::Bytes::from(
441                    payload.clone(),
442                ))]),
443            )
444            .await
445            .unwrap();
446
447        assert_eq!(written, payload.len() as u64);
448        assert!(store.exists(&namespace(), &oid).await);
449
450        assert_eq!(read_back(&store, &namespace(), &oid).await, payload);
451    }
452
453    // Compression and a bucket are configured independently, and a studio that
454    // turns both on gets no warning from either. What lands under the digest
455    // has to be the object, because the only thing that will ever read it back
456    // is a client that asked for those bytes by that name.
457    #[tokio::test]
458    async fn a_bucket_holds_the_object_even_when_the_server_was_told_to_compress() {
459        let root = tempfile::tempdir().unwrap();
460        let (endpoint, _objects) = bucket().await;
461        let store = Store::bucket(
462            store(&endpoint),
463            LocalStore::new(root.path()).with_compression(Some(3)),
464        );
465        let payload = b"a mesh that gives up most of its ground to zstd ".repeat(4096);
466        let oid = hex::encode(sha2::Sha256::digest(&payload));
467
468        store
469            .write(
470                &namespace(),
471                &oid,
472                Some(payload.len() as u64),
473                None,
474                futures_util::stream::iter([Ok::<_, std::io::Error>(axum::body::Bytes::from(
475                    payload.clone(),
476                ))]),
477            )
478            .await
479            .unwrap();
480
481        let restored = read_back(&store, &namespace(), &oid).await;
482
483        assert_eq!(
484            hex::encode(sha2::Sha256::digest(&restored)),
485            oid,
486            "the client asked for the object named by this digest and has no way to know the              server framed it on the way past: {} bytes came back",
487            restored.len()
488        );
489        assert_eq!(restored, payload);
490    }
491
492    #[tokio::test]
493    async fn the_staging_file_does_not_outlive_the_upload() {
494        let root = tempfile::tempdir().unwrap();
495        let (endpoint, _objects) = bucket().await;
496        let store = bucket_store(&root, &endpoint);
497        let payload = b"an asset passing through".to_vec();
498        let oid = hex::encode(sha2::Sha256::digest(&payload));
499
500        store
501            .write(
502                &namespace(),
503                &oid,
504                None,
505                None,
506                futures_util::stream::iter([Ok::<_, std::io::Error>(axum::body::Bytes::from(
507                    payload,
508                ))]),
509            )
510            .await
511            .unwrap();
512
513        let leftovers = crate::storage::tests::staging_files(root.path());
514        assert!(
515            leftovers.is_empty(),
516            "local disk is a write buffer here, and one that is never emptied is a disk that \
517             fills: {leftovers:?}"
518        );
519    }
520
521    #[tokio::test]
522    async fn a_bucket_reports_no_capacity_rather_than_an_empty_one() {
523        let root = tempfile::tempdir().unwrap();
524        let (endpoint, _objects) = bucket().await;
525
526        assert!(
527            bucket_store(&root, &endpoint).capacity().await.is_none(),
528            "zero would be read as an empty store by every dashboard that averages it"
529        );
530        assert!(
531            Store::local(LocalStore::new(root.path()))
532                .capacity()
533                .await
534                .is_some()
535        );
536    }
537
538    #[tokio::test]
539    async fn the_maintenance_commands_say_they_do_not_apply_rather_than_lying() {
540        let root = tempfile::tempdir().unwrap();
541        let (endpoint, _objects) = bucket().await;
542        let store = bucket_store(&root, &endpoint);
543        let ns = namespace();
544
545        for outcome in [
546            store.dedupe(&ns, true).await.err(),
547            store.compress(&ns, true).await.err(),
548            store.verify(&ns).await.err(),
549        ] {
550            assert!(
551                matches!(outcome, Some(Error::Unsupported(_))),
552                "an operator running one of these against a bucket has to be told it did nothing,                  not handed an empty report that reads like success: {outcome:?}"
553            );
554        }
555
556        // Collection is the one that no longer belongs in that list.
557        assert!(
558            store
559                .sweep(&ns, &std::collections::HashSet::new(), Duration::ZERO, true)
560                .await
561                .is_ok(),
562            "collection is implemented for a bucket and must not answer Unsupported"
563        );
564    }
565
566    // The bug this guards. A pre-signed download hands the client the bucket key
567    // itself, which is only the object while nothing framed it on the way in.
568    // `presigned_upload` has refused to sign an upload under a key since
569    // encryption landed, for exactly this reason; the download side had no such
570    // guard and handed out frames.
571    //
572    // Asserted against what is actually in the bucket rather than against the
573    // flag, so this fails if framing ever stops happening and the guard becomes
574    // theatre.
575    #[tokio::test]
576    async fn a_download_is_never_redirected_to_a_frame() {
577        for label in ["compressed", "encrypted"] {
578            let root = tempfile::tempdir().unwrap();
579            let (endpoint, objects) = bucket().await;
580            let staging = match label {
581                "compressed" => LocalStore::new(root.path()).with_compression(Some(3)),
582                _ => LocalStore::new(root.path()).with_encryption(Some(keyring())),
583            };
584            let store = Store::bucket(redirecting(&endpoint), staging);
585
586            let payload =
587                b"a scene file that compresses and must still come back whole ".repeat(512);
588            let oid = hex::encode(sha2::Sha256::digest(&payload));
589
590            store
591                .write(
592                    &namespace(),
593                    &oid,
594                    Some(payload.len() as u64),
595                    None,
596                    futures_util::stream::iter([Ok::<_, std::io::Error>(axum::body::Bytes::from(
597                        payload.clone(),
598                    ))]),
599                )
600                .await
601                .unwrap();
602
603            let stored = objects
604                .lock()
605                .unwrap()
606                .values()
607                .find(|object| !object.is_empty())
608                .cloned()
609                .unwrap();
610
611            assert_ne!(
612                stored, payload,
613                "{label}: the bucket holds a frame, which is the premise of the rest of this test"
614            );
615            assert_eq!(
616                store.redirect(&oid),
617                None,
618                "{label}: a client sent to the bucket would hash {} bytes of frame and reject the \
619                 object it asked for",
620                stored.len()
621            );
622            assert_eq!(
623                read_back(&store, &namespace(), &oid).await,
624                payload,
625                "{label}: giving up the redirect is only correct because the streamed path decodes"
626            );
627        }
628    }
629
630    // And the guard does not quietly disable the feature it protects. With no
631    // codec configured the bucket holds the object itself, so the redirect is
632    // exactly what the operator asked for.
633    #[tokio::test]
634    async fn a_bucket_holding_the_object_itself_still_redirects() {
635        let root = tempfile::tempdir().unwrap();
636        let (endpoint, _objects) = bucket().await;
637        let store = Store::bucket(redirecting(&endpoint), LocalStore::new(root.path()));
638
639        let payload = b"an object stored as it arrived".repeat(32);
640        let oid = hex::encode(sha2::Sha256::digest(&payload));
641
642        store
643            .write(
644                &namespace(),
645                &oid,
646                Some(payload.len() as u64),
647                None,
648                futures_util::stream::iter([Ok::<_, std::io::Error>(axum::body::Bytes::from(
649                    payload.clone(),
650                ))]),
651            )
652            .await
653            .unwrap();
654
655        assert!(store.redirect(&oid).is_some());
656    }
657}