namespace Mimante.Schermate.Misura; /// /// Lo strumento di misura dentro la pagina, messo con Page.addScriptToEvaluateOnNewDocument prima di ogni /// altro script: window.__mimantePerf. /// /// /// un ciclo di requestAnimationFrame che registra l'intervallo fra due frame (frame persi); /// i compiti dell'interfaccia cronometrati uno per uno (i blocchi del thread): le funzioni passate a /// setTimeout, setInterval e requestAnimationFrame, gli ascoltatori degli eventi del puntatore, /// della rotella, dello scorrimento e della finestra (la maniglia di split.js), le funzioni dei /// ResizeObserver e la gestione di ogni messaggio del bot; /// un involucro di window.WebSocket: ogni auction.delta si cronometra dall'evento del messaggio /// al primo frame dopo la sua gestione (ws.js → state.js → aste.js → grid.js aggiornano la riga in modo sincrono, e /// quel frame è il primo che la mostra); reconnect() chiude il canale e misura fino al nuovo elenco /// (snapshot) a schermo; /// un PerformanceObserver dei compiti lunghi del browser (scatta solo sopra 50 ms, quindi prende anche /// layout e stile che i cronometri non vedono): uno solo, in qualunque fase, fa fallire il criterio dei blocchi; /// sample() conta le aste in elenco e quelle in Attiva in finestra critica dallo stato della pagina /// (/js/state.js, lo stesso modulo dell'interfaccia); rows() dà a ogni <tr data-id> un /// segno, per riconoscere un nodo ridisegnato; grid() dice lo scorrimento, le righe disegnate e se la griglia /// è virtualizzata. /// /// public static class PerfScript { private const string Source = """ (() => { if (window.__mimantePerf) return; const now = () => performance.now(); const round = v => Math.round(v * 100) / 100; const P = { recording: false, frames: [], rowUpdates: [], handlers: [], tasks: [], longTasks: [], pending: [], sockets: 0, socket: null, lastOpen: 0, reconnecting: null }; // I compiti dell'interfaccia: ogni funzione data a un timer o a requestAnimationFrame, cronometrata. Gli id restano // quelli del browser, quindi clearTimeout, clearInterval e cancelAnimationFrame non cambiano. const nativeRaf = window.requestAnimationFrame.bind(window); const timed = fn => function (...a) { const s = now(); try { return fn.apply(this, a); } finally { if (P.recording) P.tasks.push(round(now() - s)); } }; for (const name of ['setTimeout', 'setInterval']) { const native = window[name].bind(window); window[name] = (fn, ...rest) => native(typeof fn === 'function' ? timed(fn) : fn, ...rest); } window.requestAnimationFrame = fn => nativeRaf(typeof fn === 'function' ? timed(fn) : fn); // Gli ascoltatori del puntatore, della rotella, dello scorrimento e della finestra e le funzioni dei ResizeObserver: // i compiti di maniglia e ridimensionamento. La stessa funzione ha sempre lo stesso involucro, così // removeEventListener la ritrova (split.js toglie pointermove e pointerup a fine trascinamento). const watched = /^(?:pointer|mouse)|^(?:wheel|scroll|resize)$/; const wrappers = new WeakMap(); const wrapped = fn => { let w = wrappers.get(fn); if (!w) { w = timed(fn); wrappers.set(fn, w); } return w; }; const nativeAdd = EventTarget.prototype.addEventListener; const nativeRemove = EventTarget.prototype.removeEventListener; EventTarget.prototype.addEventListener = function (type, fn, ...rest) { return nativeAdd.call(this, type, typeof fn === 'function' && watched.test(type) ? wrapped(fn) : fn, ...rest); }; EventTarget.prototype.removeEventListener = function (type, fn, ...rest) { return nativeRemove.call(this, type, typeof fn === 'function' && watched.test(type) ? (wrappers.get(fn) || fn) : fn, ...rest); }; const NativeResizeObserver = window.ResizeObserver; if (NativeResizeObserver) { window.ResizeObserver = class extends NativeResizeObserver { constructor(fn) { super(typeof fn === 'function' ? timed(fn) : fn); } }; } let last = 0; const loop = t => { if (P.recording && last > 0) P.frames.push(round(t - last)); last = t; if (P.pending.length) { const n = now(); for (const r of P.pending) { if (P.recording) P.rowUpdates.push(round(n - r.t0)); } P.pending.length = 0; } const rc = P.reconnecting; if (rc && rc.snapshotAt > 0) rc.done(now()); nativeRaf(loop); }; nativeRaf(loop); try { new PerformanceObserver(list => { if (!P.recording) return; for (const e of list.getEntries()) P.longTasks.push(round(e.duration)); }).observe({ type: 'longtask' }); } catch { /* browser senza longtask */ } const Native = window.WebSocket; class PerfSocket extends Native { constructor(...args) { super(...args); P.sockets++; P.socket = this; this.__perfIndex = P.sockets; this.addEventListener('open', () => { P.lastOpen = now(); }); } get onmessage() { return this.__perfHandler || null; } set onmessage(fn) { this.__perfHandler = fn; super.onmessage = typeof fn !== 'function' ? fn : ev => { const start = now(); const t0 = ev.timeStamp > 0 && ev.timeStamp <= start ? ev.timeStamp : start; const m = typeof ev.data === 'string' ? /^\{"t":"([^"]+)"/.exec(ev.data) : null; try { return fn.call(this, ev); } finally { const end = now(); const type = m ? m[1] : ''; if (P.recording) P.handlers.push(round(end - start)); if (type === 'auction.delta' && P.recording) P.pending.push({ t0 }); const rc = P.reconnecting; if (type === 'snapshot' && rc && this.__perfIndex > rc.socketIndex && !rc.snapshotAt) rc.snapshotAt = end; } }; } } window.WebSocket = PerfSocket; let token = 0; window.__mimantePerf = { start() { P.frames = []; P.rowUpdates = []; P.handlers = []; P.tasks = []; P.longTasks = []; P.pending = []; last = 0; P.recording = true; return true; }, take() { P.recording = false; const out = { frames: P.frames, rowUpdates: P.rowUpdates, handlers: P.handlers, tasks: P.tasks, longTasks: P.longTasks }; P.frames = []; P.rowUpdates = []; P.handlers = []; P.tasks = []; P.longTasks = []; return out; }, async sample() { const { state, remainingMs } = await import('/js/state.js'); let listed = 0, active = 0, critical = 0; for (const r of state.auctions.values()) { listed++; if (r.outcome || r.mode !== 'attiva') continue; active++; const ms = remainingMs(r); if (ms != null && ms > 0 && ms < __CRITICAL_MS__) critical++; } const drawn = document.querySelectorAll('.aste-list tbody tr[data-id]').length; return { listed, active, critical, drawn, connected: !!state.connected }; }, rows() { return [...document.querySelectorAll('.aste-list tbody tr[data-id]')] .map(tr => [tr.dataset.id, tr.__perfToken || (tr.__perfToken = ++token)]); }, handle() { const h = document.querySelector('.split .vsplit'); if (!h) return null; const r = h.getBoundingClientRect(); const panel = document.querySelector('.split .panel'); return { x: r.left + r.width / 2, y: r.top + r.height / 2, panel: panel ? panel.getBoundingClientRect().width : 0 }; }, grid() { const list = document.querySelector('.aste-list'); return { scroll: list ? list.scrollTop : 0, drawn: document.querySelectorAll('.aste-list tbody tr[data-id]').length, virtual: !!document.querySelector('.aste-list tbody tr.spacer-row') }; }, reconnect() { return new Promise(resolve => { const s = P.socket; if (!s || s.readyState !== 1) { resolve({ ok: false, reason: 'canale non aperto' }); return; } const rc = { start: now(), socketIndex: s.__perfIndex, snapshotAt: 0 }; const timer = setTimeout(() => { P.reconnecting = null; resolve({ ok: false, reason: 'nessun elenco nuovo entro 10 s' }); }, 10000); rc.done = at => { clearTimeout(timer); P.reconnecting = null; resolve({ ok: true, ms: round(at - rc.start), openMs: round(P.lastOpen - rc.start) }); }; P.reconnecting = rc; s.close(); }); } }; })(); """; /// Lo script con le soglie della misura. public static string Build() => Source.Replace("__CRITICAL_MS__", PerfCriteria.CriticalMs.ToString(System.Globalization.CultureInfo.InvariantCulture)); }