/** * #413: what one page costs on workerd. Runs the Worker `vite build` made * (`dist/server/fetch.js`, generated by `@foldkit/vite-plugin`, so no source * entry exists for `Stack.start` to bundle) on the Wrangler the app itself * pins, with its own `wrangler.jsonc`, and reads workerd's main thread CPU * time from `/proc` as `stack.cpu` does. Linux only. Local workerd; nothing * is deployed and no login is used. * * pnpm --filter foldkit-example-foldkit-domains-plus build * node scripts/workerd-cpu.mjs [--runs 20] [--path '/?q='] * * Each request asks a word never asked before (``), so no * kept page serves it. Prints the cold first request, then the median and * the worst of the warm ones, in milliseconds. */ import { ChildProcess } from 'node:child_process' import { subscribe } from 'node:diagnostics_channel' import { readFile } from 'node:fs/promises' import { createRequire } from 'node:module' import { basename, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' const app = fileURLToPath(new URL('../examples/foldkit/domains-plus/', import.meta.url)) const option = (name, fallback) => { const index = process.argv.indexOf(`--${name}`) return index === -1 ? fallback : process.argv[index + 1] } const runs = Number(option('runs', '20')) const path = option('path', '/?q=') if (process.platform !== 'linux') throw new Error('workerd-cpu reads /proc: Linux only.') const wranglerFile = createRequire(join(app, 'package.json')).resolve('wrangler') const { createTestHarness, experimental_readRawConfig } = await import( pathToFileURL(wranglerFile).href ) const { rawConfig } = experimental_readRawConfig({ config: join(app, 'wrangler.jsonc') }) // The harness offers no way to find its workerd but to watch what spawns. const workerds = [] subscribe('child_process', message => { const child = message?.process if (child instanceof ChildProcess) workerds.push(child) }) const running = () => workerds.filter( child => /^workerd$/.test(basename(String(child.spawnfile))) && child.exitCode === null && child.pid !== undefined, ) const pause = new Int32Array(new SharedArrayBuffer(4)) /** Milliseconds workerd's main threads have run, by the scheduler's nanoseconds. */ const spent = async () => { // Linux books a running thread's time at each tick; a millisecond's sleep has it book the rest. Atomics.wait(pause, 0, 0, 1) const times = await Promise.all( running().map(async ({ pid }) => Number((await readFile(`/proc/${pid}/task/${pid}/schedstat`, 'utf8')).split(' ')[0]), ), ) return times.reduce((a, b) => a + b, 0) / 1e6 } const harness = createTestHarness({ root: app, workers: [ { config: { ...rawConfig, main: join(app, rawConfig.main), assets: { directory: join(app, rawConfig.assets.directory) }, }, }, ], }) try { const { url } = await harness.listen() const worker = harness.getWorker() const stamp = Date.now().toString(36) const readings = [] let bytes = 0 for (let n = 0; n <= runs; n++) { const target = new URL(`${path}zephyr${stamp}${n}`, url.origin) const before = await spent() // Straight to the Worker: over HTTP a second workerd would spend time of its own. const response = await worker.fetch(target.href) const body = await response.arrayBuffer() const after = await spent() if (response.status !== 200) throw new Error(`${target} answered ${response.status}`) bytes = body.byteLength readings.push(after - before) } const [cold, ...warm] = readings const sorted = [...warm].sort((a, b) => a - b) console.log( JSON.stringify({ page: `${(bytes / 1024).toFixed(0)} KB`, requests: warm.length, coldMs: +cold.toFixed(1), medianMs: +sorted[Math.floor(sorted.length / 2)].toFixed(1), worstMs: +sorted.at(-1).toFixed(1), warmMs: warm.map(ms => +ms.toFixed(1)), }), ) } finally { await harness.close() }