lfsx_server/storage/s3.rs
1pub(crate) mod collect;
2pub(crate) mod keyspace;
3pub(crate) mod multipart;
4pub(crate) mod probe;
5pub(crate) mod refs;
6pub(crate) mod sizes;
7pub(crate) mod usage;
8
9use std::time::Duration;
10
11use axum::body::Bytes;
12use futures_util::Stream;
13
14use base64::Engine;
15
16use crate::error::Error;
17use crate::namespace::Namespace;
18use crate::oid::Oid;
19use crate::storage::Reclaimed;
20
21pub(crate) use keyspace::S3Keys;
22pub use keyspace::{Keyspace, Presigned};
23
24// Enough to hide the round trips a bucket charges for without becoming a burst
25// the store answers with 503, and the same figure the batch endpoint settled on
26// for the same reason.
27const SIZES_AT_ONCE: usize = 16;
28
29pub struct S3Config {
30 pub endpoint: String,
31 pub bucket: String,
32 pub region: String,
33 pub access_key: String,
34 pub secret_key: String,
35 pub path_style: bool,
36 // How long a signature is good for. It is the same number the batch
37 // response advertises as `expires_in`, because a client told it has half an
38 // hour and handed a URL that dies in five minutes will fail a resume it had
39 // every reason to expect to work.
40 pub lifetime: Duration,
41}
42
43// The same layout as the local store, for the same reasons. The bytes live once
44// under a key derived from their digest, and a repository that holds them owns
45// an empty marker beside it, the object store's answer to a hard link. It is
46// what keeps two projects sharing an asset pack from paying twice, and what
47// stops a repository reading an object it never pushed: the marker is the proof
48// of possession, and it is the only thing the permission check consults.
49//
50// Everything below is object semantics. What it takes to talk to the store at
51// all (signing, retrying, listing, the client) is the keyspace underneath.
52#[derive(Clone)]
53pub struct S3Store {
54 keys: Keyspace,
55 redirect: bool,
56}
57
58impl S3Store {
59 pub fn new(keys: Keyspace, redirect: bool) -> Self {
60 Self { keys, redirect }
61 }
62
63 fn content_key(oid: &Oid) -> String {
64 let (first, second) = oid.fanout();
65 format!(".content/{first}/{second}/{oid}")
66 }
67
68 // Where a client uploads to when the bytes never pass through this server.
69 // Per repository on purpose: the shared content key would take bytes from
70 // anyone allowed to write, and then nothing distinguishes a repository that
71 // uploaded an object from one that merely knew its digest. A key only this
72 // repository was handed a signature for is the proof of possession that the
73 // marker stands for everywhere else.
74 fn incoming_key(ns: &Namespace, oid: &Oid) -> String {
75 let (first, second) = oid.fanout();
76 format!(
77 ".incoming/{}/{}/{first}/{second}/{oid}",
78 ns.org(),
79 ns.repo()
80 )
81 }
82
83 fn marker_key(ns: &Namespace, oid: &Oid) -> String {
84 let (first, second) = oid.fanout();
85 format!("{}/{}/{first}/{second}/{oid}", ns.org(), ns.repo())
86 }
87
88 fn own_prefix(ns: &Namespace) -> String {
89 format!("{}/{}/", ns.org(), ns.repo())
90 }
91
92 pub async fn reachable(&self) -> Result<(), Error> {
93 self.keys.reachable().await
94 }
95
96 pub async fn exists(&self, ns: &Namespace, oid: &Oid) -> bool {
97 self.keys.head(&Self::marker_key(ns, oid)).await.is_ok()
98 }
99
100 pub async fn size_of(&self, oid: &Oid) -> Result<u64, Error> {
101 self.keys.head(&Self::content_key(oid)).await
102 }
103
104 // A download is streamed through this server rather than redirected, so the
105 // features that live in the byte path (the counters, the ranges, and the
106 // compression that will follow) keep working. The pre-signed redirect is a
107 // separate mode for operators who would rather spend the object store's
108 // bandwidth than their own.
109 pub async fn read(
110 &self,
111 oid: &Oid,
112 start: u64,
113 length: u64,
114 ) -> Result<impl Stream<Item = Result<Bytes, reqwest::Error>> + use<>, Error> {
115 self.keys
116 .get_range(&Self::content_key(oid), start, length)
117 .await
118 }
119
120 // A URL the client fetches from the bucket directly, so the bytes never
121 // cross this server. Whether the caller is entitled to them has already been
122 // settled by the marker before this is called: the signature is scoped to
123 // one content key and expires, and it grants nothing the batch response was
124 // not about to grant anyway.
125 pub fn presigned_download(&self, oid: &Oid) -> Option<String> {
126 if !self.redirect {
127 return None;
128 }
129
130 self.keys.signed_download(&Self::content_key(oid))
131 }
132
133 // A URL the client PUTs the object to, and the headers it has to send with
134 // it. The digest is bound into the signature, so the store refuses anything
135 // that does not hash to the object it was signed for: a client with this URL
136 // cannot put arbitrary bytes anywhere, which is what makes handing one out
137 // safe at all.
138 //
139 // None above the single-request ceiling, and that is not a refusal: the
140 // object falls back to coming through this server, which sends it in parts.
141 // A client cannot do the same, because the `basic` transfer adapter every
142 // git-lfs speaks does one PUT to one href and has nowhere to put a second.
143 // So the ceiling multipart removes for the streamed path is real and
144 // permanent for this one, and the only question is whether the client learns
145 // it now or after uploading five gigabytes.
146 //
147 // It also keeps `adopt` honest: `CopyObject` stops at the same 5 GiB, and
148 // nothing can reach `.incoming/` above it while this holds.
149 pub fn presigned_upload(&self, ns: &Namespace, oid: &Oid, size: u64) -> Option<Presigned> {
150 if !self.redirect || size > multipart::SINGLE_PUT_CEILING {
151 return None;
152 }
153
154 let digest =
155 base64::engine::general_purpose::STANDARD.encode(hex::decode(oid.as_str()).ok()?);
156
157 self.keys
158 .signed_upload(&Self::incoming_key(ns, oid), &digest)
159 }
160
161 // How big the object a client uploaded actually is, which is the first thing
162 // this server learns about it: nothing measured the bytes on the way past.
163 pub async fn uploaded_size(&self, ns: &Namespace, oid: &Oid) -> Result<u64, Error> {
164 self.keys.head(&Self::incoming_key(ns, oid)).await
165 }
166
167 // Take an upload that landed under this repository's own key into the shared
168 // keyspace. The bytes are already known to hash to the oid, because the store
169 // refused everything else.
170 pub async fn adopt(&self, ns: &Namespace, oid: &Oid, size: u64) -> Result<(), Error> {
171 let incoming = Self::incoming_key(ns, oid);
172 let content = Self::content_key(oid);
173
174 // First, before anything here so much as looks at the content.
175 //
176 // The marker is the claim and the ref is the index of it, so a crash
177 // between the two has to leave a ref nobody claims rather than a claim
178 // nothing indexes: the first leaks an object, the second lets a later
179 // sweep free bytes this repository holds.
180 //
181 // Writing it up here rather than beside the marker costs nothing and buys
182 // the race below. A sweep asks the index one last time before deleting
183 // bytes, so a claim recorded before this repository even checked whether
184 // the content exists is a claim that sweep will see.
185 refs::write(&self.keys, ns, oid).await?;
186
187 // Already there means another repository pushed the same object, and the
188 // bytes are identical by construction.
189 if self.keys.head(&content).await.is_err() {
190 self.keys.copy(&incoming, &content).await?;
191 }
192
193 self.keys
194 .put(&Self::marker_key(ns, oid), Vec::new())
195 .await?;
196
197 sizes::write(&self.keys, ns, oid, size).await?;
198
199 // Leaving it would pay for the object twice. A failure here is not worth
200 // failing the push over: the object is adopted, and what is left is a key
201 // the operator can see.
202 if let Err(error) = self.keys.delete(&incoming).await {
203 tracing::warn!(%error, key = incoming, "an adopted upload could not be cleaned up");
204 }
205
206 Ok(())
207 }
208
209 // The upload has already been streamed to a staging file, hashed and checked
210 // against everything the server enforces, so that file is what goes up,
211 // streamed from disk rather than read into memory, because an object here is
212 // measured in gigabytes and the whole storage layer is built on holding at
213 // most a few megabytes of one at a time.
214 //
215 // The bytes go up once, keyed by their digest, and the marker records that
216 // this repository holds them. Content that is already there is skipped: the
217 // key would receive the same bytes it already has.
218 pub async fn store(
219 &self,
220 ns: &Namespace,
221 oid: &Oid,
222 staged: &std::path::Path,
223 ) -> Result<(), Error> {
224 // Before the content is even looked at, for the reason `adopt` gives:
225 // this is what a sweep re-reads before deleting bytes, so a claim
226 // recorded here cannot be missed by one that is already deciding.
227 refs::write(&self.keys, ns, oid).await?;
228
229 // Read here rather than inside the branch below, because the size index
230 // wants it whether or not these bytes are the ones that go up: an object
231 // another repository pushed first is still this repository's to account
232 // for.
233 let length = tokio::fs::metadata(staged).await?.len();
234
235 if self.keys.head(&Self::content_key(oid)).await.is_err() {
236 self.keys.put_file(&Self::content_key(oid), staged).await?;
237 }
238
239 self.keys
240 .put(&Self::marker_key(ns, oid), Vec::new())
241 .await?;
242
243 sizes::write(&self.keys, ns, oid, length).await
244 }
245
246 // What an interrupted upload leaves behind. A client can negotiate, PUT the
247 // object, and never report it: the bytes sit under its own upload key and
248 // nothing else will ever look at them. The local path has had a reclaimer for
249 // this since the beginning, and a bucket had none, so the cost was unbounded
250 // over time and invisible.
251 pub async fn reclaim_incoming(&self, older_than: Duration) -> Result<Reclaimed, Error> {
252 let mut reclaimed = Reclaimed::default();
253
254 // `.probe/` too. A startup probe draws a key nothing else uses so that no
255 // run can read another's leftovers, which means a run that dies before
256 // cleaning up leaves one behind rather than overwriting it. They are
257 // empty or nearly so, and this is already the sweep for writes nobody
258 // will ever come back for.
259 for prefix in [".incoming/", ".probe/"] {
260 for entry in self.keys.entries(prefix).await? {
261 // A slow client on a bad connection is not an abandoned one.
262 if entry.age().is_none_or(|age| age < older_than) {
263 continue;
264 }
265
266 if self.keys.delete(&entry.key).await.is_ok() {
267 reclaimed.files += 1;
268 reclaimed.bytes += entry.size;
269 }
270 }
271 }
272
273 Ok(reclaimed)
274 }
275}
276
277#[cfg(test)]
278pub(crate) mod tests;