-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathjs_parser.rs
More file actions
268 lines (240 loc) · 8.98 KB
/
js_parser.rs
File metadata and controls
268 lines (240 loc) · 8.98 KB
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
264
265
266
267
268
//! Integration test: verify JS trace parser matches Rust parser
use dial9_tokio_telemetry::analysis_unstable::TraceReader;
use dial9_tokio_telemetry::telemetry::{RotatingWriter, TracedRuntime};
use std::io::{BufWriter, Write};
use std::process::Command;
use tempfile::TempDir;
#[inline(never)]
fn burn_cpu(iterations: u64) -> u64 {
let mut result = 0u64;
for i in 0..iterations {
result = result.wrapping_add(i.wrapping_mul(i));
}
result
}
async fn cpu_task(id: usize) {
for _ in 0..3 {
let _ = burn_cpu(1_000_000);
tokio::task::yield_now().await;
}
eprintln!("Task {id} done");
}
#[test]
fn test_js_parser_matches_rust() {
let temp_dir = TempDir::new().unwrap();
let trace_path = temp_dir.path().join("test_trace.bin");
let jsonl_path = temp_dir.path().join("expected.jsonl");
// Generate a trace — enable CPU profiling on Linux where it's available
{
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder.worker_threads(2).enable_all();
let writer = RotatingWriter::single_file(&trace_path).unwrap();
#[allow(unused_mut)]
let mut tb = TracedRuntime::builder().with_task_tracking(true);
#[cfg(feature = "cpu-profiling")]
{
tb = tb.with_cpu_profiling(
dial9_tokio_telemetry::telemetry::cpu_profile::CpuProfilingConfig::default(),
);
}
let (runtime, _guard) = tb.build_and_start(builder, writer).unwrap();
runtime.block_on(async {
let mut tasks = vec![];
for i in 0..10 {
tasks.push(tokio::spawn(cpu_task(i)));
}
for task in tasks {
let _ = task.await;
}
});
}
let sealed_path = temp_dir.path().join("test_trace.0.bin");
eprintln!("Generated trace at {}", sealed_path.display());
// Export to JSONL using Rust parser (in-process to avoid cargo subprocess overhead)
{
let reader = TraceReader::new(sealed_path.to_str().unwrap()).unwrap();
let file = std::fs::File::create(&jsonl_path).unwrap();
let mut w = BufWriter::new(file);
for e in &reader.all_events {
serde_json::to_writer(&mut w, &e).unwrap();
w.write_all(b"\n").unwrap();
}
w.flush().unwrap();
}
eprintln!("Exported JSONL to {}", jsonl_path.display());
// Run JS parser test (use CARGO_MANIFEST_DIR to find ui directory)
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let test_script = std::path::Path::new(&manifest_dir)
.parent()
.unwrap()
.join("dial9-viewer")
.join("ui")
.join("test_parser.js");
let test_output = Command::new("node")
.args([
test_script.to_str().unwrap(),
sealed_path.to_str().unwrap(),
jsonl_path.to_str().unwrap(),
])
.output()
.expect("Failed to run node test_parser.js");
eprintln!("{}", String::from_utf8_lossy(&test_output.stdout));
assert!(
test_output.status.success(),
"JS parser test failed:\n{}",
String::from_utf8_lossy(&test_output.stderr)
);
}
/// Verify that SymbolTableEntry frames at the end of a trace are still resolved
/// even when the event cap is reached (i.e., the parser doesn't break out of
/// the frame loop early and skip trailing metadata).
#[cfg(feature = "cpu-profiling")]
#[test]
fn test_js_parser_resolves_symbols_past_event_cap() {
use dial9_perf_self_profile::offline_symbolize::SymbolTableEntry;
use dial9_tokio_telemetry::telemetry::{PollEndEvent, WorkerId};
use dial9_trace_format::encoder::Encoder;
let temp_dir = TempDir::new().unwrap();
let trace_path = temp_dir.path().join("capped_trace.bin");
{
let mut enc = Encoder::new();
for i in 0..10u64 {
enc.write(&PollEndEvent {
timestamp_ns: i * 1_000_000,
worker_id: WorkerId::from(0usize),
})
.unwrap();
}
let sym_name = enc.intern_string("my_function").unwrap();
let empty_file = enc.intern_string("").unwrap();
enc.write(&SymbolTableEntry {
timestamp_ns: 0,
addr: 0x1234,
size: 256,
symbol_name: sym_name,
inline_depth: 0,
source_file: empty_file,
source_line: 0,
})
.unwrap();
std::fs::write(&trace_path, enc.finish()).unwrap();
}
// Node script: parse with maxEvents=5, verify the symbol is still resolved.
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let script = format!(
r#"
const {{ parseTrace }} = require("{viewer}/trace_parser.js");
const fs = require("fs");
async function main() {{
const result = await parseTrace(fs.readFileSync("{trace}"), {{ maxEvents: 5 }});
if (result.events.length > 5) {{
console.error("expected at most 5 events, got " + result.events.length);
process.exit(1);
}}
if (!result.truncated) {{
console.error("expected truncated=true");
process.exit(1);
}}
const sym = result.callframeSymbols.get("0x1234");
if (!sym || sym.symbol !== "my_function") {{
console.error("symbol not resolved: " + JSON.stringify(sym));
process.exit(1);
}}
console.log("OK: " + result.events.length + " events, symbol resolved");
}}
main().catch((e) => {{ console.error(e); process.exit(1); }});
"#,
viewer = std::path::Path::new(&manifest_dir)
.parent()
.unwrap()
.join("dial9-viewer")
.join("ui")
.display(),
trace = trace_path.display(),
);
let output = Command::new("node")
.args(["-e", &script])
.output()
.expect("Failed to run node");
eprintln!("{}", String::from_utf8_lossy(&output.stdout));
assert!(
output.status.success(),
"JS parser symbol resolution test failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn test_js_parser_alloc_free_events() {
use dial9_tokio_telemetry::telemetry::{AllocEvent, FreeEvent};
use dial9_trace_format::encoder::Encoder;
let temp_dir = TempDir::new().unwrap();
let trace_path = temp_dir.path().join("alloc_trace.bin");
{
let mut enc = Encoder::new();
let stack = enc.intern_stack_frames(&[0xAAAA, 0xBBBB, 0xCCCC]).unwrap();
enc.write(&AllocEvent {
timestamp_ns: 5_000_000,
tid: 42,
size: 4096,
addr: 0xDEAD_BEEF,
callchain: stack,
})
.unwrap();
enc.write(&FreeEvent {
timestamp_ns: 10_000_000,
tid: 7,
addr: 0xDEAD_BEEF,
size: 4096,
alloc_timestamp_ns: 5_000_000,
})
.unwrap();
std::fs::write(&trace_path, enc.finish()).unwrap();
}
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let script = format!(
r#"
const {{ parseTrace }} = require("{viewer}/trace_parser.js");
const fs = require("fs");
async function main() {{
const result = await parseTrace(fs.readFileSync("{trace}"));
if (result.allocEvents.length !== 1) {{
console.error("expected 1 allocEvent, got " + result.allocEvents.length);
process.exit(1);
}}
const a = result.allocEvents[0];
if (a.tid !== 42) {{ console.error("bad tid: " + a.tid); process.exit(1); }}
if (a.size !== 4096) {{ console.error("bad size: " + a.size); process.exit(1); }}
if (a.callchain.length !== 3) {{ console.error("bad callchain len: " + a.callchain.length); process.exit(1); }}
if (result.freeEvents.length !== 1) {{
console.error("expected 1 freeEvent, got " + result.freeEvents.length);
process.exit(1);
}}
const f = result.freeEvents[0];
if (f.tid !== 7) {{ console.error("bad free tid: " + f.tid); process.exit(1); }}
if (f.addr !== "3735928559") {{ console.error("bad free addr: " + f.addr); process.exit(1); }}
if (f.size !== 4096) {{ console.error("bad free size: " + f.size); process.exit(1); }}
if (f.allocTimestampNs !== 5000000) {{ console.error("bad allocTimestampNs: " + f.allocTimestampNs); process.exit(1); }}
console.log("OK: allocEvents=" + result.allocEvents.length + " freeEvents=" + result.freeEvents.length);
}}
main().catch((e) => {{ console.error(e); process.exit(1); }});
"#,
viewer = std::path::Path::new(&manifest_dir)
.parent()
.unwrap()
.join("dial9-viewer")
.join("ui")
.display(),
trace = trace_path.display(),
);
let output = Command::new("node")
.args(["-e", &script])
.output()
.expect("Failed to run node");
eprintln!("{}", String::from_utf8_lossy(&output.stdout));
assert!(
output.status.success(),
"JS parser alloc/free test failed:\nstdout: {}\nstderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}