Skip to main content

mur_common/config/
consult.rs

1//! Channel consult tuning (`consult:`).
2
3use super::*;
4
5/// Default lifetime of an `Ask`, in seconds: how long after it is written a
6/// consult may still answer it.
7pub const CONSULT_DEFAULT_ASK_EXPIRY_SECS: u64 = 600;
8
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10pub struct ConsultConfig {
11    /// Seconds an `Ask` stays answerable. Signed into the event as
12    /// `expires_at_ms`; consult refuses an `Ask` past it. `0` is not a
13    /// usable window (every `Ask` would be born expired), so it means the
14    /// default.
15    #[serde(default = "consult_default_ask_expiry_secs")]
16    pub ask_expiry_secs: u64,
17}
18
19fn consult_default_ask_expiry_secs() -> u64 {
20    CONSULT_DEFAULT_ASK_EXPIRY_SECS
21}
22
23impl Default for ConsultConfig {
24    fn default() -> Self {
25        Self {
26            ask_expiry_secs: CONSULT_DEFAULT_ASK_EXPIRY_SECS,
27        }
28    }
29}
30
31impl ConsultConfig {
32    /// The window an `Ask` written now is answerable for.
33    pub fn ask_expiry(&self) -> std::time::Duration {
34        let secs = match self.ask_expiry_secs {
35            0 => CONSULT_DEFAULT_ASK_EXPIRY_SECS,
36            s => s,
37        };
38        std::time::Duration::from_secs(secs)
39    }
40
41    /// `expires_at_ms` for an `Ask` written at `now_ms` (Unix milliseconds).
42    /// Saturates rather than wrapping on an absurd configured window.
43    pub fn ask_expires_at_ms(&self, now_ms: u64) -> u64 {
44        let window = u64::try_from(self.ask_expiry().as_millis()).unwrap_or(u64::MAX);
45        now_ms.saturating_add(window)
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn config_without_consult_block_uses_the_default() {
55        let c: Config = serde_yaml::from_str("llm: {}\n").unwrap();
56        assert_eq!(c.consult.ask_expiry_secs, CONSULT_DEFAULT_ASK_EXPIRY_SECS);
57        assert_eq!(c.consult.ask_expires_at_ms(1_000), 1_000 + 600_000);
58    }
59
60    #[test]
61    fn configured_window_is_used() {
62        let c: Config = serde_yaml::from_str("consult:\n  ask_expiry_secs: 30\n").unwrap();
63        assert_eq!(c.consult.ask_expires_at_ms(5_000), 35_000);
64    }
65
66    #[test]
67    fn zero_means_default_not_born_expired() {
68        let c = ConsultConfig { ask_expiry_secs: 0 };
69        assert_eq!(c.ask_expiry().as_secs(), CONSULT_DEFAULT_ASK_EXPIRY_SECS);
70    }
71
72    #[test]
73    fn huge_window_saturates() {
74        let c = ConsultConfig {
75            ask_expiry_secs: u64::MAX,
76        };
77        assert_eq!(c.ask_expires_at_ms(10), u64::MAX);
78    }
79}