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