Skip to main content

beszel_protocol/
upstream.rs

1//! Defensive wire types for Beszel / PocketBase HTTP and SSE payloads.
2
3use serde::{Deserialize, Serialize};
4
5use crate::local::LiveSample;
6
7const GIB_BYTES: f64 = 1024.0 * 1024.0 * 1024.0;
8
9/// PocketBase realtime topic for watching changes to the `systems` collection.
10pub const SYSTEMS_COLLECTION_TOPIC: &str = "systems/*";
11
12/// PocketBase realtime event payload emitted for `systems/*`.
13#[derive(Debug, Clone, Deserialize)]
14pub struct SystemsRealtimeEvent {
15    pub action: String,
16    pub record: UpstreamSystemRecord,
17}
18
19/// PocketBase `POST /api/collections/users/auth-with-password` response.
20#[derive(Debug, Clone, Deserialize)]
21pub struct AuthResponse {
22    pub token: String,
23}
24
25/// PocketBase `GET /api/collections/systems/records` paginated response.
26#[derive(Debug, Clone, Deserialize)]
27pub struct SystemsListResponse {
28    #[serde(default)]
29    pub items: Vec<UpstreamSystemRecord>,
30}
31
32/// System record returned by Beszel's `systems` collection.
33#[derive(Debug, Clone, Deserialize)]
34pub struct UpstreamSystemRecord {
35    pub id: String,
36    pub name: String,
37    #[serde(default)]
38    pub status: String,
39    #[serde(default)]
40    pub info: Option<UpstreamSystemInfo>,
41}
42
43/// PocketBase `PB_CONNECT` SSE event payload.
44#[derive(Debug, Clone, Deserialize)]
45#[serde(rename_all = "camelCase")]
46pub struct PbConnectEvent {
47    pub client_id: String,
48}
49
50/// PocketBase `POST /api/realtime` subscription request body.
51#[derive(Debug, Clone, Serialize)]
52#[serde(rename_all = "camelCase")]
53pub struct RealtimeSubscribeRequest {
54    pub client_id: String,
55    pub subscriptions: Vec<String>,
56}
57
58/// Live `rt_metrics` SSE payload emitted by Beszel hub (~1 Hz).
59#[derive(Debug, Clone, Deserialize)]
60pub struct RtMetricsPayload {
61    #[serde(default)]
62    pub stats: Option<UpstreamStats>,
63    #[serde(default)]
64    pub info: Option<UpstreamSystemInfo>,
65}
66
67/// Summary fields carried on system records and `rt_metrics.info`.
68#[derive(Debug, Clone, Default, Deserialize)]
69pub struct UpstreamSystemInfo {
70    /// Agent semantic version (e.g. `"0.21.2"`).
71    #[serde(default)]
72    pub v: Option<String>,
73    /// System uptime in seconds.
74    #[serde(default)]
75    pub u: Option<u64>,
76    /// CPU percent summary.
77    #[serde(default)]
78    pub cpu: Option<f64>,
79    /// Memory percent summary.
80    #[serde(default)]
81    pub mp: Option<f64>,
82}
83
84/// Detailed live system metrics carried in `rt_metrics.stats`.
85///
86/// Upstream Go structs use `omitzero` / `omitempty` extensively; all fields
87/// remain optional so minor Beszel releases or zero ticks decode cleanly.
88#[derive(Debug, Clone, Default, Deserialize)]
89pub struct UpstreamStats {
90    /// Total CPU utilization percent.
91    #[serde(default)]
92    pub cpu: Option<f64>,
93    /// Per-core busy utilization percentages (`[CPU0..]`).
94    #[serde(default)]
95    pub cpus: Option<Vec<u8>>,
96    /// Memory utilization percent.
97    #[serde(default)]
98    pub mp: Option<f64>,
99    /// Byte-accurate memory `[total, used, buff_cache, zfs_arc]`.
100    #[serde(default)]
101    pub mem: Option<[u64; 4]>,
102    /// Byte-accurate swap `[total, used]`.
103    #[serde(default)]
104    pub swap: Option<[u64; 2]>,
105    /// Deprecated total memory in GiB (fallback when `mem` is absent).
106    #[serde(default)]
107    pub m: Option<f64>,
108    /// Deprecated used memory in GiB (fallback when `mem` is absent).
109    #[serde(default)]
110    pub mu: Option<f64>,
111    /// Deprecated buffer/cache memory in GiB (fallback when `mem` is absent).
112    #[serde(default)]
113    pub mb: Option<f64>,
114}
115
116impl RtMetricsPayload {
117    /// Extract a normalized live CPU/memory sample stamped with `timestamp_ms`.
118    pub fn to_live_sample(&self, timestamp_ms: i64) -> Option<LiveSample> {
119        let stats = self.stats.as_ref()?;
120        let cpu_pct = stats
121            .cpu
122            .or_else(|| self.info.as_ref().and_then(|i| i.cpu))?;
123        let mem_pct = stats.mp.or_else(|| self.info.as_ref().and_then(|i| i.mp))?;
124
125        let (mem_total_bytes, mem_used_bytes, mem_buff_cache_bytes) = stats.memory_bytes();
126        let (swap_total_bytes, swap_used_bytes) = stats.swap_bytes();
127
128        Some(LiveSample {
129            timestamp_ms,
130            cpu_pct,
131            cpu_cores: stats.cpus.clone(),
132            mem_pct,
133            mem_used_bytes,
134            mem_total_bytes,
135            mem_buff_cache_bytes,
136            swap_used_bytes,
137            swap_total_bytes,
138        })
139    }
140}
141
142impl UpstreamStats {
143    fn memory_bytes(&self) -> (Option<u64>, Option<u64>, Option<u64>) {
144        if let Some([total, used, buff_cache, _zfs_arc]) = self.mem
145            && total > 0
146        {
147            return (Some(total), Some(used), Some(buff_cache));
148        }
149        (
150            self.m.and_then(gib_to_bytes),
151            self.mu.and_then(gib_to_bytes),
152            self.mb.and_then(gib_to_bytes),
153        )
154    }
155
156    fn swap_bytes(&self) -> (Option<u64>, Option<u64>) {
157        match self.swap {
158            Some([total, used]) => (Some(total), Some(used)),
159            None => (None, None),
160        }
161    }
162}
163
164fn gib_to_bytes(gib: f64) -> Option<u64> {
165    if !gib.is_finite() || gib < 0.0 {
166        return None;
167    }
168    Some((gib * GIB_BYTES).round() as u64)
169}
170
171/// Build the PocketBase realtime subscription topic string for a Beszel system ID.
172pub fn rt_metrics_topic(system_id: &str) -> String {
173    let options_json = serde_json::json!({
174        "query": {
175            "system": system_id,
176        }
177    })
178    .to_string();
179    format!("rt_metrics?options={}", percent_encode(&options_json))
180}
181
182fn percent_encode(input: &str) -> String {
183    let mut encoded = String::with_capacity(input.len() * 2);
184    for byte in input.bytes() {
185        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
186            encoded.push(byte as char);
187        } else {
188            encoded.push('%');
189            encoded.push(hex_nibble(byte >> 4));
190            encoded.push(hex_nibble(byte & 0x0f));
191        }
192    }
193    encoded
194}
195
196fn hex_nibble(value: u8) -> char {
197    match value {
198        0..=9 => (b'0' + value) as char,
199        10..=15 => (b'A' + (value - 10)) as char,
200        _ => unreachable!(),
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[derive(Deserialize)]
209    struct FixtureFile {
210        event_topic_template: String,
211        samples: Vec<RtMetricsPayload>,
212    }
213
214    #[test]
215    fn builds_expected_rt_metrics_topic() {
216        let topic = rt_metrics_topic("abc123456789012");
217        assert_eq!(
218            topic,
219            "rt_metrics?options=%7B%22query%22%3A%7B%22system%22%3A%22abc123456789012%22%7D%7D"
220        );
221    }
222
223    #[test]
224    fn decodes_sanitized_live_fixture_samples() {
225        let raw = include_str!("../../../docs/fixtures/rt_metrics_sample.json");
226        let fixture: FixtureFile = serde_json::from_str(raw).expect("fixture should parse");
227        assert_eq!(
228            fixture.event_topic_template,
229            "rt_metrics?options=%7B%22query%22%3A%7B%22system%22%3A%22<SYSTEM_ID>%22%7D%7D"
230        );
231        assert_eq!(fixture.samples.len(), 2);
232
233        let first = fixture.samples[0]
234            .to_live_sample(1_700_000_000_000)
235            .expect("first sample should convert");
236        assert_eq!(first.cpu_pct, 4.95);
237        assert_eq!(
238            first.cpu_cores.as_deref(),
239            Some(&[0, 0, 0, 0, 0, 0, 8, 8, 8, 7, 8, 8, 9, 8, 8, 8][..])
240        );
241        assert_eq!(first.mem_pct, 13.45);
242        assert_eq!(first.mem_total_bytes, Some(66_916_192_256));
243        assert_eq!(first.mem_used_bytes, Some(8_998_420_480));
244        assert_eq!(first.mem_buff_cache_bytes, Some(14_000_463_872));
245        assert_eq!(first.swap_total_bytes, Some(8_589_930_496));
246        assert_eq!(first.swap_used_bytes, Some(0));
247
248        let second = fixture.samples[1]
249            .to_live_sample(1_700_000_001_000)
250            .expect("second sample should convert");
251        assert_eq!(second.cpu_pct, 3.67);
252        assert_eq!(second.mem_pct, 13.44);
253    }
254
255    #[test]
256    fn falls_back_to_gib_memory_fields_when_mem_bytes_absent() {
257        let payload: RtMetricsPayload =
258            serde_json::from_str(r#"{"stats":{"cpu":12.5,"mp":50.0,"m":16.0,"mu":8.0,"mb":2.0}}"#)
259                .expect("fallback payload should parse");
260
261        let sample = payload
262            .to_live_sample(42)
263            .expect("fallback sample should convert");
264        assert_eq!(sample.mem_total_bytes, Some(16 * 1024 * 1024 * 1024));
265        assert_eq!(sample.mem_used_bytes, Some(8 * 1024 * 1024 * 1024));
266        assert_eq!(sample.mem_buff_cache_bytes, Some(2 * 1024 * 1024 * 1024));
267    }
268
269    #[test]
270    fn decodes_systems_collection_realtime_event() {
271        let raw = r#"{"action":"update","record":{"id":"sys123456789012","name":"workstation","status":"up","info":{"v":"0.21.2"}}}"#;
272        let event: SystemsRealtimeEvent =
273            serde_json::from_str(raw).expect("systems event should parse");
274        assert_eq!(event.action, "update");
275        assert_eq!(event.record.id, "sys123456789012");
276        assert_eq!(event.record.name, "workstation");
277        assert_eq!(event.record.status, "up");
278        assert_eq!(
279            event.record.info.as_ref().and_then(|i| i.v.as_deref()),
280            Some("0.21.2")
281        );
282    }
283}