Skip to main content

active_call/
runtime.rs

1//! Live runtime state derived from the configuration snapshot.
2//!
3//! `AppStateInner` holds the hot-swappable `Config`, but the media engine's
4//! processor hooks are built once and only receive a `TrackConfig`, so the
5//! module switches they need live here in a process-wide `ArcSwap`. The
6//! reload path (`AppStateInner::reload_config`) updates both atomically
7//! enough for our purposes: a call reads whatever snapshot is current when it
8//! is set up.
9//!
10//! Precedence for a module switch, highest first:
11//!   1. the ops toggle file (`PBX_TOGGLE_FILE`, default `/app/.env`) — the
12//!      emergency switch operators already use, read per call;
13//!   2. `[modules]` in the active-call config file (hot-reloaded);
14//!   3. enabled.
15
16use std::path::{Path, PathBuf};
17use std::sync::Arc;
18
19use arc_swap::ArcSwap;
20use once_cell::sync::Lazy;
21
22use crate::config::{Config, RuntimeModule};
23
24/// Effective module switches for the current config snapshot.
25#[derive(Debug, Clone)]
26pub struct ModuleSwitches {
27    pub denoise: bool,
28    pub vad: bool,
29    pub eou: bool,
30    pub ringback_detection: bool,
31    pub sipflow: bool,
32    pub playbooks: bool,
33}
34
35impl Default for ModuleSwitches {
36    fn default() -> Self {
37        Self {
38            denoise: true,
39            vad: true,
40            eou: true,
41            ringback_detection: true,
42            sipflow: true,
43            playbooks: true,
44        }
45    }
46}
47
48impl ModuleSwitches {
49    pub fn from_config(config: &Config) -> Self {
50        Self {
51            denoise: config.module_enabled(RuntimeModule::Denoise),
52            vad: config.module_enabled(RuntimeModule::Vad),
53            eou: config.module_enabled(RuntimeModule::Eou),
54            ringback_detection: config.module_enabled(RuntimeModule::RingbackDetection),
55            sipflow: config.module_enabled(RuntimeModule::Sipflow),
56            playbooks: config.module_enabled(RuntimeModule::Playbooks),
57        }
58    }
59}
60
61static MODULE_SWITCHES: Lazy<ArcSwap<ModuleSwitches>> =
62    Lazy::new(|| ArcSwap::from_pointee(ModuleSwitches::default()));
63
64/// Current module switches (cheap `Arc` clone; taken once per call setup).
65pub fn module_switches() -> Arc<ModuleSwitches> {
66    MODULE_SWITCHES.load_full()
67}
68
69/// Publish the switches derived from a freshly loaded config. Called at
70/// startup and on every successful reload.
71pub fn apply_config(config: &Config) {
72    MODULE_SWITCHES.store(Arc::new(ModuleSwitches::from_config(config)));
73}
74
75/// Ops-managed toggle file. The deploy mounts the env file into the
76/// container; overridable via `PBX_TOGGLE_FILE` for tests/embedders.
77pub fn toggle_file_path() -> PathBuf {
78    std::env::var("PBX_TOGGLE_FILE")
79        .unwrap_or_else(|_| "/app/.env".to_string())
80        .into()
81}
82
83/// Value of `key` in the toggle file: `Some(false)` when it is explicitly
84/// disabled, `Some(true)` when explicitly enabled, `None` when absent (so the
85/// caller's configured default applies).
86pub fn toggle_value(key: &str) -> Option<bool> {
87    toggle_value_from(&toggle_file_path(), key)
88}
89
90/// Same as [`toggle_value`] but against an explicit path (tests).
91/// `KEY=false|0|off` disables; `KEY=true|1|on` enables; anything else is
92/// treated as absent. Lines starting with `#` are ignored.
93pub fn toggle_value_from(path: &Path, key: &str) -> Option<bool> {
94    let content = std::fs::read_to_string(path).ok()?;
95    let prefix = format!("{}=", key);
96    for line in content.lines() {
97        let line = line.trim();
98        if line.is_empty() || line.starts_with('#') {
99            continue;
100        }
101        if let Some(value) = line.strip_prefix(&prefix) {
102            let value = value.trim().trim_matches('"').to_ascii_lowercase();
103            return match value.as_str() {
104                "false" | "0" | "off" => Some(false),
105                "true" | "1" | "on" => Some(true),
106                _ => None,
107            };
108        }
109    }
110    None
111}
112
113/// Resolve a module switch: toggle-file override first, then the value from
114/// the current config snapshot.
115pub fn module_override(key: &str, configured: bool) -> bool {
116    toggle_value(key).unwrap_or(configured)
117}
118
119#[cfg(test)]
120mod tests {
121    use super::{ModuleSwitches, toggle_value_from};
122    use crate::config::{AdmissionConfig, Config, ModulesConfig, ModuleToggle, RuntimeModule};
123
124    fn temp_toggle_file(name: &str) -> std::path::PathBuf {
125        let dir = std::env::temp_dir().join(format!(
126            "ac_runtime_toggle_{}_{}",
127            std::process::id(),
128            name
129        ));
130        std::fs::create_dir_all(&dir).unwrap();
131        dir.join("app.env")
132    }
133
134    #[test]
135    fn toggle_file_values() {
136        let path = temp_toggle_file("values");
137        std::fs::remove_file(&path).ok();
138        // Missing file: nothing is specified.
139        assert_eq!(toggle_value_from(&path, "DENOISE_ENABLED"), None);
140
141        std::fs::write(&path, "RUST_LOG=info\nDENOISE_ENABLED=false\n").unwrap();
142        assert_eq!(toggle_value_from(&path, "DENOISE_ENABLED"), Some(false));
143        assert_eq!(toggle_value_from(&path, "EOU_ENABLED"), None);
144
145        std::fs::write(&path, "DENOISE_ENABLED=\"on\"\n").unwrap();
146        assert_eq!(toggle_value_from(&path, "DENOISE_ENABLED"), Some(true));
147
148        std::fs::write(&path, "DENOISE_ENABLED=maybe\n").unwrap();
149        assert_eq!(toggle_value_from(&path, "DENOISE_ENABLED"), None);
150    }
151
152    #[test]
153    fn modules_come_from_config_with_defaults() {
154        let mut config = Config::default();
155        assert!(config.module_enabled(RuntimeModule::Denoise));
156
157        config.modules = Some(ModulesConfig {
158            denoise: Some(ModuleToggle { enabled: false }),
159            ..Default::default()
160        });
161        assert!(!config.module_enabled(RuntimeModule::Denoise));
162        assert!(config.module_enabled(RuntimeModule::Vad));
163
164        let switches = ModuleSwitches::from_config(&config);
165        assert!(!switches.denoise);
166        assert!(switches.sipflow);
167    }
168
169    #[test]
170    fn admission_defaults() {
171        let config = Config::default();
172        assert_eq!(config.admission_max_calls(), 0);
173        assert_eq!(config.admission_wait_ms(), 5_000);
174
175        let mut config = Config::default();
176        config.admission = Some(AdmissionConfig {
177            max_active_calls: Some(120),
178            wait_ms: Some(1500),
179        });
180        assert_eq!(config.admission_max_calls(), 120);
181        assert_eq!(config.admission_wait_ms(), 1500);
182    }
183}