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