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
//! Module to format captured lock events as html.

use std::collections::{BTreeMap, HashMap};
use std::io::{self, Write};
use std::path::Path;
use std::time::Duration;

use crate::event::EventId;
use crate::{Event, Events};

const STYLE: &[u8] = include_bytes!("trace.css");
const SCRIPT: &[u8] = include_bytes!("trace.js");

/// Write events to the given path.
pub fn write<P>(path: P, events: &Events) -> io::Result<()>
where
    P: AsRef<Path>,
{
    let path = path.as_ref();

    let file_stem = path.file_stem().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "Missing file stem from the specified path",
        )
    })?;

    let parent = path.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "Missing parent from the specified path",
        )
    })?;

    let css = parent.join(file_stem).with_extension("css");
    let script = parent.join(file_stem).with_extension("js");

    std::fs::write(&css, STYLE)?;
    std::fs::write(&script, SCRIPT)?;

    let css = css
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Invalid css file name"))?;

    let script = script
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Invalid script file name"))?;

    let mut out = std::fs::File::create(path)?;

    // Start of trace.
    let mut start = u64::MAX;
    // End of trace.
    let mut end = u64::MIN;

    let mut opens = BTreeMap::<_, BTreeMap<_, Vec<_>>>::new();
    let mut children = HashMap::<_, Vec<_>>::new();
    let mut closes = HashMap::new();

    for enter in &events.enters {
        start = start.min(enter.timestamp);

        if let Some(parent) = enter.parent {
            children.entry(parent).or_default().push(enter);
        } else {
            opens
                .entry((enter.lock, enter.type_name.as_ref()))
                .or_default()
                .entry(enter.thread_index)
                .or_default()
                .push(enter);
        }
    }

    for leave in &events.leaves {
        end = end.max(leave.timestamp);
        closes.insert(leave.sibling, leave.timestamp);
    }

    if start == u64::MAX || end == u64::MIN {
        return Ok(());
    }

    writeln!(out, "<!DOCTYPE html>")?;
    writeln!(out, "<html>")?;
    writeln!(out, "<head>")?;
    writeln!(out, r#"<link href="{css}" rel="stylesheet">"#)?;
    writeln!(out, "</head>")?;

    writeln!(out, "<body>")?;
    writeln!(out, "<div id=\"traces\">")?;

    for ((lock, type_name), events) in opens {
        writeln!(out, "<div class=\"lock-instance\">")?;

        let kind = lock.kind();
        let index = lock.index();

        let type_name = type_name.replace('<', "&lt;").replace('>', "&gt");

        writeln!(
            out,
            r#"<div class="title">{kind:?}&lt;{type_name}&gt; (lock index: {index})</div>"#
        )?;

        writeln!(out, "<div class=\"lock-session\">")?;

        for (thread_index, events) in events.into_iter() {
            let start = events.iter().map(|e| e.timestamp).min().unwrap_or(0);

            let end = events
                .iter()
                .flat_map(|ev| closes.get(&ev.id).copied())
                .max()
                .unwrap_or(0);

            writeln!(
                out,
                r#"<div data-toggle="event-{lock}-{thread_index}-details" data-start="{start}" data-end="{end}" class="timeline">"#
            )?;

            writeln!(
                out,
                r#"<div class="timeline-heading"><span>{thread_index}</span></div>"#
            )?;

            writeln!(out, r#"<div class="timeline-data">"#)?;

            let mut details = Vec::new();

            for ev in events {
                let open = ev.timestamp;
                let id = ev.id;

                let Some(close) = closes.get(&ev.id).copied() else {
                    return Ok(());
                };

                writeln! {
                    details,
                    r#"
                    <tr data-entry data-entry-start="{open}" data-entry-close="{close}">
                        <td class="title" colspan="6">Event: {id}</td>
                    </tr>
                    "#
                }?;

                write_section(
                    &mut out,
                    ev,
                    (start, end),
                    close,
                    &children,
                    &closes,
                    &mut details,
                )?;
            }

            writeln!(out, r#"<div class="timeline-target"></div>"#)?;
            writeln!(out, "</div>")?;
            writeln!(out, "</div>")?;

            if !details.is_empty() {
                writeln!(
                    out,
                    r#"<table id="event-{lock}-{thread_index}-details" class="details">"#
                )?;

                out.write_all(&details)?;
                writeln!(out, "</table>")?;
            }
        }

        writeln!(out, "</div>")?;
        writeln!(out, "</div>")?;
    }

    writeln!(out, "</div>")?;
    writeln!(
        out,
        r#"<script type="text/javascript" src="{script}"></script>"#
    )?;
    writeln!(out, "</body>")?;
    writeln!(out, "</html>")?;
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn write_section(
    out: &mut dyn io::Write,
    ev: &Event,
    span: (u64, u64),
    close: u64,
    children: &HashMap<EventId, Vec<&Event>>,
    closes: &HashMap<EventId, u64>,
    d: &mut Vec<u8>,
) -> io::Result<()> {
    let id = ev.id;
    let title = ev.name.as_ref();
    let open = ev.timestamp;

    let (start, end) = span;

    if start == end {
        return Ok(());
    }

    let total = (end - start) as f32;

    let left = (((open - start) as f32 / total) * 100.0).round() as u32;
    let width = (((close - open) as f32 / total) * 100.0).round() as u32;

    let s = Duration::from_nanos(open);
    let e = Duration::from_nanos(close);
    let duration = Duration::from_nanos(close - open);

    let style = format!("width: {width}%; left: {left}%;");
    let hover_title = format!("{title} ({s:?}-{e:?})");

    writeln!(
        out,
        "<div id=\"event-{id}\" class=\"section {title}\" style=\"{style}\" title=\"{hover_title}\"></div>"
    )?;

    writeln! {
        d,
        r#"
        <tr data-entry data-entry-start="{open}" data-entry-close="{close}">
            <td class="title {title}">{title}</td>
            <td>{s:?}</td>
            <td>&mdash;</td>
            <td>{e:?}</td>
            <td>({duration:?})</td>
            <td width="100%"></td>
        </tr>
        "#
    }?;

    if let Some(backtrace) = &ev.backtrace {
        writeln!(
            d,
            r#"<tr><td>Backtrace:</td><td class="backtrace" colspan="5">{backtrace}</td></tr>"#
        )?;
    }

    for ev in children.get(&ev.id).into_iter().flatten() {
        let Some(child_close) = closes.get(&ev.id).copied() else {
            continue;
        };

        write_section(out, ev, span, child_close, children, closes, d)?;
    }

    Ok(())
}