merge: integrate main and retain per-slice FAT alignment
This commit is contained in:
@@ -11,7 +11,7 @@ import {
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { HistoricalCaptureDecoder } from "../../../src/browser/history/HistoricalCaptureDecoder.js";
|
||||
import { MitmproxyCaptureAdapter } from "../../../src/browser/history/MitmproxyCaptureAdapter.js";
|
||||
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "../../../src/browser/history/CaptureRelease.js";
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { historicalHar } from "../../fixtures/historicalHar.js";
|
||||
import { decodeHarCapture } from "../../../src/browser/history/HarCapture.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
|
||||
const linux = it.skipIf(process.platform !== "linux");
|
||||
|
||||
@@ -138,6 +139,66 @@ it("classifies an oversized selected capture before creating an owned decoder",
|
||||
});
|
||||
});
|
||||
|
||||
it("retains a failed capture reader and retries it before a fresh load", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-capture-reader-close-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
const originalClose = OwnedFileHandle.prototype.close;
|
||||
const close = vi.spyOn(OwnedFileHandle.prototype, "close");
|
||||
let allowClose = false;
|
||||
let closeAttempts = 0;
|
||||
close.mockImplementation(async function (this: OwnedFileHandle) {
|
||||
closeAttempts += 1;
|
||||
if (!allowClose) throw new Error("injected capture reader close failure");
|
||||
await originalClose.call(this);
|
||||
});
|
||||
let decoderCalls = 0;
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => {
|
||||
decoderCalls += 1;
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "process.exit(0)"],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const input = inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
});
|
||||
try {
|
||||
const first = await decoder.inspect(input);
|
||||
expect(first.ok).toBe(false);
|
||||
if (first.ok) throw new Error("Reader close failure must fail inspection");
|
||||
expect(first.error.cleanupResources).toContain(path);
|
||||
expect(decoderCalls).toBe(0);
|
||||
|
||||
const refused = await decoder.inspect(input);
|
||||
expect(refused.ok).toBe(false);
|
||||
if (refused.ok) throw new Error("Fresh read must wait for owner cleanup");
|
||||
expect(refused.error.cleanupIncomplete).toBe(true);
|
||||
expect(refused.error.cleanupResources).toContain(path);
|
||||
expect(decoderCalls).toBe(0);
|
||||
expect(closeAttempts).toBe(2);
|
||||
|
||||
allowClose = true;
|
||||
await decoder.close();
|
||||
expect(closeAttempts).toBe(3);
|
||||
} finally {
|
||||
allowClose = true;
|
||||
await decoder.close().catch(() => undefined);
|
||||
close.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not misclassify decoder filesystem failures as missing selected input", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-command-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
|
||||
@@ -5,6 +5,7 @@ import { silentLogger } from "../../../src/logger.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
|
||||
|
||||
it.each([false, true])(
|
||||
"awaits cleanup retry and preserves completed output when retry failure is %s",
|
||||
@@ -82,6 +83,111 @@ it.each([false, true])(
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the primary CLI failure when close throws an untyped error", async () => {
|
||||
const cli = Cli.create("capture-cleanup-primary-test", { sync: false });
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () =>
|
||||
err(
|
||||
new AnalysisInputError("inspect_packet_capture", {
|
||||
userMessage: "The selected capture input was rejected.",
|
||||
}),
|
||||
),
|
||||
close: async () => {
|
||||
throw new Error("raw close failure");
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
message: "The selected capture input was rejected.",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: { code: "invalid_request" },
|
||||
},
|
||||
resources: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("closes the service and retains an unexpected producer rejection", async () => {
|
||||
const cli = Cli.create("capture-producer-rejection-test", { sync: false });
|
||||
let closed = false;
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
throw new Error("raw producer failure");
|
||||
},
|
||||
close: async () => {
|
||||
closed = true;
|
||||
throw new Error("raw close failure");
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(closed).toBe(true);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
operation: "inspect_packet_capture",
|
||||
provider_id: "tshark-capture",
|
||||
},
|
||||
},
|
||||
cleanup_error: { code: "cleanup_incomplete" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an oversized selector budget before the CLI invokes its service", async () => {
|
||||
const cli = Cli.create("capture-selector-test", { sync: false });
|
||||
let called = false;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { readAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import {
|
||||
snapshotBinding,
|
||||
snapshotTarget,
|
||||
} from "../../../src/domain/analysisSnapshot.js";
|
||||
import {
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
} from "../../../src/domain/analysisSnapshot.fixture.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe.each([
|
||||
{ mode: "native", paddingBytes: 0 },
|
||||
{ mode: "streamed", paddingBytes: 9 * 1024 * 1024 },
|
||||
])("analysis snapshot input ($mode)", ({ paddingBytes }) => {
|
||||
it.each(["[]", "null", "5", '"x"', "true"])(
|
||||
"classifies a readable %s root as invalid content, not an I/O failure",
|
||||
async (document) => {
|
||||
const root = await createTestTempDirectory("rea-snapshot-root-");
|
||||
const path = join(root, "snapshot.json");
|
||||
const encoded = `${" ".repeat(paddingBytes)}${document}`;
|
||||
await writeFile(path, encoded);
|
||||
|
||||
const loaded = await readAnalysisSnapshot(path);
|
||||
if (loaded.ok) throw new Error("Expected a non-object root rejection");
|
||||
const projected = projectAnalysisError(loaded.error);
|
||||
expect(projected).toMatchObject({
|
||||
code: "evidence_integrity_mismatch",
|
||||
details: { reason: "invalid-json" },
|
||||
});
|
||||
expect(projected.message).toContain("Repair or recreate");
|
||||
expect(loaded.error.cause).toMatchObject({
|
||||
message: "JSON document root must be an object",
|
||||
});
|
||||
expect(await readFile(path, "utf8")).toBe(encoded);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains syntax and snapshot-member validation and loads valid objects", async () => {
|
||||
const root = await createTestTempDirectory("rea-snapshot-validation-");
|
||||
const path = join(root, "snapshot.json");
|
||||
const prefix = " ".repeat(paddingBytes);
|
||||
await writeFile(path, `${prefix}[`);
|
||||
expect(await readAnalysisSnapshot(path)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceFileError", reason: "invalid-json" },
|
||||
});
|
||||
await writeFile(path, `${prefix}{}`);
|
||||
expect(await readAnalysisSnapshot(path)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceIntegrityError" },
|
||||
});
|
||||
const snapshot = {
|
||||
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
|
||||
binding: snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE),
|
||||
entries: [],
|
||||
workflow_entries: [],
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
};
|
||||
await writeFile(path, `${prefix}${JSON.stringify(snapshot)}`);
|
||||
expect(await readAnalysisSnapshot(path)).toEqual({
|
||||
ok: true,
|
||||
value: snapshot,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps file-selection failures distinct from invalid snapshot contents", async () => {
|
||||
const root = await createTestTempDirectory("rea-snapshot-selection-");
|
||||
for (const [path, reason] of [
|
||||
[join(root, "missing.json"), "missing"],
|
||||
[root, "not-file"],
|
||||
] as const) {
|
||||
const loaded = await readAnalysisSnapshot(path);
|
||||
if (loaded.ok) throw new Error("Expected a file-selection failure");
|
||||
expect(projectAnalysisError(loaded.error)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { reason },
|
||||
});
|
||||
}
|
||||
});
|
||||
+117
-1
@@ -152,7 +152,7 @@ describe("TypeScript source module loader semantics", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("CommonJS and ESM module relationships", () => {
|
||||
describe("JavaScript module relationships", () => {
|
||||
it("composes bindings, re-exports, dynamic imports, and JSON modules", async () => {
|
||||
const root = await moduleFixture();
|
||||
const first = await reconstructJavaScriptFixture(root);
|
||||
@@ -288,6 +288,122 @@ describe("CommonJS and ESM module relationships", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Compiler-dependent TypeScript resolution", () => {
|
||||
it("retains only compiler-independent targets for .ts static imports", async () => {
|
||||
const root = await createTestTempDirectory("rea-ts-conditional-loader-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": '{"type":"commonjs"}',
|
||||
"main.ts": `import { value as different } from "different";
|
||||
import { value as same } from "same";
|
||||
void different; void same;`,
|
||||
"node_modules/different/package.json": JSON.stringify({
|
||||
exports: {
|
||||
".": {
|
||||
import: "./import.mjs",
|
||||
require: "./require.cjs",
|
||||
},
|
||||
},
|
||||
}),
|
||||
"node_modules/different/import.mjs": "export const value = 'import';",
|
||||
"node_modules/different/require.cjs": "exports.value = 'require';",
|
||||
"node_modules/same/package.json": JSON.stringify({
|
||||
exports: { ".": { import: "./shared.js", require: "./shared.js" } },
|
||||
}),
|
||||
"node_modules/same/shared.js": "export const value = 'shared';",
|
||||
});
|
||||
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const different = findRelationshipEdge(graph, {
|
||||
kind: "import",
|
||||
specifier: "different",
|
||||
localName: "different",
|
||||
});
|
||||
const same = findRelationshipEdge(graph, {
|
||||
kind: "import",
|
||||
specifier: "same",
|
||||
localName: "same",
|
||||
resolvedPath: "node_modules/same/shared.js",
|
||||
});
|
||||
const staticFinding = (specifier: string) =>
|
||||
graph.edges.find(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.kind === "static-import" &&
|
||||
properties.specifier === specifier,
|
||||
);
|
||||
|
||||
expect(
|
||||
findSourceModule(graph, "main.ts")?.observations[0]?.properties,
|
||||
).toMatchObject({ module_format: "unknown" });
|
||||
expect(different).toMatchObject({
|
||||
properties: {
|
||||
resolution_mode: "compiler-dependent",
|
||||
resolution_status: "unavailable",
|
||||
resolved_path: null,
|
||||
conditional_resolutions: [
|
||||
{
|
||||
mode: "import",
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "node_modules/different/import.mjs",
|
||||
},
|
||||
{
|
||||
mode: "require",
|
||||
resolution_status: "resolved",
|
||||
resolved_path: "node_modules/different/require.cjs",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(same).toMatchObject({
|
||||
properties: {
|
||||
resolution_mode: "compiler-dependent",
|
||||
resolved_path: "node_modules/same/shared.js",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
"compiler-dependent without retained compiler options",
|
||||
),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(staticFinding("different")).toMatchObject({
|
||||
properties: {
|
||||
resolution_mode: "compiler-dependent",
|
||||
resolution_status: "unavailable",
|
||||
conditional_resolutions: [
|
||||
{
|
||||
mode: "import",
|
||||
resolved_path: "node_modules/different/import.mjs",
|
||||
},
|
||||
{
|
||||
mode: "require",
|
||||
resolved_path: "node_modules/different/require.cjs",
|
||||
},
|
||||
],
|
||||
},
|
||||
evidence: {
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
"compiler-dependent without retained compiler options",
|
||||
),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(staticFinding("same")).toMatchObject({
|
||||
properties: { resolved_path: "node_modules/same/shared.js" },
|
||||
evidence: {
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
"compiler-dependent without retained compiler options",
|
||||
),
|
||||
]),
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("does not assign one module origin to an export with colliding path encodings", async () => {
|
||||
const root = await createTestTempDirectory("rea-ambiguous-module-origin-");
|
||||
await writeFixtureFiles(root, {
|
||||
|
||||
@@ -31,9 +31,12 @@ it("reads exact binary and empty bytes and rejects symlink/size/cancellation bou
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(readStableArtifact(real, 3, controller.signal)).rejects.toBe(
|
||||
controller.signal.reason,
|
||||
);
|
||||
await expect(
|
||||
readStableArtifact(real, 3, controller.signal),
|
||||
).rejects.toMatchObject({
|
||||
reason: "cancelled",
|
||||
cause: controller.signal.reason,
|
||||
});
|
||||
});
|
||||
|
||||
const checkChange = async (
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
const injected = vi.hoisted(() => ({
|
||||
sourcePath: undefined as string | undefined,
|
||||
abortController: undefined as AbortController | undefined,
|
||||
failClose: false,
|
||||
closeAttempts: 0,
|
||||
}));
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...actual,
|
||||
open: async (...args: Parameters<typeof actual.open>) => {
|
||||
const handle = await actual.open(...args);
|
||||
if (args[0] !== injected.sourcePath) return handle;
|
||||
const createReadStream = handle.createReadStream.bind(handle);
|
||||
handle.createReadStream = (options) => {
|
||||
injected.abortController?.abort();
|
||||
return createReadStream(options);
|
||||
};
|
||||
const close = handle.close.bind(handle);
|
||||
handle.close = async () => {
|
||||
injected.closeAttempts += 1;
|
||||
if (injected.failClose) throw new Error("fixture close refusal");
|
||||
await close();
|
||||
};
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { WebModuleTraceService } from "../../../src/application/WebModuleTraceService.js";
|
||||
import { LocalWebModuleArtifacts } from "../../../src/browser/modules/WebModuleArtifacts.js";
|
||||
import { webModuleArtifactsFixture } from "../../fixtures/webModuleTrace.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("retains cancelled source read ownership until service close retries it", async () => {
|
||||
const root = await createTestTempDirectory("rea-web-artifact-read-owner-");
|
||||
onTestFinished(async () => {
|
||||
injected.sourcePath = undefined;
|
||||
injected.abortController = undefined;
|
||||
injected.failClose = false;
|
||||
injected.closeAttempts = 0;
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
const source = 'import "./dep.js";';
|
||||
const fixture = webModuleArtifactsFixture(source);
|
||||
const manifestPath = join(root, "manifest.json");
|
||||
const sourcePath = join(root, "files", "modules", "main.js");
|
||||
await mkdir(join(root, "files", "modules"), { recursive: true });
|
||||
await writeFile(sourcePath, source);
|
||||
await writeFile(manifestPath, JSON.stringify(fixture.manifest));
|
||||
|
||||
injected.sourcePath = sourcePath;
|
||||
injected.failClose = true;
|
||||
const controller = new AbortController();
|
||||
injected.abortController = controller;
|
||||
const resolver = {
|
||||
resolve: vi.fn(),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
const service = new WebModuleTraceService(
|
||||
new LocalWebModuleArtifacts(),
|
||||
resolver,
|
||||
);
|
||||
const input = { manifest_path: manifestPath, script_index: 0 };
|
||||
|
||||
const cancelled = await service.trace(input, { signal: controller.signal });
|
||||
expect(cancelled.ok).toBe(false);
|
||||
if (cancelled.ok) throw new Error("Expected cancelled source read");
|
||||
expect(cancelled.error.cleanupIncomplete).toBe(true);
|
||||
expect(cancelled.error.cleanupResources).toContain(sourcePath);
|
||||
expect(resolver.resolve).not.toHaveBeenCalled();
|
||||
|
||||
injected.abortController = undefined;
|
||||
const blocked = await service.trace(input);
|
||||
expect(blocked.ok).toBe(false);
|
||||
if (blocked.ok) throw new Error("Expected retained cleanup to block load");
|
||||
expect(blocked.error.cleanupIncomplete).toBe(true);
|
||||
expect(injected.closeAttempts).toBe(2);
|
||||
|
||||
await expect(service.close()).rejects.toThrow(
|
||||
"Web module trace cleanup failed",
|
||||
);
|
||||
expect(resolver.close).toHaveBeenCalledTimes(1);
|
||||
expect(injected.closeAttempts).toBe(3);
|
||||
|
||||
injected.failClose = false;
|
||||
const attemptsBeforeRetry = injected.closeAttempts;
|
||||
await service.close();
|
||||
expect(injected.closeAttempts).toBeGreaterThan(attemptsBeforeRetry);
|
||||
expect(resolver.close).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { access, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const publicationCancellation = vi.hoisted(() => ({
|
||||
controller: undefined as AbortController | undefined,
|
||||
directorySyncs: 0,
|
||||
}));
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const filesystem = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...filesystem,
|
||||
open: async (...args: Parameters<typeof filesystem.open>) => {
|
||||
const handle = await filesystem.open(...args);
|
||||
if (publicationCancellation.controller !== undefined) {
|
||||
const stats = await handle.stat();
|
||||
if (stats.isDirectory()) {
|
||||
const sync = handle.sync.bind(handle);
|
||||
handle.sync = async () => {
|
||||
await sync();
|
||||
publicationCancellation.directorySyncs += 1;
|
||||
if (publicationCancellation.directorySyncs === 2)
|
||||
publicationCancellation.controller?.abort();
|
||||
};
|
||||
}
|
||||
}
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock(
|
||||
"../../../src/javascript/recovery/WakaruCommand.js",
|
||||
async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<
|
||||
typeof import("../../../src/javascript/recovery/WakaruCommand.js")
|
||||
>();
|
||||
return {
|
||||
...actual,
|
||||
resolveWakaruCommand: async () => ({
|
||||
command: "/unused/wakaru",
|
||||
limiter: "/unused/prlimit",
|
||||
sha256: "a".repeat(64),
|
||||
bytes: 1,
|
||||
}),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
vi.mock(
|
||||
"../../../src/javascript/recovery/WakaruExecution.js",
|
||||
async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<
|
||||
typeof import("../../../src/javascript/recovery/WakaruExecution.js")
|
||||
>();
|
||||
const { createAnalysisExecution } =
|
||||
await import("../../../src/application/AnalysisProvider.js");
|
||||
return {
|
||||
...actual,
|
||||
prepareWakaruExecution: async (
|
||||
context: Parameters<typeof actual.prepareWakaruExecution>[0],
|
||||
) => {
|
||||
const source = context.sources[0];
|
||||
if (source === undefined) throw new Error("Missing recovery source");
|
||||
const bytes = Buffer.from("module.exports = 42;");
|
||||
await context.tree.write("module.js", Readable.from([bytes]), {
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.byteLength,
|
||||
});
|
||||
return createAnalysisExecution(
|
||||
{ status: "complete" },
|
||||
{ id: "wakaru", name: "Wakaru", version: "1.14.0" },
|
||||
{
|
||||
subject: {
|
||||
path: source.path,
|
||||
sha256: source.sha256,
|
||||
format: "javascript",
|
||||
},
|
||||
},
|
||||
);
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import { WakaruProvider } from "../../../src/javascript/recovery/WakaruProvider.js";
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"keeps mid-commit output-tree cancellation typed through the provider",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-wakaru-cancel-");
|
||||
const sourcePath = join(root, "source.js");
|
||||
const output = join(root, "output");
|
||||
await writeFile(sourcePath, "module.exports = 42;");
|
||||
const controller = new AbortController();
|
||||
publicationCancellation.controller = controller;
|
||||
publicationCancellation.directorySyncs = 0;
|
||||
const provider = new WakaruProvider({});
|
||||
try {
|
||||
const result = await provider.recover(
|
||||
{
|
||||
path: sourcePath,
|
||||
output_directory: output,
|
||||
extraction_mode: "structural",
|
||||
rewrite_level: "standard",
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected publication cancellation");
|
||||
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
expect(projectAnalysisError(result.error).code).toBe("cancelled");
|
||||
expect(publicationCancellation.directorySyncs).toBe(2);
|
||||
await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
publicationCancellation.controller = undefined;
|
||||
publicationCancellation.directorySyncs = 0;
|
||||
await provider.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -9,76 +9,16 @@ import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
|
||||
import { compareProcessEvidenceFiles } from "../../../src/application/process/ProcessCli.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidenceProvider.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
|
||||
import { processTraceCaptureFixture } from "../../../src/domain/process/processCapture.fixture.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import type { ProcessTraceSpecification } from "../../../src/domain/process/processTraceSpecification.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
const temporaryRoots: string[] = [];
|
||||
const beforeCheckpoint = {
|
||||
name: "before",
|
||||
at_ms: 0,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
};
|
||||
const afterCheckpoint = {
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
};
|
||||
const capture = {
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
event_journal: [
|
||||
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 2, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
|
||||
],
|
||||
} as const;
|
||||
const traceSpecification: ProcessTraceSpecification = {
|
||||
events: [
|
||||
{
|
||||
id: "before",
|
||||
source: "filesystem",
|
||||
exact: beforeCheckpoint,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "exit",
|
||||
source: "lifecycle",
|
||||
exact: { event: "exit", ...capture.exit },
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "settlement",
|
||||
source: "lifecycle",
|
||||
exact: { event: "settlement", ...capture.settlement },
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "after",
|
||||
source: "filesystem",
|
||||
exact: afterCheckpoint,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [
|
||||
{
|
||||
id: "normal",
|
||||
trace: ["before", "exit", "settlement", "after"],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const { capture, traceSpecification } = processTraceCaptureFixture();
|
||||
|
||||
const captureEvidence = (side: "left" | "right") =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
|
||||
@@ -34,6 +34,9 @@ import {
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
import { z } from "zod";
|
||||
import { createDeferred } from "../../fixtures/binarySession.js";
|
||||
import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js";
|
||||
import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCaptureService.js";
|
||||
import { AnalysisUnsupportedTargetError } from "../../../src/domain/analysisErrorCore.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
@@ -334,6 +337,68 @@ it("awaits SQLite cleanup and retries its retained owner after failed server shu
|
||||
expect(attempts).toBe(2);
|
||||
});
|
||||
|
||||
it("closes the bound Go and web-capture services and retries failed shutdown", async () => {
|
||||
let goCalls = 0;
|
||||
let goCloseAttempts = 0;
|
||||
let captureCloseAttempts = 0;
|
||||
let cleanupAllowed = false;
|
||||
const goBinary = new GoBinaryService({
|
||||
identity: { id: "go-fixture", name: "Go fixture", version: "1" },
|
||||
inspect: async ({ path }) => {
|
||||
goCalls += 1;
|
||||
return err(
|
||||
new AnalysisUnsupportedTargetError(
|
||||
"inspect_go_binary",
|
||||
path,
|
||||
"fixture rejection",
|
||||
),
|
||||
);
|
||||
},
|
||||
close: async () => {
|
||||
goCloseAttempts += 1;
|
||||
if (!cleanupAllowed) throw new Error("Go cleanup refused");
|
||||
},
|
||||
});
|
||||
const webNetworkCapture = new WebNetworkCaptureService({
|
||||
inspect: async () => {
|
||||
throw new Error("No capture inspection requested");
|
||||
},
|
||||
close: async () => {
|
||||
captureCloseAttempts += 1;
|
||||
if (!cleanupAllowed) throw new Error("Capture cleanup refused");
|
||||
},
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "fixed", analysis: { execute: async () => ok(null) } },
|
||||
{ goBinary, webNetworkCapture },
|
||||
);
|
||||
const client = new Client({ name: "bound-service-lifecycle", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "inspect_go_binary",
|
||||
arguments: { path: "/tmp/go-fixture" },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(goCalls).toBe(1);
|
||||
|
||||
await expect(server.close()).rejects.toBeInstanceOf(AggregateError);
|
||||
expect(goCloseAttempts).toBe(1);
|
||||
expect(captureCloseAttempts).toBe(1);
|
||||
|
||||
cleanupAllowed = true;
|
||||
await server.close();
|
||||
expect(goCloseAttempts).toBe(2);
|
||||
expect(captureCloseAttempts).toBe(2);
|
||||
} finally {
|
||||
cleanupAllowed = true;
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { access } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
@@ -40,6 +41,7 @@ it.each(["pre-aborted", "aborted-during-probe"] as const)(
|
||||
REA_PWNDBG_VENV_PATH: join(workspace.root, "missing-venv"),
|
||||
},
|
||||
rootPath: workspace.root,
|
||||
resources: new ArtifactResourceScope(),
|
||||
diagnostics,
|
||||
options: { signal: controller.signal },
|
||||
probePath,
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
const closeState = vi.hoisted(() => ({
|
||||
fail: false,
|
||||
failOnce: false,
|
||||
opened: 0,
|
||||
closes: 0,
|
||||
}));
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const fs = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...fs,
|
||||
open: async (...args: Parameters<typeof fs.open>) => {
|
||||
const handle = await fs.open(...args);
|
||||
closeState.opened++;
|
||||
const close = handle.close.bind(handle);
|
||||
handle.close = async () => {
|
||||
closeState.closes++;
|
||||
if (closeState.fail || closeState.failOnce) {
|
||||
closeState.failOnce = false;
|
||||
throw new Error("injected stable artifact close failure");
|
||||
}
|
||||
return close();
|
||||
};
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { PwntoolsDecoder } from "../../../src/native/pwntools/PwntoolsDecoder.js";
|
||||
import { PWNTOOLS_PROVIDER_IDENTITY } from "../../../src/native/pwntools/PwntoolsRelease.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
|
||||
const makeDecoder = () =>
|
||||
new PwntoolsDecoder(
|
||||
{
|
||||
identity: PWNTOOLS_PROVIDER_IDENTITY,
|
||||
operation: "test_pwntools_artifact_read",
|
||||
bridge: new URL("file:///unused-bridge.py"),
|
||||
payloadSchema: z.string(),
|
||||
project: () => {
|
||||
throw new Error("input read should fail before decoder launch");
|
||||
},
|
||||
},
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
undefined,
|
||||
async () => {
|
||||
throw new Error("runtime should not be created for failed input read");
|
||||
},
|
||||
);
|
||||
|
||||
const emulateSupportedHost = async (
|
||||
run: () => Promise<void>,
|
||||
): Promise<void> => {
|
||||
const platform = Object.getOwnPropertyDescriptor(process, "platform");
|
||||
const arch = Object.getOwnPropertyDescriptor(process, "arch");
|
||||
Object.defineProperty(process, "platform", { ...platform, value: "linux" });
|
||||
Object.defineProperty(process, "arch", { ...arch, value: "x64" });
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
if (platform !== undefined)
|
||||
Object.defineProperty(process, "platform", platform);
|
||||
if (arch !== undefined) Object.defineProperty(process, "arch", arch);
|
||||
}
|
||||
};
|
||||
|
||||
it("reports the read failure without stale incomplete-cleanup state when close retry succeeds", async () =>
|
||||
emulateSupportedHost(async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-pwntools-close-retry-"));
|
||||
const path = join(root, "selected.bin");
|
||||
await writeFile(path, "selected evidence");
|
||||
closeState.fail = false;
|
||||
closeState.failOnce = true;
|
||||
closeState.opened = 0;
|
||||
closeState.closes = 0;
|
||||
const decoder = makeDecoder();
|
||||
try {
|
||||
const result = await decoder.inspect({ path });
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Injected close failure was not returned");
|
||||
expect(result.error.cleanupIncomplete).toBe(false);
|
||||
expect(projectAnalysisError(result.error).code).not.toBe(
|
||||
"cleanup_incomplete",
|
||||
);
|
||||
expect(result.error.cause).toMatchObject({
|
||||
cleanup: {
|
||||
resources: [path],
|
||||
reason: expect.stringContaining(
|
||||
"injected stable artifact close failure",
|
||||
),
|
||||
},
|
||||
});
|
||||
expect(closeState.closes).toBeGreaterThanOrEqual(2);
|
||||
} finally {
|
||||
closeState.fail = false;
|
||||
closeState.failOnce = false;
|
||||
await decoder.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}));
|
||||
|
||||
it("retains a persistent failed input descriptor and refuses the next acquisition", async () =>
|
||||
emulateSupportedHost(async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-pwntools-held-close-"));
|
||||
const path = join(root, "selected.bin");
|
||||
await writeFile(path, "selected evidence");
|
||||
closeState.fail = true;
|
||||
closeState.failOnce = false;
|
||||
closeState.opened = 0;
|
||||
closeState.closes = 0;
|
||||
const decoder = makeDecoder();
|
||||
try {
|
||||
const first = await decoder.inspect({ path });
|
||||
expect(first.ok).toBe(false);
|
||||
if (first.ok)
|
||||
throw new Error("Persistent close failure was not returned");
|
||||
expect(projectAnalysisError(first.error).code).toBe("cleanup_incomplete");
|
||||
const openedAfterFailure = closeState.opened;
|
||||
|
||||
const retry = await decoder.inspect({ path });
|
||||
expect(retry.ok).toBe(false);
|
||||
if (retry.ok) throw new Error("Retained descriptor was not retried");
|
||||
expect(projectAnalysisError(retry.error).code).toBe("cleanup_incomplete");
|
||||
expect(closeState.opened).toBe(openedAfterFailure);
|
||||
|
||||
await expect(decoder.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
closeState.fail = false;
|
||||
await decoder.close();
|
||||
} finally {
|
||||
closeState.fail = false;
|
||||
closeState.failOnce = false;
|
||||
try {
|
||||
await decoder.close();
|
||||
} catch {
|
||||
// The test already asserts persistent cleanup failure before releasing it.
|
||||
}
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}));
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
const cleanupState = vi.hoisted(() => ({
|
||||
failFirstClose: false,
|
||||
abortController: undefined as AbortController | undefined,
|
||||
firstHandle: undefined as FileHandle | undefined,
|
||||
firstHandleCloseAttempts: 0,
|
||||
}));
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const fs = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...fs,
|
||||
open: async (...args: Parameters<typeof fs.open>) => {
|
||||
const handle = await fs.open(...args);
|
||||
const close = handle.close.bind(handle);
|
||||
if (cleanupState.abortController !== undefined)
|
||||
setImmediate(() => {
|
||||
cleanupState.abortController?.abort();
|
||||
cleanupState.abortController = undefined;
|
||||
});
|
||||
handle.close = async () => {
|
||||
if (handle === cleanupState.firstHandle)
|
||||
cleanupState.firstHandleCloseAttempts += 1;
|
||||
else if (cleanupState.firstHandle === undefined)
|
||||
cleanupState.firstHandle = handle;
|
||||
if (
|
||||
cleanupState.failFirstClose &&
|
||||
handle === cleanupState.firstHandle
|
||||
) {
|
||||
cleanupState.failFirstClose = false;
|
||||
throw new Error("injected descriptor close failure");
|
||||
}
|
||||
return close();
|
||||
};
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import { GoBinaryProvider } from "../../../src/go/GoBinaryProvider.js";
|
||||
import { PeResourcesProvider } from "../../../src/native/pe/PeResourcesProvider.js";
|
||||
import { createGoBinaryFixture } from "../../fixtures/go/image.js";
|
||||
import { peResourceFixture } from "../../../src/native/pe/PeResources.fixture.js";
|
||||
|
||||
it.each(["go", "pe"] as const)(
|
||||
"%s provider retains a failed descriptor close and retries that owner before the next read",
|
||||
async (kind) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-read-cleanup-"));
|
||||
const path = join(root, kind === "go" ? "program.elf" : "program.exe");
|
||||
const bytes =
|
||||
kind === "go" ? createGoBinaryFixture().bytes : peResourceFixture().bytes;
|
||||
await writeFile(path, bytes);
|
||||
const provider =
|
||||
kind === "go" ? new GoBinaryProvider() : new PeResourcesProvider();
|
||||
cleanupState.failFirstClose = true;
|
||||
const controller = new AbortController();
|
||||
cleanupState.abortController = controller;
|
||||
cleanupState.firstHandle = undefined;
|
||||
cleanupState.firstHandleCloseAttempts = 0;
|
||||
try {
|
||||
const input = {
|
||||
path,
|
||||
max_file_bytes: 8 * 1024 * 1024,
|
||||
max_entries: 4096,
|
||||
};
|
||||
const first = await provider.inspect(input, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(first.ok).toBe(false);
|
||||
if (first.ok) throw new Error("Injected close failure was not returned");
|
||||
expect(projectAnalysisError(first.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { diagnostics: { primary_error: { code: "cancelled" } } },
|
||||
});
|
||||
expect(first.error.cause).toBeInstanceOf(AggregateError);
|
||||
if (!(first.error.cause instanceof AggregateError))
|
||||
throw first.error.cause;
|
||||
expect(first.error.cause.errors[1]).toMatchObject({
|
||||
cleanupResources: [path],
|
||||
});
|
||||
|
||||
const retry = await provider.inspect(input);
|
||||
expect(retry.ok).toBe(true);
|
||||
expect(cleanupState.firstHandleCloseAttempts).toBe(2);
|
||||
} finally {
|
||||
await provider.close();
|
||||
cleanupState.failFirstClose = false;
|
||||
cleanupState.abortController = undefined;
|
||||
cleanupState.firstHandle = undefined;
|
||||
cleanupState.firstHandleCloseAttempts = 0;
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user