| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| •11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
#![warn(missing_docs)] |
| 17 |
|
| 18 |
use std::collections::{BTreeMap, BTreeSet}; |
| 19 |
use std::convert::{TryFrom, TryInto}; |
| 20 |
use std::ffi::{OsString, OsStr}; |
| 21 |
use std::fs::{File, OpenOptions}; |
| 22 |
use std::hash::{Hash, Hasher}; |
| 23 |
use std::io::{self, BufReader, ErrorKind, BufWriter, Write}; |
| 24 |
use std::path::{PathBuf, Path}; |
| 25 |
use std::time::{Duration, Instant, SystemTime}; |
| 26 |
|
| 27 |
use anyhow::{Context, Error, Result}; |
| 28 |
use serde::{Serialize, Deserialize}; |
| 29 |
use serde::de::DeserializeOwned; |
| 30 |
|
| 31 |
#[cfg(feature="debug")] |
| 32 |
macro_rules! debug_msg { |
| 33 |
($($arg:tt)*) => { eprintln!("bkt: {}", format!($($arg)*)) } |
| 34 |
} |
| 35 |
#[cfg(not(feature="debug"))] |
| 36 |
macro_rules! debug_msg { |
| 37 |
($($arg:tt)*) => { } |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
fn modtime(path: &Path) -> Result<Option<SystemTime>> { |
| 43 |
let metadata = std::fs::metadata(path); |
| 44 |
match metadata { |
| 45 |
Ok(metadata) => { |
| 46 |
Ok(Some(metadata.modified().context("Modtime is not supported")?)) |
| 47 |
}, |
| 48 |
Err(ref err) => { |
| 49 |
match err.kind() { |
| 50 |
ErrorKind::NotFound => Ok(None), |
| 51 |
_ => { metadata?; unreachable!() }, |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)] |
| 74 |
pub struct CommandDesc { |
| 75 |
args: Vec<OsString>, |
| 76 |
use_cwd: bool, |
| 77 |
envs: BTreeSet<OsString>, |
| 78 |
mod_files: BTreeSet<PathBuf>, |
| 79 |
persist_failures: bool, |
| 80 |
} |
| 81 |
|
| 82 |
impl CommandDesc { |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
pub fn new<I, S>(command: I) -> Self where I: IntoIterator<Item=S>, S: Into<OsString> { |
| 89 |
let ret = CommandDesc { |
| 90 |
args: command.into_iter().map(Into::into).collect(), |
| 91 |
use_cwd: false, |
| 92 |
envs: BTreeSet::new(), |
| 93 |
mod_files: BTreeSet::new(), |
| 94 |
persist_failures: true, |
| 95 |
}; |
| 96 |
assert!(!ret.args.is_empty(), "Command cannot be empty"); |
| 97 |
ret |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
pub fn with_cwd(mut self) -> Self { |
| 110 |
self.use_cwd = true; |
| 111 |
self |
| 112 |
} |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
pub fn with_env<K>(mut self, key: K) -> Self where K: AsRef<OsStr> { |
| 132 |
self.envs.insert(key.as_ref().into()); |
| 133 |
self |
| 134 |
} |
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
pub fn with_envs<I, E>(mut self, envs: I) -> Self where |
| 154 |
I: IntoIterator<Item=E>, |
| 155 |
E: AsRef<OsStr>, |
| 156 |
{ |
| 157 |
self.envs.extend(envs.into_iter().map(|e| e.as_ref().into())); |
| 158 |
self |
| 159 |
} |
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
pub fn with_modtime<P>(mut self, file: P) -> Self where P: AsRef<Path> { |
| 181 |
self.mod_files.insert(file.as_ref().into()); |
| 182 |
self |
| 183 |
} |
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
pub fn with_modtimes<I, P>(mut self, files: I) -> Self where |
| 205 |
I: IntoIterator<Item=P>, |
| 206 |
P: AsRef<Path>, { |
| 207 |
self.mod_files.extend(files.into_iter().map(|f| f.as_ref().into())); |
| 208 |
self |
| 209 |
} |
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
pub fn with_discard_failures(mut self, discard_failures: bool) -> Self { |
| 225 |
|
| 226 |
self.persist_failures = !discard_failures; |
| 227 |
self |
| 228 |
} |
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
pub fn capture_state(&self) -> Result<CommandState> { |
| 248 |
let cwd = if self.use_cwd { |
| 249 |
Some(std::env::current_dir()?) |
| 250 |
} else { |
| 251 |
None |
| 252 |
}; |
| 253 |
let envs = self.envs.iter() |
| 254 |
.flat_map(|e| std::env::var_os(e).map(|v| (e.clone(), v))) |
| 255 |
.collect(); |
| 256 |
let modtimes = self.mod_files.iter() |
| 257 |
.map(|f| modtime(f).map(|m| (f, m))) |
| 258 |
.collect::<Result<Vec<_>>>()?.into_iter() |
| 259 |
.flat_map(|(f, m)| m.map(|m| (f.clone(), m))) |
| 260 |
.collect(); |
| 261 |
|
| 262 |
let state = CommandState { args: self.args.clone(), cwd, envs, modtimes, persist_failures: self.persist_failures }; |
| 263 |
debug_msg!("state: {}", state.debug_info()); |
| 264 |
Ok(state) |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)] |
| 288 |
pub struct CommandState { |
| 289 |
|
| 290 |
|
| 291 |
args: Vec<OsString>, |
| 292 |
cwd: Option<PathBuf>, |
| 293 |
envs: BTreeMap<OsString, OsString>, |
| 294 |
modtimes: BTreeMap<PathBuf, SystemTime>, |
| 295 |
persist_failures: bool, |
| 296 |
} |
| 297 |
|
| 298 |
impl CommandState { |
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
pub fn with_working_dir<P: AsRef<Path>>(mut self, cwd: P) -> Self { |
| 311 |
self.cwd = Some(cwd.as_ref().into()); |
| 312 |
self |
| 313 |
} |
| 314 |
|
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
pub fn with_env<K, V>(mut self, key: K, value: V) -> Self |
| 325 |
where K: AsRef<OsStr>, V: AsRef<OsStr> { |
| 326 |
self.envs.insert(key.as_ref().into(), value.as_ref().into()); |
| 327 |
self |
| 328 |
} |
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
pub fn with_envs<I, K, V>(mut self, envs: I) -> Self |
| 347 |
where |
| 348 |
I: IntoIterator<Item=(K, V)>, |
| 349 |
K: AsRef<OsStr>, |
| 350 |
V: AsRef<OsStr>, |
| 351 |
{ |
| 352 |
for (ref key, ref val) in envs { |
| 353 |
self.envs.insert(key.as_ref().into(), val.as_ref().into()); |
| 354 |
} |
| 355 |
self |
| 356 |
} |
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
#[cfg(feature="debug")] |
| 361 |
fn debug_info(&self) -> String { |
| 362 |
fn to_timestamp(time: &SystemTime) -> u128 { |
| 363 |
time.duration_since(SystemTime::UNIX_EPOCH).expect("Precedes epoch").as_micros() |
| 364 |
} |
| 365 |
|
| 366 |
let mut parts = Vec::new(); |
| 367 |
if let Some(ref cwd) = self.cwd { |
| 368 |
parts.push(format!("cwd:{}", cwd.to_string_lossy())); |
| 369 |
} |
| 370 |
if !self.envs.is_empty() { |
| 371 |
parts.push(self.envs.iter() |
| 372 |
.map(|(k, v)| format!("{}={}", k.to_string_lossy(), v.to_string_lossy())) |
| 373 |
.collect::<Vec<_>>().join(",")); |
| 374 |
} |
| 375 |
if !self.modtimes.is_empty() { |
| 376 |
parts.push(self.modtimes.iter() |
| 377 |
.map(|(p, m)| format!("{}:{}", p.to_string_lossy(), to_timestamp(m))) |
| 378 |
.collect::<Vec<_>>().join(" ")); |
| 379 |
} |
| 380 |
parts.join(" | ") |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
impl TryFrom<&CommandDesc> for CommandState { |
| 385 |
type Error = anyhow::Error; |
| 386 |
|
| 387 |
fn try_from(desc: &CommandDesc) -> Result<Self> { |
| 388 |
desc.capture_state() |
| 389 |
} |
| 390 |
} |
| 391 |
|
| 392 |
impl From<&CommandState> for std::process::Command { |
| 393 |
fn from(cmd: &CommandState) -> Self { |
| 394 |
let mut command = std::process::Command::new(&cmd.args[0]); |
| 395 |
command.args(&cmd.args[1..]); |
| 396 |
if let Some(cwd) = &cmd.cwd { |
| 397 |
command.current_dir(cwd); |
| 398 |
} |
| 399 |
if !cmd.envs.is_empty() { |
| 400 |
command.envs(&cmd.envs); |
| 401 |
} |
| 402 |
command |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
impl CacheKey for CommandState { |
| 407 |
fn debug_label(&self) -> Option<String> { |
| 408 |
Some(self.args.iter() |
| 409 |
.map(|a| a.to_string_lossy()).collect::<Vec<_>>().join("-") |
| 410 |
.chars() |
| 411 |
.map(|c| if c.is_whitespace() { '_' } else { c }) |
| 412 |
.filter(|&c| c.is_alphanumeric() || c == '-' || c == '_') |
| 413 |
.take(100).collect()) |
| 414 |
} |
| 415 |
} |
| 416 |
|
| 417 |
#[cfg(test)] |
| 418 |
mod cmd_tests { |
| 419 |
use super::*; |
| 420 |
|
| 421 |
#[test] |
| 422 |
fn debug_label() { |
| 423 |
let cmd = CommandDesc::new(["foo", "bar", "b&r _- a"]); |
| 424 |
assert_eq!(CommandState::try_from(&cmd).unwrap().debug_label(), Some("foo-bar-br__-_a".into())); |
| 425 |
} |
| 426 |
|
| 427 |
#[test] |
| 428 |
fn collisions() { |
| 429 |
std::env::set_var("FOO", "BAR"); |
| 430 |
let commands = [ |
| 431 |
CommandDesc::new(["foo"]), |
| 432 |
CommandDesc::new(["foo", "bar"]), |
| 433 |
CommandDesc::new(["foo", "b", "ar"]), |
| 434 |
CommandDesc::new(["foo", "b ar"]), |
| 435 |
CommandDesc::new(["foo"]).with_cwd(), |
| 436 |
CommandDesc::new(["foo"]).with_env("FOO"), |
| 437 |
CommandDesc::new(["foo"]).with_cwd().with_env("FOO"), |
| 438 |
]; |
| 439 |
|
| 440 |
|
| 441 |
let mut iter = commands.iter(); |
| 442 |
for a in &commands { |
| 443 |
iter.next(); |
| 444 |
for b in iter.clone() { |
| 445 |
assert_ne!( |
| 446 |
CommandState::try_from(a).unwrap().cache_key(), |
| 447 |
CommandState::try_from(b).unwrap().cache_key(), |
| 448 |
"{:?} and {:?} have equivalent hashes", a, b); |
| 449 |
} |
| 450 |
} |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
|
| 455 |
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] |
| 456 |
pub struct Invocation { |
| 457 |
stdout: Vec<u8>, |
| 458 |
stderr: Vec<u8>, |
| 459 |
exit_code: i32, |
| 460 |
runtime: Duration, |
| 461 |
} |
| 462 |
|
| 463 |
impl Invocation { |
| 464 |
|
| 465 |
pub fn stdout(&self) -> &[u8] { &self.stdout } |
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
pub fn stdout_utf8(&self) -> &str { |
| 470 |
std::str::from_utf8(&self.stdout).expect("stdout not valid UTF-8") |
| 471 |
} |
| 472 |
|
| 473 |
|
| 474 |
pub fn stderr(&self) -> &[u8] { &self.stderr } |
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
pub fn stderr_utf8(&self) -> &str { |
| 479 |
std::str::from_utf8(&self.stderr).expect("stderr not valid UTF-8") |
| 480 |
} |
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
pub fn exit_code(&self) -> i32 { self.exit_code } |
| 486 |
|
| 487 |
|
| 488 |
pub fn runtime(&self) -> Duration { self.runtime } |
| 489 |
} |
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
#[derive(Debug)] |
| 496 |
struct FileLock { |
| 497 |
lock_file: PathBuf, |
| 498 |
} |
| 499 |
|
| 500 |
impl FileLock { |
| 501 |
fn try_acquire<P: AsRef<Path>>(lock_dir: P, name: &str, consider_stale: Duration) -> Result<Option<Self>> { |
| 502 |
let lock_file = lock_dir.as_ref().join(name).with_extension("lock"); |
| 503 |
match OpenOptions::new().create_new(true).write(true).open(&lock_file) { |
| 504 |
Ok(mut lock) => { |
| 505 |
write!(lock, "{}", std::process::id())?; |
| 506 |
Ok(Some(FileLock{ lock_file })) |
| 507 |
}, |
| 508 |
Err(io) => { |
| 509 |
match io.kind() { |
| 510 |
ErrorKind::AlreadyExists => { |
| 511 |
if let Ok(lock_metadata) = std::fs::metadata(&lock_file) { |
| 512 |
if let Ok(age) = lock_metadata.modified()?.elapsed() { |
| 513 |
if age > consider_stale { |
| 514 |
return Err(Error::msg(format!( |
| 515 |
"Lock {} held by PID {} appears stale and may need to be deleted manually.", |
| 516 |
lock_file.display(), |
| 517 |
std::fs::read_to_string(&lock_file).unwrap_or_else(|_| "unknown".into())))); |
| 518 |
} |
| 519 |
} |
| 520 |
} |
| 521 |
Ok(None) |
| 522 |
}, |
| 523 |
_ => { Err(Error::new(io)) } |
| 524 |
} |
| 525 |
}, |
| 526 |
} |
| 527 |
} |
| 528 |
} |
| 529 |
|
| 530 |
impl Drop for FileLock { |
| 531 |
fn drop(&mut self) { |
| 532 |
if let Err(e) = std::fs::remove_file(&self.lock_file) { |
| 533 |
eprintln!("Failed to delete lockfile {}, may need to be deleted manually. Reason: {:?}", |
| 534 |
self.lock_file.display(), e); |
| 535 |
} |
| 536 |
} |
| 537 |
} |
| 538 |
|
| 539 |
#[cfg(test)] |
| 540 |
mod file_lock_tests { |
| 541 |
use super::*; |
| 542 |
use test_dir::{TestDir, DirBuilder}; |
| 543 |
|
| 544 |
#[test] |
| 545 |
fn locks() { |
| 546 |
let dir = TestDir::temp(); |
| 547 |
let lock = FileLock::try_acquire(dir.root(), "test", Duration::from_secs(100)).unwrap(); |
| 548 |
let lock = lock.expect("Could not take lock"); |
| 549 |
assert!(dir.path("test.lock").exists()); |
| 550 |
std::mem::drop(lock); |
| 551 |
assert!(!dir.path("test.lock").exists()); |
| 552 |
} |
| 553 |
|
| 554 |
#[test] |
| 555 |
fn already_locked() { |
| 556 |
let dir = TestDir::temp(); |
| 557 |
let lock = FileLock::try_acquire(dir.root(), "test", Duration::from_secs(100)).unwrap(); |
| 558 |
let lock = lock.expect("Could not take lock"); |
| 559 |
|
| 560 |
let attempt = FileLock::try_acquire(dir.root(), "test", Duration::from_secs(100)).unwrap(); |
| 561 |
assert!(attempt.is_none()); |
| 562 |
|
| 563 |
std::mem::drop(lock); |
| 564 |
let attempt = FileLock::try_acquire(dir.root(), "test", Duration::from_secs(100)).unwrap(); |
| 565 |
assert!(attempt.is_some()); |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
|
| 570 |
|
| 571 |
|
| 572 |
|
| 573 |
|
| 574 |
trait CacheKey: std::fmt::Debug+Hash+PartialEq { |
| 575 |
|
| 576 |
fn debug_label(&self) -> Option<String> { None } |
| 577 |
|
| 578 |
|
| 579 |
|
| 580 |
fn cache_key(&self) -> String { |
| 581 |
|
| 582 |
|
| 583 |
|
| 584 |
let mut s = std::collections::hash_map::DefaultHasher::new(); |
| 585 |
self.hash(&mut s); |
| 586 |
let hash = s.finish(); |
| 587 |
if cfg!(feature = "debug") { |
| 588 |
if let Some(label) = self.debug_label() { |
| 589 |
if !label.is_empty() { |
| 590 |
return format!("{}_{:016X}", label, hash); |
| 591 |
} |
| 592 |
} |
| 593 |
} |
| 594 |
format!("{:016X}", hash) |
| 595 |
} |
| 596 |
} |
| 597 |
|
| 598 |
|
| 599 |
#[derive(Serialize, Deserialize)] |
| 600 |
struct CacheEntry<K, V> { |
| 601 |
key: K, |
| 602 |
value: V, |
| 603 |
} |
| 604 |
|
| 605 |
|
| 606 |
#[cfg(windows)] |
| 607 |
fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> Result<()> { |
| 608 |
std::os::windows::fs::symlink_file(original, link) |
| 609 |
.context("Windows prevents most programs from creating symlinks; see https://github.com/dimo414/bkt/issues/3") |
| 610 |
} |
| 611 |
#[cfg(unix)] |
| 612 |
use std::os::unix::fs::symlink; |
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
#[derive(Clone, Debug)] |
| 618 |
struct Cache { |
| 619 |
cache_dir: PathBuf, |
| 620 |
scope: Option<String>, |
| 621 |
} |
| 622 |
|
| 623 |
impl Cache { |
| 624 |
fn new<P: AsRef<Path>>(cache_dir: P) -> Self { |
| 625 |
Cache{ cache_dir: cache_dir.as_ref().into(), scope: None } |
| 626 |
} |
| 627 |
|
| 628 |
fn scoped(mut self, scope: String) -> Self { |
| 629 |
assert!(self.scope.is_none()); |
| 630 |
self.scope = Some(scope); |
| 631 |
self |
| 632 |
} |
| 633 |
|
| 634 |
#[cfg(not(feature = "debug"))] |
| 635 |
fn serialize<W, T>(writer: W, value: &T) -> Result<()> |
| 636 |
where W: io::Write, T: Serialize + ?Sized { |
| 637 |
Ok(bincode::serialize_into(writer, value)?) |
| 638 |
} |
| 639 |
|
| 640 |
#[cfg(feature = "debug")] |
| 641 |
fn serialize<W, T>(writer: W, value: &T) -> Result<()> |
| 642 |
where W: io::Write, T: Serialize + ?Sized { |
| 643 |
Ok(serde_json::to_writer_pretty(writer, value)?) |
| 644 |
} |
| 645 |
|
| 646 |
#[cfg(not(feature = "debug"))] |
| 647 |
fn deserialize<R, T>(reader: R) -> Result<T> |
| 648 |
where R: std::io::Read, T: DeserializeOwned { |
| 649 |
Ok(bincode::deserialize_from(reader)?) |
| 650 |
} |
| 651 |
|
| 652 |
#[cfg(feature = "debug")] |
| 653 |
fn deserialize<R, T>(reader: R) -> Result<T> |
| 654 |
where R: std::io::Read, T: DeserializeOwned { |
| 655 |
Ok(serde_json::from_reader(reader)?) |
| 656 |
} |
| 657 |
|
| 658 |
fn key_dir(&self) -> PathBuf { |
| 659 |
self.cache_dir.join("keys") |
| 660 |
} |
| 661 |
|
| 662 |
fn key_path(&self, key: &str) -> PathBuf { |
| 663 |
let file = match &self.scope { |
| 664 |
Some(scope) => format!("{}.{}", scope, key), |
| 665 |
None => key.into(), |
| 666 |
}; |
| 667 |
self.key_dir().join(file) |
| 668 |
} |
| 669 |
|
| 670 |
fn data_dir(&self) -> PathBuf { |
| 671 |
self.cache_dir.join("data") |
| 672 |
} |
| 673 |
|
| 674 |
|
| 675 |
|
| 676 |
fn lookup<K, V>(&self, key: &K, max_age: Duration) -> Result<Option<(V, SystemTime)>> |
| 677 |
where K: CacheKey+DeserializeOwned, V: DeserializeOwned { |
| 678 |
let path = self.key_path(&key.cache_key()); |
| 679 |
let file = File::open(&path); |
| 680 |
if let Err(ref e) = file { |
| 681 |
if e.kind() == ErrorKind::NotFound { |
| 682 |
debug_msg!("lookup {} not found", path.display()); |
| 683 |
return Ok(None); |
| 684 |
} |
| 685 |
} |
| 686 |
|
| 687 |
let reader = BufReader::new(file.context("Failed to access cache file")?); |
| 688 |
|
| 689 |
|
| 690 |
let found: CacheEntry<K, V> = Cache::deserialize(reader)?; |
| 691 |
|
| 692 |
let mtime = std::fs::metadata(&path)?.modified()?; |
| 693 |
let elapsed = mtime.elapsed(); |
| 694 |
if elapsed.is_err() || elapsed.unwrap() > max_age { |
| 695 |
debug_msg!("lookup {} expired", path.display()); |
| 696 |
std::fs::remove_file(&path).context("Failed to remove expired data")?; |
| 697 |
return Ok(None); |
| 698 |
} |
| 699 |
|
| 700 |
if &found.key != key { |
| 701 |
debug_msg!("lookup {} hash collision", path.display()); |
| 702 |
return Ok(None); |
| 703 |
} |
| 704 |
debug_msg!("lookup {} found", path.display()); |
| 705 |
Ok(Some((found.value, mtime))) |
| 706 |
} |
| 707 |
|
| 708 |
fn seconds_ceiling(duration: Duration) -> u64 { |
| 709 |
duration.as_secs() + if duration.subsec_nanos() != 0 { 1 } else { 0 } |
| 710 |
} |
| 711 |
|
| 712 |
|
| 713 |
fn rand_filename(dir: &Path, label: &str) -> PathBuf { |
| 714 |
use rand::{thread_rng, Rng}; |
| 715 |
use rand::distributions::Alphanumeric; |
| 716 |
let rand_str: String = thread_rng().sample_iter(Alphanumeric).take(16).map(char::from).collect(); |
| 717 |
dir.join(format!("{}.{}", label, rand_str)) |
| 718 |
} |
| 719 |
|
| 720 |
|
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
|
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
fn store<K, V>(&self, key: &K, value: &V, ttl: Duration) -> Result<()> |
| 731 |
where K: CacheKey+Serialize, V: Serialize { |
| 732 |
assert!(!ttl.is_zero(), "ttl cannot be zero"); |
| 733 |
let ttl_dir = self.data_dir().join(Cache::seconds_ceiling(ttl).to_string()); |
| 734 |
std::fs::create_dir_all(&ttl_dir)?; |
| 735 |
std::fs::create_dir_all(self.key_dir())?; |
| 736 |
let data_path = Cache::rand_filename(&ttl_dir, "data"); |
| 737 |
|
| 738 |
let file = OpenOptions::new().create_new(true).write(true).open(&data_path)?; |
| 739 |
let entry = CacheEntry{ key, value }; |
| 740 |
Cache::serialize(BufWriter::new(&file), &entry).context("Serialization failed")?; |
| 741 |
debug_msg!("store data {}", data_path.display()); |
| 742 |
|
| 743 |
|
| 744 |
let data_path = data_path.canonicalize()?; |
| 745 |
|
| 746 |
|
| 747 |
let tmp_symlink = Cache::rand_filename(&self.key_dir(), "tmp-symlink"); |
| 748 |
|
| 749 |
symlink(data_path, &tmp_symlink)?; |
| 750 |
let key_path = self.key_path(&entry.key.cache_key()); |
| 751 |
debug_msg!("store key {}", key_path.display()); |
| 752 |
std::fs::rename(&tmp_symlink, key_path)?; |
| 753 |
Ok(()) |
| 754 |
} |
| 755 |
|
| 756 |
fn cleanup(&self) -> Result<()> { |
| 757 |
fn delete_stale_file(file: &Path, ttl: Duration) -> Result<()> { |
| 758 |
let age = std::fs::metadata(file)?.modified()?.elapsed()?; |
| 759 |
if age > ttl { |
| 760 |
std::fs::remove_file(file)?; |
| 761 |
} |
| 762 |
Ok(()) |
| 763 |
} |
| 764 |
|
| 765 |
|
| 766 |
if let Ok(Some(_lock)) = FileLock::try_acquire(&self.cache_dir, "cleanup", Duration::from_secs(60*10)) { |
| 767 |
|
| 768 |
let last_attempt_file = self.cache_dir.join("last_cleanup"); |
| 769 |
if let Ok(metadata) = last_attempt_file.metadata() { |
| 770 |
if metadata.modified()?.elapsed()? < Duration::from_secs(30) { |
| 771 |
debug_msg!("cleanup skip recent"); |
| 772 |
return Ok(()); |
| 773 |
} |
| 774 |
} |
| 775 |
File::create(&last_attempt_file)?; |
| 776 |
|
| 777 |
|
| 778 |
debug_msg!("cleanup data {}", &self.data_dir().display()); |
| 779 |
if let Ok(data_dir_iter) = std::fs::read_dir(&self.data_dir()) { |
| 780 |
for entry in data_dir_iter { |
| 781 |
let ttl_dir = entry?.path(); |
| 782 |
let ttl = Duration::from_secs( |
| 783 |
ttl_dir.file_name().and_then(|s| s.to_str()).and_then(|s| s.parse().ok()) |
| 784 |
.ok_or_else(|| Error::msg(format!("Invalid ttl directory {}", ttl_dir.display())))?); |
| 785 |
|
| 786 |
for entry in std::fs::read_dir(&ttl_dir)? { |
| 787 |
let file = entry?.path(); |
| 788 |
|
| 789 |
|
| 790 |
let _ = delete_stale_file(&file, ttl); |
| 791 |
} |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
|
| 796 |
debug_msg!("cleanup keys {}", &self.key_dir().display()); |
| 797 |
if let Ok(key_dir_iter) = std::fs::read_dir(&self.key_dir()) { |
| 798 |
for entry in key_dir_iter { |
| 799 |
let symlink = entry?.path(); |
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
|
| 804 |
|
| 805 |
|
| 806 |
if !symlink.exists() { |
| 807 |
let _ = std::fs::remove_file(symlink); |
| 808 |
} |
| 809 |
} |
| 810 |
} |
| 811 |
} |
| 812 |
Ok(()) |
| 813 |
} |
| 814 |
} |
| 815 |
|
| 816 |
#[cfg(test)] |
| 817 |
mod cache_tests { |
| 818 |
use super::*; |
| 819 |
use test_dir::{TestDir, DirBuilder}; |
| 820 |
|
| 821 |
impl CacheKey for i32 {} |
| 822 |
impl CacheKey for String { |
| 823 |
fn debug_label(&self) -> Option<String> { |
| 824 |
Some(self.clone()) |
| 825 |
} |
| 826 |
} |
| 827 |
|
| 828 |
fn modtime<P: AsRef<Path>>(path: P) -> SystemTime { |
| 829 |
std::fs::metadata(&path).expect("No metadata").modified().expect("No modtime") |
| 830 |
} |
| 831 |
|
| 832 |
fn make_dir_stale<P: AsRef<Path>>(dir: P, age: Duration) -> Result<()> { |
| 833 |
let desired_time = SystemTime::now() - age; |
| 834 |
let stale_time = filetime::FileTime::from_system_time(desired_time); |
| 835 |
for entry in std::fs::read_dir(dir)? { |
| 836 |
let path = entry?.path(); |
| 837 |
let last_modified = modtime(&path); |
| 838 |
|
| 839 |
if path.is_file() && last_modified > desired_time { |
| 840 |
filetime::set_file_mtime(&path, stale_time)?; |
| 841 |
} else if path.is_dir() { |
| 842 |
make_dir_stale(&path, age)?; |
| 843 |
} |
| 844 |
} |
| 845 |
Ok(()) |
| 846 |
} |
| 847 |
|
| 848 |
fn dir_contents<P: AsRef<Path>>(dir: P) -> Vec<String> { |
| 849 |
fn contents(dir: &Path, ret: &mut Vec<PathBuf>) -> Result<()> { |
| 850 |
for entry in std::fs::read_dir(dir)? { |
| 851 |
let path = entry?.path(); |
| 852 |
if path.is_dir() { |
| 853 |
contents(&path, ret)?; |
| 854 |
} else { |
| 855 |
ret.push(path); |
| 856 |
} |
| 857 |
} |
| 858 |
Ok(()) |
| 859 |
} |
| 860 |
let mut paths = vec![]; |
| 861 |
contents(dir.as_ref(), &mut paths).unwrap(); |
| 862 |
paths.iter().map(|p| p.strip_prefix(dir.as_ref()).unwrap().display().to_string()).collect() |
| 863 |
} |
| 864 |
|
| 865 |
|
| 866 |
|
| •867 |
|
| 868 |
|
| 869 |
|
| 870 |
|
| 871 |
|
| 872 |
|
| 873 |
|
| 874 |
|
| 875 |
|
| 876 |
|
| 877 |
#[test] |
| 878 |
fn cache() { |
| 879 |
let dir = TestDir::temp(); |
| 880 |
let key = "foo".to_string(); |
| 881 |
let val = "A".to_string(); |
| 882 |
let cache = Cache::new(dir.root()); |
| 883 |
|
| 884 |
let absent = cache.lookup::<_, String>(&key, Duration::from_secs(100)).unwrap(); |
| 885 |
assert!(absent.is_none()); |
| 886 |
|
| 887 |
cache.store(&key, &val, Duration::from_secs(100)).unwrap(); |
| 888 |
let present = cache.lookup::<_, String>(&key, Duration::from_secs(100)).unwrap(); |
| 889 |
assert_eq!(present.unwrap().0, val); |
| 890 |
} |
| 891 |
|
| 892 |
#[test] |
| 893 |
fn lookup_ttls() { |
| 894 |
let dir = TestDir::temp(); |
| 895 |
let key = "foo".to_string(); |
| 896 |
let val = "A".to_string(); |
| 897 |
let cache = Cache::new(dir.root()); |
| 898 |
|
| 899 |
cache.store(&key, &val, Duration::from_secs(5)).unwrap(); |
| 900 |
make_dir_stale(dir.root(), Duration::from_secs(15)).unwrap(); |
| 901 |
|
| 902 |
|
| 903 |
let present = cache.lookup::<_, String>(&key, Duration::from_secs(20)).unwrap(); |
| 904 |
assert_eq!(present.unwrap().0, "A"); |
| 905 |
|
| 906 |
let absent = cache.lookup::<_, String>(&key, Duration::from_secs(10)).unwrap(); |
| 907 |
assert!(absent.is_none()); |
| 908 |
|
| 909 |
let absent = cache.lookup::<_, String>(&key, Duration::from_secs(20)).unwrap(); |
| 910 |
assert!(absent.is_none()); |
| 911 |
} |
| 912 |
|
| 913 |
#[test] |
| 914 |
fn scoped() { |
| 915 |
let dir = TestDir::temp(); |
| 916 |
let key = "foo".to_string(); |
| 917 |
let val_a = "A".to_string(); |
| 918 |
let val_b = "B".to_string(); |
| 919 |
let cache = Cache::new(dir.root()); |
| 920 |
let cache_scoped = Cache::new(dir.root()).scoped("scope".into()); |
| 921 |
|
| 922 |
cache.store(&key, &val_a, Duration::from_secs(100)).unwrap(); |
| 923 |
cache_scoped.store(&key, &val_b, Duration::from_secs(100)).unwrap(); |
| 924 |
|
| 925 |
let present = cache.lookup::<_, String>(&key, Duration::from_secs(20)).unwrap(); |
| 926 |
assert_eq!(present.unwrap().0, val_a); |
| 927 |
let present_scoped = cache_scoped.lookup::<_, String>(&key, Duration::from_secs(20)).unwrap(); |
| 928 |
assert_eq!(present_scoped.unwrap().0, val_b); |
| 929 |
} |
| 930 |
|
| 931 |
#[test] |
| 932 |
fn cleanup() { |
| 933 |
let dir = TestDir::temp(); |
| 934 |
let key = "foo".to_string(); |
| 935 |
let val = "A".to_string(); |
| 936 |
let cache = Cache::new(dir.root()); |
| 937 |
|
| 938 |
cache.store(&key, &val, Duration::from_secs(5)).unwrap(); |
| 939 |
make_dir_stale(dir.root(), Duration::from_secs(10)).unwrap(); |
| 940 |
cache.cleanup().unwrap(); |
| 941 |
|
| 942 |
assert_eq!(dir_contents(dir.root()), ["last_cleanup"]); |
| 943 |
|
| 944 |
let absent = cache.lookup::<_, String>(&key, Duration::from_secs(20)).unwrap(); |
| 945 |
assert!(absent.is_none()); |
| 946 |
} |
| 947 |
} |
| 948 |
|
| 949 |
|
| 950 |
#[derive(Debug, Copy, Clone)] |
| 951 |
pub enum CacheStatus { |
| 952 |
|
| 953 |
Hit(Instant), |
| 954 |
|
| 955 |
|
| 956 |
Miss(Duration), |
| 957 |
} |
| 958 |
|
| 959 |
#[cfg(test)] |
| 960 |
impl CacheStatus { |
| 961 |
|
| 962 |
|
| 963 |
|
| 964 |
fn is_hit(&self) -> bool { match self { CacheStatus::Hit(_) => true, CacheStatus::Miss(_) => false, } } |
| 965 |
fn is_miss(&self) -> bool { match self { CacheStatus::Hit(_) => false, CacheStatus::Miss(_) => true, } } |
| 966 |
} |
| 967 |
|
| 968 |
|
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
|
| 974 |
|
| 975 |
|
| 976 |
|
| •977 |
|
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
|
| 982 |
#[derive(Clone, Debug)] |
| 983 |
pub struct Bkt { |
| 984 |
cache: Cache, |
| 985 |
cleanup_on_refresh: bool, |
| 986 |
} |
| 987 |
|
| 988 |
impl Bkt { |
| 989 |
fn temp_dir() -> PathBuf { |
| 990 |
std::env::var_os("BKT_TMPDIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir) |
| 991 |
} |
| 992 |
|
| 993 |
|
| 994 |
|
| 995 |
|
| 996 |
|
| 997 |
|
| 998 |
|
| 999 |
pub fn in_tmp() -> Result<Self> { |
| 1000 |
Bkt::create(Bkt::temp_dir()) |
| 1001 |
} |
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
|
| 1006 |
|
| 1007 |
|
| 1008 |
|
| 1009 |
|
| 1010 |
|
| 1011 |
pub fn create(root_dir: PathBuf) -> Result<Self> { |
| 1012 |
|
| 1013 |
|
| 1014 |
|
| 1015 |
let cache_dir = root_dir |
| 1016 |
.join(format!("bkt-{}.{}-cache", env!("CARGO_PKG_VERSION_MAJOR"), env!("CARGO_PKG_VERSION_MINOR"))); |
| 1017 |
Bkt::restrict_dir(&cache_dir)?; |
| 1018 |
Ok(Bkt { |
| 1019 |
cache: Cache::new(&cache_dir), |
| 1020 |
cleanup_on_refresh: true, |
| 1021 |
}) |
| 1022 |
} |
| 1023 |
|
| 1024 |
|
| 1025 |
|
| 1026 |
|
| 1027 |
|
| 1028 |
|
| 1029 |
pub fn scoped(mut self, scope: String) -> Self { |
| 1030 |
self.cache = self.cache.scoped(scope); |
| 1031 |
self |
| 1032 |
} |
| 1033 |
|
| 1034 |
|
| 1035 |
|
| 1036 |
|
| 1037 |
|
| 1038 |
pub fn cleanup_on_refresh(mut self, cleanup: bool) -> Self { |
| 1039 |
self.cleanup_on_refresh = cleanup; |
| 1040 |
self |
| 1041 |
} |
| 1042 |
|
| 1043 |
#[cfg(not(unix))] |
| 1044 |
fn restrict_dir(_cache_dir: &Path) -> Result<()> { Ok(()) } |
| 1045 |
#[cfg(unix)] |
| 1046 |
fn restrict_dir(cache_dir: &Path) -> Result<()> { |
| 1047 |
use std::os::unix::fs::PermissionsExt; |
| 1048 |
if !cache_dir.exists() { |
| 1049 |
std::fs::create_dir_all(cache_dir)?; |
| 1050 |
let metadata = std::fs::metadata(cache_dir)?; |
| 1051 |
let mut permissions = metadata.permissions(); |
| 1052 |
permissions.set_mode(0o700); |
| 1053 |
std::fs::set_permissions(cache_dir, permissions)?; |
| 1054 |
} |
| 1055 |
Ok(()) |
| 1056 |
} |
| 1057 |
|
| 1058 |
fn execute_subprocess(cmd: impl Into<std::process::Command>) -> Result<Invocation> { |
| 1059 |
let mut command: std::process::Command = cmd.into(); |
| 1060 |
let start = Instant::now(); |
| 1061 |
|
| 1062 |
|
| 1063 |
let result = command.output() |
| 1064 |
.with_context(|| format!("Failed to run command {}", |
| 1065 |
command.get_args().next().expect("Executable missing").to_string_lossy()))?; |
| 1066 |
let runtime = start.elapsed(); |
| 1067 |
Ok(Invocation { |
| 1068 |
stdout: result.stdout, |
| 1069 |
stderr: result.stderr, |
| 1070 |
|
| 1071 |
exit_code: result.status.code().unwrap_or(126), |
| 1072 |
runtime, |
| 1073 |
}) |
| 1074 |
} |
| 1075 |
|
| 1076 |
|
| 1077 |
|
| 1078 |
|
| 1079 |
|
| 1080 |
|
| 1081 |
|
| 1082 |
|
| 1083 |
|
| 1084 |
|
| 1085 |
|
| 1086 |
|
| 1087 |
pub fn retrieve<T>(&self, command: T, ttl: Duration) -> Result<(Invocation, CacheStatus)> where |
| 1088 |
T: TryInto<CommandState>, |
| 1089 |
anyhow::Error: From<T::Error>, |
| 1090 |
{ |
| 1091 |
let command = command.try_into()?; |
| 1092 |
let cached = self.cache.lookup(&command, ttl).context("Cache lookup failed")?; |
| 1093 |
let result = match cached { |
| 1094 |
Some((cached, mtime)) => (cached, CacheStatus::Hit(Instant::now() - mtime.elapsed()?)), |
| 1095 |
None => { |
| 1096 |
let cleanup_hook = self.maybe_cleanup_once(); |
| 1097 |
let start = Instant::now(); |
| 1098 |
let result = Bkt::execute_subprocess(&command).context("Subprocess execution failed")?; |
| 1099 |
let runtime = Instant::now() - start; |
| 1100 |
if command.persist_failures || result.exit_code == 0 { |
| 1101 |
self.cache.store(&command, &result, ttl).context("Cache write failed")?; |
| 1102 |
} |
| 1103 |
Bkt::join_cleanup_thread(cleanup_hook); |
| 1104 |
(result, CacheStatus::Miss(runtime)) |
| 1105 |
} |
| 1106 |
}; |
| 1107 |
Ok(result) |
| 1108 |
} |
| 1109 |
|
| 1110 |
|
| 1111 |
|
| 1112 |
|
| 1113 |
|
| 1114 |
|
| 1115 |
|
| 1116 |
|
| 1117 |
|
| 1118 |
|
| 1119 |
pub fn refresh<T>(&self, command: T, ttl: Duration) -> Result<(Invocation, Duration)> where |
| 1120 |
T: TryInto<CommandState>, |
| 1121 |
anyhow::Error: From<T::Error>, |
| 1122 |
{ |
| 1123 |
let command = command.try_into()?; |
| 1124 |
let cleanup_hook = self.maybe_cleanup_once(); |
| 1125 |
let start = Instant::now(); |
| 1126 |
let result = Bkt::execute_subprocess(&command).context("Subprocess execution failed")?; |
| 1127 |
let elapsed = Instant::now() - start; |
| 1128 |
if command.persist_failures || result.exit_code == 0 { |
| 1129 |
self.cache.store(&command, &result, ttl).context("Cache write failed")?; |
| 1130 |
} |
| 1131 |
Bkt::join_cleanup_thread(cleanup_hook); |
| 1132 |
Ok((result, elapsed)) |
| 1133 |
} |
| 1134 |
|
| 1135 |
|
| 1136 |
|
| 1137 |
fn maybe_cleanup_once(&self) -> Option<std::thread::JoinHandle<Result<()>>> { |
| 1138 |
if self.cleanup_on_refresh { |
| 1139 |
Some(self.cleanup_once()) |
| 1140 |
} else { |
| 1141 |
None |
| 1142 |
} |
| 1143 |
} |
| 1144 |
|
| 1145 |
fn join_cleanup_thread(cleanup_hook: Option<std::thread::JoinHandle<Result<()>>>) { |
| 1146 |
if let Some(cleanup_hook) = cleanup_hook { |
| 1147 |
if let Err(e) = cleanup_hook.join().expect("cleanup thread panicked") { |
| 1148 |
eprintln!("bkt: cache cleanup failed: {:?}", e); |
| 1149 |
} |
| 1150 |
} |
| 1151 |
} |
| 1152 |
|
| 1153 |
|
| 1154 |
|
| 1155 |
|
| 1156 |
|
| 1157 |
|
| 1158 |
|
| 1159 |
|
| 1160 |
|
| 1161 |
|
| 1162 |
|
| 1163 |
|
| 1164 |
pub fn cleanup_once(&self) -> std::thread::JoinHandle<Result<()>> { |
| 1165 |
let cache = self.cache.clone(); |
| 1166 |
std::thread::spawn(move || { cache.cleanup() }) |
| 1167 |
} |
| 1168 |
|
| 1169 |
|
| 1170 |
|
| 1171 |
|
| 1172 |
pub fn cleanup_thread(&self) -> std::thread::JoinHandle<()> { |
| 1173 |
let cache = self.cache.clone(); |
| 1174 |
std::thread::spawn(move || { |
| 1175 |
|
| 1176 |
let poll_duration = Duration::from_secs(60); |
| 1177 |
loop { |
| 1178 |
if let Err(e) = cache.cleanup() { |
| 1179 |
eprintln!("Bkt: cache cleanup failed: {:?}", e); |
| 1180 |
} |
| 1181 |
std::thread::sleep(poll_duration); |
| 1182 |
} |
| 1183 |
}) |
| 1184 |
} |
| 1185 |
} |
| 1186 |
|
| 1187 |
|
| 1188 |
#[cfg(test)] |
| 1189 |
mod bkt_tests { |
| 1190 |
use super::*; |
| 1191 |
use test_dir::{TestDir, DirBuilder, FileType}; |
| 1192 |
|
| 1193 |
|
| 1194 |
#[test] |
| 1195 |
#[allow(clippy::redundant_clone)] |
| 1196 |
fn cloneable() { |
| 1197 |
let dir = TestDir::temp(); |
| 1198 |
let bkt = Bkt::create(dir.path("cache")).unwrap(); |
| 1199 |
let _scoped = bkt.clone().scoped("scope".into()); |
| 1200 |
let _no_cleanup = bkt.clone().cleanup_on_refresh(false); |
| 1201 |
} |
| 1202 |
|
| 1203 |
#[test] |
| 1204 |
fn cached() { |
| 1205 |
let dir = TestDir::temp(); |
| 1206 |
let file = dir.path("file"); |
| 1207 |
let cmd = CommandDesc::new( |
| 1208 |
["bash", "-c", r#"echo "$RANDOM" > "${1:?}"; cat "${1:?}""#, "arg0", file.to_str().unwrap()]); |
| 1209 |
let bkt = Bkt::create(dir.path("cache")).unwrap(); |
| 1210 |
let (first_inv, first_status) = bkt.retrieve(&cmd, Duration::from_secs(10)).unwrap(); |
| 1211 |
assert!(first_status.is_miss()); |
| 1212 |
|
| 1213 |
for _ in 1..3 { |
| 1214 |
let (subsequent_inv, subsequent_status) = bkt.retrieve(&cmd, Duration::from_secs(10)).unwrap(); |
| 1215 |
assert_eq!(first_inv, subsequent_inv); |
| 1216 |
assert!(subsequent_status.is_hit()); |
| 1217 |
} |
| 1218 |
} |
| 1219 |
|
| 1220 |
#[test] |
| 1221 |
fn discard_failures() { |
| 1222 |
let dir = TestDir::temp(); |
| 1223 |
let output = dir.path("output"); |
| 1224 |
let code = dir.path("code"); |
| 1225 |
|
| 1226 |
let cmd = CommandDesc::new( |
| 1227 |
["bash", "-c", r#"cat "${1:?}"; exit "$(< "${2:?}")""#, "arg0", output.to_str().unwrap(), code.to_str().unwrap()]) |
| 1228 |
.with_discard_failures(true); |
| 1229 |
let bkt = Bkt::create(dir.path("cache")).unwrap(); |
| 1230 |
|
| 1231 |
write!(File::create(&output).unwrap(), "A").unwrap(); |
| 1232 |
write!(File::create(&code).unwrap(), "10").unwrap(); |
| 1233 |
let (first_inv, first_status) = bkt.retrieve(&cmd, Duration::from_secs(10)).unwrap(); |
| 1234 |
assert_eq!(first_inv.exit_code, 10, "{:?}\nstderr:{}", first_inv, first_inv.stderr_utf8()); |
| 1235 |
assert_eq!(first_inv.stdout_utf8(), "A"); |
| 1236 |
assert!(first_status.is_miss()); |
| 1237 |
|
| 1238 |
write!(File::create(&output).unwrap(), "B").unwrap(); |
| 1239 |
let (subsequent_inv, subsequent_status) = bkt.retrieve(&cmd, Duration::from_secs(10)).unwrap(); |
| 1240 |
|
| 1241 |
assert_eq!(subsequent_inv.stdout_utf8(), "B"); |
| 1242 |
assert!(subsequent_status.is_miss()); |
| 1243 |
|
| 1244 |
write!(File::create(&output).unwrap(), "C").unwrap(); |
| 1245 |
write!(File::create(&code).unwrap(), "0").unwrap(); |
| 1246 |
let (success_inv, success_status) = bkt.retrieve(&cmd, Duration::from_secs(10)).unwrap(); |
| 1247 |
assert_eq!(success_inv.exit_code, 0); |
| 1248 |
assert_eq!(success_inv.stdout_utf8(), "C"); |
| 1249 |
assert!(success_status.is_miss()); |
| 1250 |
|
| 1251 |
write!(File::create(&output).unwrap(), "D").unwrap(); |
| 1252 |
let (cached_inv, cached_status) = bkt.retrieve(&cmd, Duration::from_secs(10)).unwrap(); |
| 1253 |
assert_eq!(success_inv, cached_inv); |
| 1254 |
assert!(cached_status.is_hit()); |
| 1255 |
} |
| 1256 |
|
| 1257 |
#[test] |
| 1258 |
fn with_working_dir() { |
| 1259 |
let dir = TestDir::temp().create("wd", FileType::Dir); |
| 1260 |
let work_dir = dir.path("wd"); |
| 1261 |
let cmd = CommandDesc::new(["bash", "-c", "echo Hello World > file"]); |
| 1262 |
let state = cmd.capture_state().unwrap().with_working_dir(&work_dir); |
| 1263 |
let bkt = Bkt::create(dir.path("cache")).unwrap(); |
| 1264 |
let (result, status) = bkt.retrieve(state, Duration::from_secs(10)).unwrap(); |
| 1265 |
assert_eq!(result.stderr_utf8(), ""); |
| 1266 |
assert_eq!(result.exit_code(), 0); |
| 1267 |
assert_eq!(std::fs::read_to_string(work_dir.join("file")).unwrap(), "Hello World\n"); |
| 1268 |
assert!(status.is_miss()); |
| 1269 |
} |
| 1270 |
|
| 1271 |
#[test] |
| 1272 |
fn cwd_and_working_dir_share_cache() { |
| 1273 |
let old_cwd = std::env::current_dir().unwrap(); |
| 1274 |
|
| 1275 |
let dir = TestDir::temp().create("wd", FileType::Dir); |
| 1276 |
let wd = dir.path("wd"); |
| 1277 |
let bkt = Bkt::create(dir.path("cache")).unwrap(); |
| 1278 |
|
| 1279 |
let cmd = CommandDesc::new(["bash", "-c", "pwd; echo '.' > file"]).with_cwd(); |
| 1280 |
|
| 1281 |
let state = cmd.capture_state().unwrap().with_working_dir(&wd); |
| 1282 |
let (result, status) = bkt.retrieve(state, Duration::from_secs(10)).unwrap(); |
| 1283 |
assert_eq!(result.stdout_utf8(), format!("{}\n", wd.to_str().unwrap())); |
| 1284 |
assert_eq!(result.stderr_utf8(), ""); |
| 1285 |
assert_eq!(result.exit_code(), 0); |
| 1286 |
assert!(status.is_miss()); |
| 1287 |
|
| 1288 |
|
| 1289 |
std::env::set_current_dir(&wd).unwrap(); |
| 1290 |
let (result, status) = bkt.retrieve(&cmd, Duration::from_secs(10)).unwrap(); |
| 1291 |
assert_eq!(result.stdout_utf8(), format!("{}\n", wd.to_str().unwrap())); |
| 1292 |
assert_eq!(result.stderr_utf8(), ""); |
| 1293 |
assert_eq!(result.exit_code(), 0); |
| 1294 |
assert!(status.is_hit()); |
| 1295 |
|
| 1296 |
|
| 1297 |
assert_eq!(std::fs::read_to_string(wd.join("file")).unwrap(), ".\n"); |
| 1298 |
|
| 1299 |
|
| 1300 |
|
| 1301 |
|
| 1302 |
|
| 1303 |
std::env::set_current_dir(old_cwd).unwrap(); |
| 1304 |
} |
| 1305 |
|
| •1306 |
|
| 1307 |
|
| 1308 |
|
| 1309 |
|
| •1310 |
|
| 1311 |
|
| 1312 |
|
| 1313 |
|
| 1314 |
|
| 1315 |
|
| 1316 |
|
| 1317 |
|
| 1318 |
|
| 1319 |
|
| 1320 |
|
| 1321 |
|
| 1322 |
|
| 1323 |
#[test] |
| 1324 |
fn with_modtime() { |
| 1325 |
let dir = TestDir::temp().create("dir", FileType::Dir); |
| 1326 |
let file = dir.path("file"); |
| 1327 |
let cmd = CommandDesc::new(["cat", file.to_str().unwrap()]); |
| 1328 |
let cmd_modtime = cmd.clone().with_modtime(&file); |
| 1329 |
let bkt = Bkt::create(dir.path("cache")).unwrap(); |
| 1330 |
write!(File::create(&file).unwrap(), "A").unwrap(); |
| 1331 |
let (result_a, status_a) = bkt.retrieve(&cmd, Duration::from_secs(10)).unwrap(); |
| 1332 |
let (result_mod_a, status_mod_a) = bkt.retrieve(&cmd_modtime, Duration::from_secs(10)).unwrap(); |
| 1333 |
assert!(status_a.is_miss()); |
| 1334 |
assert!(status_mod_a.is_miss()); |
| 1335 |
|
| 1336 |
|
| 1337 |
|
| 1338 |
write!(File::create(&file).unwrap(), "B").unwrap(); |
| 1339 |
filetime::set_file_mtime(&file, filetime::FileTime::from_system_time(SystemTime::now() - Duration::from_secs(15))).unwrap(); |
| 1340 |
|
| 1341 |
let (result_b, status_b) = bkt.retrieve(&cmd, Duration::from_secs(10)).unwrap(); |
| 1342 |
let (result_mod_b, status_mod_b) = bkt.retrieve(&cmd_modtime, Duration::from_secs(10)).unwrap(); |
| 1343 |
assert_eq!(result_a.stdout_utf8(), result_b.stdout_utf8()); |
| 1344 |
assert!(status_b.is_hit()); |
| 1345 |
assert_eq!(result_mod_a.stdout_utf8(), "A"); |
| 1346 |
assert_eq!(result_mod_b.stdout_utf8(), "B"); |
| 1347 |
assert!(status_mod_b.is_miss()); |
| 1348 |
} |
| 1349 |
} |