refactor(artifacts): test inventory changes at materialization boundary

This commit is contained in:
morluto
2026-10-10 02:49:46 +08:00
parent e36afa112f
commit 750fb65650
2 changed files with 46 additions and 72 deletions
@@ -26,6 +26,7 @@ import {
} from "../../domain/artifactGraph.js";
import { AnalysisUnsupportedTargetError } from "../../domain/analysisErrorCore.js";
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
import { scanArtifactInventory } from "../inventory/ArtifactInventory.js";
/** Local extraction input with the output root chosen by the adapter. */
@@ -49,6 +50,17 @@ export const extractArtifact = async (
signal,
environment: input.environment,
});
return materializeArtifactInventory(input, sourcePath, snapshot, signal);
};
/** Materialize a scanned inventory, verifying every current occurrence against it. */
export const materializeArtifactInventory = async (
input: ArtifactExtractionInput,
sourcePath: string,
snapshot: ArtifactInventorySnapshot,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> => {
abortIfNeeded(signal);
const selectedOccurrences = snapshot.occurrences.filter(
(occurrence) =>
(occurrence.entry_kind === "file" || occurrence.entry_kind === "slice") &&
@@ -1,12 +1,13 @@
import { createHash } from "node:crypto";
import { watch } from "node:fs";
import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { join } from "node:path";
import { createPackage, createPackageWithOptions } from "@electron/asar";
import { expect, it, onTestFinished } from "vitest";
import { expect, it } from "vitest";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { materializeArtifactInventory } from "../../../../src/artifacts/extraction/ArtifactExtraction.js";
import { scanArtifactInventory } from "../../../../src/artifacts/inventory/ArtifactInventory.js";
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
@@ -18,44 +19,22 @@ it.each(["file", "directory"] as const)(
const source = join(root, "source");
await mkdir(join(source, "z"), { recursive: true });
// Equal bytes share an artifact node, but both occurrences must be copied.
const bytes = Buffer.alloc(8 * 1024 * 1024, "same bytes\n");
const bytes = Buffer.from("same bytes\n");
await writeFile(join(source, "a.txt"), bytes);
await writeFile(join(source, "z", "missing.txt"), bytes);
const output = join(root, "output");
const changed = afterInventory(output, async () => {
await rm(
removedKind === "file"
? join(source, "z", "missing.txt")
: join(source, "z"),
{ recursive: removedKind === "directory" },
);
const materialize = await inventoriedExtraction(source, output);
await rm(
removedKind === "file"
? join(source, "z", "missing.txt")
: join(source, "z"),
{ recursive: removedKind === "directory" },
);
await expect(materialize()).rejects.toMatchObject({
reason: "integrity",
message:
"Inventoried regular artifact entries were not materialized: z/missing.txt",
});
const result = await extract(source, output);
await changed();
if (result.ok) throw new Error("Incomplete extraction must fail");
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
code: "artifact_operation_failed",
details: {
operation: "extract_artifact",
},
});
// A directory already returned by readdir can disappear before its stat.
// That earlier reader failure retains ENOENT instead of reaching the final
// completeness check. Both paths must reject publication and roll back.
if (removedKind === "directory" && projected.details?.reason === "io") {
expect(projected.details).toMatchObject({
reason: "io",
detail: `Could not inspect entry at ${join(source, "z")} (ENOENT)`,
});
} else {
expect(projected.details).toMatchObject({
reason: "integrity",
detail:
"Inventoried regular artifact entries were not materialized: z/missing.txt",
});
}
await expect(access(output)).rejects.toThrow();
expect(
createHash("sha256")
@@ -69,22 +48,13 @@ it("still refuses a regular file added after inventory and rolls back", async ()
const root = await createTestTempDirectory("rea-extract-added-");
const source = join(root, "source");
await mkdir(source);
await writeFile(
join(source, "a.txt"),
Buffer.alloc(8 * 1024 * 1024, "original\n"),
);
await writeFile(join(source, "a.txt"), "original\n");
const output = join(root, "output");
const changed = afterInventory(output, async () => {
await writeFile(join(source, "z.txt"), "new\n");
});
const result = await extract(source, output);
await changed();
if (result.ok) throw new Error("Changed inventory must fail");
expect(projectAnalysisError(result.error)).toMatchObject({
details: {
reason: "integrity",
detail: "Regular artifact entry is missing from inventory: z.txt",
},
const materialize = await inventoriedExtraction(source, output);
await writeFile(join(source, "z.txt"), "new\n");
await expect(materialize()).rejects.toMatchObject({
reason: "integrity",
message: "Regular artifact entry is missing from inventory: z.txt",
});
await expect(access(output)).rejects.toThrow();
});
@@ -160,27 +130,19 @@ it("ignores unavailable members of a nested ASAR but refuses them as active entr
await expect(access(activeOutput)).rejects.toThrow();
});
// The real destination is created only after inventory. A streamed first file
// leaves time to mutate a later entry without replacing any production method.
const afterInventory = (output: string, change: () => Promise<void>) => {
let mutation:
| Promise<{ ok: true } | { ok: false; cause: unknown }>
| undefined;
const watcher = watch(dirname(output), (_event, filename) => {
if (filename !== basename(output) || mutation !== undefined) return;
watcher.close();
mutation = change().then(
() => ({ ok: true as const }),
(cause: unknown) => ({ ok: false as const, cause }),
const inventoriedExtraction = async (source: string, output: string) => {
const snapshot = await scanArtifactInventory(source);
return () =>
materializeArtifactInventory(
{
inputPath: source,
inputFormat: "asar",
outputRoot: output,
environment: process.env,
},
source,
snapshot,
);
});
onTestFinished(() => watcher.close());
return async () => {
if (mutation === undefined)
throw new Error("Extraction destination was not observed");
const result = await mutation;
if (!result.ok) throw result.cause;
};
};
const extract = (source: string, output: string) =>