Skip to main content

vector_core/
blossom_stats.rs

1//! Per-server latency, speed and reachability, and the one-word status the
2//! list shows.
3//!
4//! One row per server, no history: latency and speed are exponentially
5//! weighted averages, the last few upload speeds ride along as a short array
6//! for a sparkline. The footprint does not grow with use.
7//!
8//! Latency is the BUD-06 preflight round-trip — a small request, so it is
9//! dominated by distance and server load and comparable between servers.
10//! Speed is this device's throughput to the server, which the uplink caps:
11//! shown as a number, never graded.
12
13use serde::{Deserialize, Serialize};
14
15/// Weight of a new sample against the running average.
16const ALPHA: f64 = 0.3;
17/// Below this an upload is all round-trip and says nothing about throughput.
18pub const MIN_SPEED_SAMPLE_BYTES: u64 = 256 * 1024;
19/// Sparkline length.
20const RECENT_MAX: usize = 12;
21/// A failure this old with nothing since no longer means the server is down.
22const OFFLINE_WINDOW_SECS: i64 = 30 * 60;
23/// A quota refusal is good for the rest of the day at most.
24const MAXED_WINDOW_SECS: i64 = 24 * 3600;
25
26pub const FAIL_OFFLINE: &str = "offline";
27pub const FAIL_MAXED: &str = "maxed";
28
29/// One recent upload: its speed and its size, stored as `[mbps, bytes]`.
30/// Rows written before sizes were kept hold a bare number and read back with
31/// `bytes: 0`.
32#[derive(Clone, Copy, Debug, PartialEq)]
33pub struct Sample {
34    pub mbps: f32,
35    pub bytes: u64,
36}
37
38impl Serialize for Sample {
39    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
40        (self.mbps, self.bytes).serialize(s)
41    }
42}
43
44impl<'de> Deserialize<'de> for Sample {
45    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
46        #[derive(Deserialize)]
47        #[serde(untagged)]
48        enum Shape {
49            Pair(f32, u64),
50            Bare(f32),
51        }
52        Ok(match Shape::deserialize(d)? {
53            Shape::Pair(mbps, bytes) => Sample { mbps, bytes },
54            Shape::Bare(mbps) => Sample { mbps, bytes: 0 },
55        })
56    }
57}
58
59#[derive(Clone, Debug, Serialize, PartialEq)]
60pub struct ServerStats {
61    pub latency_ms: Option<f64>,
62    pub mbps: Option<f64>,
63    pub best_mbps: Option<f64>,
64    pub uploads: u64,
65    pub bytes_total: u64,
66    pub last_ok_at: Option<i64>,
67    pub last_fail_at: Option<i64>,
68    pub last_fail_kind: Option<String>,
69    /// Recent uploads, oldest first.
70    pub recent: Vec<Sample>,
71}
72
73/// The list's one-word answer to "will my next upload here work?".
74#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
75pub struct ServerStatus {
76    /// `online` · `offline` · `maxed` · `no_access` · `disabled` · `untested`
77    pub state: &'static str,
78    pub label: &'static str,
79    /// A `.relay-status` modifier: `connected` · `connecting` · `disconnected` · `disabled`
80    pub tone: &'static str,
81    pub latency_ms: Option<u32>,
82}
83
84fn now_secs() -> i64 {
85    crate::clock::now_secs() as i64
86}
87
88fn norm_url(url: &str) -> String {
89    url.trim().trim_end_matches('/').to_lowercase()
90}
91
92fn ewma(prev: Option<f64>, sample: f64) -> f64 {
93    match prev {
94        Some(p) => p + ALPHA * (sample - p),
95        None => sample,
96    }
97}
98
99// ============================================================================
100// Storage
101// ============================================================================
102
103pub fn migrate(tx: &rusqlite::Transaction<'_>) -> Result<(), String> {
104    tx.execute_batch(
105        "CREATE TABLE IF NOT EXISTS blossom_server_stats (
106            server_url     TEXT    PRIMARY KEY,
107            latency_ms     REAL,
108            mbps           REAL,
109            best_mbps      REAL,
110            uploads        INTEGER NOT NULL DEFAULT 0,
111            bytes_total    INTEGER NOT NULL DEFAULT 0,
112            last_ok_at     INTEGER,
113            last_fail_at   INTEGER,
114            last_fail_kind TEXT,
115            recent         TEXT    NOT NULL DEFAULT '[]',
116            updated_at     INTEGER NOT NULL
117        );",
118    )
119    .map_err(|e| format!("Failed to create blossom_server_stats table: {}", e))
120}
121
122fn read_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<ServerStats> {
123    let recent_json: String = row.get(8)?;
124    Ok(ServerStats {
125        latency_ms: row.get(0)?,
126        mbps: row.get(1)?,
127        best_mbps: row.get(2)?,
128        uploads: row.get::<_, i64>(3)? as u64,
129        bytes_total: row.get::<_, i64>(4)? as u64,
130        last_ok_at: row.get(5)?,
131        last_fail_at: row.get(6)?,
132        last_fail_kind: row.get(7)?,
133        recent: serde_json::from_str(&recent_json).unwrap_or_default(),
134    })
135}
136
137const SELECT: &str = "SELECT latency_ms, mbps, best_mbps, uploads, bytes_total, last_ok_at, last_fail_at, last_fail_kind, recent
138                        FROM blossom_server_stats WHERE server_url = ?1";
139
140pub fn stats_for(server_url: &str) -> Option<ServerStats> {
141    let conn = crate::db::get_db_connection_guard_static().ok()?;
142    conn.query_row(SELECT, rusqlite::params![norm_url(server_url)], read_row).ok()
143}
144
145fn load_or_default(conn: &rusqlite::Connection, server: &str) -> ServerStats {
146    conn.query_row(SELECT, rusqlite::params![server], read_row)
147        .unwrap_or(ServerStats {
148            latency_ms: None,
149            mbps: None,
150            best_mbps: None,
151            uploads: 0,
152            bytes_total: 0,
153            last_ok_at: None,
154            last_fail_at: None,
155            last_fail_kind: None,
156            recent: Vec::new(),
157        })
158}
159
160fn save(conn: &rusqlite::Connection, server: &str, s: &ServerStats) -> Result<(), String> {
161    conn.execute(
162        "INSERT INTO blossom_server_stats
163            (server_url, latency_ms, mbps, best_mbps, uploads, bytes_total, last_ok_at, last_fail_at, last_fail_kind, recent, updated_at)
164         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
165         ON CONFLICT(server_url) DO UPDATE SET
166            latency_ms = ?2, mbps = ?3, best_mbps = ?4, uploads = ?5, bytes_total = ?6,
167            last_ok_at = ?7, last_fail_at = ?8, last_fail_kind = ?9, recent = ?10, updated_at = ?11",
168        rusqlite::params![
169            server, s.latency_ms, s.mbps, s.best_mbps, s.uploads as i64, s.bytes_total as i64,
170            s.last_ok_at, s.last_fail_at, s.last_fail_kind,
171            serde_json::to_string(&s.recent).unwrap_or_else(|_| "[]".to_string()),
172            now_secs(),
173        ],
174    )
175    .map_err(|e| format!("Failed to save server stats: {}", e))?;
176    Ok(())
177}
178
179fn update(server_url: &str, f: impl FnOnce(&mut ServerStats)) {
180    let Ok(conn) = crate::db::get_write_connection_guard_static() else { return };
181    let server = norm_url(server_url);
182    let mut s = load_or_default(&conn, &server);
183    f(&mut s);
184    if let Err(e) = save(&conn, &server, &s) {
185        crate::log_warn!("[Blossom Stats] {}: {}", server, e);
186    }
187    drop(conn);
188    // The list's pill is derived from this row.
189    crate::traits::emit_event("blossom_status_updated", &());
190}
191
192/// A small request answered in `ms`.
193pub fn record_latency(server_url: &str, ms: f64) {
194    if ms <= 0.0 { return; }
195    update(server_url, |s| {
196        s.latency_ms = Some(ewma(s.latency_ms, ms));
197        s.last_ok_at = Some(now_secs());
198    });
199}
200
201/// `bytes` accepted in `ms`. Small uploads are ignored: they measure the
202/// round-trip, not the pipe.
203pub fn record_upload(server_url: &str, bytes: u64, ms: f64) {
204    if bytes < MIN_SPEED_SAMPLE_BYTES || ms <= 0.0 { return; }
205    let mbps = (bytes as f64 * 8.0) / (ms / 1000.0) / 1_000_000.0;
206    update(server_url, |s| {
207        s.mbps = Some(ewma(s.mbps, mbps));
208        s.best_mbps = Some(s.best_mbps.map_or(mbps, |b| b.max(mbps)));
209        s.uploads += 1;
210        s.bytes_total += bytes;
211        s.last_ok_at = Some(now_secs());
212        s.recent.push(Sample { mbps: mbps as f32, bytes });
213        if s.recent.len() > RECENT_MAX {
214            let drop = s.recent.len() - RECENT_MAX;
215            s.recent.drain(..drop);
216        }
217    });
218}
219
220/// The server answered, whatever it said: it is reachable.
221pub fn record_ok(server_url: &str) {
222    update(server_url, |s| s.last_ok_at = Some(now_secs()));
223}
224
225/// `kind` is [`FAIL_OFFLINE`] or [`FAIL_MAXED`].
226pub fn record_failure(server_url: &str, kind: &str) {
227    update(server_url, |s| {
228        s.last_fail_at = Some(now_secs());
229        s.last_fail_kind = Some(kind.to_string());
230    });
231}
232
233// ============================================================================
234// Status
235// ============================================================================
236
237/// Pure: what the list should say, from what is known. `info` is the
238/// server's document when it has one; `stats` this device's history.
239pub fn derive_status(
240    enabled: bool,
241    info: Option<&crate::blossom_info::ServerInfo>,
242    stats: Option<&ServerStats>,
243    now: i64,
244) -> ServerStatus {
245    let latency_ms = stats.and_then(|s| s.latency_ms).map(|l| l.round() as u32);
246    let status = |state: &'static str, label: &'static str, tone: &'static str| ServerStatus {
247        state, label, tone, latency_ms,
248    };
249    if !enabled {
250        return status("disabled", "Disabled", "disabled");
251    }
252    if let Some(c) = info.and_then(|i| i.caller.as_ref()) {
253        if !c.allowed {
254            return status("no_access", "No access", "disconnected");
255        }
256        let full = |used: u64, limit: u64| limit > 0 && used >= limit;
257        if full(c.storage_used, c.storage_limit) || full(c.daily_used, c.daily_limit) {
258            return status("maxed", "Maxed", "connecting");
259        }
260    }
261    if let Some(s) = stats {
262        let failed_since_ok = match (s.last_fail_at, s.last_ok_at) {
263            (Some(f), Some(o)) => f > o,
264            (Some(_), None) => true,
265            _ => false,
266        };
267        if failed_since_ok {
268            let age = now - s.last_fail_at.unwrap_or(now);
269            match s.last_fail_kind.as_deref() {
270                Some(FAIL_MAXED) if age <= MAXED_WINDOW_SECS => {
271                    return status("maxed", "Maxed", "connecting");
272                }
273                Some(FAIL_OFFLINE) if age <= OFFLINE_WINDOW_SECS => {
274                    return status("offline", "Offline", "disconnected");
275                }
276                _ => {}
277            }
278        }
279        if s.last_ok_at.is_some() {
280            return status("online", "Online", "connected");
281        }
282    }
283    if info.is_some() {
284        return status("online", "Online", "connected");
285    }
286    status("untested", "Untested", "disabled")
287}
288
289pub fn status_for(server_url: &str, enabled: bool) -> ServerStatus {
290    let info = crate::blossom_info::cached(server_url);
291    let stats = stats_for(server_url);
292    derive_status(enabled, info.as_ref(), stats.as_ref(), now_secs())
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::blossom_info::{CallerInfo, ServerInfo};
299
300    fn stats() -> ServerStats {
301        ServerStats {
302            latency_ms: Some(48.4), mbps: Some(12.0), best_mbps: Some(20.0), uploads: 3,
303            bytes_total: 3_000_000, last_ok_at: Some(1000), last_fail_at: None,
304            last_fail_kind: None,
305            recent: vec![Sample { mbps: 10.0, bytes: 0 }, Sample { mbps: 12.0, bytes: 2_000_000 }],
306        }
307    }
308
309    fn doc(caller: Option<CallerInfo>) -> ServerInfo {
310        ServerInfo {
311            name: None, software: None, version: None, description: None, buds: vec![],
312            extensions: vec![], max_blob: None, mime: vec![], capacity_used: None,
313            capacity_limit: None, caller, fetched_at: 0, raw: serde_json::Value::Null,
314        }
315    }
316
317    fn caller(allowed: bool, storage: (u64, u64), daily: (u64, u64)) -> CallerInfo {
318        CallerInfo {
319            tier: "recognised".into(), max_blob: 1, storage_used: storage.0, storage_limit: storage.1,
320            blobs: 0, daily_used: daily.0, daily_limit: daily.1, allowed, reasons: vec![],
321            plan_title: None, plan_description: None,
322        }
323    }
324
325    #[test]
326    fn disabled_wins_over_everything() {
327        let s = derive_status(false, Some(&doc(Some(caller(false, (0, 1), (0, 1))))), Some(&stats()), 2000);
328        assert_eq!(s.state, "disabled");
329        assert_eq!(s.latency_ms, Some(48), "the number still rides along");
330    }
331
332    #[test]
333    fn the_document_decides_access_and_quota() {
334        assert_eq!(derive_status(true, Some(&doc(Some(caller(false, (0, 1), (0, 1))))), None, 0).state, "no_access");
335        assert_eq!(derive_status(true, Some(&doc(Some(caller(true, (5, 5), (0, 1))))), None, 0).state, "maxed");
336        assert_eq!(derive_status(true, Some(&doc(Some(caller(true, (0, 5), (1, 1))))), None, 0).state, "maxed");
337        assert_eq!(derive_status(true, Some(&doc(Some(caller(true, (0, 5), (0, 1))))), None, 0).state, "online");
338        // A zero limit is "no limit", not "full".
339        assert_eq!(derive_status(true, Some(&doc(Some(caller(true, (5, 0), (0, 0))))), None, 0).state, "online");
340    }
341
342    #[test]
343    fn a_recent_failure_with_nothing_since_is_offline_then_forgotten() {
344        let mut s = stats();
345        s.last_fail_at = Some(1500);
346        s.last_fail_kind = Some(FAIL_OFFLINE.into());
347        assert_eq!(derive_status(true, None, Some(&s), 1600).state, "offline");
348        assert_eq!(derive_status(true, None, Some(&s), 1500 + OFFLINE_WINDOW_SECS + 1).state, "online");
349        // A success after the failure clears it at once.
350        s.last_ok_at = Some(1501);
351        assert_eq!(derive_status(true, None, Some(&s), 1600).state, "online");
352    }
353
354    #[test]
355    fn a_quota_refusal_reads_maxed_for_the_day() {
356        let mut s = stats();
357        s.last_fail_at = Some(1500);
358        s.last_fail_kind = Some(FAIL_MAXED.into());
359        assert_eq!(derive_status(true, None, Some(&s), 1600).state, "maxed");
360        assert_eq!(derive_status(true, None, Some(&s), 1500 + MAXED_WINDOW_SECS + 1).state, "online");
361    }
362
363    #[test]
364    fn nothing_known_is_untested_and_a_document_alone_is_online() {
365        assert_eq!(derive_status(true, None, None, 0).state, "untested");
366        assert_eq!(derive_status(true, Some(&doc(None)), None, 0).state, "online");
367    }
368
369    #[test]
370    fn samples_round_trip_as_pairs_and_read_old_bare_numbers() {
371        let ring = vec![Sample { mbps: 4.5, bytes: 300 }];
372        let json = serde_json::to_string(&ring).unwrap();
373        assert_eq!(json, "[[4.5,300]]");
374        let back: Vec<Sample> = serde_json::from_str("[[4.5,300],7.25]").unwrap();
375        assert_eq!(back, vec![Sample { mbps: 4.5, bytes: 300 }, Sample { mbps: 7.25, bytes: 0 }]);
376    }
377
378    #[test]
379    fn ewma_starts_at_the_first_sample_and_then_leans_on_history() {
380        assert_eq!(ewma(None, 50.0), 50.0);
381        assert_eq!(ewma(Some(50.0), 100.0), 65.0);
382    }
383}