Skip to content

Commit ba3e6b7

Browse files
authored
perf(fmt): bound concurrent formatting tasks (#640)
1 parent 39db75d commit ba3e6b7

3 files changed

Lines changed: 93 additions & 38 deletions

File tree

‎packages/rstack/src/fmt/runner.ts‎

Lines changed: 51 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -139,10 +139,6 @@ const runFmtFile = async (
139139
shouldWrite: boolean,
140140
formatFile: FormatFile,
141141
): Promise<FmtFileRun> => {
142-
if (isCachedUnsupported(task)) {
143-
return { outcome: 'unsupported' };
144-
}
145-
146142
const { file, key, cache } = task;
147143
try {
148144
const result = await formatFile(file, shouldWrite, cache);
@@ -170,26 +166,44 @@ const runFmtFile = async (
170166
};
171167

172168
/** Starts slower Markdown parsers first while preserving order within both priority groups. */
173-
const runPriorityTasks = async (
174-
tasks: FmtFileRunTask[],
175-
shouldWrite: boolean,
176-
formatFile: FormatFile,
177-
): Promise<FmtFileRun[]> => {
169+
const getPriorityOrder = (tasks: FmtFileRunTask[]): number[] => {
178170
const priority: number[] = [];
179171
const rest: number[] = [];
180172

181173
for (let index = 0; index < tasks.length; index++) {
182174
(isMarkdown(tasks[index].file) ? priority : rest).push(index);
183175
}
184176

185-
const order = priority.concat(rest);
186-
const outcomes = await Promise.all(
187-
order.map((index) => runFmtFile(tasks[index], shouldWrite, formatFile)),
188-
);
177+
return priority.concat(rest);
178+
};
179+
180+
/** Bounds queued work while keeping results in the original file order. */
181+
const runScheduledTasks = async (
182+
tasks: FmtFileRunTask[],
183+
shouldWrite: boolean,
184+
formatFile: FormatFile,
185+
concurrency: number,
186+
): Promise<FmtFileRun[]> => {
187+
const order =
188+
concurrency >= minPriorityWorkers ? getPriorityOrder(tasks) : undefined;
189189
const results = new Array<FmtFileRun>(tasks.length);
190-
for (let index = 0; index < order.length; index++) {
191-
results[order[index]] = outcomes[index];
192-
}
190+
let nextIndex = 0;
191+
192+
const consume = async (): Promise<void> => {
193+
while (nextIndex < tasks.length) {
194+
const index = nextIndex++;
195+
const taskIndex = order?.[index] ?? index;
196+
results[taskIndex] = await runFmtFile(
197+
tasks[taskIndex],
198+
shouldWrite,
199+
formatFile,
200+
);
201+
}
202+
};
203+
204+
await Promise.all(
205+
Array.from({ length: Math.min(concurrency, tasks.length) }, consume),
206+
);
193207
return results;
194208
};
195209

@@ -225,40 +239,40 @@ const runFmtTasks = async (
225239
maxWorkers?: number,
226240
cache?: RunCache,
227241
): Promise<FmtFilesResult> => {
228-
const tasks = files.map((file) => createRunTask(file, cache));
229-
const pendingFileCount = tasks.reduce(
230-
(count, task) => count + (isCachedUnsupported(task) ? 0 : 1),
231-
0,
232-
);
233-
if (pendingFileCount === 0) {
242+
const tasks: FmtFileRunTask[] = [];
243+
for (const file of files) {
244+
const task = createRunTask(file, cache);
245+
if (!isCachedUnsupported(task)) {
246+
tasks.push(task);
247+
}
248+
}
249+
if (tasks.length === 0) {
234250
return { files: [], processedFileCount: 0 };
235251
}
236252

237253
// One pending file cannot benefit from parallelism, so avoid worker startup and IPC overhead.
238-
if (pendingFileCount === 1) {
254+
if (tasks.length === 1) {
239255
const { formatFile } = await import('./worker.ts');
240256
const formatFileOnMainThread: FormatFile = (file, write, fileCache) =>
241257
formatFile({ file, shouldWrite: write, cache: fileCache });
242-
const results = await Promise.all(
243-
tasks.map((task) =>
244-
runFmtFile(task, shouldWrite, formatFileOnMainThread),
245-
),
258+
const result = await runFmtFile(
259+
tasks[0],
260+
shouldWrite,
261+
formatFileOnMainThread,
246262
);
247-
return collectFmtResults(results, cache);
263+
return collectFmtResults([result], cache);
248264
}
249265

250266
const { createWorkerPool } = await import('./workerPool.ts');
251-
const workerPool = await createWorkerPool(pendingFileCount, maxWorkers);
267+
const workerPool = await createWorkerPool(tasks.length, maxWorkers);
252268

253269
try {
254-
const results =
255-
workerPool.workerCount >= minPriorityWorkers
256-
? await runPriorityTasks(tasks, shouldWrite, workerPool.formatFile)
257-
: await Promise.all(
258-
tasks.map((task) =>
259-
runFmtFile(task, shouldWrite, workerPool.formatFile),
260-
),
261-
);
270+
const results = await runScheduledTasks(
271+
tasks,
272+
shouldWrite,
273+
workerPool.formatFile,
274+
workerPool.workerCount,
275+
);
262276
return collectFmtResults(results, cache);
263277
} finally {
264278
await workerPool.terminate();
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { setImmediate } from 'node:timers/promises';
2+
import { expect, rs, test } from 'rstack/test';
3+
import { runFmtFiles } from '../../src/fmt/runner.ts';
4+
import type { FmtFileRequest } from '../../src/fmt/types.ts';
5+
6+
const state = rs.hoisted(() => ({
7+
active: 0,
8+
peak: 0,
9+
completed: [] as string[],
10+
}));
11+
12+
rs.mock('../../src/fmt/workerPool.ts', () => ({
13+
createWorkerPool: (_fileCount: number, workerCount: number) => ({
14+
workerCount,
15+
async formatFile(file: FmtFileRequest) {
16+
state.peak = Math.max(state.peak, ++state.active);
17+
await setImmediate();
18+
state.active--;
19+
state.completed.push(file.path);
20+
return { status: 'unchanged' };
21+
},
22+
terminate: () => Promise.resolve(),
23+
}),
24+
}));
25+
26+
test('bounds in-flight tasks and processes every file', async () => {
27+
const paths = Array.from({ length: 6 }, (_, index) => `${index}.ts`);
28+
29+
await runFmtFiles({
30+
files: paths.map((path) => ({ path, options: {} })),
31+
mode: 'check',
32+
maxWorkers: 2,
33+
});
34+
35+
expect(state.peak).toBe(2);
36+
expect(state.completed.sort()).toEqual(paths);
37+
});

‎packages/rstack/tests/fmt/runnerWorkerPreflight.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ test('does not start the worker pool when every parser result is cached as unsup
7070

7171
test('rechecks a path-only unsupported entry on the main thread', async () => {
7272
await withTempProject(async (rootPath) => {
73+
const { file: ignored } = await createCachedUnsupportedFile(
74+
rootPath,
75+
'ignored.unknown',
76+
);
7377
const { cache, file } = await createCachedUnsupportedFile(
7478
rootPath,
7579
'script',
@@ -78,7 +82,7 @@ test('rechecks a path-only unsupported entry on the main thread', async () => {
7882

7983
await expect(
8084
runFmtFiles({
81-
files: [file],
85+
files: [ignored, file],
8286
mode: 'check',
8387
cache,
8488
}),

0 commit comments

Comments
 (0)