Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { exec, execFile } from 'child_process';
import { exec } from 'child_process';
import { existsSync } from 'fs';
import { cp, mkdir, readFile, rm, writeFile } from 'fs/promises';
import { basename, delimiter, join } from 'path';
import { promisify } from 'util';
import { afterAll, beforeAll, test, type TestAPI } from 'vitest';
import { CLEANUP_STEPS, createRunner, PACKAGE_ROOT } from './createRunner';
import { installFixtureDependencies } from './installFixtureDependencies';

const execPromise = promisify(exec);
const execFilePromise = promisify(execFile);

interface ScenarioPaths {
cjs: {
Expand Down Expand Up @@ -255,17 +255,11 @@ function prepareTmpDir(

await writeFile(join(tmpDirPath, 'package.json'), JSON.stringify(packageJson, null, 2));

const deps = Object.entries(additionalDependencies).map(([name, range]) => {
if (!range || typeof range !== 'string') {
throw new Error(`Invalid version range for "${name}": ${String(range)}`);
}
return `${name}@${range}`;
});

if (deps.length > 0) {
// Prefer npm for temp installs to avoid Yarn engine strictness; see https://github.com/vercel/ai/issues/7777
await npmInstallWithRetry(tmpDirPath, deps);
}
await installFixtureDependencies(
tmpDirPath,
additionalDependencies,
!options?.afterSetupCommand && !options?.copyPaths?.length,
);
}

if (options?.afterSetupCommand) {
Expand Down Expand Up @@ -332,58 +326,6 @@ function convertEsmToCjs(content: string): string {
return newContent;
}

const NPM_INSTALL_MAX_RETRIES = 3;
const NPM_INSTALL_RETRY_DELAY_MS = 2_000;
// npm install can stall on CI without ever failing, which would otherwise use up the whole setup hook timeout
// before a retry gets a chance to run.
const NPM_INSTALL_TIMEOUT_MS = 60_000;

async function npmInstallWithRetry(cwd: string, deps: string[]): Promise<void> {
for (let attempt = 1; attempt <= NPM_INSTALL_MAX_RETRIES; attempt++) {
try {
// Run npm without a shell, so the timeout kills npm itself rather than leaving it running next to the retry
const { stdout, stderr } = await execFilePromise(
'npm',
// We only use --prefer-offline on the first attempt to try to read from cache
// in follow ups we just try to install in any way
['install', ...(attempt === 1 ? ['--prefer-offline'] : []), '--no-audit', '--no-fund'],
{
cwd,
encoding: 'utf8',
timeout: NPM_INSTALL_TIMEOUT_MS,
},
);

if (process.env.DEBUG) {
// eslint-disable-next-line no-console
console.log('[additionalDependencies via npm]', deps.join(' '));
// eslint-disable-next-line no-console
console.log('[npm stdout]', stdout);
// eslint-disable-next-line no-console
console.log('[npm stderr]', stderr);
}
return;
} catch (error) {
if (attempt < NPM_INSTALL_MAX_RETRIES) {
// eslint-disable-next-line no-console
console.warn(
`npm install attempt ${attempt}/${NPM_INSTALL_MAX_RETRIES} failed, retrying in ${NPM_INSTALL_RETRY_DELAY_MS}ms...`,
);
await new Promise(resolve => setTimeout(resolve, NPM_INSTALL_RETRY_DELAY_MS));
// A killed attempt leaves a partial install behind, which the next attempt would treat as complete
await rm(join(cwd, 'node_modules'), { recursive: true, force: true });
await rm(join(cwd, 'package-lock.json'), { force: true });
} else {
// oxlint-disable-next-line no-console
console.error(error);
throw new Error(
`Failed to install additionalDependencies in tmp dir ${cwd} after ${NPM_INSTALL_MAX_RETRIES} attempts`,
);
}
}
}
}

// Wrap the test API so it prepends the test name with the mode
// Also wraps the nested fields `only`, `skip`, `each`, and `for`
function wrapTestApi(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { execFile } from 'child_process';
import { rmSync } from 'fs';
import { cp, mkdtemp, rm, writeFile } from 'fs/promises';
import { join } from 'path';
import { promisify } from 'util';
import { PACKAGE_ROOT } from './createRunner';

const execFilePromise = promisify(execFile);

const dependencyInstalls = new Map<string, Promise<string>>();
const dependencyDirectories = new Set<string>();

process.once('exit', () => {
for (const directory of dependencyDirectories) {
rmSync(directory, { recursive: true, force: true });
}
});

// Install each dependency set once per worker, then copy it into each scenario's directory.
// Sharing the promise also deduplicates concurrent requests. Scenarios can modify or delete
// their copies independently; the original installs are kept until the worker exits.
export async function installFixtureDependencies(
directory: string,
dependencies: Record<string, string>,
reuseAllowed: boolean,
): Promise<void> {
const dependencySpecs = Object.entries(dependencies).map(([name, range]) => {
if (!range || typeof range !== 'string') {
throw new Error(`Invalid version range for "${name}": ${String(range)}`);
}
return `${name}@${range}`;
});
// Custom installs may depend on copied fixture files; the fast-copy path also requires GNU cp.
if (!process.env.CI || process.platform !== 'linux' || !reuseAllowed) {
await npmInstallWithRetry(directory, dependencySpecs);
return;
}

const key = JSON.stringify(Object.entries(dependencies).sort(([a], [b]) => a.localeCompare(b)));
const installPromise = getOrCreateDependencyInstall(key, dependencies, dependencySpecs);
const sourceDirectory = await installPromise;
try {
await copyDependencyInstall(sourceDirectory, directory);
} catch (error) {
// oxlint-disable-next-line no-console
console.warn('Dependency copy failed; installing fresh:', error);
if (dependencyInstalls.get(key) === installPromise) {
dependencyInstalls.delete(key);
}
await rm(join(directory, 'node_modules'), { recursive: true, force: true });
await rm(join(directory, 'package-lock.json'), { force: true });
await npmInstallWithRetry(directory, dependencySpecs);
}
}

async function copyDependencyInstall(source: string, destination: string): Promise<void> {
// Native copying avoids the per-file overhead of fs.cp for large dependency trees.
await execFilePromise('cp', [
'-a',
'--reflink=auto',
join(source, 'node_modules'),
join(destination, 'node_modules'),
]);
await cp(join(source, 'package-lock.json'), join(destination, 'package-lock.json'));
}

function getOrCreateDependencyInstall(
key: string,
dependencies: Record<string, string>,
dependencySpecs: string[],
): Promise<string> {
const existing = dependencyInstalls.get(key);
if (existing) return existing;

const installPromise = (async () => {
const directory = await mkdtemp(join(PACKAGE_ROOT, 'tmp_dependencies_'));
dependencyDirectories.add(directory);
await writeFile(
join(directory, 'package.json'),
JSON.stringify({ name: 'tmp-integration-test', private: true, version: '0.0.0', dependencies }),
);
await npmInstallWithRetry(directory, dependencySpecs);
return directory;
})();

dependencyInstalls.set(key, installPromise);
void installPromise.catch(() => {
if (dependencyInstalls.get(key) === installPromise) {
dependencyInstalls.delete(key);
}
});
return installPromise;
}

const NPM_INSTALL_MAX_RETRIES = 3;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

from here on downwards this was just moved to this file as is

const NPM_INSTALL_RETRY_DELAY_MS = 2_000;
// npm install can stall on CI without ever failing, which would otherwise use up the whole setup hook timeout
// before a retry gets a chance to run.
const NPM_INSTALL_TIMEOUT_MS = 60_000;

async function npmInstallWithRetry(cwd: string, deps: string[]): Promise<void> {
for (let attempt = 1; attempt <= NPM_INSTALL_MAX_RETRIES; attempt++) {
try {
// Run npm without a shell, so the timeout kills npm itself rather than leaving it running next to the retry
const { stdout, stderr } = await execFilePromise(
'npm',
// We only use --prefer-offline on the first attempt to try to read from cache
// in follow ups we just try to install in any way
['install', ...(attempt === 1 ? ['--prefer-offline'] : []), '--no-audit', '--no-fund'],
{
cwd,
encoding: 'utf8',
timeout: NPM_INSTALL_TIMEOUT_MS,
},
);

if (process.env.DEBUG) {
// eslint-disable-next-line no-console
console.log('[additionalDependencies via npm]', deps.join(' '));
// eslint-disable-next-line no-console
console.log('[npm stdout]', stdout);
// eslint-disable-next-line no-console
console.log('[npm stderr]', stderr);
}
return;
} catch (error) {
if (attempt < NPM_INSTALL_MAX_RETRIES) {
// eslint-disable-next-line no-console
console.warn(
`npm install attempt ${attempt}/${NPM_INSTALL_MAX_RETRIES} failed, retrying in ${NPM_INSTALL_RETRY_DELAY_MS}ms...`,
);
await new Promise(resolve => setTimeout(resolve, NPM_INSTALL_RETRY_DELAY_MS));
// A killed attempt leaves a partial install behind, which the next attempt would treat as complete
await rm(join(cwd, 'node_modules'), { recursive: true, force: true });
await rm(join(cwd, 'package-lock.json'), { force: true });
} else {
// oxlint-disable-next-line no-console
console.error(error);
throw new Error(
`Failed to install additionalDependencies in tmp dir ${cwd} after ${NPM_INSTALL_MAX_RETRIES} attempts`,
);
}
}
}
}
Loading