1 //! inf3r-blobs — the content store, the LRU, and the publish.2 //!3 //! A blob has a SHA-256 content address. The address is the name, so a blob is4 //! written once and read many times: two uploads of the same bytes are one5 //! blob (spec section 13).6 //!7 //! The store never removes a blob that a live job holds. `Blobs::hold` returns8 //! a token that the caller keeps for the life of the job; the LRU skips a held9 //! address.10 11 use std::collections::BTreeMap;12 use std::fmt;13 use std::io::{self, Cursor, Read, Write};14 use std::os::unix::fs::OpenOptionsExt;15 use std::path::{Path, PathBuf};16 use std::sync::{Arc, Mutex, MutexGuard, Weak};17 18 use inf3r_sha256::Sha256;19 pub use inf3r_sha256::{sha256, sha256_hex};20 21 /// 64 lowercase hex characters.22 pub type Hash = String;23 24 /// The reason a blob operation failed.25 #[derive(Clone, PartialEq, Eq, Debug)]26 pub enum BlobError {27 /// The address is not 64 lowercase hex characters.28 Address(String),29 /// The store has no such blob.30 Missing(Hash),31 /// The bytes do not have the address that the caller gave.32 Mismatch {33 /// The address that the caller gave.34 want: Hash,35 /// The address of the bytes that arrived.36 got: Hash,37 },38 /// The blob that the caller named is held by a live job.39 Held(Hash),40 /// The store is full and every blob is held.41 Full {42 /// Bytes that the store may hold.43 limit: u64,44 /// Bytes that it holds now.45 held: u64,46 },47 /// The bytes are larger than the whole store.48 TooLarge {49 /// Bytes that arrived.50 bytes: u64,51 /// Bytes that the store may hold.52 limit: u64,53 },54 /// The bytes are not the length that the caller declared.55 Length {56 /// The length that the caller declared.57 declared: u64,58 /// The bytes that arrived.59 got: u64,60 },61 /// An artifact names a descriptor that the terminal frame did not carry.62 Descriptor(u32),63 /// The filesystem failed.64 Io(String),65 }66 67 impl fmt::Display for BlobError {68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {69 match self {70 BlobError::Address(why) => write!(f, "bad address: {why}"),71 BlobError::Missing(hash) => write!(f, "no blob {hash}"),72 BlobError::Held(hash) => write!(f, "blob {hash} is held"),73 BlobError::Mismatch { want, got } => write!(f, "blob is {got}, not {want}"),74 BlobError::Full { limit, held } => {75 write!(f, "the store holds {held} of {limit} bytes")76 }77 BlobError::TooLarge { bytes, limit } => {78 write!(f, "{bytes} bytes do not fit a store of {limit}")79 }80 BlobError::Length { declared, got } => {81 write!(f, "the bytes are {got}, not the declared {declared}")82 }83 BlobError::Descriptor(index) => {84 write!(f, "artifact descriptor {index} is missing")85 }86 BlobError::Io(why) => write!(f, "{why}"),87 }88 }89 }90 91 impl std::error::Error for BlobError {}92 93 impl From<io::Error> for BlobError {94 fn from(why: io::Error) -> BlobError {95 BlobError::Io(why.to_string())96 }97 }98 99 /// What the store knows about one blob.100 #[derive(Clone, PartialEq, Eq, Debug)]101 pub struct Entry {102 /// The content address.103 pub hash: Hash,104 /// Bytes on disk.105 pub bytes: u64,106 /// The tick of the last read or write. The LRU order.107 pub tick: u64,108 /// Jobs that hold this blob.109 pub holds: u32,110 }111 112 /// A hold on one blob. The store does not remove a held blob until the hold113 /// drops.114 pub struct Hold {115 hash: Hash,116 store: Weak<Mutex<Blobs>>,117 }118 119 impl Hold {120 /// The address that this hold protects.121 pub fn hash(&self) -> &str {122 &self.hash123 }124 }125 126 impl fmt::Debug for Hold {127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {128 f.debug_struct("Hold").field("hash", &self.hash).finish()129 }130 }131 132 impl Drop for Hold {133 fn drop(&mut self) {134 let Some(store) = self.store.upgrade() else {135 return;136 };137 let mut store = lock(&store);138 store.release_hash(&self.hash);139 }140 }141 142 /// A content-addressed store in one directory.143 pub struct Blobs {144 dir: PathBuf,145 /// Bytes that the store may hold. It has no default; the operator or the146 /// free space of the filesystem gives it.147 limit: u64,148 entries: BTreeMap<Hash, Entry>,149 tick: u64,150 bytes: u64,151 }152 153 impl Blobs {154 /// Opens a store at `dir`, which must exist.155 ///156 /// `limit` is the number of bytes the store may hold.157 pub fn open(dir: impl Into<PathBuf>, limit: u64) -> Result<Blobs, BlobError> {158 let dir = dir.into();159 let mut store = Blobs {160 dir,161 limit,162 entries: BTreeMap::new(),163 tick: 0,164 bytes: 0,165 };166 store.scan()?;167 Ok(store)168 }169 170 /// The directory that this store owns.171 pub fn dir(&self) -> &Path {172 &self.dir173 }174 175 /// Bytes that the store holds.176 pub fn bytes(&self) -> u64 {177 self.bytes178 }179 180 /// Bytes that the store may hold.181 pub fn limit(&self) -> u64 {182 self.limit183 }184 185 /// Every blob, in address order.186 pub fn entries(&self) -> impl Iterator<Item = &Entry> {187 self.entries.values()188 }189 190 /// Reads the store from disk. A file whose name is not its address is not a191 /// blob, so it is ignored.192 fn scan(&mut self) -> Result<(), BlobError> {193 let read = match std::fs::read_dir(&self.dir) {194 Ok(read) => read,195 Err(why) if why.kind() == io::ErrorKind::NotFound => {196 return Err(BlobError::Io(format!(197 "{} does not exist",198 self.dir.display()199 )));200 }201 Err(why) => return Err(why.into()),202 };203 for item in read {204 let item = item?;205 let name = item.file_name().to_string_lossy().into_owned();206 if name.ends_with(".part") {207 // A crash can leave the temporary file of an unfinished write.208 // It has no address, so it is not a blob; remove it.209 let _ = std::fs::remove_file(item.path());210 continue;211 }212 if !is_hash(&name) {213 continue;214 }215 let bytes = item.metadata()?.len();216 self.tick += 1;217 self.bytes += bytes;218 self.entries.insert(219 name.clone(),220 Entry {221 hash: name,222 bytes,223 tick: self.tick,224 holds: 0,225 },226 );227 }228 Ok(())229 }230 231 /// The path of one address. The address is the file name, so a path never232 /// escapes the store: `is_hash` already refused anything that is not 64 hex233 /// characters.234 fn path_of(&self, hash: &str) -> PathBuf {235 self.dir.join(hash)236 }237 238 /// Adds bytes. The address is computed, never given.239 pub fn put(&mut self, bytes: &[u8]) -> Result<(Hash, bool), BlobError> {240 let mut reader = Cursor::new(bytes);241 let (hash, wrote, _) = self.put_stream(&mut reader, None)?;242 Ok((hash, wrote))243 }244 245 /// Adds bytes from a reader. The address is computed, never given.246 ///247 /// The bytes go to a temporary file as they arrive, so a 4K frame or a248 /// 60 s clip does not become a `Vec` first. The store limit is checked249 /// while the bytes are read; no whole input is ever held in memory.250 pub fn put_reader(&mut self, reader: &mut impl Read) -> Result<(Hash, bool), BlobError> {251 let (hash, wrote, _) = self.put_stream(reader, None)?;252 Ok((hash, wrote))253 }254 255 /// Adds exactly `len` bytes from a reader.256 ///257 /// A descriptor that ends before `len` or continues after it is refused.258 /// The terminal frame declares the length, so the store checks it.259 pub fn put_reader_len(260 &mut self,261 reader: &mut impl Read,262 len: u64,263 ) -> Result<(Hash, bool), BlobError> {264 let mut reader = reader.take(len.saturating_add(1));265 let (hash, wrote, _) = self.put_stream(&mut reader, Some(len))?;266 Ok((hash, wrote))267 }268 269 /// Reads a stream into a temporary file, hashes it, and moves it into the270 /// store. A duplicate address is not written twice.271 fn put_stream(272 &mut self,273 reader: &mut impl Read,274 declared: Option<u64>,275 ) -> Result<(Hash, bool, u64), BlobError> {276 let (temp, hash, size) = self.write_temp(reader, declared)?;277 if self.entries.contains_key(&hash) {278 let _ = std::fs::remove_file(&temp);279 self.touch(&hash);280 return Ok((hash, false, size));281 }282 if let Err(why) = self.make_room(size) {283 let _ = std::fs::remove_file(&temp);284 return Err(why);285 }286 // The rename is the publish. A reader sees the whole blob or none.287 if let Err(why) = std::fs::rename(&temp, self.path_of(&hash)) {288 let _ = std::fs::remove_file(&temp);289 return Err(why.into());290 }291 self.tick += 1;292 self.bytes += size;293 self.entries.insert(294 hash.clone(),295 Entry {296 hash: hash.clone(),297 bytes: size,298 tick: self.tick,299 holds: 0,300 },301 );302 Ok((hash, true, size))303 }304 305 /// Writes `reader` to a temporary file and returns its address.306 fn write_temp(307 &mut self,308 reader: &mut impl Read,309 declared: Option<u64>,310 ) -> Result<(PathBuf, Hash, u64), BlobError> {311 let temp = self.temp_path();312 let result = (|| {313 let mut file = std::fs::OpenOptions::new()314 .create_new(true)315 .write(true)316 .mode(0o600)317 .open(&temp)?;318 let mut digest = Sha256::new();319 let mut size = 0u64;320 let mut buf = [0u8; 64 << 10];321 loop {322 let n = match reader.read(&mut buf) {323 Ok(n) => n,324 Err(why) if why.kind() == io::ErrorKind::Interrupted => continue,325 Err(why) => return Err(why.into()),326 };327 if n == 0 {328 break;329 }330 size = size.saturating_add(n as u64);331 if let Some(declared) = declared332 && size > declared333 {334 return Err(BlobError::Length {335 declared,336 got: size,337 });338 }339 if size > self.limit {340 return Err(BlobError::TooLarge {341 bytes: size,342 limit: self.limit,343 });344 }345 file.write_all(&buf[..n])?;346 digest.update(&buf[..n]);347 }348 if let Some(declared) = declared349 && size != declared350 {351 return Err(BlobError::Length {352 declared,353 got: size,354 });355 }356 file.sync_all()?;357 Ok((temp.clone(), digest.finish_hex(), size))358 })();359 if result.is_err() {360 let _ = std::fs::remove_file(&temp);361 }362 result363 }364 365 fn temp_path(&mut self) -> PathBuf {366 let tick = self.next_tick();367 self.dir368 .join(format!(".upload-{}-{tick}.part", std::process::id()))369 }370 371 /// Adds bytes that a caller says have address `hash`.372 ///373 /// A plugin sends an artifact with a descriptor. The core reads it and374 /// checks that the bytes are the ones the plugin declared.375 pub fn publish(&mut self, hash: &str, bytes: &[u8]) -> Result<Hash, BlobError> {376 if !is_hash(hash) {377 return Err(BlobError::Address(hash.to_string()));378 }379 let got = sha256_hex(bytes);380 if got != hash {381 return Err(BlobError::Mismatch {382 want: hash.to_string(),383 got,384 });385 }386 let (hash, _) = self.put(bytes)?;387 Ok(hash)388 }389 390 /// The bytes of one blob, and a touch of its LRU order.391 pub fn get(&mut self, hash: &str) -> Result<Vec<u8>, BlobError> {392 if !self.entries.contains_key(hash) {393 return Err(BlobError::Missing(hash.to_string()));394 }395 let bytes = std::fs::read(self.path_of(hash))?;396 self.touch(hash);397 Ok(bytes)398 }399 400 /// A file of one blob, for the descriptor that the core hands to a plugin.401 ///402 /// The core opens the file and passes the descriptor. The plugin never sees403 /// a path (spec section 13, rule 2).404 pub fn file(&mut self, hash: &str) -> Result<std::fs::File, BlobError> {405 if !self.entries.contains_key(hash) {406 return Err(BlobError::Missing(hash.to_string()));407 }408 let file = std::fs::File::open(self.path_of(hash))?;409 self.touch(hash);410 Ok(file)411 }412 413 /// Protects one blob from the LRU until the returned hold drops.414 ///415 /// The hold names the store, so there is no release call to forget: the416 /// token's `Drop` is the release.417 pub fn hold(store: &Arc<Mutex<Blobs>>, hash: &str) -> Result<Hold, BlobError> {418 {419 let mut blobs = lock(store);420 if !blobs.entries.contains_key(hash) {421 return Err(BlobError::Missing(hash.to_string()));422 }423 let tick = blobs.next_tick();424 if let Some(entry) = blobs.entries.get_mut(hash) {425 entry.holds = entry.holds.saturating_add(1);426 entry.tick = tick;427 }428 }429 Ok(Hold {430 hash: hash.to_string(),431 store: Arc::downgrade(store),432 })433 }434 435 fn release_hash(&mut self, hash: &str) {436 if let Some(entry) = self.entries.get_mut(hash) {437 entry.holds = entry.holds.saturating_sub(1);438 }439 }440 441 /// Removes one blob that nothing holds.442 pub fn remove(&mut self, hash: &str) -> Result<(), BlobError> {443 let Some(entry) = self.entries.get(hash) else {444 return Err(BlobError::Missing(hash.to_string()));445 };446 if entry.holds > 0 {447 return Err(BlobError::Held(hash.to_string()));448 }449 std::fs::remove_file(self.path_of(hash))?;450 self.bytes = self.bytes.saturating_sub(entry.bytes);451 self.entries.remove(hash);452 Ok(())453 }454 455 /// Removes blobs until `want` more bytes fit, least recently used first.456 fn make_room(&mut self, want: u64) -> Result<(), BlobError> {457 while self.bytes.saturating_add(want) > self.limit {458 let victim = self459 .entries460 .values()461 .filter(|entry| entry.holds == 0)462 .min_by_key(|entry| entry.tick)463 .map(|entry| entry.hash.clone());464 match victim {465 Some(hash) => self.remove(&hash)?,466 None => {467 return Err(BlobError::Full {468 limit: self.limit,469 held: self.bytes,470 });471 }472 }473 }474 Ok(())475 }476 477 fn next_tick(&mut self) -> u64 {478 self.tick += 1;479 self.tick480 }481 482 fn touch(&mut self, hash: &str) {483 let tick = self.next_tick();484 if let Some(entry) = self.entries.get_mut(hash) {485 entry.tick = tick;486 }487 }488 }489 490 /// Whether `hash` is a SHA-256 address in its only spelling: 64 lowercase hex491 /// characters.492 pub fn is_hash(hash: &str) -> bool {493 hash.len() == 64494 && hash495 .bytes()496 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))497 }498 499 /// The path of a blob in a store, for a caller that must open it.500 pub fn path(dir: &Path, hash: &str) -> PathBuf {501 dir.join(hash)502 }503 504 fn lock<T>(store: &Mutex<T>) -> MutexGuard<'_, T> {505 store506 .lock()507 .unwrap_or_else(|poisoned| poisoned.into_inner())508 }