aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/assets/client/profile-worker.js (4673B)


      1 // Collect and upload outside the game and browser UI threads. All queues are bounded.
      2 let configuration, memory, uploading = false, sequence = 0, dropped = 0;
      3 let events = [], frames = [], metrics = {}, visibility = 'visible', build = null;
      4 let started = 0;
      5 const threads = new Map();
      6 
      7 function record(event) {
      8   if (events.length < 4096) events.push(event);
      9   else ++dropped;
     10 }
     11 
     12 onmessage = event => {
     13   const data = event.data;
     14   if (data.init) {
     15     configuration = data.init;
     16     visibility = configuration.visibility;
     17     memory = new Uint32Array(configuration.memory);
     18     started = configuration.started;
     19     fetch(new URL('build.json', location.href)).then(response => {
     20       if (!response.ok) throw new Error(`HTTP ${response.status}`);
     21       return response.json();
     22     }).then(value => { build = value.source_commit; }).catch(error => {
     23       postMessage(`Profiling: build identity unavailable (${error.message})`);
     24     });
     25     if (configuration.detailed) setInterval(() => {
     26       // Best-effort guest function residency, including host calls and waits.
     27       // This is not an instruction-pointer or CPU-time sample.
     28       record({name: 'guest sample', ph: 'i', s: 't', pid: 1, tid: configuration.thread,
     29         ts: (performance.timeOrigin + performance.now()) * 1000,
     30         args: {function: Atomics.load(memory, configuration.currentFunction >>> 2),
     31           phase: Atomics.load(memory, configuration.phase >>> 2)}});
     32       for (const {sample, thread, entry} of threads.values()) {
     33         const pointer = Atomics.load(memory, sample >>> 2);
     34         if (!pointer) continue;
     35         const address = Atomics.load(memory, pointer >>> 2);
     36         const phase = Atomics.load(memory, (sample + 4) >>> 2);
     37         // An exiting thread invalidates its record before its TLS can be reused.
     38         if (Atomics.load(memory, sample >>> 2) !== pointer) continue;
     39         record({name: 'guest sample', ph: 'i', s: 't', pid: 1, tid: thread,
     40           ts: (performance.timeOrigin + performance.now()) * 1000,
     41           args: {function: address, phase, entry}});
     42       }
     43     }, 4);
     44     setInterval(upload, configuration.detailed ? 1000 : 30000);
     45     postMessage(`${configuration.detailed ? 'Detailed profile' : 'Performance summaries'}: ${configuration.session}`);
     46     return;
     47   }
     48   if (data.register) {
     49     if (data.memory.byteLength > memory.byteLength) memory = new Uint32Array(data.memory);
     50     threads.set(data.register.sample, data.register);
     51     return;
     52   }
     53   if (data.unregister) {
     54     threads.delete(data.unregister);
     55     postMessage({free: data.unregister});
     56     return;
     57   }
     58   if (data.visibility) { upload(); visibility = data.visibility; return; }
     59   for (const item of data.events) record(item);
     60   for (const duration of data.frames) {
     61     if (frames.length < 120000) frames.push(duration);
     62     else ++dropped;
     63   }
     64   dropped += data.dropped;
     65   for (const [name, value] of Object.entries(data.metrics)) {
     66     const metric = metrics[name] ||= {count: 0, ms: 0, max: 0};
     67     metric.count += value.count; metric.ms += value.ms;
     68     metric.max = Math.max(metric.max, value.max);
     69   }
     70 };
     71 
     72 async function upload() {
     73   if (uploading) return;
     74   const ended = performance.timeOrigin + performance.now();
     75   frames.sort((a, b) => a - b);
     76   const sum = frames.reduce((total, value) => total + value, 0);
     77   const batch = {version: 1, sequence: sequence++, build, detailed: configuration.detailed,
     78     client: configuration.client, started, ended, visibility, dropped,
     79     frames: {count: frames.length, mean: frames.length ? sum / frames.length : 0,
     80       p95: frames[Math.floor(frames.length * .95)] || 0,
     81       p99: frames[Math.floor(frames.length * .99)] || 0, max: frames.at(-1) || 0,
     82       over50: frames.filter(value => value > 50).length,
     83       over100: frames.filter(value => value > 100).length}, metrics, traceEvents: events};
     84   events = []; frames = []; metrics = {}; dropped = 0; started = ended;
     85   uploading = true;
     86   try {
     87     const response = await fetch(new URL(`../admin/browser-profile/${configuration.session}`, location.href), {
     88       method: 'POST', headers: {'Content-Type': 'application/json'},
     89       body: JSON.stringify(batch), signal: AbortSignal.timeout(10000)
     90     });
     91     if (response.status !== 204) throw new Error(`HTTP ${response.status}`);
     92     postMessage(`Profile saved: logs/profiles/${configuration.session}.ndjson (batch ${batch.sequence})`);
     93   } catch (error) {
     94     // Failed uploads are discarded, never retried on the game thread.
     95     dropped += batch.dropped + batch.traceEvents.length + batch.frames.count;
     96     postMessage(`Profile upload failed: ${error.message}; gameplay continues`);
     97   } finally {
     98     uploading = false;
     99   }
    100 }