Skip to main content

lfsx_server/storage/
mod.rs

1mod backend;
2mod codec;
3pub mod crypt;
4mod dedupe;
5mod rewrite;
6pub mod s3;
7mod staging;
8mod sweep;
9mod usage;
10mod verify;
11mod walk;
12
13#[cfg(test)]
14mod tests;
15
16use std::path::{Path, PathBuf};
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::time::Instant;
19
20use tokio::sync::Mutex;
21
22use futures_util::{Stream, StreamExt};
23use sha2::{Digest, Sha256};
24use tokio::fs;
25use tokio::io::AsyncWriteExt;
26
27use crate::error::Error;
28use crate::namespace::Namespace;
29
30pub use backend::Store;
31pub use dedupe::DedupeReport;
32use dedupe::shares_bytes_with;
33pub use rewrite::CompressReport;
34pub use verify::VerifyReport;
35
36enum Sink {
37    Raw(fs::File),
38    Framed(Box<codec::Writer>),
39}
40
41impl Sink {
42    async fn write(&mut self, chunk: &[u8]) -> Result<(), Error> {
43        match self {
44            Self::Raw(file) => Ok(file.write_all(chunk).await?),
45            Self::Framed(writer) => writer.push(chunk).await,
46        }
47    }
48
49    async fn finish(self) -> Result<(), Error> {
50        match self {
51            Self::Raw(mut file) => {
52                file.flush().await?;
53                Ok(file.sync_all().await?)
54            }
55            Self::Framed(writer) => writer.finish().await,
56        }
57    }
58}
59
60// A transfer that has passed every check and is waiting to be put somewhere.
61pub struct Staged {
62    pub path: PathBuf,
63    destination: PathBuf,
64    pub written: u64,
65    fresh: bool,
66}
67
68// What a download reads from, whether or not the bytes on disk are the object.
69pub enum Object {
70    Raw {
71        file: fs::File,
72        size: u64,
73    },
74    Framed(codec::Framed),
75    Remote {
76        bucket: s3::S3Store,
77        oid: String,
78        size: u64,
79    },
80}
81
82impl Object {
83    pub fn size(&self) -> u64 {
84        match self {
85            Self::Raw { size, .. } => *size,
86            Self::Framed(framed) => framed.plaintext(),
87            Self::Remote { size, .. } => *size,
88        }
89    }
90
91    pub async fn stream(
92        self,
93        start: u64,
94        length: u64,
95    ) -> Result<futures_util::stream::BoxStream<'static, Result<axum::body::Bytes, Error>>, Error>
96    {
97        use futures_util::StreamExt;
98        use tokio::io::AsyncSeekExt;
99
100        match self {
101            Self::Raw { mut file, .. } => {
102                file.seek(std::io::SeekFrom::Start(start)).await?;
103                let reader =
104                    tokio_util::io::ReaderStream::new(tokio::io::AsyncReadExt::take(file, length));
105
106                Ok(reader.map(|chunk| chunk.map_err(Error::from)).boxed())
107            }
108            Self::Framed(framed) => Ok(framed.stream(start, length).boxed()),
109            Self::Remote { bucket, oid, .. } => {
110                let chunks = bucket.read(&oid, start, length).await?;
111
112                Ok(chunks
113                    .map(|chunk| {
114                        chunk.map_err(|error| Error::Storage(std::io::Error::other(error)))
115                    })
116                    .boxed())
117            }
118        }
119    }
120}
121pub use staging::{Reclaimed, reclaim};
122pub use sweep::SweepReport;
123
124// What is left of a repository's budget for one transfer. It travels with the
125// upload because a client that skips negotiation may also skip declaring a
126// size, and a budget checked once against a number the client chose is not a
127// budget.
128#[derive(Debug, Clone, Copy)]
129pub struct Budget {
130    pub used: u64,
131    pub limit: u64,
132}
133
134impl Budget {
135    pub fn exceeded_by(&self, arriving: u64) -> bool {
136        self.used + arriving > self.limit
137    }
138
139    pub fn refusal(&self) -> Error {
140        Error::OverQuota {
141            used: self.used,
142            limit: self.limit,
143        }
144    }
145}
146
147// What a write did, which the caller needs and the byte count alone does not
148// say: an object the repository already held costs it no room, so counting it
149// again would push a repository over a quota it never grew into.
150#[derive(Debug)]
151pub struct Written {
152    pub bytes: u64,
153    pub fresh: bool,
154}
155
156pub struct LocalStore {
157    root: PathBuf,
158    counter: AtomicU64,
159    usage: Mutex<Option<(Instant, u64, u64)>>,
160    scans: AtomicU64,
161    max_object_size: Option<u64>,
162    compression: Option<i32>,
163    // Shared rather than cloned: the staging store and the store proper are two
164    // handles onto one deployment's keys.
165    keys: Option<std::sync::Arc<crypt::Keyring>>,
166}
167
168impl LocalStore {
169    pub fn new(root: impl Into<PathBuf>) -> Self {
170        Self {
171            root: root.into(),
172            counter: AtomicU64::new(0),
173            usage: Mutex::new(None),
174            scans: AtomicU64::new(0),
175            max_object_size: None,
176            compression: None,
177            keys: None,
178        }
179    }
180
181    pub fn with_compression(mut self, level: Option<i32>) -> Self {
182        self.compression = level;
183        self
184    }
185
186    pub fn with_max_object_size(mut self, limit: Option<u64>) -> Self {
187        self.max_object_size = limit;
188        self
189    }
190
191    pub fn with_encryption(mut self, keys: Option<std::sync::Arc<crypt::Keyring>>) -> Self {
192        self.keys = keys;
193        self
194    }
195
196    pub(super) fn keyring(&self) -> Option<&std::sync::Arc<crypt::Keyring>> {
197        self.keys.as_ref()
198    }
199
200    pub fn encrypts(&self) -> bool {
201        self.keys.is_some()
202    }
203
204    pub fn validate_oid(oid: &str) -> Result<(), Error> {
205        let well_formed = oid.len() == 64
206            && oid
207                .bytes()
208                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
209
210        well_formed.then_some(()).ok_or(Error::MalformedOid)
211    }
212
213    fn object_path(&self, ns: &Namespace, oid: &str) -> PathBuf {
214        self.root
215            .join(ns.org())
216            .join(ns.repo())
217            .join(&oid[0..2])
218            .join(&oid[2..4])
219            .join(oid)
220    }
221
222    fn content_path(&self, oid: &str) -> PathBuf {
223        self.root
224            .join(".content")
225            .join(&oid[0..2])
226            .join(&oid[2..4])
227            .join(oid)
228    }
229
230    pub fn scans(&self) -> u64 {
231        self.scans.load(Ordering::Relaxed)
232    }
233
234    pub async fn writable(&self) -> Result<(), Error> {
235        fs::create_dir_all(&self.root).await?;
236
237        let ticket = self.counter.fetch_add(1, Ordering::Relaxed);
238        let probe = self.root.join(format!(".readiness.{ticket}"));
239
240        fs::write(&probe, b"").await?;
241        fs::remove_file(&probe).await?;
242
243        Ok(())
244    }
245
246    pub async fn exists(&self, ns: &Namespace, oid: &str) -> bool {
247        Self::validate_oid(oid).is_ok() && fs::metadata(self.object_path(ns, oid)).await.is_ok()
248    }
249
250    pub async fn open(&self, ns: &Namespace, oid: &str) -> Result<Object, Error> {
251        Self::validate_oid(oid)?;
252        let path = self.object_path(ns, oid);
253        let file = fs::File::open(&path).await.map_err(|_| Error::NotFound)?;
254        let on_disk = file.metadata().await?.len();
255
256        match codec::Framed::open(
257            codec::Reader::File(file),
258            on_disk,
259            self.keys.as_deref(),
260            oid,
261        )
262        .await?
263        {
264            Some(framed) => Ok(Object::Framed(framed)),
265            None => Ok(Object::Raw {
266                file: fs::File::open(&path).await.map_err(|_| Error::NotFound)?,
267                size: on_disk,
268            }),
269        }
270    }
271
272    // Everything a transfer has to survive before it counts as an object: the
273    // digest it claims, the size it declared, the ceiling on a single object and
274    // the repository's remaining budget. It ends on local disk whatever the
275    // backend is, because a bucket cannot be asked to hold bytes that might turn
276    // out to be the wrong ones.
277    pub async fn stage<S, E>(
278        &self,
279        ns: &Namespace,
280        oid: &str,
281        expected_size: Option<u64>,
282        budget: Option<Budget>,
283        mut chunks: S,
284    ) -> Result<Staged, Error>
285    where
286        S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
287        E: std::error::Error + Send + Sync + 'static,
288    {
289        Self::validate_oid(oid)?;
290
291        if let Some(limit) = self.max_object_size
292            && expected_size.is_some_and(|declared| declared > limit)
293        {
294            return Err(Error::TooLarge { limit });
295        }
296
297        let path = self.object_path(ns, oid);
298        let parent = path.parent().expect("object paths always have a parent");
299        fs::create_dir_all(parent).await?;
300
301        // A retried transfer of an object this repository already holds costs it
302        // no room, so it must not count against the budget a second time.
303        let fresh = fs::metadata(&path).await.is_err();
304        let staged = self.staging_path(parent, oid);
305
306        match self.stream_to(&staged, oid, budget, &mut chunks).await {
307            Ok((digest, written)) => {
308                if let Err(error) = Self::agrees(oid, expected_size, &digest, written) {
309                    let _ = fs::remove_file(&staged).await;
310                    return Err(error);
311                }
312
313                Ok(Staged {
314                    path: staged,
315                    destination: path,
316                    written,
317                    fresh,
318                })
319            }
320            Err(error) => {
321                let _ = fs::remove_file(&staged).await;
322                Err(error)
323            }
324        }
325    }
326
327    fn agrees(
328        oid: &str,
329        expected_size: Option<u64>,
330        digest: &str,
331        written: u64,
332    ) -> Result<(), Error> {
333        if let Some(declared) = expected_size.filter(|declared| *declared != written) {
334            return Err(Error::SizeMismatch {
335                declared,
336                actual: written,
337            });
338        }
339
340        if digest != oid {
341            return Err(Error::OidMismatch {
342                declared: oid.to_owned(),
343                actual: digest.to_owned(),
344            });
345        }
346
347        Ok(())
348    }
349
350    pub async fn write<S, E>(
351        &self,
352        ns: &Namespace,
353        oid: &str,
354        expected_size: Option<u64>,
355        budget: Option<Budget>,
356        chunks: S,
357    ) -> Result<Written, Error>
358    where
359        S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
360        E: std::error::Error + Send + Sync + 'static,
361    {
362        let staged = self.stage(ns, oid, expected_size, budget, chunks).await?;
363
364        self.link_or_move(&staged.path, &staged.destination, oid)
365            .await?;
366
367        Ok(Written {
368            bytes: staged.written,
369            fresh: staged.fresh,
370        })
371    }
372
373    fn staging_path(&self, parent: &Path, oid: &str) -> PathBuf {
374        let ticket = self.counter.fetch_add(1, Ordering::Relaxed);
375        parent.join(format!("{oid}.{ticket}.part"))
376    }
377
378    async fn stream_to<S, E>(
379        &self,
380        staged: &Path,
381        oid: &str,
382        budget: Option<Budget>,
383        chunks: &mut S,
384    ) -> Result<(String, u64), Error>
385    where
386        S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
387        E: std::error::Error + Send + Sync + 'static,
388    {
389        let file = fs::File::create(staged).await?;
390        // The digest, the declared size and the budget are all counted on the
391        // plaintext going past, whatever the bytes look like once they land —
392        // so compression is a different sink, not a different path.
393        let mut sink = match (self.compression, self.keys.as_deref()) {
394            (None, None) => Sink::Raw(file),
395            (level, keys) => Sink::Framed(Box::new(
396                codec::Writer::open(file, level, keys.map(crypt::Keyring::writing), oid).await?,
397            )),
398        };
399        let mut hasher = Sha256::new();
400        let mut written = 0u64;
401
402        while let Some(chunk) = chunks.next().await {
403            let chunk = chunk.map_err(std::io::Error::other)?;
404            hasher.update(&chunk);
405            written += chunk.len() as u64;
406
407            // The declared size is a claim by the client, so the ceiling has to
408            // hold against a body that ignores it. Stopping at the chunk that
409            // crosses the line is the point: reading to the end to find out how
410            // big it was would be the outage this limit exists to prevent.
411            if let Some(limit) = self.max_object_size.filter(|limit| written > *limit) {
412                return Err(Error::TooLarge { limit });
413            }
414
415            if let Some(budget) = budget.filter(|budget| budget.exceeded_by(written)) {
416                return Err(budget.refusal());
417            }
418
419            sink.write(&chunk).await?;
420        }
421
422        sink.finish().await?;
423
424        Ok((hex::encode(hasher.finalize()), written))
425    }
426
427    // One copy of the bytes under .content, and a hard link per repository that
428    // holds them. Two projects sharing an asset pack cost the disk once, and the
429    // link count is the reference count — the filesystem does the bookkeeping, so
430    // nothing can leak a repository's contents to another and nothing needs a
431    // migration: objects already sitting at their repository path keep working as
432    // ordinary files with one link.
433    async fn link_or_move(&self, staged: &Path, final_path: &Path, oid: &str) -> Result<(), Error> {
434        let content = self.content_path(oid);
435        let parent = content.parent().expect("content paths have a parent");
436        fs::create_dir_all(parent).await?;
437
438        if fs::metadata(&content).await.is_err() {
439            fs::rename(staged, &content).await?;
440        }
441
442        match self.link(&content, final_path).await {
443            // The content was collected between finding it and linking to it:
444            // a concurrent retain on another repository dropped its last other
445            // reference. The staged copy is still here precisely for this, so
446            // put it back and link again rather than failing a push that did
447            // nothing wrong.
448            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
449                fs::rename(staged, &content).await?;
450                self.link(&content, final_path).await?;
451            }
452            outcome => outcome?,
453        }
454
455        let _ = fs::remove_file(staged).await;
456        Ok(())
457    }
458
459    async fn link(&self, content: &Path, final_path: &Path) -> Result<(), std::io::Error> {
460        let from = content.to_path_buf();
461        let to = final_path.to_path_buf();
462        let linked = tokio::task::spawn_blocking(move || std::fs::hard_link(&from, &to))
463            .await
464            .map_err(std::io::Error::other)?;
465
466        match linked {
467            Ok(()) => Ok(()),
468            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
469            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Err(error),
470            // A filesystem without hard links, or one crossing a device
471            // boundary: fall back to a full copy so the transfer still
472            // succeeds. The disk pays for it, the client never notices.
473            Err(_) => fs::copy(content, final_path).await.map(|_| ()),
474        }
475    }
476}