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(super) fn keyring(&self) -> Option<&std::sync::Arc<crypt::Keyring>> {
190 self.keys.as_ref()
191 }
192
193 pub fn encrypts(&self) -> bool {
194 self.keys.is_some()
195 }
196
197 pub fn validate_oid(oid: &str) -> Result<(), Error> {
198 let well_formed = oid.len() == 64
199 && oid
200 .bytes()
201 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
202
203 well_formed.then_some(()).ok_or(Error::MalformedOid)
204 }
205
206 fn object_path(&self, ns: &Namespace, oid: &str) -> PathBuf {
207 self.root
208 .join(ns.org())
209 .join(ns.repo())
210 .join(&oid[0..2])
211 .join(&oid[2..4])
212 .join(oid)
213 }
214
215 fn content_path(&self, oid: &str) -> PathBuf {
216 self.root
217 .join(".content")
218 .join(&oid[0..2])
219 .join(&oid[2..4])
220 .join(oid)
221 }
222
223 pub fn scans(&self) -> u64 {
224 self.scans.load(Ordering::Relaxed)
225 }
226
227 pub async fn writable(&self) -> Result<(), Error> {
228 fs::create_dir_all(&self.root).await?;
229
230 let ticket = self.counter.fetch_add(1, Ordering::Relaxed);
231 let probe = self.root.join(format!(".readiness.{ticket}"));
232
233 fs::write(&probe, b"").await?;
234 fs::remove_file(&probe).await?;
235
236 Ok(())
237 }
238
239 pub async fn exists(&self, ns: &Namespace, oid: &str) -> bool {
240 Self::validate_oid(oid).is_ok() && fs::metadata(self.object_path(ns, oid)).await.is_ok()
241 }
242
243 pub async fn open(&self, ns: &Namespace, oid: &str) -> Result<Object, Error> {
244 Self::validate_oid(oid)?;
245 let path = self.object_path(ns, oid);
246 let file = fs::File::open(&path).await.map_err(|_| Error::NotFound)?;
247 let on_disk = file.metadata().await?.len();
248
249 match codec::Framed::open(
250 codec::Reader::File(file),
251 on_disk,
252 self.keys.as_deref(),
253 oid,
254 )
255 .await?
256 {
257 Some(framed) => Ok(Object::Framed(framed)),
258 None => Ok(Object::Raw {
259 file: fs::File::open(&path).await.map_err(|_| Error::NotFound)?,
260 size: on_disk,
261 }),
262 }
263 }
264
265 pub async fn stage<S, E>(
271 &self,
272 ns: &Namespace,
273 oid: &str,
274 expected_size: Option<u64>,
275 budget: Option<Budget>,
276 mut chunks: S,
277 ) -> Result<Staged, Error>
278 where
279 S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
280 E: std::error::Error + Send + Sync + 'static,
281 {
282 Self::validate_oid(oid)?;
283
284 if let Some(limit) = self.max_object_size
285 && expected_size.is_some_and(|declared| declared > limit)
286 {
287 return Err(Error::TooLarge { limit });
288 }
289
290 let path = self.object_path(ns, oid);
291 let parent = path.parent().expect("object paths always have a parent");
292 fs::create_dir_all(parent).await?;
293
294 let fresh = fs::metadata(&path).await.is_err();
297 let staged = self.staging_path(parent, oid);
298
299 match self.stream_to(&staged, oid, budget, &mut chunks).await {
300 Ok((digest, written)) => {
301 if let Err(error) = Self::agrees(oid, expected_size, &digest, written) {
302 let _ = fs::remove_file(&staged).await;
303 return Err(error);
304 }
305
306 Ok(Staged {
307 path: staged,
308 destination: path,
309 written,
310 fresh,
311 })
312 }
313 Err(error) => {
314 let _ = fs::remove_file(&staged).await;
315 Err(error)
316 }
317 }
318 }
319
320 fn agrees(
321 oid: &str,
322 expected_size: Option<u64>,
323 digest: &str,
324 written: u64,
325 ) -> Result<(), Error> {
326 if let Some(declared) = expected_size.filter(|declared| *declared != written) {
327 return Err(Error::SizeMismatch {
328 declared,
329 actual: written,
330 });
331 }
332
333 if digest != oid {
334 return Err(Error::OidMismatch {
335 declared: oid.to_owned(),
336 actual: digest.to_owned(),
337 });
338 }
339
340 Ok(())
341 }
342
343 pub async fn write<S, E>(
344 &self,
345 ns: &Namespace,
346 oid: &str,
347 expected_size: Option<u64>,
348 budget: Option<Budget>,
349 chunks: S,
350 ) -> Result<u64, Error>
351 where
352 S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
353 E: std::error::Error + Send + Sync + 'static,
354 {
355 let staged = self.stage(ns, oid, expected_size, budget, chunks).await?;
356
357 self.link_or_move(&staged.path, &staged.destination, oid)
358 .await?;
359
360 if staged.fresh {
361 self.stored(ns, staged.written).await;
362 }
363
364 Ok(staged.written)
365 }
366
367 fn staging_path(&self, parent: &Path, oid: &str) -> PathBuf {
368 let ticket = self.counter.fetch_add(1, Ordering::Relaxed);
369 parent.join(format!("{oid}.{ticket}.part"))
370 }
371
372 async fn stream_to<S, E>(
373 &self,
374 staged: &Path,
375 oid: &str,
376 budget: Option<Budget>,
377 chunks: &mut S,
378 ) -> Result<(String, u64), Error>
379 where
380 S: Stream<Item = Result<axum::body::Bytes, E>> + Unpin,
381 E: std::error::Error + Send + Sync + 'static,
382 {
383 let file = fs::File::create(staged).await?;
384 let mut sink = match (self.compression, self.keys.as_deref()) {
388 (None, None) => Sink::Raw(file),
389 (level, keys) => Sink::Framed(Box::new(
390 codec::Writer::open(file, level, keys.map(crypt::Keyring::writing), oid).await?,
391 )),
392 };
393 let mut hasher = Sha256::new();
394 let mut written = 0u64;
395
396 while let Some(chunk) = chunks.next().await {
397 let chunk = chunk.map_err(std::io::Error::other)?;
398 hasher.update(&chunk);
399 written += chunk.len() as u64;
400
401 if let Some(limit) = self.max_object_size.filter(|limit| written > *limit) {
406 return Err(Error::TooLarge { limit });
407 }
408
409 if let Some(budget) = budget.filter(|budget| budget.exceeded_by(written)) {
410 return Err(budget.refusal());
411 }
412
413 sink.write(&chunk).await?;
414 }
415
416 sink.finish().await?;
417
418 Ok((hex::encode(hasher.finalize()), written))
419 }
420
421 async fn link_or_move(&self, staged: &Path, final_path: &Path, oid: &str) -> Result<(), Error> {
428 let content = self.content_path(oid);
429 let parent = content.parent().expect("content paths have a parent");
430 fs::create_dir_all(parent).await?;
431
432 if fs::metadata(&content).await.is_err() {
433 fs::rename(staged, &content).await?;
434 }
435
436 match self.link(&content, final_path).await {
437 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
443 fs::rename(staged, &content).await?;
444 self.link(&content, final_path).await?;
445 }
446 outcome => outcome?,
447 }
448
449 let _ = fs::remove_file(staged).await;
450 Ok(())
451 }
452
453 async fn link(&self, content: &Path, final_path: &Path) -> Result<(), std::io::Error> {
454 let from = content.to_path_buf();
455 let to = final_path.to_path_buf();
456 let linked = tokio::task::spawn_blocking(move || std::fs::hard_link(&from, &to))
457 .await
458 .map_err(std::io::Error::other)?;
459
460 match linked {
461 Ok(()) => Ok(()),
462 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
463 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Err(error),
464 Err(_) => fs::copy(content, final_path).await.map(|_| ()),
468 }
469 }
470}