client/tests/browser_profile.mjs (13086B)
1 import assert from 'node:assert/strict'; 2 import fs from 'node:fs'; 3 import vm from 'node:vm'; 4 5 function fixture(detailed, status = 204) { 6 const uploads = [], timers = [], messages = []; 7 let rejectUpload = false, pendingUpload; 8 const memory = new SharedArrayBuffer(32); 9 new Uint32Array(memory).set([0x12345678, 3]); 10 const context = vm.createContext({ 11 Uint32Array, Atomics, performance: {timeOrigin: 1000, now: () => 100}, 12 setInterval: (callback, delay) => timers.push({callback, delay}), 13 postMessage: message => messages.push(message), AbortSignal, URL, 14 location: {href: 'https://example.test/wasm/profile-worker.js'}, 15 fetch: async (url, options) => { 16 if (!options) { 17 assert.equal(url.href, 'https://example.test/wasm/build.json'); 18 return {ok: true, json: async () => ({source_commit: 'build-test'})}; 19 } 20 assert.equal(url.href, 'https://example.test/admin/browser-profile/test'); 21 uploads.push(JSON.parse(options.body)); 22 if (rejectUpload) throw new Error('offline'); 23 if (pendingUpload) await pendingUpload; 24 return {status}; 25 } 26 }); 27 vm.runInContext(fs.readFileSync(new URL('../browser/profile-worker.js', import.meta.url), 'utf8'), context); 28 context.onmessage({data: {init: {session: 'test', detailed, memory, 29 currentFunction: 0, phase: 4, thread: 7, started: 1000, visibility: 'visible'}}}); 30 return {uploads, timers, messages, memory, send: data => context.onmessage({data}), 31 offline: () => { rejectUpload = true; }, hold: promise => { pendingUpload = promise; }}; 32 } 33 34 async function summaries() { 35 const test = fixture(false); 36 test.send({events: [], frames: [10, 20, 60, 110], dropped: 0, 37 metrics: {'file read': {count: 2, ms: 50, max: 40}}}); 38 39 await test.timers[0].callback(); 40 41 assert.equal(test.timers.length, 1); 42 assert.equal(test.timers[0].delay, 30000); 43 assert.deepEqual(test.uploads[0].frames, {count: 4, mean: 50, p95: 110, p99: 110, max: 110, over50: 2, over100: 1}); 44 assert.deepEqual(test.uploads[0].traceEvents, []); 45 assert.deepEqual(test.uploads[0].metrics['file read'], {count: 2, ms: 50, max: 40}); 46 } 47 48 async function boundedSamplingAndFailedUpload() { 49 const test = fixture(true); 50 test.offline(); 51 52 for (let index = 0; index < 4106; ++index) test.timers[0].callback(); 53 await test.timers[1].callback(); 54 await test.timers[1].callback(); 55 56 assert.equal(test.uploads[0].traceEvents.length, 4096); 57 assert.equal(test.uploads[0].dropped, 10); 58 assert.deepEqual(test.uploads[0].traceEvents[0].args, {function: 0x12345678, phase: 3}); 59 assert.equal(test.uploads[1].traceEvents.length, 0); 60 assert.equal(test.uploads[1].dropped, 4106); 61 assert.match(test.messages.at(-1), /upload failed.*offline/); 62 } 63 64 async function slowUploadDoesNotAccumulateRequests() { 65 const test = fixture(true); 66 let release; 67 test.hold(new Promise(resolve => { release = resolve; })); 68 69 const pending = test.timers[1].callback(); 70 await test.timers[1].callback(); 71 for (let index = 0; index < 4106; ++index) test.timers[0].callback(); 72 release(); 73 await pending; 74 await test.timers[1].callback(); 75 76 assert.equal(test.uploads.length, 2); 77 assert.equal(test.uploads[1].traceEvents.length, 4096); 78 assert.equal(test.uploads[1].dropped, 10); 79 } 80 81 await summaries(); 82 await boundedSamplingAndFailedUpload(); 83 await slowUploadDoesNotAccumulateRequests(); 84 console.log('PASS: gameplay profile summaries, sampling, queue bounds and failed/slow uploads'); 85 86 // Worker TLS may be reclaimed before its unregister message reaches the collector. 87 { 88 const test = fixture(true); 89 const memory = new SharedArrayBuffer(64), heap = new Uint32Array(memory); 90 heap.set(new Uint32Array(test.memory)); 91 heap.set([48, 3], 8); 92 heap[12] = 0x400110E0; 93 test.send({register: {sample: 32, entry: 0x1234, thread: 8}, memory}); 94 test.timers[0].callback(); 95 Atomics.store(heap, 8, 0); 96 heap[12] = 0xFFFFFFFF; 97 test.timers[0].callback(); 98 test.send({unregister: 32}); 99 test.timers[0].callback(); 100 await test.timers[1].callback(); 101 102 const samples = test.uploads[0].traceEvents.filter(event => event.tid === 8); 103 assert.equal(samples.length, 1); 104 assert.deepEqual(samples[0].args, {function: 0x400110E0, phase: 3, entry: 0x1234}); 105 assert.equal(test.messages.filter(message => message.free === 32).length, 1); 106 } 107 console.log('PASS: guest worker sampling handles memory growth and invalidated TLS'); 108 109 // Normal play starts no worker, timers or collection channel. 110 for (const search of ['', '?profile=0', '?profile=other']) { 111 let library; 112 const context = vm.createContext({ 113 addToLibrary: value => { library = value; }, URLSearchParams, 114 location: {search}, _browser_profile_configuration: () => 0 115 }); 116 vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context); 117 context.AOProfile = library.$AOProfile; 118 assert.equal(library.ao_profile_start(4, 8, 7), 0); 119 assert.equal(context.AOProfile.begin('render scene'), 0); 120 context.AOProfile.frame(); 121 context.AOProfile.flush(); 122 assert.equal(context.AOProfile.events.length, 0); 123 assert.equal(context.AOProfile.frames.length, 0); 124 assert.equal(Object.keys(context.AOProfile.metrics).length, 0); 125 } 126 127 // Explicit opt-in starts the collector with the detailed configuration. 128 { 129 let library; 130 const workers = [], messages = [], channels = []; 131 const audioContext = Object.assign(new EventTarget(), {state: 'suspended'}); 132 const context = vm.createContext({ 133 addToLibrary: value => { library = value; }, URLSearchParams, URL, 134 location: {search: '?profile=1'}, crypto: {randomUUID: () => 'test'}, 135 Worker: class { constructor(url) { workers.push(url.pathname); } postMessage(message) { messages.push(message); } }, 136 BroadcastChannel: class { constructor() { channels.push(this); } }, 137 wasmMemory: {buffer: new SharedArrayBuffer(64)}, 138 document: {baseURI: 'https://example.test/', visibilityState: 'visible', addEventListener() {}}, 139 navigator: {userAgent: 'test'}, Module: {canvas: {width: 640, height: 480}, audioContext}, 140 performance: {timeOrigin: 1000, now: () => 10}, stringToNewUTF8: value => value 141 }); 142 vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context); 143 assert.equal(library.ao_profile_start(4, 8, 7), '1:test:8:7'); 144 assert.deepEqual(workers, ['/wasm/profile-worker.js']); 145 assert.equal(messages.length, 2); 146 assert.equal(messages[0].init.detailed, true); 147 assert.equal(messages[1].events[0].name, 'audio context state'); 148 assert.equal(messages[1].events[0].args.state, 'suspended'); 149 assert.equal(messages[1].events[0].ts, 1010000); 150 channels[0].onmessage({data: {register: {sample: 32, entry: 0x1234, thread: 8}}}); 151 assert.equal(messages[2].register.sample, 32); 152 assert.equal(messages[2].memory, context.wasmMemory.buffer); 153 audioContext.state = 'running'; 154 audioContext.dispatchEvent(new Event('statechange')); 155 assert.equal(messages[3].events[0].args.state, 'running'); 156 } 157 console.log('PASS: profiling stays off until explicitly enabled'); 158 159 async function clientSpansRestorePhases() { 160 let library, now = 0; 161 const sent = []; 162 const heap = new Uint32Array(new SharedArrayBuffer(16)); 163 const context = vm.createContext({ 164 Atomics, HEAPU32: heap, performance: {timeOrigin: 1000, now: () => now}, 165 _browser_profile_configuration: () => '1:test:4:7', _pthread_self: () => 7, 166 UTF8ToString: value => value, setInterval: () => {}, 167 BroadcastChannel: class { postMessage(value) { sent.push(value); } }, 168 addToLibrary: value => { library = value; } 169 }); 170 vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context); 171 context.AOProfile = library.$AOProfile; 172 173 const render = library.ao_profile_begin('render scene'); 174 const read = library.ao_profile_begin('file read'); 175 assert.equal(heap[1], 3); 176 now = 170; 177 library.ao_profile_end('file read', read, 'ResourceDatabase.dat'); 178 assert.equal(heap[1], 2); 179 now = 180; 180 library.ao_profile_end('render scene', render, 0); 181 context.AOProfile.frame(); 182 now = 200; 183 context.AOProfile.frame(); 184 context.AOProfile.flush(); 185 186 assert.equal(heap[1], 0); 187 assert.equal(sent.length, 1); 188 assert.equal(sent[0].metrics['file read'].ms, 170); 189 assert.equal(sent[0].events[0].args.detail, 'ResourceDatabase.dat'); 190 assert.equal(sent[0].metrics['render scene'].ms, 180); 191 assert.equal(sent[0].frames[0], 20); 192 assert.equal(sent[0].events[2].name, 'frame interval'); 193 assert.equal(sent[0].events[2].dur, 20000); 194 } 195 196 await clientSpansRestorePhases(); 197 console.log('PASS: nested client spans, frame intervals and wait phase restoration'); 198 199 async function oldServerDoesNotReportSuccess() { 200 const test = fixture(false, 200); 201 202 await test.timers[0].callback(); 203 204 assert.match(test.messages.at(-1), /upload failed: HTTP 200/); 205 } 206 207 await oldServerDoesNotReportSuccess(); 208 console.log('PASS: an old server response cannot be mistaken for a saved profile'); 209 210 function cachedReadsStayInAggregates() { 211 let library, now = 0; 212 const context = vm.createContext({ 213 performance: {timeOrigin: 1000, now: () => now}, 214 _browser_profile_configuration: () => '1:test:0:7', _pthread_self: () => 7, 215 UTF8ToString: value => value, setInterval: () => {}, 216 BroadcastChannel: class { postMessage() {} }, 217 addToLibrary: value => { library = value; } 218 }); 219 vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context); 220 context.AOProfile = library.$AOProfile; 221 222 const start = library.ao_profile_begin('file read'); 223 now = 0.01; 224 library.ao_profile_end('file read', start, 0); 225 226 assert.equal(context.AOProfile.events.length, 0); 227 assert.equal(context.AOProfile.metrics['file read'].count, 1); 228 assert.ok(context.AOProfile.metrics['file read'].ms > 0); 229 } 230 231 cachedReadsStayInAggregates(); 232 console.log('PASS: tiny cached reads are counted without flooding the detailed trace'); 233 234 function busyWorkersFlushWithoutJSTimers() { 235 let library, now = 0; 236 const sent = []; 237 const context = vm.createContext({ 238 performance: {timeOrigin: 1000, now: () => now}, 239 _browser_profile_configuration: () => '0:test:0:7', _pthread_self: () => 7, 240 UTF8ToString: value => value, setInterval: () => {}, 241 BroadcastChannel: class { postMessage(value) { sent.push(value); } }, 242 addToLibrary: value => { library = value; } 243 }); 244 vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context); 245 context.AOProfile = library.$AOProfile; 246 247 const mix = library.ao_profile_begin('audio mix'); 248 now = 1001; 249 library.ao_profile_end('audio mix', mix, 0); 250 const decode = library.ao_profile_begin('sound load/decode'); 251 now = 1002; 252 library.ao_profile_end('sound load/decode', decode, 0); 253 254 assert.equal(sent.length, 2); 255 assert.equal(sent[0].metrics['audio mix'].count, 1); 256 assert.equal(sent[1].metrics['sound load/decode'].ms, 1); 257 assert.equal(sent[0].events.length, 0); 258 } 259 260 busyWorkersFlushWithoutJSTimers(); 261 console.log('PASS: busy and short-lived audio workers deliver aggregates without JS timer callbacks'); 262 263 async function frameCallbackTimestampPreservesPacing() { 264 for (const detailed of [false, true]) { 265 let library, now = 0, callbacks = 0, firstFrames = 0; 266 const sent = []; 267 const heap = new Uint32Array(new SharedArrayBuffer(16)); 268 heap[1] = 2; 269 const context = vm.createContext({ 270 Atomics, HEAPU32: heap, performance: {timeOrigin: 1000, now: () => now}, 271 _browser_profile_configuration: () => `${detailed ? 1 : 0}:test:4:7`, _pthread_self: () => 7, 272 UTF8ToString: value => value, setInterval: () => {}, 273 requestAnimationFrame: () => { ++callbacks; }, 274 AOPresented: false, AOFrameWait: 0, _ao_loading_complete: () => { ++firstFrames; }, 275 BroadcastChannel: class { postMessage(value) { sent.push(value); } }, 276 addToLibrary: value => { library = value; } 277 }); 278 vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context); 279 context.AOProfile = library.$AOProfile; 280 vm.runInContext(fs.readFileSync(new URL('../runtime/browser_host.js', import.meta.url), 'utf8'), context); 281 context.AOTest = library.$AOTest; 282 283 assert.equal(library.ao_frame_complete(), undefined); 284 now = 180; 285 library.ao_frame_begin(20); 286 context.AOProfile.flush(); 287 288 assert.equal(callbacks, 0); 289 assert.equal(firstFrames, 1); 290 assert.equal(heap[1], 2); 291 assert.equal(sent.length, 1); 292 assert.equal(sent[0].metrics['raf wait'].ms, 180); 293 assert.equal(sent[0].events.length, detailed ? 1 : 0); 294 if (detailed) { 295 assert.equal(sent[0].events[0].ts, 1000000); 296 assert.equal(sent[0].events[0].dur, 180000); 297 assert.equal(sent[0].events[0].args.frame_time_us, 1020000); 298 } 299 library.ao_frame_complete(); 300 library.ao_frame_begin(200); 301 assert.equal(firstFrames, 1); 302 } 303 } 304 305 await frameCallbackTimestampPreservesPacing(); 306 console.log('PASS: detailed RAF timestamps preserve callback pacing, phases and summary metrics');