| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | |
|
| 20 | | use std::collections::BTreeMap; |
| 21 | | use std::fs; |
| 22 | | use std::io::{self, Read, Seek, SeekFrom, Write}; |
| 23 | | use std::ops::Range; |
| 24 | | use std::path::{Path, PathBuf}; |
| 25 | | use std::sync::Mutex; |
| 26 | | use std::time::{Duration, Instant}; |
| 27 | |
|
| 28 | |
|
| 29 | |
|
| 30 | |
|
| 31 | |
|
| 32 | |
|
| 33 | |
|
| 34 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 35 | | pub struct Version(pub String); |
| 36 | |
|
| 37 | |
|
| 38 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 39 | | pub struct Entry { |
| 40 | | pub key: String, |
| 41 | | pub size: u64, |
| 42 | | |
| 43 | | |
| 44 | | pub modified_ms: Option<u64>, |
| 45 | | } |
| 46 | |
|
| 47 | | #[derive(Debug, thiserror::Error)] |
| 48 | | pub enum Error { |
| 49 | | #[error("{0}: not in the store")] |
| 50 | | NotFound(String), |
| 51 | | #[error("{0}: already in the store")] |
| 52 | | Exists(String), |
| 53 | | #[error("{0}: changed since it was read")] |
| 54 | | Conflict(String), |
| 55 | | #[error("bad store key {0:?}: {1}")] |
| 56 | | Key(String, &'static str), |
| 57 | | #[error("{0}: busy (another writer holds it)")] |
| 58 | | Busy(String), |
| 59 | | #[error(transparent)] |
| 60 | | Io(#[from] io::Error), |
| 61 | | #[error("{0}")] |
| 62 | | Backend(String), |
| 63 | | } |
| 64 | |
|
| 65 | | pub type Result<T> = std::result::Result<T, Error>; |
| 66 | |
|
| 67 | |
|
| 68 | | pub const MAX_KEY_LEN: usize = 1024; |
| 69 | |
|
| 70 | |
|
| 71 | |
|
| 72 | |
|
| 73 | |
|
| 74 | 148846× | pub fn check_key(key: &str) -> Result<()> { |
| 75 | 148846× | let bad = |why| Error::Key(key.to_string(), why); |
| 76 | 148846× | if key.is_empty() { |
| 77 | 1× | return Err(bad("empty")); |
| 78 | 148845× | } |
| 79 | 148845× | if key.len() > MAX_KEY_LEN { |
| 80 | 1× | return Err(bad("longer than 1024 bytes")); |
| 81 | 148844× | } |
| 82 | 408226× | for seg in key.split('/') { |
| 83 | 408226× | if seg.is_empty() { |
| 84 | 4× | return Err(bad( |
| 85 | 4× | "an empty segment (a leading, trailing or doubled slash)", |
| 86 | 4× | )); |
| 87 | 408222× | } |
| 88 | 408222× | if seg == "." || seg == ".." { |
| 89 | 4× | return Err(bad("a . or .. segment")); |
| 90 | 408218× | } |
| 91 | 408218× | if !seg |
| 92 | 408218× | .bytes() |
| 93 | 9746316× | .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-') |
| 94 | | { |
| 95 | 3× | return Err(bad("a character outside A-Z a-z 0-9 . _ -")); |
| 96 | 408215× | } |
| 97 | | } |
| 98 | 148833× | Ok(()) |
| 99 | 148846× | } |
| 100 | |
|
| 101 | |
|
| 102 | |
|
| 103 | | pub trait Store: Send + Sync { |
| 104 | | |
| 105 | | fn describe(&self) -> String; |
| 106 | |
|
| 107 | | |
| 108 | |
|
| 109 | | fn has(&self, key: &str) -> Result<bool>; |
| 110 | | |
| 111 | | fn get(&self, key: &str) -> Result<Vec<u8>>; |
| 112 | | |
| 113 | | fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>>; |
| 114 | | |
| 115 | | |
| 116 | | fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()>; |
| 117 | | |
| 118 | | |
| 119 | | fn list(&self, prefix: &str) -> Result<Vec<Entry>>; |
| 120 | | |
| 121 | | fn delete(&self, key: &str) -> Result<()>; |
| 122 | | |
| 123 | | |
| 124 | 8× | fn stat(&self, key: &str) -> Result<Option<Entry>> { |
| 125 | 8× | Ok(self.list(key)?.into_iter().find(|e| e.key == key)) |
| 126 | 8× | } |
| 127 | | |
| 128 | | |
| 129 | | |
| 130 | 2× | fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> { |
| 131 | 6× | for (key, bytes) in objects { |
| 132 | 6× | match self.put_new(key, bytes) { |
| 133 | 6× | Ok(()) | Err(Error::Exists(_)) => {} |
| 134 | 0× | Err(e) => return Err(e), |
| 135 | | } |
| 136 | | } |
| 137 | 2× | Ok(()) |
| 138 | 2× | } |
| 139 | | |
| 140 | | |
| 141 | 39× | fn put_new_file(&self, key: &str, path: &Path) -> Result<()> { |
| 142 | 39× | self.put_new(key, &fs::read(path)?) |
| 143 | 39× | } |
| 144 | |
|
| 145 | | |
| 146 | |
|
| 147 | | |
| 148 | | |
| 149 | | fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>>; |
| 150 | | |
| 151 | | |
| 152 | | |
| 153 | | fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version>; |
| 154 | | } |
| 155 | |
|
| 156 | |
|
| 157 | |
|
| 158 | 2099× | fn content_version(bytes: &[u8]) -> Version { |
| 159 | 2099× | Version(blake3::hash(bytes).to_hex().to_string()) |
| 160 | 2099× | } |
| 161 | |
|
| 162 | 536× | fn check_expected(key: &str, current: Option<&Version>, expected: Option<&Version>) -> Result<()> { |
| 163 | 536× | if current == expected { |
| 164 | 428× | Ok(()) |
| 165 | | } else { |
| 166 | 108× | Err(Error::Conflict(key.to_string())) |
| 167 | | } |
| 168 | 536× | } |
| 169 | |
|
| 170 | |
|
| 171 | |
|
| 172 | |
|
| 173 | |
|
| 174 | |
|
| 175 | |
|
| 176 | |
|
| 177 | | pub struct LocalStore { |
| 178 | | root: PathBuf, |
| 179 | | } |
| 180 | |
|
| 181 | |
|
| 182 | |
|
| 183 | | const LOCK_STALE: Duration = Duration::from_secs(60); |
| 184 | | const LOCK_WAIT: Duration = Duration::from_secs(10); |
| 185 | |
|
| 186 | | impl LocalStore { |
| 187 | | |
| 188 | 3468× | pub fn open(root: impl Into<PathBuf>) -> Result<LocalStore> { |
| 189 | 3468× | let root = root.into(); |
| 190 | 3468× | fs::create_dir_all(&root)?; |
| 191 | 3468× | Ok(LocalStore { root }) |
| 192 | 3468× | } |
| 193 | |
|
| 194 | 1× | pub fn root(&self) -> &Path { |
| 195 | 1× | &self.root |
| 196 | 1× | } |
| 197 | |
|
| 198 | 141873× | fn path(&self, key: &str) -> Result<PathBuf> { |
| 199 | 141873× | check_key(key)?; |
| 200 | 141871× | Ok(self.root.join(key)) |
| 201 | 141873× | } |
| 202 | |
|
| 203 | 15452× | fn temp_beside(&self, path: &Path) -> PathBuf { |
| 204 | 15452× | let mut nonce = [0u8; 6]; |
| 205 | 15452× | rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut nonce); |
| 206 | 15452× | let name = path |
| 207 | 15452× | .file_name() |
| 208 | 15452× | .map(|n| n.to_string_lossy().into_owned()) |
| 209 | 15452× | .unwrap_or_default(); |
| 210 | 15452× | path.with_file_name(format!(".{name}.tmp-{}", hex::encode(nonce))) |
| 211 | 15452× | } |
| 212 | |
|
| 213 | 44210× | fn list_dir(&self, dir: &Path, rel: &str, prefix: &str, out: &mut Vec<Entry>) -> Result<()> { |
| 214 | 44210× | let entries = match fs::read_dir(dir) { |
| 215 | 44210× | Ok(e) => e, |
| 216 | 0× | Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), |
| 217 | 0× | Err(e) => return Err(e.into()), |
| 218 | | }; |
| 219 | 111184× | for entry in entries { |
| 220 | 111184× | let entry = entry?; |
| 221 | 111184× | let name = entry.file_name().to_string_lossy().into_owned(); |
| 222 | | |
| 223 | 111184× | if name.starts_with('.') { |
| 224 | 34× | continue; |
| 225 | 111150× | } |
| 226 | 111150× | let key = if rel.is_empty() { |
| 227 | 43425× | name.clone() |
| 228 | | } else { |
| 229 | 67725× | format!("{rel}/{name}") |
| 230 | | }; |
| 231 | 111150× | let ty = entry.file_type()?; |
| 232 | 111150× | if ty.is_dir() { |
| 233 | | |
| 234 | 65605× | let dir_prefix = format!("{key}/"); |
| 235 | 65605× | if prefix.starts_with(&dir_prefix) || dir_prefix.starts_with(prefix) { |
| 236 | 29572× | self.list_dir(&entry.path(), &key, prefix, out)?; |
| 237 | 36033× | } |
| 238 | 45545× | } else if ty.is_file() && key.starts_with(prefix) { |
| 239 | 31979× | let meta = entry.metadata()?; |
| 240 | 31979× | out.push(Entry { |
| 241 | 31979× | key, |
| 242 | 31979× | size: meta.len(), |
| 243 | 31979× | modified_ms: modified_ms(&meta), |
| 244 | 31979× | }); |
| 245 | 13566× | } |
| 246 | | } |
| 247 | 44210× | Ok(()) |
| 248 | 44210× | } |
| 249 | |
|
| 250 | | |
| 251 | | |
| 252 | 131× | fn lock(&self, key: &str, path: &Path) -> Result<PathBuf> { |
| 253 | 131× | let lock = path.with_file_name(format!( |
| 254 | | ".{}.lock", |
| 255 | 131× | path.file_name() |
| 256 | 131× | .map(|n| n.to_string_lossy().into_owned()) |
| 257 | 131× | .unwrap_or_default() |
| 258 | | )); |
| 259 | 131× | let started = Instant::now(); |
| 260 | | loop { |
| 261 | 132× | match fs::OpenOptions::new() |
| 262 | 132× | .write(true) |
| 263 | 132× | .create_new(true) |
| 264 | 132× | .open(&lock) |
| 265 | | { |
| 266 | 131× | Ok(mut f) => { |
| 267 | 131× | let _ = writeln!(f, "{}", std::process::id()); |
| 268 | 131× | return Ok(lock); |
| 269 | | } |
| 270 | 1× | Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { |
| 271 | 1× | if let Ok(m) = fs::metadata(&lock) { |
| 272 | 1× | let age = m.modified().ok().and_then(|t| t.elapsed().ok()); |
| 273 | 1× | if age.is_some_and(|a| a > LOCK_STALE) { |
| 274 | 1× | let _ = fs::remove_file(&lock); |
| 275 | 1× | continue; |
| 276 | 0× | } |
| 277 | 0× | } |
| 278 | 0× | if started.elapsed() > LOCK_WAIT { |
| 279 | 0× | return Err(Error::Busy(key.to_string())); |
| 280 | 0× | } |
| 281 | 0× | std::thread::sleep(Duration::from_millis(10)); |
| 282 | | } |
| 283 | 0× | Err(e) => return Err(e.into()), |
| 284 | | } |
| 285 | | } |
| 286 | 131× | } |
| 287 | | } |
| 288 | |
|
| 289 | |
|
| 290 | 31993× | fn modified_ms(meta: &fs::Metadata) -> Option<u64> { |
| 291 | 31993× | meta.modified() |
| 292 | 31993× | .ok() |
| 293 | 31993× | .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) |
| 294 | 31993× | .map(|d| d.as_millis() as u64) |
| 295 | 31993× | } |
| 296 | |
|
| 297 | |
|
| 298 | |
|
| 299 | |
|
| 300 | 15498× | fn place_new(tmp: &Path, path: &Path) -> io::Result<()> { |
| 301 | 15498× | match fs::hard_link(tmp, path) { |
| 302 | 0× | Err(e) if e.kind() == io::ErrorKind::PermissionDenied => rename_new(tmp, path), |
| 303 | 15498× | r => r, |
| 304 | | } |
| 305 | 15498× | } |
| 306 | |
|
| 307 | | #[cfg(any(target_os = "linux", target_os = "android"))] |
| 308 | 2× | fn rename_new(tmp: &Path, path: &Path) -> io::Result<()> { |
| 309 | | use std::ffi::CString; |
| 310 | | use std::os::unix::ffi::OsStrExt; |
| 311 | 2× | let from = CString::new(tmp.as_os_str().as_bytes())?; |
| 312 | 2× | let to = CString::new(path.as_os_str().as_bytes())?; |
| 313 | 2× | let r = unsafe { |
| 314 | 2× | libc::renameat2( |
| 315 | | libc::AT_FDCWD, |
| 316 | 2× | from.as_ptr(), |
| 317 | | libc::AT_FDCWD, |
| 318 | 2× | to.as_ptr(), |
| 319 | 2× | libc::RENAME_NOREPLACE as _, |
| 320 | | ) |
| 321 | | }; |
| 322 | 2× | if r == 0 { |
| 323 | 1× | Ok(()) |
| 324 | | } else { |
| 325 | 1× | Err(io::Error::last_os_error()) |
| 326 | | } |
| 327 | 2× | } |
| 328 | |
|
| 329 | | #[cfg(not(any(target_os = "linux", target_os = "android")))] |
| 330 | | fn rename_new(tmp: &Path, path: &Path) -> io::Result<()> { |
| 331 | | if path.exists() { |
| 332 | | return Err(io::ErrorKind::AlreadyExists.into()); |
| 333 | | } |
| 334 | | fs::rename(tmp, path) |
| 335 | | } |
| 336 | |
|
| 337 | | impl LocalStore { |
| 338 | | |
| 339 | | |
| 340 | 9605× | fn link_into_place(&self, key: &str, tmp: &Path, path: &Path) -> Result<()> { |
| 341 | 9605× | let linked = place_new(tmp, path); |
| 342 | 9605× | let _ = fs::remove_file(tmp); |
| 343 | 0× | match linked { |
| 344 | | Ok(()) => { |
| 345 | 9605× | if let Some(dir) = path.parent() { |
| 346 | 9605× | crate::durable::sync_dir(dir)?; |
| 347 | 0× | } |
| 348 | 9605× | Ok(()) |
| 349 | | } |
| 350 | 0× | Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { |
| 351 | 0× | Err(Error::Exists(key.to_string())) |
| 352 | | } |
| 353 | 0× | Err(e) => Err(e.into()), |
| 354 | | } |
| 355 | 9605× | } |
| 356 | |
|
| 357 | | |
| 358 | | |
| 359 | 15524× | fn ensure_dir(&self, path: &Path) -> Result<()> { |
| 360 | 15524× | let Some(dir) = path.parent() else { |
| 361 | 0× | return Ok(()); |
| 362 | | }; |
| 363 | 15524× | if dir.is_dir() { |
| 364 | 2300× | return Ok(()); |
| 365 | 13224× | } |
| 366 | 13224× | let mut made = dir.to_path_buf(); |
| 367 | 14454× | while let Some(parent) = made.parent() { |
| 368 | 14454× | if parent.is_dir() || parent == self.root { |
| 369 | 13224× | break; |
| 370 | 1230× | } |
| 371 | 1230× | made = parent.to_path_buf(); |
| 372 | | } |
| 373 | 13224× | fs::create_dir_all(dir)?; |
| 374 | 13224× | if let Some(parent) = made.parent() { |
| 375 | 13224× | crate::durable::sync_dir(parent)?; |
| 376 | 0× | } |
| 377 | 13224× | Ok(()) |
| 378 | 15524× | } |
| 379 | | } |
| 380 | |
|
| 381 | | impl Store for LocalStore { |
| 382 | 86× | fn describe(&self) -> String { |
| 383 | 86× | self.root.display().to_string() |
| 384 | 86× | } |
| 385 | |
|
| 386 | 25× | fn stat(&self, key: &str) -> Result<Option<Entry>> { |
| 387 | 25× | match fs::metadata(self.path(key)?) { |
| 388 | 14× | Ok(m) if m.is_file() => Ok(Some(Entry { |
| 389 | 14× | key: key.to_string(), |
| 390 | 14× | size: m.len(), |
| 391 | 14× | modified_ms: modified_ms(&m), |
| 392 | 14× | })), |
| 393 | 0× | Ok(_) => Ok(None), |
| 394 | 11× | Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), |
| 395 | 0× | Err(e) => Err(e.into()), |
| 396 | | } |
| 397 | 25× | } |
| 398 | |
|
| 399 | | |
| 400 | | |
| 401 | | |
| 402 | 1612× | fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> { |
| 403 | | use rayon::prelude::*; |
| 404 | 1612× | let mut todo: Vec<(PathBuf, PathBuf, &[u8])> = Vec::new(); |
| 405 | 5847× | for (key, bytes) in objects { |
| 406 | 5847× | let path = self.path(key)?; |
| 407 | 11825× | if path.exists() || todo.iter().any(|(p, ..)| *p == path) { |
| 408 | 0× | continue; |
| 409 | 5847× | } |
| 410 | 5847× | self.ensure_dir(&path)?; |
| 411 | 5847× | todo.push((path.clone(), self.temp_beside(&path), bytes)); |
| 412 | | } |
| 413 | 1612× | if todo.is_empty() { |
| 414 | 0× | return Ok(()); |
| 415 | 1612× | } |
| 416 | 1612× | crate::durable::step("write loose objects")?; |
| 417 | 1610× | todo.par_iter() |
| 418 | 5834× | .try_for_each(|(_, tmp, bytes)| -> io::Result<()> { |
| 419 | 5834× | let mut f = fs::File::create(tmp)?; |
| 420 | 5834× | f.write_all(bytes)?; |
| 421 | 5834× | f.sync_all() |
| 422 | 5834× | })?; |
| 423 | 1610× | crate::durable::step("rename loose objects")?; |
| 424 | 1608× | let mut dirs: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new(); |
| 425 | 5821× | for (path, tmp, _) in &todo { |
| 426 | 5821× | let linked = place_new(tmp, path); |
| 427 | 5821× | let _ = fs::remove_file(tmp); |
| 428 | 0× | match linked { |
| 429 | | Ok(()) => { |
| 430 | 5821× | if let Some(d) = path.parent() { |
| 431 | 5821× | dirs.insert(d.to_path_buf()); |
| 432 | 5821× | } |
| 433 | | } |
| 434 | 0× | Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} |
| 435 | 0× | Err(e) => return Err(e.into()), |
| 436 | | } |
| 437 | | } |
| 438 | 1608× | dirs.par_iter() |
| 439 | 5780× | .try_for_each(|d| crate::durable::sync_dir(d))?; |
| 440 | 1608× | Ok(()) |
| 441 | 1612× | } |
| 442 | |
|
| 443 | | |
| 444 | | |
| 445 | 72× | fn put_new_file(&self, key: &str, file: &Path) -> Result<()> { |
| 446 | 72× | let path = self.path(key)?; |
| 447 | 72× | if path.exists() { |
| 448 | 0× | let _ = fs::remove_file(file); |
| 449 | 0× | return Err(Error::Exists(key.to_string())); |
| 450 | 72× | } |
| 451 | 72× | self.ensure_dir(&path)?; |
| 452 | 72× | match place_new(file, &path) { |
| 453 | | Ok(()) => { |
| 454 | 72× | let _ = fs::remove_file(file); |
| 455 | 72× | if let Some(dir) = path.parent() { |
| 456 | 72× | crate::durable::sync_dir(dir)?; |
| 457 | 0× | } |
| 458 | 72× | Ok(()) |
| 459 | | } |
| 460 | 0× | Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { |
| 461 | 0× | let _ = fs::remove_file(file); |
| 462 | 0× | Err(Error::Exists(key.to_string())) |
| 463 | | } |
| 464 | | Err(_) => { |
| 465 | | |
| 466 | 0× | let tmp = self.temp_beside(&path); |
| 467 | 0× | let copied = (|| { |
| 468 | 0× | let mut src = fs::File::open(file)?; |
| 469 | 0× | let mut dst = fs::File::create(&tmp)?; |
| 470 | 0× | io::copy(&mut src, &mut dst)?; |
| 471 | 0× | dst.sync_all() |
| 472 | | })(); |
| 473 | 0× | let _ = fs::remove_file(file); |
| 474 | 0× | copied?; |
| 475 | 0× | self.link_into_place(key, &tmp, &path) |
| 476 | | } |
| 477 | | } |
| 478 | 72× | } |
| 479 | |
|
| 480 | 34696× | fn has(&self, key: &str) -> Result<bool> { |
| 481 | 34696× | Ok(self.path(key)?.is_file()) |
| 482 | 34696× | } |
| 483 | |
|
| 484 | 71620× | fn get(&self, key: &str) -> Result<Vec<u8>> { |
| 485 | 71620× | let path = self.path(key)?; |
| 486 | 71619× | match fs::read(&path) { |
| 487 | 63207× | Ok(b) => Ok(b), |
| 488 | 8412× | Err(e) if e.kind() == io::ErrorKind::NotFound => Err(Error::NotFound(key.to_string())), |
| 489 | 0× | Err(e) => Err(e.into()), |
| 490 | | } |
| 491 | 71620× | } |
| 492 | |
|
| 493 | 16211× | fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> { |
| 494 | 16211× | let path = self.path(key)?; |
| 495 | 16211× | let mut f = match fs::File::open(&path) { |
| 496 | 16127× | Ok(f) => f, |
| 497 | 84× | Err(e) if e.kind() == io::ErrorKind::NotFound => { |
| 498 | 84× | return Err(Error::NotFound(key.to_string())) |
| 499 | | } |
| 500 | 0× | Err(e) => return Err(e.into()), |
| 501 | | }; |
| 502 | 16127× | let len = f.metadata()?.len(); |
| 503 | 16127× | if range.end > len || range.start > range.end { |
| 504 | 5× | return Err(Error::Backend(format!( |
| 505 | 5× | "{key}: bytes {}..{} asked of an object of {len} bytes", |
| 506 | 5× | range.start, range.end |
| 507 | 5× | ))); |
| 508 | 16122× | } |
| 509 | 16122× | f.seek(SeekFrom::Start(range.start))?; |
| 510 | 16122× | let mut out = vec![0u8; (range.end - range.start) as usize]; |
| 511 | 16122× | f.read_exact(&mut out)?; |
| 512 | 16122× | Ok(out) |
| 513 | 16211× | } |
| 514 | |
|
| 515 | 9628× | fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> { |
| 516 | 9628× | let path = self.path(key)?; |
| 517 | 9627× | if path.exists() { |
| 518 | 22× | return Err(Error::Exists(key.to_string())); |
| 519 | 9605× | } |
| 520 | 9605× | self.ensure_dir(&path)?; |
| 521 | | |
| 522 | | |
| 523 | 9605× | let tmp = self.temp_beside(&path); |
| 524 | 9605× | let written = (|| { |
| 525 | 9605× | let mut f = fs::File::create(&tmp)?; |
| 526 | 9605× | f.write_all(bytes)?; |
| 527 | 9605× | f.sync_all() |
| 528 | | })(); |
| 529 | 9605× | if let Err(e) = written { |
| 530 | 0× | let _ = fs::remove_file(&tmp); |
| 531 | 0× | return Err(e.into()); |
| 532 | 9605× | } |
| 533 | 9605× | self.link_into_place(key, &tmp, &path) |
| 534 | 9628× | } |
| 535 | |
|
| 536 | 14638× | fn list(&self, prefix: &str) -> Result<Vec<Entry>> { |
| 537 | 14638× | let mut out = Vec::new(); |
| 538 | 14638× | self.list_dir(&self.root, "", prefix, &mut out)?; |
| 539 | 170935× | out.sort_by(|a, b| a.key.cmp(&b.key)); |
| 540 | 14638× | Ok(out) |
| 541 | 14638× | } |
| 542 | |
|
| 543 | 2782× | fn delete(&self, key: &str) -> Result<()> { |
| 544 | 2782× | let path = self.path(key)?; |
| 545 | 2782× | match fs::remove_file(&path) { |
| 546 | 1770× | Ok(()) => {} |
| 547 | 1012× | Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), |
| 548 | 0× | Err(e) => return Err(e.into()), |
| 549 | | } |
| 550 | | |
| 551 | | |
| 552 | 1770× | let mut dir = path.parent(); |
| 553 | 2250× | while let Some(d) = dir { |
| 554 | 2250× | if d == self.root || fs::remove_dir(d).is_err() { |
| 555 | 1770× | break; |
| 556 | 480× | } |
| 557 | 480× | dir = d.parent(); |
| 558 | | } |
| 559 | 1770× | Ok(()) |
| 560 | 2782× | } |
| 561 | |
|
| 562 | 829× | fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> { |
| 563 | 829× | let path = self.path(key)?; |
| 564 | 829× | match fs::read(&path) { |
| 565 | 749× | Ok(b) => { |
| 566 | 749× | let v = content_version(&b); |
| 567 | 749× | Ok(Some((b, v))) |
| 568 | | } |
| 569 | 80× | Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), |
| 570 | 0× | Err(e) => Err(e.into()), |
| 571 | | } |
| 572 | 829× | } |
| 573 | |
|
| 574 | 131× | fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> { |
| 575 | 131× | let path = self.path(key)?; |
| 576 | 131× | if let Some(dir) = path.parent() { |
| 577 | 131× | fs::create_dir_all(dir)?; |
| 578 | 0× | } |
| 579 | 131× | let lock = self.lock(key, &path)?; |
| 580 | 131× | let result = (|| { |
| 581 | 131× | let current = self.read_ref(key)?.map(|(_, v)| v); |
| 582 | 131× | check_expected(key, current.as_ref(), expected)?; |
| 583 | 115× | crate::durable::write_atomic(&path, bytes)?; |
| 584 | 115× | Ok(content_version(bytes)) |
| 585 | | })(); |
| 586 | 131× | let _ = fs::remove_file(&lock); |
| 587 | 131× | result |
| 588 | 131× | } |
| 589 | | } |
| 590 | |
|
| 591 | |
|
| 592 | |
|
| 593 | |
|
| 594 | |
|
| 595 | | #[derive(Default)] |
| 596 | | pub struct MemoryStore { |
| 597 | | objects: Mutex<BTreeMap<String, (Vec<u8>, u64)>>, |
| 598 | | } |
| 599 | |
|
| 600 | 2001× | fn now_ms() -> u64 { |
| 601 | 2001× | std::time::SystemTime::now() |
| 602 | 2001× | .duration_since(std::time::UNIX_EPOCH) |
| 603 | 2001× | .map(|d| d.as_millis() as u64) |
| 604 | 2001× | .unwrap_or(0) |
| 605 | 2001× | } |
| 606 | |
|
| 607 | | impl MemoryStore { |
| 608 | 24× | pub fn new() -> MemoryStore { |
| 609 | 24× | MemoryStore::default() |
| 610 | 24× | } |
| 611 | |
|
| 612 | 7615× | fn map(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, (Vec<u8>, u64)>> { |
| 613 | 7615× | self.objects.lock().unwrap_or_else(|p| p.into_inner()) |
| 614 | 7615× | } |
| 615 | |
|
| 616 | | |
| 617 | 0× | pub fn age(&self, key: &str, age: Duration) { |
| 618 | 0× | if let Some(entry) = self.map().get_mut(key) { |
| 619 | 0× | entry.1 = now_ms().saturating_sub(age.as_millis() as u64); |
| 620 | 0× | } |
| 621 | 0× | } |
| 622 | | } |
| 623 | |
|
| 624 | | impl Store for MemoryStore { |
| 625 | 1× | fn describe(&self) -> String { |
| 626 | 1× | "memory".into() |
| 627 | 1× | } |
| 628 | |
|
| 629 | 1996× | fn has(&self, key: &str) -> Result<bool> { |
| 630 | 1996× | check_key(key)?; |
| 631 | 1996× | Ok(self.map().contains_key(key)) |
| 632 | 1996× | } |
| 633 | |
|
| 634 | 2116× | fn get(&self, key: &str) -> Result<Vec<u8>> { |
| 635 | 2116× | check_key(key)?; |
| 636 | 2116× | self.map() |
| 637 | 2116× | .get(key) |
| 638 | 2116× | .map(|(b, _)| b.clone()) |
| 639 | 2116× | .ok_or_else(|| Error::NotFound(key.to_string())) |
| 640 | 2116× | } |
| 641 | |
|
| 642 | 1212× | fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> { |
| 643 | 1212× | let all = self.get(key)?; |
| 644 | 1131× | let len = all.len() as u64; |
| 645 | 1131× | if range.end > len || range.start > range.end { |
| 646 | 1× | return Err(Error::Backend(format!( |
| 647 | 1× | "{key}: bytes {}..{} asked of an object of {len} bytes", |
| 648 | 1× | range.start, range.end |
| 649 | 1× | ))); |
| 650 | 1130× | } |
| 651 | 1130× | Ok(all[range.start as usize..range.end as usize].to_vec()) |
| 652 | 1212× | } |
| 653 | |
|
| 654 | 1691× | fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> { |
| 655 | 1691× | check_key(key)?; |
| 656 | 1691× | let mut map = self.map(); |
| 657 | 1691× | if map.contains_key(key) { |
| 658 | 3× | return Err(Error::Exists(key.to_string())); |
| 659 | 1688× | } |
| 660 | 1688× | map.insert(key.to_string(), (bytes.to_vec(), now_ms())); |
| 661 | 1688× | Ok(()) |
| 662 | 1691× | } |
| 663 | |
|
| 664 | 656× | fn list(&self, prefix: &str) -> Result<Vec<Entry>> { |
| 665 | 656× | Ok(self |
| 666 | 656× | .map() |
| 667 | 656× | .range(prefix.to_string()..) |
| 668 | 3918× | .take_while(|(k, _)| k.starts_with(prefix)) |
| 669 | 656× | .map(|(k, (v, t))| Entry { |
| 670 | 3566× | key: k.clone(), |
| 671 | 3566× | size: v.len() as u64, |
| 672 | 3566× | modified_ms: Some(*t), |
| 673 | 3566× | }) |
| 674 | 656× | .collect()) |
| 675 | 656× | } |
| 676 | |
|
| 677 | 160× | fn delete(&self, key: &str) -> Result<()> { |
| 678 | 160× | check_key(key)?; |
| 679 | 160× | self.map().remove(key); |
| 680 | 160× | Ok(()) |
| 681 | 160× | } |
| 682 | |
|
| 683 | 591× | fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> { |
| 684 | 591× | check_key(key)?; |
| 685 | 591× | Ok(self |
| 686 | 591× | .map() |
| 687 | 591× | .get(key) |
| 688 | 591× | .map(|(b, _)| (b.clone(), content_version(b)))) |
| 689 | 591× | } |
| 690 | |
|
| 691 | 405× | fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> { |
| 692 | 405× | check_key(key)?; |
| 693 | 405× | let mut map = self.map(); |
| 694 | 405× | let current = map.get(key).map(|(b, _)| content_version(b)); |
| 695 | 405× | check_expected(key, current.as_ref(), expected)?; |
| 696 | 313× | map.insert(key.to_string(), (bytes.to_vec(), now_ms())); |
| 697 | 313× | Ok(content_version(bytes)) |
| 698 | 405× | } |
| 699 | | } |
| 700 | |
|
| 701 | |
|
| 702 | |
|
| 703 | |
|
| 704 | |
|
| 705 | |
|
| 706 | |
|
| 707 | |
|
| 708 | |
|
| 709 | |
|
| 710 | |
|
| 711 | |
|
| 712 | | pub struct CachingStore { |
| 713 | | cache: LocalStore, |
| 714 | | remote: std::sync::Arc<dyn Store>, |
| 715 | | limit: u64, |
| 716 | | |
| 717 | | used: Mutex<Option<u64>>, |
| 718 | | } |
| 719 | |
|
| 720 | |
|
| 721 | |
|
| 722 | | const RANGES: &str = "cached-range"; |
| 723 | | const SIZES: &str = "cached-size"; |
| 724 | |
|
| 725 | |
|
| 726 | | const TOUCH_AFTER: Duration = Duration::from_secs(60); |
| 727 | |
|
| 728 | | impl CachingStore { |
| 729 | | |
| 730 | | |
| 731 | 8× | pub fn open( |
| 732 | 8× | remote: std::sync::Arc<dyn Store>, |
| 733 | 8× | dir: impl Into<PathBuf>, |
| 734 | 8× | limit: u64, |
| 735 | 8× | ) -> Result<CachingStore> { |
| 736 | | Ok(CachingStore { |
| 737 | 8× | cache: LocalStore::open(dir)?, |
| 738 | 8× | remote, |
| 739 | 8× | limit, |
| 740 | 8× | used: Mutex::new(None), |
| 741 | | }) |
| 742 | 8× | } |
| 743 | |
|
| 744 | 0× | pub fn remote(&self) -> &std::sync::Arc<dyn Store> { |
| 745 | 0× | &self.remote |
| 746 | 0× | } |
| 747 | |
|
| 748 | | |
| 749 | 23× | pub fn cached_bytes(&self) -> Result<u64> { |
| 750 | 23× | let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner()); |
| 751 | 23× | if used.is_none() { |
| 752 | 1× | *used = Some(self.cache.list("")?.iter().map(|e| e.size).sum()); |
| 753 | 22× | } |
| 754 | 23× | Ok(used.unwrap_or(0)) |
| 755 | 23× | } |
| 756 | |
|
| 757 | | |
| 758 | 68× | fn cacheable(&self, size: u64) -> bool { |
| 759 | 68× | size <= self.limit / 8 |
| 760 | 68× | } |
| 761 | |
|
| 762 | | |
| 763 | 66× | fn keep(&self, key: &str, bytes: &[u8]) -> Result<()> { |
| 764 | 66× | if !self.cacheable(bytes.len() as u64) { |
| 765 | 1× | return Ok(()); |
| 766 | 65× | } |
| 767 | 65× | match self.cache.put_new(key, bytes) { |
| 768 | 65× | Ok(()) => self.added(bytes.len() as u64), |
| 769 | 0× | Err(Error::Exists(_)) => Ok(()), |
| 770 | 0× | Err(e) => Err(e), |
| 771 | | } |
| 772 | 66× | } |
| 773 | |
|
| 774 | | |
| 775 | | |
| 776 | 65× | fn added(&self, n: u64) -> Result<()> { |
| 777 | 65× | let total = { |
| 778 | 65× | let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner()); |
| 779 | 65× | let total = match *used { |
| 780 | 60× | Some(u) => u + n, |
| 781 | | |
| 782 | 5× | None => self.cache.list("")?.iter().map(|e| e.size).sum(), |
| 783 | | }; |
| 784 | 65× | *used = Some(total); |
| 785 | 65× | total |
| 786 | | }; |
| 787 | 65× | if total <= self.limit { |
| 788 | 34× | return Ok(()); |
| 789 | 31× | } |
| 790 | 31× | let mut entries = self.cache.list("")?; |
| 791 | 650× | entries.sort_by_key(|e| e.modified_ms.unwrap_or(0)); |
| 792 | 31× | let mut left: u64 = entries.iter().map(|e| e.size).sum(); |
| 793 | 31× | let target = self.limit / 10 * 9; |
| 794 | 62× | for e in entries { |
| 795 | 62× | if left <= target { |
| 796 | 31× | break; |
| 797 | 31× | } |
| 798 | 31× | self.cache.delete(&e.key)?; |
| 799 | 31× | left -= e.size; |
| 800 | | } |
| 801 | 31× | *self.used.lock().unwrap_or_else(|p| p.into_inner()) = Some(left); |
| 802 | 31× | Ok(()) |
| 803 | 65× | } |
| 804 | |
|
| 805 | | |
| 806 | | |
| 807 | 2× | fn size_of(&self, key: &str) -> Result<Option<u64>> { |
| 808 | 2× | let skey = format!("{SIZES}/{key}"); |
| 809 | 2× | if let Some(n) = self |
| 810 | 2× | .cache |
| 811 | 2× | .get(&skey) |
| 812 | 2× | .ok() |
| 813 | 2× | .and_then(|b| String::from_utf8(b).ok()) |
| 814 | 2× | .and_then(|t| t.parse().ok()) |
| 815 | | { |
| 816 | 0× | return Ok(Some(n)); |
| 817 | 2× | } |
| 818 | 2× | let size = self.remote.stat(key)?.map(|e| e.size); |
| 819 | 2× | if let Some(n) = size { |
| 820 | 2× | self.keep(&skey, n.to_string().as_bytes())?; |
| 821 | 0× | } |
| 822 | 2× | Ok(size) |
| 823 | 2× | } |
| 824 | |
|
| 825 | | |
| 826 | 32× | fn touch(&self, key: &str) { |
| 827 | 32× | let Ok(path) = self.cache.path(key) else { |
| 828 | 0× | return; |
| 829 | | }; |
| 830 | 32× | let stale = fs::metadata(&path) |
| 831 | 32× | .and_then(|m| m.modified()) |
| 832 | 32× | .ok() |
| 833 | 32× | .and_then(|t| t.elapsed().ok()) |
| 834 | 32× | .is_some_and(|age| age > TOUCH_AFTER); |
| 835 | 32× | if stale { |
| 836 | 0× | if let Ok(f) = fs::File::options().append(true).open(&path) { |
| 837 | 0× | let _ = f.set_modified(std::time::SystemTime::now()); |
| 838 | 0× | } |
| 839 | 32× | } |
| 840 | 32× | } |
| 841 | | } |
| 842 | |
|
| 843 | | impl Store for CachingStore { |
| 844 | 1× | fn describe(&self) -> String { |
| 845 | 1× | format!( |
| 846 | | "{} (cached in {})", |
| 847 | 1× | self.remote.describe(), |
| 848 | 1× | self.cache.root().display() |
| 849 | | ) |
| 850 | 1× | } |
| 851 | |
|
| 852 | 17× | fn has(&self, key: &str) -> Result<bool> { |
| 853 | 17× | Ok(self.cache.has(key)? || self.remote.has(key)?) |
| 854 | 17× | } |
| 855 | |
|
| 856 | 57× | fn get(&self, key: &str) -> Result<Vec<u8>> { |
| 857 | 57× | match self.cache.get(key) { |
| 858 | 29× | Ok(bytes) => { |
| 859 | 29× | self.touch(key); |
| 860 | 29× | return Ok(bytes); |
| 861 | | } |
| 862 | | |
| 863 | 28× | Err(Error::NotFound(_)) => {} |
| 864 | 0× | Err(e) => return Err(e), |
| 865 | | } |
| 866 | 28× | let bytes = self.remote.get(key)?; |
| 867 | 27× | self.keep(key, &bytes)?; |
| 868 | 27× | Ok(bytes) |
| 869 | 57× | } |
| 870 | |
|
| 871 | 6× | fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> { |
| 872 | 6× | match self.cache.get_range(key, range.clone()) { |
| 873 | 2× | Ok(bytes) => { |
| 874 | 2× | self.touch(key); |
| 875 | 2× | return Ok(bytes); |
| 876 | | } |
| 877 | 3× | Err(Error::NotFound(_)) => {} |
| 878 | 1× | Err(e) if self.cache.has(key)? => return Err(e), |
| 879 | 0× | Err(_) => {} |
| 880 | | } |
| 881 | | |
| 882 | | |
| 883 | | |
| 884 | 3× | let rkey = format!("{RANGES}/{key}/{}-{}", range.start, range.end); |
| 885 | 3× | if let Ok(bytes) = self.cache.get(&rkey) { |
| 886 | 1× | self.touch(&rkey); |
| 887 | 1× | return Ok(bytes); |
| 888 | 2× | } |
| 889 | | |
| 890 | | |
| 891 | | |
| 892 | 2× | match self.size_of(key)? { |
| 893 | 2× | Some(size) if self.cacheable(size) => { |
| 894 | 1× | let bytes = self.get(key)?; |
| 895 | 1× | let len = bytes.len() as u64; |
| 896 | 1× | if range.end > len || range.start > range.end { |
| 897 | 0× | return Err(Error::Backend(format!( |
| 898 | 0× | "{key}: bytes {}..{} asked of an object of {len} bytes", |
| 899 | 0× | range.start, range.end |
| 900 | 0× | ))); |
| 901 | 1× | } |
| 902 | 1× | Ok(bytes[range.start as usize..range.end as usize].to_vec()) |
| 903 | | } |
| 904 | | Some(_) => { |
| 905 | 1× | let bytes = self.remote.get_range(key, range)?; |
| 906 | 1× | self.keep(&rkey, &bytes)?; |
| 907 | 1× | Ok(bytes) |
| 908 | | } |
| 909 | 0× | None => Err(Error::NotFound(key.to_string())), |
| 910 | | } |
| 911 | 6× | } |
| 912 | |
|
| 913 | 29× | fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> { |
| 914 | 29× | self.remote.put_new(key, bytes)?; |
| 915 | 28× | self.keep(key, bytes) |
| 916 | 29× | } |
| 917 | |
|
| 918 | 2× | fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> { |
| 919 | 2× | self.remote.put_many_new(objects)?; |
| 920 | 8× | for (key, bytes) in objects { |
| 921 | 8× | self.keep(key, bytes)?; |
| 922 | | } |
| 923 | 2× | Ok(()) |
| 924 | 2× | } |
| 925 | |
|
| 926 | 0× | fn put_new_file(&self, key: &str, path: &Path) -> Result<()> { |
| 927 | 0× | let size = fs::metadata(path)?.len(); |
| 928 | 0× | let copy = if self.cacheable(size) { |
| 929 | 0× | Some(fs::read(path)?) |
| 930 | | } else { |
| 931 | 0× | None |
| 932 | | }; |
| 933 | 0× | self.remote.put_new_file(key, path)?; |
| 934 | 0× | match copy { |
| 935 | 0× | Some(bytes) => self.keep(key, &bytes), |
| 936 | 0× | None => Ok(()), |
| 937 | | } |
| 938 | 0× | } |
| 939 | |
|
| 940 | 15× | fn list(&self, prefix: &str) -> Result<Vec<Entry>> { |
| 941 | 15× | self.remote.list(prefix) |
| 942 | 15× | } |
| 943 | |
|
| 944 | 2× | fn stat(&self, key: &str) -> Result<Option<Entry>> { |
| 945 | 2× | self.remote.stat(key) |
| 946 | 2× | } |
| 947 | |
|
| 948 | 5× | fn delete(&self, key: &str) -> Result<()> { |
| 949 | 5× | self.remote.delete(key)?; |
| 950 | | |
| 951 | 5× | let mut extra = self.cache.list(&format!("{RANGES}/{key}/"))?; |
| 952 | 5× | extra.extend(self.cache.stat(&format!("{SIZES}/{key}"))?); |
| 953 | 5× | for e in extra { |
| 954 | 2× | self.cache.delete(&e.key)?; |
| 955 | 2× | let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner()); |
| 956 | 2× | if let Some(u) = used.as_mut() { |
| 957 | 2× | *u = u.saturating_sub(e.size); |
| 958 | 2× | } |
| 959 | | } |
| 960 | 5× | let size = self.cache.stat(key)?.map(|e| e.size); |
| 961 | 5× | self.cache.delete(key)?; |
| 962 | 5× | if let Some(n) = size { |
| 963 | 2× | let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner()); |
| 964 | 2× | if let Some(u) = used.as_mut() { |
| 965 | 2× | *u = u.saturating_sub(n); |
| 966 | 2× | } |
| 967 | 3× | } |
| 968 | 5× | Ok(()) |
| 969 | 5× | } |
| 970 | |
|
| 971 | 11× | fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> { |
| 972 | 11× | self.remote.read_ref(key) |
| 973 | 11× | } |
| 974 | |
|
| 975 | 9× | fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> { |
| 976 | 9× | self.remote.write_ref(key, bytes, expected) |
| 977 | 9× | } |
| 978 | | } |
| 979 | |
|
| 980 | |
|
| 981 | |
|
| 982 | |
|
| 983 | |
|
| 984 | |
|
| 985 | |
|
| 986 | |
|
| 987 | 6× | pub fn conformance(store: &dyn Store, prefix: &str) -> Result<Vec<&'static str>> { |
| 988 | 6× | let mut passed = Vec::new(); |
| 989 | 144× | let key = |name: &str| format!("{prefix}/{name}"); |
| 990 | 6× | let fail = |what: &str| Error::Backend(format!("{}: {what}", store.describe())); |
| 991 | 132× | let expect = |ok: bool, what: &str| if ok { Ok(()) } else { Err(fail(what)) }; |
| 992 | |
|
| 993 | 6× | expect( |
| 994 | 6× | store.list(prefix)?.is_empty(), |
| 995 | 6× | "the probe prefix is not empty", |
| 996 | 0× | )?; |
| 997 | 6× | expect( |
| 998 | 6× | !store.has(&key("a"))?, |
| 999 | 6× | "has() of a missing object says true", |
| 1000 | 0× | )?; |
| 1001 | 6× | expect( |
| 1002 | 6× | matches!(store.get(&key("a")), Err(Error::NotFound(_))), |
| 1003 | 6× | "get() of a missing object is not NotFound", |
| 1004 | 0× | )?; |
| 1005 | 6× | passed.push("missing objects are reported missing"); |
| 1006 | |
|
| 1007 | 1572864× | let a: Vec<u8> = (0..256u32 * 1024).map(|i| (i % 251) as u8).collect(); |
| 1008 | 6× | store.put_new(&key("a"), &a)?; |
| 1009 | 6× | expect(store.has(&key("a"))?, "has() after put_new says false")?; |
| 1010 | 6× | expect( |
| 1011 | 6× | store.get(&key("a"))? == a, |
| 1012 | 6× | "get() returns other bytes than put_new wrote", |
| 1013 | 0× | )?; |
| 1014 | 6× | passed.push("an object round-trips"); |
| 1015 | |
|
| 1016 | 6× | expect( |
| 1017 | 6× | store.get_range(&key("a"), 1000..1500)? == a[1000..1500], |
| 1018 | 6× | "get_range() returns the wrong bytes", |
| 1019 | 0× | )?; |
| 1020 | 6× | expect( |
| 1021 | 6× | store.get_range(&key("a"), 0..0)?.is_empty(), |
| 1022 | 6× | "an empty range is not empty", |
| 1023 | 0× | )?; |
| 1024 | 6× | expect( |
| 1025 | 6× | store.get_range(&key("a"), 0..a.len() as u64 + 1).is_err(), |
| 1026 | 6× | "a range past the end is not refused", |
| 1027 | 6× | )?; |
| 1028 | 6× | passed.push("ranges read correctly and are bounded"); |
| 1029 | |
|
| 1030 | 6× | expect( |
| 1031 | 6× | matches!(store.put_new(&key("a"), b"other"), Err(Error::Exists(_))), |
| 1032 | 6× | "put_new() over an existing object is not refused", |
| 1033 | 0× | )?; |
| 1034 | 6× | expect( |
| 1035 | 6× | store.get(&key("a"))? == a, |
| 1036 | 6× | "a refused put_new() changed the object", |
| 1037 | 0× | )?; |
| 1038 | 6× | passed.push("objects are written once"); |
| 1039 | |
|
| 1040 | 6× | store.put_new(&key("dir/b"), b"bb")?; |
| 1041 | 6× | let listed: Vec<(String, u64)> = store |
| 1042 | 6× | .list(prefix)? |
| 1043 | 6× | .into_iter() |
| 1044 | 12× | .map(|e| (e.key, e.size)) |
| 1045 | 6× | .collect(); |
| 1046 | 6× | expect( |
| 1047 | 6× | listed == vec![(key("a"), a.len() as u64), (key("dir/b"), 2)], |
| 1048 | 6× | "list() does not return the two objects, sorted, with their sizes", |
| 1049 | 6× | )?; |
| 1050 | 6× | expect( |
| 1051 | 6× | store |
| 1052 | 6× | .stat(&key("dir/b"))? |
| 1053 | 6× | .is_some_and(|e| e.key == key("dir/b") && e.size == 2) |
| 1054 | 6× | && store.stat(&key("dir/c"))?.is_none(), |
| 1055 | 6× | "stat() does not describe one object, or describes a missing one", |
| 1056 | 0× | )?; |
| 1057 | 6× | expect( |
| 1058 | 6× | store |
| 1059 | 6× | .list(&key("dir/"))? |
| 1060 | 6× | .into_iter() |
| 1061 | 6× | .map(|e| (e.key, e.size)) |
| 1062 | 6× | .collect::<Vec<_>>() |
| 1063 | 6× | == vec![(key("dir/b"), 2)], |
| 1064 | 6× | "list() of a sub-prefix is wrong", |
| 1065 | 0× | )?; |
| 1066 | 6× | expect( |
| 1067 | 6× | store.list(&key("nothing/"))?.is_empty(), |
| 1068 | 6× | "list() of an unused prefix is not empty", |
| 1069 | 0× | )?; |
| 1070 | 6× | passed.push("listing by prefix"); |
| 1071 | |
|
| 1072 | 6× | store.delete(&key("dir/b"))?; |
| 1073 | 6× | expect( |
| 1074 | 6× | !store.has(&key("dir/b"))?, |
| 1075 | 6× | "an object is still there after delete()", |
| 1076 | 0× | )?; |
| 1077 | 6× | store.delete(&key("dir/b"))?; |
| 1078 | 6× | passed.push("deletion, and deleting again, succeed"); |
| 1079 | |
|
| 1080 | 6× | let r = key("refs"); |
| 1081 | 6× | expect( |
| 1082 | 6× | store.read_ref(&r)?.is_none(), |
| 1083 | 6× | "an unwritten reference reads as something", |
| 1084 | 0× | )?; |
| 1085 | 6× | let v1 = store.write_ref(&r, b"one", None)?; |
| 1086 | 6× | expect( |
| 1087 | 6× | matches!(store.write_ref(&r, b"again", None), Err(Error::Conflict(_))), |
| 1088 | 6× | "a second create-only write of the reference is not refused", |
| 1089 | 0× | )?; |
| 1090 | 6× | let (bytes, seen) = store |
| 1091 | 6× | .read_ref(&r)? |
| 1092 | 6× | .ok_or_else(|| fail("the reference vanished"))?; |
| 1093 | 6× | expect( |
| 1094 | 6× | bytes == b"one" && seen == v1, |
| 1095 | 6× | "the reference reads back wrong", |
| 1096 | 0× | )?; |
| 1097 | 6× | let v2 = store.write_ref(&r, b"two", Some(&v1))?; |
| 1098 | 6× | expect(v2 != v1, "the version did not change on write")?; |
| 1099 | 6× | expect( |
| 1100 | 0× | matches!( |
| 1101 | 6× | store.write_ref(&r, b"three", Some(&v1)), |
| 1102 | | Err(Error::Conflict(_)) |
| 1103 | | ), |
| 1104 | 6× | "a write with a stale version is not refused", |
| 1105 | 0× | )?; |
| 1106 | 6× | let (bytes, seen) = store |
| 1107 | 6× | .read_ref(&r)? |
| 1108 | 6× | .ok_or_else(|| fail("the reference vanished"))?; |
| 1109 | 6× | expect( |
| 1110 | 6× | bytes == b"two" && seen == v2, |
| 1111 | 6× | "a refused write changed the reference", |
| 1112 | 0× | )?; |
| 1113 | 6× | passed.push("references update by compare-and-swap"); |
| 1114 | |
|
| 1115 | 6× | store.delete(&key("a"))?; |
| 1116 | 6× | store.delete(&r)?; |
| 1117 | 6× | expect( |
| 1118 | 6× | store.list(prefix)?.is_empty(), |
| 1119 | 6× | "the probe prefix is not empty after cleanup", |
| 1120 | 0× | )?; |
| 1121 | 6× | passed.push("cleanup"); |
| 1122 | 6× | Ok(passed) |
| 1123 | 6× | } |
| 1124 | |
|
| 1125 | | #[cfg(test)] |
| 1126 | | mod tests { |
| 1127 | | use super::*; |
| 1128 | | use std::sync::Arc; |
| 1129 | |
|
| 1130 | | |
| 1131 | | |
| 1132 | | #[test] |
| 1133 | 1× | fn a_create_only_rename_never_replaces() { |
| 1134 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1135 | 1× | let (a, b, to) = ( |
| 1136 | 1× | dir.path().join("a"), |
| 1137 | 1× | dir.path().join("b"), |
| 1138 | 1× | dir.path().join("to"), |
| 1139 | 1× | ); |
| 1140 | 1× | fs::write(&a, b"first").unwrap(); |
| 1141 | 1× | fs::write(&b, b"second").unwrap(); |
| 1142 | 1× | rename_new(&a, &to).unwrap(); |
| 1143 | 1× | assert_eq!( |
| 1144 | 1× | rename_new(&b, &to).unwrap_err().kind(), |
| 1145 | | io::ErrorKind::AlreadyExists |
| 1146 | | ); |
| 1147 | 1× | assert_eq!(fs::read(&to).unwrap(), b"first"); |
| 1148 | 1× | assert!(!a.exists() && b.exists()); |
| 1149 | 1× | } |
| 1150 | |
|
| 1151 | | #[test] |
| 1152 | 1× | fn keys_are_plain_relative_paths() { |
| 1153 | 3× | for ok in ["a", "packs/ab.pack", "a-b_c.d/e"] { |
| 1154 | 3× | check_key(ok).unwrap(); |
| 1155 | 3× | } |
| 1156 | 10× | for bad in [ |
| 1157 | 1× | "", "/a", "a/", "a//b", "..", "a/../b", "./a", "a b", "a\\b", "ä", |
| 1158 | 1× | ] { |
| 1159 | 10× | assert!(check_key(bad).is_err(), "{bad:?}"); |
| 1160 | | } |
| 1161 | 1× | assert!(check_key(&"x".repeat(MAX_KEY_LEN + 1)).is_err()); |
| 1162 | 1× | } |
| 1163 | |
|
| 1164 | | #[test] |
| 1165 | 1× | fn a_caching_store_conforms_and_reads_and_writes_through() { |
| 1166 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1167 | 1× | let remote: Arc<dyn Store> = Arc::new(MemoryStore::new()); |
| 1168 | 1× | let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8 << 20).unwrap(); |
| 1169 | 1× | assert_eq!(conformance(&store, "probe").unwrap().len(), 8); |
| 1170 | 1× | assert_eq!( |
| 1171 | 1× | store.cached_bytes().unwrap(), |
| 1172 | | 0, |
| 1173 | | "the probe left nothing cached" |
| 1174 | | ); |
| 1175 | |
|
| 1176 | | |
| 1177 | 1× | store.put_new("loose/aa", b"written").unwrap(); |
| 1178 | 1× | assert_eq!(remote.get("loose/aa").unwrap(), b"written"); |
| 1179 | 1× | assert!(store.cache.has("loose/aa").unwrap()); |
| 1180 | | |
| 1181 | 1× | remote.put_new("loose/bb", b"remote only").unwrap(); |
| 1182 | 1× | assert!(!store.cache.has("loose/bb").unwrap()); |
| 1183 | 1× | assert_eq!(store.get_range("loose/bb", 0..6).unwrap(), b"remote"); |
| 1184 | 1× | assert!(store.cache.has("loose/bb").unwrap()); |
| 1185 | | |
| 1186 | 1× | remote.delete("loose/bb").unwrap(); |
| 1187 | 1× | assert_eq!(store.get("loose/bb").unwrap(), b"remote only"); |
| 1188 | | |
| 1189 | 1× | let v = remote.write_ref("refs", b"one", None).unwrap(); |
| 1190 | 1× | assert_eq!( |
| 1191 | 1× | store.read_ref("refs").unwrap(), |
| 1192 | 1× | Some((b"one".to_vec(), v.clone())) |
| 1193 | | ); |
| 1194 | 1× | remote.write_ref("refs", b"two", Some(&v)).unwrap(); |
| 1195 | 1× | assert_eq!(store.read_ref("refs").unwrap().unwrap().0, b"two"); |
| 1196 | 1× | assert!(matches!( |
| 1197 | 1× | store.write_ref("refs", b"three", Some(&v)), |
| 1198 | | Err(Error::Conflict(_)) |
| 1199 | | )); |
| 1200 | 1× | assert!(!store.cache.has("refs").unwrap()); |
| 1201 | 1× | } |
| 1202 | |
|
| 1203 | | |
| 1204 | | struct Unreachable; |
| 1205 | |
|
| 1206 | | impl Store for Unreachable { |
| 1207 | 0× | fn describe(&self) -> String { |
| 1208 | 0× | "unreachable".into() |
| 1209 | 0× | } |
| 1210 | 0× | fn has(&self, _: &str) -> Result<bool> { |
| 1211 | 0× | Err(Error::Backend("asked the remote".into())) |
| 1212 | 0× | } |
| 1213 | 0× | fn get(&self, _: &str) -> Result<Vec<u8>> { |
| 1214 | 0× | Err(Error::Backend("asked the remote".into())) |
| 1215 | 0× | } |
| 1216 | 0× | fn get_range(&self, _: &str, _: Range<u64>) -> Result<Vec<u8>> { |
| 1217 | 0× | Err(Error::Backend("asked the remote".into())) |
| 1218 | 0× | } |
| 1219 | 0× | fn put_new(&self, _: &str, _: &[u8]) -> Result<()> { |
| 1220 | 0× | Err(Error::Backend("asked the remote".into())) |
| 1221 | 0× | } |
| 1222 | 0× | fn list(&self, _: &str) -> Result<Vec<Entry>> { |
| 1223 | 0× | Err(Error::Backend("asked the remote".into())) |
| 1224 | 0× | } |
| 1225 | 0× | fn delete(&self, _: &str) -> Result<()> { |
| 1226 | 0× | Err(Error::Backend("asked the remote".into())) |
| 1227 | 0× | } |
| 1228 | 0× | fn stat(&self, _: &str) -> Result<Option<Entry>> { |
| 1229 | 0× | Err(Error::Backend("asked the remote".into())) |
| 1230 | 0× | } |
| 1231 | 0× | fn read_ref(&self, _: &str) -> Result<Option<(Vec<u8>, Version)>> { |
| 1232 | 0× | Err(Error::Backend("asked the remote".into())) |
| 1233 | 0× | } |
| 1234 | 0× | fn write_ref(&self, _: &str, _: &[u8], _: Option<&Version>) -> Result<Version> { |
| 1235 | 0× | Err(Error::Backend("asked the remote".into())) |
| 1236 | 0× | } |
| 1237 | | } |
| 1238 | |
|
| 1239 | | #[test] |
| 1240 | 1× | fn a_caching_store_stays_within_its_limit() { |
| 1241 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1242 | 1× | let remote: Arc<dyn Store> = Arc::new(MemoryStore::new()); |
| 1243 | 1× | let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8000).unwrap(); |
| 1244 | 20× | for i in 0..20 { |
| 1245 | 20× | store |
| 1246 | 20× | .put_new(&format!("loose/{i:02}"), &[i as u8; 900]) |
| 1247 | 20× | .unwrap(); |
| 1248 | 20× | assert!(store.cached_bytes().unwrap() <= 8000); |
| 1249 | | } |
| 1250 | 1× | assert_eq!( |
| 1251 | 1× | remote.list("loose/").unwrap().len(), |
| 1252 | | 20, |
| 1253 | | "the remote holds everything" |
| 1254 | | ); |
| 1255 | 1× | let cached = store.cache.list("loose/").unwrap(); |
| 1256 | 1× | assert!(cached.len() < 20 && cached.len() >= 7, "{}", cached.len()); |
| 1257 | 1× | assert!( |
| 1258 | 8× | cached.iter().any(|e| e.key == "loose/19"), |
| 1259 | | "the newest is kept" |
| 1260 | | ); |
| 1261 | 20× | for i in 0..20 { |
| 1262 | 20× | assert_eq!( |
| 1263 | 20× | store.get(&format!("loose/{i:02}")).unwrap(), |
| 1264 | 20× | vec![i as u8; 900] |
| 1265 | | ); |
| 1266 | | } |
| 1267 | | |
| 1268 | 1× | remote.put_new("pack-big", &[7u8; 2000]).unwrap(); |
| 1269 | 1× | assert_eq!(store.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]); |
| 1270 | 1× | assert_eq!(store.get("pack-big").unwrap().len(), 2000); |
| 1271 | 1× | assert!(!store.cache.has("pack-big").unwrap()); |
| 1272 | | |
| 1273 | | |
| 1274 | 1× | let again = |
| 1275 | 1× | CachingStore::open(Arc::new(Unreachable), dir.path().join("cache"), 8000).unwrap(); |
| 1276 | 1× | assert_eq!(again.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]); |
| 1277 | | |
| 1278 | 1× | let fresh = CachingStore::open(remote, dir.path().join("cache"), 8000).unwrap(); |
| 1279 | 1× | assert_eq!(fresh.cached_bytes().unwrap(), store.cached_bytes().unwrap()); |
| 1280 | | |
| 1281 | 1× | store.delete("pack-big").unwrap(); |
| 1282 | 1× | assert!( |
| 1283 | 1× | store.cache.list("cached-range/").unwrap().is_empty() |
| 1284 | 1× | && store.cache.list("cached-size/").unwrap().is_empty() |
| 1285 | | ); |
| 1286 | 1× | } |
| 1287 | |
|
| 1288 | | #[test] |
| 1289 | 1× | fn the_memory_store_conforms() { |
| 1290 | 1× | let store = MemoryStore::new(); |
| 1291 | 1× | let passed = conformance(&store, "probe").unwrap(); |
| 1292 | 1× | assert_eq!(passed.len(), 8, "{passed:?}"); |
| 1293 | 1× | } |
| 1294 | |
|
| 1295 | | #[test] |
| 1296 | 1× | fn the_directory_store_conforms() { |
| 1297 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1298 | 1× | let store = LocalStore::open(dir.path().join("bucket")).unwrap(); |
| 1299 | 1× | let passed = conformance(&store, "repos/one").unwrap(); |
| 1300 | 1× | assert_eq!(passed.len(), 8, "{passed:?}"); |
| 1301 | | |
| 1302 | 1× | let stray: Vec<_> = walkdir(dir.path()) |
| 1303 | 1× | .into_iter() |
| 1304 | 1× | .filter(|p| p.is_file()) |
| 1305 | 1× | .collect(); |
| 1306 | 1× | assert!(stray.is_empty(), "{stray:?}"); |
| 1307 | 1× | assert_eq!( |
| 1308 | 1× | fs::read_dir(dir.path().join("bucket")).unwrap().count(), |
| 1309 | | 0, |
| 1310 | | "no empty directories left" |
| 1311 | | ); |
| 1312 | 1× | } |
| 1313 | |
|
| 1314 | 2× | fn walkdir(dir: &Path) -> Vec<PathBuf> { |
| 1315 | 2× | let mut out = vec![]; |
| 1316 | 2× | if let Ok(rd) = fs::read_dir(dir) { |
| 1317 | 2× | for e in rd.flatten() { |
| 1318 | 1× | let p = e.path(); |
| 1319 | 1× | if p.is_dir() { |
| 1320 | 1× | out.extend(walkdir(&p)); |
| 1321 | 1× | } else { |
| 1322 | 0× | out.push(p); |
| 1323 | 0× | } |
| 1324 | | } |
| 1325 | 0× | } |
| 1326 | 2× | out |
| 1327 | 2× | } |
| 1328 | |
|
| 1329 | | #[test] |
| 1330 | 1× | fn a_directory_store_refuses_keys_that_leave_its_root() { |
| 1331 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1332 | 1× | let store = LocalStore::open(dir.path().join("bucket")).unwrap(); |
| 1333 | 1× | assert!(matches!( |
| 1334 | 1× | store.put_new("../escape", b"x"), |
| 1335 | | Err(Error::Key(..)) |
| 1336 | | )); |
| 1337 | 1× | assert!(matches!(store.get("/etc/passwd"), Err(Error::Key(..)))); |
| 1338 | 1× | assert!(!dir.path().join("escape").exists()); |
| 1339 | 1× | } |
| 1340 | |
|
| 1341 | | |
| 1342 | | |
| 1343 | | #[test] |
| 1344 | 1× | fn compare_and_swap_admits_one_writer_per_round() { |
| 1345 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1346 | 1× | let local: Arc<dyn Store> = Arc::new(LocalStore::open(dir.path()).unwrap()); |
| 1347 | 1× | let memory: Arc<dyn Store> = Arc::new(MemoryStore::new()); |
| 1348 | 2× | for store in [local, memory] { |
| 1349 | 2× | let v0 = store.write_ref("refs", b"0", None).unwrap(); |
| 1350 | 2× | let wins: Vec<bool> = (0..8) |
| 1351 | 16× | .map(|i| { |
| 1352 | 16× | let store = store.clone(); |
| 1353 | 16× | let v0 = v0.clone(); |
| 1354 | 16× | std::thread::spawn(move || { |
| 1355 | 16× | store |
| 1356 | 16× | .write_ref("refs", format!("{}", i + 1).as_bytes(), Some(&v0)) |
| 1357 | 16× | .is_ok() |
| 1358 | 16× | }) |
| 1359 | 16× | }) |
| 1360 | 2× | .collect::<Vec<_>>() |
| 1361 | 2× | .into_iter() |
| 1362 | 16× | .map(|h| h.join().unwrap()) |
| 1363 | 2× | .collect(); |
| 1364 | 2× | assert_eq!( |
| 1365 | 2× | wins.iter().filter(|w| **w).count(), |
| 1366 | | 1, |
| 1367 | | "{}: {wins:?}", |
| 1368 | 0× | store.describe() |
| 1369 | | ); |
| 1370 | 2× | let (bytes, _) = store.read_ref("refs").unwrap().unwrap(); |
| 1371 | 2× | assert_ne!(bytes, b"0"); |
| 1372 | | } |
| 1373 | 1× | } |
| 1374 | |
|
| 1375 | | #[test] |
| 1376 | 1× | fn a_stale_lock_is_broken_and_a_live_one_waited_for() { |
| 1377 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1378 | 1× | let store = LocalStore::open(dir.path()).unwrap(); |
| 1379 | 1× | let lock = dir.path().join(".refs.lock"); |
| 1380 | 1× | fs::write(&lock, "dead").unwrap(); |
| 1381 | 1× | let old = std::time::SystemTime::now() - LOCK_STALE - Duration::from_secs(5); |
| 1382 | 1× | fs::File::open(&lock).unwrap().set_modified(old).unwrap(); |
| 1383 | 1× | store.write_ref("refs", b"after a crash", None).unwrap(); |
| 1384 | 1× | assert!(!lock.exists()); |
| 1385 | 1× | } |
| 1386 | |
|
| 1387 | | #[test] |
| 1388 | 1× | fn temporaries_and_locks_are_not_listed() { |
| 1389 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1390 | 1× | let store = LocalStore::open(dir.path()).unwrap(); |
| 1391 | 1× | store.put_new("packs/a", b"a").unwrap(); |
| 1392 | 1× | fs::write(dir.path().join("packs/.a.tmp-ffffff"), "junk").unwrap(); |
| 1393 | 1× | fs::write(dir.path().join(".refs.lock"), "1").unwrap(); |
| 1394 | 1× | let keys: Vec<String> = store.list("").unwrap().into_iter().map(|e| e.key).collect(); |
| 1395 | 1× | assert_eq!(keys, ["packs/a"]); |
| 1396 | 1× | } |
| 1397 | | } |