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
55    for event in events {
56        match event {
57            Event::RunStarted { run_id: id, .. } => run_id = id.to_string(),
58            Event::StepFinished {
59                scenario,
60                step,
61                status,
62                attempts,
63                duration_ms,
64                detail,
65                ..
66            } => {
67                total_steps += 1;
68                total_attempts += u64::from(*attempts);
69                let at = block_index(&mut blocks, &mut index, &step.file, scenario);
70                blocks[at].steps.push(StepRow {
71                    line: step.line,
72                    text: step.text.to_string(),
73                    status: *status,
74                    attempts: *attempts,
75                    duration_ms: *duration_ms,
76                    detail: detail.clone(),
77                });
78            }
79            Event::ScenarioStarted {
80                scenario,
81                file,
82                timestamp_ms,
83                worker,
84            } => {
85                let at = block_index(&mut blocks, &mut index, file, scenario);
86                blocks[at].start_ms = *timestamp_ms;
87                blocks[at].worker = *worker;
88            }
89            Event::ScenarioFinished {
90                scenario,
91                file,
92                status,
93                timestamp_ms,
94                worker,
95            } => {
96                let at = block_index(&mut blocks, &mut index, file, scenario);
97                blocks[at].status = Some(*status);
98                blocks[at].end_ms = *timestamp_ms;
99                if blocks[at].worker.is_none() {
100                    blocks[at].worker = *worker;
101                }
102            }
103            _ => {}
104        }
105    }
106
107    let (mut passed, mut failed, mut skipped, mut warned) = (0usize, 0usize, 0usize, 0usize);
108    for block in &blocks {
109        match block.status {
110            Some(Status::Passed) => passed += 1,
111            Some(Status::Failed) => failed += 1,
112            Some(Status::Skipped) => skipped += 1,
113            Some(Status::Warned) => warned += 1,
114            None => {}
115        }
116    }
117
118    let mut html = String::with_capacity(2048 + blocks.len() * 256);
119    let _ = writeln!(
120        html,
121        "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\
122         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
123         <title>proef report — {run}</title>\n<style>{STYLE}</style>\n</head>\n<body>\n\
124         <h1>proef run <code>{run}</code></h1>",
125        run = esc(&run_id)
126    );
127    html.push_str("<p class=\"summary\">");
128    tally(&mut html, "pass", passed, "passed");
129    tally(&mut html, "fail", failed, "failed");
130    tally(&mut html, "skip", skipped, "skipped");
131    if warned > 0 {
132        tally(&mut html, "warn", warned, "warned");
133    }
134    let _ = writeln!(
135        html,
136        "<span class=\"steps\">{total_steps} steps · {total_attempts} attempts</span></p>"
137    );
138
139    render_timeline(&mut html, &blocks);
140    for block in &blocks {
141        render_block(&mut html, block, artifacts_href);
142    }
143    html.push_str("</body>\n</html>\n");
144    html
145}
146
147/// Find or create the block for `(file, scenario)`, preserving first-seen order.
148fn block_index(
149    blocks: &mut Vec<ScenarioBlock>,
150    index: &mut BTreeMap<(String, String), usize>,
151    file: &str,
152    scenario: &str,
153) -> usize {
154    *index
155        .entry((file.to_string(), scenario.to_string()))
156        .or_insert_with(|| {
157            blocks.push(ScenarioBlock {
158                file: file.to_string(),
159                name: scenario.to_string(),
160                ..ScenarioBlock::default()
161            });
162            blocks.len() - 1
163        })
164}
165
166/// One `<details>` per scenario — failures open by default so the report leads
167/// with what broke.
168fn render_block(html: &mut String, block: &ScenarioBlock, artifacts_href: &str) {
169    let status = block.status.unwrap_or(Status::Skipped);
170    let open = if status == Status::Failed {
171        " open"
172    } else {
173        ""
174    };
175    let _ = write!(
176        html,
177        "<details class=\"scenario {cls}\"{open}>\n<summary>\
178         <span class=\"pill {cls}\">{word}</span> \
179         <span class=\"loc\">{file}</span> {name}",
180        cls = status_class(status),
181        word = status_word(status),
182        file = esc(&block.file),
183        name = esc(&block.name),
184    );
185    // Link the artifact only when the scenario actually ran hurl steps (else
186    // no `.hurl` was emitted for it).
187    if !block.steps.is_empty() {
188        let stem = Path::new(&block.file).file_stem().map_or_else(
189            || "feature".to_owned(),
190            |stem| stem.to_string_lossy().into_owned(),
191        );
192        let slug = format!("{}--{}", slugify(&stem), slugify(&block.name));
193        let _ = write!(
194            html,
195            " <a class=\"artifact\" href=\"{href}/{slug}.hurl\">artifact</a>",
196            href = esc(artifacts_href),
197        );
198    }
199    html.push_str("</summary>\n<ol class=\"steps\">\n");
200    // Per-scenario timing waterfall: each step's bar is offset by the steps
201    // before it and as wide as its own duration, both as a fraction of the
202    // scenario total. Purely derived from `duration_ms` (no timestamps), so it
203    // shows the *sequential* cascade within one scenario — not cross-worker
204    // occupancy, which would need an injected clock the sans-IO core never reads.
205    let total_ms: u64 = block.steps.iter().map(|step| step.duration_ms).sum();
206    let mut elapsed_ms: u64 = 0;
207    for step in &block.steps {
208        let _ = write!(
209            html,
210            "<li class=\"{cls}\"><span class=\"glyph\">{glyph}</span> {text}\
211             <span class=\"meta\">:{line} · {attempts}× · {ms}ms</span>",
212            cls = status_class(step.status),
213            glyph = status_glyph(step.status),
214            text = esc(&step.text),
215            line = step.line,
216            attempts = step.attempts,
217            ms = step.duration_ms,
218        );
219        if total_ms > 0 {
220            let _ = write!(
221                html,
222                "<span class=\"track\"><span class=\"bar {cls}\" \
223                 style=\"margin-left:{offset}%;width:{width}%\"></span></span>",
224                cls = status_class(step.status),
225                offset = pct(elapsed_ms, total_ms),
226                width = pct(step.duration_ms, total_ms),
227            );
228        }
229        elapsed_ms += step.duration_ms;
230        if let Some(detail) = &step.detail {
231            let _ = write!(html, "<pre class=\"detail\">{}</pre>", esc(detail));
232        }
233        html.push_str("</li>\n");
234    }
235    html.push_str("</ol>\n</details>\n");
236}
237
238/// The cross-worker run timeline (ADR-0015): a lane per worker, each scenario a
239/// bar from its start to its finish, positioned on a shared run-relative axis so
240/// concurrency is visible at a glance. Rendered only when the record carries
241/// injected timing (`start`/`end` timestamps); absent, the report shows just the
242/// per-scenario waterfalls, so old records degrade cleanly.
243fn render_timeline(html: &mut String, blocks: &[ScenarioBlock]) {
244    let timed: Vec<&ScenarioBlock> = blocks
245        .iter()
246        .filter(|block| block.start_ms.is_some() && block.end_ms.is_some())
247        .collect();
248    let Some(max_end) = timed.iter().filter_map(|block| block.end_ms).max() else {
249        return; // no timed scenarios — old record, waterfalls only
250    };
251    if max_end == 0 {
252        return; // a zero-length run has nothing to place on the axis
253    }
254    let mut workers: Vec<u64> = timed
255        .iter()
256        .map(|block| block.worker.unwrap_or(0))
257        .collect();
258    workers.sort_unstable();
259    workers.dedup();
260
261    let _ = writeln!(
262        html,
263        "<h2 class=\"timeline-h\">Timeline <span class=\"count\">{max_end}ms</span></h2>\n\
264         <div class=\"timeline\">"
265    );
266    for worker in &workers {
267        let _ = write!(
268            html,
269            "<div class=\"lane\"><span class=\"lane-label\">worker {worker}</span>\
270             <div class=\"lane-track\">"
271        );
272        for block in timed
273            .iter()
274            .filter(|block| block.worker.unwrap_or(0) == *worker)
275        {
276            let start = block.start_ms.unwrap_or(0);
277            let end = block.end_ms.unwrap_or(start).max(start);
278            let _ = write!(
279                html,
280                "<span class=\"tbar {cls}\" style=\"left:{left}%;width:{width}%\" \
281                 title=\"{title} ({dur}ms)\"></span>",
282                cls = status_class(block.status.unwrap_or(Status::Skipped)),
283                left = pct(start, max_end),
284                width = pct(end - start, max_end),
285                title = esc(&block.name),
286                dur = end - start,
287            );
288        }
289        html.push_str("</div></div>\n");
290    }
291    html.push_str("</div>\n");
292}
293
294/// `n / total` as a percentage string with one decimal place, using integer
295/// math only (no lossy float cast). `total` must be non-zero (callers guard).
296fn pct(n: u64, total: u64) -> String {
297    let permille = u128::from(n) * 1000 / u128::from(total); // 0..=1000
298    format!("{}.{}", permille / 10, permille % 10)
299}
300
301/// Write one `<span>` count into the summary bar, omitting nothing (callers gate
302/// on zero where a bucket should hide).
303fn tally(html: &mut String, class: &str, count: usize, word: &str) {
304    let _ = write!(html, "<span class=\"count {class}\">{count} {word}</span> ");
305}
306
307fn status_class(status: Status) -> &'static str {
308    match status {
309        Status::Passed => "pass",
310        Status::Failed => "fail",
311        Status::Skipped => "skip",
312        Status::Warned => "warn",
313    }
314}
315
316fn status_word(status: Status) -> &'static str {
317    match status {
318        Status::Passed => "passed",
319        Status::Failed => "failed",
320        Status::Skipped => "skipped",
321        Status::Warned => "warned",
322    }
323}
324
325fn status_glyph(status: Status) -> &'static str {
326    match status {
327        Status::Passed => "✓",
328        Status::Failed => "✗",
329        Status::Skipped => "·",
330        Status::Warned => "⚠",
331    }
332}
333
334/// HTML-escape text destined for element content or a double-quoted attribute.
335fn esc(text: &str) -> String {
336    let mut out = String::with_capacity(text.len());
337    for ch in text.chars() {
338        match ch {
339            '&' => out.push_str("&amp;"),
340            '<' => out.push_str("&lt;"),
341            '>' => out.push_str("&gt;"),
342            '"' => out.push_str("&quot;"),
343            '\'' => out.push_str("&#39;"),
344            _ => out.push(ch),
345        }
346    }
347    out
348}
349
350/// Inlined stylesheet — the report is a single self-contained file (no external
351/// requests), light/dark aware for a local artifact.
352const STYLE: &str = "\
353:root{--bg:#fff;--fg:#1a1a1a;--muted:#666;--line:#e2e2e2;--pass:#1a7f37;--fail:#cf222e;--skip:#8a8a8a;--warn:#9a6700;--card:#f6f8fa}\
354@media(prefers-color-scheme:dark){:root{--bg:#0d1117;--fg:#e6edf3;--muted:#9aa4af;--line:#30363d;--pass:#3fb950;--fail:#f85149;--skip:#8a8a8a;--warn:#d29922;--card:#161b22}}\
355*{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}\
356h1{font-size:1.4rem;font-weight:600}code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}\
357.summary{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin:0 0 1.5rem}\
358.count{font-weight:600;padding:.15rem .6rem;border-radius:999px;background:var(--card)}\
359.count.pass{color:var(--pass)}.count.fail{color:var(--fail)}.count.skip{color:var(--skip)}.count.warn{color:var(--warn)}\
360.summary .steps{color:var(--muted);margin-left:auto}\
361.scenario{border:1px solid var(--line);border-radius:8px;margin:.5rem 0;background:var(--card)}\
362.scenario summary{cursor:pointer;padding:.6rem .8rem;list-style:none;display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}\
363.scenario summary::-webkit-details-marker{display:none}\
364.pill{font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.03em;padding:.1rem .5rem;border-radius:4px;color:#fff}\
365.pill.pass{background:var(--pass)}.pill.fail{background:var(--fail)}.pill.skip{background:var(--skip)}.pill.warn{background:var(--warn)}\
366.loc{color:var(--muted);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.85rem}\
367.artifact{margin-left:auto;font-size:.85rem;color:var(--muted)}\
368.steps{margin:0;padding:.2rem .8rem .8rem 2rem;border-top:1px solid var(--line)}\
369.steps li{margin:.3rem 0}.steps .glyph{font-weight:700}\
370li.pass .glyph{color:var(--pass)}li.fail .glyph{color:var(--fail)}li.skip .glyph{color:var(--skip)}li.warn .glyph{color:var(--warn)}\
371.meta{color:var(--muted);font-size:.8rem;margin-left:.4rem;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}\
372.track{display:block;height:4px;margin:.25rem 0 0;background:var(--line);border-radius:2px;overflow:hidden}\
373.bar{display:block;height:100%;min-width:1px;border-radius:2px}\
374.bar.pass{background:var(--pass)}.bar.fail{background:var(--fail)}.bar.skip{background:var(--skip)}.bar.warn{background:var(--warn)}\
375.timeline-h{font-size:1.05rem;font-weight:600;margin:1.5rem 0 .5rem}\
376.timeline{margin:0 0 1.5rem}\
377.lane{display:flex;align-items:center;gap:.5rem;margin:.25rem 0}\
378.lane-label{color:var(--muted);font-size:.75rem;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;min-width:5rem;text-align:right}\
379.lane-track{position:relative;flex:1;height:1rem;background:var(--card);border:1px solid var(--line);border-radius:3px}\
380.tbar{position:absolute;top:1px;height:calc(100% - 2px);min-width:2px;border-radius:2px;opacity:.9}\
381.tbar.pass{background:var(--pass)}.tbar.fail{background:var(--fail)}.tbar.skip{background:var(--skip)}.tbar.warn{background:var(--warn)}\
382.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}\
383";