Skip to main content

remem/
hook_runtime.rs

1//! Process-wide hook invocation mode (GH-952).
2//!
3//! Host hooks (SessionStart context, session-init, observe, summarize) run
4//! under tight host budgets, so embedding network calls made from a hook
5//! process are capped to a short deadline. A capped call that times out
6//! degrades through the configured embedding fallback chain with an error
7//! log instead of stalling the hook.
8
9use std::sync::atomic::{AtomicBool, Ordering};
10
11use anyhow::{bail, Result};
12
13pub const DEFAULT_HOOK_EMBEDDING_TIMEOUT_SECS: u64 = 2;
14pub const ENV_HOOK_EMBEDDING_TIMEOUT_SECS: &str = "REMEM_EMBEDDINGS_HOOK_TIMEOUT_SECS";
15
16static HOOK_RUNTIME_MODE: AtomicBool = AtomicBool::new(false);
17
18/// Mark this process as a host hook invocation. One-way for the process
19/// lifetime: hook entrypoints are always dedicated short-lived processes.
20pub fn enter_hook_runtime_mode() {
21    HOOK_RUNTIME_MODE.store(true, Ordering::Relaxed);
22}
23
24pub fn hook_runtime_mode() -> bool {
25    HOOK_RUNTIME_MODE.load(Ordering::Relaxed)
26}
27
28/// The embedding network deadline cap for hook processes, in seconds.
29pub fn hook_embedding_timeout_secs() -> Result<u64> {
30    match std::env::var(ENV_HOOK_EMBEDDING_TIMEOUT_SECS) {
31        Ok(raw) if !raw.trim().is_empty() => parse_hook_timeout_secs(raw.trim()),
32        _ => Ok(DEFAULT_HOOK_EMBEDDING_TIMEOUT_SECS),
33    }
34}
35
36fn parse_hook_timeout_secs(raw: &str) -> Result<u64> {
37    match raw.parse::<u64>() {
38        Ok(secs) if secs > 0 => Ok(secs),
39        _ => bail!("{ENV_HOOK_EMBEDDING_TIMEOUT_SECS} must be a positive integer, got {raw:?}"),
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::parse_hook_timeout_secs;
46
47    #[test]
48    fn parses_positive_seconds() {
49        assert_eq!(parse_hook_timeout_secs("1").unwrap(), 1);
50        assert_eq!(parse_hook_timeout_secs("30").unwrap(), 30);
51    }
52
53    #[test]
54    fn rejects_zero_and_garbage() {
55        assert!(parse_hook_timeout_secs("0").is_err());
56        assert!(parse_hook_timeout_secs("-1").is_err());
57        assert!(parse_hook_timeout_secs("abc").is_err());
58    }
59}