Skip to main content

modo/sse/
config.rs

1use serde::Deserialize;
2use std::time::Duration;
3
4fn default_keep_alive_interval_secs() -> u64 {
5    15
6}
7
8/// Configuration for Server-Sent Events.
9///
10/// Controls keep-alive behavior for SSE connections. Loaded from the `sse`
11/// section of your application config YAML.
12///
13/// # Example
14///
15/// ```yaml
16/// sse:
17///     keep_alive_interval_secs: 30
18/// ```
19///
20/// # Defaults
21///
22/// | Field | Default |
23/// |-------|---------|
24/// | `keep_alive_interval_secs` | `15` |
25#[non_exhaustive]
26#[derive(Debug, Clone, Deserialize)]
27#[serde(default)]
28pub struct SseConfig {
29    /// Keep-alive interval in seconds. The server sends a comment line (`:`)
30    /// at this interval to prevent proxies and browsers from closing idle
31    /// connections.
32    pub keep_alive_interval_secs: u64,
33}
34
35impl Default for SseConfig {
36    fn default() -> Self {
37        Self {
38            keep_alive_interval_secs: default_keep_alive_interval_secs(),
39        }
40    }
41}
42
43impl SseConfig {
44    /// Returns the keep-alive interval as a [`Duration`].
45    pub fn keep_alive_interval(&self) -> Duration {
46        Duration::from_secs(self.keep_alive_interval_secs)
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn default_keep_alive_is_15_seconds() {
56        let config = SseConfig::default();
57        assert_eq!(config.keep_alive_interval_secs, 15);
58        assert_eq!(
59            config.keep_alive_interval(),
60            std::time::Duration::from_secs(15)
61        );
62    }
63
64    #[test]
65    fn deserialize_from_yaml() {
66        let yaml = "keep_alive_interval_secs: 30";
67        let config: SseConfig = serde_yaml_ng::from_str(yaml).unwrap();
68        assert_eq!(config.keep_alive_interval_secs, 30);
69        assert_eq!(
70            config.keep_alive_interval(),
71            std::time::Duration::from_secs(30)
72        );
73    }
74
75    #[test]
76    fn deserialize_empty_uses_defaults() {
77        let yaml = "{}";
78        let config: SseConfig = serde_yaml_ng::from_str(yaml).unwrap();
79        assert_eq!(config.keep_alive_interval_secs, 15);
80    }
81}