diff --git a/src/artifacts/BunStandaloneArtifactReader.ts b/src/artifacts/BunStandaloneArtifactReader.ts index 5d949ef4481..87bc7c87505 100644 --- a/src/artifacts/BunStandaloneArtifactReader.ts +++ b/src/artifacts/BunStandaloneArtifactReader.ts @@ -1,12 +1,9 @@ -import { ArtifactPreparation } from "./ArtifactPreparation.js"; import { DEFAULT_BUN_READER_LIMITS, type BunReaderLimits, } from "../domain/artifactReaderLimits.js"; import type { BunStandaloneAdmission } from "./bun/BunStandaloneAdmission.js"; import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js"; -import { setImmediate } from "node:timers/promises"; -import { Readable } from "node:stream"; import { artifactExpansionBudgetBytes } from "../domain/artifactExpansionBudget.js"; import type { BunStandaloneEntryMetadata, @@ -14,26 +11,18 @@ import type { } from "../domain/artifactFormatMetadata.js"; import { jsonValueByteLength } from "../domain/jsonValueByteLength.js"; import type { JsonValue } from "../domain/jsonValue.js"; -import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js"; import { assertArtifactReadActive, ArtifactReaderFailure, - copyArtifactEntry, - assertProducedEntry, type ArtifactEntry, - type ArtifactReader, - type ArtifactTraversalOptions, - ArtifactResourceScope, normalizeArtifactPath, ArtifactPathRegistry, - ArtifactFileSource, artifactReaderLimitFailure, } from "../resources/index.js"; import { - ArtifactStreamLifecycle, - checkedArtifactMemberStream, - ownArtifactStream, -} from "./OwnedArtifactStream.js"; + PositionalArtifactReader, + type PositionalArtifactEntries, +} from "./PositionalArtifactReader.js"; import { bunFormatFailure, bunMetadataBytesLimit, @@ -55,15 +44,12 @@ interface BunModuleDestination { } /** One descriptor and bounded reads of an embedded Bun standalone module graph. */ -export class BunStandaloneArtifactReader implements ArtifactReader { +export class BunStandaloneArtifactReader extends PositionalArtifactReader< + BunStandaloneMetadata, + ArtifactEntry +> { readonly format = "bun-standalone" as const; - readonly #scope = new ArtifactResourceScope(); - #entries = new Map(); - readonly #lifecycle = new ArtifactStreamLifecycle("Bun standalone"); - readonly #source: ArtifactFileSource; #admission: BunStandaloneAdmission | undefined; - readonly #preparation = new ArtifactPreparation(); - #header: BunStandaloneMetadata | undefined; constructor( path: string, @@ -71,122 +57,38 @@ export class BunStandaloneArtifactReader implements ArtifactReader { private readonly limits: BunReaderLimits = DEFAULT_BUN_READER_LIMITS, private readonly expandedBytes?: number, ) { + const descriptor = + admitted !== undefined && "kind" in admitted ? admitted.source : admitted; + super(path, "Bun standalone", descriptor, { verifySelectedPath: true }); if (admitted !== undefined && "kind" in admitted) { this.#admission = admitted; - this.#source = new ArtifactFileSource( - path, - "Bun standalone", - admitted.source, - ); - } else - this.#source = new ArtifactFileSource(path, "Bun standalone", admitted); + } } formatMetadata(): BunStandaloneMetadata | undefined { - return this.#header === undefined ? undefined : { ...this.#header }; + const header = this.preparedFormatMetadata; + return header === undefined ? undefined : { ...header }; } - async prepareContainer( - expectedSha256: string, - signal?: AbortSignal, - ): Promise { - await this.#scope.run(async () => { - this.#assertOpen(signal); - await this.#source.bindSelectedPathSha256(expectedSha256, signal); - }); - } - - async *entries( - signal?: AbortSignal, - options?: ArtifactTraversalOptions, - ): AsyncIterable { - await this.#scope.run(async () => { - this.#assertOpen(signal); - await this.#preparation.run( - signal, - () => this.#prepare(signal), - () => this.#assertOpen(signal), - ); - await this.#source.readSelectedPath(signal); - }); - this.#assertOpen(signal); - let index = 0; - for (const entry of this.#entries.values()) { - if (index++ % 256 === 0) await setImmediate(); - this.#assertOpen(signal); - yield copyArtifactEntry(entry); - } - this.#assertOpen(signal); - // Every present module region is listed; absent regions are not members. - options?.onCoverage?.({ status: "complete", limitations: [] }); - } - - async open(entry: ArtifactEntry, signal?: AbortSignal): Promise { - return this.#scope.run(async () => { - this.#assertOpen(signal); - const stored = this.#entries.get(entry.adapterKey); - assertProducedEntry( - entry, - stored, - "Bun standalone entry does not match its owning inventory", - ); - const { handle } = await this.#source.readSelectedPath(signal); - this.#assertOpen(signal); - if (stored.byteOffset === null || stored.declaredSize === null) - throw bunFormatFailure("member has no physical byte range"); - const lifecycle = this.#lifecycle.member(signal); - const { signal: streamSignal, cancellationFailure } = lifecycle; - const source = - stored.declaredSize === 0 - ? Readable.from([]) - : readFileHandleChunks(handle, { - start: stored.byteOffset, - end: stored.byteOffset + stored.declaredSize - 1, - signal: streamSignal, - cancellationFailure, - }); - const output = checkedArtifactMemberStream( - stored, - "Bun standalone", - bunFormatFailure, - () => - lifecycle.verify((signal) => this.#source.readSelectedPath(signal)), - ); - ownArtifactStream(source, output, { - scope: this.#scope, - signal: streamSignal, - cancellationFailure, - label: "Bun standalone", - }); - return output; - }); - } - - async close(): Promise { - this.#lifecycle.close(); - await this.#scope.close(); - await this.#source.close(); - this.#entries.clear(); - this.#header = undefined; + override async close(): Promise { this.#admission = undefined; - this.#preparation.clear(); + await super.close(); } - provenance(): readonly [] { - return []; + protected override noPhysicalRange(): ArtifactReaderFailure { + return bunFormatFailure("member has no physical byte range"); } - #assertOpen(signal?: AbortSignal): void { - assertArtifactReadActive(signal); - if (this.#lifecycle.closed) - throw new ArtifactReaderFailure( - "unavailable", - "Bun standalone reader is closed", - ); + protected override entryEndedEarly( + entry: ArtifactEntry, + ): ArtifactReaderFailure { + return bunFormatFailure(`member ended early: ${entry.path}`); } - async #prepare(signal?: AbortSignal): Promise { - const source = await this.#source.readSelectedPath(signal); + protected async prepareEntries( + signal?: AbortSignal, + ): Promise> { + const source = await this.verifyCarrier(signal); const probe = this.#admission?.probe ?? (await probeBunStandaloneGraph( @@ -288,11 +190,13 @@ export class BunStandaloneArtifactReader implements ArtifactReader { entries.set(entry.adapterKey, entry); } } - await this.#source.readSelectedPath(signal); - this.#assertOpen(signal); - this.#entries = entries; - this.#header = header; this.#admission = undefined; + return { + entries: [...entries.values()], + // Every present module region is listed; absent regions are not members. + coverage: { status: "complete", limitations: [] }, + formatMetadata: header, + }; } } diff --git a/src/artifacts/DenoStandaloneArtifactReader.ts b/src/artifacts/DenoStandaloneArtifactReader.ts index 3a778bb13ec..dd4d51206b5 100644 --- a/src/artifacts/DenoStandaloneArtifactReader.ts +++ b/src/artifacts/DenoStandaloneArtifactReader.ts @@ -1,9 +1,4 @@ -import { ArtifactPreparation } from "./ArtifactPreparation.js"; -import { Readable } from "node:stream"; -import { setImmediate } from "node:timers/promises"; - import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js"; -import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js"; import { readFileHandleRange } from "../filesystem/readFileHandleRange.js"; import { artifactExpansionBudgetBytes } from "../domain/artifactExpansionBudget.js"; import type { @@ -16,21 +11,14 @@ import { assertArtifactReadActive, ArtifactReaderFailure, artifactFixedLimitFailure, - copyArtifactEntry, - assertProducedEntry, type ArtifactEntry, - type ArtifactReader, - type ArtifactTraversalOptions, - ArtifactResourceScope, ArtifactPathRegistry, normalizeArtifactPath, - ArtifactFileSource, } from "../resources/index.js"; import { - ArtifactStreamLifecycle, - checkedArtifactMemberStream, - ownArtifactStream, -} from "./OwnedArtifactStream.js"; + PositionalArtifactReader, + type PositionalArtifactEntries, +} from "./PositionalArtifactReader.js"; import type { DenoStandaloneAdmission } from "./deno/DenoStandaloneAdmission.js"; import { denoFormatFailure, @@ -70,138 +58,49 @@ interface RemoteDestination { } /** One descriptor and bounded reads of an embedded Deno compile section. */ -export class DenoStandaloneArtifactReader implements ArtifactReader { +export class DenoStandaloneArtifactReader extends PositionalArtifactReader< + DenoStandaloneMetadata, + ArtifactEntry +> { readonly format = "deno-standalone" as const; - readonly #scope = new ArtifactResourceScope(); - #entries = new Map(); - readonly #lifecycle = new ArtifactStreamLifecycle("Deno compile"); - readonly #source: ArtifactFileSource; #admission: DenoStandaloneAdmission | undefined; - readonly #preparation = new ArtifactPreparation(); - #header: DenoStandaloneMetadata | undefined; constructor( private readonly path: string, admitted?: StableRegularFileDescriptor | DenoStandaloneAdmission, ) { + const descriptor = + admitted !== undefined && "kind" in admitted ? admitted.source : admitted; + super(path, "Deno compile", descriptor, { verifySelectedPath: true }); if (admitted !== undefined && "kind" in admitted) { this.#admission = admitted; - this.#source = new ArtifactFileSource( - path, - "Deno compile", - admitted.source, - ); - } else - this.#source = new ArtifactFileSource(path, "Deno compile", admitted); + } } formatMetadata(): DenoStandaloneMetadata | undefined { - return this.#header === undefined ? undefined : { ...this.#header }; + const header = this.preparedFormatMetadata; + return header === undefined ? undefined : { ...header }; } - async prepareContainer( - expectedSha256: string, - signal?: AbortSignal, - ): Promise { - await this.#scope.run(async () => { - this.#assertOpen(signal); - await this.#source.bindSelectedPathSha256(expectedSha256, signal); - }); - } - - async *entries( - signal?: AbortSignal, - options?: ArtifactTraversalOptions, - ): AsyncIterable { - await this.#scope.run(async () => { - this.#assertOpen(signal); - await this.#preparation.run( - signal, - () => this.#prepare(signal), - () => this.#assertOpen(signal), - ); - await this.#source.readSelectedPath(signal); - }); - options?.onCoverage?.( - this.#header?.vfs_listing === "unsupported" - ? { status: "unknown", limitations: [UNLISTED_VFS_LIMITATION] } - : { status: "complete", limitations: [] }, - ); - let index = 0; - for (const entry of this.#entries.values()) { - if (index++ % 256 === 0) await setImmediate(); - this.#assertOpen(signal); - yield copyArtifactEntry(entry); - } - this.#assertOpen(signal); - } - - async open(entry: ArtifactEntry, signal?: AbortSignal): Promise { - return this.#scope.run(async () => { - this.#assertOpen(signal); - const stored = this.#entries.get(entry.adapterKey); - assertProducedEntry( - entry, - stored, - "Deno compile entry does not match its owning inventory", - ); - const { handle } = await this.#source.readSelectedPath(signal); - this.#assertOpen(signal); - if (stored.byteOffset === null || stored.declaredSize === null) - throw denoFormatFailure("member has no physical byte range"); - const lifecycle = this.#lifecycle.member(signal); - const { signal: streamSignal, cancellationFailure } = lifecycle; - const source = - stored.declaredSize === 0 - ? Readable.from([]) - : readFileHandleChunks(handle, { - start: stored.byteOffset, - end: stored.byteOffset + stored.declaredSize - 1, - signal: streamSignal, - cancellationFailure, - }); - const output = checkedArtifactMemberStream( - stored, - "Deno compile", - denoFormatFailure, - () => - lifecycle.verify((signal) => this.#source.readSelectedPath(signal)), - ); - ownArtifactStream(source, output, { - scope: this.#scope, - signal: streamSignal, - cancellationFailure, - label: "Deno compile", - }); - return output; - }); - } - - async close(): Promise { - this.#lifecycle.close(); - await this.#scope.close(); - await this.#source.close(); - this.#entries.clear(); - this.#header = undefined; + override async close(): Promise { this.#admission = undefined; - this.#preparation.clear(); + await super.close(); } - provenance(): readonly [] { - return []; + protected override noPhysicalRange(): ArtifactReaderFailure { + return denoFormatFailure("member has no physical byte range"); } - #assertOpen(signal?: AbortSignal): void { - assertArtifactReadActive(signal); - if (this.#lifecycle.closed) - throw new ArtifactReaderFailure( - "unavailable", - "Deno compile reader is closed", - ); + protected override entryEndedEarly( + entry: ArtifactEntry, + ): ArtifactReaderFailure { + return denoFormatFailure(`member ended early: ${entry.path}`); } - async #prepare(signal?: AbortSignal): Promise { - const source = await this.#source.readSelectedPath(signal); + protected async prepareEntries( + signal?: AbortSignal, + ): Promise> { + const source = await this.verifyCarrier(signal); const probe = this.#admission?.probe ?? (await new ArtifactEmbeddedFormatProbes( @@ -281,11 +180,15 @@ export class DenoStandaloneArtifactReader implements ArtifactReader { )) admit(entry); } - await this.#source.readSelectedPath(signal); - this.#assertOpen(signal); - this.#entries = entries; - this.#header = header; this.#admission = undefined; + return { + entries: [...entries.values()], + coverage: + header.vfs_listing === "unsupported" + ? { status: "unknown", limitations: [UNLISTED_VFS_LIMITATION] } + : { status: "complete", limitations: [] }, + formatMetadata: header, + }; } } diff --git a/src/artifacts/OwnedArtifactStream.ts b/src/artifacts/OwnedArtifactStream.ts index 6c448387a63..8baad7e0850 100644 --- a/src/artifacts/OwnedArtifactStream.ts +++ b/src/artifacts/OwnedArtifactStream.ts @@ -3,7 +3,6 @@ import { pipeline, Transform, type Readable } from "node:stream"; import { ArtifactReaderFailure, artifactReadCancelledBy, - type ArtifactEntry, type ArtifactResourceScope, } from "../resources/index.js"; @@ -65,37 +64,6 @@ export class ArtifactStreamLifecycle { } } -/** Verify the member's byte count and source before stream completion. */ -export const checkedArtifactMemberStream = ( - entry: ArtifactEntry, - label: string, - incomplete: (detail: string) => Error, - verify: () => Promise, -): Transform => { - let bytes = 0; - return new Transform({ - transform(chunk: Buffer, _encoding, callback) { - bytes += chunk.length; - callback(null, chunk); - }, - flush(callback) { - if (bytes !== entry.declaredSize) { - callback(incomplete(`member ended early: ${entry.path}`)); - return; - } - void verify().then( - () => callback(), - (cause: unknown) => - callback( - cause instanceof Error - ? cause - : new Error(`${label} read failed`, { cause }), - ), - ); - }, - }); -}; - /** Keep the carrier and buffered output owned through production and retirement. */ export const ownArtifactStream = ( source: Readable, diff --git a/src/artifacts/PositionalArtifactReader.ts b/src/artifacts/PositionalArtifactReader.ts index 80e31026c36..9f8dafc2966 100644 --- a/src/artifacts/PositionalArtifactReader.ts +++ b/src/artifacts/PositionalArtifactReader.ts @@ -31,8 +31,11 @@ export type PositionalArtifactEntry = ArtifactEntry & { }; /** The entries one preparation established and the coverage to report. */ -export interface PositionalArtifactEntries { - readonly entries: readonly PositionalArtifactEntry[]; +export interface PositionalArtifactEntries< + Metadata = never, + Entry extends ArtifactEntry = PositionalArtifactEntry, +> { + readonly entries: readonly Entry[]; /** The coverage the preparation established, including complete coverage. */ readonly coverage: ArtifactReaderTraversal; readonly formatMetadata?: Metadata; @@ -46,16 +49,18 @@ export interface PositionalArtifactEntries { */ export abstract class PositionalArtifactReader< Metadata extends ArtifactFormatMetadata = never, + Entry extends ArtifactEntry = PositionalArtifactEntry, > implements ArtifactReader { abstract readonly format: ArtifactReader["format"]; readonly #scope = new ArtifactResourceScope(); readonly #lifecycle: ArtifactStreamLifecycle; readonly #label: string; readonly #source: ArtifactFileSource; + readonly #verifySelectedPath: boolean; readonly #preparation = new ArtifactPreparation(); #prepared: | { - readonly entries: ReadonlyMap; + readonly entries: ReadonlyMap; readonly coverage: ArtifactReaderTraversal; readonly formatMetadata: Metadata | undefined; } @@ -65,17 +70,30 @@ export abstract class PositionalArtifactReader< path: string, label: string, admitted?: StableRegularFileDescriptor, - sourceLabel = label, + sourceOptions: + | string + | { + readonly sourceLabel?: string; + readonly verifySelectedPath?: boolean; + } = label, ) { this.#label = label; this.#lifecycle = new ArtifactStreamLifecycle(label); + const sourceLabel = + typeof sourceOptions === "string" + ? sourceOptions + : (sourceOptions.sourceLabel ?? label); + this.#verifySelectedPath = + typeof sourceOptions === "string" + ? false + : (sourceOptions.verifySelectedPath ?? false); this.#source = new ArtifactFileSource(path, sourceLabel, admitted); } /** Read the carrier once and describe its entries. */ protected abstract prepareEntries( signal?: AbortSignal, - ): Promise>; + ): Promise>; /** Metadata from the same validated preparation that established entries and coverage. */ protected get preparedFormatMetadata(): Metadata | undefined { @@ -88,7 +106,9 @@ export abstract class PositionalArtifactReader< ): Promise { await this.#scope.run(async () => { this.assertOpen(signal); - await this.#source.bindSha256(expectedSha256, signal); + if (this.#verifySelectedPath) + await this.#source.bindSelectedPathSha256(expectedSha256, signal); + else await this.#source.bindSha256(expectedSha256, signal); }); } @@ -100,7 +120,7 @@ export abstract class PositionalArtifactReader< this.assertOpen(signal); // The first preparation validates before publishing; cached traversals // still need their own freshness admission. - if (this.#prepared !== undefined) await this.#source.read(signal); + if (this.#prepared !== undefined) await this.verifyCarrier(signal); await this.#preparation.run( signal, () => this.#prepare(signal), @@ -141,8 +161,10 @@ export abstract class PositionalArtifactReader< "unavailable", `Encrypted ${this.#label} member is unsupported: ${stored.path}`, ); - const { handle } = await this.#source.read(signal); + const { handle } = await this.verifyCarrier(signal); this.assertOpen(signal); + if (stored.byteOffset === null || stored.declaredSize === null) + throw this.noPhysicalRange(stored); const lifecycle = this.#lifecycle.member(signal); const { signal: streamSignal, cancellationFailure } = lifecycle; const source = @@ -181,7 +203,9 @@ export abstract class PositionalArtifactReader< protected verifyCarrier( signal?: AbortSignal, ): Promise { - return this.#source.read(signal); + return this.#verifySelectedPath + ? this.#source.readSelectedPath(signal) + : this.#source.read(signal); } /** Refuse work once the caller cancels or close begins. */ @@ -199,7 +223,7 @@ export abstract class PositionalArtifactReader< const entries = new Map( prepared.entries.map((entry) => [entry.adapterKey, entry] as const), ); - await this.#source.read(signal); + await this.verifyCarrier(signal); this.assertOpen(signal); this.#prepared = { entries, @@ -208,10 +232,16 @@ export abstract class PositionalArtifactReader< }; } + /** Format-specific failure when an entry without a physical byte range is opened. */ + protected noPhysicalRange(entry: Entry): ArtifactReaderFailure { + return new ArtifactReaderFailure( + "format", + `${this.#label} member has no physical byte range: ${entry.path}`, + ); + } + /** Format-specific failure when a member stream ends before its declared byte count. */ - protected entryEndedEarly( - entry: PositionalArtifactEntry, - ): ArtifactReaderFailure { + protected entryEndedEarly(entry: Entry): ArtifactReaderFailure { return new ArtifactReaderFailure( "integrity", `${this.#label} entry ended early: ${entry.path}`, @@ -219,15 +249,12 @@ export abstract class PositionalArtifactReader< ); } - #entryStream( - entry: PositionalArtifactEntry, - lifecycle: ArtifactMemberLifecycle, - ): Transform { + #entryStream(entry: Entry, lifecycle: ArtifactMemberLifecycle): Transform { const label = this.#label; let bytes = 0; const check = async (): Promise => { if (bytes !== entry.declaredSize) throw this.entryEndedEarly(entry); - await lifecycle.verify((signal) => this.#source.read(signal)); + await lifecycle.verify((signal) => this.verifyCarrier(signal)); }; return new Transform({ transform(chunk: Buffer, _encoding, callback) {