1mod backend;
2mod codec;
3pub mod crypt;
4mod dedupe;
5mod rewrite;
6pub mod s3;
7mod staging;
8mod sweep;
9mod verify;
10mod walk;
11
12#[cfg(test)]
13mod tests;
14
15use std::collections::HashMap;
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
60pub struct Staged {
62 pub path: PathBuf,
63 destination: PathBuf,
64 pub written: u64,
65 fresh: bool,
66}
67
68pub 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#[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
147pub struct LocalStore {
148 root: PathBuf,
149 counter: AtomicU64,
150 usage: Mutex<Option<(Instant, u64, u64)>>,
151 per_namespace: Mutex<HashMap<String, (Instant, u64, u64)>>,
152 scans: AtomicU64,
153 max_object_size: Option<u64>,
154 compression: Option<i32>,
155 keys: Option<std::sync::Arc<crypt::Keyring>>,
158}
159
160impl LocalStore {
161 pub fn new(root: impl Into<PathBuf>) -> Self {
162 Self {
163 root: root.into(),
164 counter: AtomicU64::new(0),
165 usage: Mutex::new(None),
166 per_namespace: Mutex::new(HashMap::new()),
167 scans: AtomicU64::new(0),
168 max_object_size: None,
169 compression: None,
170 keys: None,
171 }
172 }
173
174 pub fn with_compression(mut self, level: Option<i32>) -> Self {
175 self.compression = level;
176 self
177 }
178
179 pub fn with_max_object_size(mut self, limit: Option<u64>) -> Self {
180 self.max_object_size = limit;
181 self
182 }
183
184 pub fn with_encryption(mut self, keys: Option<std::sync::Arc<crypt::Keyring>>) -> Self {
185 self.keys = keys;
186 self
187 }
188
189 pub fn encrypts(&self) -> bool {
190 self.keys.is_some()
191 }
192
193 pub fn validate_oid(oid: &str) -> Result<(), Error> {
194 let well_formed = oid.len() == 64
195 && oid
196 .bytes()
197 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
198
199 well_formed.then_some(()).ok_or(Error::MalformedOid)
200 }
201
202 fn object_path(&self, ns: &Namespace, oid: &str) -> PathBuf {
203 self.root
204 .join(ns.org())
205 .join(ns.repo())
206 .join(&oid[0..2])
207 .join(&oid[2..4])
208 .join(oid)
209 }
210
211 fn content_path(&self, oid: &str) -> PathBuf {
212 self.root
213 .join(".content")
214 .join(&oid[0..2])
215 .join(&oid[2..4])
216 .join(oid)
217 }
218
219 pub fn scans(&self) -> u64 {
220 self.scans.load(Ordering::Relaxed)
221 }
222
223 pub async fn writable(&self) -> Result<(), Error> {
224 fs::create_dir_all(&self.root).await?;
225
226 let ticket = self.counter.fetch_add(1, Ordering::Relaxed);
227 let probe = self.root.join(format!(".readiness.{ticket}"));
228
229 fs::write(&probe, b"").await?;
230 fs::remove_file(&probe).await?;
231
232 Ok(())
233 }
234
235 pub async fn exists(&self, ns: &Namespace, oid: &str) -> bool {
236 Self::validate_oid(oid).is_ok() && fs::metadata(self.object_path(ns, oid)).await.is_ok()
237 }
238
239 pub async fn open(&self, ns: &Namespace, oid: &str) -> Result<Object, Error> {
240 Self::validate_oid(oid)?;
241 let path = self.object_path(ns, oid);
242 let file = fs::File::open(&path).await.map_err(|_| Error::NotFound)?;
243 let on_disk = file.metadata().await?.len();
244
245 match codec::Framed::open(file, on_disk, self.keys.as_deref(), oid).await? {
246 Some(framed) => Ok(Object::Framed(framed)),
247 None => Ok(Object::Raw {
248 file: fs::File::open(&path).await.map_err(|_| Error::NotFound)?,
249 size: on_disk,
250 }),
251 }
252 }
253
254 pub async fn stage<S, E>(
260 &self,
261 ns: &Namespace,
262 oid: &str,
263 expected_size: Option<u64>,
264 budget: Option<Budget>,
265 mut chunks: S,
266 ) -> Result<Staged, Error>
267 where
268 S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
269 E: std::error::Error + Send + Sync + 'static,
270 {
271 Self::validate_oid(oid)?;
272
273 if let Some(limit) = self.max_object_size
274 && expected_size.is_some_and(|declared| declared > limit)
275 {
276 return Err(Error::TooLarge { limit });
277 }
278
279 let path = self.object_path(ns, oid);
280 let parent = path.parent().expect("object paths always have a parent");
281 fs::create_dir_all(parent).await?;
282
283 let fresh = fs::metadata(&path).await.is_err();
286 let staged = self.staging_path(parent, oid);
287
288 match self.stream_to(&staged, oid, budget, &mut chunks).await {
289 Ok((digest, written)) => {
290 if let Err(error) = Self::agrees(oid, expected_size, &digest, written) {
291 let _ = fs::remove_file(&staged).await;
292 return Err(error);
293 }
294
295 Ok(Staged {
296 path: staged,
297 destination: path,
298 written,
299 fresh,
300 })
301 }
302 Err(error) => {
303 let _ = fs::remove_file(&staged).await;
304 Err(error)
305 }
306 }
307 }
308
309 fn agrees(
310 oid: &str,
311 expected_size: Option<u64>,
312 digest: &str,
313 written: u64,
314 ) -> Result<(), Error> {
315 if let Some(declared) = expected_size.filter(|declared| *declared != written) {
316 return Err(Error::SizeMismatch {
317 declared,
318 actual: written,
319 });
320 }
321
322 if digest != oid {
323 return Err(Error::OidMismatch {
324 declared: oid.to_owned(),
325 actual: digest.to_owned(),
326 });
327 }
328
329 Ok(())
330 }
331
332 pub async fn write<S, E>(
333 &self,
334 ns: &Namespace,
335 oid: &str,
336 expected_size: Option<u64>,
337 budget: Option<Budget>,
338 chunks: S,
339 ) -> Result<u64, Error>
340 where
341 S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
342 E: std::error::Error + Send + Sync + 'static,
343 {
344 let staged = self.stage(ns, oid, expected_size, budget, chunks).await?;
345
346 self.link_or_move(&staged.path, &staged.destination, oid)
347 .await?;
348
349 if staged.fresh {
350 self.stored(ns, staged.written).await;
351 }
352
353 Ok(staged.written)
354 }
355
356 fn staging_path(&self, parent: &Path, oid: &str) -> PathBuf {
357 let ticket = self.counter.fetch_add(1, Ordering::Relaxed);
358 parent.join(format!("{oid}.{ticket}.part"))
359 }
360
361 async fn stream_to<S, E>(
362 &self,
363 staged: &Path,
364 oid: &str,
365 budget: Option<Budget>,
366 chunks: &mut S,
367 ) -> Result<(String, u64), Error>
368 where
369 S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
370 E: std::error::Error + Send + Sync + 'static,
371 {
372 let file = fs::File::create(staged).await?;
373 let mut sink = match (self.compression, self.keys.as_deref()) {
377 (None, None) => Sink::Raw(file),
378 (level, keys) => Sink::Framed(Box::new(
379 codec::Writer::open(file, level, keys.map(crypt::Keyring::writing), oid).await?,
380 )),
381 };
382 let mut hasher = Sha256::new();
383 let mut written = 0u64;
384
385 while let Some(chunk) = chunks.next().await {
386 let chunk = chunk.map_err(std::io::Error::other)?;
387 hasher.update(&chunk);
388 written += chunk.len() as u64;
389
390 if let Some(limit) = self.max_object_size.filter(|limit| written > *limit) {
395 return Err(Error::TooLarge { limit });
396 }
397
398 if let Some(budget) = budget.filter(|budget| budget.exceeded_by(written)) {
399 return Err(budget.refusal());
400 }
401
402 sink.write(&chunk).await?;
403 }
404
405 sink.finish().await?;
406
407 Ok((hex::encode(hasher.finalize()), written))
408 }
409
410 async fn link_or_move(&self, staged: &Path, final_path: &Path, oid: &str) -> Result<(), Error> {
417 let content = self.content_path(oid);
418 let parent = content.parent().expect("content paths have a parent");
419 fs::create_dir_all(parent).await?;
420
421 if fs::metadata(&content).await.is_err() {
422 fs::rename(staged, &content).await?;
423 }
424
425 match self.link(&content, final_path).await {
426 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
432 fs::rename(staged, &content).await?;
433 self.link(&content, final_path).await?;
434 }
435 outcome => outcome?,
436 }
437
438 let _ = fs::remove_file(staged).await;
439 Ok(())
440 }
441
442 async fn link(&self, content: &Path, final_path: &Path) -> Result<(), std::io::Error> {
443 let from = content.to_path_buf();
444 let to = final_path.to_path_buf();
445 let linked = tokio::task::spawn_blocking(move || std::fs::hard_link(&from, &to))
446 .await
447 .map_err(std::io::Error::other)?;
448
449 match linked {
450 Ok(()) => Ok(()),
451 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
452 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Err(error),
453 Err(_) => fs::copy(content, final_path).await.map(|_| ()),
457 }
458 }
459}