summaryrefslogtreecommitdiff
path: root/internal/flamegraph/livehtml_browser_test.go
blob: d8f1951a49421f9a1f4a902ed3938e1104798a6c (plain)
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
package flamegraph

import (
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"testing"
)

type jsFrame struct {
	Name  string  `json:"name"`
	X     float64 `json:"x"`
	Y     float64 `json:"y"`
	W     float64 `json:"w"`
	H     float64 `json:"h"`
	Depth int     `json:"depth"`
}

type liveJSResult struct {
	Colors         map[string]string `json:"colors"`
	KnownFrames    []jsFrame         `json:"knownFrames"`
	SVGHTML        string            `json:"svgHTML"`
	ViewBox        string            `json:"viewBox"`
	SingleCount    int               `json:"singleCount"`
	DeepMaxDepth   int               `json:"deepMaxDepth"`
	WideFrameCount int               `json:"wideFrameCount"`
}

func TestLiveHTMLJSRenderingParity(t *testing.T) {
	if _, err := exec.LookPath("node"); err != nil {
		t.Skip("node not available")
	}

	out := runLiveHTMLJSHarness(t)
	var got liveJSResult
	if err := json.Unmarshal([]byte(out), &got); err != nil {
		t.Fatalf("unmarshal node output: %v\nraw:\n%s", err, out)
	}

	names := []string{"read", "write", "io_uring_enter", "nested/path"}
	for _, name := range names {
		want := frameColor(name)
		if got.Colors[name] != want {
			t.Fatalf("fgFrameColor(%q) = %q, want %q", name, got.Colors[name], want)
		}
	}

	if len(got.KnownFrames) != 3 {
		t.Fatalf("known frame count = %d, want 3", len(got.KnownFrames))
	}
	assertFrame(t, got.KnownFrames[0], "A", 0, 96, 720, 15, 1)
	assertFrame(t, got.KnownFrames[1], "A1", 0, 80, 720, 15, 2)
	assertFrame(t, got.KnownFrames[2], "B", 720, 96, 480, 15, 1)

	if !strings.Contains(got.SVGHTML, `<g class="frame"`) {
		t.Fatalf("svg markup missing frame group")
	}
	if !strings.Contains(got.SVGHTML, `data-name="A"`) {
		t.Fatalf("svg markup missing data-name for A")
	}
	if !strings.Contains(got.SVGHTML, `data-x="0.000"`) {
		t.Fatalf("svg markup missing data-x")
	}
	if !strings.Contains(got.SVGHTML, `data-w="720.000"`) {
		t.Fatalf("svg markup missing data-w")
	}
	if !strings.Contains(got.SVGHTML, `data-depth="1"`) {
		t.Fatalf("svg markup missing data-depth")
	}
	if !strings.Contains(got.SVGHTML, `data-base-fill="rgb(`) {
		t.Fatalf("svg markup missing data-base-fill")
	}
	if got.ViewBox != "0 0 1200 128" {
		t.Fatalf("viewBox = %q, want %q", got.ViewBox, "0 0 1200 128")
	}

	if got.SingleCount != 1 {
		t.Fatalf("single-frame case count = %d, want 1", got.SingleCount)
	}
	if got.DeepMaxDepth < 50 {
		t.Fatalf("deep max depth = %d, want at least 50", got.DeepMaxDepth)
	}
	if got.WideFrameCount != 1000 {
		t.Fatalf("wide frame count = %d, want 1000", got.WideFrameCount)
	}
}

func assertFrame(t *testing.T, got jsFrame, name string, x, y, w, h float64, depth int) {
	t.Helper()
	if got.Name != name {
		t.Fatalf("frame name = %q, want %q", got.Name, name)
	}
	if got.Depth != depth {
		t.Fatalf("frame %q depth = %d, want %d", got.Name, got.Depth, depth)
	}
	const eps = 0.001
	if diff(got.X, x) > eps || diff(got.Y, y) > eps || diff(got.W, w) > eps || diff(got.H, h) > eps {
		t.Fatalf("frame %q geometry = {x:%f y:%f w:%f h:%f}, want {x:%f y:%f w:%f h:%f}",
			got.Name, got.X, got.Y, got.W, got.H, x, y, w, h)
	}
}

func diff(a, b float64) float64 {
	if a > b {
		return a - b
	}
	return b - a
}

func runLiveHTMLJSHarness(t *testing.T) string {
	t.Helper()

	script := extractLiveHTMLScript(t)
	harness := fmt.Sprintf(`
const vm = require("vm");
const liveScript = %q;

function makeElement(id) {
  return {
    id,
    textContent: "",
    innerHTML: "",
    style: {},
    dataset: {},
    attrs: {},
    classList: { toggle: function(){}, add: function(){}, remove: function(){} },
    addEventListener: function(){},
    setAttribute: function(k, v) { this.attrs[k] = String(v); },
    getAttribute: function(k) { return this.attrs[k] || ""; },
    querySelectorAll: function() { return []; },
    querySelector: function() { return null; }
  };
}

const elements = {};
["flamegraph", "status", "btn-pause", "btn-search", "btn-reset-search", "btn-undo-zoom", "btn-reset-zoom"].forEach((id) => {
  elements[id] = makeElement(id);
});
elements["body"] = makeElement("body");

global.document = {
  body: elements["body"],
  getElementById: function(id) {
    if (!elements[id]) elements[id] = makeElement(id);
    return elements[id];
  },
  addEventListener: function(){},
};
global.window = global;
global.prompt = function(){ return ""; };
global.requestAnimationFrame = function(cb){ cb(); };
global.EventSource = function() {
  this.onmessage = null;
  this.onerror = null;
};
window.addEventListener = function(){};

vm.runInThisContext(liveScript);

const names = ["read", "write", "io_uring_enter", "nested/path"];
const colors = {};
for (const n of names) {
  colors[n] = fgFrameColor(n);
}

const knownTree = {
  n: "",
  v: 0,
  t: 10,
  c: [
    { n: "A", v: 0, t: 6, c: [{ n: "A1", v: 6, t: 6 }] },
    { n: "B", v: 4, t: 4 }
  ]
};
const maxDepth = fgMaxDepth(knownTree, 0);
const canvasHeight = (liveFlamegraphState.cfg.frameHeight * (maxDepth + 1)) + 80;
const knownFramesRaw = [];
fgBuildFrames(knownTree, knownTree.t, 0, 0, canvasHeight, true, knownFramesRaw, "");
const knownFrames = knownFramesRaw.map((f) => ({
  name: f.name,
  x: Number(f.x.toFixed(3)),
  y: Number(f.y.toFixed(3)),
  w: Number(f.w.toFixed(3)),
  h: Number(f.h.toFixed(3)),
  depth: f.depth,
}));

fgRender(knownTree);
const svgHTML = elements["flamegraph"].innerHTML;
const viewBox = elements["flamegraph"].attrs["viewBox"] || "";

const singleTree = { n: "", v: 0, t: 1, c: [{ n: "only", v: 1, t: 1 }] };
const singleFrames = [];
const singleCanvas = (liveFlamegraphState.cfg.frameHeight * (fgMaxDepth(singleTree, 0) + 1)) + 80;
fgBuildFrames(singleTree, singleTree.t, 0, 0, singleCanvas, true, singleFrames, "");

let deepTree = { n: "", v: 0, t: 1, c: [] };
let cursor = deepTree;
for (let i = 0; i < 55; i++) {
  const child = { n: "d" + i, v: i === 54 ? 1 : 0, t: 1, c: [] };
  cursor.c = [child];
  cursor = child;
}
const deepMaxDepth = fgMaxDepth(deepTree, 0);

const wideChildren = [];
for (let i = 0; i < 1000; i++) {
  wideChildren.push({ n: "w" + i, v: 1, t: 1 });
}
const wideTree = { n: "", v: 0, t: 1000, c: wideChildren };
const wideCanvas = (liveFlamegraphState.cfg.frameHeight * (fgMaxDepth(wideTree, 0) + 1)) + 80;
const wideFrames = [];
fgBuildFrames(wideTree, wideTree.t, 0, 0, wideCanvas, true, wideFrames, "");

console.log(JSON.stringify({
  colors,
  knownFrames,
  svgHTML,
  viewBox,
  singleCount: singleFrames.length,
  deepMaxDepth,
  wideFrameCount: wideFrames.length,
}));
`, script)

	tmp, err := os.CreateTemp("", "livehtml-js-*.cjs")
	if err != nil {
		t.Fatalf("create temp script: %v", err)
	}
	defer os.Remove(tmp.Name())

	if _, err := tmp.WriteString(harness); err != nil {
		_ = tmp.Close()
		t.Fatalf("write temp script: %v", err)
	}
	if err := tmp.Close(); err != nil {
		t.Fatalf("close temp script: %v", err)
	}

	out, err := exec.Command("node", tmp.Name()).CombinedOutput()
	if err != nil {
		t.Fatalf("node harness failed: %v\n%s", err, string(out))
	}
	return strings.TrimSpace(string(out))
}

func extractLiveHTMLScript(t *testing.T) string {
	t.Helper()
	const openTag = "<script>"
	const closeTag = "</script>"
	start := strings.Index(liveHTML, openTag)
	if start < 0 {
		t.Fatalf("script tag not found in liveHTML")
	}
	start += len(openTag)
	end := strings.Index(liveHTML[start:], closeTag)
	if end < 0 {
		t.Fatalf("closing script tag not found in liveHTML")
	}
	return strings.TrimSpace(liveHTML[start : start+end])
}