runnerd-web 0.1.3

The web dashboard runnerd serves on loopback: a client of the daemon's API
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! The dashboard's HTML, rendered on the server with maud from `runnerd_core::api` types. Each page is a module with
//! a struct of what it shows, a `load` that reads it from the daemon, and pure render functions: one per region a
//! live update replaces by its `id`. Views never write to the daemon; `crate::actions` does.

use std::cell::RefCell;
use std::fmt::Write as _;
use std::hash::{DefaultHasher, Hash as _, Hasher as _};

use maud::{DOCTYPE, Markup, PreEscaped, html};
use runnerd_core::api::{self, JobSummary, Section, Status, View};

use crate::assets;
use crate::format;

pub(crate) mod caches;
pub(crate) mod config;
pub(crate) mod history;
pub(crate) mod insights;
pub(crate) mod job;
pub(crate) mod overview;
pub(crate) mod records;
pub(crate) mod sizing;

/// The dashboard's pages: core's views, each a page or a group of its sections' pages (ADR 0132).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Page {
    Overview,
    History,
    Records,
    Sizing,
    Insights,
    Caches,
    Config,
}

impl Page {
    /// The page a view opens on: its own, or its first section's.
    pub(crate) fn of(view: View) -> Page {
        match view.sections().first() {
            Some(section) => Page::of_section(*section),
            None => match view {
                View::Insights => Page::Insights,
                _ => Page::Overview,
            },
        }
    }

    pub(crate) fn of_section(section: Section) -> Page {
        match section {
            Section::History => Page::History,
            Section::Records => Page::Records,
            Section::Sizing => Page::Sizing,
            Section::Caches => Page::Caches,
            Section::Config => Page::Config,
        }
    }

    /// The view it is in.
    fn view(self) -> View {
        match self {
            Page::Overview => View::Overview,
            Page::Insights => View::Insights,
            Page::History => Section::History.view(),
            Page::Records => Section::Records.view(),
            Page::Sizing => Section::Sizing.view(),
            Page::Caches => Section::Caches.view(),
            Page::Config => Section::Config.view(),
        }
    }

    pub(crate) fn path(self) -> &'static str {
        match self {
            Page::Overview => "/",
            Page::History => "/history",
            Page::Records => "/records",
            Page::Sizing => "/sizing",
            Page::Insights => "/insights",
            Page::Caches => "/caches",
            Page::Config => "/config",
        }
    }
}

const MARK: &str = include_str!("../assets/mark.svg");

/// The pieces of a live region that change on their own, such as a reading or the latest stretch of a chart. When
/// the rest of a region is unchanged, its stream sends only the pieces that changed. Rendering records them here; a
/// page ignores them.
#[derive(Debug, Default)]
pub(crate) struct Parts {
    parts: RefCell<Vec<Part>>,
    clocked: RefCell<Vec<String>>,
}

/// One piece of a region: an element with an `id`, as HTML.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Part {
    pub(crate) id: String,
    /// For a stretch of a chart, the SVG group it belongs to: stretches come and go as time passes, so the stream
    /// adds a new one to the group and removes one that is no longer drawn.
    pub(crate) group: Option<String>,
    pub(crate) html: String,
}

impl Parts {
    /// Records `markup`, an HTML element with `id`, as a part, and returns it.
    pub(crate) fn html(&self, id: &str, markup: Markup) -> Markup {
        self.push(id, None, markup)
    }

    /// Records `markup`, an SVG element with `id` in the group with id `group`, as a part, and returns it.
    pub(crate) fn stretch(&self, id: &str, group: &str, markup: Markup) -> Markup {
        self.push(id, Some(group), markup)
    }

    /// Records `value`, an attribute's value that follows the page's clock, such as a live chart's transform, and
    /// returns it. A Datastar binding keeps it current on the page, so a change to it alone sends nothing; the value
    /// is the page's until its script runs.
    pub(crate) fn clocked(&self, value: String) -> String {
        self.clocked.borrow_mut().push(value.clone());
        value
    }

    fn push(&self, id: &str, group: Option<&str>, markup: Markup) -> Markup {
        self.parts.borrow_mut().push(Part {
            id: id.to_owned(),
            group: group.map(str::to_owned),
            html: markup.0.clone(),
        });
        markup
    }

    /// The parts, and the values that follow the clock.
    pub(crate) fn into_parts(self) -> (Vec<Part>, Vec<String>) {
        (self.parts.into_inner(), self.clocked.into_inner())
    }
}

/// A short digest of a region's HTML. A page holds one per live region, which its stream reads on connecting to
/// skip the regions the page has already.
pub(crate) fn digest(html: &str) -> String {
    let mut hasher = DefaultHasher::new();
    html.hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

/// The event stream of a live page, and what the page shows: the time it was rendered at and a digest of each
/// region, by id. The stream keeps both current in the `shown` signal; live charts follow `$shown.at`.
pub(crate) struct Live<'url> {
    pub(crate) url: &'url str,
    pub(crate) at: u64,
    /// The number of the last log line the page shows, on a job's page.
    pub(crate) log: Option<u64>,
    pub(crate) regions: Vec<(&'static str, String)>,
}

impl Live<'_> {
    /// The `shown` signal as a Datastar expression.
    fn signals(&self) -> String {
        let mut signals = format!("{{shown: {{at: {}", self.at);
        if let Some(log) = self.log {
            let _ = write!(signals, ", log: {log}");
        }
        for (id, digest) in &self.regions {
            let _ = write!(signals, ", {}: {}", js(id), js(digest));
        }
        signals.push_str("}}");
        signals
    }
}

/// The keys the dashboard answers, as the help lists them: what is pressed, and what it does.
const KEYS: [(&str, &str); 8] = [
    ("1 to 5", "Open a view"),
    ("j / k", "Next or previous row"),
    ("Enter", "Open the row"),
    ("/", "Search the page"),
    ("Ctrl K", "Commands"),
    ("?", "These keys"),
    ("Esc", "Close, or leave a field"),
    ("Tab", "Every control, in reading order"),
];

/// A full page: the navigation, `main`, and, with `live`, the event stream that keeps its regions current.
pub(crate) fn page(
    title: &str,
    active: Option<Page>,
    live: Option<&Live<'_>>,
    main: &Markup,
) -> Markup {
    let nav = View::ALL.map(|view| (view, Page::of(view).path(), view.title()));
    let view = active.map(Page::view);

    html! {
        (DOCTYPE)
        html lang="en" {
            head {
                meta charset="utf-8";
                meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover";
                meta name="color-scheme" content="light dark";
                // The browser's bar and an installed app's status bar take the page's background; theme.js keeps
                // them on the theme chosen with the switch.
                meta name="theme-color" content="#e9ece9" media="(prefers-color-scheme: light)";
                meta name="theme-color" content="#070908" media="(prefers-color-scheme: dark)";
                meta name="description" content="runnerd's dashboard: its slots, jobs, caches and config on this machine.";
                title { (title) " · runnerd" }
                link rel="icon" href=(assets::path("mark.svg")) type="image/svg+xml";
                link rel="manifest" href=(assets::path("manifest.webmanifest"));
                link rel="preload" href=(assets::path("libre-franklin.woff2")) as="font" type="font/woff2" crossorigin;
                link rel="stylesheet" href=(assets::path("style.css"));
                script src=(assets::path("theme.js")) {}
                script type="module" src=(assets::path("datastar.js")) {}
                script type="module" src=(assets::path("keys.js")) {}
            }
            body data-signals=[live.map(Live::signals)] {
                a.skip href="#main" { "Skip to content" }
                header.top {
                    a.wordmark href="/" aria-label="runnerd overview" {
                        span.mark aria-hidden="true" { (PreEscaped(MARK)) }
                        "runnerd"
                    }
                    nav aria-label="Dashboard" {
                        @for (index, (shown, href, label)) in nav.iter().enumerate() {
                            @let key = (index + 1).to_string();
                            a href=(href) data-key=(key) aria-keyshortcuts=(key)
                                aria-current=[(view == Some(*shown)).then_some("page")] {
                                (label)
                                kbd.nav-key aria-hidden="true" { (key) }
                            }
                        }
                    }
                    div.tools {
                        @if let Some(live) = live {
                            // The indicator before the init: it has to listen when the request starts.
                            span.connection data-indicator:_live=""
                                data-init=(format!("@get('{}', {{retryMaxCount: 1000000, retryMaxWait: 10000}})", live.url))
                                data-class:online="$_live"
                                data-attr:title="$_live ? 'Updates as it happens' : 'Not connected; retrying'" {
                                span.dot aria-hidden="true" {}
                                span data-text="$_live ? 'Live' : 'Offline'" { "Live" }
                            }
                        }
                        button.tool type="button" data-open-palette aria-label="Commands" aria-keyshortcuts="Control+K" title="Commands (Ctrl K)" {
                            svg viewBox="0 0 20 20" aria-hidden="true" {
                                circle cx="8.5" cy="8.5" r="5.5" fill="none" stroke="currentColor" stroke-width="2" {}
                                path d="M12.6 12.6 17 17" stroke="currentColor" stroke-width="2" stroke-linecap="square" {}
                            }
                        }
                        button.tool.keys-button type="button" data-open-keys aria-label="Keys" aria-keyshortcuts="?" title="Keys (?)" {
                            svg viewBox="0 0 20 20" aria-hidden="true" {
                                rect x="1.5" y="4.5" width="17" height="11" fill="none" stroke="currentColor" stroke-width="1.6" {}
                                path d="M5 8h1.5M9.25 8h1.5M13.5 8H15M6 12h8" stroke="currentColor" stroke-width="1.6" {}
                            }
                        }
                        button.tool.theme type="button" data-theme-toggle aria-label="Switch between light and dark" {
                            svg viewBox="0 0 20 20" aria-hidden="true" {
                                circle cx="10" cy="10" r="8" fill="none" stroke="currentColor" stroke-width="2" {}
                                path d="M10 2a8 8 0 0 1 0 16z" fill="currentColor" {}
                            }
                        }
                    }
                }
                main #main { (main) }
                div #notice role="status" aria-live="polite" {}
                dialog #keys .sheet aria-labelledby="keys-title" {
                    div.sheet-head {
                        h2 #keys-title { "Keys" }
                        button.button-quiet type="button" data-close { "Close" }
                    }
                    dl.key-list {
                        @for (key, what) in KEYS {
                            div { dt { kbd { (key) } } dd { (what) } }
                        }
                    }
                }
                dialog #palette .sheet.palette aria-label="Commands" {
                    label.visually-hidden for="palette-input" { "Go to a page, a row, or a job number" }
                    input #palette-input type="text" autocomplete="off" spellcheck="false" role="combobox"
                        aria-controls="palette-list" aria-expanded="true" placeholder="Go to…";
                    ul #palette-list role="listbox" aria-label="Commands" {}
                }
            }
        }
    }
}

/// A page's visible title and, in a view of several sections, the sections as tabs, the one shown marked; `aside`
/// sits at the end of the row, such as a page's own figures.
pub(crate) fn heading(title: &str, active: Option<Page>, aside: Option<Markup>) -> Markup {
    let view = active.map(Page::view);
    let sections: Vec<_> = view
        .map(View::sections)
        .unwrap_or_default()
        .iter()
        .map(|section| (Page::of_section(*section), section.title()))
        .collect();
    html! {
        div.page-title {
            h1 { (title) }
            @if sections.len() > 1 {
                nav.sections aria-label=(view.map_or("", View::title)) {
                    @for (page, label) in &sections {
                        a href=(page.path()) aria-current=[(active == Some(*page)).then_some("page")] { (label) }
                    }
                }
            }
            @if let Some(aside) = aside { div.page-aside { (aside) } }
        }
    }
}

/// Why a request gets the signed-out page.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SignedOut {
    /// It came without the session cookie.
    NoSession,
    /// It brought a login code that was used already or never issued.
    CodeUsed,
}

/// The page every request without the session cookie gets.
pub(crate) fn signed_out(reason: SignedOut) -> Markup {
    let main = html! {
        section.signed-out {
            h1 { @if reason == SignedOut::CodeUsed { "That link was used already, or it expired" } @else { "Sign in to runnerd" } }
            p { "On another device, such as a phone: open the dashboard on runnerd's computer, choose " strong { "Add a device" } " on the Config page, and scan the QR code. Or run " code { "runnerctl web --qr" } " on that computer." }
            p { "On runnerd's computer: run " code { "runnerctl web" } ". It opens a link that signs this browser in." }
            p.muted { "Each link works once. A device stays signed in for 30 days after its last visit." }
        }
    };
    page("Sign in", None, None, &main)
}

/// A page for a daemon error, such as an unknown job.
pub(crate) fn error_page(title: &str, message: &str) -> Markup {
    let main = html! {
        section.signed-out {
            h1 { (title) }
            p { (message) }
            p { a href="/" { "Back to the overview" } }
        }
    };
    page(title, None, None, &main)
}

/// Whether a notice reports something done or something that failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Tone {
    Done,
    Failed,
}

/// A notice for `#notice`, such as why a pause failed. It goes away by itself.
pub(crate) fn notice(message: &str, tone: Tone) -> Markup {
    html! {
        div #notice role="status" aria-live="polite" {
            p class=(if tone == Tone::Failed { "toast failed" } else { "toast" }) data-init="setTimeout(() => el.remove(), 8000)" { (message) }
        }
    }
}

/// A notice that offers a next step, such as cancelling the job a pause waits for, or `dismiss` to drop it. It stays
/// until answered.
pub(crate) fn question(message: &str, action: &str, label: &str, dismiss: &str) -> Markup {
    html! {
        div #notice role="status" aria-live="polite" {
            div.toast.failed.question {
                p { (message) }
                div.toast-actions {
                    button.button-danger type="button" data-indicator:_answering=""
                        data-attr:aria-busy="$_answering && 'true'" data-attr:disabled="$_answering"
                        data-on:click=(action) { (label) }
                    button.button-quiet type="button" data-on:click="el.closest('.toast').remove()" { (dismiss) }
                }
            }
        }
    }
}

/// The colour class of a profile: its place among the configured profiles.
pub(crate) fn profile_class(status: &Status, profile: &str) -> String {
    let index = status
        .profiles
        .iter()
        .position(|candidate| candidate.name == profile)
        .unwrap_or(usize::MAX);
    if index == usize::MAX {
        "p-none".to_owned()
    } else {
        format!("p{}", index % 6)
    }
}

/// The CSS class of a tone, as core gives it: `tone-bad`, `tone-warn`, `tone-good`, `tone-neutral` or `tone-quiet`.
pub(crate) fn tone_class(tone: api::Tone) -> &'static str {
    match tone {
        api::Tone::Bad => "tone-bad",
        api::Tone::Warn => "tone-warn",
        api::Tone::Good => "tone-good",
        api::Tone::Neutral => "tone-neutral",
        api::Tone::Quiet => "tone-quiet",
    }
}

/// The CSS class of an outcome's kind: `success`, `failure`, `warn`, `running`, `queued` or `neutral`.
pub(crate) fn outcome_kind_class(kind: api::OutcomeKind) -> &'static str {
    match kind {
        api::OutcomeKind::Succeeded => "success",
        api::OutcomeKind::Failed => "failure",
        api::OutcomeKind::RunnerFault => "warn",
        api::OutcomeKind::Running => "running",
        api::OutcomeKind::Waiting => "queued",
        api::OutcomeKind::Ended => "neutral",
    }
}

/// The CSS class of a job's outcome.
pub(crate) fn outcome_class(job: &JobSummary) -> &'static str {
    outcome_kind_class(job.outcome().kind)
}

/// A job's outcome as a badge.
pub(crate) fn badge(job: &JobSummary) -> Markup {
    let outcome = job.outcome();
    html! { span class=(format!("badge {}", outcome_kind_class(outcome.kind))) { (outcome.label) } }
}

/// A time as text with its exact value in a tooltip.
pub(crate) fn time_ago(at: u64, now: u64) -> Markup {
    html! { time datetime=(format::rfc3339(at)) title=(format::timestamp(at)) { (format::ago(at, now)) } }
}

/// Text as a JavaScript string literal, for a Datastar expression: `it's` → `'it\'s'`.
pub(crate) fn js(text: &str) -> String {
    let mut literal = String::with_capacity(text.len() + 2);
    literal.push('\'');
    for c in text.chars() {
        match c {
            '\\' | '\'' => {
                literal.push('\\');
                literal.push(c);
            }
            '\n' => literal.push_str("\\n"),
            _ => literal.push(c),
        }
    }
    literal.push('\'');
    literal
}

/// `text`'s bytes in hex: an id or signal name no two texts share, as `node-js` and `node_js` would as a slug.
fn hex(text: &str) -> String {
    let mut hex = String::with_capacity(text.len() * 2);
    for byte in text.bytes() {
        let _ = write!(hex, "{byte:02x}");
    }
    hex
}

/// The id of a slot's card, which its budget block and its job's rows point at: `jvm` slot 1 → `slot-6a766d-1`.
pub(crate) fn slot_id(profile: &str, slot: usize) -> String {
    format!("slot-{}-{slot}", hex(profile))
}

/// A budget block's size: its figure as `runnerd.toml` writes it, and when shorter, `ByteSize::short`'s, which only a
/// narrow block shows. A figure longer than five characters, such as `767.5M`, would not fit a block's font at its
/// largest, so the block shows the short one alone.
pub(crate) fn block_size(memory: u64) -> Markup {
    let full = format::bytes(memory);
    let short = runnerd_core::config::ByteSize(memory).short();
    html! {
        span.size {
            @if full.chars().count() > 5 {
                (short)
            } @else if short == full {
                (full)
            } @else {
                span.full { (full) }
                span.short { (short) }
            }
        }
    }
}

/// The id of a repository's row, which a pause or resume replaces: `a/b` → `repo-612f62`. Also a signal name's
/// suffix, so it has only letters and digits after its dash.
pub(crate) fn repository_id(name: &str) -> String {
    format!("repo-{}", hex(name))
}

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

    #[test]
    fn a_block_reads_its_full_size_as_the_tui_does_and_the_short_one_only_when_narrow() {
        let block = block_size(3328 << 20).into_string();
        assert!(
            block.contains(r#"<span class="full">3.25G</span>"#)
                && block.contains(r#"<span class="short">3.3G</span>"#),
            "{block}"
        );
        assert_eq!(
            block_size(8 << 30).into_string(),
            r#"<span class="size">8G</span>"#
        );
        assert_eq!(
            block_size(1535 << 19).into_string(),
            r#"<span class="size">768M</span>"#,
            "767.5M is too long for a block, so it reads short whatever the width"
        );
    }

    #[test]
    fn names_whose_slugs_match_get_their_own_ids() {
        assert_ne!(slot_id("node-js", 1), slot_id("node_js", 1));
        assert_ne!(slot_id("a", 11), slot_id("a1", 1));
        assert_ne!(repository_id("halyard/b-c"), repository_id("halyard/b_c"));
    }

    #[test]
    fn a_quote_in_a_job_name_stays_inside_its_expression_string() {
        assert_eq!(js(r"it's a \ test"), r"'it\'s a \\ test'");
    }
}