Skip to main content

lfsx_server/storage/
s3.rs

1pub(crate) mod keyspace;
2pub(crate) mod multipart;
3pub(crate) mod probe;
4pub(crate) mod refs;
5
6use std::time::Duration;
7
8use axum::body::Bytes;
9use futures_util::Stream;
10
11use base64::Engine;
12
13use crate::error::Error;
14use crate::namespace::Namespace;
15use crate::storage::Reclaimed;
16
17pub use keyspace::{Keyspace, Presigned};
18
19const CHECKSUM: &str = "x-amz-checksum-sha256";
20
21pub struct S3Config {
22    pub endpoint: String,
23    pub bucket: String,
24    pub region: String,
25    pub access_key: String,
26    pub secret_key: String,
27    pub path_style: bool,
28    // How long a signature is good for. It is the same number the batch
29    // response advertises as `expires_in`, because a client told it has half an
30    // hour and handed a URL that dies in five minutes will fail a resume it had
31    // every reason to expect to work.
32    pub lifetime: Duration,
33}
34
35// The same layout as the local store, for the same reasons. The bytes live once
36// under a key derived from their digest, and a repository that holds them owns
37// an empty marker beside it — the object store's answer to a hard link. It is
38// what keeps two projects sharing an asset pack from paying twice, and what
39// stops a repository reading an object it never pushed: the marker is the proof
40// of possession, and it is the only thing the permission check consults.
41//
42// Everything below is object semantics. What it takes to talk to the store at
43// all — signing, retrying, listing, the client — is the keyspace underneath.
44#[derive(Clone)]
45pub struct S3Store {
46    keys: Keyspace,
47    redirect: bool,
48}
49
50impl S3Store {
51    pub fn new(keys: Keyspace, redirect: bool) -> Self {
52        Self { keys, redirect }
53    }
54
55    fn content_key(oid: &str) -> String {
56        format!(".content/{}/{}/{oid}", &oid[0..2], &oid[2..4])
57    }
58
59    // Where a client uploads to when the bytes never pass through this server.
60    // Per repository on purpose: the shared content key would take bytes from
61    // anyone allowed to write, and then nothing distinguishes a repository that
62    // uploaded an object from one that merely knew its digest. A key only this
63    // repository was handed a signature for is the proof of possession that the
64    // marker stands for everywhere else.
65    fn incoming_key(ns: &Namespace, oid: &str) -> String {
66        format!(
67            ".incoming/{}/{}/{}/{}/{oid}",
68            ns.org(),
69            ns.repo(),
70            &oid[0..2],
71            &oid[2..4]
72        )
73    }
74
75    fn marker_key(ns: &Namespace, oid: &str) -> String {
76        format!(
77            "{}/{}/{}/{}/{oid}",
78            ns.org(),
79            ns.repo(),
80            &oid[0..2],
81            &oid[2..4]
82        )
83    }
84
85    fn own_prefix(ns: &Namespace) -> String {
86        format!("{}/{}/", ns.org(), ns.repo())
87    }
88
89    pub async fn reachable(&self) -> Result<(), Error> {
90        self.keys.reachable().await
91    }
92
93    pub async fn exists(&self, ns: &Namespace, oid: &str) -> bool {
94        if crate::storage::LocalStore::validate_oid(oid).is_err() {
95            return false;
96        }
97
98        self.keys.head(&Self::marker_key(ns, oid)).await.is_ok()
99    }
100
101    pub async fn size_of(&self, oid: &str) -> Result<u64, Error> {
102        // Every entry point validates before slicing an oid into a key: the
103        // fanout takes the first four characters, so a short one is a panic
104        // rather than a refusal, and a panic is a 500 for something that should
105        // have been a 422.
106        crate::storage::LocalStore::validate_oid(oid)?;
107
108        self.keys.head(&Self::content_key(oid)).await
109    }
110
111    // A download is streamed through this server rather than redirected, so the
112    // features that live in the byte path — the counters, the ranges, and the
113    // compression that will follow — keep working. The pre-signed redirect is a
114    // separate mode for operators who would rather spend the object store's
115    // bandwidth than their own.
116    pub async fn read(
117        &self,
118        oid: &str,
119        start: u64,
120        length: u64,
121    ) -> Result<impl Stream<Item = Result<Bytes, reqwest::Error>> + use<>, Error> {
122        crate::storage::LocalStore::validate_oid(oid)?;
123
124        self.keys
125            .get_range(&Self::content_key(oid), start, length)
126            .await
127    }
128
129    // A URL the client fetches from the bucket directly, so the bytes never
130    // cross this server. Whether the caller is entitled to them has already been
131    // settled by the marker before this is called: the signature is scoped to
132    // one content key and expires, and it grants nothing the batch response was
133    // not about to grant anyway.
134    pub fn presigned_download(&self, oid: &str) -> Option<String> {
135        if !self.redirect || crate::storage::LocalStore::validate_oid(oid).is_err() {
136            return None;
137        }
138
139        Some(self.keys.signed_download(&Self::content_key(oid)))
140    }
141
142    // A URL the client PUTs the object to, and the headers it has to send with
143    // it. The digest is bound into the signature, so the store refuses anything
144    // that does not hash to the object it was signed for: a client with this URL
145    // cannot put arbitrary bytes anywhere, which is what makes handing one out
146    // safe at all.
147    // None above the single-request ceiling, and that is not a refusal: the
148    // object falls back to coming through this server, which sends it in parts.
149    // A client cannot do the same, because the `basic` transfer adapter every
150    // git-lfs speaks does one PUT to one href and has nowhere to put a second.
151    // So the ceiling multipart removes for the streamed path is real and
152    // permanent for this one, and the only question is whether the client learns
153    // it now or after uploading five gigabytes.
154    //
155    // It also keeps `adopt` honest: `CopyObject` stops at the same 5 GiB, and
156    // nothing can reach `.incoming/` above it while this holds.
157    pub fn presigned_upload(&self, ns: &Namespace, oid: &str, size: u64) -> Option<Presigned> {
158        if !self.redirect
159            || size > multipart::SINGLE_PUT_CEILING
160            || crate::storage::LocalStore::validate_oid(oid).is_err()
161        {
162            return None;
163        }
164
165        let digest = base64::engine::general_purpose::STANDARD.encode(hex::decode(oid).ok()?);
166
167        Some(self.keys.signed_upload(
168            &Self::incoming_key(ns, oid),
169            vec![(CHECKSUM.to_owned(), digest)],
170        ))
171    }
172
173    // How big the object a client uploaded actually is, which is the first thing
174    // this server learns about it: nothing measured the bytes on the way past.
175    pub async fn uploaded_size(&self, ns: &Namespace, oid: &str) -> Result<u64, Error> {
176        crate::storage::LocalStore::validate_oid(oid)?;
177
178        self.keys.head(&Self::incoming_key(ns, oid)).await
179    }
180
181    // Take an upload that landed under this repository's own key into the shared
182    // keyspace. The bytes are already known to hash to the oid, because the store
183    // refused everything else.
184    pub async fn adopt(&self, ns: &Namespace, oid: &str) -> Result<(), Error> {
185        crate::storage::LocalStore::validate_oid(oid)?;
186
187        let incoming = Self::incoming_key(ns, oid);
188        let content = Self::content_key(oid);
189
190        // Already there means another repository pushed the same object, and the
191        // bytes are identical by construction.
192        if self.keys.head(&content).await.is_err() {
193            self.keys.copy(&incoming, &content).await?;
194        }
195
196        // Before the marker, always. The marker is the claim and the ref is the
197        // index of it, so a crash between the two has to leave a ref nobody
198        // claims rather than a claim nothing indexes: the first leaks an object,
199        // the second lets a later sweep free bytes this repository holds.
200        refs::write(&self.keys, ns, oid).await?;
201
202        self.keys
203            .put(
204                &Self::marker_key(ns, oid),
205                reqwest::Body::from(Vec::new()),
206                0,
207            )
208            .await?;
209
210        // Leaving it would pay for the object twice. A failure here is not worth
211        // failing the push over: the object is adopted, and what is left is a key
212        // the operator can see.
213        if let Err(error) = self.keys.delete(&incoming).await {
214            tracing::warn!(%error, key = incoming, "an adopted upload could not be cleaned up");
215        }
216
217        Ok(())
218    }
219
220    // The upload has already been streamed to a staging file, hashed and checked
221    // against everything the server enforces, so that file is what goes up —
222    // streamed from disk rather than read into memory, because an object here is
223    // measured in gigabytes and the whole storage layer is built on holding at
224    // most a few megabytes of one at a time.
225    //
226    // The bytes go up once, keyed by their digest, and the marker records that
227    // this repository holds them. Content that is already there is skipped: the
228    // key would receive the same bytes it already has.
229    pub async fn store(
230        &self,
231        ns: &Namespace,
232        oid: &str,
233        staged: &std::path::Path,
234    ) -> Result<(), Error> {
235        crate::storage::LocalStore::validate_oid(oid)?;
236
237        if self.keys.head(&Self::content_key(oid)).await.is_err() {
238            let file = tokio::fs::File::open(staged).await?;
239            let length = file.metadata().await?.len();
240
241            // One request while one request will carry it, which is every
242            // object a store normally sees, and parts when it will not. The
243            // split is here rather than always going in parts because the
244            // single write is one round trip and needs no cleanup if it fails.
245            if length > multipart::SINGLE_PUT_CEILING {
246                drop(file);
247                multipart::put(&self.keys, &Self::content_key(oid), staged, length).await?;
248            } else {
249                let stream = tokio_util::io::ReaderStream::new(file);
250
251                self.keys
252                    .put(
253                        &Self::content_key(oid),
254                        reqwest::Body::wrap_stream(stream),
255                        length,
256                    )
257                    .await?;
258            }
259        }
260
261        refs::write(&self.keys, ns, oid).await?;
262
263        self.keys
264            .put(
265                &Self::marker_key(ns, oid),
266                reqwest::Body::from(Vec::new()),
267                0,
268            )
269            .await
270    }
271
272    // What an interrupted upload leaves behind. A client can negotiate, PUT the
273    // object, and never report it: the bytes sit under its own upload key and
274    // nothing else will ever look at them. The local path has had a reclaimer for
275    // this since the beginning, and a bucket had none, so the cost was unbounded
276    // over time and invisible.
277    pub async fn reclaim_incoming(&self, older_than: Duration) -> Result<Reclaimed, Error> {
278        let mut reclaimed = Reclaimed::default();
279
280        for entry in self.keys.entries(".incoming/").await? {
281            // A slow client on a bad connection is not an abandoned one.
282            if entry.age().is_none_or(|age| age < older_than) {
283                continue;
284            }
285
286            if self.keys.delete(&entry.key).await.is_ok() {
287                reclaimed.files += 1;
288                reclaimed.bytes += entry.size;
289            }
290        }
291
292        Ok(reclaimed)
293    }
294
295    // Collection, with the marker keyspace standing in for the link count a
296    // filesystem keeps. A repository's marker is its claim on the bytes, and the
297    // bytes go when the last claim does.
298    //
299    // Everything hard here is one question: does any *other* repository still
300    // claim this object? A marker is `{org}/{repo}/.../{oid}`, so the oid is the
301    // suffix and the org and repo that would make a prefix are exactly what is
302    // unknown. The claim index turns that into one prefix listing per object. A
303    // bucket that predates the index has to be read whole instead, and that pass
304    // builds the index as it goes, so it is paid once rather than every sweep.
305    pub async fn sweep(
306        &self,
307        ns: &Namespace,
308        retained: &std::collections::HashSet<String>,
309        grace: Duration,
310        dry_run: bool,
311    ) -> Result<crate::storage::SweepReport, Error> {
312        if refs::ready(&self.keys).await {
313            self.sweep_indexed(ns, retained, grace, dry_run).await
314        } else {
315            self.sweep_whole_bucket(ns, retained, grace, dry_run).await
316        }
317    }
318
319    // The markers this repository is allowed to drop. Retained is what the client
320    // says it still needs; the grace window is what keeps a push still in flight
321    // from being read as an abandoned object.
322    fn droppable(
323        mine: Vec<(keyspace::Entry, String)>,
324        retained: &std::collections::HashSet<String>,
325        grace: Duration,
326        report: &mut crate::storage::SweepReport,
327    ) -> Vec<(keyspace::Entry, String)> {
328        mine.into_iter()
329            .filter(|(entry, oid)| {
330                if retained.contains(oid) {
331                    return false;
332                }
333
334                if entry.age().is_none_or(|age| age < grace) {
335                    report.within_grace += 1;
336                    return false;
337                }
338
339                report.swept += 1;
340                true
341            })
342            .collect()
343    }
344
345    // The cost this exists to avoid: one listing of this repository's own prefix,
346    // then one listing of a short index prefix per object actually being dropped.
347    // Nothing here is proportional to the size of the bucket.
348    async fn sweep_indexed(
349        &self,
350        ns: &Namespace,
351        retained: &std::collections::HashSet<String>,
352        grace: Duration,
353        dry_run: bool,
354    ) -> Result<crate::storage::SweepReport, Error> {
355        let listing = self.keys.listing(&Self::own_prefix(ns)).await;
356        let mut report = crate::storage::SweepReport {
357            dry_run,
358            incomplete: !listing.complete,
359            ..Default::default()
360        };
361
362        let mine = listing
363            .entries
364            .into_iter()
365            .filter_map(|entry| {
366                let oid = entry.key.rsplit('/').next()?.to_owned();
367                crate::storage::LocalStore::validate_oid(&oid).ok()?;
368                Some((entry, oid))
369            })
370            .collect();
371
372        for (entry, oid) in Self::droppable(mine, retained, grace, &mut report) {
373            let frees = !refs::claimed_by_another(&self.keys, ns, &oid).await;
374
375            if dry_run {
376                if frees {
377                    report.bytes += self.size_of(&oid).await.unwrap_or_default();
378                }
379                continue;
380            }
381
382            self.keys.delete(&entry.key).await?;
383
384            // After the marker, never before. A failure between the two has to
385            // leave a ref with no claim behind it, which costs an object nobody
386            // reads, rather than a claim with no ref, which would let the next
387            // sweep free bytes this repository still holds.
388            if let Err(error) = self.keys.delete(&refs::key(ns, &oid)).await {
389                tracing::warn!(%error, oid, "a dropped marker left its index entry behind");
390            }
391
392            if frees {
393                // Asked before the delete, because afterwards there is nothing
394                // left to ask.
395                let size = self.size_of(&oid).await.unwrap_or_default();
396
397                if self.keys.delete(&Self::content_key(&oid)).await? {
398                    report.bytes += size;
399                }
400            }
401        }
402
403        Ok(report)
404    }
405
406    // What a bucket with no index costs, and what builds one.
407    //
408    // One listing of the whole bucket answers all three questions at once: which
409    // markers this repository holds, which oids any other repository still
410    // claims, and how big each content object is. Asked separately they would
411    // cost a request per object, which on a bucket is the difference between a
412    // collection an operator runs and one they read about.
413    //
414    // A listing that did not finish is the dangerous case. It cannot be used to
415    // conclude that nothing references an object, because the reference may sit
416    // in the pages that never arrived. So an incomplete listing still drops this
417    // repository's markers, which the retained set alone decides, and leaves
418    // every content key exactly where it is.
419    async fn sweep_whole_bucket(
420        &self,
421        ns: &Namespace,
422        retained: &std::collections::HashSet<String>,
423        grace: Duration,
424        dry_run: bool,
425    ) -> Result<crate::storage::SweepReport, Error> {
426        let listing = self.keys.listing("").await;
427        let mut report = crate::storage::SweepReport {
428            dry_run,
429            incomplete: !listing.complete,
430            ..Default::default()
431        };
432
433        let ours = Self::own_prefix(ns);
434        let mut markers = Vec::new();
435        let mut mine = Vec::new();
436        let mut claimed_elsewhere = std::collections::HashSet::new();
437        let mut sizes = std::collections::HashMap::new();
438
439        for entry in listing.entries {
440            if let Some(rest) = entry.key.strip_prefix(".content/") {
441                if let Some(oid) = rest.rsplit('/').next() {
442                    sizes.insert(oid.to_owned(), entry.size);
443                }
444                continue;
445            }
446
447            // Locks live at `.locks/{org}/{repo}/{id}`, so they never match the
448            // marker prefix and are never swept. Skipped explicitly all the same:
449            // falling through would file every lock id in the claimed set, and an
450            // object whose digest happened to equal a lock id would then never be
451            // collected. The odds are absurd today and the line costs nothing,
452            // but the code should not depend on ids and digests never colliding.
453            //
454            // The index is skipped for a sharper reason than caution:
455            // `.refs/{oid}/{org}/{repo}` ends in a repository name, so reading one
456            // as a marker would file that name as an oid somebody claims.
457            if entry.key.starts_with(".incoming/")
458                || entry.key.starts_with(".locks/")
459                || entry.key.starts_with(".refs/")
460                || entry.key.starts_with(".probe/")
461            {
462                continue;
463            }
464
465            let Some(oid) = entry.key.rsplit('/').next().map(str::to_owned) else {
466                continue;
467            };
468
469            markers.push(entry.key.clone());
470
471            if entry.key.starts_with(&ours) {
472                mine.push((entry, oid));
473            } else {
474                claimed_elsewhere.insert(oid);
475            }
476        }
477
478        // Before anything is deleted, so the index never gains a ref for a marker
479        // this sweep is about to drop. Built from the listing already paid for,
480        // and only when that listing finished: an index built from half a bucket
481        // would be missing holders, which is the one direction it must never
482        // drift in.
483        //
484        // A failure is not fatal. The listing above has already answered the
485        // question correctly on its own, so collection proceeds and the next
486        // sweep reads the bucket again.
487        if !dry_run
488            && listing.complete
489            && let Err(error) = refs::backfill(&self.keys, &markers).await
490        {
491            tracing::warn!(
492                %error,
493                "the claim index could not be built, so the next sweep reads the bucket again"
494            );
495        }
496
497        for (entry, oid) in Self::droppable(mine, retained, grace, &mut report) {
498            // Only what this call actually frees is counted. Another repository
499            // holding the same bytes means dropping this marker frees nothing,
500            // and a dry run that said otherwise would promise space it cannot
501            // deliver.
502            let frees = listing.complete && !claimed_elsewhere.contains(&oid);
503            let size = sizes.get(&oid).copied().unwrap_or_default();
504
505            if dry_run {
506                if frees {
507                    report.bytes += size;
508                }
509                continue;
510            }
511
512            self.keys.delete(&entry.key).await?;
513
514            if let Err(error) = self.keys.delete(&refs::key(ns, &oid)).await {
515                tracing::warn!(%error, oid, "a dropped marker left its index entry behind");
516            }
517
518            // Counted only when this call is the one that removed them, so two
519            // repositories letting go at once cannot each claim the same space.
520            if frees && self.keys.delete(&Self::content_key(&oid)).await? {
521                report.bytes += size;
522            }
523        }
524
525        Ok(report)
526    }
527
528    // What the bucket holds for this repository, counted from its markers and
529    // the content they point at. The markers are empty, so their own size says
530    // nothing — this is a listing plus one head per object, which is why the
531    // figure is cached the same way the local one is.
532    pub async fn usage_of(&self, ns: &Namespace) -> (u64, u64) {
533        let prefix = Self::own_prefix(ns);
534        let mut objects = 0;
535        let mut bytes = 0;
536
537        for oid in self.list(&prefix).await {
538            objects += 1;
539            bytes += self.size_of(&oid).await.unwrap_or_default();
540        }
541
542        (objects, bytes)
543    }
544
545    async fn list(&self, prefix: &str) -> Vec<String> {
546        // A capacity figure that silently reads zero is worse than one that is
547        // missing, because it looks like an answer.
548        let keys = match self.keys.keys(prefix).await {
549            Ok(keys) => keys,
550            Err(error) => {
551                tracing::warn!(%error, "the object store could not be listed");
552                return Vec::new();
553            }
554        };
555
556        keys.into_iter()
557            .filter_map(|key| key.rsplit('/').next().map(str::to_owned))
558            .filter(|oid| crate::storage::LocalStore::validate_oid(oid).is_ok())
559            .collect()
560    }
561}
562
563#[cfg(test)]
564pub(crate) mod tests;