sagittarius 0.2.0

A fast, self-hosted DNS sinkhole in a single Rust binary
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Dashboard page — since-startup runtime figures (SPEC §9).
//!
//! Renders the in-memory E6.6 runtime counters (total queries, blocked count
//! and ratio, cached, forwarded, top domains, top clients) plus the current
//! in-memory aggregated **blocklist set size** read from the shared
//! [`ResolverState`](crate::resolver::state::ResolverState).
//!
//! The four scalar counters are seeded into Datastar **signals** and formatted
//! client-side, so the live SSE stream (E8.6) can update them with a single
//! `PatchSignals` event without re-rendering the page.  The top-N tables and
//! the blocklist size are server-rendered and refresh on navigation.
//!
//! v0.1 figures are since-startup and non-persistent.

use askama::Template;
use askama_web::WebTemplate;
use axum::{extract::State, response::IntoResponse};

use std::time::Duration;

use crate::{
    resolver::upstream::UpstreamHealthRow,
    storage::query_log::{QueryLogCounts, QueryLogRepository},
    telemetry::StatsSnapshot,
    time::{self, Clock},
    web::{AppState, Chrome, auth::CurrentUser, render::DomainDisplay},
};

/// How many entries to show in the top-domains / top-clients tables.
const TOP_N: usize = 10;

/// The persisted-figures window: the last 24 hours.
const WINDOW: Duration = time::days(1);

impl AppState {
    /// `GET /` — the dashboard.
    ///
    /// Combines the live since-startup counters (in-memory, streamed over SSE)
    /// with a restart-surviving 24-hour window read from the `query_log` table.
    pub async fn dashboard(user: CurrentUser, State(state): State<AppState>) -> impl IntoResponse {
        let snapshot = state.telemetry.stats.snapshot(TOP_N);
        let blocklist_size = state.resolver.blocklist().len();

        // Persisted 24h window. On a DB error the figures degrade to zeros
        // rather than failing the whole page.
        let repo = state.db.query_log();
        let since = Clock::millis_ago(WINDOW);
        let window = WindowStats {
            counts: repo.counts_since(since).await.unwrap_or_default(),
            top_domains: repo
                .top_domains_since(since, TOP_N as i64)
                .await
                .unwrap_or_default(),
            top_clients: repo
                .top_clients_since(since, TOP_N as i64)
                .await
                .unwrap_or_default(),
        };

        // Per-upstream health (E15.2): in-memory, since-startup, refreshed on
        // navigation.
        let upstreams = state
            .upstream_pool
            .health()
            .snapshot()
            .into_iter()
            .map(UpstreamRow::from)
            .collect();

        let system = SystemInfo::capture(&state);

        // Decorate top-client IPs with their cached hostnames (E14.2).
        // Aggregation stays keyed by IP; the hostname is display-only and is
        // resolved once per distinct IP from the reverse-lookup cache (a miss
        // renders the bare IP and warms the cache for the next render).
        let mut top_clients = Vec::with_capacity(snapshot.top_clients.len());
        for (ip, count) in &snapshot.top_clients {
            top_clients.push((state.client_label_ip(*ip).await, group(*count)));
        }
        let mut window_top_clients = Vec::with_capacity(window.top_clients.len());
        for (ip, count) in &window.top_clients {
            window_top_clients.push((state.client_label(ip).await, group((*count).max(0) as u64)));
        }

        DashboardTemplate::new(
            state.chrome("dashboard", &user).await,
            snapshot,
            blocklist_size,
            window,
            top_clients,
            window_top_clients,
            upstreams,
            system,
        )
    }
}

/// At-a-glance server info for the dashboard "System" panel (E15.7).
///
/// All app-native (no host metrics): version, uptime, cache fill, and the
/// process's own resident memory. `uptime_secs` seeds a client-side ticker so
/// the uptime and queries/sec figures update without server round-trips.
struct SystemInfo {
    version: &'static str,
    uptime_secs: i64,
    uptime: String,
    cache_entries: String,
    cache_capacity: String,
    process_memory: String,
}

impl SystemInfo {
    fn capture(state: &AppState) -> Self {
        let uptime_secs = state.started_at.elapsed().as_secs() as i64;
        Self {
            version: env!("CARGO_PKG_VERSION"),
            uptime_secs,
            uptime: humanize_uptime(uptime_secs),
            cache_entries: group(state.resolver.cache().entry_count()),
            cache_capacity: group(state.resolver.settings().cache_capacity),
            process_memory: process_rss_bytes()
                .map(format_mib)
                .unwrap_or_else(|| "".to_owned()),
        }
    }
}

/// The process's resident set size in bytes, read from `/proc/self/status`
/// (`VmRSS`, already in kB so no page-size constant is needed). Returns `None`
/// off Linux or if the field is unavailable.
fn process_rss_bytes() -> Option<u64> {
    let status = std::fs::read_to_string("/proc/self/status").ok()?;
    let kb: u64 = status
        .lines()
        .find_map(|line| line.strip_prefix("VmRSS:"))?
        .split_whitespace()
        .next()?
        .parse()
        .ok()?;
    Some(kb * 1024)
}

/// Format a byte count as mebibytes with one decimal (e.g. `14.2 MiB`).
fn format_mib(bytes: u64) -> String {
    format!("{:.1} MiB", bytes as f64 / (1024.0 * 1024.0))
}

/// Humanize an uptime in seconds as `Nd Nh Nm` (server-render fallback before
/// the client-side ticker takes over).
fn humanize_uptime(secs: i64) -> String {
    let secs = secs.max(0);
    let days = secs / 86_400;
    let hours = (secs % 86_400) / 3_600;
    let mins = (secs % 3_600) / 60;
    format!("{days}d {hours}h {mins}m")
}

/// A per-upstream health row, pre-formatted for display (E15.3).
struct UpstreamRow {
    addr: String,
    queries: String,
    success_rate: String,
    latency: String,
    last_error: String,
}

impl From<UpstreamHealthRow> for UpstreamRow {
    fn from(row: UpstreamHealthRow) -> Self {
        Self {
            addr: row.addr.to_string(),
            queries: group(row.attempts()),
            success_rate: format!("{:.1}%", row.success_rate * 100.0),
            latency: row
                .ewma_latency_ms
                .map(|ms| format!("{ms:.1} ms"))
                .unwrap_or_else(|| "".to_owned()),
            last_error: row.last_error.unwrap_or_default(),
        }
    }
}

/// Persisted, windowed aggregates read from `query_log` for the dashboard.
struct WindowStats {
    counts: QueryLogCounts,
    top_domains: Vec<(String, i64)>,
    top_clients: Vec<(String, i64)>,
}

/// The dashboard view model.
///
/// The scalar counters are raw numbers (seeded into Datastar signals and
/// formatted client-side via `toLocaleString()`); the tables and blocklist
/// size are pre-formatted strings.
#[derive(Template, WebTemplate)]
#[template(path = "dashboard.html")]
struct DashboardTemplate {
    chrome: Chrome,
    total: u64,
    blocked: u64,
    cached: u64,
    forwarded: u64,
    blocklist_size: String,
    top_domains: Vec<(String, String)>,
    top_clients: Vec<(String, String)>,
    // Persisted 24h window (pre-formatted strings; these don't stream live).
    window_total: String,
    window_blocked: String,
    window_cached: String,
    window_forwarded: String,
    window_top_domains: Vec<(String, String)>,
    window_top_clients: Vec<(String, String)>,
    // Per-upstream health (in-memory, since-startup).
    upstreams: Vec<UpstreamRow>,
    // At-a-glance server info (E15.7).
    system: SystemInfo,
}

impl DashboardTemplate {
    #[allow(clippy::too_many_arguments)]
    fn new(
        chrome: Chrome,
        snap: StatsSnapshot,
        blocklist_size: usize,
        window: WindowStats,
        top_clients: Vec<(String, String)>,
        window_top_clients: Vec<(String, String)>,
        upstreams: Vec<UpstreamRow>,
        system: SystemInfo,
    ) -> Self {
        Self {
            chrome,
            upstreams,
            system,
            total: snap.total,
            blocked: snap.blocked,
            cached: snap.cached,
            forwarded: snap.forwarded,
            blocklist_size: group(blocklist_size as u64),
            top_domains: snap
                .top_domains
                .into_iter()
                .map(|(d, c)| (d.display_domain().to_owned(), group(c)))
                .collect(),
            // Client lists arrive pre-decorated with hostnames (E14.2); the
            // decoration is async + state-bound, so it happens in the handler.
            top_clients,
            window_total: group(window.counts.total.max(0) as u64),
            window_blocked: group(window.counts.blocked.max(0) as u64),
            window_cached: group(window.counts.cached.max(0) as u64),
            window_forwarded: group(window.counts.forwarded.max(0) as u64),
            window_top_domains: window
                .top_domains
                .into_iter()
                .map(|(d, c)| (d.display_domain().to_owned(), group(c.max(0) as u64)))
                .collect(),
            window_top_clients,
        }
    }
}

/// Format an integer with `,` thousands separators (e.g. `12403` → `12,403`).
pub(crate) fn group(n: u64) -> String {
    let digits = n.to_string();
    let len = digits.len();
    let mut out = String::with_capacity(len + len / 3);
    for (i, ch) in digits.chars().enumerate() {
        if i > 0 && (len - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(ch);
    }
    out
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn group_inserts_thousands_separators() {
        assert_eq!(group(0), "0");
        assert_eq!(group(42), "42");
        assert_eq!(group(1_000), "1,000");
        assert_eq!(group(12_403), "12,403");
        assert_eq!(group(1_234_567), "1,234,567");
    }

    fn test_chrome() -> Chrome {
        Chrome {
            theme: "auto".to_owned(),
            active: "dashboard",
            show_nav: true,
            authenticated: true,
            csrf_token: "tok".to_owned(),
            pause_remaining: None,
            asset_version: "test",
        }
    }

    fn test_system() -> SystemInfo {
        SystemInfo {
            version: "9.9.9",
            uptime_secs: 90_061,
            uptime: humanize_uptime(90_061),
            cache_entries: group(8_123),
            cache_capacity: group(100_000),
            process_memory: "14.2 MiB".to_owned(),
        }
    }

    #[test]
    fn template_seeds_signals_and_tables() {
        let snap = StatsSnapshot {
            total: 1000,
            blocked: 382,
            cached: 100,
            forwarded: 518,
            blocked_ratio: 0.382,
            top_domains: vec![("ads.example.com.".to_owned(), 50)],
            top_clients: vec![("192.168.1.10".parse().unwrap(), 120)],
        };
        let window = WindowStats {
            counts: QueryLogCounts {
                total: 2400,
                blocked: 900,
                cached: 500,
                forwarded: 1000,
            },
            top_domains: vec![("win.example.com.".to_owned(), 77)],
            top_clients: vec![("10.9.8.7".to_owned(), 64)],
        };
        let html = DashboardTemplate::new(
            test_chrome(),
            snap,
            65432,
            window,
            vec![("192.168.1.10".to_owned(), "120".to_owned())],
            vec![("10.9.8.7".to_owned(), "64".to_owned())],
            vec![],
            test_system(),
        )
        .render()
        .expect("render");
        // Live counters seeded as raw Datastar signal values.
        assert!(html.contains("queries: 1000"));
        assert!(html.contains("blocked: 382"));
        // Blocklist size is server-formatted.
        assert!(html.contains("65,432"));
        // Live top tables rendered without the canonical trailing dot.
        assert!(html.contains("ads.example.com"));
        assert!(!html.contains("ads.example.com."));
        assert!(html.contains("192.168.1.10"));
        // Persisted 24h window: figures (thousands-grouped) and trimmed domain.
        assert!(html.contains("Last 24 hours (persisted)"));
        assert!(html.contains("2,400"));
        assert!(html.contains("win.example.com"));
        assert!(!html.contains("win.example.com."));
        assert!(html.contains("10.9.8.7"));
    }

    #[test]
    fn template_empty_window_renders_zeros_without_panic() {
        let snap = StatsSnapshot {
            total: 0,
            blocked: 0,
            cached: 0,
            forwarded: 0,
            blocked_ratio: 0.0,
            top_domains: vec![],
            top_clients: vec![],
        };
        let window = WindowStats {
            counts: QueryLogCounts::default(),
            top_domains: vec![],
            top_clients: vec![],
        };
        let html = DashboardTemplate::new(
            test_chrome(),
            snap,
            0,
            window,
            vec![],
            vec![],
            vec![],
            test_system(),
        )
        .render()
        .expect("render");
        assert!(html.contains("No queries in the last 24 hours."));
    }

    /// The per-upstream health table renders address, success rate, latency,
    /// and last error from the snapshot rows.
    #[test]
    fn upstream_health_table_renders() {
        let snap = StatsSnapshot {
            total: 0,
            blocked: 0,
            cached: 0,
            forwarded: 0,
            blocked_ratio: 0.0,
            top_domains: vec![],
            top_clients: vec![],
        };
        let window = WindowStats {
            counts: QueryLogCounts::default(),
            top_domains: vec![],
            top_clients: vec![],
        };
        // One healthy upstream and one with a recorded failure (no latency yet).
        let rows = vec![
            UpstreamRow::from(UpstreamHealthRow {
                addr: "1.1.1.1:53".parse().unwrap(),
                successes: 99,
                failures: 1,
                success_rate: 0.99,
                ewma_latency_ms: Some(12.34),
                last_error: None,
            }),
            UpstreamRow::from(UpstreamHealthRow {
                addr: "9.9.9.9:53".parse().unwrap(),
                successes: 0,
                failures: 3,
                success_rate: 0.0,
                ewma_latency_ms: None,
                last_error: Some("upstream UDP query timed out".to_owned()),
            }),
        ];
        let html = DashboardTemplate::new(
            test_chrome(),
            snap,
            0,
            window,
            vec![],
            vec![],
            rows,
            test_system(),
        )
        .render()
        .expect("render");

        assert!(html.contains("1.1.1.1:53"));
        assert!(
            html.contains("99.0%"),
            "success rate is formatted as a percent"
        );
        assert!(html.contains("12.3 ms"), "latency EWMA is shown in ms");
        assert!(html.contains("9.9.9.9:53"));
        assert!(html.contains("0.0%"));
        assert!(html.contains("upstream UDP query timed out"));
    }

    /// The System panel renders version, humanized uptime, cache fill, and
    /// process memory, and wires the client-side uptime ticker.
    #[test]
    fn system_panel_renders() {
        let snap = StatsSnapshot {
            total: 0,
            blocked: 0,
            cached: 0,
            forwarded: 0,
            blocked_ratio: 0.0,
            top_domains: vec![],
            top_clients: vec![],
        };
        let window = WindowStats {
            counts: QueryLogCounts::default(),
            top_domains: vec![],
            top_clients: vec![],
        };
        let html = DashboardTemplate::new(
            test_chrome(),
            snap,
            0,
            window,
            vec![],
            vec![],
            vec![],
            test_system(),
        )
        .render()
        .expect("render");

        assert!(html.contains("System"));
        assert!(html.contains("9.9.9"), "version shown");
        // 90_061s = 1d 1h 1m.
        assert!(html.contains("1d 1h 1m"), "uptime humanized");
        assert!(html.contains("8,123 / 100,000"), "cache fill shown");
        assert!(html.contains("14.2 MiB"), "process memory shown");
        // The uptime ticker drives the live uptime + queries/sec figures.
        assert!(html.contains("data-on-interval"));
    }

    #[test]
    fn humanize_uptime_formats_days_hours_minutes() {
        assert_eq!(humanize_uptime(0), "0d 0h 0m");
        assert_eq!(humanize_uptime(90_061), "1d 1h 1m");
        assert_eq!(humanize_uptime(-5), "0d 0h 0m");
    }

    #[test]
    fn format_mib_rounds_to_one_decimal() {
        assert_eq!(format_mib(14_889_779), "14.2 MiB");
        assert_eq!(format_mib(0), "0.0 MiB");
    }
}