Compare commits

...
6 changed files with 145 additions and 29 deletions
+2 -2
View File
@@ -175,7 +175,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
];
phase = "workspace";
root = await this.createRuntime();
this.#resources.retain(root, undefined, operation);
this.#resources.retain(root, undefined);
const snapshotPath = join(root.path, "capture");
const configurationPath = join(root.path, "configuration");
await mkdir(configurationPath, { mode: 0o700 });
@@ -406,7 +406,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
cause instanceof OwnedCommandFailure &&
cause.cleanupOwner !== undefined
)
this.#resources.retain(root, cause.cleanupOwner, operation);
this.#resources.retain(root, cause.cleanupOwner);
result = err(
this.#failure(
cause,
+29 -11
View File
@@ -33,7 +33,10 @@ export type ArtifactAnalysisRuntime = Pick<
/** Own admission, artifact descriptors, producer cleanup and private workspaces together. */
export class ArtifactAnalysisResources {
readonly #artifacts = new ArtifactResourceScope();
readonly #artifacts: {
readonly scope: ArtifactResourceScope;
operation: string;
};
readonly #pending = new Map<
ArtifactAnalysisRuntime,
{
@@ -54,7 +57,9 @@ export class ArtifactAnalysisResources {
readonly message: string;
readonly details: Readonly<Record<string, JsonValue>>;
},
) {}
) {
this.#artifacts = { scope: new ArtifactResourceScope(), operation };
}
run<T>(
work: () => Promise<Result<T, AnalysisError>>,
@@ -76,8 +81,15 @@ export class ArtifactAnalysisResources {
);
this.#busy = true;
const running = this.#tail
.then(() => this.#artifacts.run(work))
.catch((cause: unknown) => err(this.#artifactFailure(cause, operation)))
.then(() =>
this.#artifacts.scope.run(() => {
// Failed descriptor cleanup still belongs to the preceding request until
// this scope has drained it and admits acquisition for the new request.
this.#artifacts.operation = operation;
return work();
}),
)
.catch((cause: unknown) => err(this.#artifactFailure(cause)))
.finally(() => {
this.#busy = false;
});
@@ -94,20 +106,23 @@ export class ArtifactAnalysisResources {
maximumBytes,
signal,
undefined,
this.#artifacts,
this.#artifacts.scope,
);
}
readLimits(limits: LinuxResourceLimits): Promise<LinuxResourceLimits> {
return this.readKernelLimits(limits, this.#artifacts);
return this.readKernelLimits(limits, this.#artifacts.scope);
}
retain(
root: ArtifactAnalysisRuntime,
owner?: ProviderProcessSupervisor,
operation = this.operation,
): void {
this.#pending.set(root, { owner, operation });
this.#pending.set(root, {
owner,
operation:
this.#pending.get(root)?.operation ?? this.#artifacts.operation,
});
}
get pendingPaths(): readonly string[] {
@@ -251,7 +266,7 @@ export class ArtifactAnalysisResources {
async #closeResources(): Promise<void> {
let descriptorFailure: AnalysisError | undefined;
try {
await this.#artifacts.close();
await this.#artifacts.scope.close();
} catch (cause: unknown) {
descriptorFailure = this.#artifactFailure(cause);
}
@@ -262,14 +277,17 @@ export class ArtifactAnalysisResources {
throw analysisErrorWithCleanupFailure(
descriptorFailure,
cause,
this.operation,
this.#artifacts.operation,
);
throw cause;
}
if (descriptorFailure !== undefined) throw descriptorFailure;
}
#artifactFailure(cause: unknown, operation = this.operation): AnalysisError {
#artifactFailure(
cause: unknown,
operation = this.#artifacts.operation,
): AnalysisError {
if (cause instanceof AnalysisError) return cause;
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
return this.cleanupFailure(cause.cleanup, cause, undefined, operation);
+2 -2
View File
@@ -173,7 +173,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
];
phase = "workspace";
root = await this.createRuntime();
this.#resources.retain(root, undefined, operation);
this.#resources.retain(root, undefined);
const snapshotPath = join(root.path, "recording");
const execute = async (args: readonly string[]) => {
const output = await runOwnedCommand(
@@ -371,7 +371,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
cause instanceof OwnedCommandFailure &&
cause.cleanupOwner !== undefined
)
this.#resources.retain(root, cause.cleanupOwner, operation);
this.#resources.retain(root, cause.cleanupOwner);
result = err(
this.#failure(
cause,
@@ -35,7 +35,15 @@ vi.mock("node:fs/promises", async (importOriginal) => {
it
.runIf(process.platform === "linux")
.each(["capture", "tool", "limiter", "kernel"])(
.each([
"capture",
"tool",
"limiter",
"kernel",
"field-tool",
"field-limiter",
"field-kernel",
])(
"retains failed %s descriptors and retries them before further acquisition and shutdown",
async (member) => {
const directory = await createTestTempDirectory("rea-capture-descriptor-");
@@ -67,12 +75,17 @@ it
},
() => PrivateRuntimeRoot.create({ parent: directory }),
);
const discovery = member.startsWith("field-");
const resource = discovery ? member.slice(6) : member;
const operation = discovery
? "inspect_packet_fields"
: "inspect_packet_capture";
cleanup.path =
member === "capture"
resource === "capture"
? path
: member === "tool"
: resource === "tool"
? command
: member === "limiter"
: resource === "limiter"
? limiter
: "/proc/self/limits";
cleanup.denied = true;
@@ -84,24 +97,55 @@ it
cleanup.path = "";
});
const service = new PacketCaptureService(provider);
const first = await service.inspect({ path, fields: ["frame.number"] });
const first = discovery
? await service.inspectFields({ query: "usb" })
: await service.inspect({ path, fields: ["frame.number"] });
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
error: {
cleanupIncomplete: true,
cleanupResources: [cleanup.path],
operation,
},
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
const launchCount = launches;
expect(
await service.inspect({ path, fields: ["frame.number"] }),
).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, operation },
});
expect(cleanup.handles).toHaveLength(1);
expect(launches).toBe(launchCount);
let closingOperation = operation;
if (discovery) {
cleanup.denied = false;
const recovered = await service.inspect({
path,
fields: ["frame.number"],
});
expect(recovered.ok).toBe(true);
expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true);
expect(launches).toBeGreaterThan(launchCount);
cleanup.denied = true;
expect(
await service.inspect({ path, fields: ["frame.number"] }),
).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, operation: "inspect_packet_capture" },
});
expect(cleanup.handles.at(-1)?.fd).toBeGreaterThanOrEqual(0);
closingOperation = "inspect_packet_capture";
}
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
operation: closingOperation,
});
cleanup.denied = false;
await provider.close();
expect(cleanup.handles[0]?.fd).toBe(-1);
expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true);
},
);
@@ -11,6 +11,9 @@ import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createDeferred } from "../../fixtures/binarySession.js";
import { Cli } from "incur";
import { registerCaptureCommands } from "../../../src/cli/captureCommands.js";
import { silentLogger } from "../../../src/logger.js";
// A command-boundary simulator: real process ownership/filesystem, not real TShark coverage.
const fixture = async (mode = "ok", failCleanup = false) => {
@@ -625,3 +628,34 @@ it("retains completed discovery on late cancellation and cleanup failure", async
await f.service.close();
}
});
it("preserves discovery resource ownership through CLI shutdown retries", async () => {
const f = await fixture("cleanup", true);
const cli = Cli.create("discovery-cleanup", { sync: false });
registerCaptureCommands(cli, silentLogger, {}, f.service);
let stdout = "";
try {
await cli.serve(
["inspect-packet-fields", "--query", "usb", "--format", "json"],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(JSON.parse(stdout)).toMatchObject({
code: "cleanup_incomplete",
details: {
diagnostics: {
cleanup_error: {
details: { operation: "inspect_packet_fields" },
},
},
},
});
} finally {
f.allowCleanup();
await f.service.close();
}
});
@@ -35,7 +35,15 @@ vi.mock("node:fs/promises", async (importOriginal) => {
it
.runIf(process.platform === "linux")
.each(["capture", "tool", "limiter", "kernel"])(
.each([
"capture",
"tool",
"limiter",
"kernel",
"field-tool",
"field-limiter",
"field-kernel",
])(
"retains failed %s descriptors and retries them before further acquisition and shutdown",
async (member) => {
const directory = await createTestTempDirectory("rea-signal-descriptor-");
@@ -67,12 +75,17 @@ it
},
() => PrivateRuntimeRoot.create({ parent: directory }),
);
const discovery = member.startsWith("field-");
const resource = discovery ? member.slice(6) : member;
const operation = discovery
? "inspect_signal_decoders"
: "decode_signal_recording";
cleanup.path =
member === "capture"
resource === "capture"
? path
: member === "tool"
: resource === "tool"
? command
: member === "limiter"
: resource === "limiter"
? limiter
: "/proc/self/limits";
cleanup.denied = true;
@@ -84,22 +97,29 @@ it
cleanup.path = "";
});
const service = new SignalRecordingService(provider);
const first = await service.decode({ path, decoders: "uart" });
const first = discovery
? await service.inspectDecoders({ query: "uart" })
: await service.decode({ path, decoders: "uart" });
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
error: {
cleanupIncomplete: true,
cleanupResources: [cleanup.path],
operation,
},
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
const launchCount = launches;
expect(await service.decode({ path, decoders: "uart" })).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
error: { cleanupIncomplete: true, operation },
});
expect(cleanup.handles).toHaveLength(1);
expect(launches).toBe(launchCount);
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
operation,
});
cleanup.denied = false;
await provider.close();