From e56b637b940d52f4da9c1f4a9d21a1441a4231b3 Mon Sep 17 00:00:00 2001 From: iclanton <5010588+iclanton@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:24:32 +0000 Subject: [PATCH 1/8] [rush] Add tarball support to deploy archives Support .tar, .tar.gz, and .tgz deployment archives using the existing tar dependency. Preserve ZIP support and add archive coverage, documentation, and release changefiles. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../rush/deploy-tarballs_2026-11-25.json | 10 ++ .../deploy-tarballs_2026-11-25.json | 10 ++ .../config/subspaces/default/pnpm-lock.yaml | 3 + libraries/package-extractor/README.md | 3 + libraries/package-extractor/package.json | 3 +- .../package-extractor/src/ArchiveManager.ts | 79 ++++++++-- .../package-extractor/src/AssetHandler.ts | 5 +- .../package-extractor/src/PackageExtractor.ts | 3 +- .../src/test/ArchiveManager.test.ts | 147 ++++++++++++++++++ .../rush-lib/src/cli/actions/DeployAction.ts | 2 +- 10 files changed, 248 insertions(+), 17 deletions(-) create mode 100644 common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json create mode 100644 common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json create mode 100644 libraries/package-extractor/src/test/ArchiveManager.test.ts diff --git a/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json new file mode 100644 index 00000000000..0971bde54e8 --- /dev/null +++ b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json @@ -0,0 +1,10 @@ +{ + "changes": [ + { + "packageName": "@microsoft/rush", + "comment": "Add support for .tar, .tar.gz, and .tgz archives to \"rush deploy --create-archive\".", + "type": "minor" + } + ], + "packageName": "@microsoft/rush" +} diff --git a/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json new file mode 100644 index 00000000000..91a26f9c556 --- /dev/null +++ b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json @@ -0,0 +1,10 @@ +{ + "changes": [ + { + "packageName": "@rushstack/package-extractor", + "comment": "Support .tar, .tar.gz, and .tgz deployment archives, including archive-only extraction.", + "type": "minor" + } + ], + "packageName": "@rushstack/package-extractor" +} diff --git a/common/config/subspaces/default/pnpm-lock.yaml b/common/config/subspaces/default/pnpm-lock.yaml index 2ba67bda337..4b0b412c30f 100644 --- a/common/config/subspaces/default/pnpm-lock.yaml +++ b/common/config/subspaces/default/pnpm-lock.yaml @@ -4069,6 +4069,9 @@ importers: semver: specifier: ~7.7.4 version: 7.7.4 + tar: + specifier: ~7.5.6 + version: 7.5.13 devDependencies: '@rushstack/heft': specifier: workspace:* diff --git a/libraries/package-extractor/README.md b/libraries/package-extractor/README.md index 6bdf6b3af4a..9f83c783213 100644 --- a/libraries/package-extractor/README.md +++ b/libraries/package-extractor/README.md @@ -2,6 +2,9 @@ A library used for creating an isolated copy of a package and, optionally, bundling it into an archive. +The `createArchiveFilePath` option supports ZIP (`.zip`), tar (`.tar`), and gzip-compressed +tar (`.tar.gz` or `.tgz`) archives, including when `createArchiveOnly` is enabled. + ## Links - [CHANGELOG.md]( diff --git a/libraries/package-extractor/package.json b/libraries/package-extractor/package.json index 9e7e116df2d..4d701cca9e3 100644 --- a/libraries/package-extractor/package.json +++ b/libraries/package-extractor/package.json @@ -52,7 +52,8 @@ "jszip": "~3.8.0", "minimatch": "10.2.3", "npm-packlist": "~5.1.3", - "semver": "~7.7.4" + "semver": "~7.7.4", + "tar": "~7.5.6" }, "devDependencies": { "local-node-rig": "workspace:*", diff --git a/libraries/package-extractor/src/ArchiveManager.ts b/libraries/package-extractor/src/ArchiveManager.ts index 69a7d1360c2..c6c47e71316 100644 --- a/libraries/package-extractor/src/ArchiveManager.ts +++ b/libraries/package-extractor/src/ArchiveManager.ts @@ -1,7 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. +import { createWriteStream, type WriteStream } from 'node:fs'; +import { pipeline } from 'node:stream/promises'; + import JSZip from 'jszip'; +import * as tar from 'tar'; import { FileSystem, type FileSystemStats, Path } from '@rushstack/node-core-library'; @@ -20,19 +24,40 @@ export interface IAddToArchiveOptions { stats?: FileSystemStats; } +interface IArchiveEntry { + data: Buffer | string; + permissions: number; + isSymbolicLink: boolean; +} + export class ArchiveManager { - #zip: JSZip = new JSZip(); + readonly #archiveFormat: 'zip' | 'tar' | 'tgz'; + readonly #entries: Map = new Map(); + + public constructor(archiveFilePath: string) { + if (archiveFilePath.endsWith('.zip')) { + this.#archiveFormat = 'zip'; + } else if (archiveFilePath.endsWith('.tar')) { + this.#archiveFormat = 'tar'; + } else if (archiveFilePath.endsWith('.tar.gz') || archiveFilePath.endsWith('.tgz')) { + this.#archiveFormat = 'tgz'; + } else { + throw new Error('Supported archive file extensions: .zip, .tar, .tar.gz, .tgz.'); + } + } public async addToArchiveAsync(options: IAddToArchiveOptions): Promise { const { filePath, fileData, archivePath } = options; let data: Buffer | string; let permissions: number; + let isSymbolicLink: boolean = false; if (filePath) { const stats: FileSystemStats = options.stats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); if (stats.isSymbolicLink()) { data = await FileSystem.readLinkAsync(filePath); permissions = SYMBOLIC_LINK_PERMISSIONS; + isSymbolicLink = true; } else if (stats.isDirectory()) { throw new Error('Directories cannot be added to the archive'); } else { @@ -48,17 +73,51 @@ export class ArchiveManager { // Replace backslashes for Unix compat const addPath: string = Path.convertToSlashes(archivePath); - this.#zip.file(addPath, data, { - unixPermissions: permissions, - dir: false - }); + this.#entries.set(addPath, { data, permissions, isSymbolicLink }); } public async createArchiveAsync(archiveFilePath: string): Promise { - const zipContent: Buffer = await this.#zip.generateAsync({ - type: 'nodebuffer', - platform: 'UNIX' - }); - await FileSystem.writeFileAsync(archiveFilePath, zipContent); + if (this.#archiveFormat === 'zip') { + const zip: JSZip = new JSZip(); + for (const [archivePath, { data, permissions }] of this.#entries) { + zip.file(archivePath, data, { + unixPermissions: permissions, + dir: false + }); + } + + const zipContent: Buffer = await zip.generateAsync({ + type: 'nodebuffer', + platform: 'UNIX' + }); + await FileSystem.writeFileAsync(archiveFilePath, zipContent); + } else { + const pack: tar.Pack = new tar.Pack({ gzip: this.#archiveFormat === 'tgz' }); + const output: WriteStream = createWriteStream(archiveFilePath); + const archivePromise: Promise = pipeline(pack, output); + + for (const [archivePath, { data, permissions, isSymbolicLink }] of this.#entries) { + const content: Buffer = isSymbolicLink + ? Buffer.alloc(0) + : typeof data === 'string' + ? Buffer.from(data) + : data; + // ReadEntry allows generated assets to be archived without staging them on disk. + const entry: tar.ReadEntry = new tar.ReadEntry( + new tar.Header({ + path: archivePath, + mode: permissions, + type: isSymbolicLink ? 'SymbolicLink' : 'File', + linkpath: isSymbolicLink ? Path.convertToSlashes(data.toString()) : undefined, + size: content.length + }) + ); + pack.add(entry); + entry.end(content); + } + + pack.end(); + await archivePromise; + } } } diff --git a/libraries/package-extractor/src/AssetHandler.ts b/libraries/package-extractor/src/AssetHandler.ts index cf064774d3d..7ff1d0cb75f 100644 --- a/libraries/package-extractor/src/AssetHandler.ts +++ b/libraries/package-extractor/src/AssetHandler.ts @@ -71,11 +71,8 @@ export class AssetHandler { this.#targetRootFolder = targetRootFolder; this.#symlinkAnalyzer = symlinkAnalyzer; if (createArchiveFilePath) { - if (path.extname(createArchiveFilePath) !== '.zip') { - throw new Error('Only archives with the .zip file extension are currently supported.'); - } this.#archiveFilePath = path.resolve(targetRootFolder, createArchiveFilePath); - this.#archiveManager = new ArchiveManager(); + this.#archiveManager = new ArchiveManager(this.#archiveFilePath); } if (createArchiveOnly && !this.#archiveManager) { throw new Error('createArchiveOnly cannot be true if createArchiveFilePath is not provided'); diff --git a/libraries/package-extractor/src/PackageExtractor.ts b/libraries/package-extractor/src/PackageExtractor.ts index e60df7b46ae..219d8c61211 100644 --- a/libraries/package-extractor/src/PackageExtractor.ts +++ b/libraries/package-extractor/src/PackageExtractor.ts @@ -233,7 +233,8 @@ export interface IExtractorOptions { overwriteExisting: boolean; /** - * The desired path to be used when archiving the target folder. Supported file extensions: .zip. + * The desired path to be used when archiving the target folder. + * Supported file extensions: .zip, .tar, .tar.gz, .tgz. */ createArchiveFilePath?: string; diff --git a/libraries/package-extractor/src/test/ArchiveManager.test.ts b/libraries/package-extractor/src/test/ArchiveManager.test.ts new file mode 100644 index 00000000000..76e51436567 --- /dev/null +++ b/libraries/package-extractor/src/test/ArchiveManager.test.ts @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import path from 'node:path'; + +import JSZip from 'jszip'; +import * as tar from 'tar'; +import { FileSystem, Path, PosixModeBits } from '@rushstack/node-core-library'; +import { Terminal, StringBufferTerminalProvider } from '@rushstack/terminal'; + +import { ArchiveManager } from '../ArchiveManager'; +import { AssetHandler } from '../AssetHandler'; +import { SymlinkAnalyzer } from '../SymlinkAnalyzer'; + +interface ITarEntry { + type: string; + mode?: number; + linkpath?: string; + data: Buffer; +} + +async function readTarAsync(archivePath: string): Promise> { + const entries: Map = new Map(); + await tar.list({ + file: archivePath, + onReadEntry: (entry) => { + const chunks: Buffer[] = []; + entry.on('data', (chunk: Buffer) => chunks.push(chunk)); + entry.on('end', () => { + const { path: entryPath, type, mode, linkpath } = entry; + entries.set(entryPath, { type, mode, linkpath, data: Buffer.concat(chunks) }); + }); + } + }); + + return entries; +} + +describe(ArchiveManager.name, () => { + const testFolder: string = path.resolve(__dirname, '../../test-output/archives'); + const sourceFolder: string = path.join(testFolder, 'source'); + const sourceFile: string = path.join(sourceFolder, 'input.bin'); + const binaryContent: Buffer = Buffer.from([0, 1, 127, 128, 255]); + const terminal: Terminal = new Terminal(new StringBufferTerminalProvider()); + + beforeAll(async () => { + await FileSystem.ensureEmptyFolderAsync(testFolder); + await FileSystem.writeFileAsync(sourceFile, binaryContent, { ensureFolderExists: true }); + await FileSystem.changePosixModeBitsAsync( + sourceFile, + // eslint-disable-next-line no-bitwise + PosixModeBits.AllRead | PosixModeBits.UserWrite | PosixModeBits.GroupWrite | PosixModeBits.AllExecute + ); + }); + + it.each(['.tar', '.tar.gz', '.tgz'])('creates %s archives with and without copying assets', async (ext) => { + for (const createArchiveOnly of [false, true]) { + const targetRootFolder: string = path.join(testFolder, `${ext.slice(1)}-${createArchiveOnly}`); + await FileSystem.ensureFolderAsync(targetRootFolder); + const archiveFilePath: string = path.join(targetRootFolder, `deploy${ext}`); + const targetFilePath: string = path.join(targetRootFolder, 'nested', 'input.bin'); + const handler: AssetHandler = new AssetHandler({ + terminal, + mainProjectName: 'test', + projectConfigurations: [], + sourceRootFolder: sourceFolder, + targetRootFolder, + overwriteExisting: false, + linkCreation: 'none', + symlinkAnalyzer: new SymlinkAnalyzer(), + createArchiveFilePath: archiveFilePath, + createArchiveOnly + }); + + await handler.includeAssetAsync({ sourceFilePath: sourceFile, targetFilePath }); + await handler.includeAssetAsync({ + sourceFileContent: 'generated content', + targetFilePath: path.join(targetRootFolder, 'generated.txt') + }); + await handler.finalizeAsync(); + + const entries: Map = await readTarAsync(archiveFilePath); + const archiveContent: Buffer = await FileSystem.readFileToBufferAsync(archiveFilePath); + if (ext === '.tar') { + expect(archiveContent.subarray(257, 262).toString()).toBe('ustar'); + } else { + expect(archiveContent.subarray(0, 2)).toEqual(Buffer.from([0x1f, 0x8b])); + } + + expect([...entries.keys()].sort()).toEqual(['generated.txt', 'nested/input.bin']); + expect(entries.get('nested/input.bin')?.data).toEqual(binaryContent); + expect(entries.get('nested/input.bin')).toMatchObject({ + type: 'File', + // eslint-disable-next-line no-bitwise + mode: (await FileSystem.getStatisticsAsync(sourceFile)).mode & 0o7777 + }); + expect(entries.get('generated.txt')?.data.toString()).toBe('generated content'); + expect(await FileSystem.existsAsync(targetFilePath)).toBe(!createArchiveOnly); + if (createArchiveOnly) { + expect(await FileSystem.readFolderItemNamesAsync(targetRootFolder)).toEqual([`deploy${ext}`]); + } + } + }); + + const testSymlinks: typeof it = process.platform === 'win32' ? it.skip : it; + testSymlinks.each(['.tar', '.tar.gz', '.tgz'])('preserves symbolic links in %s archives', async (ext) => { + const linkPath: string = path.join(sourceFolder, `link${ext}`); + await FileSystem.createSymbolicLinkFileAsync({ + newLinkPath: linkPath, + linkTargetPath: 'input.bin' + }); + const archiveFilePath: string = path.join(testFolder, `links${ext}`); + const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + await manager.addToArchiveAsync({ filePath: linkPath, archivePath: 'nested\\link' }); + await manager.createArchiveAsync(archiveFilePath); + + const entries: Map = await readTarAsync(archiveFilePath); + expect(entries.get('nested/link')).toMatchObject({ + type: 'SymbolicLink', + linkpath: Path.convertToSlashes(await FileSystem.readLinkAsync(linkPath)), + data: Buffer.alloc(0) + }); + }); + + it('continues to create ZIP archives', async () => { + const archiveFilePath: string = path.join(testFolder, 'deploy.zip'); + const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'nested\\input.bin' }); + await manager.addToArchiveAsync({ fileData: 'generated content', archivePath: 'generated.txt' }); + await manager.createArchiveAsync(archiveFilePath); + + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(await zip.file('nested/input.bin')?.async('nodebuffer')).toEqual(binaryContent); + expect(await zip.file('generated.txt')?.async('string')).toBe('generated content'); + }); + + it('rejects unsupported extensions', () => { + expect(() => new ArchiveManager('deploy.gz')).toThrow('Supported archive file extensions'); + }); + + it('reports archive write failures', async () => { + const archiveFilePath: string = path.join(testFolder, 'missing', 'deploy.tgz'); + const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + await manager.addToArchiveAsync({ fileData: 'content', archivePath: 'file.txt' }); + await expect(manager.createArchiveAsync(archiveFilePath)).rejects.toThrow(); + }); +}); diff --git a/libraries/rush-lib/src/cli/actions/DeployAction.ts b/libraries/rush-lib/src/cli/actions/DeployAction.ts index 62c9c33da88..513234b971a 100644 --- a/libraries/rush-lib/src/cli/actions/DeployAction.ts +++ b/libraries/rush-lib/src/cli/actions/DeployAction.ts @@ -93,7 +93,7 @@ export class DeployAction extends BaseRushAction { 'If specified, after the deployment has been prepared, "rush deploy"' + ' will create an archive containing the contents of the target folder.' + ' The newly created archive file will be placed according to the designated path, relative' + - ' to the target folder. Supported file extensions: .zip' + ' to the target folder. Supported file extensions: .zip, .tar, .tar.gz, .tgz' }); this.#createArchiveOnly = this.defineFlagParameter({ From 6eec598713237da6efcfd4db7459023ade5a78a0 Mon Sep 17 00:00:00 2001 From: iclanton <5010588+iclanton@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:11:56 +0000 Subject: [PATCH 2/8] fixup! [rush] Add tarball support to deploy archives Share native tar discovery and execution between deployment and build caching, retaining the JavaScript path for unavailable/incompatible tar and in-memory archive-only assets. Check in fixtures, remove the Windows symlink test skip, use FileSystem streams and template paths, and apply changefile wording. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../rush/deploy-tarballs_2026-11-25.json | 2 +- .../deploy-tarballs_2026-11-25.json | 2 +- common/reviews/api/package-extractor.api.md | 35 +++ libraries/package-extractor/README.md | 3 + .../package-extractor/src/ArchiveManager.ts | 53 +++- .../package-extractor/src/AssetHandler.ts | 5 +- .../package-extractor/src/TarExecutable.ts | 235 ++++++++++++++++++ libraries/package-extractor/src/index.ts | 7 + .../src/test/ArchiveManager.test.ts | 156 +++++++++--- .../src/test/fixtures/archive/executable.sh | 2 + .../src/test/fixtures/archive/generated.txt | 1 + .../src/test/fixtures/archive/input.txt | 1 + .../rush-lib/src/utilities/TarExecutable.ts | 215 ++-------------- 13 files changed, 475 insertions(+), 242 deletions(-) create mode 100644 libraries/package-extractor/src/TarExecutable.ts create mode 100755 libraries/package-extractor/src/test/fixtures/archive/executable.sh create mode 100644 libraries/package-extractor/src/test/fixtures/archive/generated.txt create mode 100644 libraries/package-extractor/src/test/fixtures/archive/input.txt diff --git a/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json index 0971bde54e8..2a6f5662ec7 100644 --- a/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json +++ b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json @@ -2,7 +2,7 @@ "changes": [ { "packageName": "@microsoft/rush", - "comment": "Add support for .tar, .tar.gz, and .tgz archives to \"rush deploy --create-archive\".", + "comment": "Add support for `.tar`, `.tar.gz`, and `.tgz` archives to `rush deploy --create-archive`.", "type": "minor" } ], diff --git a/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json index 91a26f9c556..0773a9f72f0 100644 --- a/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json +++ b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json @@ -2,7 +2,7 @@ "changes": [ { "packageName": "@rushstack/package-extractor", - "comment": "Support .tar, .tar.gz, and .tgz deployment archives, including archive-only extraction.", + "comment": "Support `.tar`, `.tar.gz`, and `.tgz` deployment archives, including archive-only extraction, preferring native tar when assets are available on disk.", "type": "minor" } ], diff --git a/common/reviews/api/package-extractor.api.md b/common/reviews/api/package-extractor.api.md index 1b0cfb0139c..690a82f0fc4 100644 --- a/common/reviews/api/package-extractor.api.md +++ b/common/reviews/api/package-extractor.api.md @@ -7,6 +7,17 @@ import { IPackageJson } from '@rushstack/node-core-library'; import { ITerminal } from '@rushstack/terminal'; +// @beta (undocumented) +export interface ICreateArchiveOptions extends ITarOptionsBase { + abortSignal?: AbortSignal; + // (undocumented) + archivePath: string; + baseFolderPath: string; + gzip?: boolean; + // (undocumented) + paths: string[]; +} + // @public export interface IExtractorDependencyConfiguration { dependencyName: string; @@ -76,6 +87,20 @@ export interface IProjectInfoJson { projectName: string; } +// @beta (undocumented) +export interface ITarOptionsBase { + // (undocumented) + logFilePath: string; +} + +// @beta (undocumented) +export interface IUntarOptions extends ITarOptionsBase { + // (undocumented) + archivePath: string; + // (undocumented) + outputFolderPath: string; +} + // @public export type LinkCreationMode = 'default' | 'script' | 'none'; @@ -86,6 +111,16 @@ export class PackageExtractor { static getPackageIncludedFilesAsync(packageRootPath: string): Promise; } +// @beta +export class TarExecutable { + // (undocumented) + tryCreateArchiveAsync(options: ICreateArchiveOptions): Promise; + // (undocumented) + static tryInitializeAsync(terminal: ITerminal, tarBinaryPath?: string): Promise; + // (undocumented) + tryUntarAsync(options: IUntarOptions): Promise; +} + // (No @packageDocumentation comment for this package) ``` diff --git a/libraries/package-extractor/README.md b/libraries/package-extractor/README.md index 9f83c783213..a8d5b862141 100644 --- a/libraries/package-extractor/README.md +++ b/libraries/package-extractor/README.md @@ -4,6 +4,9 @@ A library used for creating an isolated copy of a package and, optionally, bundl The `createArchiveFilePath` option supports ZIP (`.zip`), tar (`.tar`), and gzip-compressed tar (`.tar.gz` or `.tgz`) archives, including when `createArchiveOnly` is enabled. +Tar archives use the native `tar` executable when the deployed files are available on disk, +falling back to JavaScript when it is unavailable or fails. Archive-only deployments use +JavaScript so generated assets do not need to be staged on disk. ## Links diff --git a/libraries/package-extractor/src/ArchiveManager.ts b/libraries/package-extractor/src/ArchiveManager.ts index c6c47e71316..90b3312e127 100644 --- a/libraries/package-extractor/src/ArchiveManager.ts +++ b/libraries/package-extractor/src/ArchiveManager.ts @@ -1,13 +1,20 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { createWriteStream, type WriteStream } from 'node:fs'; import { pipeline } from 'node:stream/promises'; import JSZip from 'jszip'; import * as tar from 'tar'; -import { FileSystem, type FileSystemStats, Path } from '@rushstack/node-core-library'; +import { + FileSystem, + type FileSystemStats, + type FileSystemWriteStream, + Path +} from '@rushstack/node-core-library'; +import type { ITerminal } from '@rushstack/terminal'; + +import { TarExecutable } from './TarExecutable'; // 755 are default permissions to allow read/write/execute for owner and read/execute for group and others. const DEFAULT_FILE_PERMISSIONS: number = 0o755; @@ -30,6 +37,12 @@ interface IArchiveEntry { isSymbolicLink: boolean; } +export interface ICreateArchiveOptions { + terminal: ITerminal; + /** Omit when assets have not been materialized, such as archive-only deployment. */ + sourceFolder?: string; +} + export class ArchiveManager { readonly #archiveFormat: 'zip' | 'tar' | 'tgz'; readonly #entries: Map = new Map(); @@ -76,7 +89,7 @@ export class ArchiveManager { this.#entries.set(addPath, { data, permissions, isSymbolicLink }); } - public async createArchiveAsync(archiveFilePath: string): Promise { + public async createArchiveAsync(archiveFilePath: string, options?: ICreateArchiveOptions): Promise { if (this.#archiveFormat === 'zip') { const zip: JSZip = new JSZip(); for (const [archivePath, { data, permissions }] of this.#entries) { @@ -92,8 +105,40 @@ export class ArchiveManager { }); await FileSystem.writeFileAsync(archiveFilePath, zipContent); } else { + const { terminal, sourceFolder } = options ?? {}; + const nativePathsSupported: boolean = [...this.#entries.keys()].every( + (entryPath) => !entryPath.startsWith('-') && !/[\r\n\\]/.test(entryPath) + ); + if (terminal && sourceFolder && nativePathsSupported) { + const tarExecutable: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + if (tarExecutable) { + const logFilePath: string = `${archiveFilePath}.log`; + const exitCode: number = await tarExecutable.tryCreateArchiveAsync({ + archivePath: archiveFilePath, + paths: [...this.#entries.keys()], + baseFolderPath: sourceFolder, + logFilePath, + gzip: this.#archiveFormat === 'tgz' + }); + if (exitCode === 0) { + await FileSystem.deleteFileAsync(logFilePath); + return; + } + + terminal.writeWarningLine( + `Native tar exited with code ${exitCode}; falling back to JavaScript. See "${logFilePath}".` + ); + } else { + terminal.writeVerboseLine('Native tar is unavailable; falling back to JavaScript.'); + } + } else { + terminal?.writeVerboseLine( + 'Using JavaScript tar for in-memory assets or paths incompatible with native tar file lists.' + ); + } + const pack: tar.Pack = new tar.Pack({ gzip: this.#archiveFormat === 'tgz' }); - const output: WriteStream = createWriteStream(archiveFilePath); + const output: FileSystemWriteStream = await FileSystem.createWriteStreamAsync(archiveFilePath); const archivePromise: Promise = pipeline(pack, output); for (const [archivePath, { data, permissions, isSymbolicLink }] of this.#entries) { diff --git a/libraries/package-extractor/src/AssetHandler.ts b/libraries/package-extractor/src/AssetHandler.ts index 7ff1d0cb75f..35c8bfa8564 100644 --- a/libraries/package-extractor/src/AssetHandler.ts +++ b/libraries/package-extractor/src/AssetHandler.ts @@ -170,7 +170,10 @@ export class AssetHandler { if (this.#archiveManager && this.#archiveFilePath) { this.#terminal.writeLine(`Creating archive at "${this.#archiveFilePath}"`); - await this.#archiveManager.createArchiveAsync(this.#archiveFilePath); + await this.#archiveManager.createArchiveAsync(this.#archiveFilePath, { + terminal: this.#terminal, + sourceFolder: this.#createArchiveOnly ? undefined : this.#targetRootFolder + }); } this.#isFinalized = true; diff --git a/libraries/package-extractor/src/TarExecutable.ts b/libraries/package-extractor/src/TarExecutable.ts new file mode 100644 index 00000000000..0cb4e12cca3 --- /dev/null +++ b/libraries/package-extractor/src/TarExecutable.ts @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import * as path from 'node:path'; +import type { ChildProcess } from 'node:child_process'; +import events from 'node:events'; + +import { Executable, FileSystem, FileWriter } from '@rushstack/node-core-library'; +import type { ITerminal } from '@rushstack/terminal'; + +/** + * @beta + */ +export interface ITarOptionsBase { + logFilePath: string; +} + +/** + * @beta + */ +export interface IUntarOptions extends ITarOptionsBase { + archivePath: string; + outputFolderPath: string; +} + +/** + * @beta + */ +export interface ICreateArchiveOptions extends ITarOptionsBase { + archivePath: string; + paths: string[]; + /** The folder that `paths` are relative to. */ + baseFolderPath: string; + /** Whether to compress the archive with gzip. Defaults to true. */ + gzip?: boolean; + /** When aborted, kills the tar process, which then exits with a nonzero code. */ + abortSignal?: AbortSignal; +} + +/** + * Shared native tar discovery and execution for deployment and build caching. + * @beta + */ +export class TarExecutable { + #tarExecutablePath: string; + + private constructor(tarExecutablePath: string) { + this.#tarExecutablePath = tarExecutablePath; + } + + public static async tryInitializeAsync( + terminal: ITerminal, + tarBinaryPath?: string + ): Promise { + terminal.writeVerboseLine('Trying to find "tar" binary'); + const tarExecutablePath: string | undefined = tarBinaryPath || (await _tryFindTarExecutablePathAsync()); + if (!tarExecutablePath) { + terminal.writeVerboseLine('"tar" was not found on the PATH'); + return undefined; + } else { + terminal.writeVerboseLine(`Using "tar" binary: ${tarExecutablePath}`); + return new TarExecutable(tarExecutablePath); + } + } + + /** + * @returns + * The "tar" exit code + */ + public async tryUntarAsync(options: IUntarOptions): Promise { + return await this.#spawnTarWithLoggingAsync( + // These parameters are chosen for compatibility with the very primitive bsdtar 3.3.2 shipped with Windows 10. + [ + // [Windows bsdtar 3.3.2] Extract: tar -x [options] [] + '-x', + // [Windows bsdtar 3.3.2] -m Don't restore modification times + '-m', + // [Windows bsdtar 3.3.2] -f Location of archive (default \\.\tape0) + '-f', + options.archivePath + ], + options.outputFolderPath, + options.logFilePath + ); + } + + /** + * @returns + * The "tar" exit code + */ + public async tryCreateArchiveAsync(options: ICreateArchiveOptions): Promise { + const { archivePath, paths, logFilePath, baseFolderPath, abortSignal, gzip = true } = options; + + const tarInput: string = paths.join('\n'); + + // On Windows, tar.exe will report a "Failed to clean up compressor" error if the target folder + // does not exist (GitHub #2622) + await FileSystem.ensureFolderAsync(path.dirname(archivePath)); + + const tarExitCode: number = await this.#spawnTarWithLoggingAsync( + // These parameters are chosen for compatibility with the very primitive bsdtar 3.3.2 shipped with Windows 10. + [ + // [Windows bsdtar 3.3.2] -c Create + '-c', + // [Windows bsdtar 3.3.2] -f Location of archive (default \\.\tape0) + '-f', + archivePath, + // [Windows bsdtar 3.3.2] -z, -j, -J, --lzma Compress archive with gzip/bzip2/xz/lzma + ...(gzip ? ['-z'] : []), + // [GNU tar 1.33] -T, --files-from=FILE get names to extract or create from FILE + // + // Windows bsdtar does not document this parameter, but seems to accept it. + '--files-from=-' + ], + baseFolderPath, + logFilePath, + tarInput, + abortSignal + ); + + return tarExitCode; + } + + async #spawnTarWithLoggingAsync( + args: string[], + currentWorkingDirectory: string, + logFilePath: string, + input?: string, + abortSignal?: AbortSignal + ): Promise { + // Runs "tar" with the specified args and logs its output to the specified location. + // The log file looks like this: + // + // Windows: + // Start time: Mon Apr 19 2021 13:06:40 GMT-0700 (Pacific Daylight Time) + // Invoking "C:\WINDOWS\system32\tar.exe -x -f E:\rush-cache\d18105f7f83eb610b468be4e2421681f4a52e44d" + // + // ======= BEGIN PROCESS OUTPUT ======= + // [stdout] + // [stderr] + // ======== END PROCESS OUTPUT ======== + // + // Exited with code "0" + // + // Linux: + // Start time: Mon Apr 19 2021 13:06:40 GMT-0700 (Pacific Daylight Time) + // Invoking "/bin/tar -x -f /home/username/rush-cache/d18105f7f83eb610b468be4e2421681f4a52e44d" + // + // ======= BEGIN PROCESS OUTPUT ======= + // [stdout] + // [stderr] + // ======== END PROCESS OUTPUT ======== + // + // Exited with code "0" + + await FileSystem.ensureFolderAsync(path.dirname(logFilePath)); + const fileWriter: FileWriter = FileWriter.open(logFilePath); + fileWriter.write( + [ + `Start time: ${new Date().toString()}`, + `Invoking "${this.#tarExecutablePath} ${args.join(' ')}"`, + '', + `======= BEGIN PROCESS INPUT ======`, + input || '', + '======== END PROCESS INPUT =======', + '======= BEGIN PROCESS OUTPUT =======', + '' + ].join('\n') + ); + + const childProcess: ChildProcess = Executable.spawn(this.#tarExecutablePath, args, { + currentWorkingDirectory: currentWorkingDirectory + }); + const kill: () => void = () => childProcess.kill(); + if (abortSignal?.aborted) { + kill(); + } else { + abortSignal?.addEventListener('abort', kill, { once: true }); + } + + childProcess.stdout!.on('data', (chunk) => fileWriter.write(`[stdout] ${chunk}`)); + childProcess.stderr!.on('data', (chunk) => fileWriter.write(`[stderr] ${chunk}`)); + + if (input !== undefined) { + childProcess.stdin!.on('error', (error: NodeJS.ErrnoException) => { + // An incompatible or aborted tar may exit before reading the file list. + if (error.code === 'EPIPE') { + fileWriter.write(`[stdin] ${error.message}\n`); + } else { + childProcess.emit('error', error); + } + }); + + childProcess.stdin!.write(input, 'utf-8'); + childProcess.stdin!.end(); + } + + // Wait for process to exit and all streams to close + let tarExitCode: number | null; + let tarSignal: NodeJS.Signals | null; + try { + [tarExitCode, tarSignal] = await events.once(childProcess, 'close'); + } finally { + abortSignal?.removeEventListener('abort', kill); + } + + fileWriter.write( + ['======== END PROCESS OUTPUT ========', '', `Exited with code "${tarExitCode ?? tarSignal}"`].join( + '\n' + ) + ); + fileWriter.close(); + + // A tar process that was killed has no exit code. + return tarExitCode ?? 1; + } +} + +async function _tryFindTarExecutablePathAsync(): Promise { + if (process.platform === 'win32') { + // If we're running on Windows, first try to use the OOB tar executable. If + // we're running in the Git Bash, the tar executable on the PATH doesn't handle + // Windows file paths correctly. + // eslint-disable-next-line dot-notation + const windowsFolderPath: string | undefined = process.env['WINDIR']; + if (windowsFolderPath) { + const defaultWindowsTarExecutablePath: string = `${windowsFolderPath}\\system32\\tar.exe`; + if (await FileSystem.existsAsync(defaultWindowsTarExecutablePath)) { + return defaultWindowsTarExecutablePath; + } + } + } + + return Executable.tryResolve('tar'); +} diff --git a/libraries/package-extractor/src/index.ts b/libraries/package-extractor/src/index.ts index 564800a2f3c..de9077fdd83 100644 --- a/libraries/package-extractor/src/index.ts +++ b/libraries/package-extractor/src/index.ts @@ -13,3 +13,10 @@ export { } from './PackageExtractor'; export type { ILinkInfo } from './SymlinkAnalyzer'; + +export { + TarExecutable, + type ITarOptionsBase, + type IUntarOptions, + type ICreateArchiveOptions +} from './TarExecutable'; diff --git a/libraries/package-extractor/src/test/ArchiveManager.test.ts b/libraries/package-extractor/src/test/ArchiveManager.test.ts index 76e51436567..707f34af277 100644 --- a/libraries/package-extractor/src/test/ArchiveManager.test.ts +++ b/libraries/package-extractor/src/test/ArchiveManager.test.ts @@ -1,16 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import path from 'node:path'; - import JSZip from 'jszip'; import * as tar from 'tar'; -import { FileSystem, Path, PosixModeBits } from '@rushstack/node-core-library'; +import { FileSystem, type FileSystemStats } from '@rushstack/node-core-library'; import { Terminal, StringBufferTerminalProvider } from '@rushstack/terminal'; import { ArchiveManager } from '../ArchiveManager'; import { AssetHandler } from '../AssetHandler'; import { SymlinkAnalyzer } from '../SymlinkAnalyzer'; +import { TarExecutable } from '../TarExecutable'; interface ITarEntry { type: string; @@ -37,28 +36,29 @@ async function readTarAsync(archivePath: string): Promise } describe(ArchiveManager.name, () => { - const testFolder: string = path.resolve(__dirname, '../../test-output/archives'); - const sourceFolder: string = path.join(testFolder, 'source'); - const sourceFile: string = path.join(sourceFolder, 'input.bin'); - const binaryContent: Buffer = Buffer.from([0, 1, 127, 128, 255]); + const testFolder: string = `${__dirname}/../../test-output/archives`; + const sourceFolder: string = `${__dirname}/../../src/test/fixtures/archive`; + const sourceFile: string = `${sourceFolder}/input.txt`; + let fileContent: Buffer; + let generatedContent: string; const terminal: Terminal = new Terminal(new StringBufferTerminalProvider()); beforeAll(async () => { await FileSystem.ensureEmptyFolderAsync(testFolder); - await FileSystem.writeFileAsync(sourceFile, binaryContent, { ensureFolderExists: true }); - await FileSystem.changePosixModeBitsAsync( - sourceFile, - // eslint-disable-next-line no-bitwise - PosixModeBits.AllRead | PosixModeBits.UserWrite | PosixModeBits.GroupWrite | PosixModeBits.AllExecute - ); + fileContent = await FileSystem.readFileToBufferAsync(sourceFile); + generatedContent = await FileSystem.readFileAsync(`${sourceFolder}/generated.txt`); + }); + + afterEach(() => { + jest.restoreAllMocks(); }); it.each(['.tar', '.tar.gz', '.tgz'])('creates %s archives with and without copying assets', async (ext) => { for (const createArchiveOnly of [false, true]) { - const targetRootFolder: string = path.join(testFolder, `${ext.slice(1)}-${createArchiveOnly}`); + const targetRootFolder: string = `${testFolder}/${ext.slice(1)}-${createArchiveOnly}`; await FileSystem.ensureFolderAsync(targetRootFolder); - const archiveFilePath: string = path.join(targetRootFolder, `deploy${ext}`); - const targetFilePath: string = path.join(targetRootFolder, 'nested', 'input.bin'); + const archiveFilePath: string = `${targetRootFolder}/deploy${ext}`; + const targetFilePath: string = `${targetRootFolder}/nested/input.txt`; const handler: AssetHandler = new AssetHandler({ terminal, mainProjectName: 'test', @@ -74,8 +74,8 @@ describe(ArchiveManager.name, () => { await handler.includeAssetAsync({ sourceFilePath: sourceFile, targetFilePath }); await handler.includeAssetAsync({ - sourceFileContent: 'generated content', - targetFilePath: path.join(targetRootFolder, 'generated.txt') + sourceFileContent: generatedContent, + targetFilePath: `${targetRootFolder}/generated.txt` }); await handler.finalizeAsync(); @@ -87,14 +87,19 @@ describe(ArchiveManager.name, () => { expect(archiveContent.subarray(0, 2)).toEqual(Buffer.from([0x1f, 0x8b])); } - expect([...entries.keys()].sort()).toEqual(['generated.txt', 'nested/input.bin']); - expect(entries.get('nested/input.bin')?.data).toEqual(binaryContent); - expect(entries.get('nested/input.bin')).toMatchObject({ - type: 'File', - // eslint-disable-next-line no-bitwise - mode: (await FileSystem.getStatisticsAsync(sourceFile)).mode & 0o7777 + expect([...entries.keys()].sort()).toEqual(['generated.txt', 'nested/input.txt']); + expect(entries.get('nested/input.txt')?.data).toEqual(fileContent); + expect(entries.get('nested/input.txt')).toMatchObject({ + type: 'File' }); - expect(entries.get('generated.txt')?.data.toString()).toBe('generated content'); + if (process.platform !== 'win32') { + expect(entries.get('nested/input.txt')?.mode).toBe( + // eslint-disable-next-line no-bitwise + (await FileSystem.getStatisticsAsync(sourceFile)).mode & 0o7777 + ); + } + + expect(entries.get('generated.txt')?.data.toString()).toBe(generatedContent); expect(await FileSystem.existsAsync(targetFilePath)).toBe(!createArchiveOnly); if (createArchiveOnly) { expect(await FileSystem.readFolderItemNamesAsync(targetRootFolder)).toEqual([`deploy${ext}`]); @@ -102,36 +107,64 @@ describe(ArchiveManager.name, () => { } }); - const testSymlinks: typeof it = process.platform === 'win32' ? it.skip : it; - testSymlinks.each(['.tar', '.tar.gz', '.tgz'])('preserves symbolic links in %s archives', async (ext) => { - const linkPath: string = path.join(sourceFolder, `link${ext}`); - await FileSystem.createSymbolicLinkFileAsync({ - newLinkPath: linkPath, - linkTargetPath: 'input.bin' - }); - const archiveFilePath: string = path.join(testFolder, `links${ext}`); + it.each(['.tar', '.tar.gz', '.tgz'])('preserves symbolic links in %s archives', async (ext) => { + const linkPath: string = `${sourceFolder}/link${ext}`; + const stats: FileSystemStats = await FileSystem.getStatisticsAsync(sourceFile); + jest.spyOn(stats, 'isSymbolicLink').mockReturnValue(true); + jest.spyOn(FileSystem, 'readLinkAsync').mockResolvedValue('../input.txt'); + const archiveFilePath: string = `${testFolder}/links${ext}`; const manager: ArchiveManager = new ArchiveManager(archiveFilePath); - await manager.addToArchiveAsync({ filePath: linkPath, archivePath: 'nested\\link' }); + await manager.addToArchiveAsync({ filePath: linkPath, archivePath: 'nested\\link', stats }); await manager.createArchiveAsync(archiveFilePath); const entries: Map = await readTarAsync(archiveFilePath); expect(entries.get('nested/link')).toMatchObject({ type: 'SymbolicLink', - linkpath: Path.convertToSlashes(await FileSystem.readLinkAsync(linkPath)), + linkpath: '../input.txt', data: Buffer.alloc(0) }); }); it('continues to create ZIP archives', async () => { - const archiveFilePath: string = path.join(testFolder, 'deploy.zip'); + const archiveFilePath: string = `${testFolder}/deploy.zip`; const manager: ArchiveManager = new ArchiveManager(archiveFilePath); - await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'nested\\input.bin' }); - await manager.addToArchiveAsync({ fileData: 'generated content', archivePath: 'generated.txt' }); + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'nested\\input.txt' }); + await manager.addToArchiveAsync({ fileData: generatedContent, archivePath: 'generated.txt' }); await manager.createArchiveAsync(archiveFilePath); const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); - expect(await zip.file('nested/input.bin')?.async('nodebuffer')).toEqual(binaryContent); - expect(await zip.file('generated.txt')?.async('string')).toBe('generated content'); + expect(await zip.file('nested/input.txt')?.async('nodebuffer')).toEqual(fileContent); + expect(await zip.file('generated.txt')?.async('string')).toBe(generatedContent); + }); + + it('preserves executable permissions for in-memory tar entries', async () => { + const archiveFilePath: string = `${testFolder}/permissions.tar`; + const executablePath: string = `${sourceFolder}/executable.sh`; + const stats: FileSystemStats = await FileSystem.getStatisticsAsync(executablePath); + stats.mode = 0o100775; + const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + await manager.addToArchiveAsync({ filePath: executablePath, archivePath: 'executable.sh', stats }); + await manager.createArchiveAsync(archiveFilePath); + expect((await readTarAsync(archiveFilePath)).get('executable.sh')?.mode).toBe(0o775); + }); + + it('prefers native tar for materialized files', async () => { + const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + if (!nativeTar) { + throw new Error('Native tar is required for the native-tar test'); + } + + jest.spyOn(TarExecutable, 'tryInitializeAsync').mockResolvedValue(nativeTar); + const createSpy = jest.spyOn(nativeTar, 'tryCreateArchiveAsync'); + const archiveFilePath: string = `${testFolder}/native.tar`; + const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); + await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder }); + expect(createSpy).toHaveBeenCalledWith( + expect.objectContaining({ baseFolderPath: sourceFolder, paths: ['input.txt'], gzip: false }) + ); + expect((await readTarAsync(archiveFilePath)).get('input.txt')?.data).toEqual(fileContent); + expect(await FileSystem.existsAsync(`${archiveFilePath}.log`)).toBe(false); }); it('rejects unsupported extensions', () => { @@ -139,9 +172,50 @@ describe(ArchiveManager.name, () => { }); it('reports archive write failures', async () => { - const archiveFilePath: string = path.join(testFolder, 'missing', 'deploy.tgz'); + const archiveFilePath: string = `${testFolder}/missing/deploy.tgz`; const manager: ArchiveManager = new ArchiveManager(archiveFilePath); await manager.addToArchiveAsync({ fileData: 'content', archivePath: 'file.txt' }); await expect(manager.createArchiveAsync(archiveFilePath)).rejects.toThrow(); }); + + it.each(['unavailable', 'incompatible'])('falls back when native tar is %s', async (reason) => { + const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + const initializeSpy = jest.spyOn(TarExecutable, 'tryInitializeAsync'); + if (reason === 'unavailable') { + initializeSpy.mockResolvedValue(undefined); + } else { + if (!nativeTar) { + throw new Error('Native tar is required for the incompatible-tar test'); + } + + jest.spyOn(nativeTar, 'tryCreateArchiveAsync').mockResolvedValue(1); + initializeSpy.mockResolvedValue(nativeTar); + } + + const archiveFilePath: string = `${testFolder}/fallback-${reason}.tgz`; + const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); + await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder }); + expect(initializeSpy).toHaveBeenCalled(); + expect((await readTarAsync(archiveFilePath)).get('input.txt')?.data).toEqual(fileContent); + }); + + it('handles a native executable that exits before reading the file list', async () => { + const incompatibleTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync( + terminal, + process.execPath + ); + if (!incompatibleTar) { + throw new Error('The Node executable could not be located'); + } + + const exitCode: number = await incompatibleTar.tryCreateArchiveAsync({ + archivePath: `${testFolder}/incompatible.tgz`, + baseFolderPath: sourceFolder, + paths: new Array(10000).fill('input.txt'), + logFilePath: `${testFolder}/incompatible.log` + }); + expect(exitCode).not.toBe(0); + expect(await FileSystem.readFileAsync(`${testFolder}/incompatible.log`)).toContain('Exited with code'); + }); }); diff --git a/libraries/package-extractor/src/test/fixtures/archive/executable.sh b/libraries/package-extractor/src/test/fixtures/archive/executable.sh new file mode 100755 index 00000000000..59baf464cd5 --- /dev/null +++ b/libraries/package-extractor/src/test/fixtures/archive/executable.sh @@ -0,0 +1,2 @@ +#!/bin/sh +echo "Archive executable fixture." diff --git a/libraries/package-extractor/src/test/fixtures/archive/generated.txt b/libraries/package-extractor/src/test/fixtures/archive/generated.txt new file mode 100644 index 00000000000..9a4ea740cee --- /dev/null +++ b/libraries/package-extractor/src/test/fixtures/archive/generated.txt @@ -0,0 +1 @@ +Generated archive content. diff --git a/libraries/package-extractor/src/test/fixtures/archive/input.txt b/libraries/package-extractor/src/test/fixtures/archive/input.txt new file mode 100644 index 00000000000..d3773fd38f9 --- /dev/null +++ b/libraries/package-extractor/src/test/fixtures/archive/input.txt @@ -0,0 +1 @@ +Archive fixture content. diff --git a/libraries/rush-lib/src/utilities/TarExecutable.ts b/libraries/rush-lib/src/utilities/TarExecutable.ts index cfad7649f2f..2e8e2d41037 100644 --- a/libraries/rush-lib/src/utilities/TarExecutable.ts +++ b/libraries/rush-lib/src/utilities/TarExecutable.ts @@ -1,221 +1,48 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import * as path from 'node:path'; -import type { ChildProcess } from 'node:child_process'; -import events from 'node:events'; - -import { Executable, FileSystem, FileWriter } from '@rushstack/node-core-library'; +import { + TarExecutable as SharedTarExecutable, + type ICreateArchiveOptions as ISharedCreateArchiveOptions, + type IUntarOptions +} from '@rushstack/package-extractor'; import type { ITerminal } from '@rushstack/terminal'; import type { RushConfigurationProject } from '../api/RushConfigurationProject'; import { EnvironmentConfiguration } from '../api/EnvironmentConfiguration'; -import { IS_WINDOWS } from './executionUtilities'; - -export interface ITarOptionsBase { - logFilePath: string; -} -export interface IUntarOptions extends ITarOptionsBase { - archivePath: string; - outputFolderPath: string; -} +export type { IUntarOptions }; -export interface ICreateArchiveOptions extends ITarOptionsBase { - archivePath: string; - paths: string[]; +export interface ICreateArchiveOptions extends Omit { project: RushConfigurationProject; - /** - * The folder that `paths` are relative to, and that the archive's members are named from. Defaults to the - * project folder. - */ + /** The folder that paths are relative to. Defaults to the project folder. */ baseFolderPath?: string; - /** When aborted, kills the tar process, which then exits with a nonzero code. */ - abortSignal?: AbortSignal; } export class TarExecutable { - #tarExecutablePath: string; + readonly #tarExecutable: SharedTarExecutable; - private constructor(tarExecutablePath: string) { - this.#tarExecutablePath = tarExecutablePath; + private constructor(tarExecutable: SharedTarExecutable) { + this.#tarExecutable = tarExecutable; } public static async tryInitializeAsync(terminal: ITerminal): Promise { - terminal.writeVerboseLine('Trying to find "tar" binary'); - const tarExecutablePath: string | undefined = - EnvironmentConfiguration.tarBinaryPath || (await _tryFindTarExecutablePathAsync()); - if (!tarExecutablePath) { - terminal.writeVerboseLine('"tar" was not found on the PATH'); - return undefined; - } else { - terminal.writeVerboseLine(`Using "tar" binary: ${tarExecutablePath}`); - return new TarExecutable(tarExecutablePath); - } + const tarExecutable: SharedTarExecutable | undefined = await SharedTarExecutable.tryInitializeAsync( + terminal, + EnvironmentConfiguration.tarBinaryPath + ); + return tarExecutable ? new TarExecutable(tarExecutable) : undefined; } - /** - * @returns - * The "tar" exit code - */ public async tryUntarAsync(options: IUntarOptions): Promise { - return await this.#spawnTarWithLoggingAsync( - // These parameters are chosen for compatibility with the very primitive bsdtar 3.3.2 shipped with Windows 10. - [ - // [Windows bsdtar 3.3.2] Extract: tar -x [options] [] - '-x', - // [Windows bsdtar 3.3.2] -m Don't restore modification times - '-m', - // [Windows bsdtar 3.3.2] -f Location of archive (default \\.\tape0) - '-f', - options.archivePath - ], - options.outputFolderPath, - options.logFilePath - ); + return await this.#tarExecutable.tryUntarAsync(options); } - /** - * @returns - * The "tar" exit code - */ public async tryCreateArchiveFromProjectPathsAsync(options: ICreateArchiveOptions): Promise { - const { project, archivePath, paths, logFilePath, baseFolderPath, abortSignal } = options; - - const tarInput: string = paths.join('\n'); - - // On Windows, tar.exe will report a "Failed to clean up compressor" error if the target folder - // does not exist (GitHub #2622) - await FileSystem.ensureFolderAsync(path.dirname(archivePath)); - - const tarExitCode: number = await this.#spawnTarWithLoggingAsync( - // These parameters are chosen for compatibility with the very primitive bsdtar 3.3.2 shipped with Windows 10. - [ - // [Windows bsdtar 3.3.2] -c Create - '-c', - // [Windows bsdtar 3.3.2] -f Location of archive (default \\.\tape0) - '-f', - archivePath, - // [Windows bsdtar 3.3.2] -z, -j, -J, --lzma Compress archive with gzip/bzip2/xz/lzma - '-z', - // [GNU tar 1.33] -T, --files-from=FILE get names to extract or create from FILE - // - // Windows bsdtar does not document this parameter, but seems to accept it. - '--files-from=-' - ], - baseFolderPath ?? project.projectFolder, - logFilePath, - tarInput, - abortSignal - ); - - return tarExitCode; - } - - async #spawnTarWithLoggingAsync( - args: string[], - currentWorkingDirectory: string, - logFilePath: string, - input?: string, - abortSignal?: AbortSignal - ): Promise { - // Runs "tar" with the specified args and logs its output to the specified location. - // The log file looks like this: - // - // Windows: - // Start time: Mon Apr 19 2021 13:06:40 GMT-0700 (Pacific Daylight Time) - // Invoking "C:\WINDOWS\system32\tar.exe -x -f E:\rush-cache\d18105f7f83eb610b468be4e2421681f4a52e44d" - // - // ======= BEGIN PROCESS OUTPUT ======= - // [stdout] - // [stderr] - // ======== END PROCESS OUTPUT ======== - // - // Exited with code "0" - // - // Linux: - // Start time: Mon Apr 19 2021 13:06:40 GMT-0700 (Pacific Daylight Time) - // Invoking "/bin/tar -x -f /home/username/rush-cache/d18105f7f83eb610b468be4e2421681f4a52e44d" - // - // ======= BEGIN PROCESS OUTPUT ======= - // [stdout] - // [stderr] - // ======== END PROCESS OUTPUT ======== - // - // Exited with code "0" - - await FileSystem.ensureFolderAsync(path.dirname(logFilePath)); - const fileWriter: FileWriter = FileWriter.open(logFilePath); - fileWriter.write( - [ - `Start time: ${new Date().toString()}`, - `Invoking "${this.#tarExecutablePath} ${args.join(' ')}"`, - '', - `======= BEGIN PROCESS INPUT ======`, - input || '', - '======== END PROCESS INPUT =======', - '======= BEGIN PROCESS OUTPUT =======', - '' - ].join('\n') - ); - - const childProcess: ChildProcess = Executable.spawn(this.#tarExecutablePath, args, { - currentWorkingDirectory: currentWorkingDirectory + const { project, baseFolderPath, ...rest } = options; + return await this.#tarExecutable.tryCreateArchiveAsync({ + ...rest, + baseFolderPath: baseFolderPath ?? project.projectFolder }); - const kill: () => void = () => childProcess.kill(); - if (abortSignal?.aborted) { - kill(); - } else { - abortSignal?.addEventListener('abort', kill, { once: true }); - } - - childProcess.stdout!.on('data', (chunk) => fileWriter.write(`[stdout] ${chunk}`)); - childProcess.stderr!.on('data', (chunk) => fileWriter.write(`[stderr] ${chunk}`)); - - if (input !== undefined) { - if (abortSignal) { - // A tar process that was killed may have closed its end of the pipe already; its exit code reports that. - childProcess.stdin!.on('error', () => undefined); - } - childProcess.stdin!.write(input, 'utf-8'); - childProcess.stdin!.end(); - } - - // Wait for process to exit and all streams to close - let tarExitCode: number | null; - let tarSignal: NodeJS.Signals | null; - try { - [tarExitCode, tarSignal] = await events.once(childProcess, 'close'); - } finally { - abortSignal?.removeEventListener('abort', kill); - } - - fileWriter.write( - ['======== END PROCESS OUTPUT ========', '', `Exited with code "${tarExitCode ?? tarSignal}"`].join( - '\n' - ) - ); - fileWriter.close(); - - // A tar process that was killed has no exit code. - return tarExitCode ?? 1; - } -} - -async function _tryFindTarExecutablePathAsync(): Promise { - if (IS_WINDOWS) { - // If we're running on Windows, first try to use the OOB tar executable. If - // we're running in the Git Bash, the tar executable on the PATH doesn't handle - // Windows file paths correctly. - // eslint-disable-next-line dot-notation - const windowsFolderPath: string | undefined = process.env['WINDIR']; - if (windowsFolderPath) { - const defaultWindowsTarExecutablePath: string = `${windowsFolderPath}\\system32\\tar.exe`; - if (await FileSystem.existsAsync(defaultWindowsTarExecutablePath)) { - return defaultWindowsTarExecutablePath; - } - } } - - return Executable.tryResolve('tar'); } From 00e49487fe6808ceafd2a620e7854cb2054dc264 Mon Sep 17 00:00:00 2001 From: iclanton <5010588+iclanton@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:54:15 +0000 Subject: [PATCH 3/8] fixup! fixup! [rush] Add tarball support to deploy archives Memoize native tar discovery, separate archive format detection, and remove the Rush adapter in favor of direct shared callers. Extract JavaScript tar creation and use it for build cache creation fallback, retaining atomic publication and abort handling. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../rush/deploy-tarballs_2026-11-25.json | 5 + .../deploy-tarballs_2026-11-25.json | 5 + common/reviews/api/package-extractor.api.md | 38 ++++++ libraries/package-extractor/README.md | 4 + .../package-extractor/src/ArchiveManager.ts | 59 +++------ .../package-extractor/src/AssetHandler.ts | 2 +- libraries/package-extractor/src/TarArchive.ts | 89 ++++++++++++++ .../package-extractor/src/TarExecutable.ts | 34 ++++-- libraries/package-extractor/src/index.ts | 7 ++ .../src/test/ArchiveManager.test.ts | 44 +++++-- .../logic/buildCache/OperationBuildCache.ts | 115 ++++++++++-------- .../test/OperationBuildCache.test.ts | 2 +- .../OperationBuildCacheDeferredWrites.test.ts | 12 +- .../test/OperationBuildCacheReceipt.test.ts | 42 +++++-- .../buildCache/test/StagedRestore.test.ts | 2 +- .../rush-lib/src/utilities/TarExecutable.ts | 48 -------- .../src/utilities/test/TarExecutable.test.ts | 17 +-- 17 files changed, 338 insertions(+), 187 deletions(-) create mode 100644 libraries/package-extractor/src/TarArchive.ts delete mode 100644 libraries/rush-lib/src/utilities/TarExecutable.ts diff --git a/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json index 2a6f5662ec7..ee6be83ff7a 100644 --- a/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json +++ b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json @@ -4,6 +4,11 @@ "packageName": "@microsoft/rush", "comment": "Add support for `.tar`, `.tar.gz`, and `.tgz` archives to `rush deploy --create-archive`.", "type": "minor" + }, + { + "packageName": "@microsoft/rush", + "comment": "Use the shared JavaScript tar writer when native tar is unavailable or fails while creating a build cache entry.", + "type": "patch" } ], "packageName": "@microsoft/rush" diff --git a/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json index 0773a9f72f0..d537ec9fd6f 100644 --- a/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json +++ b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json @@ -4,6 +4,11 @@ "packageName": "@rushstack/package-extractor", "comment": "Support `.tar`, `.tar.gz`, and `.tgz` deployment archives, including archive-only extraction, preferring native tar when assets are available on disk.", "type": "minor" + }, + { + "packageName": "@rushstack/package-extractor", + "comment": "Expose shared native tar discovery and JavaScript archive creation for use by Rush build caching.", + "type": "minor" } ], "packageName": "@rushstack/package-extractor" diff --git a/common/reviews/api/package-extractor.api.md b/common/reviews/api/package-extractor.api.md index 690a82f0fc4..dab0b03edfa 100644 --- a/common/reviews/api/package-extractor.api.md +++ b/common/reviews/api/package-extractor.api.md @@ -87,6 +87,36 @@ export interface IProjectInfoJson { projectName: string; } +// @beta +export interface ITarArchiveEntry { + // (undocumented) + archivePath: string; + // (undocumented) + data: Buffer | string; + // (undocumented) + isSymbolicLink: boolean; + // (undocumented) + permissions: number; +} + +// @beta +export interface ITarArchiveFromPathsOptions extends ITarArchiveOptions { + // (undocumented) + baseFolderPath: string; + // (undocumented) + paths: string[]; +} + +// @beta +export interface ITarArchiveOptions { + // (undocumented) + abortSignal?: AbortSignal; + // (undocumented) + archivePath: string; + // (undocumented) + gzip?: boolean; +} + // @beta (undocumented) export interface ITarOptionsBase { // (undocumented) @@ -111,6 +141,14 @@ export class PackageExtractor { static getPackageIncludedFilesAsync(packageRootPath: string): Promise; } +// @beta +export class TarArchive { + // (undocumented) + static createFromEntriesAsync(options: ITarArchiveOptions, entries: Iterable): Promise; + // (undocumented) + static createFromPathsAsync(options: ITarArchiveFromPathsOptions): Promise; +} + // @beta export class TarExecutable { // (undocumented) diff --git a/libraries/package-extractor/README.md b/libraries/package-extractor/README.md index a8d5b862141..9fafae6fcc5 100644 --- a/libraries/package-extractor/README.md +++ b/libraries/package-extractor/README.md @@ -8,6 +8,10 @@ Tar archives use the native `tar` executable when the deployed files are availab falling back to JavaScript when it is unavailable or fails. Archive-only deployments use JavaScript so generated assets do not need to be staged on disk. +`TarExecutable` memoizes native executable discovery. `TarArchive` provides JavaScript +archive creation from filesystem paths or in-memory entries; Rush's build-cache writer +also uses it when native tar is unavailable or fails. + ## Links - [CHANGELOG.md]( diff --git a/libraries/package-extractor/src/ArchiveManager.ts b/libraries/package-extractor/src/ArchiveManager.ts index 90b3312e127..9ceac47a909 100644 --- a/libraries/package-extractor/src/ArchiveManager.ts +++ b/libraries/package-extractor/src/ArchiveManager.ts @@ -1,20 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { pipeline } from 'node:stream/promises'; - import JSZip from 'jszip'; -import * as tar from 'tar'; - -import { - FileSystem, - type FileSystemStats, - type FileSystemWriteStream, - Path -} from '@rushstack/node-core-library'; + +import { FileSystem, type FileSystemStats, Path } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; import { TarExecutable } from './TarExecutable'; +import { TarArchive } from './TarArchive'; + +export type ArchiveFormat = 'zip' | 'tar' | 'tgz'; // 755 are default permissions to allow read/write/execute for owner and read/execute for group and others. const DEFAULT_FILE_PERMISSIONS: number = 0o755; @@ -44,16 +39,20 @@ export interface ICreateArchiveOptions { } export class ArchiveManager { - readonly #archiveFormat: 'zip' | 'tar' | 'tgz'; + readonly #archiveFormat: ArchiveFormat; readonly #entries: Map = new Map(); - public constructor(archiveFilePath: string) { + public constructor(archiveFormat: ArchiveFormat) { + this.#archiveFormat = archiveFormat; + } + + public static getArchiveFormat(archiveFilePath: string): ArchiveFormat { if (archiveFilePath.endsWith('.zip')) { - this.#archiveFormat = 'zip'; + return 'zip'; } else if (archiveFilePath.endsWith('.tar')) { - this.#archiveFormat = 'tar'; + return 'tar'; } else if (archiveFilePath.endsWith('.tar.gz') || archiveFilePath.endsWith('.tgz')) { - this.#archiveFormat = 'tgz'; + return 'tgz'; } else { throw new Error('Supported archive file extensions: .zip, .tar, .tar.gz, .tgz.'); } @@ -137,32 +136,10 @@ export class ArchiveManager { ); } - const pack: tar.Pack = new tar.Pack({ gzip: this.#archiveFormat === 'tgz' }); - const output: FileSystemWriteStream = await FileSystem.createWriteStreamAsync(archiveFilePath); - const archivePromise: Promise = pipeline(pack, output); - - for (const [archivePath, { data, permissions, isSymbolicLink }] of this.#entries) { - const content: Buffer = isSymbolicLink - ? Buffer.alloc(0) - : typeof data === 'string' - ? Buffer.from(data) - : data; - // ReadEntry allows generated assets to be archived without staging them on disk. - const entry: tar.ReadEntry = new tar.ReadEntry( - new tar.Header({ - path: archivePath, - mode: permissions, - type: isSymbolicLink ? 'SymbolicLink' : 'File', - linkpath: isSymbolicLink ? Path.convertToSlashes(data.toString()) : undefined, - size: content.length - }) - ); - pack.add(entry); - entry.end(content); - } - - pack.end(); - await archivePromise; + await TarArchive.createFromEntriesAsync( + { archivePath: archiveFilePath, gzip: this.#archiveFormat === 'tgz' }, + [...this.#entries].map(([archivePath, entry]) => ({ archivePath, ...entry })) + ); } } } diff --git a/libraries/package-extractor/src/AssetHandler.ts b/libraries/package-extractor/src/AssetHandler.ts index 35c8bfa8564..308075f73d5 100644 --- a/libraries/package-extractor/src/AssetHandler.ts +++ b/libraries/package-extractor/src/AssetHandler.ts @@ -72,7 +72,7 @@ export class AssetHandler { this.#symlinkAnalyzer = symlinkAnalyzer; if (createArchiveFilePath) { this.#archiveFilePath = path.resolve(targetRootFolder, createArchiveFilePath); - this.#archiveManager = new ArchiveManager(this.#archiveFilePath); + this.#archiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(this.#archiveFilePath)); } if (createArchiveOnly && !this.#archiveManager) { throw new Error('createArchiveOnly cannot be true if createArchiveFilePath is not provided'); diff --git a/libraries/package-extractor/src/TarArchive.ts b/libraries/package-extractor/src/TarArchive.ts new file mode 100644 index 00000000000..fbe5491aed8 --- /dev/null +++ b/libraries/package-extractor/src/TarArchive.ts @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import { pipeline } from 'node:stream/promises'; + +import * as tar from 'tar'; + +import { FileSystem, type FileSystemWriteStream, Path } from '@rushstack/node-core-library'; + +/** + * An in-memory tar archive member. + * @beta + */ +export interface ITarArchiveEntry { + archivePath: string; + data: Buffer | string; + permissions: number; + isSymbolicLink: boolean; +} + +/** + * Options for JavaScript tar archive creation. + * @beta + */ +export interface ITarArchiveOptions { + archivePath: string; + gzip?: boolean; + abortSignal?: AbortSignal; +} + +/** + * Options for archiving files from disk. + * @beta + */ +export interface ITarArchiveFromPathsOptions extends ITarArchiveOptions { + baseFolderPath: string; + paths: string[]; +} + +/** + * JavaScript tar creation shared by deployment and build caching. + * @beta + */ +export class TarArchive { + public static async createFromPathsAsync(options: ITarArchiveFromPathsOptions): Promise { + const { baseFolderPath, paths, gzip = true } = options; + options.abortSignal?.throwIfAborted(); + const pack: tar.Pack = tar.create({ cwd: baseFolderPath, gzip, strict: true, noDirRecurse: true }, paths); + await writeAsync(pack, options); + } + + public static async createFromEntriesAsync( + options: ITarArchiveOptions, + entries: Iterable + ): Promise { + const { gzip = true } = options; + options.abortSignal?.throwIfAborted(); + const pack: tar.Pack = new tar.Pack({ gzip }); + const writePromise: Promise = writeAsync(pack, options); + for (const { archivePath, data, permissions, isSymbolicLink } of entries) { + const content: Buffer = isSymbolicLink + ? Buffer.alloc(0) + : typeof data === 'string' + ? Buffer.from(data) + : data; + // ReadEntry archives generated assets without staging them on disk. + const entry: tar.ReadEntry = new tar.ReadEntry( + new tar.Header({ + path: archivePath, + mode: permissions, + type: isSymbolicLink ? 'SymbolicLink' : 'File', + linkpath: isSymbolicLink ? Path.convertToSlashes(data.toString()) : undefined, + size: content.length + }) + ); + pack.add(entry); + entry.end(content); + } + + pack.end(); + await writePromise; + } +} + +async function writeAsync(pack: tar.Pack, options: ITarArchiveOptions): Promise { + const { archivePath, abortSignal } = options; + const output: FileSystemWriteStream = FileSystem.createWriteStream(archivePath); + await pipeline(pack, output, { signal: abortSignal }); +} diff --git a/libraries/package-extractor/src/TarExecutable.ts b/libraries/package-extractor/src/TarExecutable.ts index 0cb4e12cca3..8355b30d300 100644 --- a/libraries/package-extractor/src/TarExecutable.ts +++ b/libraries/package-extractor/src/TarExecutable.ts @@ -8,6 +8,8 @@ import events from 'node:events'; import { Executable, FileSystem, FileWriter } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; +const initializations: Map> = new Map(); + /** * @beta */ @@ -52,15 +54,24 @@ export class TarExecutable { terminal: ITerminal, tarBinaryPath?: string ): Promise { - terminal.writeVerboseLine('Trying to find "tar" binary'); - const tarExecutablePath: string | undefined = tarBinaryPath || (await _tryFindTarExecutablePathAsync()); - if (!tarExecutablePath) { - terminal.writeVerboseLine('"tar" was not found on the PATH'); - return undefined; - } else { - terminal.writeVerboseLine(`Using "tar" binary: ${tarExecutablePath}`); - return new TarExecutable(tarExecutablePath); + let initialization: Promise | undefined = initializations.get(tarBinaryPath); + if (!initialization) { + initialization = (async () => { + terminal.writeVerboseLine('Trying to find "tar" binary'); + const tarExecutablePath: string | undefined = + tarBinaryPath || (await _tryFindTarExecutablePathAsync()); + if (!tarExecutablePath) { + terminal.writeVerboseLine('"tar" was not found on the PATH'); + return undefined; + } else { + terminal.writeVerboseLine(`Using "tar" binary: ${tarExecutablePath}`); + return new TarExecutable(tarExecutablePath); + } + })(); + initializations.set(tarBinaryPath, initialization); } + + return await initialization; } /** @@ -68,6 +79,7 @@ export class TarExecutable { * The "tar" exit code */ public async tryUntarAsync(options: IUntarOptions): Promise { + const { archivePath, outputFolderPath, logFilePath } = options; return await this.#spawnTarWithLoggingAsync( // These parameters are chosen for compatibility with the very primitive bsdtar 3.3.2 shipped with Windows 10. [ @@ -77,10 +89,10 @@ export class TarExecutable { '-m', // [Windows bsdtar 3.3.2] -f Location of archive (default \\.\tape0) '-f', - options.archivePath + archivePath ], - options.outputFolderPath, - options.logFilePath + outputFolderPath, + logFilePath ); } diff --git a/libraries/package-extractor/src/index.ts b/libraries/package-extractor/src/index.ts index de9077fdd83..0f127a993b8 100644 --- a/libraries/package-extractor/src/index.ts +++ b/libraries/package-extractor/src/index.ts @@ -14,6 +14,13 @@ export { export type { ILinkInfo } from './SymlinkAnalyzer'; +export { + TarArchive, + type ITarArchiveEntry, + type ITarArchiveOptions, + type ITarArchiveFromPathsOptions +} from './TarArchive'; + export { TarExecutable, type ITarOptionsBase, diff --git a/libraries/package-extractor/src/test/ArchiveManager.test.ts b/libraries/package-extractor/src/test/ArchiveManager.test.ts index 707f34af277..e4f898dff1e 100644 --- a/libraries/package-extractor/src/test/ArchiveManager.test.ts +++ b/libraries/package-extractor/src/test/ArchiveManager.test.ts @@ -10,6 +10,7 @@ import { ArchiveManager } from '../ArchiveManager'; import { AssetHandler } from '../AssetHandler'; import { SymlinkAnalyzer } from '../SymlinkAnalyzer'; import { TarExecutable } from '../TarExecutable'; +import { TarArchive } from '../TarArchive'; interface ITarEntry { type: string; @@ -113,7 +114,7 @@ describe(ArchiveManager.name, () => { jest.spyOn(stats, 'isSymbolicLink').mockReturnValue(true); jest.spyOn(FileSystem, 'readLinkAsync').mockResolvedValue('../input.txt'); const archiveFilePath: string = `${testFolder}/links${ext}`; - const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: linkPath, archivePath: 'nested\\link', stats }); await manager.createArchiveAsync(archiveFilePath); @@ -127,7 +128,7 @@ describe(ArchiveManager.name, () => { it('continues to create ZIP archives', async () => { const archiveFilePath: string = `${testFolder}/deploy.zip`; - const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'nested\\input.txt' }); await manager.addToArchiveAsync({ fileData: generatedContent, archivePath: 'generated.txt' }); await manager.createArchiveAsync(archiveFilePath); @@ -142,7 +143,7 @@ describe(ArchiveManager.name, () => { const executablePath: string = `${sourceFolder}/executable.sh`; const stats: FileSystemStats = await FileSystem.getStatisticsAsync(executablePath); stats.mode = 0o100775; - const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: executablePath, archivePath: 'executable.sh', stats }); await manager.createArchiveAsync(archiveFilePath); expect((await readTarAsync(archiveFilePath)).get('executable.sh')?.mode).toBe(0o775); @@ -157,7 +158,7 @@ describe(ArchiveManager.name, () => { jest.spyOn(TarExecutable, 'tryInitializeAsync').mockResolvedValue(nativeTar); const createSpy = jest.spyOn(nativeTar, 'tryCreateArchiveAsync'); const archiveFilePath: string = `${testFolder}/native.tar`; - const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder }); expect(createSpy).toHaveBeenCalledWith( @@ -168,12 +169,12 @@ describe(ArchiveManager.name, () => { }); it('rejects unsupported extensions', () => { - expect(() => new ArchiveManager('deploy.gz')).toThrow('Supported archive file extensions'); + expect(() => ArchiveManager.getArchiveFormat('deploy.gz')).toThrow('Supported archive file extensions'); }); it('reports archive write failures', async () => { const archiveFilePath: string = `${testFolder}/missing/deploy.tgz`; - const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ fileData: 'content', archivePath: 'file.txt' }); await expect(manager.createArchiveAsync(archiveFilePath)).rejects.toThrow(); }); @@ -193,7 +194,7 @@ describe(ArchiveManager.name, () => { } const archiveFilePath: string = `${testFolder}/fallback-${reason}.tgz`; - const manager: ArchiveManager = new ArchiveManager(archiveFilePath); + const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder }); expect(initializeSpy).toHaveBeenCalled(); @@ -218,4 +219,33 @@ describe(ArchiveManager.name, () => { expect(exitCode).not.toBe(0); expect(await FileSystem.readFileAsync(`${testFolder}/incompatible.log`)).toContain('Exited with code'); }); + + it('memoizes native discovery independently for each explicit executable', async () => { + const provider: StringBufferTerminalProvider = new StringBufferTerminalProvider(); + const discoveryTerminal: Terminal = new Terminal(provider); + const executablePath: string = `${testFolder}/memoized-tar`; + const [first, second] = await Promise.all([ + TarExecutable.tryInitializeAsync(discoveryTerminal, executablePath), + TarExecutable.tryInitializeAsync(discoveryTerminal, executablePath) + ]); + expect(first).toBe(second); + expect(provider.getVerboseOutput().match(/Trying to find/g)).toHaveLength(1); + const other: TarExecutable | undefined = await TarExecutable.tryInitializeAsync( + terminal, + process.execPath + ); + expect(first).not.toBe(other); + }); + + it('cancels JavaScript tar creation', async () => { + const archivePath: string = `${testFolder}/aborted.tgz`; + await expect( + TarArchive.createFromPathsAsync({ + archivePath, + baseFolderPath: sourceFolder, + paths: ['input.txt'], + abortSignal: AbortSignal.abort() + }) + ).rejects.toMatchObject({ name: 'AbortError' }); + }); }); diff --git a/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts b/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts index bf3476fdfc3..cb921bcc506 100644 --- a/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts +++ b/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts @@ -6,13 +6,13 @@ import * as crypto from 'node:crypto'; import { FileSystem, type FolderItem, InternalError, Async, LockFile } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; +import { TarArchive, TarExecutable } from '@rushstack/package-extractor'; import type { RushConfigurationProject } from '../../api/RushConfigurationProject'; import type { BuildCacheConfiguration } from '../../api/BuildCacheConfiguration'; import type { ICloudBuildCacheProvider } from './ICloudBuildCacheProvider'; import type { FileSystemBuildCacheProvider } from './FileSystemBuildCacheProvider'; -import { TarExecutable } from '../../utilities/TarExecutable'; -import { EnvironmentVariableNames } from '../../api/EnvironmentConfiguration'; +import { EnvironmentConfiguration } from '../../api/EnvironmentConfiguration'; import type { IBaseOperationExecutionResult } from '../operations/IOperationExecutionResult'; import { OutputFolderReceipt, type PendingOutputFolderReceipt } from './OutputFolderReceipt'; import { tryRestoreThroughStagingFolderAsync } from './StagedRestore'; @@ -120,7 +120,7 @@ function _getTempLocalCacheEntryPath(finalLocalCacheEntryPath: string): string { function _tryGetTarUtility(terminal: ITerminal): Promise { if (!_tarUtilityPromise) { - _tarUtilityPromise = TarExecutable.tryInitializeAsync(terminal); + _tarUtilityPromise = TarExecutable.tryInitializeAsync(terminal, EnvironmentConfiguration.tarBinaryPath); } return _tarUtilityPromise; @@ -507,7 +507,7 @@ export class OperationBuildCache { `Caching build output folders: ${filesToCache.filteredOutputFolderNames.join(', ')}` ); - // If tar can't be found, the write below fails at once, so that the operation reports it. + // Without native tar, use the JavaScript fallback in the foreground instead of sealing outputs. if (deferredCacheEntryWrites && (await _tryGetTarUtility(terminal))) { // A restore consults the receipt only if the local cache has the entry, so a receipt for an entry that is not // written yet is never consulted if the write is dropped or fails. But an older entry for the same cache ID, @@ -583,58 +583,75 @@ export class OperationBuildCache { let localCacheEntryPath: string | undefined; const tarUtility: TarExecutable | undefined = await _tryGetTarUtility(terminal); - if (tarUtility) { - const finalLocalCacheEntryPath: string = this.#localBuildCacheProvider.getCacheEntryPath(cacheId); - const tempLocalCacheEntryPath: string = _getTempLocalCacheEntryPath(finalLocalCacheEntryPath); - - const logFilePath: string = this.#getTarLogFilePath(cacheId, 'tar'); - const tarExitCode: number = await tarUtility.tryCreateArchiveFromProjectPathsAsync({ - archivePath: tempLocalCacheEntryPath, - paths: filesToCache.outputFilePaths, - project: this.#project, - logFilePath, - baseFolderPath: deferredWrite?.baseFolderPath, - abortSignal: deferredWrite?.abortSignal - }); + const finalLocalCacheEntryPath: string = this.#localBuildCacheProvider.getCacheEntryPath(cacheId); + const tempLocalCacheEntryPath: string = _getTempLocalCacheEntryPath(finalLocalCacheEntryPath); + + const logFilePath: string = this.#getTarLogFilePath(cacheId, 'tar'); + const baseFolderPath: string = deferredWrite?.baseFolderPath ?? this.#project.projectFolder; + let tarExitCode: number | undefined = await tarUtility?.tryCreateArchiveAsync({ + archivePath: tempLocalCacheEntryPath, + paths: filesToCache.outputFilePaths, + logFilePath, + baseFolderPath, + abortSignal: deferredWrite?.abortSignal + }); - if (tarExitCode === 0) { - // Move after the archive is finished so that if the process is interrupted we aren't left with an invalid file - try { - await Async.runWithRetriesAsync({ - action: () => - FileSystem.moveAsync({ - sourcePath: tempLocalCacheEntryPath, - destinationPath: finalLocalCacheEntryPath, - overwrite: true - }), - maxRetries: 2, - retryDelayMs: 500 - }); - } catch (moveError) { - try { - await FileSystem.deleteFileAsync(tempLocalCacheEntryPath); - } catch (deleteError) { - // Ignored - } - throw moveError; + if (tarExitCode !== 0 && !deferredWrite?.abortSignal.aborted) { + terminal.writeVerboseLine( + tarExitCode === undefined + ? 'Native tar is unavailable; using JavaScript to create the cache entry.' + : `Native tar exited with code ${tarExitCode}; using JavaScript. See "${logFilePath}".` + ); + await FileSystem.ensureFolderAsync(path.dirname(tempLocalCacheEntryPath)); + try { + await TarArchive.createFromPathsAsync({ + archivePath: tempLocalCacheEntryPath, + paths: filesToCache.outputFilePaths, + baseFolderPath, + abortSignal: deferredWrite?.abortSignal + }); + tarExitCode = 0; + } catch (error) { + if (!deferredWrite?.abortSignal.aborted) { + throw error; } - localCacheEntryPath = finalLocalCacheEntryPath; - await this.#tryCommitReceiptAsync(terminal, pendingReceipt, cacheId, filesToCache.outputFilePaths); - } else { - if (deferredWrite) { - // A write in the background can be cut short, so it deletes its partial archive. + + terminal.writeVerboseLine('JavaScript cache archive creation was aborted.'); + tarExitCode = 1; + } + } + + if (tarExitCode === 0) { + // Move after the archive is finished so that if the process is interrupted we aren't left with an invalid file + try { + await Async.runWithRetriesAsync({ + action: () => + FileSystem.moveAsync({ + sourcePath: tempLocalCacheEntryPath, + destinationPath: finalLocalCacheEntryPath, + overwrite: true + }), + maxRetries: 2, + retryDelayMs: 500 + }); + } catch (moveError) { + try { await FileSystem.deleteFileAsync(tempLocalCacheEntryPath); + } catch (deleteError) { + // Ignored } - terminal.writeWarningLine( - `"tar" exited with code ${tarExitCode} while attempting to create the cache entry. ` + - `See "${logFilePath}" for logs from the tar process.` - ); - return false; + throw moveError; } + localCacheEntryPath = finalLocalCacheEntryPath; + await this.#tryCommitReceiptAsync(terminal, pendingReceipt, cacheId, filesToCache.outputFilePaths); } else { + if (deferredWrite) { + // A write in the background can be cut short, so it deletes its partial archive. + await FileSystem.deleteFileAsync(tempLocalCacheEntryPath); + } terminal.writeWarningLine( - `Unable to locate "tar". Please ensure that "tar" is on your PATH environment variable, or set the ` + - `${EnvironmentVariableNames.RUSH_TAR_BINARY_PATH} environment variable to the full path to the "tar" binary.` + `"tar" exited with code ${tarExitCode} while attempting to create the cache entry. ` + + `See "${logFilePath}" for logs from the tar process.` ); return false; } diff --git a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCache.test.ts b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCache.test.ts index 1a944aa8172..c2088c648ba 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCache.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCache.test.ts @@ -8,7 +8,7 @@ import type { BuildCacheConfiguration } from '../../../api/BuildCacheConfigurati import type { RushConfigurationProject } from '../../../api/RushConfigurationProject'; import type { IGenerateCacheEntryIdOptions } from '../CacheEntryId'; import type { FileSystemBuildCacheProvider } from '../FileSystemBuildCacheProvider'; -import type { TarExecutable } from '../../../utilities/TarExecutable'; +import type { TarExecutable } from '@rushstack/package-extractor'; import { OperationBuildCache, diff --git a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts index 493650d404e..7af81220814 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts @@ -10,7 +10,7 @@ import { StringBufferTerminalProvider, Terminal } from '@rushstack/terminal'; import type { BuildCacheConfiguration } from '../../../api/BuildCacheConfiguration'; import type { RushConfigurationProject } from '../../../api/RushConfigurationProject'; -import { TarExecutable } from '../../../utilities/TarExecutable'; +import { TarExecutable } from '@rushstack/package-extractor'; import type { IGenerateCacheEntryIdOptions } from '../CacheEntryId'; import { DEFERRED_CACHE_ENTRY_STAGING_FOLDER_NAME, @@ -249,20 +249,18 @@ describe('OperationBuildCache with deferred cache entry writes', () => { expect(writes.takeReport()).toMatchObject({ queuedCount: 0, pendingCount: 0 }); }); - it('seals nothing if tar is not found', async () => { + it('uses the JavaScript fallback without sealing if native tar is not found', async () => { _setTarUtilityPromiseForTesting(Promise.resolve(undefined)); const cloneFileAsync: jest.Mock = jest.fn(copyFileAsync); const writes: DeferredCacheEntryWrites = createWrites(cloneFileAsync); - // The operation reports the failure, instead of the daemon's log reporting it later. const result: boolean = await createSubject().trySetCacheEntryAsync(terminal, undefined, writes); await writes.waitForIdleAsync(); - expect(result).toBe(false); + expect(result).toBe(true); expect(cloneFileAsync).not.toHaveBeenCalled(); - expect(terminalProvider.getWarningOutput({ normalizeSpecialCharacters: false })).toContain( - 'Unable to locate "tar".' - ); + expect(await restoreEntryAsync()).toEqual({ 'dist/index.js': 'index 1', 'dist/nested/a.js': 'a 1' }); + expect(terminalProvider.getWarningOutput({ normalizeSpecialCharacters: false })).toBe(''); expect(writes.takeReport()).toMatchObject({ queuedCount: 0, pendingCount: 0 }); expect(logLines).toEqual([]); }); diff --git a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts index 979e5df9e41..06b48b649e9 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts @@ -5,11 +5,12 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; +import * as tar from 'tar'; import { StringBufferTerminalProvider, Terminal, type ITerminal } from '@rushstack/terminal'; import type { BuildCacheConfiguration } from '../../../api/BuildCacheConfiguration'; import type { RushConfigurationProject } from '../../../api/RushConfigurationProject'; -import type { ICreateArchiveOptions, IUntarOptions, TarExecutable } from '../../../utilities/TarExecutable'; +import type { ICreateArchiveOptions, IUntarOptions, TarExecutable } from '@rushstack/package-extractor'; import type { IBaseOperationExecutionResult } from '../../operations/IOperationExecutionResult'; import type { IGenerateCacheEntryIdOptions } from '../CacheEntryId'; import { DeferredCacheEntryWrites } from '../DeferredCacheEntryWrites'; @@ -69,7 +70,7 @@ describe('OperationBuildCache receipts', () => { return 0; }); createArchiveMock = jest.fn( - async ({ archivePath, paths, project, baseFolderPath, abortSignal }: ICreateArchiveOptions) => { + async ({ archivePath, paths, baseFolderPath, abortSignal }: ICreateArchiveOptions) => { await waitForGateAsync(abortSignal); if (abortSignal?.aborted) { // As a killed tar would @@ -77,12 +78,9 @@ describe('OperationBuildCache receipts', () => { } const archive: FakeArchive = {}; for (const relativePath of paths) { - archive[relativePath] = fs.readFileSync( - path.join(baseFolderPath ?? project.projectFolder, relativePath), - 'utf8' - ); + archive[relativePath] = fs.readFileSync(path.join(baseFolderPath, relativePath), 'utf8'); } - tarHook?.(project.projectFolder); + tarHook?.(projectFolder); fs.writeFileSync(archivePath, JSON.stringify(archive)); return 0; } @@ -90,7 +88,7 @@ describe('OperationBuildCache receipts', () => { _setTarUtilityPromiseForTesting( Promise.resolve({ tryUntarAsync: untarMock, - tryCreateArchiveFromProjectPathsAsync: createArchiveMock + tryCreateArchiveAsync: createArchiveMock } as unknown as TarExecutable) ); }); @@ -229,6 +227,34 @@ describe('OperationBuildCache receipts', () => { return JSON.parse(fs.readFileSync(path.join(cacheFolder, CACHE_ID), 'utf8')); } + it.each(['unavailable', 'failed'])( + 'writes a cache entry with JavaScript when native tar is %s', + async (reason) => { + if (reason === 'unavailable') { + _setTarUtilityPromiseForTesting(Promise.resolve(undefined)); + } else { + createArchiveMock.mockResolvedValue(1); + } + + writeFiles(projectFolder, ENTRY); + expect(await setCacheEntryAsync(createSubject())).toBe(true); + const archive: FakeArchive = {}; + await tar.list({ + file: path.join(cacheFolder, CACHE_ID), + onReadEntry: (entry) => { + const chunks: Buffer[] = []; + entry.on('data', (chunk: Buffer) => chunks.push(chunk)); + entry.on('end', () => { + archive[entry.path] = Buffer.concat(chunks).toString(); + }); + } + }); + expect(archive).toEqual(ENTRY); + expect(hasReceipt()).toBe(true); + expect(fs.readdirSync(cacheFolder)).toEqual([CACHE_ID]); + } + ); + // Waits for the writes in the background to make the condition true. async function waitForAsync(condition: () => boolean): Promise { while (!condition()) { diff --git a/libraries/rush-lib/src/logic/buildCache/test/StagedRestore.test.ts b/libraries/rush-lib/src/logic/buildCache/test/StagedRestore.test.ts index 698f31b3468..65d54cad61b 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/StagedRestore.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/StagedRestore.test.ts @@ -9,7 +9,7 @@ import { StringBufferTerminalProvider, Terminal, type ITerminal } from '@rushsta import type { BuildCacheConfiguration } from '../../../api/BuildCacheConfiguration'; import type { RushConfigurationProject } from '../../../api/RushConfigurationProject'; -import type { IUntarOptions, TarExecutable } from '../../../utilities/TarExecutable'; +import type { IUntarOptions, TarExecutable } from '@rushstack/package-extractor'; import type { IBaseOperationExecutionResult } from '../../operations/IOperationExecutionResult'; import type { IGenerateCacheEntryIdOptions } from '../CacheEntryId'; import { OperationBuildCache, _setTarUtilityPromiseForTesting } from '../OperationBuildCache'; diff --git a/libraries/rush-lib/src/utilities/TarExecutable.ts b/libraries/rush-lib/src/utilities/TarExecutable.ts deleted file mode 100644 index 2e8e2d41037..00000000000 --- a/libraries/rush-lib/src/utilities/TarExecutable.ts +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. -// See LICENSE in the project root for license information. - -import { - TarExecutable as SharedTarExecutable, - type ICreateArchiveOptions as ISharedCreateArchiveOptions, - type IUntarOptions -} from '@rushstack/package-extractor'; -import type { ITerminal } from '@rushstack/terminal'; - -import type { RushConfigurationProject } from '../api/RushConfigurationProject'; -import { EnvironmentConfiguration } from '../api/EnvironmentConfiguration'; - -export type { IUntarOptions }; - -export interface ICreateArchiveOptions extends Omit { - project: RushConfigurationProject; - /** The folder that paths are relative to. Defaults to the project folder. */ - baseFolderPath?: string; -} - -export class TarExecutable { - readonly #tarExecutable: SharedTarExecutable; - - private constructor(tarExecutable: SharedTarExecutable) { - this.#tarExecutable = tarExecutable; - } - - public static async tryInitializeAsync(terminal: ITerminal): Promise { - const tarExecutable: SharedTarExecutable | undefined = await SharedTarExecutable.tryInitializeAsync( - terminal, - EnvironmentConfiguration.tarBinaryPath - ); - return tarExecutable ? new TarExecutable(tarExecutable) : undefined; - } - - public async tryUntarAsync(options: IUntarOptions): Promise { - return await this.#tarExecutable.tryUntarAsync(options); - } - - public async tryCreateArchiveFromProjectPathsAsync(options: ICreateArchiveOptions): Promise { - const { project, baseFolderPath, ...rest } = options; - return await this.#tarExecutable.tryCreateArchiveAsync({ - ...rest, - baseFolderPath: baseFolderPath ?? project.projectFolder - }); - } -} diff --git a/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts b/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts index 78d6568bddb..d1c2d2f1743 100644 --- a/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts +++ b/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts @@ -9,13 +9,7 @@ import { setTimeout as delayAsync } from 'node:timers/promises'; import { StringBufferTerminalProvider, Terminal } from '@rushstack/terminal'; -import type { RushConfigurationProject } from '../../api/RushConfigurationProject'; -import { TarExecutable } from '../TarExecutable'; - -// Archives are created from the base folder, so this folder is never used. -const project: RushConfigurationProject = { - projectFolder: path.join(os.tmpdir(), 'rush-tar-executable-missing-project') -} as RushConfigurationProject; +import { TarExecutable } from '@rushstack/package-extractor'; describe(TarExecutable.name, () => { let tar: TarExecutable; @@ -45,10 +39,9 @@ describe(TarExecutable.name, () => { it('names the members of an archive from its base folder', async () => { const archivePath: string = path.join(folderPath, 'entry.tar.gz'); - const exitCode: number = await tar.tryCreateArchiveFromProjectPathsAsync({ + const exitCode: number = await tar.tryCreateArchiveAsync({ archivePath, paths: ['lib/index.js'], - project, baseFolderPath, logFilePath: path.join(folderPath, 'create.log') }); @@ -69,10 +62,9 @@ describe(TarExecutable.name, () => { it('kills tar at once when its signal was aborted before it started', async () => { const logFilePath: string = path.join(folderPath, 'create.log'); - const exitCode: number = await tar.tryCreateArchiveFromProjectPathsAsync({ + const exitCode: number = await tar.tryCreateArchiveAsync({ archivePath: path.join(folderPath, 'entry.tar.gz'), paths: ['lib/index.js'], - project, baseFolderPath, logFilePath, abortSignal: AbortSignal.abort() @@ -93,10 +85,9 @@ describe(TarExecutable.name, () => { } const logFilePath: string = path.join(folderPath, 'create.log'); const abortController: AbortController = new AbortController(); - const exitCodePromise: Promise = tar.tryCreateArchiveFromProjectPathsAsync({ + const exitCodePromise: Promise = tar.tryCreateArchiveAsync({ archivePath: path.join(folderPath, 'entry.tar.gz'), paths: ['lib/index.js', 'large.bin'], - project, baseFolderPath, logFilePath, abortSignal: abortController.signal From e5252b79467c9c317a4929cc471b4dff0bd8cd30 Mon Sep 17 00:00:00 2001 From: iclanton <5010588+iclanton@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:16:07 +0000 Subject: [PATCH 4/8] fixup! fixup! fixup! [rush] Add tarball support to deploy archives Use native tar exclusively and stage archive-only deployment assets in isolated common/temp folders with guaranteed cleanup. Remove the shared JavaScript writer and restore native-only cache behavior. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../rush/deploy-tarballs_2026-11-25.json | 5 - .../deploy-tarballs_2026-11-25.json | 4 +- .../config/subspaces/default/pnpm-lock.yaml | 6 +- common/reviews/api/package-extractor.api.md | 39 +---- libraries/package-extractor/README.md | 11 +- libraries/package-extractor/package.json | 4 +- .../package-extractor/src/ArchiveManager.ts | 148 ++++++++++-------- .../package-extractor/src/AssetHandler.ts | 5 +- .../package-extractor/src/PackageExtractor.ts | 6 + libraries/package-extractor/src/TarArchive.ts | 89 ----------- .../package-extractor/src/TarExecutable.ts | 4 +- libraries/package-extractor/src/index.ts | 7 - .../src/test/ArchiveManager.test.ts | 144 ++++++++++++----- .../rush-lib/src/cli/actions/DeployAction.ts | 1 + .../logic/buildCache/OperationBuildCache.ts | 41 ++--- .../OperationBuildCacheDeferredWrites.test.ts | 10 +- .../test/OperationBuildCacheReceipt.test.ts | 29 ---- 17 files changed, 237 insertions(+), 316 deletions(-) delete mode 100644 libraries/package-extractor/src/TarArchive.ts diff --git a/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json index ee6be83ff7a..2a6f5662ec7 100644 --- a/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json +++ b/common/changes/@microsoft/rush/deploy-tarballs_2026-11-25.json @@ -4,11 +4,6 @@ "packageName": "@microsoft/rush", "comment": "Add support for `.tar`, `.tar.gz`, and `.tgz` archives to `rush deploy --create-archive`.", "type": "minor" - }, - { - "packageName": "@microsoft/rush", - "comment": "Use the shared JavaScript tar writer when native tar is unavailable or fails while creating a build cache entry.", - "type": "patch" } ], "packageName": "@microsoft/rush" diff --git a/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json index d537ec9fd6f..68158770839 100644 --- a/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json +++ b/common/changes/@rushstack/package-extractor/deploy-tarballs_2026-11-25.json @@ -2,12 +2,12 @@ "changes": [ { "packageName": "@rushstack/package-extractor", - "comment": "Support `.tar`, `.tar.gz`, and `.tgz` deployment archives, including archive-only extraction, preferring native tar when assets are available on disk.", + "comment": "Support `.tar`, `.tar.gz`, and `.tgz` deployment archives using native tar, staging archive-only assets in a temporary folder.", "type": "minor" }, { "packageName": "@rushstack/package-extractor", - "comment": "Expose shared native tar discovery and JavaScript archive creation for use by Rush build caching.", + "comment": "Expose shared, memoized native tar discovery and execution for use by Rush build caching.", "type": "minor" } ], diff --git a/common/config/subspaces/default/pnpm-lock.yaml b/common/config/subspaces/default/pnpm-lock.yaml index 4b0b412c30f..e195106916e 100644 --- a/common/config/subspaces/default/pnpm-lock.yaml +++ b/common/config/subspaces/default/pnpm-lock.yaml @@ -4069,9 +4069,6 @@ importers: semver: specifier: ~7.7.4 version: 7.7.4 - tar: - specifier: ~7.5.6 - version: 7.5.13 devDependencies: '@rushstack/heft': specifier: workspace:* @@ -4097,6 +4094,9 @@ importers: local-node-rig: specifier: workspace:* version: link:../../rigs/local-node-rig + tar: + specifier: ~7.5.6 + version: 7.5.13 webpack: specifier: ~5.105.2 version: 5.105.4 diff --git a/common/reviews/api/package-extractor.api.md b/common/reviews/api/package-extractor.api.md index dab0b03edfa..a39cb16fb63 100644 --- a/common/reviews/api/package-extractor.api.md +++ b/common/reviews/api/package-extractor.api.md @@ -36,6 +36,7 @@ export interface IExtractorMetadataJson { // @public export interface IExtractorOptions { + archiveTempFolder?: string; createArchiveFilePath?: string; createArchiveOnly?: boolean; dependencyConfigurations?: IExtractorDependencyConfiguration[]; @@ -87,36 +88,6 @@ export interface IProjectInfoJson { projectName: string; } -// @beta -export interface ITarArchiveEntry { - // (undocumented) - archivePath: string; - // (undocumented) - data: Buffer | string; - // (undocumented) - isSymbolicLink: boolean; - // (undocumented) - permissions: number; -} - -// @beta -export interface ITarArchiveFromPathsOptions extends ITarArchiveOptions { - // (undocumented) - baseFolderPath: string; - // (undocumented) - paths: string[]; -} - -// @beta -export interface ITarArchiveOptions { - // (undocumented) - abortSignal?: AbortSignal; - // (undocumented) - archivePath: string; - // (undocumented) - gzip?: boolean; -} - // @beta (undocumented) export interface ITarOptionsBase { // (undocumented) @@ -141,14 +112,6 @@ export class PackageExtractor { static getPackageIncludedFilesAsync(packageRootPath: string): Promise; } -// @beta -export class TarArchive { - // (undocumented) - static createFromEntriesAsync(options: ITarArchiveOptions, entries: Iterable): Promise; - // (undocumented) - static createFromPathsAsync(options: ITarArchiveFromPathsOptions): Promise; -} - // @beta export class TarExecutable { // (undocumented) diff --git a/libraries/package-extractor/README.md b/libraries/package-extractor/README.md index 9fafae6fcc5..198024bc13c 100644 --- a/libraries/package-extractor/README.md +++ b/libraries/package-extractor/README.md @@ -4,13 +4,12 @@ A library used for creating an isolated copy of a package and, optionally, bundl The `createArchiveFilePath` option supports ZIP (`.zip`), tar (`.tar`), and gzip-compressed tar (`.tar.gz` or `.tgz`) archives, including when `createArchiveOnly` is enabled. -Tar archives use the native `tar` executable when the deployed files are available on disk, -falling back to JavaScript when it is unavailable or fails. Archive-only deployments use -JavaScript so generated assets do not need to be staged on disk. +Tar archives require the native `tar` executable on PATH. Archive-only tar deployments +stage assets in a unique folder under `archiveTempFolder` (default: `common/temp` under +the source root), then remove that folder after success or failure. ZIP archives continue +to use JavaScript and do not require staging. -`TarExecutable` memoizes native executable discovery. `TarArchive` provides JavaScript -archive creation from filesystem paths or in-memory entries; Rush's build-cache writer -also uses it when native tar is unavailable or fails. +`TarExecutable` shares memoized native discovery and execution with Rush's build cache. ## Links diff --git a/libraries/package-extractor/package.json b/libraries/package-extractor/package.json index 4d701cca9e3..d6568b89609 100644 --- a/libraries/package-extractor/package.json +++ b/libraries/package-extractor/package.json @@ -52,10 +52,10 @@ "jszip": "~3.8.0", "minimatch": "10.2.3", "npm-packlist": "~5.1.3", - "semver": "~7.7.4", - "tar": "~7.5.6" + "semver": "~7.7.4" }, "devDependencies": { + "tar": "~7.5.6", "local-node-rig": "workspace:*", "@rushstack/heft-webpack5-plugin": "workspace:*", "@rushstack/heft": "workspace:*", diff --git a/libraries/package-extractor/src/ArchiveManager.ts b/libraries/package-extractor/src/ArchiveManager.ts index 9ceac47a909..65a3f5fed83 100644 --- a/libraries/package-extractor/src/ArchiveManager.ts +++ b/libraries/package-extractor/src/ArchiveManager.ts @@ -1,13 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. +import { randomUUID } from 'node:crypto'; +import path from 'node:path'; + import JSZip from 'jszip'; -import { FileSystem, type FileSystemStats, Path } from '@rushstack/node-core-library'; +import { FileSystem, type FileSystemStats, Path, type PosixModeBits } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; import { TarExecutable } from './TarExecutable'; -import { TarArchive } from './TarArchive'; export type ArchiveFormat = 'zip' | 'tar' | 'tgz'; @@ -27,15 +29,16 @@ export interface IAddToArchiveOptions { } interface IArchiveEntry { - data: Buffer | string; - permissions: number; - isSymbolicLink: boolean; + filePath?: string; + fileData?: Buffer | string; + stats?: FileSystemStats; } export interface ICreateArchiveOptions { terminal: ITerminal; /** Omit when assets have not been materialized, such as archive-only deployment. */ sourceFolder?: string; + tempFolder: string; } export class ArchiveManager { @@ -59,39 +62,38 @@ export class ArchiveManager { } public async addToArchiveAsync(options: IAddToArchiveOptions): Promise { - const { filePath, fileData, archivePath } = options; - - let data: Buffer | string; - let permissions: number; - let isSymbolicLink: boolean = false; - if (filePath) { - const stats: FileSystemStats = options.stats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); - if (stats.isSymbolicLink()) { - data = await FileSystem.readLinkAsync(filePath); - permissions = SYMBOLIC_LINK_PERMISSIONS; - isSymbolicLink = true; - } else if (stats.isDirectory()) { - throw new Error('Directories cannot be added to the archive'); - } else { - data = await FileSystem.readFileToBufferAsync(filePath); - permissions = stats.mode; - } - } else if (fileData) { - data = fileData; - permissions = DEFAULT_FILE_PERMISSIONS; - } else { + const { filePath, fileData, archivePath, stats } = options; + if (!filePath && fileData === undefined) { throw new Error('Either filePath or fileData must be provided'); } - // Replace backslashes for Unix compat const addPath: string = Path.convertToSlashes(archivePath); - this.#entries.set(addPath, { data, permissions, isSymbolicLink }); + if (path.isAbsolute(addPath) || addPath.split('/').includes('..')) { + throw new Error('Archive entries must be relative paths within the archive'); + } + + this.#entries.set(addPath, { filePath, fileData, stats }); } public async createArchiveAsync(archiveFilePath: string, options?: ICreateArchiveOptions): Promise { if (this.#archiveFormat === 'zip') { const zip: JSZip = new JSZip(); - for (const [archivePath, { data, permissions }] of this.#entries) { + for (const [archivePath, { filePath, fileData, stats: providedStats }] of this.#entries) { + let data: Buffer | string = fileData ?? ''; + let permissions: number = DEFAULT_FILE_PERMISSIONS; + if (filePath) { + const stats: FileSystemStats = providedStats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); + if (stats.isSymbolicLink()) { + data = await FileSystem.readLinkAsync(filePath); + permissions = SYMBOLIC_LINK_PERMISSIONS; + } else if (stats.isDirectory()) { + throw new Error('Directories cannot be added to the archive'); + } else { + data = await FileSystem.readFileToBufferAsync(filePath); + permissions = stats.mode; + } + } + zip.file(archivePath, data, { unixPermissions: permissions, dir: false @@ -104,42 +106,66 @@ export class ArchiveManager { }); await FileSystem.writeFileAsync(archiveFilePath, zipContent); } else { - const { terminal, sourceFolder } = options ?? {}; - const nativePathsSupported: boolean = [...this.#entries.keys()].every( - (entryPath) => !entryPath.startsWith('-') && !/[\r\n\\]/.test(entryPath) - ); - if (terminal && sourceFolder && nativePathsSupported) { - const tarExecutable: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); - if (tarExecutable) { - const logFilePath: string = `${archiveFilePath}.log`; - const exitCode: number = await tarExecutable.tryCreateArchiveAsync({ - archivePath: archiveFilePath, - paths: [...this.#entries.keys()], - baseFolderPath: sourceFolder, - logFilePath, - gzip: this.#archiveFormat === 'tgz' - }); - if (exitCode === 0) { - await FileSystem.deleteFileAsync(logFilePath); - return; + if (!options) { + throw new Error('Native tar creation requires terminal and temporary folder options'); + } + + const { terminal, sourceFolder, tempFolder } = options; + const tarExecutable: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + if (!tarExecutable) { + throw new Error('Native tar is required to create tar archives. Ensure "tar" is on PATH.'); + } + + const archiveSourceFolder: string = + sourceFolder ?? path.resolve(tempFolder, `deploy-archive-${randomUUID()}`); + const logFilePath: string = `${archiveFilePath}.log`; + try { + if (!sourceFolder) { + await FileSystem.ensureFolderAsync(archiveSourceFolder); + for (const [archivePath, { filePath, fileData, stats: providedStats }] of this.#entries) { + const stagedPath: string = path.resolve(archiveSourceFolder, archivePath); + await FileSystem.ensureFolderAsync(path.dirname(stagedPath)); + if (filePath) { + const stats: FileSystemStats = + providedStats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); + if (stats.isSymbolicLink()) { + await FileSystem.createSymbolicLinkFileAsync({ + newLinkPath: stagedPath, + linkTargetPath: await FileSystem.readLinkAsync(filePath) + }); + } else if (stats.isDirectory()) { + throw new Error('Directories cannot be added to the archive'); + } else { + await FileSystem.copyFileAsync({ sourcePath: filePath, destinationPath: stagedPath }); + } + } else { + await FileSystem.writeFileAsync(stagedPath, fileData ?? ''); + await FileSystem.changePosixModeBitsAsync( + stagedPath, + DEFAULT_FILE_PERMISSIONS as PosixModeBits + ); + } } + } - terminal.writeWarningLine( - `Native tar exited with code ${exitCode}; falling back to JavaScript. See "${logFilePath}".` - ); - } else { - terminal.writeVerboseLine('Native tar is unavailable; falling back to JavaScript.'); + const exitCode: number = await tarExecutable.tryCreateArchiveAsync({ + archivePath: archiveFilePath, + paths: [...this.#entries.keys()], + baseFolderPath: archiveSourceFolder, + logFilePath, + gzip: this.#archiveFormat === 'tgz' + }); + if (exitCode !== 0) { + await FileSystem.deleteFileAsync(archiveFilePath); + throw new Error(`Native tar exited with code ${exitCode}. See "${logFilePath}" for details.`); } - } else { - terminal?.writeVerboseLine( - 'Using JavaScript tar for in-memory assets or paths incompatible with native tar file lists.' - ); - } - await TarArchive.createFromEntriesAsync( - { archivePath: archiveFilePath, gzip: this.#archiveFormat === 'tgz' }, - [...this.#entries].map(([archivePath, entry]) => ({ archivePath, ...entry })) - ); + await FileSystem.deleteFileAsync(logFilePath); + } finally { + if (!sourceFolder) { + await FileSystem.deleteFolderAsync(archiveSourceFolder); + } + } } } } diff --git a/libraries/package-extractor/src/AssetHandler.ts b/libraries/package-extractor/src/AssetHandler.ts index 308075f73d5..c0a2c88e2f5 100644 --- a/libraries/package-extractor/src/AssetHandler.ts +++ b/libraries/package-extractor/src/AssetHandler.ts @@ -52,6 +52,7 @@ export class AssetHandler { readonly #symlinkAnalyzer: SymlinkAnalyzer; readonly #archiveManager: ArchiveManager | undefined; readonly #archiveFilePath: string | undefined; + readonly #archiveTempFolder: string; readonly #linkCreationMode: LinkCreationMode; readonly #includedAssetPaths: Set = new Set(); #isFinalized: boolean = false; @@ -69,6 +70,7 @@ export class AssetHandler { this.#terminal = terminal; this.#sourceRootFolder = sourceRootFolder; this.#targetRootFolder = targetRootFolder; + this.#archiveTempFolder = options.archiveTempFolder ?? `${sourceRootFolder}/common/temp`; this.#symlinkAnalyzer = symlinkAnalyzer; if (createArchiveFilePath) { this.#archiveFilePath = path.resolve(targetRootFolder, createArchiveFilePath); @@ -172,7 +174,8 @@ export class AssetHandler { this.#terminal.writeLine(`Creating archive at "${this.#archiveFilePath}"`); await this.#archiveManager.createArchiveAsync(this.#archiveFilePath, { terminal: this.#terminal, - sourceFolder: this.#createArchiveOnly ? undefined : this.#targetRootFolder + sourceFolder: this.#createArchiveOnly ? undefined : this.#targetRootFolder, + tempFolder: this.#archiveTempFolder }); } diff --git a/libraries/package-extractor/src/PackageExtractor.ts b/libraries/package-extractor/src/PackageExtractor.ts index 219d8c61211..087b22d015e 100644 --- a/libraries/package-extractor/src/PackageExtractor.ts +++ b/libraries/package-extractor/src/PackageExtractor.ts @@ -238,6 +238,12 @@ export interface IExtractorOptions { */ createArchiveFilePath?: string; + /** + * The parent folder for temporary tar archive staging. Defaults to "common/temp" under + * {@link IExtractorOptions.sourceRootFolder}. Staging folders are removed after archive creation. + */ + archiveTempFolder?: string; + /** * Whether to skip copying files to the extraction target directory, and only create an extraction * archive. This is only supported when {@link IExtractorOptions.linkCreation} is 'script' or 'none'. diff --git a/libraries/package-extractor/src/TarArchive.ts b/libraries/package-extractor/src/TarArchive.ts deleted file mode 100644 index fbe5491aed8..00000000000 --- a/libraries/package-extractor/src/TarArchive.ts +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. -// See LICENSE in the project root for license information. - -import { pipeline } from 'node:stream/promises'; - -import * as tar from 'tar'; - -import { FileSystem, type FileSystemWriteStream, Path } from '@rushstack/node-core-library'; - -/** - * An in-memory tar archive member. - * @beta - */ -export interface ITarArchiveEntry { - archivePath: string; - data: Buffer | string; - permissions: number; - isSymbolicLink: boolean; -} - -/** - * Options for JavaScript tar archive creation. - * @beta - */ -export interface ITarArchiveOptions { - archivePath: string; - gzip?: boolean; - abortSignal?: AbortSignal; -} - -/** - * Options for archiving files from disk. - * @beta - */ -export interface ITarArchiveFromPathsOptions extends ITarArchiveOptions { - baseFolderPath: string; - paths: string[]; -} - -/** - * JavaScript tar creation shared by deployment and build caching. - * @beta - */ -export class TarArchive { - public static async createFromPathsAsync(options: ITarArchiveFromPathsOptions): Promise { - const { baseFolderPath, paths, gzip = true } = options; - options.abortSignal?.throwIfAborted(); - const pack: tar.Pack = tar.create({ cwd: baseFolderPath, gzip, strict: true, noDirRecurse: true }, paths); - await writeAsync(pack, options); - } - - public static async createFromEntriesAsync( - options: ITarArchiveOptions, - entries: Iterable - ): Promise { - const { gzip = true } = options; - options.abortSignal?.throwIfAborted(); - const pack: tar.Pack = new tar.Pack({ gzip }); - const writePromise: Promise = writeAsync(pack, options); - for (const { archivePath, data, permissions, isSymbolicLink } of entries) { - const content: Buffer = isSymbolicLink - ? Buffer.alloc(0) - : typeof data === 'string' - ? Buffer.from(data) - : data; - // ReadEntry archives generated assets without staging them on disk. - const entry: tar.ReadEntry = new tar.ReadEntry( - new tar.Header({ - path: archivePath, - mode: permissions, - type: isSymbolicLink ? 'SymbolicLink' : 'File', - linkpath: isSymbolicLink ? Path.convertToSlashes(data.toString()) : undefined, - size: content.length - }) - ); - pack.add(entry); - entry.end(content); - } - - pack.end(); - await writePromise; - } -} - -async function writeAsync(pack: tar.Pack, options: ITarArchiveOptions): Promise { - const { archivePath, abortSignal } = options; - const output: FileSystemWriteStream = FileSystem.createWriteStream(archivePath); - await pipeline(pack, output, { signal: abortSignal }); -} diff --git a/libraries/package-extractor/src/TarExecutable.ts b/libraries/package-extractor/src/TarExecutable.ts index 8355b30d300..416acad1655 100644 --- a/libraries/package-extractor/src/TarExecutable.ts +++ b/libraries/package-extractor/src/TarExecutable.ts @@ -103,7 +103,7 @@ export class TarExecutable { public async tryCreateArchiveAsync(options: ICreateArchiveOptions): Promise { const { archivePath, paths, logFilePath, baseFolderPath, abortSignal, gzip = true } = options; - const tarInput: string = paths.join('\n'); + const tarInput: string = paths.length > 0 ? `${paths.join('\0')}\0` : ''; // On Windows, tar.exe will report a "Failed to clean up compressor" error if the target folder // does not exist (GitHub #2622) @@ -119,6 +119,8 @@ export class TarExecutable { archivePath, // [Windows bsdtar 3.3.2] -z, -j, -J, --lzma Compress archive with gzip/bzip2/xz/lzma ...(gzip ? ['-z'] : []), + // NUL-delimited lists preserve whitespace and treat leading dashes as filenames. + '--null', // [GNU tar 1.33] -T, --files-from=FILE get names to extract or create from FILE // // Windows bsdtar does not document this parameter, but seems to accept it. diff --git a/libraries/package-extractor/src/index.ts b/libraries/package-extractor/src/index.ts index 0f127a993b8..de9077fdd83 100644 --- a/libraries/package-extractor/src/index.ts +++ b/libraries/package-extractor/src/index.ts @@ -14,13 +14,6 @@ export { export type { ILinkInfo } from './SymlinkAnalyzer'; -export { - TarArchive, - type ITarArchiveEntry, - type ITarArchiveOptions, - type ITarArchiveFromPathsOptions -} from './TarArchive'; - export { TarExecutable, type ITarOptionsBase, diff --git a/libraries/package-extractor/src/test/ArchiveManager.test.ts b/libraries/package-extractor/src/test/ArchiveManager.test.ts index e4f898dff1e..d97cd63e10e 100644 --- a/libraries/package-extractor/src/test/ArchiveManager.test.ts +++ b/libraries/package-extractor/src/test/ArchiveManager.test.ts @@ -1,16 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. +import path from 'node:path'; + import JSZip from 'jszip'; import * as tar from 'tar'; -import { FileSystem, type FileSystemStats } from '@rushstack/node-core-library'; +import { FileSystem, Path } from '@rushstack/node-core-library'; import { Terminal, StringBufferTerminalProvider } from '@rushstack/terminal'; import { ArchiveManager } from '../ArchiveManager'; import { AssetHandler } from '../AssetHandler'; import { SymlinkAnalyzer } from '../SymlinkAnalyzer'; import { TarExecutable } from '../TarExecutable'; -import { TarArchive } from '../TarArchive'; interface ITarEntry { type: string; @@ -37,15 +38,17 @@ async function readTarAsync(archivePath: string): Promise } describe(ArchiveManager.name, () => { - const testFolder: string = `${__dirname}/../../test-output/archives`; + const testFolder: string = path.resolve(`${__dirname}/../../test-output/archives`); const sourceFolder: string = `${__dirname}/../../src/test/fixtures/archive`; const sourceFile: string = `${sourceFolder}/input.txt`; + const tempFolder: string = `${testFolder}/common/temp`; let fileContent: Buffer; let generatedContent: string; const terminal: Terminal = new Terminal(new StringBufferTerminalProvider()); beforeAll(async () => { await FileSystem.ensureEmptyFolderAsync(testFolder); + await FileSystem.ensureFolderAsync(tempFolder); fileContent = await FileSystem.readFileToBufferAsync(sourceFile); generatedContent = await FileSystem.readFileAsync(`${sourceFolder}/generated.txt`); }); @@ -70,6 +73,7 @@ describe(ArchiveManager.name, () => { linkCreation: 'none', symlinkAnalyzer: new SymlinkAnalyzer(), createArchiveFilePath: archiveFilePath, + archiveTempFolder: tempFolder, createArchiveOnly }); @@ -105,23 +109,27 @@ describe(ArchiveManager.name, () => { if (createArchiveOnly) { expect(await FileSystem.readFolderItemNamesAsync(targetRootFolder)).toEqual([`deploy${ext}`]); } + + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); } }); it.each(['.tar', '.tar.gz', '.tgz'])('preserves symbolic links in %s archives', async (ext) => { - const linkPath: string = `${sourceFolder}/link${ext}`; - const stats: FileSystemStats = await FileSystem.getStatisticsAsync(sourceFile); - jest.spyOn(stats, 'isSymbolicLink').mockReturnValue(true); - jest.spyOn(FileSystem, 'readLinkAsync').mockResolvedValue('../input.txt'); + const linksFolder: string = `${testFolder}/links-${ext.slice(1)}`; + const linkPath: string = `${linksFolder}/nested/link`; + const linkTargetPath: string = `${linksFolder}/linked-folder`; + await FileSystem.ensureFolderAsync(`${linksFolder}/nested`); + await FileSystem.ensureFolderAsync(linkTargetPath); + await FileSystem.createSymbolicLinkJunctionAsync({ newLinkPath: linkPath, linkTargetPath }); const archiveFilePath: string = `${testFolder}/links${ext}`; const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); - await manager.addToArchiveAsync({ filePath: linkPath, archivePath: 'nested\\link', stats }); - await manager.createArchiveAsync(archiveFilePath); + await manager.addToArchiveAsync({ filePath: linkPath, archivePath: 'nested\\link' }); + await manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder, sourceFolder: linksFolder }); const entries: Map = await readTarAsync(archiveFilePath); expect(entries.get('nested/link')).toMatchObject({ type: 'SymbolicLink', - linkpath: '../input.txt', + linkpath: expect.stringContaining('linked-folder'), data: Buffer.alloc(0) }); }); @@ -138,18 +146,20 @@ describe(ArchiveManager.name, () => { expect(await zip.file('generated.txt')?.async('string')).toBe(generatedContent); }); - it('preserves executable permissions for in-memory tar entries', async () => { + it('preserves executable permissions when staging archive-only assets', async () => { const archiveFilePath: string = `${testFolder}/permissions.tar`; const executablePath: string = `${sourceFolder}/executable.sh`; - const stats: FileSystemStats = await FileSystem.getStatisticsAsync(executablePath); - stats.mode = 0o100775; const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); - await manager.addToArchiveAsync({ filePath: executablePath, archivePath: 'executable.sh', stats }); - await manager.createArchiveAsync(archiveFilePath); - expect((await readTarAsync(archiveFilePath)).get('executable.sh')?.mode).toBe(0o775); + await manager.addToArchiveAsync({ filePath: executablePath, archivePath: 'executable.sh' }); + await manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder }); + const entry: ITarEntry | undefined = (await readTarAsync(archiveFilePath)).get('executable.sh'); + expect(entry?.data).toEqual(await FileSystem.readFileToBufferAsync(executablePath)); + if (process.platform !== 'win32') { + expect(entry?.mode).toBe(0o755); + } }); - it('prefers native tar for materialized files', async () => { + it('uses native tar without staging materialized files', async () => { const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); if (!nativeTar) { throw new Error('Native tar is required for the native-tar test'); @@ -160,28 +170,35 @@ describe(ArchiveManager.name, () => { const archiveFilePath: string = `${testFolder}/native.tar`; const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); - await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder }); + await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder, tempFolder }); expect(createSpy).toHaveBeenCalledWith( expect.objectContaining({ baseFolderPath: sourceFolder, paths: ['input.txt'], gzip: false }) ); expect((await readTarAsync(archiveFilePath)).get('input.txt')?.data).toEqual(fileContent); expect(await FileSystem.existsAsync(`${archiveFilePath}.log`)).toBe(false); + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); }); it('rejects unsupported extensions', () => { expect(() => ArchiveManager.getArchiveFormat('deploy.gz')).toThrow('Supported archive file extensions'); }); - it('reports archive write failures', async () => { - const archiveFilePath: string = `${testFolder}/missing/deploy.tgz`; + it('cleans up staging when copying an asset fails', async () => { + const archiveFilePath: string = `${testFolder}/copy-failure.tgz`; const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); - await manager.addToArchiveAsync({ fileData: 'content', archivePath: 'file.txt' }); - await expect(manager.createArchiveAsync(archiveFilePath)).rejects.toThrow(); + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'file.txt' }); + jest.spyOn(FileSystem, 'copyFileAsync').mockRejectedValue(new Error('copy failed')); + await expect(manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder })).rejects.toThrow( + 'copy failed' + ); + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); + expect(await FileSystem.existsAsync(archiveFilePath)).toBe(false); }); - it.each(['unavailable', 'incompatible'])('falls back when native tar is %s', async (reason) => { + it.each(['unavailable', 'incompatible'])('fails explicitly when native tar is %s', async (reason) => { const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); const initializeSpy = jest.spyOn(TarExecutable, 'tryInitializeAsync'); + const archiveFilePath: string = `${testFolder}/failure-${reason}.tgz`; if (reason === 'unavailable') { initializeSpy.mockResolvedValue(undefined); } else { @@ -189,16 +206,77 @@ describe(ArchiveManager.name, () => { throw new Error('Native tar is required for the incompatible-tar test'); } - jest.spyOn(nativeTar, 'tryCreateArchiveAsync').mockResolvedValue(1); + jest.spyOn(nativeTar, 'tryCreateArchiveAsync').mockImplementation(async ({ baseFolderPath }) => { + expect(Path.convertToSlashes(baseFolderPath)).toContain( + `${Path.convertToSlashes(tempFolder)}/deploy-archive-` + ); + expect(await FileSystem.readFileToBufferAsync(`${baseFolderPath}/input.txt`)).toEqual(fileContent); + await FileSystem.writeFileAsync(archiveFilePath, 'partial archive'); + return 1; + }); initializeSpy.mockResolvedValue(nativeTar); } - const archiveFilePath: string = `${testFolder}/fallback-${reason}.tgz`; const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); - await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder }); + await expect(manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder })).rejects.toThrow( + reason === 'unavailable' ? 'Native tar is required' : 'Native tar exited with code 1' + ); expect(initializeSpy).toHaveBeenCalled(); - expect((await readTarAsync(archiveFilePath)).get('input.txt')?.data).toEqual(fileContent); + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); + expect(await FileSystem.existsAsync(archiveFilePath)).toBe(false); + }); + + it('uses isolated staging folders for concurrent archive-only deployments', async () => { + const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + if (!nativeTar) { + throw new Error('Native tar is required for the staging test'); + } + + const createSpy = jest.spyOn(nativeTar, 'tryCreateArchiveAsync'); + const archivePaths: string[] = [`${testFolder}/concurrent-1.tgz`, `${testFolder}/concurrent-2.tgz`]; + await Promise.all( + archivePaths.map(async (archivePath, index) => { + const manager: ArchiveManager = new ArchiveManager('tgz'); + await manager.addToArchiveAsync({ fileData: `content ${index}`, archivePath: 'input.txt' }); + await manager.createArchiveAsync(archivePath, { terminal, tempFolder }); + expect((await readTarAsync(archivePath)).get('input.txt')?.data.toString()).toBe(`content ${index}`); + }) + ); + const stagingFolders: string[] = createSpy.mock.calls.map(([{ baseFolderPath }]) => baseFolderPath); + expect(new Set(stagingFolders).size).toBe(2); + for (const stagingFolder of stagingFolders) { + expect(Path.convertToSlashes(stagingFolder)).toContain( + `${Path.convertToSlashes(tempFolder)}/deploy-archive-` + ); + expect(await FileSystem.existsAsync(stagingFolder)).toBe(false); + } + }); + + it('treats whitespace and leading dashes in member names literally', async () => { + const archiveFilePath: string = `${testFolder}/special-paths.tar`; + const memberNames: string[] = ['-C', ' leading spaces', 'nested/file with spaces.txt']; + if (process.platform !== 'win32') { + memberNames.push(' trailing spaces ', 'line\nbreak', 'line\rbreak'); + } + + const manager: ArchiveManager = new ArchiveManager('tar'); + for (const archivePath of memberNames) { + await manager.addToArchiveAsync({ fileData: archivePath, archivePath }); + } + + await manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder }); + const entries: Map = await readTarAsync(archiveFilePath); + for (const memberName of memberNames) { + expect(entries.get(memberName)?.data.toString()).toBe(memberName); + } + }); + + it('rejects archive entries outside the staging folder', async () => { + const manager: ArchiveManager = new ArchiveManager('tar'); + await expect( + manager.addToArchiveAsync({ fileData: 'content', archivePath: '../outside' }) + ).rejects.toThrow('relative paths within the archive'); }); it('handles a native executable that exits before reading the file list', async () => { @@ -236,16 +314,4 @@ describe(ArchiveManager.name, () => { ); expect(first).not.toBe(other); }); - - it('cancels JavaScript tar creation', async () => { - const archivePath: string = `${testFolder}/aborted.tgz`; - await expect( - TarArchive.createFromPathsAsync({ - archivePath, - baseFolderPath: sourceFolder, - paths: ['input.txt'], - abortSignal: AbortSignal.abort() - }) - ).rejects.toMatchObject({ name: 'AbortError' }); - }); }); diff --git a/libraries/rush-lib/src/cli/actions/DeployAction.ts b/libraries/rush-lib/src/cli/actions/DeployAction.ts index 513234b971a..a0eaeb06048 100644 --- a/libraries/rush-lib/src/cli/actions/DeployAction.ts +++ b/libraries/rush-lib/src/cli/actions/DeployAction.ts @@ -220,6 +220,7 @@ export class DeployAction extends BaseRushAction { projectConfigurations, dependencyConfigurations: scenarioConfiguration.json.dependencySettings, createArchiveFilePath, + archiveTempFolder: this.rushConfiguration.commonTempFolder, createArchiveOnly, subspaces: Array.from(subspaces.values()) }); diff --git a/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts b/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts index cb921bcc506..4ca883b405e 100644 --- a/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts +++ b/libraries/rush-lib/src/logic/buildCache/OperationBuildCache.ts @@ -6,13 +6,13 @@ import * as crypto from 'node:crypto'; import { FileSystem, type FolderItem, InternalError, Async, LockFile } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; -import { TarArchive, TarExecutable } from '@rushstack/package-extractor'; +import { TarExecutable } from '@rushstack/package-extractor'; import type { RushConfigurationProject } from '../../api/RushConfigurationProject'; import type { BuildCacheConfiguration } from '../../api/BuildCacheConfiguration'; import type { ICloudBuildCacheProvider } from './ICloudBuildCacheProvider'; import type { FileSystemBuildCacheProvider } from './FileSystemBuildCacheProvider'; -import { EnvironmentConfiguration } from '../../api/EnvironmentConfiguration'; +import { EnvironmentConfiguration, EnvironmentVariableNames } from '../../api/EnvironmentConfiguration'; import type { IBaseOperationExecutionResult } from '../operations/IOperationExecutionResult'; import { OutputFolderReceipt, type PendingOutputFolderReceipt } from './OutputFolderReceipt'; import { tryRestoreThroughStagingFolderAsync } from './StagedRestore'; @@ -507,7 +507,7 @@ export class OperationBuildCache { `Caching build output folders: ${filesToCache.filteredOutputFolderNames.join(', ')}` ); - // Without native tar, use the JavaScript fallback in the foreground instead of sealing outputs. + // If tar can't be found, the write below fails at once, so that the operation reports it. if (deferredCacheEntryWrites && (await _tryGetTarUtility(terminal))) { // A restore consults the receipt only if the local cache has the entry, so a receipt for an entry that is not // written yet is never consulted if the write is dropped or fails. But an older entry for the same cache ID, @@ -583,12 +583,20 @@ export class OperationBuildCache { let localCacheEntryPath: string | undefined; const tarUtility: TarExecutable | undefined = await _tryGetTarUtility(terminal); + if (!tarUtility) { + terminal.writeWarningLine( + `Unable to locate "tar". Please ensure that "tar" is on your PATH environment variable, or set the ` + + `${EnvironmentVariableNames.RUSH_TAR_BINARY_PATH} environment variable to the full path to the "tar" binary.` + ); + return false; + } + const finalLocalCacheEntryPath: string = this.#localBuildCacheProvider.getCacheEntryPath(cacheId); const tempLocalCacheEntryPath: string = _getTempLocalCacheEntryPath(finalLocalCacheEntryPath); const logFilePath: string = this.#getTarLogFilePath(cacheId, 'tar'); const baseFolderPath: string = deferredWrite?.baseFolderPath ?? this.#project.projectFolder; - let tarExitCode: number | undefined = await tarUtility?.tryCreateArchiveAsync({ + const tarExitCode: number = await tarUtility.tryCreateArchiveAsync({ archivePath: tempLocalCacheEntryPath, paths: filesToCache.outputFilePaths, logFilePath, @@ -596,31 +604,6 @@ export class OperationBuildCache { abortSignal: deferredWrite?.abortSignal }); - if (tarExitCode !== 0 && !deferredWrite?.abortSignal.aborted) { - terminal.writeVerboseLine( - tarExitCode === undefined - ? 'Native tar is unavailable; using JavaScript to create the cache entry.' - : `Native tar exited with code ${tarExitCode}; using JavaScript. See "${logFilePath}".` - ); - await FileSystem.ensureFolderAsync(path.dirname(tempLocalCacheEntryPath)); - try { - await TarArchive.createFromPathsAsync({ - archivePath: tempLocalCacheEntryPath, - paths: filesToCache.outputFilePaths, - baseFolderPath, - abortSignal: deferredWrite?.abortSignal - }); - tarExitCode = 0; - } catch (error) { - if (!deferredWrite?.abortSignal.aborted) { - throw error; - } - - terminal.writeVerboseLine('JavaScript cache archive creation was aborted.'); - tarExitCode = 1; - } - } - if (tarExitCode === 0) { // Move after the archive is finished so that if the process is interrupted we aren't left with an invalid file try { diff --git a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts index 7af81220814..4b9c8063356 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheDeferredWrites.test.ts @@ -249,18 +249,20 @@ describe('OperationBuildCache with deferred cache entry writes', () => { expect(writes.takeReport()).toMatchObject({ queuedCount: 0, pendingCount: 0 }); }); - it('uses the JavaScript fallback without sealing if native tar is not found', async () => { + it('seals nothing if tar is not found', async () => { _setTarUtilityPromiseForTesting(Promise.resolve(undefined)); const cloneFileAsync: jest.Mock = jest.fn(copyFileAsync); const writes: DeferredCacheEntryWrites = createWrites(cloneFileAsync); + // The operation reports the failure, instead of the daemon's log reporting it later. const result: boolean = await createSubject().trySetCacheEntryAsync(terminal, undefined, writes); await writes.waitForIdleAsync(); - expect(result).toBe(true); + expect(result).toBe(false); expect(cloneFileAsync).not.toHaveBeenCalled(); - expect(await restoreEntryAsync()).toEqual({ 'dist/index.js': 'index 1', 'dist/nested/a.js': 'a 1' }); - expect(terminalProvider.getWarningOutput({ normalizeSpecialCharacters: false })).toBe(''); + expect(terminalProvider.getWarningOutput({ normalizeSpecialCharacters: false })).toContain( + 'Unable to locate "tar".' + ); expect(writes.takeReport()).toMatchObject({ queuedCount: 0, pendingCount: 0 }); expect(logLines).toEqual([]); }); diff --git a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts index 06b48b649e9..1a7b7d3199b 100644 --- a/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts +++ b/libraries/rush-lib/src/logic/buildCache/test/OperationBuildCacheReceipt.test.ts @@ -5,7 +5,6 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import * as tar from 'tar'; import { StringBufferTerminalProvider, Terminal, type ITerminal } from '@rushstack/terminal'; import type { BuildCacheConfiguration } from '../../../api/BuildCacheConfiguration'; @@ -227,34 +226,6 @@ describe('OperationBuildCache receipts', () => { return JSON.parse(fs.readFileSync(path.join(cacheFolder, CACHE_ID), 'utf8')); } - it.each(['unavailable', 'failed'])( - 'writes a cache entry with JavaScript when native tar is %s', - async (reason) => { - if (reason === 'unavailable') { - _setTarUtilityPromiseForTesting(Promise.resolve(undefined)); - } else { - createArchiveMock.mockResolvedValue(1); - } - - writeFiles(projectFolder, ENTRY); - expect(await setCacheEntryAsync(createSubject())).toBe(true); - const archive: FakeArchive = {}; - await tar.list({ - file: path.join(cacheFolder, CACHE_ID), - onReadEntry: (entry) => { - const chunks: Buffer[] = []; - entry.on('data', (chunk: Buffer) => chunks.push(chunk)); - entry.on('end', () => { - archive[entry.path] = Buffer.concat(chunks).toString(); - }); - } - }); - expect(archive).toEqual(ENTRY); - expect(hasReceipt()).toBe(true); - expect(fs.readdirSync(cacheFolder)).toEqual([CACHE_ID]); - } - ); - // Waits for the writes in the background to make the condition true. async function waitForAsync(condition: () => boolean): Promise { while (!condition()) { From fde053316b38e0ac6f89ff35ff644817bd6b0f7d Mon Sep 17 00:00:00 2001 From: iclanton <5010588+iclanton@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:30:40 +0000 Subject: [PATCH 5/8] fixup! fixup! fixup! fixup! [rush] Add tarball support to deploy archives Fix CI snapshots and Windows tar tests; handle early stdin EOF as a closed pipe. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../package-extractor/src/TarExecutable.ts | 2 +- .../src/test/ArchiveManager.test.ts | 2 +- .../RushCommandLine.test.ts.snap | 2 +- .../CommandLineHelp.test.ts.snap | 2 +- .../src/utilities/test/TarExecutable.test.ts | 31 +++++++++++++++++++ 5 files changed, 35 insertions(+), 4 deletions(-) diff --git a/libraries/package-extractor/src/TarExecutable.ts b/libraries/package-extractor/src/TarExecutable.ts index 416acad1655..712dcd865f1 100644 --- a/libraries/package-extractor/src/TarExecutable.ts +++ b/libraries/package-extractor/src/TarExecutable.ts @@ -198,7 +198,7 @@ export class TarExecutable { if (input !== undefined) { childProcess.stdin!.on('error', (error: NodeJS.ErrnoException) => { // An incompatible or aborted tar may exit before reading the file list. - if (error.code === 'EPIPE') { + if (error.code === 'EPIPE' || error.code === 'EOF') { fileWriter.write(`[stdin] ${error.message}\n`); } else { childProcess.emit('error', error); diff --git a/libraries/package-extractor/src/test/ArchiveManager.test.ts b/libraries/package-extractor/src/test/ArchiveManager.test.ts index d97cd63e10e..e8994c893a2 100644 --- a/libraries/package-extractor/src/test/ArchiveManager.test.ts +++ b/libraries/package-extractor/src/test/ArchiveManager.test.ts @@ -120,7 +120,7 @@ describe(ArchiveManager.name, () => { const linkTargetPath: string = `${linksFolder}/linked-folder`; await FileSystem.ensureFolderAsync(`${linksFolder}/nested`); await FileSystem.ensureFolderAsync(linkTargetPath); - await FileSystem.createSymbolicLinkJunctionAsync({ newLinkPath: linkPath, linkTargetPath }); + await FileSystem.createSymbolicLinkFolderAsync({ newLinkPath: linkPath, linkTargetPath }); const archiveFilePath: string = `${testFolder}/links${ext}`; const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: linkPath, archivePath: 'nested\\link' }); diff --git a/libraries/rush-lib/src/api/test/__snapshots__/RushCommandLine.test.ts.snap b/libraries/rush-lib/src/api/test/__snapshots__/RushCommandLine.test.ts.snap index e28042fd3de..144bce05e7e 100644 --- a/libraries/rush-lib/src/api/test/__snapshots__/RushCommandLine.test.ts.snap +++ b/libraries/rush-lib/src/api/test/__snapshots__/RushCommandLine.test.ts.snap @@ -246,7 +246,7 @@ Object { "shortName": "-t", }, Object { - "description": "If specified, after the deployment has been prepared, \\"rush deploy\\" will create an archive containing the contents of the target folder. The newly created archive file will be placed according to the designated path, relative to the target folder. Supported file extensions: .zip", + "description": "If specified, after the deployment has been prepared, \\"rush deploy\\" will create an archive containing the contents of the target folder. The newly created archive file will be placed according to the designated path, relative to the target folder. Supported file extensions: .zip, .tar, .tar.gz, .tgz", "environmentVariable": undefined, "kind": "String", "longName": "--create-archive", diff --git a/libraries/rush-lib/src/cli/test/__snapshots__/CommandLineHelp.test.ts.snap b/libraries/rush-lib/src/cli/test/__snapshots__/CommandLineHelp.test.ts.snap index 6d2357c00e9..7617470e7a9 100644 --- a/libraries/rush-lib/src/cli/test/__snapshots__/CommandLineHelp.test.ts.snap +++ b/libraries/rush-lib/src/cli/test/__snapshots__/CommandLineHelp.test.ts.snap @@ -481,7 +481,7 @@ Optional arguments: contents of the target folder. The newly created archive file will be placed according to the designated path, relative to the target folder. - Supported file extensions: .zip + Supported file extensions: .zip, .tar, .tar.gz, .tgz --create-archive-only If specified, \\"rush deploy\\" will only create an archive containing the contents of the target folder. diff --git a/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts b/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts index d1c2d2f1743..6768104825a 100644 --- a/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts +++ b/libraries/rush-lib/src/utilities/test/TarExecutable.test.ts @@ -2,11 +2,14 @@ // See LICENSE in the project root for license information. import * as fs from 'node:fs'; +import { ChildProcess } from 'node:child_process'; import * as os from 'node:os'; import * as path from 'node:path'; import { performance } from 'node:perf_hooks'; +import { PassThrough } from 'node:stream'; import { setTimeout as delayAsync } from 'node:timers/promises'; +import { Executable } from '@rushstack/node-core-library'; import { StringBufferTerminalProvider, Terminal } from '@rushstack/terminal'; import { TarExecutable } from '@rushstack/package-extractor'; @@ -34,9 +37,37 @@ describe(TarExecutable.name, () => { }); afterEach(() => { + jest.restoreAllMocks(); fs.rmSync(folderPath, { recursive: true, force: true }); }); + it.each(['EPIPE', 'EOF'])('logs %s when tar exits before reading its file list', async (code) => { + const childProcess: ChildProcess = new ChildProcess(); + childProcess.stdin = new PassThrough(); + childProcess.stdout = new PassThrough(); + childProcess.stderr = new PassThrough(); + jest.spyOn(Executable, 'spawn').mockImplementationOnce(() => { + queueMicrotask(() => { + childProcess.stdin!.emit('error', Object.assign(new Error('pipe closed'), { code })); + childProcess.emit('close', 1, null); + }); + return childProcess; + }); + + const logFilePath: string = `${folderPath}/closed-pipe.log`; + expect( + await tar.tryCreateArchiveAsync({ + archivePath: `${folderPath}/closed-pipe.tar.gz`, + paths: ['lib/index.js'], + baseFolderPath, + logFilePath + }) + ).toBe(1); + const log: string = fs.readFileSync(logFilePath, 'utf8'); + expect(log).toContain('[stdin] pipe closed'); + expect(log).toContain('Exited with code "1"'); + }); + it('names the members of an archive from its base folder', async () => { const archivePath: string = path.join(folderPath, 'entry.tar.gz'); const exitCode: number = await tar.tryCreateArchiveAsync({ From 483d37c28250e8356f5c45265dfb497448478a5c Mon Sep 17 00:00:00 2001 From: iclanton <5010588+iclanton@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:30:45 +0000 Subject: [PATCH 6/8] fixup! fixup! fixup! fixup! fixup! [rush] Add tarball support to deploy archives Use file-path-only archive inputs and stage generated assets once in AssetHandler. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- libraries/package-extractor/README.md | 4 +- .../package-extractor/src/ArchiveManager.ts | 116 ++++---------- .../package-extractor/src/AssetHandler.ts | 112 +++++++++----- .../package-extractor/src/PackageExtractor.ts | 36 +++-- .../src/test/ArchiveManager.test.ts | 145 +++++++++++++++--- .../src/test/PackageExtractor.test.ts | 36 +++++ 6 files changed, 285 insertions(+), 164 deletions(-) diff --git a/libraries/package-extractor/README.md b/libraries/package-extractor/README.md index 198024bc13c..90eef64d512 100644 --- a/libraries/package-extractor/README.md +++ b/libraries/package-extractor/README.md @@ -7,7 +7,9 @@ tar (`.tar.gz` or `.tgz`) archives, including when `createArchiveOnly` is enable Tar archives require the native `tar` executable on PATH. Archive-only tar deployments stage assets in a unique folder under `archiveTempFolder` (default: `common/temp` under the source root), then remove that folder after success or failure. ZIP archives continue -to use JavaScript and do not require staging. +to use JavaScript; archive-only ZIP deployments stage only generated files and read existing +source files directly. Materialized deployments archive their target files without staging. +Generated assets are written once by the asset handler; the archive manager accepts only file paths. `TarExecutable` shares memoized native discovery and execution with Rush's build cache. diff --git a/libraries/package-extractor/src/ArchiveManager.ts b/libraries/package-extractor/src/ArchiveManager.ts index 65a3f5fed83..690b15de6de 100644 --- a/libraries/package-extractor/src/ArchiveManager.ts +++ b/libraries/package-extractor/src/ArchiveManager.ts @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { randomUUID } from 'node:crypto'; import path from 'node:path'; import JSZip from 'jszip'; -import { FileSystem, type FileSystemStats, Path, type PosixModeBits } from '@rushstack/node-core-library'; +import { FileSystem, type FileSystemStats, Path } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; import { TarExecutable } from './TarExecutable'; @@ -22,28 +21,19 @@ const DEFAULT_FILE_PERMISSIONS: number = 0o755; const SYMBOLIC_LINK_PERMISSIONS: number = 0o120000 | DEFAULT_FILE_PERMISSIONS; export interface IAddToArchiveOptions { - filePath?: string; - fileData?: Buffer | string; + filePath: string; archivePath: string; stats?: FileSystemStats; } -interface IArchiveEntry { - filePath?: string; - fileData?: Buffer | string; - stats?: FileSystemStats; -} - export interface ICreateArchiveOptions { terminal: ITerminal; - /** Omit when assets have not been materialized, such as archive-only deployment. */ - sourceFolder?: string; - tempFolder: string; + sourceFolder: string; } export class ArchiveManager { readonly #archiveFormat: ArchiveFormat; - readonly #entries: Map = new Map(); + readonly #entries: Map = new Map(); public constructor(archiveFormat: ArchiveFormat) { this.#archiveFormat = archiveFormat; @@ -62,36 +52,30 @@ export class ArchiveManager { } public async addToArchiveAsync(options: IAddToArchiveOptions): Promise { - const { filePath, fileData, archivePath, stats } = options; - if (!filePath && fileData === undefined) { - throw new Error('Either filePath or fileData must be provided'); - } - + const { archivePath } = options; const addPath: string = Path.convertToSlashes(archivePath); if (path.isAbsolute(addPath) || addPath.split('/').includes('..')) { throw new Error('Archive entries must be relative paths within the archive'); } - this.#entries.set(addPath, { filePath, fileData, stats }); + this.#entries.set(addPath, options); } public async createArchiveAsync(archiveFilePath: string, options?: ICreateArchiveOptions): Promise { if (this.#archiveFormat === 'zip') { const zip: JSZip = new JSZip(); - for (const [archivePath, { filePath, fileData, stats: providedStats }] of this.#entries) { - let data: Buffer | string = fileData ?? ''; - let permissions: number = DEFAULT_FILE_PERMISSIONS; - if (filePath) { - const stats: FileSystemStats = providedStats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); - if (stats.isSymbolicLink()) { - data = await FileSystem.readLinkAsync(filePath); - permissions = SYMBOLIC_LINK_PERMISSIONS; - } else if (stats.isDirectory()) { - throw new Error('Directories cannot be added to the archive'); - } else { - data = await FileSystem.readFileToBufferAsync(filePath); - permissions = stats.mode; - } + for (const [archivePath, { filePath, stats: providedStats }] of this.#entries) { + let data: Buffer | string; + let permissions: number; + const stats: FileSystemStats = providedStats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); + if (stats.isSymbolicLink()) { + data = await FileSystem.readLinkAsync(filePath); + permissions = SYMBOLIC_LINK_PERMISSIONS; + } else if (stats.isDirectory()) { + throw new Error('Directories cannot be added to the archive'); + } else { + data = await FileSystem.readFileToBufferAsync(filePath); + permissions = stats.mode; } zip.file(archivePath, data, { @@ -107,65 +91,29 @@ export class ArchiveManager { await FileSystem.writeFileAsync(archiveFilePath, zipContent); } else { if (!options) { - throw new Error('Native tar creation requires terminal and temporary folder options'); + throw new Error('Native tar creation requires terminal and source folder options'); } - const { terminal, sourceFolder, tempFolder } = options; + const { terminal, sourceFolder } = options; const tarExecutable: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); if (!tarExecutable) { throw new Error('Native tar is required to create tar archives. Ensure "tar" is on PATH.'); } - const archiveSourceFolder: string = - sourceFolder ?? path.resolve(tempFolder, `deploy-archive-${randomUUID()}`); const logFilePath: string = `${archiveFilePath}.log`; - try { - if (!sourceFolder) { - await FileSystem.ensureFolderAsync(archiveSourceFolder); - for (const [archivePath, { filePath, fileData, stats: providedStats }] of this.#entries) { - const stagedPath: string = path.resolve(archiveSourceFolder, archivePath); - await FileSystem.ensureFolderAsync(path.dirname(stagedPath)); - if (filePath) { - const stats: FileSystemStats = - providedStats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); - if (stats.isSymbolicLink()) { - await FileSystem.createSymbolicLinkFileAsync({ - newLinkPath: stagedPath, - linkTargetPath: await FileSystem.readLinkAsync(filePath) - }); - } else if (stats.isDirectory()) { - throw new Error('Directories cannot be added to the archive'); - } else { - await FileSystem.copyFileAsync({ sourcePath: filePath, destinationPath: stagedPath }); - } - } else { - await FileSystem.writeFileAsync(stagedPath, fileData ?? ''); - await FileSystem.changePosixModeBitsAsync( - stagedPath, - DEFAULT_FILE_PERMISSIONS as PosixModeBits - ); - } - } - } - - const exitCode: number = await tarExecutable.tryCreateArchiveAsync({ - archivePath: archiveFilePath, - paths: [...this.#entries.keys()], - baseFolderPath: archiveSourceFolder, - logFilePath, - gzip: this.#archiveFormat === 'tgz' - }); - if (exitCode !== 0) { - await FileSystem.deleteFileAsync(archiveFilePath); - throw new Error(`Native tar exited with code ${exitCode}. See "${logFilePath}" for details.`); - } - - await FileSystem.deleteFileAsync(logFilePath); - } finally { - if (!sourceFolder) { - await FileSystem.deleteFolderAsync(archiveSourceFolder); - } + const exitCode: number = await tarExecutable.tryCreateArchiveAsync({ + archivePath: archiveFilePath, + paths: [...this.#entries.keys()], + baseFolderPath: sourceFolder, + logFilePath, + gzip: this.#archiveFormat === 'tgz' + }); + if (exitCode !== 0) { + await FileSystem.deleteFileAsync(archiveFilePath); + throw new Error(`Native tar exited with code ${exitCode}. See "${logFilePath}" for details.`); } + + await FileSystem.deleteFileAsync(logFilePath); } } } diff --git a/libraries/package-extractor/src/AssetHandler.ts b/libraries/package-extractor/src/AssetHandler.ts index c0a2c88e2f5..d8a95733b3f 100644 --- a/libraries/package-extractor/src/AssetHandler.ts +++ b/libraries/package-extractor/src/AssetHandler.ts @@ -3,8 +3,15 @@ import path from 'node:path'; import fs from 'node:fs'; +import { randomUUID } from 'node:crypto'; -import { Async, FileSystem, Path, type FileSystemStats } from '@rushstack/node-core-library'; +import { + Async, + FileSystem, + Path, + type FileSystemStats, + type PosixModeBits +} from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; import { ArchiveManager } from './ArchiveManager'; @@ -53,6 +60,7 @@ export class AssetHandler { readonly #archiveManager: ArchiveManager | undefined; readonly #archiveFilePath: string | undefined; readonly #archiveTempFolder: string; + readonly #stageArchiveAssets: boolean; readonly #linkCreationMode: LinkCreationMode; readonly #includedAssetPaths: Set = new Set(); #isFinalized: boolean = false; @@ -70,7 +78,14 @@ export class AssetHandler { this.#terminal = terminal; this.#sourceRootFolder = sourceRootFolder; this.#targetRootFolder = targetRootFolder; - this.#archiveTempFolder = options.archiveTempFolder ?? `${sourceRootFolder}/common/temp`; + this.#archiveTempFolder = path.resolve( + options.archiveTempFolder ?? `${sourceRootFolder}/common/temp`, + `deploy-archive-${randomUUID()}` + ); + this.#stageArchiveAssets = + createArchiveOnly && + !!createArchiveFilePath && + ArchiveManager.getArchiveFormat(createArchiveFilePath) !== 'zip'; this.#symlinkAnalyzer = symlinkAnalyzer; if (createArchiveFilePath) { this.#archiveFilePath = path.resolve(targetRootFolder, createArchiveFilePath); @@ -93,13 +108,13 @@ export class AssetHandler { if (this.#isFinalized) { throw new Error('includeAssetAsync() cannot be called after finalizeAsync()'); } - if (!sourceFilePath && !sourceFileContent) { + if (!sourceFilePath && sourceFileContent === undefined) { if (!Path.isUnder(targetFilePath, this.#targetRootFolder)) { throw new Error('The existing asset path must be under the target root folder'); } sourceFilePath = targetFilePath; } - if (sourceFilePath && sourceFileContent) { + if (sourceFilePath && sourceFileContent !== undefined) { throw new Error('Either sourceFilePath or sourceFileContent must be provided, but not both'); } if (this.#includedAssetPaths.has(targetFilePath)) { @@ -109,41 +124,45 @@ export class AssetHandler { throw new Error(`The asset at path "${targetFilePath}" has already been included`); } - if (!this.#createArchiveOnly) { + const targetRelativeFilePath: string = path.relative(this.#targetRootFolder, targetFilePath); + if (path.isAbsolute(targetRelativeFilePath) || targetRelativeFilePath.split(path.sep).includes('..')) { + throw new Error('The asset path must be under the target root folder'); + } + + const writePath: string = this.#createArchiveOnly + ? path.resolve(this.#archiveTempFolder, targetRelativeFilePath) + : targetFilePath; + if (!this.#createArchiveOnly || this.#stageArchiveAssets || sourceFileContent !== undefined) { // Ignore when the source file is the same as the target file, as it's a no-op - if (sourceFilePath && sourceFilePath !== targetFilePath) { + if (sourceFilePath && sourceFilePath !== writePath) { // Use the fs.copyFile API instead of FileSystem.copyFileAsync() since copyFileAsync performs // a needless stat() call to determine if it's a file or folder, and we already know it's a file. try { - await fs.promises.copyFile(sourceFilePath, targetFilePath, fs.constants.COPYFILE_EXCL); + await fs.promises.copyFile(sourceFilePath, writePath, fs.constants.COPYFILE_EXCL); } catch (e: unknown) { if (!FileSystem.isNotExistError(e as Error)) { throw e; } // The parent folder may not exist, so ensure it exists before trying to copy again - await FileSystem.ensureFolderAsync(path.dirname(targetFilePath)); - await fs.promises.copyFile(sourceFilePath, targetFilePath, fs.constants.COPYFILE_EXCL); + await FileSystem.ensureFolderAsync(path.dirname(writePath)); + await fs.promises.copyFile(sourceFilePath, writePath, fs.constants.COPYFILE_EXCL); } - } else if (sourceFileContent) { - await FileSystem.writeFileAsync(targetFilePath, sourceFileContent, { + } else if (sourceFileContent !== undefined) { + await FileSystem.writeFileAsync(writePath, sourceFileContent, { ensureFolderExists: true }); + if (this.#createArchiveOnly) { + await FileSystem.changePosixModeBitsAsync(writePath, 0o755 as PosixModeBits); + } } } if (this.#archiveManager) { - const targetRelativeFilePath: string = path.relative(this.#targetRootFolder, targetFilePath); - if (sourceFilePath) { - await this.#archiveManager.addToArchiveAsync({ - filePath: sourceFilePath, - archivePath: targetRelativeFilePath - }); - } else if (sourceFileContent) { - await this.#archiveManager.addToArchiveAsync({ - fileData: sourceFileContent, - archivePath: targetRelativeFilePath - }); - } + await this.#archiveManager.addToArchiveAsync({ + filePath: + this.#createArchiveOnly && !this.#stageArchiveAssets && sourceFilePath ? sourceFilePath : writePath, + archivePath: targetRelativeFilePath + }); } this.#includedAssetPaths.add(targetFilePath); @@ -153,6 +172,12 @@ export class AssetHandler { return [...this.#includedAssetPaths]; } + public async cleanupAsync(): Promise { + if (this.#createArchiveOnly) { + await FileSystem.deleteFolderAsync(this.#archiveTempFolder); + } + } + public async finalizeAsync(options?: IFinalizeOptions): Promise { const { onAfterExtractSymlinksAsync } = options ?? {}; @@ -160,26 +185,33 @@ export class AssetHandler { throw new Error('finalizeAsync() has already been called'); } - if (this.#linkCreationMode === 'default') { - this.#terminal.writeLine('Creating symlinks'); - const linksToCopy: ILinkInfo[] = this.#symlinkAnalyzer.reportSymlinks(); - await Async.forEachAsync(linksToCopy, async (linkToCopy: ILinkInfo) => { - await this.#extractSymlinkAsync(linkToCopy); - }); - } + try { + if (this.#linkCreationMode === 'default') { + this.#terminal.writeLine('Creating symlinks'); + const linksToCopy: ILinkInfo[] = this.#symlinkAnalyzer.reportSymlinks(); + await Async.forEachAsync(linksToCopy, async (linkToCopy: ILinkInfo) => { + await this.#extractSymlinkAsync(linkToCopy); + }); + } - await onAfterExtractSymlinksAsync?.(); + await onAfterExtractSymlinksAsync?.(); - if (this.#archiveManager && this.#archiveFilePath) { - this.#terminal.writeLine(`Creating archive at "${this.#archiveFilePath}"`); - await this.#archiveManager.createArchiveAsync(this.#archiveFilePath, { - terminal: this.#terminal, - sourceFolder: this.#createArchiveOnly ? undefined : this.#targetRootFolder, - tempFolder: this.#archiveTempFolder - }); - } + if (this.#archiveManager && this.#archiveFilePath) { + if (this.#stageArchiveAssets) { + await FileSystem.ensureFolderAsync(this.#archiveTempFolder); + } - this.#isFinalized = true; + this.#terminal.writeLine(`Creating archive at "${this.#archiveFilePath}"`); + await this.#archiveManager.createArchiveAsync(this.#archiveFilePath, { + terminal: this.#terminal, + sourceFolder: this.#createArchiveOnly ? this.#archiveTempFolder : this.#targetRootFolder + }); + } + + this.#isFinalized = true; + } finally { + await this.cleanupAsync(); + } } /** diff --git a/libraries/package-extractor/src/PackageExtractor.ts b/libraries/package-extractor/src/PackageExtractor.ts index 087b22d015e..56a8aa6059a 100644 --- a/libraries/package-extractor/src/PackageExtractor.ts +++ b/libraries/package-extractor/src/PackageExtractor.ts @@ -239,7 +239,7 @@ export interface IExtractorOptions { createArchiveFilePath?: string; /** - * The parent folder for temporary tar archive staging. Defaults to "common/temp" under + * The parent folder for temporary archive-only assets. Defaults to "common/temp" under * {@link IExtractorOptions.sourceRootFolder}. Staging folders are removed after archive creation. */ archiveTempFolder?: string; @@ -420,22 +420,26 @@ export class PackageExtractor { existingDependencyConfigurations.push(dependencyConfiguration); } - await this.#performExtractionAsync(options, state); - await state.assetHandler.finalizeAsync({ - onAfterExtractSymlinksAsync: async () => { - // We need the symlinks to be created before attempting to create the bin links, since it requires - // the node_modules folder to be realized. While we're here, we may as well perform some specific - // link creation tasks and write the extractor-metadata.json file before the asset handler finalizes. - if (linkCreation === 'default') { - await this.#makeBinLinksAsync(options, state); - } else if (linkCreation === 'script') { - await this.#writeCreateLinksScriptAsync(options, state); - } + try { + await this.#performExtractionAsync(options, state); + await state.assetHandler.finalizeAsync({ + onAfterExtractSymlinksAsync: async () => { + // We need the symlinks to be created before attempting to create the bin links, since it requires + // the node_modules folder to be realized. While we're here, we may as well perform some specific + // link creation tasks and write the extractor-metadata.json file before the asset handler finalizes. + if (linkCreation === 'default') { + await this.#makeBinLinksAsync(options, state); + } else if (linkCreation === 'script') { + await this.#writeCreateLinksScriptAsync(options, state); + } - terminal.writeLine('Creating extractor-metadata.json'); - await this.#writeExtractorMetadataAsync(options, state); - } - }); + terminal.writeLine('Creating extractor-metadata.json'); + await this.#writeExtractorMetadataAsync(options, state); + } + }); + } finally { + await state.assetHandler.cleanupAsync(); + } } async #performExtractionAsync(options: IExtractorOptions, state: IExtractorState): Promise { diff --git a/libraries/package-extractor/src/test/ArchiveManager.test.ts b/libraries/package-extractor/src/test/ArchiveManager.test.ts index e8994c893a2..667eccf83e1 100644 --- a/libraries/package-extractor/src/test/ArchiveManager.test.ts +++ b/libraries/package-extractor/src/test/ArchiveManager.test.ts @@ -46,6 +46,22 @@ describe(ArchiveManager.name, () => { let generatedContent: string; const terminal: Terminal = new Terminal(new StringBufferTerminalProvider()); + function createHandler(archiveFilePath: string, createArchiveOnly: boolean = true): AssetHandler { + return new AssetHandler({ + terminal, + mainProjectName: 'test', + projectConfigurations: [], + sourceRootFolder: sourceFolder, + targetRootFolder: path.dirname(archiveFilePath), + overwriteExisting: false, + linkCreation: 'none', + symlinkAnalyzer: new SymlinkAnalyzer(), + createArchiveFilePath: archiveFilePath, + archiveTempFolder: tempFolder, + createArchiveOnly + }); + } + beforeAll(async () => { await FileSystem.ensureEmptyFolderAsync(testFolder); await FileSystem.ensureFolderAsync(tempFolder); @@ -124,7 +140,7 @@ describe(ArchiveManager.name, () => { const archiveFilePath: string = `${testFolder}/links${ext}`; const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: linkPath, archivePath: 'nested\\link' }); - await manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder, sourceFolder: linksFolder }); + await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder: linksFolder }); const entries: Map = await readTarAsync(archiveFilePath); expect(entries.get('nested/link')).toMatchObject({ @@ -138,7 +154,10 @@ describe(ArchiveManager.name, () => { const archiveFilePath: string = `${testFolder}/deploy.zip`; const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'nested\\input.txt' }); - await manager.addToArchiveAsync({ fileData: generatedContent, archivePath: 'generated.txt' }); + await manager.addToArchiveAsync({ + filePath: `${sourceFolder}/generated.txt`, + archivePath: 'generated.txt' + }); await manager.createArchiveAsync(archiveFilePath); const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); @@ -146,12 +165,73 @@ describe(ArchiveManager.name, () => { expect(await zip.file('generated.txt')?.async('string')).toBe(generatedContent); }); + it.each(['.zip', '.tar', '.tgz'])('writes generated %s assets only once per deployment', async (ext) => { + for (const createArchiveOnly of [false, true]) { + const targetRootFolder: string = `${testFolder}/single-write-${ext.slice(1)}-${createArchiveOnly}`; + await FileSystem.ensureFolderAsync(targetRootFolder); + const archiveFilePath: string = `${targetRootFolder}/deploy${ext}`; + const targetFilePath: string = `${targetRootFolder}/generated.txt`; + const handler: AssetHandler = createHandler(archiveFilePath, createArchiveOnly); + const writeSpy = jest.spyOn(FileSystem, 'writeFileAsync'); + const addSpy = jest.spyOn(ArchiveManager.prototype, 'addToArchiveAsync'); + await handler.includeAssetAsync({ sourceFileContent: generatedContent, targetFilePath }); + await handler.includeAssetAsync({ + sourceFileContent: '', + targetFilePath: `${targetRootFolder}/empty.txt` + }); + await handler.finalizeAsync(); + + const writes = writeSpy.mock.calls.filter(([, content]) => content === generatedContent); + expect(writes).toHaveLength(1); + const [[writtenPath]] = writes; + expect(addSpy).toHaveBeenCalledWith({ + filePath: writtenPath, + archivePath: 'generated.txt' + }); + if (createArchiveOnly) { + expect(Path.convertToSlashes(writtenPath)).toContain(`${Path.convertToSlashes(tempFolder)}/`); + expect(await FileSystem.existsAsync(targetFilePath)).toBe(false); + } else { + expect(writtenPath).toBe(targetFilePath); + } + + if (ext === '.zip') { + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(await zip.file('generated.txt')?.async('string')).toBe(generatedContent); + expect(await zip.file('empty.txt')?.async('string')).toBe(''); + } else { + const entries: Map = await readTarAsync(archiveFilePath); + expect(entries.get('generated.txt')?.data.toString()).toBe(generatedContent); + expect(entries.get('empty.txt')?.data.length).toBe(0); + } + + expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); + jest.restoreAllMocks(); + } + }); + + it('archives the materialized target rather than the original source in ZIP deployments', async () => { + const targetRootFolder: string = `${testFolder}/zip-target`; + await FileSystem.ensureFolderAsync(targetRootFolder); + const archiveFilePath: string = `${targetRootFolder}/deploy.zip`; + const targetFilePath: string = `${targetRootFolder}/input.txt`; + const handler: AssetHandler = createHandler(archiveFilePath, false); + await handler.includeAssetAsync({ sourceFilePath: sourceFile, targetFilePath }); + await FileSystem.writeFileAsync(targetFilePath, 'updated target'); + await handler.finalizeAsync(); + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(await zip.file('input.txt')?.async('string')).toBe('updated target'); + }); + it('preserves executable permissions when staging archive-only assets', async () => { const archiveFilePath: string = `${testFolder}/permissions.tar`; const executablePath: string = `${sourceFolder}/executable.sh`; - const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); - await manager.addToArchiveAsync({ filePath: executablePath, archivePath: 'executable.sh' }); - await manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder }); + const handler: AssetHandler = createHandler(archiveFilePath); + await handler.includeAssetAsync({ + sourceFilePath: executablePath, + targetFilePath: `${testFolder}/executable.sh` + }); + await handler.finalizeAsync(); const entry: ITarEntry | undefined = (await readTarAsync(archiveFilePath)).get('executable.sh'); expect(entry?.data).toEqual(await FileSystem.readFileToBufferAsync(executablePath)); if (process.platform !== 'win32') { @@ -170,7 +250,7 @@ describe(ArchiveManager.name, () => { const archiveFilePath: string = `${testFolder}/native.tar`; const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); - await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder, tempFolder }); + await manager.createArchiveAsync(archiveFilePath, { terminal, sourceFolder }); expect(createSpy).toHaveBeenCalledWith( expect.objectContaining({ baseFolderPath: sourceFolder, paths: ['input.txt'], gzip: false }) ); @@ -183,14 +263,24 @@ describe(ArchiveManager.name, () => { expect(() => ArchiveManager.getArchiveFormat('deploy.gz')).toThrow('Supported archive file extensions'); }); - it('cleans up staging when copying an asset fails', async () => { + it('cleans up staging when generating an asset during finalization fails', async () => { const archiveFilePath: string = `${testFolder}/copy-failure.tgz`; - const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); - await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'file.txt' }); - jest.spyOn(FileSystem, 'copyFileAsync').mockRejectedValue(new Error('copy failed')); - await expect(manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder })).rejects.toThrow( - 'copy failed' - ); + const handler: AssetHandler = createHandler(archiveFilePath); + await handler.includeAssetAsync({ + sourceFileContent: generatedContent, + targetFilePath: `${testFolder}/generated.txt` + }); + jest.spyOn(FileSystem, 'writeFileAsync').mockRejectedValue(new Error('write failed')); + await expect( + handler.finalizeAsync({ + onAfterExtractSymlinksAsync: async () => { + await handler.includeAssetAsync({ + sourceFileContent: 'content', + targetFilePath: `${testFolder}/other.txt` + }); + } + }) + ).rejects.toThrow('write failed'); expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); expect(await FileSystem.existsAsync(archiveFilePath)).toBe(false); }); @@ -217,9 +307,12 @@ describe(ArchiveManager.name, () => { initializeSpy.mockResolvedValue(nativeTar); } - const manager: ArchiveManager = new ArchiveManager(ArchiveManager.getArchiveFormat(archiveFilePath)); - await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); - await expect(manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder })).rejects.toThrow( + const handler: AssetHandler = createHandler(archiveFilePath); + await handler.includeAssetAsync({ + sourceFilePath: sourceFile, + targetFilePath: `${testFolder}/input.txt` + }); + await expect(handler.finalizeAsync()).rejects.toThrow( reason === 'unavailable' ? 'Native tar is required' : 'Native tar exited with code 1' ); expect(initializeSpy).toHaveBeenCalled(); @@ -237,9 +330,12 @@ describe(ArchiveManager.name, () => { const archivePaths: string[] = [`${testFolder}/concurrent-1.tgz`, `${testFolder}/concurrent-2.tgz`]; await Promise.all( archivePaths.map(async (archivePath, index) => { - const manager: ArchiveManager = new ArchiveManager('tgz'); - await manager.addToArchiveAsync({ fileData: `content ${index}`, archivePath: 'input.txt' }); - await manager.createArchiveAsync(archivePath, { terminal, tempFolder }); + const handler: AssetHandler = createHandler(archivePath); + await handler.includeAssetAsync({ + sourceFileContent: `content ${index}`, + targetFilePath: `${testFolder}/input.txt` + }); + await handler.finalizeAsync(); expect((await readTarAsync(archivePath)).get('input.txt')?.data.toString()).toBe(`content ${index}`); }) ); @@ -260,12 +356,15 @@ describe(ArchiveManager.name, () => { memberNames.push(' trailing spaces ', 'line\nbreak', 'line\rbreak'); } - const manager: ArchiveManager = new ArchiveManager('tar'); + const handler: AssetHandler = createHandler(archiveFilePath); for (const archivePath of memberNames) { - await manager.addToArchiveAsync({ fileData: archivePath, archivePath }); + await handler.includeAssetAsync({ + sourceFileContent: archivePath, + targetFilePath: `${testFolder}/${archivePath}` + }); } - await manager.createArchiveAsync(archiveFilePath, { terminal, tempFolder }); + await handler.finalizeAsync(); const entries: Map = await readTarAsync(archiveFilePath); for (const memberName of memberNames) { expect(entries.get(memberName)?.data.toString()).toBe(memberName); @@ -275,7 +374,7 @@ describe(ArchiveManager.name, () => { it('rejects archive entries outside the staging folder', async () => { const manager: ArchiveManager = new ArchiveManager('tar'); await expect( - manager.addToArchiveAsync({ fileData: 'content', archivePath: '../outside' }) + manager.addToArchiveAsync({ filePath: sourceFile, archivePath: '../outside' }) ).rejects.toThrow('relative paths within the archive'); }); diff --git a/libraries/package-extractor/src/test/PackageExtractor.test.ts b/libraries/package-extractor/src/test/PackageExtractor.test.ts index e16677fd277..fd6931ddcec 100644 --- a/libraries/package-extractor/src/test/PackageExtractor.test.ts +++ b/libraries/package-extractor/src/test/PackageExtractor.test.ts @@ -2,6 +2,7 @@ // See LICENSE in the project root for license information. import path from 'node:path'; +import fs from 'node:fs'; import type { ChildProcess } from 'node:child_process'; import { Executable, FileSystem, Sort } from '@rushstack/node-core-library'; @@ -52,6 +53,41 @@ describe(PackageExtractor.name, () => { const terminal = new Terminal(new StringBufferTerminalProvider()); const packageExtractor = new PackageExtractor(); + it('removes archive-only staging when extraction fails after copying a file', async () => { + const targetFolder: string = `${extractorTargetFolder}/archive-copy-failure`; + const archiveTempFolder: string = `${extractorTargetFolder}/archive-copy-failure-temp`; + await FileSystem.ensureEmptyFolderAsync(archiveTempFolder); + const copyFileAsync: typeof fs.promises.copyFile = fs.promises.copyFile; + const copySpy = jest + .spyOn(fs.promises, 'copyFile') + .mockImplementation(async (source, destination, mode) => { + await copyFileAsync(source, destination, mode); + throw new Error('copy failed after writing'); + }); + try { + await expect( + packageExtractor.extractAsync({ + mainProjectName: project1PackageName, + sourceRootFolder: repoRoot, + targetRootFolder: targetFolder, + overwriteExisting: true, + projectConfigurations: getDefaultProjectConfigurations(), + terminal, + createArchiveOnly: true, + createArchiveFilePath: 'deploy.tgz', + archiveTempFolder, + includeNpmIgnoreFiles: true, + linkCreation: 'none' + }) + ).rejects.toThrow('copy failed after writing'); + expect(copySpy).toHaveBeenCalled(); + expect(await FileSystem.readFolderItemNamesAsync(archiveTempFolder)).toEqual([]); + expect(await FileSystem.readFolderItemNamesAsync(targetFolder)).toEqual([]); + } finally { + copySpy.mockRestore(); + } + }); + it('should extract project', async () => { const targetFolder: string = path.join(extractorTargetFolder, 'extractor-output-01'); From a47409b7742900c8b3881747a14def7815d22ef3 Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 26 Nov 2026 13:09:03 -0800 Subject: [PATCH 7/8] Update tsdoc-metadata. --- build-tests/api-extractor-test-05/dist/tsdoc-metadata.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build-tests/api-extractor-test-05/dist/tsdoc-metadata.json b/build-tests/api-extractor-test-05/dist/tsdoc-metadata.json index ccb284c3209..b8d504d3f76 100644 --- a/build-tests/api-extractor-test-05/dist/tsdoc-metadata.json +++ b/build-tests/api-extractor-test-05/dist/tsdoc-metadata.json @@ -5,7 +5,7 @@ "toolPackages": [ { "packageName": "@microsoft/api-extractor", - "packageVersion": "7.58.11" + "packageVersion": "7.60.1" } ] } From 4c430384dad19b229e7142b83586b8fec55871e5 Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 26 Nov 2026 13:19:40 -0800 Subject: [PATCH 8/8] fixup! [rush] Add tarball support to deploy archives Address latest archive review comments, preserving ZIP order and concurrent staging isolation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- libraries/package-extractor/README.md | 5 +- .../package-extractor/src/ArchiveManager.ts | 48 +++++---- .../package-extractor/src/AssetHandler.ts | 13 ++- .../src/test/ArchiveManager.test.ts | 98 ++++++++++++++++++- 4 files changed, 135 insertions(+), 29 deletions(-) diff --git a/libraries/package-extractor/README.md b/libraries/package-extractor/README.md index 90eef64d512..b30e6f749c4 100644 --- a/libraries/package-extractor/README.md +++ b/libraries/package-extractor/README.md @@ -5,8 +5,9 @@ A library used for creating an isolated copy of a package and, optionally, bundl The `createArchiveFilePath` option supports ZIP (`.zip`), tar (`.tar`), and gzip-compressed tar (`.tar.gz` or `.tgz`) archives, including when `createArchiveOnly` is enabled. Tar archives require the native `tar` executable on PATH. Archive-only tar deployments -stage assets in a unique folder under `archiveTempFolder` (default: `common/temp` under -the source root), then remove that folder after success or failure. ZIP archives continue +stage assets in a unique timestamp-based folder under `archiveTempFolder` (default: +`common/temp` under the source root), then remove that folder after success or failure. +ZIP archives continue to use JavaScript; archive-only ZIP deployments stage only generated files and read existing source files directly. Materialized deployments archive their target files without staging. Generated assets are written once by the asset handler; the archive manager accepts only file paths. diff --git a/libraries/package-extractor/src/ArchiveManager.ts b/libraries/package-extractor/src/ArchiveManager.ts index 690b15de6de..78130751dcf 100644 --- a/libraries/package-extractor/src/ArchiveManager.ts +++ b/libraries/package-extractor/src/ArchiveManager.ts @@ -5,10 +5,11 @@ import path from 'node:path'; import JSZip from 'jszip'; -import { FileSystem, type FileSystemStats, Path } from '@rushstack/node-core-library'; +import { Async, FileSystem, type FileSystemStats, Path } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; import { TarExecutable } from './TarExecutable'; +import { MAX_CONCURRENCY } from './scripts/createLinks/utilities/constants'; export type ArchiveFormat = 'zip' | 'tar' | 'tgz'; @@ -34,6 +35,7 @@ export interface ICreateArchiveOptions { export class ArchiveManager { readonly #archiveFormat: ArchiveFormat; readonly #entries: Map = new Map(); + #tarExecutablePromise: Promise | undefined; public constructor(archiveFormat: ArchiveFormat) { this.#archiveFormat = archiveFormat; @@ -64,20 +66,29 @@ export class ArchiveManager { public async createArchiveAsync(archiveFilePath: string, options?: ICreateArchiveOptions): Promise { if (this.#archiveFormat === 'zip') { const zip: JSZip = new JSZip(); - for (const [archivePath, { filePath, stats: providedStats }] of this.#entries) { - let data: Buffer | string; - let permissions: number; - const stats: FileSystemStats = providedStats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); - if (stats.isSymbolicLink()) { - data = await FileSystem.readLinkAsync(filePath); - permissions = SYMBOLIC_LINK_PERMISSIONS; - } else if (stats.isDirectory()) { - throw new Error('Directories cannot be added to the archive'); - } else { - data = await FileSystem.readFileToBufferAsync(filePath); - permissions = stats.mode; - } - + const entries: { archivePath: string; data: Buffer | string; permissions: number }[] = + await Async.mapAsync( + this.#entries, + async ([archivePath, { filePath, stats: providedStats }]) => { + let data: Buffer | string; + let permissions: number; + const stats: FileSystemStats = + providedStats ?? (await FileSystem.getLinkStatisticsAsync(filePath)); + if (stats.isSymbolicLink()) { + data = await FileSystem.readLinkAsync(filePath); + permissions = SYMBOLIC_LINK_PERMISSIONS; + } else if (stats.isDirectory()) { + throw new Error('Directories cannot be added to the archive'); + } else { + data = await FileSystem.readFileToBufferAsync(filePath); + permissions = stats.mode; + } + + return { archivePath, data, permissions }; + }, + { concurrency: MAX_CONCURRENCY } + ); + for (const { archivePath, data, permissions } of entries) { zip.file(archivePath, data, { unixPermissions: permissions, dir: false @@ -95,7 +106,8 @@ export class ArchiveManager { } const { terminal, sourceFolder } = options; - const tarExecutable: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + const tarExecutable: TarExecutable | undefined = await (this.#tarExecutablePromise ??= + TarExecutable.tryInitializeAsync(terminal)); if (!tarExecutable) { throw new Error('Native tar is required to create tar archives. Ensure "tar" is on PATH.'); } @@ -111,9 +123,9 @@ export class ArchiveManager { if (exitCode !== 0) { await FileSystem.deleteFileAsync(archiveFilePath); throw new Error(`Native tar exited with code ${exitCode}. See "${logFilePath}" for details.`); + } else { + await FileSystem.deleteFileAsync(logFilePath); } - - await FileSystem.deleteFileAsync(logFilePath); } } } diff --git a/libraries/package-extractor/src/AssetHandler.ts b/libraries/package-extractor/src/AssetHandler.ts index d8a95733b3f..714e2d7ed7a 100644 --- a/libraries/package-extractor/src/AssetHandler.ts +++ b/libraries/package-extractor/src/AssetHandler.ts @@ -3,7 +3,6 @@ import path from 'node:path'; import fs from 'node:fs'; -import { randomUUID } from 'node:crypto'; import { Async, @@ -19,6 +18,8 @@ import type { IExtractorOptions, LinkCreationMode } from './PackageExtractor'; import type { ILinkInfo, SymlinkAnalyzer } from './SymlinkAnalyzer'; import { remapSourcePathForTargetFolder } from './Utils'; +let _archiveTempFolderCounter: number = 0; + export interface IIncludeAssetOptions { sourceFilePath?: string; sourceFileStats?: FileSystemStats; @@ -73,14 +74,16 @@ export class AssetHandler { linkCreation, symlinkAnalyzer, createArchiveFilePath, - createArchiveOnly = false + createArchiveOnly = false, + archiveTempFolder } = options; this.#terminal = terminal; this.#sourceRootFolder = sourceRootFolder; this.#targetRootFolder = targetRootFolder; + // Disambiguate deployments started in the same millisecond or in different processes. this.#archiveTempFolder = path.resolve( - options.archiveTempFolder ?? `${sourceRootFolder}/common/temp`, - `deploy-archive-${randomUUID()}` + archiveTempFolder ?? `${sourceRootFolder}/common/temp`, + `deploy-archive-${Date.now()}-${process.pid}-${_archiveTempFolderCounter++}` ); this.#stageArchiveAssets = createArchiveOnly && @@ -125,7 +128,7 @@ export class AssetHandler { } const targetRelativeFilePath: string = path.relative(this.#targetRootFolder, targetFilePath); - if (path.isAbsolute(targetRelativeFilePath) || targetRelativeFilePath.split(path.sep).includes('..')) { + if (path.isAbsolute(targetRelativeFilePath) || /^\.\.(?:[\\/]|$)/.test(targetRelativeFilePath)) { throw new Error('The asset path must be under the target root folder'); } diff --git a/libraries/package-extractor/src/test/ArchiveManager.test.ts b/libraries/package-extractor/src/test/ArchiveManager.test.ts index 667eccf83e1..aefd2530c77 100644 --- a/libraries/package-extractor/src/test/ArchiveManager.test.ts +++ b/libraries/package-extractor/src/test/ArchiveManager.test.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import JSZip from 'jszip'; import * as tar from 'tar'; -import { FileSystem, Path } from '@rushstack/node-core-library'; +import { Async, FileSystem, Path } from '@rushstack/node-core-library'; import { Terminal, StringBufferTerminalProvider } from '@rushstack/terminal'; import { ArchiveManager } from '../ArchiveManager'; @@ -165,6 +165,30 @@ describe(ArchiveManager.name, () => { expect(await zip.file('generated.txt')?.async('string')).toBe(generatedContent); }); + it('reads ZIP assets in parallel while preserving entry order', async () => { + const archiveFilePath: string = `${testFolder}/parallel.zip`; + const manager: ArchiveManager = new ArchiveManager('zip'); + const stats = await FileSystem.getStatisticsAsync(sourceFile); + for (const archivePath of ['first.txt', 'second.txt']) { + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath, stats }); + } + + const readSpy = jest + .spyOn(FileSystem, 'readFileToBufferAsync') + .mockImplementationOnce(async () => { + await Async.sleepAsync(0); + expect(readSpy).toHaveBeenCalledTimes(2); + return fileContent; + }) + .mockResolvedValueOnce(Buffer.from(generatedContent)); + await manager.createArchiveAsync(archiveFilePath); + + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(Object.keys(zip.files)).toEqual(['first.txt', 'second.txt']); + expect(await zip.file('first.txt')?.async('nodebuffer')).toEqual(fileContent); + expect(await zip.file('second.txt')?.async('string')).toBe(generatedContent); + }); + it.each(['.zip', '.tar', '.tgz'])('writes generated %s assets only once per deployment', async (ext) => { for (const createArchiveOnly of [false, true]) { const targetRootFolder: string = `${testFolder}/single-write-${ext.slice(1)}-${createArchiveOnly}`; @@ -235,7 +259,10 @@ describe(ArchiveManager.name, () => { const entry: ITarEntry | undefined = (await readTarAsync(archiveFilePath)).get('executable.sh'); expect(entry?.data).toEqual(await FileSystem.readFileToBufferAsync(executablePath)); if (process.platform !== 'win32') { - expect(entry?.mode).toBe(0o755); + expect(entry?.mode).toBe( + // eslint-disable-next-line no-bitwise + (await FileSystem.getStatisticsAsync(executablePath)).mode & 0o7777 + ); } }); @@ -259,6 +286,38 @@ describe(ArchiveManager.name, () => { expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); }); + it.each(['available', 'unavailable'])( + 'memoizes %s native tar initialization for an archive manager', + async (availability) => { + const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); + if (!nativeTar) { + throw new Error('Native tar is required for the initialization test'); + } + + const initializeSpy = jest + .spyOn(TarExecutable, 'tryInitializeAsync') + .mockResolvedValue(availability === 'available' ? nativeTar : undefined); + const manager: ArchiveManager = new ArchiveManager('tar'); + await manager.addToArchiveAsync({ filePath: sourceFile, archivePath: 'input.txt' }); + await Promise.all( + [1, 2].map(async (index) => { + const archiveFilePath: string = `${testFolder}/memoized-${availability}-${index}.tar`; + const archivePromise: Promise = manager.createArchiveAsync(archiveFilePath, { + terminal, + sourceFolder + }); + if (availability === 'available') { + await archivePromise; + expect((await readTarAsync(archiveFilePath)).get('input.txt')?.data).toEqual(fileContent); + } else { + await expect(archivePromise).rejects.toThrow('Native tar is required'); + } + }) + ); + expect(initializeSpy).toHaveBeenCalledTimes(1); + } + ); + it('rejects unsupported extensions', () => { expect(() => ArchiveManager.getArchiveFormat('deploy.gz')).toThrow('Supported archive file extensions'); }); @@ -302,6 +361,7 @@ describe(ArchiveManager.name, () => { ); expect(await FileSystem.readFileToBufferAsync(`${baseFolderPath}/input.txt`)).toEqual(fileContent); await FileSystem.writeFileAsync(archiveFilePath, 'partial archive'); + await FileSystem.writeFileAsync(`${archiveFilePath}.log`, 'native tar failed'); return 1; }); initializeSpy.mockResolvedValue(nativeTar); @@ -318,15 +378,20 @@ describe(ArchiveManager.name, () => { expect(initializeSpy).toHaveBeenCalled(); expect(await FileSystem.readFolderItemNamesAsync(tempFolder)).toEqual([]); expect(await FileSystem.existsAsync(archiveFilePath)).toBe(false); + if (reason === 'incompatible') { + expect(await FileSystem.readFileAsync(`${archiveFilePath}.log`)).toBe('native tar failed'); + } }); - it('uses isolated staging folders for concurrent archive-only deployments', async () => { + it('uses isolated staging folders for archive-only deployments started in the same millisecond', async () => { const nativeTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync(terminal); if (!nativeTar) { throw new Error('Native tar is required for the staging test'); } const createSpy = jest.spyOn(nativeTar, 'tryCreateArchiveAsync'); + const timestamp: number = Date.now(); + jest.spyOn(Date, 'now').mockReturnValue(timestamp); const archivePaths: string[] = [`${testFolder}/concurrent-1.tgz`, `${testFolder}/concurrent-2.tgz`]; await Promise.all( archivePaths.map(async (archivePath, index) => { @@ -343,7 +408,7 @@ describe(ArchiveManager.name, () => { expect(new Set(stagingFolders).size).toBe(2); for (const stagingFolder of stagingFolders) { expect(Path.convertToSlashes(stagingFolder)).toContain( - `${Path.convertToSlashes(tempFolder)}/deploy-archive-` + `${Path.convertToSlashes(tempFolder)}/deploy-archive-${timestamp}-` ); expect(await FileSystem.existsAsync(stagingFolder)).toBe(false); } @@ -378,6 +443,31 @@ describe(ArchiveManager.name, () => { ).rejects.toThrow('relative paths within the archive'); }); + it.each(['..', '../outside.txt', 'nested/../../outside.txt'])( + 'rejects an asset path outside the target folder: %s', + async (relativePath) => { + const handler: AssetHandler = createHandler(`${testFolder}/outside.zip`); + await expect( + handler.includeAssetAsync({ + sourceFileContent: generatedContent, + targetFilePath: path.resolve(testFolder, relativePath) + }) + ).rejects.toThrow('The asset path must be under the target root folder'); + } + ); + + it('allows asset names that contain dots without traversing outside the target folder', async () => { + const archiveFilePath: string = `${testFolder}/dotted-name.zip`; + const handler: AssetHandler = createHandler(archiveFilePath); + await handler.includeAssetAsync({ + sourceFileContent: generatedContent, + targetFilePath: `${testFolder}/nested/..input.txt` + }); + await handler.finalizeAsync(); + const zip: JSZip = await JSZip.loadAsync(await FileSystem.readFileToBufferAsync(archiveFilePath)); + expect(await zip.file('nested/..input.txt')?.async('string')).toBe(generatedContent); + }); + it('handles a native executable that exits before reading the file list', async () => { const incompatibleTar: TarExecutable | undefined = await TarExecutable.tryInitializeAsync( terminal,