fix(artifacts): reuse current classification and region reads

This commit is contained in:
64579525
2026-10-13 15:38:40 +08:00
175 changed files with 6746 additions and 1348 deletions
@@ -167,46 +167,50 @@ it("retains a failed rollback owner and preserves the materialization failure",
await expect(access(output)).rejects.toThrow();
});
it("retains a tree whose setup failed after root identity was captured", async () => {
const { root, archive } = await createArchive();
const output = join(root, "output");
const blocker = join(output, "unowned.txt");
const client = createClient(archive);
const prototypeHandle = await open(join(root, "prototype-handle"), "w");
const handlePrototype = Object.getPrototypeOf(prototypeHandle) as Pick<
typeof prototypeHandle,
"chmod"
>;
await prototypeHandle.close();
await rm(join(root, "prototype-handle"));
onTestFinished(async () => {
vi.restoreAllMocks();
await rm(blocker, { force: true });
await client.close();
});
vi.spyOn(handlePrototype, "chmod").mockImplementationOnce(async function (
this: typeof prototypeHandle,
) {
await writeFile(blocker, "keep until owner retry");
throw new Error("injected output setup failure");
});
// Windows intentionally skips directory fchmod; this fault requires POSIX setup.
it.skipIf(process.platform === "win32")(
"retains a tree whose POSIX setup failed after root identity was captured",
async () => {
const { root, archive } = await createArchive();
const output = join(root, "output");
const blocker = join(output, "unowned.txt");
const client = createClient(archive);
const prototypeHandle = await open(join(root, "prototype-handle"), "w");
const handlePrototype = Object.getPrototypeOf(prototypeHandle) as Pick<
typeof prototypeHandle,
"chmod"
>;
await prototypeHandle.close();
await rm(join(root, "prototype-handle"));
onTestFinished(async () => {
vi.restoreAllMocks();
await rm(blocker, { force: true });
await client.close();
});
vi.spyOn(handlePrototype, "chmod").mockImplementationOnce(async function (
this: typeof prototypeHandle,
) {
await writeFile(blocker, "keep until owner retry");
throw new Error("injected output setup failure");
});
const extraction = await client.execute("extract_artifact", {
output_root: output,
});
expect(extraction).toMatchObject({
ok: false,
error: {
_tag: "ArtifactOperationError",
detail: expect.stringContaining("injected output setup failure"),
cleanup: { resources: [output] },
},
});
expect(await readFile(blocker, "utf8")).toBe("keep until owner retry");
await rm(blocker);
expect(await client.close()).toMatchObject({ ok: true });
await expect(access(output)).rejects.toThrow();
});
const extraction = await client.execute("extract_artifact", {
output_root: output,
});
expect(extraction).toMatchObject({
ok: false,
error: {
_tag: "ArtifactOperationError",
detail: expect.stringContaining("injected output setup failure"),
cleanup: { resources: [output] },
},
});
expect(await readFile(blocker, "utf8")).toBe("keep until owner retry");
await rm(blocker);
expect(await client.close()).toMatchObject({ ok: true });
await expect(access(output)).rejects.toThrow();
},
);
it("waits for admitted extraction before close and rejects later work", async () => {
const { root, archive } = await createArchive();
@@ -3,7 +3,7 @@ import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackage, createPackageWithOptions } from "@electron/asar";
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import {
@@ -13,6 +13,7 @@ import {
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { DirectoryArtifactReader } from "../../../../src/artifacts/DirectoryArtifactReader.js";
it.each(["file", "directory"] as const)(
"rolls back when an inventoried %s disappears before extraction",
@@ -61,6 +62,41 @@ it("still refuses a regular file added after inventory and rolls back", async ()
await expect(access(output)).rejects.toThrow();
});
it("rolls back when cancellation arrives while closing the materialization reader", async () => {
const root = await createTestTempDirectory("rea-extract-cancel-close-");
const source = join(root, "source");
await mkdir(source);
await writeFile(join(source, "payload.txt"), "complete payload\n");
const snapshot = await scanArtifactInventory(source);
const output = join(root, "output");
const controller = new AbortController();
const close = DirectoryArtifactReader.prototype.close;
const closeSpy = vi
.spyOn(DirectoryArtifactReader.prototype, "close")
.mockImplementation(async function (this: DirectoryArtifactReader) {
controller.abort();
await close.call(this);
});
try {
await expect(
materializeArtifactInventory(
{
inputPath: source,
outputRoot: output,
environment: process.env,
integrityPolicy: "fail",
},
source,
snapshot,
controller.signal,
),
).rejects.toMatchObject({ reason: "cancelled" });
await expect(access(output)).rejects.toThrow();
} finally {
closeSpy.mockRestore();
}
});
it("preserves every equal-content occurrence and copies a nested ASAR as its containing file", async () => {
const root = await createTestTempDirectory("rea-extract-nested-");
const source = join(root, "source");
@@ -135,7 +171,6 @@ const inventoriedExtraction = async (source: string, output: string) => {
materializeArtifactInventory(
{
inputPath: source,
inputFormat: "asar",
outputRoot: output,
environment: process.env,
integrityPolicy: "fail",
@@ -3,17 +3,63 @@ import { access, mkdir, readFile, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { buildBinary } from "plist";
import { writeOrderedZip } from "../../../fixtures/artifactEntryOrder.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import { inesFixture } from "../../../fixtures/ines.js";
import { nativeAotPeFixture } from "../../../fixtures/nativeaotPe.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
it.each(["plist", "pe"] as const)(
"extracts current iNES bytes after a non-extractable %s target is replaced",
async (format) => {
const root = await createTestTempDirectory("rea-extract-current-");
const path = join(root, "source.bin");
await writeFile(
path,
format === "plist" ? buildBinary({ value: "old" }) : nativeAotPeFixture(),
);
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
expect(target.value.format).toBe(format);
const client = new ArtifactProvider(process.env).createClient(target.value);
const bytes = inesFixture({
trainer: true,
trailing: Buffer.from("tail"),
});
await writeFile(path, bytes);
const output = join(root, "output");
const result = await client.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({ output_root: output }),
);
if (!result.ok) throw result.error;
const extracted = artifactExtractionResultSchema.parse(result.value.result);
expect(extracted.manifest.root_format).toBe("ines");
const paths = [
"header.bin",
"trainer.bin",
"prg/000.bin",
"prg/001.bin",
"chr/000.bin",
"trailing.bin",
];
expect(extracted.artifacts).toHaveLength(paths.length);
expect(
Buffer.concat(
await Promise.all(paths.map((part) => readFile(join(output, part)))),
),
).toEqual(bytes);
await client.close();
},
);
describe("artifact extraction format support", () => {
it.each(["zip", "asar", "hap", "hsp", "app"] as const)(
"extracts the scanned %s after an active iNES path is replaced",
@@ -82,10 +128,12 @@ describe("artifact extraction format support", () => {
await expect(access(output)).rejects.toThrow();
});
it("refuses unsupported formats before inventory or output", async () => {
it("refuses a currently unsupported format before child inventory or output", async () => {
const root = await createTestTempDirectory("rea-extract-format-");
const image = join(root, "Image.dmg");
await writeFile(image, "not mounted");
const bytes = Buffer.alloc(512);
bytes.write("koly", 0, "ascii");
await writeFile(image, bytes);
const alias = join(root, "Alias.dmg");
await symlink(image, alias);
const output = join(root, "output");
@@ -3,6 +3,8 @@ import { readFile } from "node:fs/promises";
import { describe, expect, it, onTestFinished } from "vitest";
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
import { XcrunCommandRunner } from "../../../../src/native/CommandRunner.js";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
/**
* Read a 32-bit FAT table directly. The host's /bin/ls changes between macOS
@@ -20,6 +22,26 @@ const fatSlices = async (
};
describe("Mach-O slice reader with system lipo", () => {
it("names the process ownership helper prerequisite when lipo cannot be supervised", async () => {
const prerequisite =
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.";
const reader = new MachOSliceArtifactReader(
process.execPath,
{},
new XcrunCommandRunner({}, undefined, () =>
Promise.reject(new DarwinProcessOwnershipInspectionError(prerequisite)),
),
);
onTestFinished(() => reader.close());
const enumerate = async () => {
for await (const _entry of reader.entries()) continue;
};
await expect(enumerate()).rejects.toMatchObject({
reason: "unavailable",
message: `lipo could not enumerate universal Mach-O slices: ${prerequisite}`,
});
});
it.skipIf(process.platform !== "darwin")(
"checks real /bin/ls slice ranges against its FAT table",
async () => {
@@ -8,6 +8,7 @@ import {
type NativeCommandLauncher,
} from "../../../../src/native/CommandRunner.js";
import { ok } from "../../../../src/domain/result.js";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
afterEach(() => vi.unstubAllEnvs());
@@ -210,3 +211,23 @@ it.skipIf(process.platform === "win32")(
if (!killed.ok) expect(killed.error.reason).toBe("nonzero-exit");
},
);
it("keeps the ownership helper prerequisite when xcrun cannot be supervised", async () => {
const inspection = new DarwinProcessOwnershipInspectionError(
"macOS process ownership inspection requires the Apple Swift compiler via xcrun",
);
const runner = new XcrunCommandRunner({}, undefined, () =>
Promise.reject(inspection),
);
const result = await runner.run("file", [], {});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
tool: "file",
reason: "io",
detail: inspection.message,
cause: { tool: "xcrun", detail: inspection.message, cause: inspection },
});
});
@@ -1,4 +1,5 @@
import { createHash } from "node:crypto";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
import { EventEmitter } from "node:events";
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -280,6 +281,30 @@ describe("native command failure capture and limits", () => {
stderr_bytes: expect.any(Number),
},
});
expect(projectAnalysisError(result.error).details).not.toHaveProperty(
"diagnostics.detail",
);
});
it("projects the ownership helper prerequisite when a command cannot be supervised", async () => {
const inspection = new DarwinProcessOwnershipInspectionError(
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.",
);
const runner = new XcrunCommandRunner(
{},
() =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
() => Promise.reject(inspection),
);
const result = await new NativeMacOSProvider({}, runner, "darwin")
.createClient(machoTarget("/private/fixture"))
.execute("demangle_swift", { symbols: ["fixture-symbol"] });
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error).details).toMatchObject({
diagnostics: { reason: "io", detail: inspection.message },
});
});
it("retains output written before cancellation and reaps the stalled command", async () => {