Skip to content

πŸŽ₯ Make videos programmatically with React

Docs: Speed up startup with parallel Twoslash prewarming (#9157)

Igor Samokhovets8a827d3b7ecf
diff --git a/packages/docs/package.json b/packages/docs/package.json
index f5571f9859..8b85c3da9d 100644
--- a/packages/docs/package.json
+++ b/packages/docs/package.json
@@ -9,7 +9,7 @@
"formatting": "oxfmt src --check",
"format": "oxfmt src",
"docusaurus": "docusaurus",
- "start": "bun copy-raw-docs.ts && bun fetch-prompt-submissions.ts && bun update-prompt.ts && cd .. && bun run build && cd docs && docusaurus start --host 0.0.0.0",
+ "start": "bun copy-raw-docs.ts && bun fetch-prompt-submissions.ts && bun update-prompt.ts && cd .. && bun run build && cd docs && bun prewarm-twoslash.ts && docusaurus start --host 0.0.0.0",
"build-docs": "bun build-docs.ts",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
diff --git a/packages/docs/prewarm-twoslash.ts b/packages/docs/prewarm-twoslash.ts
index ba11301a82..767b8897fa 100644
--- a/packages/docs/prewarm-twoslash.ts
+++ b/packages/docs/prewarm-twoslash.ts
@@ -1,26 +1,30 @@
-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} from 'fs';
import {createRequire} from 'module';
import {availableParallelism, cpus, totalmem} from 'os';
-import {join, resolve} from 'path';
+import {dirname, join, resolve} from 'path';
import {createInterface} from 'readline';
+import {Glob} from 'bun';
import {expandElementSourceReferences} from './plugins/element-source-utils';
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 WORKER_SOURCE_PATH = join(DOCS_ROOT, 'twoslash-worker.mjs');
+const WORKER_PATH = join(
+ DOCS_ROOT,
+ 'node_modules',
+ '.cache',
+ 'twoslash-worker-bundle.mjs',
+);
const GIB = 1024 * 1024 * 1024;
const cpuCount =
typeof availableParallelism === 'function'
? availableParallelism()
: cpus().length;
-const cpuCap = process.env.VERCEL
- ? Math.max(1, cpuCount - 1)
- : Math.max(1, cpuCount - 2);
+const cpuCap = Math.max(1, cpuCount - 1);
// 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.
@@ -34,9 +38,9 @@ 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);
+// process. Derived from a global budget that leaves 25% of memory for the OS
+// and other processes so combined worker RSS stays bounded on long runs.
+const MEM_BUDGET = Math.max(2 * GIB, totalmem() * 0.75);
const recycleLimitOverride = process.env.TWOSLASH_RECYCLE_LIMIT_BYTES
? parseInt(process.env.TWOSLASH_RECYCLE_LIMIT_BYTES, 10)
: null;
@@ -44,12 +48,13 @@ const RECYCLE_LIMIT_BYTES =
recycleLimitOverride && Number.isFinite(recycleLimitOverride)
? recycleLimitOverride
: Math.round(
- Math.min(1.5 * GIB, Math.max(0.75 * GIB, MEM_BUDGET / NUM_WORKERS)),
+ Math.min(2.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;
+const MAX_UNIT_SOURCE_LENGTH = 16_000;
// A worker is killed if it makes no progress for this long. Unfinished
// items are requeued on a fresh worker.
@@ -61,7 +66,7 @@ const STALL_TIMEOUT_MS = process.env.TWOSLASH_STALL_TIMEOUT_MS
const MAX_ATTEMPTS = 2;
// Exit code by which a worker asks to be replaced (memory recycling).
-// Keep in sync with twoslash-worker.ts.
+// Keep in sync with twoslash-worker.mjs.
const RECYCLE_EXIT_CODE = 42;
const pluginDir = join(DOCS_ROOT, '..', 'docusaurus-plugin');
@@ -248,13 +253,33 @@ function buildWorkUnits(blocks: TwoslashBlock[]): WorkUnit[] {
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)});
+ let currentItems: TwoslashBlock[] = [];
+ let currentSourceLength = 0;
+ for (const item of items) {
+ if (
+ currentItems.length > 0 &&
+ (currentItems.length >= MAX_UNIT_SIZE ||
+ currentSourceLength + item.code.length > MAX_UNIT_SOURCE_LENGTH)
+ ) {
+ units.push({key, items: currentItems});
+ currentItems = [];
+ currentSourceLength = 0;
+ }
+
+ currentItems.push(item);
+ currentSourceLength += item.code.length;
+ }
+
+ if (currentItems.length > 0) {
+ units.push({key, items: currentItems});
}
}
- // Largest first so long-running groups start as early as possible
- units.sort((a, b) => b.items.length - a.items.length);
+ // Put more source-heavy units first so expensive outliers do not become
+ // stragglers after most workers have exhausted the queue.
+ const estimatedCost = (unit: WorkUnit) =>
+ unit.items.reduce((total, item) => total + item.code.length, 0);
+ units.sort((a, b) => estimatedCost(b) - estimatedCost(a));
return units;
}
@@ -293,19 +318,44 @@ async function main() {
const allBlocks: TwoslashBlock[] = [];
const validCachePaths = new Set<string>();
const cachePathToFiles = new Map<string, string[]>();
+ let bundlePromise: Promise<void> | null = null;
+ const startWorkerBundle = () => {
+ if (bundlePromise !== null) {
+ return;
+ }
+
+ bundlePromise = (async () => {
+ const result = await Bun.build({
+ entrypoints: [WORKER_SOURCE_PATH],
+ format: 'esm',
+ target: 'node',
+ });
+ if (!result.success || result.outputs.length !== 1) {
+ throw new Error(
+ `Could not bundle Twoslash worker: ${result.logs.join('\n')}`,
+ );
+ }
+
+ mkdirSync(dirname(WORKER_PATH), {recursive: true});
+ await Bun.write(WORKER_PATH, result.outputs[0]);
+ })();
+ };
+
for (const file of allFiles) {
const content = expandElementSourceReferences({
raw: readFileSync(file, 'utf8'),
sourceFilePath: file,
});
- allBlocks.push(
- ...extractTwoslashBlocks(
- content,
- file,
- validCachePaths,
- cachePathToFiles,
- ),
+ const blocks = extractTwoslashBlocks(
+ content,
+ file,
+ validCachePaths,
+ cachePathToFiles,
);
+ if (blocks.length > 0) {
+ startWorkerBundle();
+ allBlocks.push(...blocks);
+ }
}
// Delete stale cache entries that no longer correspond to any twoslash block
@@ -344,6 +394,8 @@ async function main() {
mkdirSync(CACHE_ROOT, {recursive: true});
}
+ await bundlePromise;
+
const unitQueue = buildWorkUnits(uncachedBlocks);
const numWorkers = Math.min(NUM_WORKERS, unitQueue.length);
@@ -514,10 +566,10 @@ async function main() {
if (unfinished.length > 0) {
const requeue: TwoslashBlock[] = [];
for (const item of unfinished) {
- // Items that were written before the worker died are done
+ // A worker can be killed while writing. Only its batched completion
+ // message proves the final cache file is complete.
if (existsSync(item.cachePath)) {
- recordResult({cachePath: item.cachePath, ms: 0});
- continue;
+ unlinkSync(item.cachePath);
}
const attempt = (attempts.get(item.cachePath) ?? 0) + 1;
@@ -579,7 +631,7 @@ async function main() {
const spawnWorker = () => {
const worker: WorkerHandle = {
id: nextWorkerId++,
- child: spawn('bun', ['run', WORKER_PATH], {
+ child: spawn('node', ['--no-warnings', WORKER_PATH], {
cwd: DOCS_ROOT,
stdio: ['pipe', 'pipe', 'pipe'],
env: {
@@ -604,9 +656,7 @@ async function main() {
rl.on('line', (line: string) => {
let message: {
type: string;
- cachePath?: string;
- ms?: number;
- error?: string;
+ results?: TimingEntry[];
recycling?: boolean;
rss?: number;
};
@@ -621,18 +671,12 @@ async function main() {
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') {
+ for (const result of message.results ?? []) {
+ worker.pendingItems.delete(result.cachePath);
+ recordResult(result);
+ }
+
worker.currentKey = null;
if (message.recycling) {
// The worker exits after this message; its exit handler
diff --git a/packages/docs/twoslash-worker.ts b/packages/docs/twoslash-worker.mjs
similarity index 76%
rename from packages/docs/twoslash-worker.ts
rename to packages/docs/twoslash-worker.mjs
index d31f54686d..c814f2d9cc 100644
--- a/packages/docs/twoslash-worker.ts
+++ b/packages/docs/twoslash-worker.mjs
@@ -1,19 +1,11 @@
-import {rendererClassic, transformerTwoslash} from '@shikijs/twoslash';
import {existsSync, mkdirSync, writeFileSync} from 'fs';
import {dirname} from 'path';
import {createInterface} from 'readline';
+import {rendererClassic, transformerTwoslash} from '@shikijs/twoslash';
import {createHighlighter} from 'shiki';
import {createTwoslasher} from 'twoslash';
-interface WorkItem {
- code: string;
- lang: string;
- cachePath: string;
-}
-
-type InboundMessage = {type: 'unit'; items: WorkItem[]} | {type: 'exit'};
-
-// Exit code by which this worker asks to be replaced (memory recycling).
+// Exit code by which a worker asks to be replaced (memory recycling).
// Keep in sync with prewarm-twoslash.ts.
const RECYCLE_EXIT_CODE = 42;
@@ -23,7 +15,7 @@ const RECYCLE_EXIT_CODE = 42;
const MEMORY_RECYCLE_LIMIT_BYTES =
Number(process.env.TWOSLASH_RECYCLE_LIMIT_BYTES) || 1.5 * 1024 * 1024 * 1024;
-const LANGS = ['tsx', 'ts', 'typescript', 'jsx', 'javascript', 'json'];
+const LANGS = ['tsx', 'ts', 'jsx', 'javascript'];
// Create Language Service ONCE per worker β€” reused across all units
const twoslasher = createTwoslasher({
@@ -32,6 +24,7 @@ const twoslasher = createTwoslasher({
target: 99 /* ESNext */,
module: 99 /* ESNext */,
jsx: 4 /* ReactJSX */,
+ skipLibCheck: true,
},
});
@@ -41,7 +34,7 @@ const transformer = transformerTwoslash({
explicitTrigger: false,
});
-const send = (message: Record<string, unknown>) => {
+const send = (message) => {
process.stdout.write(JSON.stringify(message) + '\n');
};
@@ -50,7 +43,7 @@ const highlighter = await createHighlighter({
langs: LANGS,
});
-const processItem = (item: WorkItem) => {
+const processItem = (item) => {
const start = performance.now();
try {
const html = highlighter.codeToHtml(item.code, {
@@ -62,18 +55,17 @@ const processItem = (item: WorkItem) => {
const dir = dirname(item.cachePath);
if (!existsSync(dir)) mkdirSync(dir, {recursive: true});
writeFileSync(item.cachePath, html, 'utf8');
- send({
- type: 'item',
+ return {
cachePath: item.cachePath,
ms: Math.round(performance.now() - start),
- });
+ };
} catch (error) {
- send({
- type: 'item',
+ return {
cachePath: item.cachePath,
ms: Math.round(performance.now() - start),
- error: (error as Error).message.slice(0, 300),
- });
+ error:
+ error instanceof Error ? error.message.slice(0, 300) : String(error),
+ };
}
};
@@ -81,8 +73,8 @@ send({type: 'ready'});
const rl = createInterface({input: process.stdin});
-rl.on('line', (line: string) => {
- let message: InboundMessage;
+rl.on('line', (line) => {
+ let message;
try {
message = JSON.parse(line);
} catch {
@@ -95,13 +87,10 @@ rl.on('line', (line: string) => {
}
if (message.type === 'unit') {
- for (const item of message.items) {
- processItem(item);
- }
-
+ const results = message.items.map(processItem);
const rss = process.memoryUsage.rss();
const recycling = rss > MEMORY_RECYCLE_LIMIT_BYTES;
- send({type: 'unit-done', rss, recycling});
+ send({type: 'unit-done', results, rss, recycling});
if (recycling) {
// Ask the dispatcher to replace this worker with a fresh one
diff --git a/packages/docusaurus-plugin/src/caching.ts b/packages/docusaurus-plugin/src/caching.ts
index ecc4e9d58a..390ab01f00 100644
--- a/packages/docusaurus-plugin/src/caching.ts
+++ b/packages/docusaurus-plugin/src/caching.ts
@@ -13,6 +13,7 @@ function getTwoslasher() {
target: 99 /* ESNext */,
module: 99 /* ESNext */,
jsx: 4 /* ReactJSX */,
+ skipLibCheck: true,
},
});
}