| 1 |
//! `bkt` (pronounced "bucket") is a library for caching subprocess executions. It enables reuse of |
| 2 |
//! expensive invocations across separate processes and supports synchronous and asynchronous |
| 3 |
//! refreshing, TTLs, and other functionality. `bkt` is also a standalone binary for use by shell |
| 4 |
//! scripts and other languages, see <https://github.com/dimo414/bkt> for binary details. |
| 5 |
//! |
| 6 |
//! ```no_run |
| 7 |
//! # fn do_something(_: &str) {} |
| 8 |
//! # fn main() -> anyhow::Result<()> { |
| 9 |
//! # use std::time::Duration; |
| 10 |
//! let bkt = bkt::Bkt::in_tmp()?; |
| 11 |
//! let expensive_cmd = bkt::CommandDesc::new(["wget", "http://example.com"]); |
| 12 |
//! let (result, age) = bkt.retrieve(&expensive_cmd, Duration::from_secs(3600))?; |
| 13 |
//! do_something(result.stdout_utf8()); |
| 14 |
//! # Ok(()) } |
| 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 |
/// Returns the modtime of the given path. Returns Ok(None) if the file is not found, and |
| 41 |
/// otherwise returns an error if the modtime cannot be determined. |
| 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 |
/// A stateless description of a command to be executed and cached. It consists of a command line |
| 58 |
/// invocation and additional metadata about how the command should be cached which are configured |
| 59 |
/// via the `with_*` methods. Instances can be persisted and reused. |
| 60 |
/// |
| 61 |
/// Calling any of these methods changes how the invocation's cache key will be constructed, |
| 62 |
/// therefore two invocations with different metadata configured will be cached separately. This |
| 63 |
/// allows - for example - commands that interact with the current working directory to be cached |
| 64 |
/// dependent on the working directory even if the command line arguments are equal. |
| 65 |
/// |
| 66 |
/// # Examples |
| 67 |
/// |
| 68 |
/// ``` |
| 69 |
/// let cmd = bkt::CommandDesc::new(["echo", "Hello World!"]); |
| 70 |
/// let with_cwd = bkt::CommandDesc::new(["ls"]).with_cwd(); |
| 71 |
/// let with_env = bkt::CommandDesc::new(["date"]).with_env("TZ"); |
| 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 |
/// Constructs a CommandDesc instance for the given command line. |
| 84 |
/// |
| 85 |
/// ``` |
| 86 |
/// let cmd = bkt::CommandDesc::new(["echo", "Hello World!"]); |
| 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 |
/// Specifies that the current process' working directory should be included in the cache key. |
| 101 |
/// Commands that depend on the working directory (e.g. `ls` or `git status`) should call this |
| 102 |
/// in order to cache executions in different working directories separately. |
| 103 |
/// |
| 104 |
/// # Examples |
| 105 |
/// |
| 106 |
/// ``` |
| 107 |
/// let cmd = bkt::CommandDesc::new(["pwd"]).with_cwd(); |
| 108 |
/// ``` |
| 109 |
pub fn with_cwd(mut self) -> Self { |
| 110 |
self.use_cwd = true; |
| 111 |
self |
| 112 |
} |
| 113 |
|
| 114 |
/// Specifies that the given environment variable should be included in the cache key. Commands |
| 115 |
/// that depend on the values of certain environment variables (e.g. `LANG`, `PATH`, or `TZ`) |
| 116 |
/// should call this in order to cache such executions separately. Although it's possible to |
| 117 |
/// pass `PWD` here calling [`with_cwd()`] is generally recommended instead for clarity and |
| 118 |
/// consistency with subprocesses that don't read this environment variable. |
| 119 |
/// |
| 120 |
/// Note: If the given variable name is not found in the current process' environment at |
| 121 |
/// execution time the variable is _not_ included in the cache key, and the execution will be |
| 122 |
/// cached as if the environment variable had not been specified at all. |
| 123 |
/// |
| 124 |
/// [`with_cwd()`]: CommandDesc::with_cwd |
| 125 |
/// |
| 126 |
/// # Examples |
| 127 |
/// |
| 128 |
/// ``` |
| 129 |
/// let cmd = bkt::CommandDesc::new(["date"]).with_env("TZ"); |
| 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 |
/// Specifies that the given environment variables should be included in the cache key. Commands |
| 137 |
/// that depend on the values of certain environment variables (e.g. `LANG`, `PATH`, or `TZ`) |
| 138 |
/// should call this in order to cache such executions separately. Although it's possible to |
| 139 |
/// pass `PWD` here calling [`with_cwd()`] is generally recommended instead for clarity and |
| 140 |
/// consistency with subprocesses that don't read this environment variable. |
| 141 |
/// |
| 142 |
/// Note: If a given variable name is not found in the current process' environment at execution |
| 143 |
/// time that variable is _not_ included in the cache key, and the execution will be cached as |
| 144 |
/// if the environment variable had not been specified at all. |
| 145 |
/// |
| 146 |
/// [`with_cwd()`]: CommandDesc::with_cwd |
| 147 |
/// |
| 148 |
/// # Examples |
| 149 |
/// |
| 150 |
/// ``` |
| 151 |
/// let cmd = bkt::CommandDesc::new(["date"]).with_envs(["LANG", "TZ"]); |
| 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 |
/// Specifies that the modification time of the given file should be included in the cache key, |
| 162 |
/// causing cached commands to be invalidated if the file is modified in the future. Commands |
| 163 |
/// that depend on the contents of certain files should call this in order to invalidate the |
| 164 |
/// cache when the file changes. |
| 165 |
/// |
| 166 |
/// It is recommended to pass absolute paths when this is used along with [`with_cwd()`] or |
| 167 |
/// [`CommandState::with_working_dir()`] to avoid any ambiguity in how relative paths are |
| 168 |
/// resolved. |
| 169 |
/// |
| 170 |
/// Note: If the given path is not found at execution time the file is _not_ included in the |
| 171 |
/// cache key, and the execution will be cached as if the file had not been specified at all. |
| 172 |
/// |
| 173 |
/// [`with_cwd()`]: CommandDesc::with_cwd |
| 174 |
/// |
| 175 |
/// # Examples |
| 176 |
/// |
| 177 |
/// ``` |
| 178 |
/// let cmd = bkt::CommandDesc::new(["..."]).with_modtime("/etc/passwd"); |
| 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 |
/// Specifies that the modification time of the given files should be included in the cache key, |
| 186 |
/// causing cached commands to be invalidated if the files are modified in the future. Commands |
| 187 |
/// that depend on the contents of certain files should call this in order to invalidate the |
| 188 |
/// cache when the files change. |
| 189 |
/// |
| 190 |
/// It is recommended to pass absolute paths when this is used along with [`with_cwd()`] or |
| 191 |
/// [`CommandState::with_working_dir()`] to avoid any ambiguity in how relative paths are |
| 192 |
/// resolved. |
| 193 |
/// |
| 194 |
/// Note: If a given path is not found at execution time that file is _not_ included in the |
| 195 |
/// cache key, and the execution will be cached as if the file had not been specified at all. |
| 196 |
/// |
| 197 |
/// [`with_cwd()`]: CommandDesc::with_cwd |
| 198 |
/// |
| 199 |
/// # Examples |
| 200 |
/// |
| 201 |
/// ``` |
| 202 |
/// let cmd = bkt::CommandDesc::new(["..."]).with_modtimes(["/etc/passwd", "/etc/group"]); |
| 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 |
/// Specifies this command should only be cached if it succeeds - i.e. it returns a zero exit |
| 212 |
/// code. Commands that return a non-zero exit code will not be cached, and therefore will be |
| 213 |
/// rerun on each invocation (until they succeed). |
| 214 |
/// |
| 215 |
/// **WARNING:** use this option with caution. Discarding invocations that fail can overload |
| 216 |
/// downstream resources that were protected by the caching layer limiting QPS. For example, |
| 217 |
/// if a website is rejecting a fraction of requests to shed load and then clients start |
| 218 |
/// sending _more_ requests when their attempts fail the website could be taken down outright by |
| 219 |
/// the added load. In other words, using this option can lead to accidental DDoSes. |
| 220 |
/// |
| 221 |
/// ``` |
| 222 |
/// let cmd = bkt::CommandDesc::new(["grep", "foo", "/var/log/syslog"]).with_discard_failures(true); |
| 223 |
/// ``` |
| 224 |
pub fn with_discard_failures(mut self, discard_failures: bool) -> Self { |
| 225 |
// Invert the boolean so it's not a double negative at usage sites |
| 226 |
self.persist_failures = !discard_failures; |
| 227 |
self |
| 228 |
} |
| 229 |
|
| 230 |
/// Constructs a [`CommandState`] instance, capturing application state that will be used in the |
| 231 |
/// cache key, such as the current working directory and any specified environment variables. |
| 232 |
/// The `CommandState` can also be further customized to change how the subprocess is invoked. |
| 233 |
/// |
| 234 |
/// Most callers should be able to pass a `CommandDesc` directly to a [`Bkt`] instance without |
| 235 |
/// needing to construct a separate `CommandState` first. |
| 236 |
/// |
| 237 |
/// Example: |
| 238 |
/// |
| 239 |
/// ```no_run |
| 240 |
/// # fn main() -> anyhow::Result<()> { |
| 241 |
/// # use std::time::Duration; |
| 242 |
/// let bkt = bkt::Bkt::in_tmp()?; |
| 243 |
/// let cmd = bkt::CommandDesc::new(["foo", "bar"]).capture_state()?.with_env("FOO", "BAR"); |
| 244 |
/// let (result, age) = bkt.retrieve(cmd, Duration::from_secs(3600))?; |
| 245 |
/// # Ok(()) } |
| 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 |
/// The stateful sibling of [`CommandDesc`] which represents a command to be executed and cached |
| 269 |
/// along with environment state (e.g. the current working directory) at the time the `CommandState` |
| 270 |
/// instance is constructed. It consists of a command line invocation and application state |
| 271 |
/// determining how the command should be cached and executed. Additional `with_*` methods are |
| 272 |
/// provided on this type for further modifying how the subprocess will be executed. |
| 273 |
/// |
| 274 |
/// Calling any of these methods changes how the invocation's cache key will be constructed, |
| 275 |
/// therefore two invocations with different configured state will be cached separately, in the same |
| 276 |
/// manner as the `with_*` methods on `CommandDesc`. |
| 277 |
/// |
| 278 |
/// # Examples |
| 279 |
/// |
| 280 |
/// ``` |
| 281 |
/// # fn main() -> anyhow::Result<()> { |
| 282 |
/// let cmd = bkt::CommandDesc::new(["echo", "Hello World!"]).capture_state(); |
| 283 |
/// let with_custom_wd = bkt::CommandDesc::new(["ls"]).capture_state()?.with_working_dir("/"); |
| 284 |
/// let with_env = bkt::CommandDesc::new(["date"]).capture_state()?.with_env("TZ", "UTC"); |
| 285 |
/// # Ok(()) } |
| 286 |
/// ``` |
| 287 |
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)] |
| 288 |
pub struct CommandState { |
| 289 |
// TODO Borrow<Vec<OsString>> or Cow<Vec<OsString>> might be better, need to validate |
| 290 |
// serialization. Or maybe just make it &Vec<OsString> and add a lifetime to CommandState? |
| 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 |
/// Sets the working directory the command should be run from, and causes this working directory |
| 300 |
/// to be included in the cache key. If unset the working directory will be inherited from the |
| 301 |
/// current process' and will _not_ be used to differentiate invocations in separate working |
| 302 |
/// directories. |
| 303 |
/// |
| 304 |
/// ``` |
| 305 |
/// # fn main() -> anyhow::Result<()> { |
| 306 |
/// let cmd = bkt::CommandDesc::new(["pwd"]); |
| 307 |
/// let state = cmd.capture_state()?.with_working_dir("/tmp"); |
| 308 |
/// # Ok(()) } |
| 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 |
/// Adds the given key/value pair to the environment the command should be run from, and causes |
| 316 |
/// this pair to be included in the cache key. |
| 317 |
/// |
| 318 |
/// ``` |
| 319 |
/// # fn main() -> anyhow::Result<()> { |
| 320 |
/// let cmd = bkt::CommandDesc::new(["pwd"]); |
| 321 |
/// let state = cmd.capture_state()?.with_env("FOO", "bar"); |
| 322 |
/// # Ok(()) } |
| 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 |
/// Adds the given key/value pairs to the environment the command should be run from, and causes |
| 331 |
/// these pair to be included in the cache key. |
| 332 |
/// |
| 333 |
/// ``` |
| 334 |
/// # fn main() -> anyhow::Result<()> { |
| 335 |
/// use std::env; |
| 336 |
/// use std::collections::HashMap; |
| 337 |
/// |
| 338 |
/// let important_envs : HashMap<String, String> = |
| 339 |
/// env::vars().filter(|&(ref k, _)| |
| 340 |
/// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH" |
| 341 |
/// ).collect(); |
| 342 |
/// let cmd = bkt::CommandDesc::new(["..."]); |
| 343 |
/// let state = cmd.capture_state()?.with_envs(&important_envs); |
| 344 |
/// # Ok(()) } |
| 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 |
/// Format's the CommandState's metadata (information read from the system rather than provided |
| 359 |
/// by the caller) for diagnostic purposes. |
| 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 |
// https://old.reddit.com/r/rust/comments/2koptu/best_way_to_visit_all_pairs_in_a_vec/clnhxr5/ |
| 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 |
/// The outputs of a cached invocation of a [`CommandDesc`], akin to [`std::process::Output`]. |
| 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 |
/// The data that the process wrote to stdout. |
| 465 |
pub fn stdout(&self) -> &[u8] { &self.stdout } |
| 466 |
|
| 467 |
/// Helper to view stdout as a UTF-8 string. Use [`from_utf8`](std::str::from_utf8) directly if |
| 468 |
/// you need to handle output that may not be UTF-8. |
| 469 |
pub fn stdout_utf8(&self) -> &str { |
| 470 |
std::str::from_utf8(&self.stdout).expect("stdout not valid UTF-8") |
| 471 |
} |
| 472 |
|
| 473 |
/// The data that the process wrote to stderr. |
| 474 |
pub fn stderr(&self) -> &[u8] { &self.stderr } |
| 475 |
|
| 476 |
/// Helper to view stderr as a UTF-8 string. Use [`from_utf8`](std::str::from_utf8) directly if |
| 477 |
/// you need to handle output that may not be UTF-8. |
| 478 |
pub fn stderr_utf8(&self) -> &str { |
| 479 |
std::str::from_utf8(&self.stderr).expect("stderr not valid UTF-8") |
| 480 |
} |
| 481 |
|
| 482 |
/// The exit code of the program, or 126 if the program terminated without an exit status. |
| 483 |
/// See [`ExitStatus::code()`](std::process::ExitStatus::code()). This is subject to change to |
| 484 |
/// better support other termination states. |
| 485 |
pub fn exit_code(&self) -> i32 { self.exit_code } |
| 486 |
|
| 487 |
/// The time the process took to complete. |
| 488 |
pub fn runtime(&self) -> Duration { self.runtime } |
| 489 |
} |
| 490 |
|
| 491 |
/// A file-lock mechanism that holds a lock by atomically creating a file in the given directory, |
| 492 |
/// and deleting the file upon being dropped. Callers should beware that dropping is not guaranteed |
| 493 |
/// (e.g. if the program panics). When a conflicting lock file is found its age (mtime) is checked |
| 494 |
/// to detect stale locks leaked by a separate process that failed to properly drop its lock. |
| 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 |
/// Trait allowing a type to be used as a cache key. It would be nice to blanket-implement |
| 570 |
/// this for all types that implement the dependent traits, but without a way for specific |
| 571 |
/// impls to opt-out of the blanket that would prevent customizing the debug_label(). |
| 572 |
/// Specialization might resolve that issue, in the meantime it's fine since Cache is a |
| 573 |
/// private type anyways. |
| 574 |
trait CacheKey: std::fmt::Debug+Hash+PartialEq { |
| 575 |
/// Label is added to the cache key when run with the debug feature, useful for diagnostics. |
| 576 |
fn debug_label(&self) -> Option<String> { None } |
| 577 |
|
| 578 |
/// Generates a string sufficiently unique to describe the key; typically just the hex encoding |
| 579 |
/// of the key's hash code. Most impls should not need to override this. |
| 580 |
fn cache_key(&self) -> String { |
| 581 |
// The hash_map::DefaultHasher is somewhat underspecified, but it notes that "hashes should |
| 582 |
// not be relied upon over releases", which implies it is stable across multiple |
| 583 |
// invocations of the same build.... See cache_tests::stable_hash. |
| 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 |
/// Container for serialized key/value pairs. |
| 599 |
#[derive(Serialize, Deserialize)] |
| 600 |
struct CacheEntry<K, V> { |
| 601 |
key: K, |
| 602 |
value: V, |
| 603 |
} |
| 604 |
|
| 605 |
// See https://doc.rust-lang.org/std/fs/fn.soft_link.html |
| 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 |
/// A file-system-backed cache for mapping keys (i.e. `CommandDesc`) to values (i.e. `Invocation`) |
| 615 |
/// for a given duration. |
| 616 |
// TODO make this a trait so we can swap out impls, such as an in-memory cache or SQLite-backed |
| 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 |
/// Looks up the given key in the cache, returning the associated value and its age |
| 675 |
/// if the data is found and is newer than the max_age. |
| 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 |
// Missing file is OK; other errors get propagated to the caller |
| 687 |
let reader = BufReader::new(file.context("Failed to access cache file")?); |
| 688 |
// TODO consider returning OK(None) if deserialization fails, which could happen if |
| 689 |
// different types hashed to the same key |
| 690 |
let found: CacheEntry<K, V> = Cache::deserialize(reader)?; |
| 691 |
// Discard data that is too old |
| 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 |
// Ignore false-positive hits that happened to collide with the hash code |
| 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 |
// https://rust-lang-nursery.github.io/rust-cookbook/algorithms/randomness.html#create-random-passwords-from-a-set-of-alphanumeric-characters |
| 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 |
/// Write the given key/value pair to the cache, persisting it for at least the given TTL. |
| 721 |
/// |
| 722 |
/// Note: This method takes references to the key and value because they are serialized |
| 723 |
/// externally, therefore consuming either parameter is unhelpful. An in-memory implementation |
| 724 |
/// would need to do an internal `.clone()` which is at odds with |
| 725 |
/// [`C-CALLER-CONTROL`](https://rust-lang.github.io/api-guidelines/flexibility.html) but Cache |
| 726 |
/// is intended for serialization use cases so some overhead in the in-memory case may be |
| 727 |
/// acceptable. |
| 728 |
// TODO C-INTERMEDIATE suggests emulating HashMap::insert and returning any existing value in |
| 729 |
// the cache, though it would be expensive to construct this so perhaps should be a callback |
| 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 |
// Note: this will fail if filename collides, could retry in a loop if that happens |
| 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 |
// The target needs to be canonicalized as we're creating the link in a subdirectory, but I'd somewhat prefer |
| 743 |
// to fix it to be correctly relative to the link's location. Probably not worth the trouble though. |
| 744 |
let data_path = data_path.canonicalize()?; |
| 745 |
// Roundabout approach to an atomic symlink replacement |
| 746 |
// https://github.com/dimo414/bash-cache/issues/26 |
| 747 |
let tmp_symlink = Cache::rand_filename(&self.key_dir(), "tmp-symlink"); |
| 748 |
// Note: this call will fail if the tmp_symlink filename collides, could retry in a loop if that happens. |
| 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 |
// if try_acquire fails, e.g. because the directory does not exist, there's nothing to clean up |
| 766 |
if let Ok(Some(_lock)) = FileLock::try_acquire(&self.cache_dir, "cleanup", Duration::from_secs(60*10)) { |
| 767 |
// Don't bother if cleanup has been attempted recently |
| 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)?; // resets mtime if already exists |
| 776 |
|
| 777 |
// First delete stale data files |
| 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 |
// Disregard errors on individual files; typically due to concurrent deletion |
| 789 |
// or other changes we don't care about. |
| 790 |
let _ = delete_stale_file(&file, ttl); |
| 791 |
} |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
// Then delete broken symlinks |
| 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 |
// This reads as if we're deleting files that no longer exist, but what it really |
| 801 |
// means is "if the symlink is broken, try to delete _the symlink_." It would also |
| 802 |
// try to delete a symlink that happened to be deleted concurrently, but this is |
| 803 |
// harmless since we ignore the error. |
| 804 |
// std::fs::symlink_metadata() could be used to check that the symlink itself exists |
| 805 |
// if needed, but this could still have false-positives due to a TOCTOU race. |
| 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 |
// Sanity-checking that cache_key's behavior is stable over time. This test may need to be |
| 866 |
// updated when changing Rust versions / editions. |
| 867 |
#[test] |
| 868 |
fn stable_hash() { |
| 869 |
assert_eq!(100.cache_key(), "7D208C81E8236995"); |
| 870 |
if cfg!(feature = "debug") { |
| 871 |
assert_eq!("FooBar".to_string().cache_key(), "FooBar_2C8878C07E3ADA57"); |
| 872 |
} else { |
| 873 |
assert_eq!("FooBar".to_string().cache_key(), "2C8878C07E3ADA57"); |
| 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(); // store duration doesn't affect lookups |
| 900 |
make_dir_stale(dir.root(), Duration::from_secs(15)).unwrap(); |
| 901 |
|
| 902 |
// data is still present until a cleanup iteration runs, or a lookup() invalidates it |
| 903 |
let present = cache.lookup::<_, String>(&key, Duration::from_secs(20)).unwrap(); |
| 904 |
assert_eq!(present.unwrap().0, "A"); |
| 905 |
// lookup() finds stale data, deletes it |
| 906 |
let absent = cache.lookup::<_, String>(&key, Duration::from_secs(10)).unwrap(); |
| 907 |
assert!(absent.is_none()); |
| 908 |
// now data is gone, even though this lookup() would have accepted it |
| 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"]); // keys and data dirs are now empty |
| 943 |
|
| 944 |
let absent = cache.lookup::<_, String>(&key, Duration::from_secs(20)).unwrap(); |
| 945 |
assert!(absent.is_none()); |
| 946 |
} |
| 947 |
} |
| 948 |
|
| 949 |
/// Holds information about the cache status of a given command. |
| 950 |
#[derive(Debug, Copy, Clone)] |
| 951 |
pub enum CacheStatus { |
| 952 |
/// Command was found in the cache. Contains the time the returned invocation was cached. |
| 953 |
Hit(Instant), |
| 954 |
/// Command was not found in the cache and was executed. Contains the execution time of the |
| 955 |
/// subprocess. |
| 956 |
Miss(Duration), |
| 957 |
} |
| 958 |
|
| 959 |
#[cfg(test)] |
| 960 |
impl CacheStatus { |
| 961 |
// Note these functions are intentionally not public for now. They're only currently needed to |
| 962 |
// make assertions shorter, and should be able to be removed once assert_matches #82775 is |
| 963 |
// stable. Can be made public if other use-cases arise. |
| 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 |
/// This struct is the main API entry point for the `bkt` library, allowing callers to invoke and |
| 969 |
/// cache subprocesses for later reuse. |
| 970 |
/// |
| 971 |
/// Example: |
| 972 |
/// |
| 973 |
/// ```no_run |
| 974 |
/// # fn main() -> anyhow::Result<()> { |
| 975 |
/// # use std::time::Duration; |
| 976 |
/// let bkt = bkt::Bkt::in_tmp()?; |
| 977 |
/// let cmd = bkt::CommandDesc::new(["curl", "http://expensive.api/foo"]); |
| 978 |
/// let (result, age) = bkt.retrieve(&cmd, Duration::from_secs(60*60))?; |
| 979 |
/// println!("Retrieved: {:?}\nAge: {:?}", result, age); |
| 980 |
/// # Ok(()) } |
| 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 |
/// Creates a new Bkt instance using the [`std::env::temp_dir`] as the cache location. If a |
| 994 |
/// `BKT_TMPDIR` environment variable is set that value will be preferred. |
| 995 |
/// |
| 996 |
/// # Errors |
| 997 |
/// |
| 998 |
/// If preparing the tmp cache directory fails. |
| 999 |
pub fn in_tmp() -> Result<Self> { |
| 1000 |
Bkt::create(Bkt::temp_dir()) |
| 1001 |
} |
| 1002 |
|
| 1003 |
/// Creates a new Bkt instance. |
| 1004 |
/// |
| 1005 |
/// The given `root_dir` will be used as the parent directory of the cache. It's recommended |
| 1006 |
/// this directory be in a tmpfs partition, on an SSD, or similar, so operations are fast. |
| 1007 |
/// |
| 1008 |
/// # Errors |
| 1009 |
/// |
| 1010 |
/// If preparing the cache directory under `root_dir` fails. |
| 1011 |
pub fn create(root_dir: PathBuf) -> Result<Self> { |
| 1012 |
// Note the cache is invalidated when the minor version changes |
| 1013 |
// TODO use separate directories per user, like bash-cache |
| 1014 |
// See https://stackoverflow.com/q/57951893/113632 |
| 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 |
/// Associates a scope with this Bkt instance, causing it to namespace its cache keys so that |
| 1025 |
/// they do not collide with other instances using the same cache directory. This is useful when |
| 1026 |
/// separate applications could potentially invoke the same commands but should not share a |
| 1027 |
/// cache. Consider using the application's name, PID, and/or a timestamp in order to create a |
| 1028 |
/// sufficiently unique namespace. |
| 1029 |
pub fn scoped(mut self, scope: String) -> Self { |
| 1030 |
self.cache = self.cache.scoped(scope); |
| 1031 |
self |
| 1032 |
} |
| 1033 |
|
| 1034 |
/// By default a background cleanup thread runs on cache misses and calls to [`Bkt::refresh()`] |
| 1035 |
/// to remove stale data. You may prefer to manage cleanup yourself if you expect frequent cache |
| 1036 |
/// misses and want to minimize the number of threads being created. See [`Bkt::cleanup_once()`] |
| 1037 |
/// and [`Bkt::cleanup_thread()`] if you set this to `false`. |
| 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); // Only accessible to current user |
| 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 |
// TODO write to stdout/stderr while running, rather than after the process completes? |
| 1062 |
// See https://stackoverflow.com/q/66060139 |
| 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 |
// TODO handle signals, see https://stackoverflow.com/q/66272686 |
| 1071 |
exit_code: result.status.code().unwrap_or(126), |
| 1072 |
runtime, |
| 1073 |
}) |
| 1074 |
} |
| 1075 |
|
| 1076 |
/// Looks up the given command in Bkt's cache. If found (and newer than the given TTL) returns |
| 1077 |
/// the cached invocation. If stale or not found the command is executed and the result is |
| 1078 |
/// cached and then returned. |
| 1079 |
/// |
| 1080 |
/// The second element in the returned tuple reports whether or not the invocation was cached |
| 1081 |
/// and includes information such as the cached data's age or the executed subprocess' runtime. |
| 1082 |
/// |
| 1083 |
/// # Errors |
| 1084 |
/// |
| 1085 |
/// If looking up, deserializing, executing, or serializing the command fails. This generally |
| 1086 |
/// reflects a user error such as an invalid command. |
| 1087 |
pub fn retrieve<T>(&self, command: T, ttl: Duration) -> Result<(Invocation, CacheStatus)> where |
| 1088 |
T: TryInto<CommandState>, |
| 1089 |
anyhow::Error: From<T::Error>, // https://stackoverflow.com/a/72627328 |
| 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 |
/// Unconditionally executes the given command and caches the invocation for the given TTL. |
| 1111 |
/// This can be used to "warm" the cache so that subsequent calls to `execute` are fast. |
| 1112 |
/// |
| 1113 |
/// The second element in the returned tuple is the subprocess' execution time. |
| 1114 |
/// |
| 1115 |
/// # Errors |
| 1116 |
/// |
| 1117 |
/// If executing or serializing the command fails. This generally reflects a user error such as |
| 1118 |
/// an invalid command. |
| 1119 |
pub fn refresh<T>(&self, command: T, ttl: Duration) -> Result<(Invocation, Duration)> where |
| 1120 |
T: TryInto<CommandState>, |
| 1121 |
anyhow::Error: From<T::Error>, // https://stackoverflow.com/a/72627328 |
| 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 |
/// Clean the cache in the background on a cache-miss; this will usually |
| 1136 |
/// be much faster than the actual background process. |
| 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 |
/// Initiates a single cleanup cycle of the cache, removing stale data in the background. This |
| 1154 |
/// should be invoked by short-lived applications early in their lifecycle and then joined |
| 1155 |
/// before exiting. `execute_and_cleanup` can be used instead to only trigger a cleanup on a |
| 1156 |
/// cache miss, avoiding the extra work on cache hits. Long-running applications should |
| 1157 |
/// typically prefer `cleanup_thread` which triggers periodic cleanups. |
| 1158 |
/// |
| 1159 |
/// # Errors |
| 1160 |
/// |
| 1161 |
/// The Result returned by joining indicates whether there were any unexpected errors while |
| 1162 |
/// cleaning up. It should be Ok in all normal circumstances. |
| 1163 |
// TODO if cleanup should always succeed (or no-op) why return Result? |
| 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 |
/// Initiates an infinite-loop thread that triggers periodic cleanups of the cache, removing |
| 1170 |
/// stale data in the background. It is not necessary to `join()` this thread, it will |
| 1171 |
/// be terminated when the main thread exits. |
| 1172 |
pub fn cleanup_thread(&self) -> std::thread::JoinHandle<()> { |
| 1173 |
let cache = self.cache.clone(); |
| 1174 |
std::thread::spawn(move || { |
| 1175 |
// Hard-coded for now, could be made configurable if needed |
| 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 |
// Note: most functionality of Bkt is tested via cli.rs |
| 1188 |
#[cfg(test)] |
| 1189 |
mod bkt_tests { |
| 1190 |
use super::*; |
| 1191 |
use test_dir::{TestDir, DirBuilder, FileType}; |
| 1192 |
|
| 1193 |
// Just validating that Bkt can be cloned to create siblings with different settings. |
| 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 |
// call is not cached |
| 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 |
// Note we haven't changed the cwd yet - use_cwd() shouldn't read it |
| 1279 |
let cmd = CommandDesc::new(["bash", "-c", "pwd; echo '.' > file"]).with_cwd(); |
| 1280 |
// Now the cwd is captured, but overwritten by with_working_dir() |
| 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 |
// now change the cwd and see it get captured lazily |
| 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 |
// and the file was only written to once, hence the cache was shared |
| 1297 |
assert_eq!(std::fs::read_to_string(wd.join("file")).unwrap(), ".\n"); |
| 1298 |
|
| 1299 |
// Restore the original cwd |
| 1300 |
// NB this could fail to be reached if the test fails, which could cause other confusing |
| 1301 |
// errors. An RAII pattern using Drop, similar to absl::Cleanup, would be nicer but I'm not |
| 1302 |
// aware of a standard pattern for this atm. |
| 1303 |
std::env::set_current_dir(old_cwd).unwrap(); |
| 1304 |
} |
| 1305 |
|
| 1306 |
#[test] |
| 1307 |
// TODO the JSON serializer doesn't support OsString keys, CommandState needs a custom |
| 1308 |
// Serializer (for feature="debug", at least) - see https://stackoverflow.com/q/51276896 |
| 1309 |
// and https://github.com/serde-rs/json/issues/809 |
| 1310 |
#[cfg(not(feature = "debug"))] |
| 1311 |
fn with_env() { |
| 1312 |
let dir = TestDir::temp().create("dir", FileType::Dir); |
| 1313 |
let cmd = CommandDesc::new(["bash", "-c", r#"echo "FOO:${FOO:?}""#]).capture_state().unwrap() |
| 1314 |
.with_env("FOO", "bar"); |
| 1315 |
let bkt = Bkt::create(dir.path("cache")).unwrap(); |
| 1316 |
let (result, status) = bkt.retrieve(cmd, Duration::from_secs(10)).unwrap(); |
| 1317 |
assert_eq!(result.stderr_utf8(), ""); |
| 1318 |
assert_eq!(result.exit_code(), 0); |
| 1319 |
assert_eq!(result.stdout_utf8(), "FOO:bar\n"); |
| 1320 |
assert!(status.is_miss()); |
| 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 |
// Update the file _and_ reset its modtime because modtime is not consistently updated e.g. |
| 1337 |
// if writes are too close together. |
| 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()); // cached |
| 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 |
} |