From bddb0233250ee29de3c3832aa785eb07383c8ead Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:19:57 -0500 Subject: [PATCH] perf(nuget): stream .nupkg ZIP over FileHandle instead of buffering full archive (#13835) * perf(nuget): stream .nupkg ZIP over FileHandle instead of buffering full archive Closes #13834 * fix(nuget): check artifact stability after format rejection --- src/nuget/NugetNupkgParser.ts | 62 ++++++++- src/nuget/NugetNupkgProvider.ts | 51 +++---- src/resources/StableArtifactFailure.ts | 7 +- src/resources/StableArtifactObservation.ts | 14 +- src/resources/index.ts | 3 + src/resources/readStableArtifact.ts | 124 +++++++++++++++--- .../stableArtifactConsumers.test.ts | 30 +++++ 7 files changed, 242 insertions(+), 49 deletions(-) diff --git a/src/nuget/NugetNupkgParser.ts b/src/nuget/NugetNupkgParser.ts index 38020e05f37..9017182752e 100644 --- a/src/nuget/NugetNupkgParser.ts +++ b/src/nuget/NugetNupkgParser.ts @@ -6,6 +6,7 @@ import { unsupportedInput, } from "../domain/parseFailure.js"; import { + Reader, Uint8ArrayReader, Uint8ArrayWriter, ZipReader, @@ -513,24 +514,75 @@ const findNuspec = ( return { member: undefined, source: undefined }; }; +/** Random-access source over one verified .nupkg descriptor. */ +export interface NugetNupkgRandomAccessSource { + readonly prefix: Uint8Array; + readonly size: number; + readonly readRange: (offset: number, length: number) => Promise; +} + +class RandomAccessZipReader extends Reader { + readonly #source: NugetNupkgRandomAccessSource; + readonly #path: string; + + constructor(source: NugetNupkgRandomAccessSource, path: string) { + super(undefined); + this.#source = source; + this.#path = path; + this.size = source.size; + } + + override async readUint8Array( + index: number, + length: number, + ): Promise { + const readBytes = Math.min(length, this.size - index); + if (readBytes < 0) + throw new ArtifactReaderFailure( + "format", + `ZIP archive is malformed: read at ${String(index)} extends beyond the ${String(this.size)}-byte archive`, + ); + const bytes = await this.#source.readRange(index, readBytes); + if (bytes.length !== readBytes) + throw new ArtifactReaderFailure( + "integrity", + `ZIP source ended before its admitted extent: ${this.#path}`, + { integrityCheck: "read-coverage" }, + ); + return bytes; + } +} + /** Decode one bounded NuGet .nupkg without restore, execution, or network. */ export const parseNugetNupkg = async ( - bytes: Uint8Array, + source: Uint8Array | NugetNupkgRandomAccessSource, artifact: { path: string; sha256: string; bytes: number }, input: InspectNugetNupkgInput, signal?: AbortSignal, ): Promise => { - if (bytes.length !== artifact.bytes) + const isBuffer = source instanceof Uint8Array; + const sourceLength = isBuffer ? source.length : source.size; + if (sourceLength !== artifact.bytes) throw malformedInput( NUGET_NUPKG_FORMAT, "Selected artifact length disagrees with the retained bytes.", ); - if (!hasZipSignature(bytes)) + const signatureBytes = isBuffer ? source : source.prefix; + if (!hasZipSignature(signatureBytes)) throw malformedInput( NUGET_NUPKG_FORMAT, "Selected file is not a ZIP archive (NuGet .nupkg).", ); - const reader = new ZipReader(new Uint8ArrayReader(bytes), ZIP_READER_OPTIONS); + const reader = new ZipReader( + isBuffer + ? new Uint8ArrayReader(source) + : new RandomAccessZipReader(source, artifact.path), + ZIP_READER_OPTIONS, + ); + const readLocalRange: (at: number, length: number) => Promise = + isBuffer + ? (at, length) => Promise.resolve(source.subarray(at, at + length)) + : (at, length) => source.readRange(at, length); const limitations: string[] = [...BASE_LIMITATIONS]; const zipAbort = signal === undefined ? undefined : new AbortController(); const zipSignal = zipAbort?.signal; @@ -587,7 +639,7 @@ export const parseNugetNupkg = async ( dataDescriptor: entry.bitFlag?.dataDescriptor ?? false, })), directoryOffset, - (at, length) => Promise.resolve(bytes.subarray(at, at + length)), + readLocalRange, ), ); limitations.push(...listing.limitations); diff --git a/src/nuget/NugetNupkgProvider.ts b/src/nuget/NugetNupkgProvider.ts index 0edccb8153f..0f1f9fed4eb 100644 --- a/src/nuget/NugetNupkgProvider.ts +++ b/src/nuget/NugetNupkgProvider.ts @@ -8,10 +8,9 @@ import { projectOwnedArtifactInputFailure, projectSelectedArtifactFileFailure, projectStableArtifactFailure, - readStableArtifact, translateArtifactFailure, + withStableArtifactHandle, type ArtifactFilePrimaryFacts, - type StableArtifactSnapshot, } from "../resources/index.js"; import { isParseLimit, @@ -134,7 +133,7 @@ const nupkgFailurePrimary = ( const nupkgFailure = ( cause: unknown, input: InspectNugetNupkgInput, - snapshot?: StableArtifactSnapshot, + identity?: { readonly sha256: string; readonly bytes: number }, ) => projectStableArtifactFailure( cause, @@ -142,7 +141,7 @@ const nupkgFailure = ( input.path, NUGET_NUPKG_PROVIDER_IDENTITY.id, OPERATION, - snapshot, + identity, ); /** Portable parser over one bounded, identity-checked regular file. */ @@ -166,31 +165,35 @@ export class NugetNupkgProvider { input: InspectNugetNupkgInput, options?: { readonly signal?: AbortSignal }, ) { - let snapshot: StableArtifactSnapshot | undefined; + let identity: + | { readonly sha256: string; readonly bytes: number } + | undefined; try { - return await this.#resources.run(async () => { - snapshot = await readStableArtifact( + return await this.#resources.run(async () => + withStableArtifactHandle( input.path, input.max_file_bytes, - options?.signal, - undefined, - this.#resources, - ); - return ok( - await parseNugetNupkg( - snapshot.bytes, - { - path: input.path, - sha256: snapshot.sha256, - bytes: snapshot.bytes.length, + { + retainBytes: () => 4, + signal: options?.signal, + resourceScope: this.#resources, + onIdentity: (verified) => { + identity = verified; }, - input, - options?.signal, - ), - ); - }); + }, + async ({ prefix, size, sha256, readRange }) => + ok( + await parseNugetNupkg( + { prefix, size, readRange }, + { path: input.path, sha256, bytes: size }, + input, + options?.signal, + ), + ), + ), + ); } catch (cause) { - return err(nupkgFailure(cause, input, snapshot)); + return err(nupkgFailure(cause, input, identity)); } } } diff --git a/src/resources/StableArtifactFailure.ts b/src/resources/StableArtifactFailure.ts index f71efe21ec7..c7da6950e86 100644 --- a/src/resources/StableArtifactFailure.ts +++ b/src/resources/StableArtifactFailure.ts @@ -11,7 +11,10 @@ import { bindArtifactFileCleanup, type ArtifactFilePrimaryFacts, } from "./ArtifactFileOperation.js"; -import { completedStableArtifactObservation } from "./StableArtifactObservation.js"; +import { + completedStableArtifactObservation, + type CompletedStableArtifact, +} from "./StableArtifactObservation.js"; import { isSelectedRegularFileError } from "../filesystem/RegularFile.js"; import { AnalysisAccessDeniedError, @@ -194,7 +197,7 @@ export const projectStableArtifactFailure = ( path: string, providerId: string, operation: string, - snapshot?: StableArtifactSnapshot, + snapshot?: CompletedStableArtifact, ): AnalysisError => { const observation = completedStableArtifactObservation(cause, path, snapshot); if (observation !== undefined) primary.retainPartialObservation(observation); diff --git a/src/resources/StableArtifactObservation.ts b/src/resources/StableArtifactObservation.ts index 6245d5984bb..70897c8e436 100644 --- a/src/resources/StableArtifactObservation.ts +++ b/src/resources/StableArtifactObservation.ts @@ -7,21 +7,29 @@ import { completedStableArtifactIdentity, } from "./readStableArtifact.js"; +/** Completed whole-file identity, with or without retained snapshot bytes. */ +export type CompletedStableArtifact = + | StableArtifactSnapshot + | { readonly sha256: string; readonly bytes: number }; + /** * Completed file identity survives finalization and later decoding failures; - * `completed` is the snapshot a provider already holds when its parser fails. + * `completed` is the snapshot or identity a provider already holds when its parser fails. */ export const completedStableArtifactObservation = ( cause: unknown, path: string, - completedSnapshot?: StableArtifactSnapshot, + completedSnapshot?: CompletedStableArtifact, ): FileSnapshotPartialObservation | undefined => { const identity = completedSnapshot === undefined ? completedStableArtifactIdentity(cause) : { sha256: completedSnapshot.sha256, - bytes: completedSnapshot.bytes.length, + bytes: + typeof completedSnapshot.bytes === "number" + ? completedSnapshot.bytes + : completedSnapshot.bytes.length, }; return identity === undefined ? undefined diff --git a/src/resources/index.ts b/src/resources/index.ts index 6a268425cbb..922de78cf11 100644 --- a/src/resources/index.ts +++ b/src/resources/index.ts @@ -111,9 +111,12 @@ export { completedStableArtifactStream, readStableArtifact, streamStableArtifact, + withStableArtifactHandle, } from "./readStableArtifact.js"; export type { StableArtifactFileSystem, + StableArtifactHandle, + StableArtifactHandleOptions, StableArtifactSnapshot, StableArtifactStream, StableArtifactStreamOptions, diff --git a/src/resources/readStableArtifact.ts b/src/resources/readStableArtifact.ts index 930ed19a870..f2cb1bca8d9 100644 --- a/src/resources/readStableArtifact.ts +++ b/src/resources/readStableArtifact.ts @@ -5,6 +5,8 @@ import { resolvedRegularFile, sameRegularFileState, } from "../filesystem/RegularFile.js"; +import { readFileHandleRange } from "../filesystem/readFileHandleRange.js"; +import { ParseFailureError } from "../domain/parseFailure.js"; import { ArtifactReaderFailure } from "./ArtifactReader.js"; import type { ArtifactResourceScope } from "./ArtifactResourceScope.js"; import { @@ -103,6 +105,28 @@ const afterValidation = async ( } }; +const verifyStableArtifactRead = async ( + path: string, + fileSystem: StableArtifactFileSystem, + file: FileHandle, + initial: BigIntStats, + count: number, +): Promise => { + const after = await file.stat({ bigint: true }); + const current = await afterValidation(path, "during read", () => + fileSystem.lstat(path), + ); + if ( + [after, current].some((stat) => !sameRegularFileState(initial, stat)) || + BigInt(count) !== initial.size + ) + throw new ArtifactReaderFailure( + "integrity", + `Artifact changed during read: ${path}`, + { integrityCheck: "container-identity" }, + ); +}; + const DEFAULT_STREAM_CHUNK_BYTES = 65536; const SNAPSHOT_READ_CHUNK_BYTES = 1048576; const EOF_PROBE_BYTES = 4096; @@ -188,6 +212,87 @@ export const streamStableArtifact = async ( }); }; +/** Verified random-access handle for one streamed stable artifact. */ +export interface StableArtifactHandle { + readonly sha256: string; + readonly size: number; + readonly prefix: Buffer; + /** Read a verified positional byte range from the open descriptor. */ + readonly readRange: (offset: number, length: number) => Promise; +} + +/** Options for {@link withStableArtifactHandle}. */ +export interface StableArtifactHandleOptions { + /** Bytes to retain from the start of the file, given its admitted size. */ + readonly retainBytes: (size: number) => number; + /** Maximum streaming hash chunk size in bytes; defaults to 65536. */ + readonly chunkBytes?: number | undefined; + readonly signal?: AbortSignal | undefined; + readonly fileSystem?: StableArtifactFileSystem; + readonly resourceScope?: ArtifactResourceScope | undefined; + /** Called once whole-file hashing and stability verification complete, before `useFile`. */ + readonly onIdentity?: (identity: { + readonly sha256: string; + readonly bytes: number; + }) => void; +} + +/** + * Stream one bounded regular file to verify its identity and SHA-256 without + * buffering the whole file, then run `useFile` with random-access reads on the + * same open descriptor and re-verify file stability before closing. + */ +export const withStableArtifactHandle = async ( + path: string, + maximumBytes: number, + options: StableArtifactHandleOptions, + useFile: (handle: StableArtifactHandle) => Promise, +): Promise => { + const chunkBytes = options.chunkBytes ?? DEFAULT_STREAM_CHUNK_BYTES; + if (!Number.isSafeInteger(chunkBytes) || chunkBytes <= 0) + throw new ArtifactReaderFailure( + "format", + `Artifact read chunk size must be a positive integer: ${String(chunkBytes)}`, + ); + const fileSystem = options.fileSystem ?? FILE_SYSTEM; + return readStableArtifactChunks({ + path, + maximumBytes, + chunkBytes, + signal: options.signal, + fileSystem, + resourceScope: options.resourceScope, + retainBytes: options.retainBytes, + onChunk: undefined, + complete: async (prefix, sha256, size, initial, file) => { + options.onIdentity?.({ sha256, bytes: size }); + const verifyState = () => + verifyStableArtifactRead(path, fileSystem, file, initial, size); + const value = await useFile({ + sha256, + size, + prefix, + readRange: (offset, length) => + readFileHandleRange(file, offset, length, () => + assertArtifactReadActive(options.signal), + ), + }).catch(async (cause: unknown) => { + // Format findings can reflect bytes rewritten during parsing. Keep + // independent physical I/O, cancellation, and decoder failures primary. + if ( + (cause instanceof ParseFailureError && cause.kind !== "limit") || + (cause instanceof ArtifactReaderFailure && cause.reason === "format") + ) + await verifyState(); + throw cause; + }); + await verifyState(); + assertArtifactReadActive(options.signal); + return value; + }, + }); +}; + const readStableArtifactChunks = async (options: { readonly path: string; readonly maximumBytes: number; @@ -202,7 +307,8 @@ const readStableArtifactChunks = async (options: { sha256: string, size: number, state: BigIntStats, - ) => Value; + file: FileHandle, + ) => Value | Promise; }): Promise => { const { path, @@ -322,21 +428,9 @@ const readStableArtifactChunks = async (options: { hash.update(chunk); if (onChunk !== undefined) await onChunk(chunk); } - const after = await file.stat({ bigint: true }); - const current = await afterValidation(path, "during read", () => - fileSystem.lstat(path), - ); - if ( - [after, current].some((stat) => !sameRegularFileState(initial, stat)) || - BigInt(count) !== initial.size - ) - throw new ArtifactReaderFailure( - "integrity", - `Artifact changed during read: ${path}`, - { integrityCheck: "container-identity" }, - ); + await verifyStableArtifactRead(path, fileSystem, file, initial, count); assertArtifactReadActive(signal); - return complete(bytes, hash.digest("hex"), count, initial); + return complete(bytes, hash.digest("hex"), count, initial, file); }, ); }; diff --git a/tests/process-global/stableArtifactConsumers.test.ts b/tests/process-global/stableArtifactConsumers.test.ts index f74768843fb..771d5d65bef 100644 --- a/tests/process-global/stableArtifactConsumers.test.ts +++ b/tests/process-global/stableArtifactConsumers.test.ts @@ -214,6 +214,36 @@ it("preserves opaque NuGet decoder failures and the completed file identity", as } }); +it("reports a NuGet package changed after hashing when its ZIP decode fails", async () => { + const path = await selectedImage(); + const bytes = await nugetNupkgFixture(); + await writeFile(path, bytes); + fault.blockNew = false; + const enumerate = ZipReader.prototype.getEntriesGenerator; + const enumeration = vi + .spyOn(ZipReader.prototype, "getEntriesGenerator") + .mockImplementation(async function* (this: ZipReader, options) { + await writeFile(path, Buffer.alloc(bytes.length)); + return yield* enumerate.call(this, options); + }); + const provider = new NugetNupkgProvider(); + try { + const result = await provider.inspect( + inspectNugetNupkgInputSchema.parse({ path }), + ); + if (result.ok) throw new Error("Expected source change"); + expect(result.error).toBeInstanceOf(AnalysisArtifactChangedError); + expect(result.error).toMatchObject({ + integrityCheck: "container-identity", + }); + expect(fault.handles).toHaveLength(1); + expect(fault.handles[0]?.fd).toBe(-1); + } finally { + enumeration.mockRestore(); + await provider.close(); + } +}); + it.each( ["close failure", "close cancellation"].flatMap((outcome) => ["NuGet", "Maven/Gradle"].map((kind) => ({ outcome, kind })),