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
88 changes: 51 additions & 37 deletions packages/rstack/src/fmt/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,6 @@ const runFmtFile = async (
shouldWrite: boolean,
formatFile: FormatFile,
): Promise<FmtFileRun> => {
if (isCachedUnsupported(task)) {
return { outcome: 'unsupported' };
}

const { file, key, cache } = task;
try {
const result = await formatFile(file, shouldWrite, cache);
Expand Down Expand Up @@ -170,26 +166,44 @@ const runFmtFile = async (
};

/** Starts slower Markdown parsers first while preserving order within both priority groups. */
const runPriorityTasks = async (
tasks: FmtFileRunTask[],
shouldWrite: boolean,
formatFile: FormatFile,
): Promise<FmtFileRun[]> => {
const getPriorityOrder = (tasks: FmtFileRunTask[]): number[] => {
const priority: number[] = [];
const rest: number[] = [];

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

const order = priority.concat(rest);
const outcomes = await Promise.all(
order.map((index) => runFmtFile(tasks[index], shouldWrite, formatFile)),
);
return priority.concat(rest);
};

/** Bounds queued work while keeping results in the original file order. */
const runScheduledTasks = async (
tasks: FmtFileRunTask[],
shouldWrite: boolean,
formatFile: FormatFile,
concurrency: number,
): Promise<FmtFileRun[]> => {
const order =
concurrency >= minPriorityWorkers ? getPriorityOrder(tasks) : undefined;
const results = new Array<FmtFileRun>(tasks.length);
for (let index = 0; index < order.length; index++) {
results[order[index]] = outcomes[index];
}
let nextIndex = 0;

const consume = async (): Promise<void> => {
while (nextIndex < tasks.length) {
const index = nextIndex++;
const taskIndex = order?.[index] ?? index;
results[taskIndex] = await runFmtFile(
tasks[taskIndex],
shouldWrite,
formatFile,
);
}
};

await Promise.all(
Array.from({ length: Math.min(concurrency, tasks.length) }, consume),
);
return results;
};

Expand Down Expand Up @@ -225,40 +239,40 @@ const runFmtTasks = async (
maxWorkers?: number,
cache?: RunCache,
): Promise<FmtFilesResult> => {
const tasks = files.map((file) => createRunTask(file, cache));
const pendingFileCount = tasks.reduce(
(count, task) => count + (isCachedUnsupported(task) ? 0 : 1),
0,
);
if (pendingFileCount === 0) {
const tasks: FmtFileRunTask[] = [];
for (const file of files) {
const task = createRunTask(file, cache);
if (!isCachedUnsupported(task)) {
tasks.push(task);
}
}
if (tasks.length === 0) {
return { files: [], processedFileCount: 0 };
}

// One pending file cannot benefit from parallelism, so avoid worker startup and IPC overhead.
if (pendingFileCount === 1) {
if (tasks.length === 1) {
const { formatFile } = await import('./worker.ts');
const formatFileOnMainThread: FormatFile = (file, write, fileCache) =>
formatFile({ file, shouldWrite: write, cache: fileCache });
const results = await Promise.all(
tasks.map((task) =>
runFmtFile(task, shouldWrite, formatFileOnMainThread),
),
const result = await runFmtFile(
tasks[0],
shouldWrite,
formatFileOnMainThread,
);
return collectFmtResults(results, cache);
return collectFmtResults([result], cache);
}

const { createWorkerPool } = await import('./workerPool.ts');
const workerPool = await createWorkerPool(pendingFileCount, maxWorkers);
const workerPool = await createWorkerPool(tasks.length, maxWorkers);

try {
const results =
workerPool.workerCount >= minPriorityWorkers
? await runPriorityTasks(tasks, shouldWrite, workerPool.formatFile)
: await Promise.all(
tasks.map((task) =>
runFmtFile(task, shouldWrite, workerPool.formatFile),
),
);
const results = await runScheduledTasks(
tasks,
shouldWrite,
workerPool.formatFile,
workerPool.workerCount,
);
return collectFmtResults(results, cache);
} finally {
await workerPool.terminate();
Expand Down
37 changes: 37 additions & 0 deletions packages/rstack/tests/fmt/runnerScheduling.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { setImmediate } from 'node:timers/promises';
import { expect, rs, test } from 'rstack/test';
import { runFmtFiles } from '../../src/fmt/runner.ts';
import type { FmtFileRequest } from '../../src/fmt/types.ts';

const state = rs.hoisted(() => ({
active: 0,
peak: 0,
completed: [] as string[],
}));

rs.mock('../../src/fmt/workerPool.ts', () => ({
createWorkerPool: (_fileCount: number, workerCount: number) => ({
workerCount,
async formatFile(file: FmtFileRequest) {
state.peak = Math.max(state.peak, ++state.active);
await setImmediate();
state.active--;
state.completed.push(file.path);
return { status: 'unchanged' };
},
terminate: () => Promise.resolve(),
}),
}));

test('bounds in-flight tasks and processes every file', async () => {
const paths = Array.from({ length: 6 }, (_, index) => `${index}.ts`);

await runFmtFiles({
files: paths.map((path) => ({ path, options: {} })),
mode: 'check',
maxWorkers: 2,
});

expect(state.peak).toBe(2);
expect(state.completed.sort()).toEqual(paths);
});
6 changes: 5 additions & 1 deletion packages/rstack/tests/fmt/runnerWorkerPreflight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ test('does not start the worker pool when every parser result is cached as unsup

test('rechecks a path-only unsupported entry on the main thread', async () => {
await withTempProject(async (rootPath) => {
const { file: ignored } = await createCachedUnsupportedFile(
rootPath,
'ignored.unknown',
);
const { cache, file } = await createCachedUnsupportedFile(
rootPath,
'script',
Expand All @@ -78,7 +82,7 @@ test('rechecks a path-only unsupported entry on the main thread', async () => {

await expect(
runFmtFiles({
files: [file],
files: [ignored, file],
mode: 'check',
cache,
}),
Expand Down
Loading