rperf 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,847 @@
1
+ require_relative "../rperf"
2
+ require "json"
3
+
4
+ # Rack middleware that serves flamegraph visualizations of rperf snapshots.
5
+ #
6
+ # *Security note*: This middleware exposes profiling data without
7
+ # authentication. It is intended for development and staging environments.
8
+ # In production, place it behind an authenticated reverse proxy or restrict
9
+ # access by IP / VPN.
10
+ #
11
+ # Usage:
12
+ # require "rperf/viewer"
13
+ # use Rperf::Viewer # mount at /rperf (default)
14
+ # use Rperf::Viewer, path: "/profiler" # custom mount path
15
+ # use Rperf::Viewer, max_snapshots: 12 # keep fewer snapshots
16
+ #
17
+ # Take snapshots periodically:
18
+ # viewer = Rperf::Viewer.instance
19
+ # viewer.take_snapshot! # snapshot with clear: true
20
+ # viewer.add_snapshot(data) # or add pre-taken snapshot data
21
+ #
22
+ class Rperf::Viewer
23
+ @instance = nil
24
+
25
+ class << self
26
+ # Returns the most recently created Viewer instance.
27
+ attr_reader :instance
28
+ end
29
+
30
+ attr_reader :max_snapshots, :path
31
+
32
+ def initialize(app, path: "/rperf", max_snapshots: 24)
33
+ raise ArgumentError, "max_snapshots must be a positive integer, got #{max_snapshots.inspect}" unless max_snapshots.is_a?(Integer) && max_snapshots > 0
34
+ @app = app
35
+ @path = path.chomp("/")
36
+ @max_snapshots = max_snapshots
37
+ @snapshots = [] # [{id:, taken_at:, data:}, ...]
38
+ @mutex = Mutex.new
39
+ @next_id = 0
40
+ self.class.instance_variable_set(:@instance, self)
41
+ end
42
+
43
+ # Take a snapshot from the running profiler and store it.
44
+ # Returns the snapshot entry or nil if profiler is not running.
45
+ def take_snapshot!
46
+ data = Rperf.snapshot(clear: true)
47
+ return nil unless data
48
+ add_snapshot(data)
49
+ end
50
+
51
+ # Add a pre-taken snapshot hash to the history.
52
+ def add_snapshot(data)
53
+ @mutex.synchronize do
54
+ @next_id += 1
55
+ entry = { id: @next_id, taken_at: Time.now, data: data }
56
+ @snapshots << entry
57
+ @snapshots.shift while @snapshots.size > @max_snapshots
58
+ entry
59
+ end
60
+ end
61
+
62
+ # Rack interface
63
+ def call(env)
64
+ req_path = env["PATH_INFO"] || "/"
65
+
66
+ # Not our path — pass through to app
67
+ if req_path == @path
68
+ # Exact match: redirect to trailing slash
69
+ return [301, { "location" => "#{@path}/" }, [""]]
70
+ end
71
+ unless req_path.start_with?("#{@path}/")
72
+ return @app ? @app.call(env) : [404, { "content-type" => "text/plain" }, ["Not Found"]]
73
+ end
74
+
75
+ # Strip prefix to get sub-path
76
+ sub_path = req_path[@path.size..]
77
+
78
+ case sub_path
79
+ when "/"
80
+ serve_html
81
+ when "/snapshots"
82
+ serve_snapshot_list
83
+ when %r{\A/snapshots/(\d+)\z}
84
+ serve_snapshot($1.to_i)
85
+ else
86
+ [404, { "content-type" => "text/plain" }, ["Not Found"]]
87
+ end
88
+ end
89
+
90
+ # Convert aggregated samples to JSON-friendly format.
91
+ # Stack is stored top-to-bottom (leaf first) in C; reverse to root-first for flamegraph.
92
+ # Label set keys are converted from symbols to strings for JSON.
93
+ def self.samples_to_json(samples, label_sets)
94
+ json_samples = samples.map do |frames, weight, thread_seq, label_set_id|
95
+ {
96
+ stack: frames.reverse.map { |_, label| label },
97
+ weight: weight,
98
+ thread_seq: thread_seq || 0,
99
+ label_set_id: label_set_id || 0,
100
+ }
101
+ end
102
+ json_label_sets = label_sets.map do |ls|
103
+ ls.is_a?(Hash) ? ls.transform_keys(&:to_s) : ls
104
+ end
105
+ [json_samples, json_label_sets]
106
+ end
107
+
108
+ # Generate a self-contained static HTML file with inline snapshot data.
109
+ # The HTML loads d3/d3-flamegraph from CDN but requires no server.
110
+ def self.render_static_html(data)
111
+ samples = data[:aggregated_samples] || []
112
+ label_sets = data[:label_sets] || []
113
+ json_samples, json_label_sets = samples_to_json(samples, label_sets)
114
+
115
+ json_snapshot = JSON.generate({
116
+ id: 1,
117
+ taken_at: Time.now.iso8601,
118
+ mode: data[:mode],
119
+ frequency: data[:frequency],
120
+ duration_ns: data[:duration_ns],
121
+ sampling_count: data[:sampling_count],
122
+ samples: json_samples,
123
+ label_sets: json_label_sets,
124
+ })
125
+
126
+ logo = LOGO_SVG.sub("<svg ", '<svg style="height:36px;width:auto" ')
127
+
128
+ html = VIEWER_HTML.sub("<!-- LOGO -->") { logo }
129
+
130
+ # Hide snapshot selector (single snapshot, no server)
131
+ html = html.sub('<select id="sel-snapshot"', '<select id="sel-snapshot" style="display:none"')
132
+
133
+ # Replace dynamic loading with inline data.
134
+ # Escape for safe embedding in <script>:
135
+ # - "</" prevents closing </script> tag injection
136
+ # - U+2028/U+2029 are line terminators in JS but valid in JSON
137
+ json_safe = json_snapshot
138
+ .gsub("</", "<\\/")
139
+ .gsub("\u2028", "\\u2028")
140
+ .gsub("\u2029", "\\u2029")
141
+ html = html.sub("loadSnapshotList();",
142
+ "currentData = #{json_safe}; updateTagDropdowns(); applyAndRender();")
143
+
144
+ html
145
+ end
146
+
147
+ private
148
+
149
+ LOGO_SVG = begin
150
+ path = File.expand_path("../../docs/logo.svg", __dir__)
151
+ File.exist?(path) ? File.read(path).freeze : ""
152
+ end
153
+
154
+ def serve_html
155
+ logo = LOGO_SVG
156
+ .sub("<svg ", '<svg style="height:36px;width:auto" ')
157
+ [200, {
158
+ "content-type" => "text/html; charset=utf-8",
159
+ "x-frame-options" => "DENY",
160
+ "x-content-type-options" => "nosniff",
161
+ "content-security-policy" => "default-src 'none'; script-src 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; style-src 'unsafe-inline' https://cdn.jsdelivr.net; connect-src 'self'; img-src data:; frame-ancestors 'none'",
162
+ }, [VIEWER_HTML.sub("<!-- LOGO -->") { logo }]]
163
+ end
164
+
165
+ def serve_snapshot_list
166
+ list = @mutex.synchronize do
167
+ @snapshots.map do |s|
168
+ {
169
+ id: s[:id],
170
+ taken_at: s[:taken_at].iso8601,
171
+ mode: s[:data][:mode],
172
+ duration_ns: s[:data][:duration_ns],
173
+ sampling_count: s[:data][:sampling_count],
174
+ }
175
+ end
176
+ end
177
+ json_response(list)
178
+ end
179
+
180
+ def serve_snapshot(id)
181
+ entry = @mutex.synchronize { @snapshots.find { |s| s[:id] == id } }
182
+ return [404, { "content-type" => "text/plain" }, ["Snapshot not found"]] unless entry
183
+
184
+ data = entry[:data]
185
+ samples = data[:aggregated_samples] || []
186
+ label_sets = data[:label_sets] || []
187
+ json_samples, json_label_sets = self.class.samples_to_json(samples, label_sets)
188
+
189
+ json_response({
190
+ id: entry[:id],
191
+ taken_at: entry[:taken_at].iso8601,
192
+ mode: data[:mode],
193
+ frequency: data[:frequency],
194
+ duration_ns: data[:duration_ns],
195
+ sampling_count: data[:sampling_count],
196
+ samples: json_samples,
197
+ label_sets: json_label_sets,
198
+ })
199
+ end
200
+
201
+ def json_response(obj)
202
+ [200, {
203
+ "content-type" => "application/json; charset=utf-8",
204
+ "x-content-type-options" => "nosniff",
205
+ }, [JSON.generate(obj)]]
206
+ end
207
+
208
+ VIEWER_HTML = <<~'HTML'
209
+ <!DOCTYPE html>
210
+ <html lang="en">
211
+ <head>
212
+ <meta charset="utf-8">
213
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; style-src 'unsafe-inline' https://cdn.jsdelivr.net; connect-src 'self'; img-src data:; frame-ancestors 'none'">
214
+ <title>rperf Viewer</title>
215
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/d3-flame-graph@4/dist/d3-flamegraph.css" integrity="sha384-DgAQSBzzhv8bu6Qc6Lq08THluOr+kO5qLMHt1yv8A3my7Jz2OQv6aq/WSZRYIQkG" crossorigin="anonymous">
216
+ <style>
217
+ * { box-sizing: border-box; margin: 0; padding: 0; }
218
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, monospace; background: #fafafa; color: #333; }
219
+
220
+ /* Header */
221
+ .header { background: #fff; padding: 10px 20px; display: flex; align-items: center; gap: 16px; flex-wrap: wrap; border-bottom: 1px solid #ddd; }
222
+ .controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
223
+ .controls label { font-size: 13px; color: #555; }
224
+ .controls select, .controls input[type="text"] {
225
+ background: #fff; color: #333; border: 1px solid #ccc; border-radius: 4px;
226
+ padding: 4px 8px; font-size: 13px; font-family: inherit;
227
+ }
228
+ .controls input[type="text"] { width: 120px; }
229
+ .dropdown-cb { position: relative; display: inline-block; vertical-align: middle; }
230
+ .dropdown-cb-btn {
231
+ background: #fff; color: #888; border: 1px solid #ccc; border-radius: 4px;
232
+ padding: 4px 8px; font-size: 13px; font-family: inherit; cursor: pointer; min-width: 60px; text-align: left;
233
+ }
234
+ .dropdown-cb-btn.has-selection { color: #333; }
235
+ .dropdown-cb-btn:hover { border-color: #999; }
236
+ .dropdown-cb-list {
237
+ display: none; position: absolute; top: 100%; left: 0; z-index: 100;
238
+ background: #fff; border: 1px solid #ccc; border-radius: 4px;
239
+ padding: 4px 0; min-width: 180px; max-height: 240px; overflow-y: auto;
240
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
241
+ }
242
+ .dropdown-cb-list.open { display: block; }
243
+ .dropdown-cb-list label {
244
+ display: block; padding: 4px 10px; font-size: 12px; cursor: pointer; white-space: nowrap;
245
+ color: #333; background: none; border: none; border-radius: 0;
246
+ }
247
+ .dropdown-cb-list label:hover { background: #f0e8e0; }
248
+ .controls input[type="text"]::placeholder { color: #aaa; }
249
+
250
+ /* Tabs */
251
+ .tabs { display: flex; background: #fff; border-bottom: 1px solid #ddd; padding: 0 20px; }
252
+ .tab {
253
+ padding: 8px 20px; font-size: 13px; color: #888; cursor: pointer;
254
+ border-bottom: 2px solid transparent; transition: color 0.15s;
255
+ }
256
+ .tab:hover { color: #555; }
257
+ .tab.active { color: #cc342d; border-bottom-color: #cc342d; }
258
+
259
+ /* Info bar */
260
+ .info-bar { background: #f5f5f5; padding: 6px 20px; font-size: 12px; color: #888; border-bottom: 1px solid #eee; }
261
+
262
+ /* Tab content */
263
+ .tab-content { display: none; }
264
+ .tab-content.active { display: block; }
265
+ #panel-flamegraph { background: #fff; min-height: 300px; }
266
+ .empty-state { display: flex; align-items: center; justify-content: center; height: 400px; color: #aaa; font-size: 16px; }
267
+ #panel-flamegraph .d3-flame-graph rect { stroke: #fff; stroke-width: 0.5px; }
268
+
269
+ /* Top table */
270
+ #panel-top { padding: 16px 20px; background: #fff; }
271
+ #panel-top table { width: 100%; border-collapse: collapse; font-size: 13px; }
272
+ #panel-top th { text-align: left; color: #cc342d; border-bottom: 2px solid #eee; padding: 6px 8px; cursor: pointer; }
273
+ #panel-top th:hover { color: #a82a24; }
274
+ #panel-top td { padding: 5px 8px; border-bottom: 1px solid #f0f0f0; }
275
+ #panel-top tr:hover td { background: #faf5f0; }
276
+ .num { text-align: right; font-variant-numeric: tabular-nums; }
277
+
278
+ /* Tags panel */
279
+ #panel-tags { padding: 16px 20px; background: #fff; }
280
+ .tag-group { margin-bottom: 20px; }
281
+ .tag-group h3 { font-size: 14px; color: #cc342d; margin-bottom: 8px; }
282
+ .tag-group table { width: 100%; max-width: 600px; border-collapse: collapse; font-size: 13px; }
283
+ .tag-group th { text-align: left; color: #888; border-bottom: 2px solid #eee; padding: 5px 8px; }
284
+ .tag-group td { padding: 5px 8px; border-bottom: 1px solid #f0f0f0; }
285
+ .tag-group tr:hover td { background: #faf5f0; }
286
+ .tag-group tr { cursor: pointer; }
287
+ .tag-bar { display: inline-block; height: 12px; background: #cc342d; border-radius: 2px; vertical-align: middle; }
288
+ </style>
289
+ </head>
290
+ <body>
291
+ <div class="header">
292
+ <a href="https://github.com/ko1/rperf" target="_blank" rel="noopener" title="rperf on GitHub" style="display:flex;align-items:center;text-decoration:none;">
293
+ <!-- LOGO -->
294
+ </a>
295
+ <div class="controls">
296
+ <label>Snapshot:
297
+ <select id="sel-snapshot"><option value="">Loading...</option></select>
298
+ </label>
299
+ <label>tagfocus: <input type="text" id="in-tagfocus" placeholder="value regex"></label>
300
+ <label>tagignore:
301
+ <span class="dropdown-cb">
302
+ <button type="button" id="btn-tagignore" class="dropdown-cb-btn">none</button>
303
+ <div id="cb-tagignore" class="dropdown-cb-list"></div>
304
+ </span>
305
+ </label>
306
+ <label>tagroot:
307
+ <span class="dropdown-cb">
308
+ <button type="button" id="btn-tagroot" class="dropdown-cb-btn">none</button>
309
+ <div id="cb-tagroot" class="dropdown-cb-list"></div>
310
+ </span>
311
+ </label>
312
+ <label>tagleaf:
313
+ <span class="dropdown-cb">
314
+ <button type="button" id="btn-tagleaf" class="dropdown-cb-btn">none</button>
315
+ <div id="cb-tagleaf" class="dropdown-cb-list"></div>
316
+ </span>
317
+ </label>
318
+ </div>
319
+ </div>
320
+ <div class="tabs">
321
+ <div class="tab active" data-tab="flamegraph">Flamegraph</div>
322
+ <div class="tab" data-tab="top">Top</div>
323
+ <div class="tab" data-tab="tags">Tags</div>
324
+ </div>
325
+ <div id="info-bar" class="info-bar"></div>
326
+ <div id="panel-flamegraph" class="tab-content active"></div>
327
+ <div id="panel-top" class="tab-content"></div>
328
+ <div id="panel-tags" class="tab-content"></div>
329
+
330
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js" integrity="sha384-CjloA8y00+1SDAUkjs099PVfnY2KmDC2BZnws9kh8D/lX1s46w6EPhpXdqMfjK6i" crossorigin="anonymous"></script>
331
+ <script src="https://cdn.jsdelivr.net/npm/d3-flame-graph@4/dist/d3-flamegraph.min.js" integrity="sha384-p4NaVVE+k6MT/enE0MtQ8B15rM9BGzHCnx8DizawPGks1ssZUeNdw6bAPpH2gp2w" crossorigin="anonymous"></script>
332
+ <script>
333
+ "use strict";
334
+
335
+ var BASE = location.pathname.replace(/\/$/, "");
336
+ var currentData = null;
337
+ var currentTab = "flamegraph";
338
+ var filteredSamples = null; // cached after filter
339
+ var totalFilteredNs = 0;
340
+
341
+ // --- Helpers ---
342
+
343
+ function fmtMs(ns) { return (ns / 1e6).toFixed(2); }
344
+ function fmtPct(ns, total) { return total > 0 ? (ns / total * 100).toFixed(1) : "0.0"; }
345
+
346
+ // --- Data fetching ---
347
+
348
+ async function fetchJSON(path) {
349
+ var res = await fetch(BASE + path);
350
+ if (!res.ok) throw new Error(res.status + " " + res.statusText);
351
+ return res.json();
352
+ }
353
+
354
+ async function loadSnapshotList() {
355
+ var list = await fetchJSON("/snapshots");
356
+ var sel = document.getElementById("sel-snapshot");
357
+ sel.innerHTML = "";
358
+ if (list.length === 0) {
359
+ sel.innerHTML = '<option value="">No snapshots</option>';
360
+ return;
361
+ }
362
+ var reversed = list.slice().reverse();
363
+ reversed.forEach(function(s) {
364
+ var opt = document.createElement("option");
365
+ opt.value = s.id;
366
+ var t = new Date(s.taken_at);
367
+ var dur = (s.duration_ns / 1e9).toFixed(1);
368
+ opt.textContent = "#" + s.id + " " + t.toLocaleTimeString() +
369
+ " (" + s.mode + ", " + dur + "s, " + s.sampling_count + " samples)";
370
+ sel.appendChild(opt);
371
+ });
372
+ await loadSnapshot(reversed[0].id);
373
+ }
374
+
375
+ async function loadSnapshot(id) {
376
+ currentData = await fetchJSON("/snapshots/" + id);
377
+ updateTagDropdowns();
378
+ applyAndRender();
379
+ }
380
+
381
+ // --- Update tag key/value dropdowns from current snapshot ---
382
+
383
+ function updateTagDropdowns() {
384
+ if (!currentData || !currentData.label_sets) return;
385
+ var labelSets = currentData.label_sets;
386
+
387
+ // Collect all keys and all key:value pairs
388
+ var keys = {};
389
+ var vals = {};
390
+ labelSets.forEach(function(ls) {
391
+ if (!ls) return;
392
+ Object.keys(ls).forEach(function(k) {
393
+ keys[k] = true;
394
+ var compound = k + " = " + ls[k];
395
+ vals[compound] = true;
396
+ });
397
+ });
398
+
399
+ var sortedKeys = Object.keys(keys).sort();
400
+ // Group by key: for each key, (none) first, then values sorted
401
+ var sortedVals = [];
402
+ sortedKeys.forEach(function(k) {
403
+ sortedVals.push(k + " = (none)");
404
+ Object.keys(vals).sort().forEach(function(v) {
405
+ if (v.substring(0, k.length + 3) === k + " = ") sortedVals.push(v);
406
+ });
407
+ });
408
+
409
+ // tagroot / tagleaf: dropdown checkboxes for label keys
410
+ ["tagroot", "tagleaf"].forEach(function(name) {
411
+ var container = document.getElementById("cb-" + name);
412
+ var prev = getCheckedValues(container);
413
+ container.innerHTML = "";
414
+ sortedKeys.forEach(function(k) {
415
+ var lbl = document.createElement("label");
416
+ var cb = document.createElement("input");
417
+ cb.type = "checkbox";
418
+ cb.value = k;
419
+ if (prev.indexOf(k) >= 0) cb.checked = true;
420
+ cb.addEventListener("change", function() {
421
+ updateDropdownButton("btn-" + name, "cb-" + name, "none");
422
+ applyAndRender();
423
+ });
424
+ lbl.appendChild(cb);
425
+ lbl.appendChild(document.createTextNode(" " + k));
426
+ container.appendChild(lbl);
427
+ });
428
+ updateDropdownButton("btn-" + name, "cb-" + name, "none");
429
+ });
430
+
431
+ // tagignore: dropdown with checkboxes for key=value pairs
432
+ var container = document.getElementById("cb-tagignore");
433
+ var prev = getCheckedValues(container);
434
+ container.innerHTML = "";
435
+ sortedVals.forEach(function(display) {
436
+ var lbl = document.createElement("label");
437
+ var cb = document.createElement("input");
438
+ cb.type = "checkbox";
439
+ cb.value = display;
440
+ if (prev.indexOf(display) >= 0) cb.checked = true;
441
+ cb.addEventListener("change", function() {
442
+ updateDropdownButton("btn-tagignore", "cb-tagignore", "none");
443
+ applyAndRender();
444
+ });
445
+ lbl.appendChild(cb);
446
+ lbl.appendChild(document.createTextNode(" " + display));
447
+ container.appendChild(lbl);
448
+ });
449
+ updateDropdownButton("btn-tagignore", "cb-tagignore", "none");
450
+ }
451
+
452
+ function updateDropdownButton(btnId, containerId, emptyText) {
453
+ var vals = getCheckedValues(document.getElementById(containerId));
454
+ var btn = document.getElementById(btnId);
455
+ if (vals.length === 0) {
456
+ btn.textContent = emptyText;
457
+ btn.classList.remove("has-selection");
458
+ } else {
459
+ btn.textContent = vals.join(", ");
460
+ btn.classList.add("has-selection");
461
+ }
462
+ }
463
+
464
+ function getCheckedValues(container) {
465
+ var result = [];
466
+ var cbs = container.querySelectorAll("input[type=checkbox]:checked");
467
+ for (var i = 0; i < cbs.length; i++) result.push(cbs[i].value);
468
+ return result;
469
+ }
470
+
471
+ // --- Tag filtering ---
472
+
473
+ function getFilteredSamples() {
474
+ if (!currentData) return [];
475
+ var samples = currentData.samples;
476
+ var labelSets = currentData.label_sets || [];
477
+ var tagfocus = document.getElementById("in-tagfocus").value.trim();
478
+ var tagignoreVals = getCheckedValues(document.getElementById("cb-tagignore"));
479
+ var tagroots = getCheckedValues(document.getElementById("cb-tagroot"));
480
+ var tagleaves = getCheckedValues(document.getElementById("cb-tagleaf"));
481
+
482
+ var filtered = samples;
483
+
484
+ // tagfocus: keep only samples whose label values match the regex
485
+ if (tagfocus) {
486
+ try { var re = new RegExp(tagfocus); } catch(e) { /* invalid regex, skip filter */ }
487
+ if (!re) return filtered;
488
+ filtered = filtered.filter(function(s) {
489
+ if (s.label_set_id === 0) return false;
490
+ var ls = labelSets[s.label_set_id];
491
+ if (!ls) return false;
492
+ return Object.values(ls).some(function(v) { return re.test(String(v)); });
493
+ });
494
+ }
495
+
496
+ // tagignore: remove samples matching selected key=value pairs (or missing key for "(none)")
497
+ if (tagignoreVals.length > 0) {
498
+ var ignores = tagignoreVals.map(function(s) {
499
+ var idx = s.indexOf(" = ");
500
+ return { key: s.substring(0, idx), val: s.substring(idx + 3) };
501
+ });
502
+ filtered = filtered.filter(function(s) {
503
+ var ls = (s.label_set_id > 0) ? labelSets[s.label_set_id] : null;
504
+ return !ignores.some(function(ig) {
505
+ if (ig.val === "(none)") {
506
+ // Match samples that do NOT have this key
507
+ return !ls || !(ig.key in ls);
508
+ }
509
+ return ls && ls[ig.key] !== undefined && String(ls[ig.key]) === ig.val;
510
+ });
511
+ });
512
+ }
513
+
514
+ // tagroot: prepend label values as root frames (outermost first)
515
+ if (tagroots.length > 0) {
516
+ filtered = filtered.map(function(s) {
517
+ if (s.label_set_id === 0) return s;
518
+ var ls = labelSets[s.label_set_id];
519
+ if (!ls) return s;
520
+ var extra = [];
521
+ for (var i = 0; i < tagroots.length; i++) {
522
+ var k = tagroots[i];
523
+ if (k in ls) extra.push("[" + k + ": " + ls[k] + "]");
524
+ }
525
+ if (extra.length === 0) return s;
526
+ return Object.assign({}, s, { stack: extra.concat(s.stack) });
527
+ });
528
+ }
529
+
530
+ // tagleaf: append label values as leaf frames (innermost first)
531
+ if (tagleaves.length > 0) {
532
+ filtered = filtered.map(function(s) {
533
+ if (s.label_set_id === 0) return s;
534
+ var ls = labelSets[s.label_set_id];
535
+ if (!ls) return s;
536
+ var extra = [];
537
+ for (var i = 0; i < tagleaves.length; i++) {
538
+ var k = tagleaves[i];
539
+ if (k in ls) extra.push("[" + k + ": " + ls[k] + "]");
540
+ }
541
+ if (extra.length === 0) return s;
542
+ return Object.assign({}, s, { stack: s.stack.concat(extra) });
543
+ });
544
+ }
545
+
546
+ return filtered;
547
+ }
548
+
549
+ function applyAndRender() {
550
+ filteredSamples = getFilteredSamples();
551
+ totalFilteredNs = 0;
552
+ for (var i = 0; i < filteredSamples.length; i++) totalFilteredNs += filteredSamples[i].weight;
553
+
554
+ // Update info bar
555
+ if (!currentData) return;
556
+ var dur = (currentData.duration_ns / 1e9).toFixed(2);
557
+ document.getElementById("info-bar").textContent =
558
+ "Mode: " + currentData.mode + " | Freq: " + currentData.frequency + "Hz | Duration: " + dur + "s" +
559
+ " | Stacks: " + filteredSamples.length + " | Total weight: " + fmtMs(totalFilteredNs) + "ms";
560
+
561
+ renderCurrentTab();
562
+ }
563
+
564
+ function renderCurrentTab() {
565
+ if (currentTab === "flamegraph") renderFlamegraph();
566
+ else if (currentTab === "top") renderTop();
567
+ else if (currentTab === "tags") renderTags();
568
+ }
569
+
570
+ // ==================== Flamegraph ====================
571
+
572
+ function buildTree(samples) {
573
+ var root = { name: "root", value: 0, children: [] };
574
+ for (var si = 0; si < samples.length; si++) {
575
+ var sample = samples[si];
576
+ var node = root;
577
+ for (var i = 0; i < sample.stack.length; i++) {
578
+ var name = sample.stack[i];
579
+ var child = null;
580
+ for (var j = 0; j < node.children.length; j++) {
581
+ if (node.children[j].name === name) { child = node.children[j]; break; }
582
+ }
583
+ if (!child) {
584
+ child = { name: name, value: 0, children: [] };
585
+ node.children.push(child);
586
+ }
587
+ node = child;
588
+ }
589
+ node.value += sample.weight;
590
+ }
591
+ return root;
592
+ }
593
+
594
+ function renderFlamegraph() {
595
+ var el = document.getElementById("panel-flamegraph");
596
+ el.innerHTML = "";
597
+ if (!filteredSamples || filteredSamples.length === 0) {
598
+ el.innerHTML = '<div class="empty-state">No matching samples</div>';
599
+ return;
600
+ }
601
+ var tree = buildTree(filteredSamples);
602
+ var total = totalFilteredNs;
603
+ var width = el.clientWidth || document.body.clientWidth;
604
+ var chart = flamegraph()
605
+ .width(width)
606
+ .cellHeight(20)
607
+ .selfValue(true)
608
+ .getName(function(d) {
609
+ return d.data.name + " (" + fmtMs(d.data.value) + "ms, " + fmtPct(d.data.value, total) + "%)";
610
+ });
611
+ d3.select("#panel-flamegraph").datum(tree).call(chart);
612
+ }
613
+
614
+ // ==================== Top ====================
615
+
616
+ var topSortKey = "flat";
617
+ var topSortAsc = false;
618
+
619
+ function renderTop() {
620
+ var el = document.getElementById("panel-top");
621
+ if (!filteredSamples || filteredSamples.length === 0) {
622
+ el.innerHTML = '<div class="empty-state">No matching samples</div>';
623
+ return;
624
+ }
625
+
626
+ // Compute flat (leaf) and cumulative (any position) per function
627
+ var flatMap = {};
628
+ var cumMap = {};
629
+ for (var si = 0; si < filteredSamples.length; si++) {
630
+ var s = filteredSamples[si];
631
+ var stack = s.stack;
632
+ var w = s.weight;
633
+ var leaf = stack[stack.length - 1];
634
+ flatMap[leaf] = (flatMap[leaf] || 0) + w;
635
+ var seen = {};
636
+ for (var i = 0; i < stack.length; i++) {
637
+ if (!seen[stack[i]]) {
638
+ seen[stack[i]] = true;
639
+ cumMap[stack[i]] = (cumMap[stack[i]] || 0) + w;
640
+ }
641
+ }
642
+ }
643
+
644
+ var rows = [];
645
+ var allNames = {};
646
+ Object.keys(flatMap).forEach(function(k) { allNames[k] = true; });
647
+ Object.keys(cumMap).forEach(function(k) { allNames[k] = true; });
648
+ Object.keys(allNames).forEach(function(name) {
649
+ rows.push({ name: name, flat: flatMap[name] || 0, cum: cumMap[name] || 0 });
650
+ });
651
+
652
+ // Sort
653
+ var key = topSortKey;
654
+ var asc = topSortAsc;
655
+ rows.sort(function(a, b) {
656
+ var va = (key === "name") ? a.name : a[key];
657
+ var vb = (key === "name") ? b.name : b[key];
658
+ if (key === "name") {
659
+ return asc ? va.localeCompare(vb) : vb.localeCompare(va);
660
+ }
661
+ return asc ? va - vb : vb - va;
662
+ });
663
+
664
+ var total = totalFilteredNs;
665
+ var arrow = function(k) { return (topSortKey === k) ? (topSortAsc ? " \u25b2" : " \u25bc") : ""; };
666
+ var html = '<table><thead><tr>' +
667
+ '<th class="num" data-sort="flat">Flat' + arrow("flat") + '</th>' +
668
+ '<th class="num" data-sort="cum">Cum' + arrow("cum") + '</th>' +
669
+ '<th data-sort="name">Function' + arrow("name") + '</th>' +
670
+ '</tr></thead><tbody>';
671
+ var limit = Math.min(rows.length, 50);
672
+ for (var ri = 0; ri < limit; ri++) {
673
+ var r = rows[ri];
674
+ html += '<tr>' +
675
+ '<td class="num">' + fmtMs(r.flat) + 'ms (' + fmtPct(r.flat, total) + '%)</td>' +
676
+ '<td class="num">' + fmtMs(r.cum) + 'ms (' + fmtPct(r.cum, total) + '%)</td>' +
677
+ '<td>' + escHtml(r.name) + '</td>' +
678
+ '</tr>';
679
+ }
680
+ html += '</tbody></table>';
681
+ if (rows.length > 50) {
682
+ html += '<p style="color:#888;margin-top:8px;font-size:12px;">Showing top 50 of ' + rows.length + ' functions</p>';
683
+ }
684
+ el.innerHTML = html;
685
+
686
+ // Attach sort handlers
687
+ el.querySelectorAll("th[data-sort]").forEach(function(th) {
688
+ th.addEventListener("click", function() {
689
+ var newKey = th.getAttribute("data-sort");
690
+ if (topSortKey === newKey) {
691
+ topSortAsc = !topSortAsc;
692
+ } else {
693
+ topSortKey = newKey;
694
+ topSortAsc = (newKey === "name");
695
+ }
696
+ renderTop();
697
+ });
698
+ });
699
+ }
700
+
701
+ function escHtml(s) {
702
+ return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
703
+ }
704
+
705
+ // ==================== Tags ====================
706
+
707
+ function renderTags() {
708
+ var el = document.getElementById("panel-tags");
709
+ if (!currentData) { el.innerHTML = '<div class="empty-state">No data</div>'; return; }
710
+
711
+ var samples = filteredSamples || [];
712
+ var labelSets = currentData.label_sets || [];
713
+ if (labelSets.length === 0) {
714
+ el.innerHTML = '<div class="empty-state">No tags in this snapshot</div>';
715
+ return;
716
+ }
717
+
718
+ // Collect all tag keys
719
+ var tagKeys = {};
720
+ labelSets.forEach(function(ls) {
721
+ if (!ls) return;
722
+ Object.keys(ls).forEach(function(k) { tagKeys[k] = true; });
723
+ });
724
+
725
+ var keys = Object.keys(tagKeys);
726
+ if (keys.length === 0) {
727
+ el.innerHTML = '<div class="empty-state">No tags in this snapshot</div>';
728
+ return;
729
+ }
730
+
731
+ // For each key, aggregate weight per value
732
+ var html = "";
733
+ keys.forEach(function(key) {
734
+ var byVal = {}; // value -> weight
735
+ var untagged = 0; // weight without this key
736
+ for (var i = 0; i < samples.length; i++) {
737
+ var s = samples[i];
738
+ var ls = (s.label_set_id > 0) ? labelSets[s.label_set_id] : null;
739
+ if (ls && key in ls) {
740
+ var v = String(ls[key]);
741
+ byVal[v] = (byVal[v] || 0) + s.weight;
742
+ } else {
743
+ untagged += s.weight;
744
+ }
745
+ }
746
+
747
+ var entries = [];
748
+ Object.keys(byVal).forEach(function(v) { entries.push({ val: v, weight: byVal[v] }); });
749
+ entries.sort(function(a, b) { return b.weight - a.weight; });
750
+ var maxWeight = entries.length > 0 ? entries[0].weight : 0;
751
+ var total = totalFilteredNs;
752
+
753
+ html += '<div class="tag-group"><h3>' + escHtml(key) +
754
+ ' <span style="color:#666;font-weight:normal;">(' + entries.length + ' values)</span></h3>';
755
+ html += '<table><thead><tr><th>Value</th><th class="num">Weight</th><th class="num">%</th><th style="width:200px"></th></tr></thead><tbody>';
756
+ entries.forEach(function(e) {
757
+ var barW = maxWeight > 0 ? Math.max(1, Math.round(e.weight / maxWeight * 180)) : 0;
758
+ html += '<tr data-tagfocus="' + escAttr(key) + ':' + escAttr(e.val) + '">' +
759
+ '<td>' + escHtml(e.val) + '</td>' +
760
+ '<td class="num">' + fmtMs(e.weight) + 'ms</td>' +
761
+ '<td class="num">' + fmtPct(e.weight, total) + '%</td>' +
762
+ '<td><span class="tag-bar" style="width:' + barW + 'px"></span></td>' +
763
+ '</tr>';
764
+ });
765
+ if (untagged > 0) {
766
+ html += '<tr style="color:#666"><td>(untagged)</td>' +
767
+ '<td class="num">' + fmtMs(untagged) + 'ms</td>' +
768
+ '<td class="num">' + fmtPct(untagged, total) + '%</td>' +
769
+ '<td></td></tr>';
770
+ }
771
+ html += '</tbody></table></div>';
772
+ });
773
+
774
+ el.innerHTML = html;
775
+
776
+ // Click on a tag value row -> set tagfocus and switch to flamegraph
777
+ el.querySelectorAll("tr[data-tagfocus]").forEach(function(tr) {
778
+ tr.addEventListener("click", function() {
779
+ var parts = tr.getAttribute("data-tagfocus").split(":");
780
+ var val = parts.slice(1).join(":");
781
+ document.getElementById("in-tagfocus").value = "^" + escRegex(val) + "$";
782
+ switchTab("flamegraph");
783
+ applyAndRender();
784
+ });
785
+ });
786
+ }
787
+
788
+ function escAttr(s) { return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"); }
789
+ function escRegex(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
790
+
791
+ // ==================== Tab switching ====================
792
+
793
+ function switchTab(name) {
794
+ currentTab = name;
795
+ document.querySelectorAll(".tab").forEach(function(t) {
796
+ t.classList.toggle("active", t.getAttribute("data-tab") === name);
797
+ });
798
+ document.querySelectorAll(".tab-content").forEach(function(c) {
799
+ c.classList.toggle("active", c.id === "panel-" + name);
800
+ });
801
+ renderCurrentTab();
802
+ }
803
+
804
+ // ==================== Events ====================
805
+
806
+ document.getElementById("sel-snapshot").addEventListener("change", function(e) {
807
+ if (e.target.value) loadSnapshot(e.target.value);
808
+ });
809
+
810
+ // Dropdown toggles for tagignore, tagroot, tagleaf
811
+ ["tagignore", "tagroot", "tagleaf"].forEach(function(name) {
812
+ document.getElementById("btn-" + name).addEventListener("click", function(e) {
813
+ e.stopPropagation();
814
+ // Close other dropdowns first
815
+ ["tagignore", "tagroot", "tagleaf"].forEach(function(other) {
816
+ if (other !== name) document.getElementById("cb-" + other).classList.remove("open");
817
+ });
818
+ document.getElementById("cb-" + name).classList.toggle("open");
819
+ });
820
+ });
821
+ document.addEventListener("click", function(e) {
822
+ ["tagignore", "tagroot", "tagleaf"].forEach(function(name) {
823
+ var list = document.getElementById("cb-" + name);
824
+ if (!list.contains(e.target) && e.target.id !== "btn-" + name) {
825
+ list.classList.remove("open");
826
+ }
827
+ });
828
+ });
829
+
830
+ document.querySelectorAll(".tab").forEach(function(t) {
831
+ t.addEventListener("click", function() { switchTab(t.getAttribute("data-tab")); });
832
+ });
833
+
834
+ var inputs = document.querySelectorAll(".controls input[type=text]");
835
+ for (var i = 0; i < inputs.length; i++) {
836
+ inputs[i].addEventListener("keydown", function(e) {
837
+ if (e.key === "Enter") applyAndRender();
838
+ });
839
+ }
840
+
841
+ // --- Init ---
842
+ loadSnapshotList();
843
+ </script>
844
+ </body>
845
+ </html>
846
+ HTML
847
+ end