Skip to main content

asimov_patterns/options/
caching.rs

1// This is free and unencumbered software released into the public domain.
2
3//! Shared cache freshness options for source commands.
4
5#[cfg(feature = "clap")]
6use alloc::string::ToString;
7#[cfg(any(feature = "std", feature = "clap"))]
8use alloc::{format, string::String};
9use bon::Builder;
10use core::time::Duration;
11
12#[cfg(feature = "clap")]
13const HELP_MAX_AGE: &str = r#"Maximum acceptable cache age.
14
15Use a positive duration such as 1h, 7d, or "1m 30s".
16If omitted, the default is module-specific."#;
17
18/// Cache freshness requests shared by fetcher and lister commands.
19///
20/// Flatten this alongside [`crate::FetcherOptions`] or [`crate::ListerOptions`]
21/// in a host's Clap arguments. The maximum age defaults to `None`, leaving
22/// policy to the selected module. Clap accepts durations such as `1h`,
23/// `7d`, or `1m 30s`; it rejects a zero maximum age.
24/// Builders and direct field assignments do not validate durations.
25///
26/// These options describe requests; they do not implement caching. Hosts can
27/// forward explicit values using `max_age_option()` (available with `std` or
28/// `clap`). Execution deadlines are configured separately by
29/// [`crate::TimingOptions`].
30#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Builder)]
31#[builder(derive(Debug))]
32#[cfg_attr(feature = "clap", derive(clap::Args))]
33#[cfg_attr(feature = "clap", command(about = None, long_about = None))]
34pub struct CachingOptions {
35    /// Maximum acceptable cache age (for example, 1h or 7d).
36    /// Default is module-specific.
37    #[cfg_attr(
38        feature = "clap",
39        clap(
40            long,
41            value_name = "DURATION",
42            value_parser = parse_max_age,
43            help = "Maximum acceptable cache age",
44            long_help = HELP_MAX_AGE
45        )
46    )]
47    pub max_age: Option<Duration>,
48}
49
50#[cfg(any(feature = "std", feature = "clap"))]
51impl CachingOptions {
52    /// Formats an explicit maximum age as one `--max-age=DURATION` argument.
53    ///
54    /// Returns `None` when unset, preserving the module's default policy.
55    pub fn max_age_option(&self) -> Option<String> {
56        self.max_age
57            .map(|value| format!("--max-age={}", humantime::format_duration(value)))
58    }
59}
60
61#[cfg(feature = "clap")]
62fn parse_max_age(value: &str) -> Result<Duration, String> {
63    let duration = humantime::parse_duration(value).map_err(|error| error.to_string())?;
64    if duration.is_zero() {
65        return Err("max age must be positive".into());
66    }
67    Ok(duration)
68}