fix(evidence): cancel exports before atomic publication
This commit is contained in:
@@ -9,6 +9,7 @@ import {
|
||||
EvidenceIntegrityError,
|
||||
} from "../domain/evidenceErrors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import { parseProcessCapture } from "../domain/process/processCapture.js";
|
||||
import {
|
||||
bufferedJsonParts,
|
||||
@@ -17,7 +18,10 @@ import {
|
||||
import { readJsonFile, writeTextParts } from "./JsonFiles.js";
|
||||
|
||||
type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
type EvidenceWriteFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
type EvidenceWriteFailure =
|
||||
| EvidenceFileError
|
||||
| EvidenceIntegrityError
|
||||
| AnalysisCancelledError;
|
||||
|
||||
/** Read and validate an evidence bundle at the caller-supplied path. */
|
||||
export const readEvidenceBundle = async (
|
||||
@@ -57,12 +61,15 @@ export const writeEvidenceBundle = async (
|
||||
bundle: EvidenceBundle,
|
||||
path: string,
|
||||
overwrite: boolean,
|
||||
signal?: AbortSignal,
|
||||
): Promise<
|
||||
Result<
|
||||
{ readonly path: string; readonly bytes: number },
|
||||
EvidenceWriteFailure
|
||||
>
|
||||
> => {
|
||||
if (signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError("export_evidence_bundle"));
|
||||
let checked: EvidenceBundle;
|
||||
try {
|
||||
checked = parseEvidenceBundle(bundle);
|
||||
@@ -77,5 +84,8 @@ export const writeEvidenceBundle = async (
|
||||
bufferedJsonParts(canonicalJsonParts(checked)),
|
||||
path,
|
||||
overwrite,
|
||||
signal === undefined
|
||||
? undefined
|
||||
: { signal, operation: "export_evidence_bundle" },
|
||||
);
|
||||
};
|
||||
|
||||
@@ -7,12 +7,23 @@ import {
|
||||
realpath,
|
||||
rename,
|
||||
rm,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { basename, dirname, resolve } from "node:path";
|
||||
|
||||
import { EvidenceFileError } from "../domain/evidenceErrors.js";
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Request control and its owning operation for an interruptible atomic write. */
|
||||
export interface TextWriteCancellation {
|
||||
readonly signal: AbortSignal;
|
||||
readonly operation: string;
|
||||
}
|
||||
|
||||
type TextWriteResult<Failure = EvidenceFileError | AnalysisCancelledError> =
|
||||
Result<{ readonly path: string; readonly bytes: number }, Failure>;
|
||||
|
||||
/** Read JSON data from a regular file at the caller-supplied path. */
|
||||
export const readJsonFile = async (
|
||||
path: string,
|
||||
@@ -57,20 +68,31 @@ export const writeTextFile = async (
|
||||
encoded: string,
|
||||
path: string,
|
||||
overwrite: boolean,
|
||||
): Promise<
|
||||
Result<{ readonly path: string; readonly bytes: number }, EvidenceFileError>
|
||||
> => writeTextParts([encoded], path, overwrite);
|
||||
): Promise<TextWriteResult<EvidenceFileError>> =>
|
||||
writeTextParts([encoded], path, overwrite);
|
||||
|
||||
/** Publish complete streamed text atomically, keeping only one encoded part in memory. */
|
||||
export const writeTextParts = async (
|
||||
/** Publish streamed text atomically unless cancellation wins before publication. */
|
||||
export function writeTextParts(
|
||||
parts: Iterable<string>,
|
||||
path: string,
|
||||
overwrite: boolean,
|
||||
): Promise<
|
||||
Result<{ readonly path: string; readonly bytes: number }, EvidenceFileError>
|
||||
> => {
|
||||
): Promise<TextWriteResult<EvidenceFileError>>;
|
||||
/** Pass request control to stop streamed generation before atomic publication. */
|
||||
export function writeTextParts(
|
||||
parts: Iterable<string>,
|
||||
path: string,
|
||||
overwrite: boolean,
|
||||
cancellation: TextWriteCancellation | undefined,
|
||||
): Promise<TextWriteResult>;
|
||||
export async function writeTextParts(
|
||||
parts: Iterable<string>,
|
||||
path: string,
|
||||
overwrite: boolean,
|
||||
cancellation?: TextWriteCancellation,
|
||||
): Promise<TextWriteResult> {
|
||||
const requestedPath = resolve(path);
|
||||
try {
|
||||
assertWriteActive(cancellation);
|
||||
const canonicalParent = await realpath(dirname(requestedPath));
|
||||
const destination = resolve(canonicalParent, basename(requestedPath));
|
||||
const existing = await lstat(destination).catch((cause: unknown) => {
|
||||
@@ -87,9 +109,21 @@ export const writeTextParts = async (
|
||||
new EvidenceFileError("write", "not-file", { path: requestedPath }),
|
||||
);
|
||||
}
|
||||
const bytes = await publishFile(destination, parts, overwrite);
|
||||
assertWriteActive(cancellation);
|
||||
const bytes = await publishFile(
|
||||
destination,
|
||||
parts,
|
||||
overwrite,
|
||||
cancellation,
|
||||
);
|
||||
return ok({ path: requestedPath, bytes });
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cancellation?.signal.aborted === true &&
|
||||
cause instanceof AnalysisCancelledError &&
|
||||
cause.operation === cancellation.operation
|
||||
)
|
||||
return err(cause);
|
||||
if (!overwrite && fileErrorCode(cause) === "EEXIST")
|
||||
return err(
|
||||
new EvidenceFileError("write", "exists", {
|
||||
@@ -104,7 +138,7 @@ export const writeTextParts = async (
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** A missing path or parent is a selection error, not a permission failure. */
|
||||
const missingOrIo = (cause: unknown): "missing" | "io" => {
|
||||
@@ -116,6 +150,7 @@ const publishFile = async (
|
||||
destination: string,
|
||||
parts: Iterable<string>,
|
||||
overwrite: boolean,
|
||||
cancellation?: TextWriteCancellation,
|
||||
): Promise<number> => {
|
||||
const stagingDirectory = await mkdtemp(
|
||||
resolve(dirname(destination), ".rea-write-"),
|
||||
@@ -125,14 +160,14 @@ const publishFile = async (
|
||||
const file = await open(staged, "wx", 0o600);
|
||||
let bytes = 0;
|
||||
try {
|
||||
for (const part of parts) {
|
||||
await file.writeFile(part, { encoding: "utf8" });
|
||||
bytes += Buffer.byteLength(part, "utf8");
|
||||
}
|
||||
bytes = await writeStagedParts(file, parts, cancellation);
|
||||
assertWriteActive(cancellation);
|
||||
await file.sync();
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
// Once submitted, the atomic publication can win a later cancellation race.
|
||||
assertWriteActive(cancellation);
|
||||
if (overwrite) await rename(staged, destination);
|
||||
// A hard link publishes complete bytes atomically and cannot replace an existing name.
|
||||
else await link(staged, destination);
|
||||
@@ -142,6 +177,35 @@ const publishFile = async (
|
||||
}
|
||||
};
|
||||
|
||||
const writeStagedParts = async (
|
||||
file: FileHandle,
|
||||
parts: Iterable<string>,
|
||||
cancellation?: TextWriteCancellation,
|
||||
): Promise<number> => {
|
||||
assertWriteActive(cancellation);
|
||||
const iterator = parts[Symbol.iterator]();
|
||||
let exhausted = false;
|
||||
let bytes = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
assertWriteActive(cancellation);
|
||||
const part = iterator.next();
|
||||
if (part.done) exhausted = true;
|
||||
assertWriteActive(cancellation);
|
||||
if (part.done) return bytes;
|
||||
await file.writeFile(part.value, { encoding: "utf8" });
|
||||
bytes += Buffer.byteLength(part.value, "utf8");
|
||||
}
|
||||
} finally {
|
||||
if (!exhausted) iterator.return?.();
|
||||
}
|
||||
};
|
||||
|
||||
const assertWriteActive = (cancellation?: TextWriteCancellation): void => {
|
||||
if (cancellation?.signal.aborted === true)
|
||||
throw new AnalysisCancelledError(cancellation.operation);
|
||||
};
|
||||
|
||||
const fileErrorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
|
||||
Reference in New Issue
Block a user