Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ clean:
fmt:
bunx eslint --fix .

.PHONY: install build dev clean fmt
bench: build
@for file in bench/*.js; do echo; bun $$file || exit 1; done

.PHONY: install build dev clean fmt bench
162 changes: 162 additions & 0 deletions bench/navigation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { spawn } from 'node:child_process';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { setTimeout as sleep } from 'node:timers/promises';

const root = fileURLToPath(new URL('..', import.meta.url));
const previewPort = 4180;
const debugPort = 9230;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛑 Logic Error: Both fast and mobile profiles use the same hardcoded debugPort = 9230. Each runProfile spawns its own Chrome process against that port. If the Chrome process from the first profile is still releasing the port during the 300 ms grace sleep, the second Chrome will fail to bind on the same port, causing the waitUntil for 'chrome' to silently poll the previous (or a failed) debug endpoint and either return stale targets or timeout. Consider either passing a unique port per profile or ensuring the port is free before spawning the next Chrome instance.

const base = `http://localhost:${previewPort}`;
const chromeBin = process.env.CHROME ?? 'google-chrome';

const profiles = {
fast : null,
mobile: { cpu: 4, latency: 100, downloadMbps: 10, uploadMbps: 5 },
};

const steps = [
{ name: 'load home' , load : '/' , ready: '.post-item' },
{ name: 'click first post', click: '.post-item a[href$=".html"]', ready: '.markdown-body' },
{ name: 'reload post' , reload: true , ready: '.markdown-body' },
{ name: 'click logo' , click: 'a.logo' , ready: '.post-item' },
{ name: 'click tags' , click: 'a[href="/tags"]' , ready: '.tag-cloud-item' },
{ name: 'click first tag' , click: '.tag-cloud-item' , ready: '.post-item' },
{ name: 'history back' , back : true , ready: '.tag-cloud-item' },
{ name: 'click about' , click: 'a[href="/about"]' , ready: '.markdown-body' },
];

const selectors = [...new Set(steps.map(step => step.ready))];

const probe = `
window.__marks = {};
new MutationObserver(() => {
for (const selector of ${JSON.stringify(selectors)}) {
if (!window.__marks[selector] && document.querySelector(selector)) {
window.__marks[selector] = performance.timeOrigin + performance.now();
}
}
}).observe(document, { childList: true, subtree: true });
`;

const waitUntil = async (check, label, timeout = 30000) => {
const deadline = Date.now() + timeout;

while (Date.now() < deadline) {
const value = await check().catch(() => null);
if (value) {
return value;
}
await sleep(10);
}
throw new Error(`timeout: ${label}`);
};

const connect = async url => {
const ws = new WebSocket(url);
const pending = new Map();
let id = 0;

await new Promise((resolve, reject) => {
ws.onopen = resolve;
ws.onerror = reject;
});

ws.onmessage = ({ data }) => {
const message = JSON.parse(data);
pending.get(message.id)?.(message);
pending.delete(message.id);
};

const send = (method, params = {}) => new Promise((resolve, reject) => {
id += 1;
pending.set(id, message => (message.error ? reject(new Error(message.error.message)) : resolve(message.result)));
ws.send(JSON.stringify({ id, method, params }));
});

const evaluate = async expression => (await send('Runtime.evaluate', { expression, returnByValue: true })).result.value;

return { send, evaluate, close: () => ws.close() };
};

const runProfile = async (name, throttle) => {
const userDir = mkdtempSync(path.join(tmpdir(), 'bench-chrome-'));
const chrome = spawn(chromeBin, [
'--headless=new',
`--remote-debugging-port=${debugPort}`,
`--user-data-dir=${userDir}`,
'--no-first-run',
'--no-default-browser-check',
'about:blank',
], { stdio: 'ignore' });

try {
const target = await waitUntil(async () => {
const targets = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json();
return targets.find(item => item.type === 'page');
}, 'chrome');

const page = await connect(target.webSocketDebuggerUrl);

await page.send('Page.enable');
await page.send('Network.enable');
await page.send('Network.setBlockedURLs', { urls: ['*googletagmanager.com*', '*google-analytics.com*'] });
await page.send('Page.addScriptToEvaluateOnNewDocument', { source: probe });

if (throttle) {
await page.send('Emulation.setCPUThrottlingRate', { rate: throttle.cpu });
await page.send('Network.emulateNetworkConditions', {
offline : false,
latency : throttle.latency,
downloadThroughput: (throttle.downloadMbps * 1024 * 1024) / 8,
uploadThroughput : (throttle.uploadMbps * 1024 * 1024) / 8,
});
}

for (const step of steps) {
const inPage = step.click || step.back;
await page.evaluate(inPage ? 'window.__marks = {}' : 'window.__stale = true').catch(() => null);
const start = Date.now();

if (step.load) {
await page.send('Page.navigate', { url: `${base}${step.load}` });
} else if (step.reload) {
await page.send('Page.reload');
} else if (step.back) {
await page.evaluate('history.back()');
} else {
await page.evaluate(`document.querySelector(${JSON.stringify(step.click)}).click()`);
}

const ready = `!window.__stale && window.__marks[${JSON.stringify(step.ready)}]`;
const end = await waitUntil(() => page.evaluate(ready), step.name);
console.log(`${name.padEnd(7)} ${step.name.padEnd(16)} ${String(Math.round(end - start)).padStart(5)}`);
await sleep(300);
}

page.close();
} finally {
chrome.kill();
await sleep(300);
rmSync(userDir, { recursive: true, force: true });
}
};

const preview = spawn(path.join(root, 'node_modules/.bin/vite'), ['preview', '--port', String(previewPort), '--strictPort'], {
cwd : root,
stdio: 'ignore',
});

try {
await waitUntil(async () => (await fetch(base)).ok, 'vite preview');

console.log('navigation: action -> content visible, vite preview + headless chrome');
console.log(`${'profile'.padEnd(7)} ${'step'.padEnd(16)} ${'ms'.padStart(5)}`);

for (const [name, throttle] of Object.entries(profiles)) {
await runProfile(name, throttle);
}
} finally {
preview.kill();
}
43 changes: 43 additions & 0 deletions bench/render.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { readdirSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { renderMarkdown } from '../src/components/MarkdownRenderer/markdown.js';

const publicDir = fileURLToPath(new URL('../public/', import.meta.url));

const files = [
'about.md',
...readdirSync(`${publicDir}posts`, { recursive: true })
.filter(file => file.endsWith('.md'))
.sort()
.map(file => `posts/${file}`),
];

const results = files.map(file => ({
name : file.split('/').pop().replace(/\.md$/, ''),
source: readFileSync(`${publicDir}${file}`, 'utf8'),
}));

for (const pass of ['cold', 'warm']) {
for (const result of results) {
const start = performance.now();
const post = await renderMarkdown(result.source);

result[pass] = performance.now() - start;
result.kb = JSON.stringify(post).length / 1024;
}
}

const width = Math.max(...results.map(result => result.name.length));
const sum = key => results.reduce((total, result) => total + result[key], 0);
const row = (name, cold, warm, kb) => console.log(
`${name.padEnd(width)} ${String(cold).padStart(7)} ${String(warm).padStart(7)} ${String(kb).padStart(7)}`
);

console.log('render: markdown -> json at build time');
row('file', 'cold ms', 'warm ms', 'json KB');

for (const result of results) {
row(result.name, Math.round(result.cold), Math.round(result.warm), result.kb.toFixed(1));
}

row('total', Math.round(sum('cold')), Math.round(sum('warm')), sum('kb').toFixed(1));
Loading
Loading