Files
faunosteo/scripts/browser/lib/memory-probes.mjs
T

252 lines
8.7 KiB
JavaScript

/**
* The memory bench's readings (R4.9): what the export keeps, told apart.
* (1) the module's linear memory, read on the `WebAssembly.Memory` the
* page instantiated (held through a WeakRef, so the probe retains no dead
* instance); (3) the objects the rasteriser and the download create
* (canvases, images, bitmaps, blobs, the PDF blob) counted at creation and
* at collection through a FinalizationRegistry, the object URLs created
* and revoked; Chromium adds the JS heap, the DOM counters and a heap
* snapshot census of the same classes. (2) RSS and (4) peaks come from
* the watchdog, (5) the post-export windows from the bench's protocol.
* `installMemoryProbes` is serialised into the page by Playwright: it must
* not reference anything outside its own body.
*/
export const KINDS = ['canvas', 'image', 'bitmap', 'blob', 'pdfBlob']
export function installMemoryProbes() {
const kinds = ['canvas', 'image', 'bitmap', 'blob', 'pdfBlob']
const created = Object.fromEntries(kinds.map((k) => [k, 0]))
const collected = Object.fromEntries(kinds.map((k) => [k, 0]))
const registry = new FinalizationRegistry((kind) => {
collected[kind] += 1
})
const track = (object, kind) => {
created[kind] += 1
registry.register(object, kind)
return object
}
const memories = []
const urls = { created: 0, revoked: 0 }
// The raster control replays two view drawings (a logo is under 64 KB).
const svgSamples = []
const VIEW_SVG_MIN_CHARS = 64 * 1024
const keepSvg = (parts, options) => {
const text = parts?.[0]
if (svgSamples.length >= 2 || typeof text !== 'string') return
const isSvg = options?.type?.startsWith('image/svg+xml')
if (isSvg && text.length >= VIEW_SVG_MIN_CHARS) svgSamples.push(text)
}
function keepMemory(result) {
const instance =
result instanceof WebAssembly.Instance ? result : result?.instance
const memory = instance?.exports?.memory
if (memory instanceof WebAssembly.Memory) memories.push(new WeakRef(memory))
return result
}
function wrapInstantiation() {
const instantiate = WebAssembly.instantiate
WebAssembly.instantiate = function (...args) {
return instantiate.apply(WebAssembly, args).then(keepMemory)
}
const streaming = WebAssembly.instantiateStreaming
if (!streaming) return
WebAssembly.instantiateStreaming = function (...args) {
return streaming.apply(WebAssembly, args).then(keepMemory)
}
}
function wrapElements() {
const createElement = Document.prototype.createElement
Document.prototype.createElement = function (tag, ...rest) {
const element = createElement.call(this, tag, ...rest)
const name = String(tag).toLowerCase()
if (name === 'canvas') track(element, 'canvas')
else if (name === 'img') track(element, 'image')
return element
}
const NativeImage = window.Image
window.Image = function Image(...args) {
return track(new NativeImage(...args), 'image')
}
window.Image.prototype = NativeImage.prototype
}
function wrapBitmaps() {
const create = window.createImageBitmap
if (!create) return
window.createImageBitmap = function (...args) {
return create.apply(window, args).then((b) => track(b, 'bitmap'))
}
}
function wrapBlobs() {
const NativeBlob = window.Blob
window.Blob = class Blob extends NativeBlob {
constructor(parts, options) {
super(parts, options)
keepSvg(parts, options)
track(this, options?.type === 'application/pdf' ? 'pdfBlob' : 'blob')
}
}
const create = URL.createObjectURL
URL.createObjectURL = function (object) {
urls.created += 1
return create.call(URL, object)
}
const revoke = URL.revokeObjectURL
URL.revokeObjectURL = function (url) {
urls.revoked += 1
return revoke.call(URL, url)
}
}
wrapInstantiation()
wrapElements()
wrapBitmaps()
wrapBlobs()
window.__memBench = {
svgSamples,
read: () => {
const alive = memories.map((ref) => ref.deref()).filter(Boolean)
const heap = performance.memory
return {
linearBytes: alive.reduce((s, m) => s + m.buffer.byteLength, 0),
instances: alive.length,
instancesEver: memories.length,
created: { ...created },
collected: { ...collected },
urls: { ...urls },
jsHeap: heap
? { used: heap.usedJSHeapSize, total: heap.totalJSHeapSize }
: null,
}
},
}
}
/** The page's counters (structured clone). */
export const readMemoryProbe = () => window.__memBench.read()
// Heap snapshot node names worth a census: V8 names DOM wrappers by class
// (detached ones with a `Detached ` prefix) and a wasm memory's bytes sit in
// its backing store node. Exact names, on object / native / hidden nodes
// only: code and closure nodes carry source text and function names.
const CENSUS = new Set([
'HTMLCanvasElement',
'Detached HTMLCanvasElement',
'OffscreenCanvas',
'CanvasRenderingContext2D',
'HTMLImageElement',
'Detached HTMLImageElement',
'ImageBitmap',
'ImageData',
'Blob',
'ArrayBuffer',
'Uint8Array',
'WebAssembly.Memory',
'system / JSArrayBufferData',
])
const CENSUS_TYPES = new Set(['object', 'native', 'hidden'])
function censusOf(snapshot) {
const { node_fields: fields, node_types: types } = snapshot.snapshot.meta
const typeIx = fields.indexOf('type')
const nameIx = fields.indexOf('name')
const sizeIx = fields.indexOf('self_size')
const stride = fields.length
const typeNames = types[typeIx]
const { nodes, strings } = snapshot
const census = {}
for (let i = 0; i < nodes.length; i += stride) {
const name = strings[nodes[i + nameIx]]
if (!CENSUS.has(name)) continue
const type = typeNames[nodes[i + typeIx]]
if (!CENSUS_TYPES.has(type)) continue
const key = `${name} (${type})`
const entry = (census[key] ??= { count: 0, selfBytes: 0 })
entry.count += 1
entry.selfBytes += nodes[i + sizeIx]
}
return { totalNodes: nodes.length / stride, census }
}
/** Chromium: a heap snapshot through CDP, reduced to the census above. */
export async function heapCensus(cdp) {
const chunks = []
const onChunk = (event) => chunks.push(event.chunk)
cdp.on('HeapProfiler.addHeapSnapshotChunk', onChunk)
try {
await cdp.send('HeapProfiler.takeHeapSnapshot', {
reportProgress: false,
treatGlobalObjectsAsRoots: true,
captureNumericValue: false,
})
} finally {
cdp.off('HeapProfiler.addHeapSnapshotChunk', onChunk)
}
const text = chunks.join('')
return { snapshotBytes: text.length, ...censusOf(JSON.parse(text)) }
}
const METRICS = [
'Documents',
'Nodes',
'JSEventListeners',
'JSHeapUsedSize',
'JSHeapTotalSize',
]
/** Chromium: the renderer's DOM and heap counters (`Performance.getMetrics`). */
export async function domMetrics(cdp) {
const { metrics } = await cdp.send('Performance.getMetrics')
const picked = {}
for (const { name, value } of metrics) {
if (METRICS.includes(name)) picked[name] = value
}
return picked
}
/**
* The raster control: the rasteriser's own steps (browserRasterizer.ts:
* size stamped on the root, an SVG Blob URL, a sync-decoded Image, a white
* canvas, toBlob, the bytes read) on the two view drawings the init export
* drew, at the sizes it drew, `count` times; the bytes are dropped (no core
* call). Serialised into the page: self-contained.
*/
export async function rasterControl({ sizes }) {
const samples = window.__memBench.svgSamples
if (samples.length === 0) throw new Error('no view drawing captured')
const SVG_NS = 'http://www.w3.org/2000/svg'
for (let i = 0; i < sizes.length; i += 1) {
const { width, height } = sizes[i]
const root = new DOMParser().parseFromString(
samples[i % samples.length],
'image/svg+xml',
).documentElement
if (root.namespaceURI !== SVG_NS) root.setAttribute('xmlns', SVG_NS)
root.setAttribute('width', String(width))
root.setAttribute('height', String(height))
const svg = new XMLSerializer().serializeToString(root)
const url = URL.createObjectURL(
new Blob([svg], { type: 'image/svg+xml;charset=utf-8' }),
)
const img = new Image()
img.decoding = 'sync'
img.crossOrigin = 'anonymous'
await new Promise((resolve, reject) => {
img.onload = resolve
img.onerror = reject
img.src = url
}).finally(() => URL.revokeObjectURL(url))
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, width, height)
ctx.drawImage(img, 0, 0, width, height)
const blob = await new Promise((r) => canvas.toBlob(r, 'image/png'))
await blob.arrayBuffer()
}
return sizes.length
}