Skip to content

πŸŽ₯ Make videos programmatically with React

docs: Optimize twoslash pre-warming for cold cache (#8296)

Jonny Burger9117c7bb1632
diff --git a/packages/docs/prewarm-twoslash.ts b/packages/docs/prewarm-twoslash.ts
index 1dd9e66ed3..788263f01a 100644
--- a/packages/docs/prewarm-twoslash.ts
+++ b/packages/docs/prewarm-twoslash.ts
@@ -1,28 +1,55 @@
+import {Glob} from 'bun';
+import type {ChildProcessWithoutNullStreams} from 'child_process';
import {spawn} from 'child_process';
import {createHash} from 'crypto';
-import {
- existsSync,
- mkdirSync,
- readdirSync,
- readFileSync,
- unlinkSync,
- writeFileSync,
-} from 'fs';
+import {existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync} from 'fs';
import {createRequire} from 'module';
-import {availableParallelism, cpus} from 'os';
+import {availableParallelism, cpus, totalmem} from 'os';
import {join, resolve} from 'path';
-import {Glob} from 'bun';
+import {createInterface} from 'readline';
const DOCS_ROOT = resolve(import.meta.dirname);
const CACHE_ROOT = join(DOCS_ROOT, 'node_modules', '.cache', 'twoslash');
const WORKER_PATH = join(DOCS_ROOT, 'twoslash-worker.ts');
+
+const GIB = 1024 * 1024 * 1024;
const cpuCount =
typeof availableParallelism === 'function'
? availableParallelism()
: cpus().length;
-const NUM_WORKERS = process.env.VERCEL
+const cpuCap = process.env.VERCEL
? Math.max(1, cpuCount - 1)
: Math.max(1, cpuCount - 2);
+// Each worker holds a TypeScript language service that can grow to >1GB.
+// Cap the worker count so the combined RSS leaves room for the OS and
+// other processes on low-memory machines.
+const memCap = Math.max(1, Math.floor((totalmem() - 4 * GIB) / (1.25 * GIB)));
+const NUM_WORKERS = Math.min(cpuCap, memCap);
+
+// Per-worker RSS threshold after which a worker is replaced with a fresh
+// process. Derived from a global budget of half the machine's memory so the
+// combined RSS of all workers stays bounded even on long runs.
+const MEM_BUDGET = Math.max(2 * GIB, totalmem() / 2);
+const RECYCLE_LIMIT_BYTES = Math.round(
+ Math.min(1.5 * GIB, Math.max(0.75 * GIB, MEM_BUDGET / NUM_WORKERS)),
+);
+
+// Blocks per work unit handed to a worker at a time. Small enough for
+// fine-grained work stealing, large enough to amortize dispatch overhead.
+const MAX_UNIT_SIZE = 24;
+
+// A worker is killed if it makes no progress for this long. Unfinished
+// items are requeued on a fresh worker.
+const STALL_TIMEOUT_MS = process.env.TWOSLASH_STALL_TIMEOUT_MS
+ ? parseInt(process.env.TWOSLASH_STALL_TIMEOUT_MS, 10)
+ : 3 * 60 * 1000;
+
+// How often an item may be requeued after its worker died before giving up.
+const MAX_ATTEMPTS = 2;
+
+// Exit code by which a worker asks to be replaced (memory recycling).
+// Keep in sync with twoslash-worker.ts.
+const RECYCLE_EXIT_CODE = 42;
const pluginDir = join(DOCS_ROOT, '..', 'docusaurus-plugin');
const pluginRequire = createRequire(join(pluginDir, 'package.json'));
@@ -35,7 +62,11 @@ interface TwoslashBlock {
code: string;
lang: string;
cachePath: string;
- sourceFiles: string[];
+}
+
+interface WorkUnit {
+ key: string;
+ items: TwoslashBlock[];
}
function computeCachePath(code: string): string {
@@ -93,6 +124,29 @@ function replaceIncludes(map: Map<string, string>, code: string): string {
return newCode;
}
+// Remove up to `width` leading spaces from every line, the way CommonMark
+// dedents fenced code blocks that are indented (e.g. inside list items).
+// This must produce the same string as the `value` of the mdast code node,
+// otherwise the cache path computed here will not match the one computed
+// during the Docusaurus build.
+function dedent(content: string, width: number): string {
+ if (width === 0) {
+ return content;
+ }
+
+ return content
+ .split('\n')
+ .map((line) => {
+ let strip = 0;
+ while (strip < width && line[strip] === ' ') {
+ strip++;
+ }
+
+ return line.slice(strip);
+ })
+ .join('\n');
+}
+
function extractTwoslashBlocks(
content: string,
filePath: string,
@@ -102,13 +156,16 @@ function extractTwoslashBlocks(
const blocks: TwoslashBlock[] = [];
const includes = new Map<string, string>();
- const codeBlockRegex = /^```(\S*)(.*?)\n([\s\S]*?)^```$/gm;
+ // Also matches blocks indented inside list items β€” `\1` anchors the
+ // closing fence to the same indentation as the opening fence.
+ const codeBlockRegex = /^([ \t]*)```(\S*)([^\n]*)\n([\s\S]*?)^\1```[ \t]*$/gm;
let match;
while ((match = codeBlockRegex.exec(content)) !== null) {
- const lang = match[1];
- const meta = match[2].trim();
- const code = match[3].replace(/\n$/, '');
+ const indent = match[1];
+ const lang = match[2];
+ const meta = match[3].trim();
+ const code = dedent(match[4], indent.length).replace(/\n$/, '');
if (lang === 'twoslash') {
const includeMatch = meta.match(/include\s+(\S+)/);
@@ -138,96 +195,71 @@ function extractTwoslashBlocks(
continue;
}
- blocks.push({code: importedCode, lang, cachePath, sourceFiles: []});
+ blocks.push({code: importedCode, lang, cachePath});
}
return blocks;
}
-interface TimingEntry {
- cachePath: string;
- ms: number;
- error?: string;
-}
+// Snippets that import the same packages reuse the worker's TypeScript
+// language service state. Grouping by import set avoids every worker
+// having to load the type graph of every package (the dominant cost of a
+// cold run, e.g. the AWS SDK types pulled in by @remotion/lambda).
+const importRegex = /(?:from\s+|import\s+|require\()['"]([^'"]+)['"]/g;
+
+function importSetKey(code: string): string {
+ const packages = new Set<string>();
+ for (const match of code.matchAll(importRegex)) {
+ const spec = match[1];
+ if (spec.startsWith('.') || spec.startsWith('/')) {
+ continue;
+ }
-interface WorkerResult {
- completed: number;
- errors: number;
- timings: TimingEntry[];
-}
+ const parts = spec.split('/');
+ packages.add(spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]);
+ }
-const WORKER_TIMEOUT_MS = 8 * 60 * 1000; // 8 minutes per worker
+ return [...packages].sort().join(',');
+}
-function runWorker(
- workItems: TwoslashBlock[],
- workerId: number,
-): Promise<WorkerResult> {
- return new Promise((resolvePromise, reject) => {
- const tmpFile = join(DOCS_ROOT, `.twoslash-work-${workerId}.json`);
- writeFileSync(tmpFile, JSON.stringify(workItems));
+function buildWorkUnits(blocks: TwoslashBlock[]): WorkUnit[] {
+ const groups = new Map<string, TwoslashBlock[]>();
+ for (const block of blocks) {
+ const key = importSetKey(block.code);
+ if (!groups.has(key)) {
+ groups.set(key, []);
+ }
- const child = spawn('bun', ['run', WORKER_PATH, tmpFile], {
- cwd: DOCS_ROOT,
- stdio: ['ignore', 'pipe', 'pipe'],
- });
+ groups.get(key)!.push(block);
+ }
- let lastReport: WorkerResult = {completed: 0, errors: 0, timings: []};
- let settled = false;
-
- const timeout = setTimeout(() => {
- if (!settled) {
- settled = true;
- console.error(
- `Worker ${workerId} timed out after ${WORKER_TIMEOUT_MS / 1000}s, killing...`,
- );
- child.kill('SIGKILL');
- try {
- unlinkSync(tmpFile);
- } catch {}
- resolvePromise(lastReport);
- }
- }, WORKER_TIMEOUT_MS);
-
- child.stdout.on('data', (data: Buffer) => {
- const lines = data.toString().trim().split('\n');
- for (const line of lines) {
- try {
- lastReport = JSON.parse(line);
- } catch {
- // ignore non-JSON output
- }
- }
- });
+ const units: WorkUnit[] = [];
+ for (const [key, items] of groups) {
+ for (let i = 0; i < items.length; i += MAX_UNIT_SIZE) {
+ units.push({key, items: items.slice(i, i + MAX_UNIT_SIZE)});
+ }
+ }
- child.stderr.on('data', (data: Buffer) => {
- process.stderr.write(`[worker ${workerId}] ${data}`);
- });
+ // Largest first so long-running groups start as early as possible
+ units.sort((a, b) => b.items.length - a.items.length);
+ return units;
+}
- child.on('close', (code) => {
- clearTimeout(timeout);
- if (!settled) {
- settled = true;
- if (code !== 0 && code !== null) {
- console.error(`Worker ${workerId} exited with code ${code}`);
- }
- try {
- unlinkSync(tmpFile);
- } catch {}
- resolvePromise(lastReport);
- }
- });
+interface TimingEntry {
+ cachePath: string;
+ ms: number;
+ error?: string;
+}
- child.on('error', (err) => {
- clearTimeout(timeout);
- if (!settled) {
- settled = true;
- try {
- unlinkSync(tmpFile);
- } catch {}
- reject(err);
- }
- });
- });
+interface WorkerHandle {
+ id: number;
+ child: ChildProcessWithoutNullStreams;
+ pendingItems: Map<string, TwoslashBlock>;
+ currentKey: string | null;
+ lastKey: string | null;
+ loadedPackages: Set<string>;
+ stallTimer: ReturnType<typeof setTimeout> | null;
+ exiting: boolean;
}
async function main() {
@@ -280,7 +312,6 @@ async function main() {
const uniqueBlocks = new Map<string, TwoslashBlock>();
for (const block of allBlocks) {
if (!uniqueBlocks.has(block.cachePath)) {
- block.sourceFiles = cachePathToFiles.get(block.cachePath) || [];
uniqueBlocks.set(block.cachePath, block);
}
}
@@ -293,52 +324,355 @@ async function main() {
return;
}
- console.log(
- `${uncachedBlocks.length} twoslash blocks to type-check (${allFiles.length} files scanned)`,
- );
-
if (!existsSync(CACHE_ROOT)) {
mkdirSync(CACHE_ROOT, {recursive: true});
}
- const numWorkers = Math.min(NUM_WORKERS, uncachedBlocks.length);
- console.log(`Launching ${numWorkers} workers...`);
+ const unitQueue = buildWorkUnits(uncachedBlocks);
+ const numWorkers = Math.min(NUM_WORKERS, unitQueue.length);
- const chunks: TwoslashBlock[][] = Array.from({length: numWorkers}, () => []);
- uncachedBlocks.forEach((block, i) => {
- chunks[i % numWorkers].push(block);
+ console.log(
+ `${uncachedBlocks.length} twoslash blocks to type-check (${allFiles.length} files scanned)`,
+ );
+ console.log(
+ `Launching ${numWorkers} workers for ${unitQueue.length} work units...`,
+ );
+
+ const timings = new Map<string, TimingEntry>();
+ const attempts = new Map<string, number>();
+ let completedCount = 0;
+ let errorCount = 0;
+ let respawnBudget = numWorkers * 3;
+ const workers = new Set<WorkerHandle>();
+ let nextWorkerId = 0;
+ let finishing = false;
+
+ let resolveDone: () => void;
+ const done = new Promise<void>((r) => {
+ resolveDone = r;
});
- const workerPromises = chunks.map((chunk, i) => runWorker(chunk, i));
+ const remainingItems = () =>
+ uncachedBlocks.length - completedCount - errorCount;
+
+ const recordResult = (entry: TimingEntry) => {
+ timings.set(entry.cachePath, entry);
+ if (entry.error) {
+ errorCount++;
+ } else {
+ completedCount++;
+ }
+ };
+
+ const sendMessage = (
+ worker: WorkerHandle,
+ message: Record<string, unknown>,
+ ) => {
+ try {
+ worker.child.stdin.write(JSON.stringify(message) + '\n');
+ } catch {
+ // Worker died β€” its exit handler requeues the work
+ }
+ };
+
+ const clearStallTimer = (worker: WorkerHandle) => {
+ if (worker.stallTimer) {
+ clearTimeout(worker.stallTimer);
+ worker.stallTimer = null;
+ }
+ };
+
+ const resetStallTimer = (worker: WorkerHandle) => {
+ clearStallTimer(worker);
+ worker.stallTimer = setTimeout(() => {
+ console.error(
+ `Worker ${worker.id} made no progress for ${Math.round(STALL_TIMEOUT_MS / 1000)}s, killing...`,
+ );
+ worker.child.kill('SIGKILL');
+ }, STALL_TIMEOUT_MS);
+ };
+
+ // Pick the queued unit whose type graphs the worker has already loaded
+ // where possible β€” loading a new package graph costs far more than the
+ // type-checking itself, and accumulating graphs grows the worker's RSS.
+ const takeUnit = (worker: WorkerHandle): WorkUnit | null => {
+ if (unitQueue.length === 0) {
+ return null;
+ }
+
+ let bestIndex = 0;
+ if (worker.loadedPackages.size > 0) {
+ let bestScore = -Infinity;
+ for (let i = 0; i < unitQueue.length; i++) {
+ const unit = unitQueue[i];
+ if (unit.key === worker.lastKey) {
+ bestIndex = i;
+ break;
+ }
+
+ const packages = unit.key === '' ? [] : unit.key.split(',');
+ let overlap = 0;
+ for (const pkg of packages) {
+ if (worker.loadedPackages.has(pkg)) {
+ overlap++;
+ }
+ }
+
+ const score = overlap * 2 - (packages.length - overlap);
+ if (score > bestScore) {
+ bestScore = score;
+ bestIndex = i;
+ }
+ }
+ }
+
+ return unitQueue.splice(bestIndex, 1)[0];
+ };
+
+ const maybeFinish = () => {
+ if (finishing) {
+ return;
+ }
+
+ if (remainingItems() > 0) {
+ return;
+ }
+
+ finishing = true;
+ for (const worker of workers) {
+ worker.exiting = true;
+ clearStallTimer(worker);
+ sendMessage(worker, {type: 'exit'});
+ }
+
+ // Give workers a moment to exit cleanly, then force-kill stragglers
+ setTimeout(() => {
+ for (const worker of workers) {
+ worker.child.kill('SIGKILL');
+ }
+
+ resolveDone();
+ }, 5000).unref?.();
+
+ const checkAllClosed = setInterval(() => {
+ if (workers.size === 0) {
+ clearInterval(checkAllClosed);
+ resolveDone();
+ }
+ }, 100);
+ };
+
+ const assignNextUnit = (worker: WorkerHandle) => {
+ const unit = takeUnit(worker);
+ if (!unit) {
+ worker.exiting = true;
+ clearStallTimer(worker);
+ sendMessage(worker, {type: 'exit'});
+ maybeFinish();
+ return;
+ }
+
+ worker.currentKey = unit.key;
+ worker.lastKey = unit.key;
+ for (const pkg of unit.key.split(',')) {
+ if (pkg) {
+ worker.loadedPackages.add(pkg);
+ }
+ }
+
+ worker.pendingItems = new Map(
+ unit.items.map((item) => [item.cachePath, item]),
+ );
+ resetStallTimer(worker);
+ sendMessage(worker, {type: 'unit', items: unit.items});
+ };
+
+ const handleWorkerExit = (worker: WorkerHandle, code: number | null) => {
+ clearStallTimer(worker);
+ workers.delete(worker);
+
+ const died = !worker.exiting && code !== RECYCLE_EXIT_CODE;
+ const unfinished = [...worker.pendingItems.values()];
+ worker.pendingItems = new Map();
+
+ if (unfinished.length > 0) {
+ const requeue: TwoslashBlock[] = [];
+ for (const item of unfinished) {
+ // Items that were written before the worker died are done
+ if (existsSync(item.cachePath)) {
+ recordResult({cachePath: item.cachePath, ms: 0});
+ continue;
+ }
+
+ const attempt = (attempts.get(item.cachePath) ?? 0) + 1;
+ attempts.set(item.cachePath, attempt);
+ if (attempt >= MAX_ATTEMPTS) {
+ recordResult({
+ cachePath: item.cachePath,
+ ms: 0,
+ error: `Worker died ${attempt} times while processing this snippet`,
+ });
+ } else {
+ requeue.push(item);
+ }
+ }
+
+ if (requeue.length > 0) {
+ unitQueue.unshift({key: worker.currentKey ?? '', items: requeue});
+ }
+ }
+
+ if (died) {
+ respawnBudget--;
+ console.error(
+ `Worker ${worker.id} died unexpectedly (exit code ${code ?? 'signal'}), requeueing its work`,
+ );
+
+ if (respawnBudget <= 0) {
+ console.error('Too many worker crashes, giving up on remaining work');
+ for (const unit of unitQueue.splice(0)) {
+ for (const item of unit.items) {
+ recordResult({
+ cachePath: item.cachePath,
+ ms: 0,
+ error: 'Skipped after too many worker crashes',
+ });
+ }
+ }
+
+ maybeFinish();
+ return;
+ }
+ }
+
+ if (finishing) {
+ maybeFinish();
+ return;
+ }
+
+ const workScheduled =
+ unitQueue.length > 0 || [...workers].some((w) => w.pendingItems.size > 0);
+
+ if (unitQueue.length > 0 && workers.size < numWorkers) {
+ spawnWorker();
+ } else if (!workScheduled) {
+ maybeFinish();
+ }
+ };
+
+ const spawnWorker = () => {
+ const worker: WorkerHandle = {
+ id: nextWorkerId++,
+ child: spawn('bun', ['run', WORKER_PATH], {
+ cwd: DOCS_ROOT,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env: {
+ ...process.env,
+ TWOSLASH_RECYCLE_LIMIT_BYTES: String(RECYCLE_LIMIT_BYTES),
+ },
+ }),
+ pendingItems: new Map(),
+ currentKey: null,
+ lastKey: null,
+ loadedPackages: new Set(),
+ stallTimer: null,
+ exiting: false,
+ };
+ workers.add(worker);
+ resetStallTimer(worker);
+
+ // Don't crash on EPIPE if the worker dies while we write to it
+ worker.child.stdin.on('error', () => undefined);
+
+ const rl = createInterface({input: worker.child.stdout});
+ rl.on('line', (line: string) => {
+ let message: {
+ type: string;
+ cachePath?: string;
+ ms?: number;
+ error?: string;
+ recycling?: boolean;
+ rss?: number;
+ };
+ try {
+ message = JSON.parse(line);
+ } catch {
+ return;
+ }
+
+ if (message.type === 'ready') {
+ assignNextUnit(worker);
+ return;
+ }
+
+ if (message.type === 'item' && message.cachePath) {
+ worker.pendingItems.delete(message.cachePath);
+ recordResult({
+ cachePath: message.cachePath,
+ ms: message.ms ?? 0,
+ error: message.error,
+ });
+ resetStallTimer(worker);
+ return;
+ }
+
+ if (message.type === 'unit-done') {
+ worker.currentKey = null;
+ if (message.recycling) {
+ // The worker exits after this message; its exit handler
+ // spawns a replacement that picks up the remaining units.
+ console.log(
+ ` Worker ${worker.id} recycled at ${Math.round((message.rss ?? 0) / 1024 / 1024)} MB RSS`,
+ );
+ worker.exiting = true;
+ clearStallTimer(worker);
+ return;
+ }
+
+ assignNextUnit(worker);
+ }
+ });
+
+ worker.child.stderr.on('data', (data: Buffer) => {
+ process.stderr.write(`[worker ${worker.id}] ${data}`);
+ });
+
+ worker.child.on('close', (code) => {
+ handleWorkerExit(worker, code);
+ });
+
+ worker.child.on('error', () => {
+ handleWorkerExit(worker, 1);
+ });
+ };
+
+ for (let i = 0; i < numWorkers; i++) {
+ spawnWorker();
+ }
const progressInterval = setInterval(() => {
- const cached = existsSync(CACHE_ROOT) ? readdirSync(CACHE_ROOT).length : 0;
const elapsed = ((performance.now() - startTime) / 1000).toFixed(0);
- console.log(` ${elapsed}s elapsed, ~${cached} cached`);
+ console.log(
+ ` ${elapsed}s elapsed, ${completedCount}/${uncachedBlocks.length} done, ${unitQueue.length} units queued, ${workers.size} workers`,
+ );
}, 15000);
- const results = await Promise.all(workerPromises);
+ await done;
clearInterval(progressInterval);
- console.log('Workers completed');
- const totalCompleted = results.reduce((s, r) => s + r.completed, 0);
- const totalErrors = results.reduce((s, r) => s + r.errors, 0);
const totalTime = ((performance.now() - startTime) / 1000).toFixed(1);
- // Collect all timings and sort by duration (slowest first)
- const allTimings: (TimingEntry & {sourceFiles: string[]})[] = [];
- for (const result of results) {
- for (const t of result.timings) {
- const files = cachePathToFiles.get(t.cachePath) || [];
- allTimings.push({...t, sourceFiles: files});
- }
- }
-
- allTimings.sort((a, b) => b.ms - a.ms);
+ const allTimings = [...timings.values()]
+ .map((t) => ({
+ ...t,
+ sourceFiles: cachePathToFiles.get(t.cachePath) ?? [],
+ }))
+ .sort((a, b) => b.ms - a.ms);
console.log(
- `\nTwoslash pre-warm: ${totalCompleted} blocks in ${totalTime}s using ${numWorkers} workers (${totalErrors} errors)`,
+ `\nTwoslash pre-warm: ${completedCount} blocks in ${totalTime}s using ${numWorkers} workers (${errorCount} errors)`,
);
+
const errorTimings = allTimings.filter((t) => t.error);
if (errorTimings.length > 0) {
console.log(`\nErrors:`);
@@ -355,8 +689,8 @@ async function main() {
console.log(` ${t.ms}ms - ${files}${status}`);
}
- if (totalErrors > 0) {
- console.error(`\n${totalErrors} twoslash errors β€” failing build`);
+ if (errorCount > 0) {
+ console.error(`\n${errorCount} twoslash errors β€” failing build`);
process.exit(1);
}
diff --git a/packages/docs/twoslash-worker.ts b/packages/docs/twoslash-worker.ts
index 1ac1c7b7b0..d31f54686d 100644
--- a/packages/docs/twoslash-worker.ts
+++ b/packages/docs/twoslash-worker.ts
@@ -1,6 +1,7 @@
-import {existsSync, mkdirSync, readFileSync, writeFileSync} from 'fs';
-import {dirname} from 'path';
import {rendererClassic, transformerTwoslash} from '@shikijs/twoslash';
+import {existsSync, mkdirSync, writeFileSync} from 'fs';
+import {dirname} from 'path';
+import {createInterface} from 'readline';
import {createHighlighter} from 'shiki';
import {createTwoslasher} from 'twoslash';
@@ -10,11 +11,21 @@ interface WorkItem {
cachePath: string;
}
-// Read work items from the file passed as argument
-const workFile = process.argv[2];
-const items: WorkItem[] = JSON.parse(readFileSync(workFile, 'utf8'));
+type InboundMessage = {type: 'unit'; items: WorkItem[]} | {type: 'exit'};
+
+// Exit code by which this worker asks to be replaced (memory recycling).
+// Keep in sync with prewarm-twoslash.ts.
+const RECYCLE_EXIT_CODE = 42;
+
+// The TypeScript language service grows as snippets with new imports are
+// type-checked. Recycle the process once it gets too large. The dispatcher
+// derives the limit from the machine's total memory.
+const MEMORY_RECYCLE_LIMIT_BYTES =
+ Number(process.env.TWOSLASH_RECYCLE_LIMIT_BYTES) || 1.5 * 1024 * 1024 * 1024;
-// Create Language Service ONCE per worker (5-20x faster for batch)
+const LANGS = ['tsx', 'ts', 'typescript', 'jsx', 'javascript', 'json'];
+
+// Create Language Service ONCE per worker β€” reused across all units
const twoslasher = createTwoslasher({
compilerOptions: {
types: ['node'],
@@ -24,26 +35,22 @@ const twoslasher = createTwoslasher({
},
});
-// Collect unique languages from work items
-const uniqueLangs = [...new Set(items.map((item) => item.lang))];
-
-// Create highlighter ONCE with all needed languages
-const highlighter = await createHighlighter({
- themes: ['github-dark'],
- langs: uniqueLangs,
-});
-
const transformer = transformerTwoslash({
twoslasher,
renderer: rendererClassic(),
explicitTrigger: false,
});
-let completed = 0;
-let errors = 0;
-const timings: Array<{cachePath: string; ms: number; error?: string}> = [];
+const send = (message: Record<string, unknown>) => {
+ process.stdout.write(JSON.stringify(message) + '\n');
+};
+
+const highlighter = await createHighlighter({
+ themes: ['github-dark'],
+ langs: LANGS,
+});
-for (const item of items) {
+const processItem = (item: WorkItem) => {
const start = performance.now();
try {
const html = highlighter.codeToHtml(item.code, {
@@ -55,38 +62,54 @@ for (const item of items) {
const dir = dirname(item.cachePath);
if (!existsSync(dir)) mkdirSync(dir, {recursive: true});
writeFileSync(item.cachePath, html, 'utf8');
- completed++;
- timings.push({
+ send({
+ type: 'item',
cachePath: item.cachePath,
ms: Math.round(performance.now() - start),
});
} catch (error) {
- errors++;
- timings.push({
+ send({
+ type: 'item',
cachePath: item.cachePath,
ms: Math.round(performance.now() - start),
- error: (error as Error).message.slice(0, 200),
+ error: (error as Error).message.slice(0, 300),
});
}
+};
+
+send({type: 'ready'});
- // Report progress every 10 items
- if ((completed + errors) % 10 === 0) {
- process.stdout.write(
- JSON.stringify({completed, errors, total: items.length, timings}) + '\n',
- );
+const rl = createInterface({input: process.stdin});
+
+rl.on('line', (line: string) => {
+ let message: InboundMessage;
+ try {
+ message = JSON.parse(line);
+ } catch {
+ return;
+ }
+
+ if (message.type === 'exit') {
+ // The TS language service keeps the process alive β€” exit explicitly
+ process.exit(0);
}
-}
-// Final report
-process.stdout.write(
- JSON.stringify({
- completed,
- errors,
- total: items.length,
- done: true,
- timings,
- }) + '\n',
-);
-
-// Force exit β€” createTwoslasher holds a TS language service that keeps the process alive
-process.exit(0);
+ if (message.type === 'unit') {
+ for (const item of message.items) {
+ processItem(item);
+ }
+
+ const rss = process.memoryUsage.rss();
+ const recycling = rss > MEMORY_RECYCLE_LIMIT_BYTES;
+ send({type: 'unit-done', rss, recycling});
+
+ if (recycling) {
+ // Ask the dispatcher to replace this worker with a fresh one
+ process.exit(RECYCLE_EXIT_CODE);
+ }
+ }
+});
+
+rl.on('close', () => {
+ process.exit(0);
+});