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
96 changes: 96 additions & 0 deletions packages/cli/src/utils/managed-npm-update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,4 +347,100 @@ describe('managed npm update', () => {

expect(fs.existsSync(update.stagingDir)).toBe(false);
});

it('removes only orphaned managed update artifacts before staging', () => {
const root = makeTemporaryDirectory();
const bootstrap = writeBaseInstallation(root);
const updateRoot = path.join(root, 'updates');
const current = prepareManagedNpmUpdate('2.0.0', bootstrap, updateRoot);
const versionsDir = path.dirname(current.stagingDir);
const missingPid = 999999999;
const staleStagingDir = fs.mkdtempSync(
path.join(versionsDir, `.2.1.0-${missingPid}-`),
);
const staleActiveFile = path.join(
current.launcherRoot,
`active.json.${missingPid}`,
);
const activeStagingDir = fs.mkdtempSync(
path.join(versionsDir, `.2.2.0-${process.pid}-`),
);
const activeTemporaryFile = path.join(
current.launcherRoot,
`active.json.${process.pid}`,
);
const versionDir = path.join(versionsDir, '1.0.0');
const unknownDir = path.join(versionsDir, 'unrelated');
Comment thread
patrick-andstar marked this conversation as resolved.
const nonSemverDir = path.join(
versionsDir,
`.not-semver-${missingPid}-abc123`,
);
const stagingSymlink = path.join(
versionsDir,
`.2.3.0-${missingPid}-abcdef`,
);
fs.writeFileSync(staleActiveFile, 'stale');
fs.writeFileSync(activeTemporaryFile, 'active');
fs.mkdirSync(versionDir);
fs.mkdirSync(unknownDir);
fs.mkdirSync(nonSemverDir);
fs.symlinkSync(
versionDir,
stagingSymlink,
process.platform === 'win32' ? 'junction' : 'dir',
);
const kill = vi.spyOn(process, 'kill').mockImplementation((pid) => {
if (pid === missingPid) {
const error = new Error('process not found') as NodeJS.ErrnoException;
error.code = 'ESRCH';
throw error;
}
return true;
});
try {
prepareManagedNpmUpdate('3.0.0', bootstrap, updateRoot);

expect(fs.existsSync(staleStagingDir)).toBe(false);
expect(fs.existsSync(staleActiveFile)).toBe(false);
expect(fs.existsSync(current.stagingDir)).toBe(true);
expect(fs.existsSync(activeStagingDir)).toBe(true);
expect(fs.existsSync(activeTemporaryFile)).toBe(true);
expect(fs.existsSync(versionDir)).toBe(true);
expect(fs.existsSync(unknownDir)).toBe(true);
expect(fs.existsSync(nonSemverDir)).toBe(true);
expect(fs.existsSync(stagingSymlink)).toBe(true);
} finally {
kill.mockRestore();
}
});

it('keeps artifacts when process liveness is uncertain', () => {
const root = makeTemporaryDirectory();
const bootstrap = writeBaseInstallation(root);
const updateRoot = path.join(root, 'updates');
const current = prepareManagedNpmUpdate('2.0.0', bootstrap, updateRoot);
const versionsDir = path.dirname(current.stagingDir);
const inaccessiblePid = 888888888;
const stagingDir = fs.mkdtempSync(
path.join(versionsDir, `.2.1.0-${inaccessiblePid}-`),
);
const temporaryActiveFile = path.join(
current.launcherRoot,
`active.json.${inaccessiblePid}`,
);
fs.writeFileSync(temporaryActiveFile, 'unverified');
const kill = vi.spyOn(process, 'kill').mockImplementation(() => {
const error = new Error('permission denied') as NodeJS.ErrnoException;
error.code = 'EPERM';
throw error;
});
try {
prepareManagedNpmUpdate('3.0.0', bootstrap, updateRoot);

expect(fs.existsSync(stagingDir)).toBe(true);
expect(fs.existsSync(temporaryActiveFile)).toBe(true);
} finally {
kill.mockRestore();
}
});
});
63 changes: 63 additions & 0 deletions packages/cli/src/utils/managed-npm-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,68 @@ function launcherId(bootstrapPath: string): string {
return createHash('sha256').update(bootstrapPath).digest('hex').slice(0, 16);
}

function processDoesNotExist(pidText: string): boolean {
const pid = Number(pidText);
if (!Number.isSafeInteger(pid)) return false;
try {
process.kill(pid, 0);
return false;
} catch (error) {
return (error as NodeJS.ErrnoException).code === 'ESRCH';
}
}

function readDirectoryEntries(directory: string): fs.Dirent[] {
try {
return fs.readdirSync(directory, { withFileTypes: true });
} catch {
return [];
}
}

function cleanupOrphanedManagedNpmUpdateArtifacts(
launcherRoot: string,
versionsDir: string,
): void {
for (const entry of readDirectoryEntries(versionsDir)) {
const match = /^\.(.+)-([1-9]\d*)-[A-Za-z0-9]{6}$/.exec(entry.name);
if (
!entry.isDirectory() ||
entry.isSymbolicLink() ||
!match ||
semver.valid(match[1]) !== match[1] ||
!processDoesNotExist(match[2])
) {
continue;
}
try {
fs.rmSync(path.join(versionsDir, entry.name), {
recursive: true,
force: true,
});
} catch {
continue;
}
}

for (const entry of readDirectoryEntries(launcherRoot)) {
const match = /^active\.json\.([1-9]\d*)$/.exec(entry.name);
if (
!entry.isFile() ||
entry.isSymbolicLink() ||
!match ||
!processDoesNotExist(match[1])
) {
continue;
}
try {
fs.rmSync(path.join(launcherRoot, entry.name), { force: true });
} catch {
continue;
}
}
}

function resolveNpmGlobalConfigPath(): string {
const configured = process.env['NPM_CONFIG_GLOBALCONFIG'];
if (configured) return path.resolve(configured);
Expand Down Expand Up @@ -156,6 +218,7 @@ export function prepareManagedNpmUpdate(
const launcherRoot = path.join(updateRoot, launcherId(resolvedBootstrapPath));
const versionsDir = path.join(launcherRoot, 'versions');
fs.mkdirSync(versionsDir, { recursive: true });
cleanupOrphanedManagedNpmUpdateArtifacts(launcherRoot, versionsDir);
const stagingDir = fs.mkdtempSync(
path.join(versionsDir, `.${version}-${process.pid}-`),
);
Expand Down
Loading