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
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 21:19:57 -05:00
1 parent f47dbd9351
commit bddb023325
7 files changed
+242 -49

No files matched your search

+57 -5
View File
@@ -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<Uint8Array>;
}
class RandomAccessZipReader extends Reader<undefined> {
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<Uint8Array> {
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<NugetNupkg> => {
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<Uint8Array> =
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);
+27 -24
View File
@@ -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));
}
}
}
+5 -2
View File
@@ -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);
+11 -3
View File
@@ -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
+3
View File
@@ -111,9 +111,12 @@ export {
completedStableArtifactStream,
readStableArtifact,
streamStableArtifact,
withStableArtifactHandle,
} from "./readStableArtifact.js";
export type {
StableArtifactFileSystem,
StableArtifactHandle,
StableArtifactHandleOptions,
StableArtifactSnapshot,
StableArtifactStream,
StableArtifactStreamOptions,
+109 -15
View File
@@ -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 <T>(
}
};
const verifyStableArtifactRead = async (
path: string,
fileSystem: StableArtifactFileSystem,
file: FileHandle,
initial: BigIntStats,
count: number,
): Promise<void> => {
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<Buffer>;
}
/** 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 <Value>(
path: string,
maximumBytes: number,
options: StableArtifactHandleOptions,
useFile: (handle: StableArtifactHandle) => Promise<Value>,
): Promise<Value> => {
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 <Value>(options: {
readonly path: string;
readonly maximumBytes: number;
@@ -202,7 +307,8 @@ const readStableArtifactChunks = async <Value>(options: {
sha256: string,
size: number,
state: BigIntStats,
) => Value;
file: FileHandle,
) => Value | Promise<Value>;
}): Promise<Value> => {
const {
path,
@@ -322,21 +428,9 @@ const readStableArtifactChunks = async <Value>(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);
},
);
};
@@ -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<unknown>, 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 })),