fix(providers): preserve observations and primary cleanup failures
This commit is contained in:
@@ -221,7 +221,7 @@ class ArtifactClient implements AnalysisClient {
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(translateFailure(operation, cause));
|
||||
return err(translateArtifactFailure(operation, cause));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -378,7 +378,8 @@ const isArtifactOperation = (
|
||||
operation as (typeof ARTIFACT_ANALYSIS_OPERATIONS)[number],
|
||||
);
|
||||
|
||||
const translateFailure = (
|
||||
/** Translate one artifact boundary failure while retaining cleanup evidence. */
|
||||
export const translateArtifactFailure = (
|
||||
operation: ArtifactAnalysisOperation,
|
||||
cause: unknown,
|
||||
): AnalysisError => {
|
||||
@@ -388,6 +389,12 @@ const translateFailure = (
|
||||
cause.reason,
|
||||
cause.details,
|
||||
cause.message,
|
||||
{
|
||||
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
|
||||
...(cause.partialObservation === undefined
|
||||
? {}
|
||||
: { partialObservation: cause.partialObservation }),
|
||||
},
|
||||
);
|
||||
// Caller-selection and unsupported-target failures are already typed; keep
|
||||
// their correction details instead of reducing them to an I/O failure.
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import type { Readable } from "node:stream";
|
||||
import type { ArtifactCommand } from "../domain/artifactGraph.js";
|
||||
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
|
||||
import type {
|
||||
AnalysisCleanupObservation,
|
||||
AnalysisPartialObservation,
|
||||
} from "../domain/analysisErrorBase.js";
|
||||
|
||||
export interface ArtifactReaderFailureOptions extends ErrorOptions {
|
||||
readonly cleanup?: AnalysisCleanupObservation;
|
||||
readonly partialObservation?: AnalysisPartialObservation;
|
||||
}
|
||||
|
||||
/** Archive-neutral entry metadata. Reader adapters never choose output paths. */
|
||||
export interface ArtifactEntry {
|
||||
@@ -33,6 +42,9 @@ export interface ArtifactReader {
|
||||
|
||||
/** Typed adapter failure translated at provider boundary. */
|
||||
export class ArtifactReaderFailure extends Error {
|
||||
readonly cleanup: AnalysisCleanupObservation | undefined;
|
||||
readonly partialObservation: AnalysisPartialObservation | undefined;
|
||||
|
||||
constructor(
|
||||
readonly reason:
|
||||
| "cancelled"
|
||||
@@ -43,7 +55,7 @@ export class ArtifactReaderFailure extends Error {
|
||||
| "path"
|
||||
| "unavailable",
|
||||
message: string,
|
||||
options?: ErrorOptions,
|
||||
options?: ArtifactReaderFailureOptions,
|
||||
readonly details?: Readonly<{
|
||||
logicalPath: string;
|
||||
declaredSha256: string | null;
|
||||
@@ -53,5 +65,56 @@ export class ArtifactReaderFailure extends Error {
|
||||
) {
|
||||
super(message, options);
|
||||
this.name = "ArtifactReaderFailure";
|
||||
this.cleanup = options?.cleanup;
|
||||
this.partialObservation = options?.partialObservation;
|
||||
}
|
||||
|
||||
/** Preserve the primary failure while attaching cleanup and any complete observation. */
|
||||
static withCleanup(
|
||||
cause: unknown,
|
||||
cleanup: AnalysisCleanupObservation,
|
||||
partialObservation?: AnalysisPartialObservation,
|
||||
): ArtifactReaderFailure {
|
||||
const primary =
|
||||
cause instanceof ArtifactReaderFailure
|
||||
? cause
|
||||
: new ArtifactReaderFailure("io", errorMessage(cause), { cause });
|
||||
const mergedObservation = partialObservation ?? primary.partialObservation;
|
||||
return new ArtifactReaderFailure(
|
||||
primary.reason,
|
||||
primary.message,
|
||||
{
|
||||
cause: primary,
|
||||
cleanup: combineCleanup(primary.cleanup, cleanup),
|
||||
...(mergedObservation === undefined
|
||||
? {}
|
||||
: { partialObservation: mergedObservation }),
|
||||
},
|
||||
primary.details,
|
||||
);
|
||||
}
|
||||
|
||||
/** Give otherwise opaque cleanup failures a concrete owned resource. */
|
||||
static cleanupObservation(
|
||||
cause: unknown,
|
||||
resource: string,
|
||||
): AnalysisCleanupObservation {
|
||||
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
|
||||
return cause.cleanup;
|
||||
return { reason: errorMessage(cause), resources: [resource] };
|
||||
}
|
||||
}
|
||||
|
||||
const combineCleanup = (
|
||||
primary: AnalysisCleanupObservation | undefined,
|
||||
cleanup: AnalysisCleanupObservation,
|
||||
): AnalysisCleanupObservation =>
|
||||
primary === undefined || primary === cleanup
|
||||
? cleanup
|
||||
: {
|
||||
reason: `${primary.reason}; ${cleanup.reason}`,
|
||||
resources: [...new Set([...primary.resources, ...cleanup.resources])],
|
||||
};
|
||||
|
||||
const errorMessage = (cause: unknown): string =>
|
||||
cause instanceof Error ? cause.message : String(cause);
|
||||
|
||||
@@ -188,7 +188,18 @@ export class NativeDmgArtifactReader implements ArtifactReader {
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`DMG detach or mount-root cleanup failed for ${JSON.stringify(this.path)}: ${failureMessage(detachFailure)}`,
|
||||
{ cause: detachFailure },
|
||||
{
|
||||
cause: detachFailure,
|
||||
cleanup: {
|
||||
reason: failureMessage(detachFailure),
|
||||
resources: [
|
||||
...this.#devices.map((device) => `DMG device ${device}`),
|
||||
...(this.#mountRoot === undefined
|
||||
? []
|
||||
: [`DMG mount root ${this.#mountRoot}`]),
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -298,10 +309,12 @@ export class NativeDmgArtifactReader implements ArtifactReader {
|
||||
cleanupFailure = cleanupCause;
|
||||
}
|
||||
if (cleanupFailure !== undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`DMG attach failed and cleanup could not detach every device: ${failureMessage(cause)}; cleanup: ${failureMessage(cleanupFailure)}`,
|
||||
{ cause: new AggregateError([cause, cleanupFailure]) },
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
cause,
|
||||
ArtifactReaderFailure.cleanupObservation(
|
||||
cleanupFailure,
|
||||
`DMG mount root ${this.#mountRoot ?? this.path}`,
|
||||
),
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
|
||||
@@ -208,7 +208,12 @@ export class SafeOutputTree {
|
||||
/** Remove only this operation's unsealed tree and verify absence. */
|
||||
async rollback(): Promise<SafeOutputCleanup> {
|
||||
if (this.#published) return structuredClone(this.#cleanup);
|
||||
await rm(this.#outputRoot, { recursive: true, force: true });
|
||||
let removalFailure: unknown;
|
||||
try {
|
||||
await rm(this.#outputRoot, { recursive: true, force: true });
|
||||
} catch (cause: unknown) {
|
||||
removalFailure = cause;
|
||||
}
|
||||
const absent = await isAbsent(this.#outputRoot);
|
||||
this.#cleanup = absent
|
||||
? { status: "complete", residualPaths: [] }
|
||||
@@ -219,7 +224,17 @@ export class SafeOutputTree {
|
||||
if (!absent)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Extraction output cleanup could not be verified",
|
||||
`Extraction output cleanup could not be verified${removalFailure === undefined ? "" : `: ${removalFailure instanceof Error ? removalFailure.message : String(removalFailure)}`}`,
|
||||
{
|
||||
cause: removalFailure,
|
||||
cleanup: {
|
||||
reason:
|
||||
removalFailure instanceof Error
|
||||
? removalFailure.message
|
||||
: "Extraction output root remains after rollback",
|
||||
resources: [this.#outputRoot],
|
||||
},
|
||||
},
|
||||
);
|
||||
return structuredClone(this.#cleanup);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { lstat, realpath } from "node:fs/promises";
|
||||
|
||||
import { compareCodePoints } from "../../domain/canonicalOrdering.js";
|
||||
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
|
||||
import { AsarArtifactReader } from "../AsarArtifactReader.js";
|
||||
import {
|
||||
@@ -136,10 +137,12 @@ const materializeSelection = async ({
|
||||
selected.map((item) => [item.occurrence.logical_path, item]),
|
||||
);
|
||||
const reader = await createReader(sourcePath, input);
|
||||
const output = await SafeOutputTree.create(input.outputRoot);
|
||||
let output: SafeOutputTree | undefined;
|
||||
let readerCloseAttempted = false;
|
||||
let readerClosed = false;
|
||||
const extracted: ExtractedOccurrence[] = [];
|
||||
try {
|
||||
output = await SafeOutputTree.create(input.outputRoot);
|
||||
const materialized: SelectedOccurrence[] = [];
|
||||
const registry = new ArtifactPathRegistry();
|
||||
for await (const entry of reader.entries(signal)) {
|
||||
@@ -171,10 +174,11 @@ const materializeSelection = async ({
|
||||
});
|
||||
materialized.push(selectedItem);
|
||||
}
|
||||
readerCloseAttempted = true;
|
||||
await reader.close();
|
||||
readerClosed = true;
|
||||
extracted.sort((left, right) =>
|
||||
left.relative_path.localeCompare(right.relative_path, "en"),
|
||||
compareCodePoints(left.relative_path, right.relative_path),
|
||||
);
|
||||
const result = createExtractionResult(
|
||||
input,
|
||||
@@ -185,12 +189,48 @@ const materializeSelection = async ({
|
||||
await output.commit();
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
if (!readerClosed)
|
||||
await reader.close().catch((cause: unknown) => {
|
||||
// best-effort cleanup: reader close must not mask the extraction failure.
|
||||
void cause;
|
||||
const cleanupFailures: {
|
||||
readonly cause: unknown;
|
||||
readonly resource: string;
|
||||
}[] = [];
|
||||
if (readerCloseAttempted && !readerClosed)
|
||||
cleanupFailures.push({
|
||||
cause,
|
||||
resource: `artifact reader for ${sourcePath}`,
|
||||
});
|
||||
await output.rollback();
|
||||
if (!readerCloseAttempted) {
|
||||
try {
|
||||
readerCloseAttempted = true;
|
||||
await reader.close();
|
||||
} catch (cleanupCause: unknown) {
|
||||
cleanupFailures.push({
|
||||
cause: cleanupCause,
|
||||
resource: `artifact reader for ${sourcePath}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (output !== undefined) {
|
||||
try {
|
||||
await output.rollback();
|
||||
} catch (cleanupCause: unknown) {
|
||||
cleanupFailures.push({
|
||||
cause: cleanupCause,
|
||||
resource: input.outputRoot,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (cleanupFailures.length > 0) {
|
||||
const observations = cleanupFailures.map(
|
||||
({ cause: cleanupCause, resource }) =>
|
||||
ArtifactReaderFailure.cleanupObservation(cleanupCause, resource),
|
||||
);
|
||||
throw ArtifactReaderFailure.withCleanup(cause, {
|
||||
reason: observations.map(({ reason }) => reason).join("; "),
|
||||
resources: [
|
||||
...new Set(observations.flatMap(({ resources }) => resources)),
|
||||
],
|
||||
});
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
@@ -205,7 +245,7 @@ const createExtractionResult = (
|
||||
source_manifest_id: inventory.manifest.manifest_id,
|
||||
selected_occurrence_ids: selected
|
||||
.map(({ occurrence }) => occurrence.occurrence_id)
|
||||
.sort((left, right) => left.localeCompare(right)),
|
||||
.sort(compareCodePoints),
|
||||
files_sha256: canonicalDigest(extracted, "Artifact"),
|
||||
output_root_alias: "$OUTPUT_ROOT" as const,
|
||||
};
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
export const scanCanonicalArtifactInventory = async (
|
||||
path: string,
|
||||
options: ArtifactInventoryOptions = {},
|
||||
readerFactory: typeof createReader = createReader,
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY;
|
||||
const metadata = await lstat(path);
|
||||
@@ -52,33 +53,59 @@ export const scanCanonicalArtifactInventory = async (
|
||||
const rootDigest = metadata.isDirectory()
|
||||
? null
|
||||
: await hashReadable(createReadStream(path), options.signal);
|
||||
const reader = await createReader(
|
||||
const reader = await readerFactory(
|
||||
path,
|
||||
rootFormat,
|
||||
options.environment ?? {},
|
||||
options.signal,
|
||||
);
|
||||
|
||||
let outcome:
|
||||
| {
|
||||
readonly kind: "completed";
|
||||
readonly snapshot: ArtifactInventorySnapshot;
|
||||
}
|
||||
| { readonly kind: "failed"; readonly cause: unknown };
|
||||
try {
|
||||
const { nodes, occurrences, pendingContradictions } = await scanReader(
|
||||
reader,
|
||||
options.signal,
|
||||
integrity,
|
||||
);
|
||||
return await buildInventorySnapshot({
|
||||
path,
|
||||
metadata,
|
||||
rootFormat,
|
||||
rootDigest,
|
||||
reader,
|
||||
signal: options.signal,
|
||||
nodes,
|
||||
occurrences,
|
||||
pendingContradictions,
|
||||
});
|
||||
} finally {
|
||||
await reader?.close();
|
||||
outcome = {
|
||||
kind: "completed",
|
||||
snapshot: await buildInventorySnapshot({
|
||||
path,
|
||||
metadata,
|
||||
rootFormat,
|
||||
rootDigest,
|
||||
reader,
|
||||
signal: options.signal,
|
||||
nodes,
|
||||
occurrences,
|
||||
pendingContradictions,
|
||||
}),
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
outcome = { kind: "failed", cause };
|
||||
}
|
||||
try {
|
||||
await reader?.close();
|
||||
} catch (cleanupCause: unknown) {
|
||||
const cleanup = ArtifactReaderFailure.cleanupObservation(
|
||||
cleanupCause,
|
||||
`artifact reader for ${path}`,
|
||||
);
|
||||
const primary = outcome.kind === "failed" ? outcome.cause : cleanupCause;
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
primary,
|
||||
cleanup,
|
||||
outcome.kind === "completed"
|
||||
? { kind: "artifact-inventory", inventory: outcome.snapshot }
|
||||
: undefined,
|
||||
);
|
||||
}
|
||||
if (outcome.kind === "failed") throw outcome.cause;
|
||||
return outcome.snapshot;
|
||||
};
|
||||
|
||||
interface SnapshotBuildInput {
|
||||
|
||||
Reference in New Issue
Block a user