Skip to main content

proef_core/
html.rs

1//! `render_html` — a self-contained HTML view of a run's event stream.
2//!
3//! A *derived* view (ADR-0008), never a second record: it replays the same
4//! `events.jsonl` the console and `JUnit` reporters consume. Pure and
5//! deterministic in `events` (sans-IO core), so it snapshot-locks like the
6//! emitter. Events reaching here are already redacted at the sink
7//! (`report::sink`), so no secret value can enter the page — the same
8//! assumption `explain` makes.
9
10use std::collections::BTreeMap;
11use std::fmt::Write as _;
12use std::path::Path;
13
14use crate::emit::slugify;
15use crate::event::Event;
16use crate::step::Status;
17
18/// One step's row in the report.
19struct StepRow {
20    line: usize,
21    text: String,
22    status: Status,
23    attempts: u32,
24    duration_ms: u64,
25    detail: Option<String>,
26}
27
28/// One scenario's block: identity, aggregate status, and its steps in order.
29#[derive(Default)]
30struct ScenarioBlock {
31    file: String,
32    name: String,
33    status: Option<Status>,
34    steps: Vec<StepRow>,
35    /// Run-relative start/end ms and worker index — injected observability
36    /// (ADR-0015), present only when the record carries timing. When present
37    /// they drive the cross-worker run timeline; absent, the report falls back
38    /// to the per-scenario waterfalls alone.
39    start_ms: Option<u64>,
40    end_ms: Option<u64>,
41    worker: Option<u64>,
42}
43
44/// Render `events` as a standalone HTML document. `artifacts_href` is the link
45/// prefix for each scenario's `.hurl` artifact (e.g. `"artifacts"`, resolved
46/// relative to wherever the caller writes the file); the artifact filename is
47/// derived with the same slug the emitter uses, so the links match on disk.
48pub fn render_html(events: &[Event], artifacts_href: &str) -> String {
49    let mut run_id = String::new();
50    let mut blocks: Vec<ScenarioBlock> = Vec::new();
51    let mut index: BTreeMap<(String, String), usize> = BTreeMap::new();
52    let mut total_steps = 0usize;
53    let mut total_attempts = 0u64;
54    let mut run_finished: Option<(usize, usize, usize)> = None;
55
56    for event in events {
57        match event {
58            Event::RunStarted { run_id: id, .. } => run_id = id.to_string(),
59            Event::StepFinished {
60                scenario,
61                step,
62                status,
63                attempts,
64                duration_ms,
65                detail,
66                ..
67            } => {
68                total_steps += 1;
69                total_attempts += u64::from(*attempts);
70                let at = block_index(&mut blocks, &mut index, &step.file, scenario);
71                blocks[at].steps.push(StepRow {
72                    line: step.line,
73                    text: step.text.to_string(),
74                    status: *status,
75                    attempts: *attempts,
76                    duration_ms: *duration_ms,
77                    detail: detail.clone(),
78                });
79            }
80            Event::ScenarioStarted {
81                scenario,
82                file,
83                timestamp_ms,
84                worker,
85            } => {
86                let at = block_index(&mut blocks, &mut index, file, scenario);
87                blocks[at].start_ms = *timestamp_ms;
88                blocks[at].worker = *worker;
89            }
90            Event::ScenarioFinished {
91                scenario,
92                file,
93                status,
94                timestamp_ms,
95                worker,
96            } => {
97                let at = block_index(&mut blocks, &mut index, file, scenario);
98                blocks[at].status = Some(*status);
99                blocks[at].end_ms = *timestamp_ms;
100                if blocks[at].worker.is_none() {
101                    blocks[at].worker = *worker;
102                }
103            }
104            Event::RunFinished {
105                passed,
106                failed,
107                skipped,
108                ..
109            } => {
110                run_finished = Some((*passed, *failed, *skipped));
111            }
112            _ => {}
113        }
114    }
115
116    let (passed, failed, skipped) = suite_totals(run_finished, &blocks);
117    // `warned` is informational only — never part of the aligned three
118    // numbers above (no other surface breaks it out either) — so it stays a
119    // plain count of every rendered block regardless of phase.
120    let warned = blocks
121        .iter()
122        .filter(|block| block.status == Some(Status::Warned))
123        .count();
124
125    let mut html = String::with_capacity(2048 + blocks.len() * 256);
126    let _ = writeln!(
127        html,
128        "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\
129         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
130         <title>proef report — {run}</title>\n<style>{STYLE}</style>\n</head>\n<body>\n\
131         <h1>proef run <code>{run}</code></h1>",
132        run = esc(&run_id)
133    );
134    html.push_str("<p class=\"summary\">");
135    tally(&mut html, "pass", passed, "passed");
136    tally(&mut html, "fail", failed, "failed");
137    tally(&mut html, "skip", skipped, "skipped");
138    if warned > 0 {
139        tally(&mut html, "warn", warned, "warned");
140    }
141    let _ = writeln!(
142        html,
143        "<span class=\"steps\">{total_steps} steps · {total_attempts} attempts</span></p>"
144    );
145
146    render_timeline(&mut html, &blocks);
147    for block in &blocks {
148        render_block(&mut html, block, artifacts_href, failed);
149    }
150    html.push_str("</body>\n</html>\n");
151    html
152}
153
154/// The headline `(passed, failed, skipped)` — mirrors every other surface
155/// that reads `RunFinished` (console `summary:`, `explain`, `--output json`,
156/// `JUnit`, TAP, the SLA gate, the exit code): main-suite scenarios only,
157/// `[run] setup`/`teardown` excluded (ADR-0014). A truncated record has no
158/// `RunFinished` to read, so fall back to counting every rendered block — the
159/// only totals a dead run can offer.
160fn suite_totals(
161    run_finished: Option<(usize, usize, usize)>,
162    blocks: &[ScenarioBlock],
163) -> (usize, usize, usize) {
164    run_finished.unwrap_or_else(|| {
165        let (mut passed, mut failed, mut skipped) = (0usize, 0usize, 0usize);
166        for block in blocks {
167            match block.status {
168                Some(Status::Passed) => passed += 1,
169                Some(Status::Failed) => failed += 1,
170                Some(Status::Skipped) => skipped += 1,
171                Some(Status::Warned) | None => {}
172            }
173        }
174        (passed, failed, skipped)
175    })
176}
177
178/// Find or create the block for `(file, scenario)`, preserving first-seen order.
179fn block_index(
180    blocks: &mut Vec<ScenarioBlock>,
181    index: &mut BTreeMap<(String, String), usize>,
182    file: &str,
183    scenario: &str,
184) -> usize {
185    *index
186        .entry((file.to_string(), scenario.to_string()))
187        .or_insert_with(|| {
188            blocks.push(ScenarioBlock {
189                file: file.to_string(),
190                name: scenario.to_string(),
191                ..ScenarioBlock::default()
192            });
193            blocks.len() - 1
194        })
195}
196
197/// One `<details>` per scenario — failures open by default so the report leads
198/// with what broke. `headline_failed` is the aligned failed count in the
199/// summary bar above (`RunFinished`'s, suite-only per ADR-0014, or the
200/// counted-block fallback on a truncated record): a block whose own status is
201/// `Failed` while that count is `0` cannot be one of the failures the
202/// headline counts — it is necessarily a `[run] setup`/`teardown` fault
203/// excluded from it, so it is flagged here rather than left to read as the
204/// page contradicting its own summary.
205fn render_block(
206    html: &mut String,
207    block: &ScenarioBlock,
208    artifacts_href: &str,
209    headline_failed: usize,
210) {
211    let status = block.status.unwrap_or(Status::Skipped);
212    let open = if status == Status::Failed {
213        " open"
214    } else {
215        ""
216    };
217    let _ = write!(
218        html,
219        "<details class=\"scenario {cls}\"{open}>\n<summary>\
220         <span class=\"pill {cls}\">{word}</span> \
221         <span class=\"loc\">{file}</span> {name}",
222        cls = status_class(status),
223        word = status_word(status),
224        file = esc(&block.file),
225        name = esc(&block.name),
226    );
227    if status == Status::Failed && headline_failed == 0 {
228        html.push_str(
229            " <span class=\"phase-note\">setup/teardown — excluded from totals above</span>",
230        );
231    }
232    // Link the artifact only when the scenario actually ran hurl steps (else
233    // no `.hurl` was emitted for it).
234    if !block.steps.is_empty() {
235        let stem = Path::new(&block.file).file_stem().map_or_else(
236            || "feature".to_owned(),
237            |stem| stem.to_string_lossy().into_owned(),
238        );
239        let slug = format!("{}--{}", slugify(&stem), slugify(&block.name));
240        let _ = write!(
241            html,
242            " <a class=\"artifact\" href=\"{href}/{slug}.hurl\">artifact</a>",
243            href = esc(artifacts_href),
244        );
245    }
246    html.push_str("</summary>\n<ol class=\"steps\">\n");
247    // Per-scenario timing waterfall: each step's bar is offset by the steps
248    // before it and as wide as its own duration, both as a fraction of the
249    // scenario total. Purely derived from `duration_ms` (no timestamps), so it
250    // shows the *sequential* cascade within one scenario — not cross-worker
251    // occupancy, which would need an injected clock the sans-IO core never reads.
252    let total_ms: u64 = block.steps.iter().map(|step| step.duration_ms).sum();
253    let mut elapsed_ms: u64 = 0;
254    for step in &block.steps {
255        let _ = write!(
256            html,
257            "<li class=\"{cls}\"><span class=\"glyph\">{glyph}</span> {text}\
258             <span class=\"meta\">:{line} · {attempts}× · {ms}ms</span>",
259            cls = status_class(step.status),
260            glyph = status_glyph(step.status),
261            text = esc(&step.text),
262            line = step.line,
263            attempts = step.attempts,
264            ms = step.duration_ms,
265        );
266        if total_ms > 0 {
267            let _ = write!(
268                html,
269                "<span class=\"track\"><span class=\"bar {cls}\" \
270                 style=\"margin-left:{offset}%;width:{width}%\"></span></span>",
271                cls = status_class(step.status),
272                offset = pct(elapsed_ms, total_ms),
273                width = pct(step.duration_ms, total_ms),
274            );
275        }
276        elapsed_ms += step.duration_ms;
277        if let Some(detail) = &step.detail {
278            let _ = write!(html, "<pre class=\"detail\">{}</pre>", esc(detail));
279        }
280        html.push_str("</li>\n");
281    }
282    html.push_str("</ol>\n</details>\n");
283}
284
285/// The cross-worker run timeline (ADR-0015): a lane per worker, each scenario a
286/// bar from its start to its finish, positioned on a shared run-relative axis so
287/// concurrency is visible at a glance. Rendered only when the record carries
288/// injected timing (`start`/`end` timestamps); absent, the report shows just the
289/// per-scenario waterfalls, so old records degrade cleanly.
290fn render_timeline(html: &mut String, blocks: &[ScenarioBlock]) {
291    let timed: Vec<&ScenarioBlock> = blocks
292        .iter()
293        .filter(|block| block.start_ms.is_some() && block.end_ms.is_some())
294        .collect();
295    let Some(max_end) = timed.iter().filter_map(|block| block.end_ms).max() else {
296        return; // no timed scenarios — old record, waterfalls only
297    };
298    if max_end == 0 {
299        return; // a zero-length run has nothing to place on the axis
300    }
301    let mut workers: Vec<u64> = timed
302        .iter()
303        .map(|block| block.worker.unwrap_or(0))
304        .collect();
305    workers.sort_unstable();
306    workers.dedup();
307
308    let _ = writeln!(
309        html,
310        "<h2 class=\"timeline-h\">Timeline <span class=\"count\">{max_end}ms</span></h2>\n\
311         <div class=\"timeline\">"
312    );
313    for worker in &workers {
314        let _ = write!(
315            html,
316            "<div class=\"lane\"><span class=\"lane-label\">worker {worker}</span>\
317             <div class=\"lane-track\">"
318        );
319        for block in timed
320            .iter()
321            .filter(|block| block.worker.unwrap_or(0) == *worker)
322        {
323            let start = block.start_ms.unwrap_or(0);
324            let end = block.end_ms.unwrap_or(start).max(start);
325            let _ = write!(
326                html,
327                "<span class=\"tbar {cls}\" style=\"left:{left}%;width:{width}%\" \
328                 title=\"{title} ({dur}ms)\"></span>",
329                cls = status_class(block.status.unwrap_or(Status::Skipped)),
330                left = pct(start, max_end),
331                width = pct(end - start, max_end),
332                title = esc(&block.name),
333                dur = end - start,
334            );
335        }
336        html.push_str("</div></div>\n");
337    }
338    html.push_str("</div>\n");
339}
340
341/// `n / total` as a percentage string with one decimal place, using integer
342/// math only (no lossy float cast). `total` must be non-zero (callers guard).
343fn pct(n: u64, total: u64) -> String {
344    let permille = u128::from(n) * 1000 / u128::from(total); // 0..=1000
345    format!("{}.{}", permille / 10, permille % 10)
346}
347
348/// Write one `<span>` count into the summary bar, omitting nothing (callers gate
349/// on zero where a bucket should hide).
350fn tally(html: &mut String, class: &str, count: usize, word: &str) {
351    let _ = write!(html, "<span class=\"count {class}\">{count} {word}</span> ");
352}
353
354fn status_class(status: Status) -> &'static str {
355    match status {
356        Status::Passed => "pass",
357        Status::Failed => "fail",
358        Status::Skipped => "skip",
359        Status::Warned => "warn",
360    }
361}
362
363fn status_word(status: Status) -> &'static str {
364    match status {
365        Status::Passed => "passed",
366        Status::Failed => "failed",
367        Status::Skipped => "skipped",
368        Status::Warned => "warned",
369    }
370}
371
372fn status_glyph(status: Status) -> &'static str {
373    match status {
374        Status::Passed => "✓",
375        Status::Failed => "✗",
376        Status::Skipped => "·",
377        Status::Warned => "⚠",
378    }
379}
380
381/// HTML-escape text destined for element content or a double-quoted attribute.
382fn esc(text: &str) -> String {
383    let mut out = String::with_capacity(text.len());
384    for ch in text.chars() {
385        match ch {
386            '&' => out.push_str("&amp;"),
387            '<' => out.push_str("&lt;"),
388            '>' => out.push_str("&gt;"),
389            '"' => out.push_str("&quot;"),
390            '\'' => out.push_str("&#39;"),
391            _ => out.push(ch),
392        }
393    }
394    out
395}
396
397/// Inlined stylesheet — the report is a single self-contained file (no external
398/// requests), light/dark aware for a local artifact.
399const STYLE: &str = "\
400:root{--bg:#fff;--fg:#1a1a1a;--muted:#666;--line:#e2e2e2;--pass:#1a7f37;--fail:#cf222e;--skip:#8a8a8a;--warn:#9a6700;--card:#f6f8fa}\
401@media(prefers-color-scheme:dark){:root{--bg:#0d1117;--fg:#e6edf3;--muted:#9aa4af;--line:#30363d;--pass:#3fb950;--fail:#f85149;--skip:#8a8a8a;--warn:#d29922;--card:#161b22}}\
402*{box-sizing:border-box}body{margin:0;padding:2rem;max-width:60rem;margin:0 auto;background:var(--bg);color:var(--fg);font:15px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif}\
403h1{font-size:1.4rem;font-weight:600}code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}\
404.incomplete-banner{color:var(--warn);font-weight:600;margin:0 0 1rem}\
405.summary{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin:0 0 1.5rem}\
406.count{font-weight:600;padding:.15rem .6rem;border-radius:999px;background:var(--card)}\
407.count.pass{color:var(--pass)}.count.fail{color:var(--fail)}.count.skip{color:var(--skip)}.count.warn{color:var(--warn)}\
408.summary .steps{color:var(--muted);margin-left:auto}\
409.scenario{border:1px solid var(--line);border-radius:8px;margin:.5rem 0;background:var(--card)}\
410.scenario summary{cursor:pointer;padding:.6rem .8rem;list-style:none;display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}\
411.scenario summary::-webkit-details-marker{display:none}\
412.pill{font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.03em;padding:.1rem .5rem;border-radius:4px;color:#fff}\
413.pill.pass{background:var(--pass)}.pill.fail{background:var(--fail)}.pill.skip{background:var(--skip)}.pill.warn{background:var(--warn)}\
414.loc{color:var(--muted);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.85rem}\
415.artifact{margin-left:auto;font-size:.85rem;color:var(--muted)}\
416.phase-note{color:var(--muted);font-size:.78rem;font-style:italic}\
417.steps{margin:0;padding:.2rem .8rem .8rem 2rem;border-top:1px solid var(--line)}\
418.steps li{margin:.3rem 0}.steps .glyph{font-weight:700}\
419li.pass .glyph{color:var(--pass)}li.fail .glyph{color:var(--fail)}li.skip .glyph{color:var(--skip)}li.warn .glyph{color:var(--warn)}\
420.meta{color:var(--muted);font-size:.8rem;margin-left:.4rem;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}\
421.track{display:block;height:4px;margin:.25rem 0 0;background:var(--line);border-radius:2px;overflow:hidden}\
422.bar{display:block;height:100%;min-width:1px;border-radius:2px}\
423.bar.pass{background:var(--pass)}.bar.fail{background:var(--fail)}.bar.skip{background:var(--skip)}.bar.warn{background:var(--warn)}\
424.timeline-h{font-size:1.05rem;font-weight:600;margin:1.5rem 0 .5rem}\
425.timeline{margin:0 0 1.5rem}\
426.lane{display:flex;align-items:center;gap:.5rem;margin:.25rem 0}\
427.lane-label{color:var(--muted);font-size:.75rem;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;min-width:5rem;text-align:right}\
428.lane-track{position:relative;flex:1;height:1rem;background:var(--card);border:1px solid var(--line);border-radius:3px}\
429.tbar{position:absolute;top:1px;height:calc(100% - 2px);min-width:2px;border-radius:2px;opacity:.9}\
430.tbar.pass{background:var(--pass)}.tbar.fail{background:var(--fail)}.tbar.skip{background:var(--skip)}.tbar.warn{background:var(--warn)}\
431.detail{background:var(--bg);border:1px solid var(--line);border-radius:6px;padding:.5rem .7rem;margin:.4rem 0 0;white-space:pre-wrap;font-size:.82rem;overflow-x:auto}\
432";