fix(reference)!: retain source and metadata cleanup owners

Require a caller-owned artifact resource scope for source traversal and Git metadata reads. Preserve cancellation, filesystem reasons, partial entries and bytes, and cleanup observations through import and the CLI. Transfer exact failed file owners at regular-file admission and close boundaries, including multiple failures encountered by Git reference resolution.

Validation: 169 focused tests passed across 26 files; two Windows-only cases skipped. Build, typecheck, lint, formatting, knip, architecture guards, discovery and docs checks passed.

BREAKING CHANGE: Reference source readers and imports require an ArtifactResourceScope. VCS metadata reads return Result, and CLI import failures include observed details and partial evidence.
This commit is contained in:
morluto
2026-10-11 06:10:10 +08:00
parent 215001a1ce
commit 53e7fadbd0
30 changed files with 1450 additions and 222 deletions
+76 -16
View File
@@ -8,8 +8,14 @@ import {
type HistoricalSourceGraphInput,
} from "../domain/referenceSourceGraph.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js";
import { readReferenceSource } from "../reference/ReferenceSourceReader.js";
import type { ReferenceSourceEntryKind } from "../reference/ReferenceSourceReaderTypes.js";
import type {
ReferenceSourceEntryKind,
ReferenceSourceRead,
ReferenceSourceReaderError,
} from "../reference/ReferenceSourceReaderTypes.js";
import { parseReferenceSourceEntries } from "./ReferenceSourceImportEntries.js";
import { readReferenceSourceVcs } from "./ReferenceSourceVcsAdapter.js";
import {
@@ -30,8 +36,12 @@ const failure = (
message,
});
const cancelled = (): ReferenceSourceImportError =>
failure("cancelled", "Reference source import cancelled");
const cancelled = (
partial?: ReferenceSourceRead,
): ReferenceSourceImportError => ({
...failure("cancelled", "Reference source import cancelled"),
...(partial === undefined ? {} : { partial }),
});
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
@@ -170,9 +180,10 @@ const createShouldExclude =
*/
export const importReferenceSource = async (
options: ReferenceSourceImportOptions,
resources: ArtifactResourceScope,
): Promise<Result<HistoricalSourceGraph, ReferenceSourceImportError>> => {
if (isAborted(options.signal)) return err(cancelled());
const prepared = await prepareReferenceSourceImport(options);
const prepared = await prepareReferenceSourceImport(options, resources);
if (!prepared.ok) return prepared;
const { ignored, root, secrets } = prepared.value;
if (isAborted(options.signal)) return err(cancelled());
@@ -180,23 +191,30 @@ export const importReferenceSource = async (
const exclusions: HistoricalSourceGraphInput["exclusions"] = [];
const shouldExclude = createShouldExclude(exclusions, secrets, ignored);
const [readResult, vcs] = await Promise.all([
readReferenceSource(root, {
const [readResult, vcsResult] = await Promise.all([
readReferenceSource(root, resources, {
...(options.signal === undefined ? {} : { signal: options.signal }),
shouldExclude,
}),
readReferenceSourceVcs(root, options.signal),
readReferenceSourceVcs(root, resources, options.signal),
]);
if (!readResult.ok) {
const error = readResult.error;
if (error.code === "cancelled") return err(cancelled());
if (error.code === "unsupported")
return err(failure("unsupported", error.message));
return err(failure("io", error.message));
}
if (!readResult.ok)
return err(
combineReadFailures(
readResult.error,
vcsResult.ok ? undefined : vcsResult.error,
readResult.error.partial,
),
);
if (!vcsResult.ok)
return err(
combineReadFailures(vcsResult.error, undefined, readResult.value),
);
if (isAborted(options.signal)) return err(cancelled());
const vcs = vcsResult.value;
if (isAborted(options.signal)) return err(cancelled(readResult.value));
const read = readResult.value;
const filePaths = new Set(
@@ -208,7 +226,7 @@ export const importReferenceSource = async (
const { entries, relationships, parseFailures, limitations } =
parseReferenceSourceEntries(read, filePaths, options.signal);
if (isAborted(options.signal)) return err(cancelled());
if (isAborted(options.signal)) return err(cancelled(read));
const uniqueRelationships = deduplicateRelationships(relationships);
const uniqueFailures = normalizeHistoricalSourceParseFailures(parseFailures);
@@ -254,3 +272,45 @@ export const importReferenceSource = async (
);
}
};
const combineReadFailures = (
primary: ReferenceSourceReaderError,
other: ReferenceSourceReaderError | undefined,
partial: ReferenceSourceRead | undefined,
): ReferenceSourceImportError => {
const code =
primary.code === "cancelled" || other?.code === "cancelled"
? "cancelled"
: primary.code;
const cleanup = mergeCleanup(primary.cleanup, other?.cleanup);
const message =
other === undefined
? primary.message
: `${primary.message}; additional reference metadata failure: ${other.message}`;
const cause =
other === undefined
? primary.cause
: new AggregateError(
[primary, other],
"Reference source inventory and metadata both failed",
{ cause: primary },
);
return {
...failure(code, message),
...(cleanup === undefined ? {} : { cleanup }),
...(partial === undefined ? {} : { partial }),
...(cause === undefined ? {} : { cause }),
};
};
const mergeCleanup = (
first: AnalysisCleanupObservation | undefined,
second: AnalysisCleanupObservation | undefined,
): AnalysisCleanupObservation | undefined => {
if (first === undefined) return second;
if (second === undefined) return first;
return {
reason: `${first.reason}; ${second.reason}`,
resources: [...new Set([...first.resources, ...second.resources])],
};
};
+75 -25
View File
@@ -2,9 +2,15 @@ import { lstat, realpath, stat } from "node:fs/promises";
import { join, resolve } from "node:path";
import ignore from "ignore";
import { readRegularFileText } from "./RegularFileRead.js";
import {
readRegularFileText,
RegularFileCleanupFailure,
retryRegularFileCleanup,
} from "./RegularFileRead.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import {
DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS,
type ReferenceSourceImportError,
@@ -52,7 +58,10 @@ const resolveRoot = async (
return err(failure("cancelled", "Reference source import cancelled"));
if (!metadata.isDirectory())
return err(
failure("invalid-root", "Reference source root is not a directory"),
failure(
"invalid-root",
`Reference source root is not a directory: ${requestedRoot}`,
),
);
const canonicalRoot = await realpath(resolve(requestedRoot));
if (isAborted(signal))
@@ -66,19 +75,16 @@ const resolveRoot = async (
"Reference source root could not be resolved",
);
if (rootFailure === undefined) throw cause;
const message =
rootFailure.code === "invalid-root"
? "Reference source root could not be resolved"
: rootFailure.message;
return err(failure(rootFailure.code, message));
return err({ ...failure(rootFailure.code, rootFailure.message), cause });
}
};
const buildIgnored = async (
root: string,
excludePaths: readonly string[],
resources: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<ReturnType<typeof ignore>> => {
): Promise<Result<ReturnType<typeof ignore>, ReferenceSourceImportError>> => {
const ignored = ignore();
const policyPath = join(root, ".gitignore");
let present = true;
@@ -98,7 +104,29 @@ const buildIgnored = async (
}
signal?.throwIfAborted();
if (present) {
const text = await readRegularFileText(policyPath, { signal });
let text: string;
try {
text = await readRegularFileText(policyPath, { signal });
} catch (cause: unknown) {
if (!(cause instanceof RegularFileCleanupFailure)) throw cause;
const retry = await retryRegularFileCleanup(cause, resources);
if (retry.cleanup !== undefined) {
const primary =
cause.outcome.kind === "failed"
? cause.outcome.cause
: cause.cleanupCause;
return err({
...failure(
signal?.aborted === true ? "cancelled" : "io",
`Reference source ignore policy could not be read at ${policyPath}: ${errorMessage(primary)}`,
),
cleanup: retry.cleanup,
cause: primary,
});
}
if (retry.outcome.kind === "failed") throw retry.outcome.cause;
text = retry.outcome.value;
}
addMarkedPatterns(ignored, [text], "project-ignored");
}
addMarkedPatterns(
@@ -109,33 +137,55 @@ const buildIgnored = async (
for (const path of excludePaths) {
addMarkedPatterns(ignored, [path, `${path}/`], "caller-excluded");
}
return ignored;
return ok(ignored);
};
/** Resolve the caller-selected directory and build path filters. */
export const prepareReferenceSourceImport = async (
options: ReferenceSourceImportOptions,
resources: ArtifactResourceScope,
): Promise<
Result<PreparedReferenceSourceImport, ReferenceSourceImportError>
> => {
const root = await resolveRoot(options.root, options.signal);
if (!root.ok) return root;
try {
return ok({
root: root.value,
ignored: await buildIgnored(
root.value,
options.excludePaths ?? [],
options.signal,
),
secrets: ignore().add([...options.policy.secretPatterns]),
return await resources.run(async () => {
const root = await resolveRoot(options.root, options.signal);
if (!root.ok) return root;
try {
const ignored = await buildIgnored(
root.value,
options.excludePaths ?? [],
resources,
options.signal,
);
if (!ignored.ok) return ignored;
return ok({
root: root.value,
ignored: ignored.value,
secrets: ignore().add([...options.policy.secretPatterns]),
});
} catch (cause: unknown) {
return err({
...failure(
options.signal?.aborted === true ? "cancelled" : "io",
`Reference source ignore policy could not be read at ${join(root.value, ".gitignore")}: ${errorMessage(cause)}`,
),
cause,
});
}
});
} catch (cause: unknown) {
return err(
failure(
options.signal?.aborted === true ? "cancelled" : "io",
`Reference source ignore policy could not be read at ${join(root.value, ".gitignore")}: ${cause instanceof Error ? cause.message : String(cause)}`,
if (!(cause instanceof ArtifactReaderFailure)) throw cause;
return err({
...failure(
cause.reason === "cancelled" ? "cancelled" : "io",
cause.message,
),
);
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
cause,
});
}
};
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import {
projectReferenceSourceImportError,
type ReferenceSourceImportError,
} from "./ReferenceSourceImportTypes.js";
import type { ReferenceSourceRead } from "../reference/ReferenceSourceReaderTypes.js";
describe("reference-source import error projection", () => {
it("preserves primary evidence with category-specific recovery guidance", () => {
const expectedCategories = {
cancelled: "cancelled",
"invalid-root": "invalid_input",
unsupported: "unsupported_host",
io: "execution_failure",
parse: "execution_failure",
} as const;
for (const [code, category] of Object.entries(expectedCategories)) {
const projected = projectReferenceSourceImportError({
tag: "reference-source-import",
code: code as ReferenceSourceImportError["code"],
message: "EIO while reading /selected/source/src/main.ts",
});
expect(projected.category).toBe(category);
expect(projected.message).toContain(
"EIO while reading /selected/source/src/main.ts",
);
expect(projected.message).toMatch(
/try again|when ready|Check that|REA on Linux/u,
);
}
});
it("preserves cancellation, partial facts, and cleanup diagnostics", () => {
const bytes = Buffer.from("export const observed = true;\n");
const partial: ReferenceSourceRead = {
root: "/selected/source",
entries: [
{
status: "read",
kind: "file",
path: "src/main.ts",
bytes,
size: bytes.length,
},
],
bytesRead: bytes.length,
limitations: [],
};
const projected = projectReferenceSourceImportError({
tag: "reference-source-import",
code: "cancelled",
message: "Traversal cancelled after reading src/main.ts",
cleanup: {
reason: "directory close rejected",
resources: ["/selected/source"],
},
partial,
});
expect(projected).toMatchObject({
category: "cancelled",
message: expect.stringContaining(
"Traversal cancelled after reading src/main.ts",
),
cleanup: {
reason: "directory close rejected",
resources: ["/selected/source"],
},
partial: {
root: "/selected/source",
entries: [{ path: "src/main.ts", bytes }],
},
});
expect(projected.message).toContain("Cleanup failed during import");
expect(projected.message).toContain("directory close rejected");
expect(projected.message).toContain("/selected/source");
expect(projected.message).not.toContain("remains unconfirmed");
});
});
+51 -28
View File
@@ -1,44 +1,67 @@
import type { ReferenceSourcePolicy } from "../domain/referenceSourcePolicy.js";
import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js";
import type { ReferenceSourceRead } from "../reference/ReferenceSourceReaderTypes.js";
/** Typed expected failure returned by historical-source imports. */
export interface ReferenceSourceImportError {
readonly tag: "reference-source-import";
readonly code: "cancelled" | "invalid-root" | "unsupported" | "io" | "parse";
readonly message: string;
readonly cleanup?: AnalysisCleanupObservation;
readonly partial?: ReferenceSourceRead;
readonly cause?: unknown;
}
const IMPORT_FAILURE_GUIDANCE = {
cancelled: {
category: "cancelled",
message:
"Reference source import was cancelled. Start it again when ready.",
},
"invalid-root": {
category: "invalid_input",
message:
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
},
unsupported: {
category: "unsupported_host",
message:
"Safe no-follow file opens are unavailable on this host. Import the source tree with REA on Linux (including WSL) or macOS.",
},
io: {
category: "execution_failure",
message:
"Reference source files could not be read. Check directory permissions and try again.",
},
parse: {
category: "execution_failure",
message:
"Reference source could not be indexed. Check that the source tree is readable, then try again.",
},
} satisfies Record<
ReferenceSourceImportError["code"],
{ readonly category: string; readonly message: string }
>;
/** Safe CLI projection for a historical-source import failure. */
export const projectReferenceSourceImportError = (
error: ReferenceSourceImportError,
): Readonly<{ category: string; message: string }> => {
if (error.code === "cancelled")
return {
category: "cancelled",
message:
"Reference source import was cancelled. Start it again when ready.",
};
if (error.code === "invalid-root")
return {
category: "invalid_input",
message:
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
};
if (error.code === "unsupported")
return {
category: "unsupported_host",
message:
"Safe no-follow file opens are unavailable on this host. Import the source tree with REA on Linux (including WSL) or macOS.",
};
if (error.code === "io")
return {
category: "execution_failure",
message:
"Reference source files could not be read. Check directory permissions and try again.",
};
): Readonly<{
category: string;
message: string;
cleanup?: AnalysisCleanupObservation;
partial?: ReferenceSourceRead;
}> => {
const primary = IMPORT_FAILURE_GUIDANCE[error.code];
const cleanupMessage =
error.cleanup === undefined
? ""
: ` Cleanup failed during import for ${error.cleanup.resources.join(", ")}: ${error.cleanup.reason}.`;
return {
category: "execution_failure",
message:
"Reference source could not be indexed. Check that the source tree is readable, then try again.",
category: primary.category,
message: `${error.message} ${primary.message}${cleanupMessage}`,
...(error.cleanup === undefined ? {} : { cleanup: error.cleanup }),
...(error.partial === undefined ? {} : { partial: error.partial }),
};
};
+166 -20
View File
@@ -1,7 +1,17 @@
import fs from "node:fs";
import { lstat } from "node:fs/promises";
import { join, resolve } from "node:path";
import { readRegularFile, readRegularFileText } from "./RegularFileRead.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js";
import {
readRegularFile,
readRegularFileText,
RegularFileCleanupFailure,
retryRegularFileCleanup,
} from "./RegularFileRead.js";
import type { ReferenceSourceReaderError } from "../reference/ReferenceSourceReaderTypes.js";
export type ReferenceSourceVcsInfo =
| {
@@ -19,40 +29,122 @@ export type ReferenceSourceVcsInfo =
*/
export const readReferenceSourceVcs = async (
root: string,
resources: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<ReferenceSourceVcsInfo> => {
if (isAborted(signal)) return { kind: "unknown", head: null, dirty: null };
): Promise<Result<ReferenceSourceVcsInfo, ReferenceSourceReaderError>> => {
try {
await lstat(join(root, ".git"));
return await resources.run(async () => {
if (isAborted(signal)) return ok(unknownVcs());
try {
await lstat(join(root, ".git"));
} catch (cause: unknown) {
return ok(
errorCode(cause) === "ENOENT"
? { kind: "none", head: null, dirty: null }
: unknownVcs(),
);
}
try {
const head = await resolveSourceHead(root, resources, signal);
if (isAborted(signal)) return ok(unknownVcs());
return ok({ kind: "git", head, dirty: null });
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure) throw cause;
if (cause instanceof RegularFileCleanupFailure) {
const retry = await retryRegularFileCleanup(cause, resources);
if (retry.cleanup !== undefined) {
const primary =
cause.outcome.kind === "failed"
? cause.outcome.cause
: cause.cleanupCause;
const code = isAborted(signal) ? "cancelled" : "io";
return err({
tag: "reference-source-reader",
code,
message: `Git metadata could not be read safely: ${errorMessage(primary)}`,
cleanup: retry.cleanup,
cause: primary,
});
}
if (retry.outcome.kind === "completed")
return err({
tag: "reference-source-reader",
code: isAborted(signal) ? "cancelled" : "io",
message: isAborted(signal)
? "Git metadata read cancelled"
: `Git metadata close failed: ${errorMessage(cause.cleanupCause)}`,
cause: cause.cleanupCause,
});
if (retry.outcome.kind === "failed") {
return isAborted(signal)
? err({
tag: "reference-source-reader",
code: "cancelled",
message: "Git metadata read cancelled",
cause: retry.outcome.cause,
})
: ok(unknownVcs());
}
}
return ok(unknownVcs());
}
});
} catch (cause: unknown) {
return errorCode(cause) === "ENOENT"
? { kind: "none", head: null, dirty: null }
: { kind: "unknown", head: null, dirty: null };
}
try {
const head = await resolveSourceHead(root, signal);
if (isAborted(signal)) return { kind: "unknown", head: null, dirty: null };
return { kind: "git", head, dirty: null };
} catch (cause: unknown) {
// Unresolvable refs mean VCS state is unknown, not absent.
void cause;
return { kind: "unknown", head: null, dirty: null };
if (!(cause instanceof ArtifactReaderFailure)) throw cause;
return err({
tag: "reference-source-reader",
code: cause.reason === "cancelled" ? "cancelled" : "io",
message: cause.message,
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
cause,
});
}
};
const unknownVcs = (): ReferenceSourceVcsInfo => ({
kind: "unknown",
head: null,
dirty: null,
});
const resolveSourceHead = async (
root: string,
resources: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<string> => {
// isomorphic-git is loaded on first use so CLI and MCP startup skip it.
const { resolveRef } = await import("isomorphic-git");
let failedRead: { readonly cause: unknown } | undefined;
const cleanupFailures: {
readonly failure: RegularFileCleanupFailure;
readonly cleanup?: NonNullable<ArtifactReaderFailure["cleanup"]>;
}[] = [];
const throwCleanupFailures = (primary: unknown): never => {
const cleanup = mergeCleanup(
cleanupFailures.flatMap((failure) =>
failure.cleanup === undefined ? [] : [failure.cleanup],
),
);
throw new ArtifactReaderFailure(
isAborted(signal) ? "cancelled" : "io",
`Git metadata could not be read safely: ${errorMessage(primary)}`,
{
cause: new AggregateError(
[primary, ...cleanupFailures.map((item) => item.failure)],
"Git metadata reads and cleanup failed",
{ cause: primary },
),
...(cleanup === undefined ? {} : { cleanup }),
},
);
};
const referenceFs = {
...fs,
promises: {
...fs.promises,
// isomorphic-git treats every read failure as absence. Preserve real
// failures so a readable packed ref cannot hide an unreadable loose ref.
// Let isomorphic-git continue from a failed loose ref to packed-refs,
// then report the original read failure after resolution. This preserves
// both observations when packed metadata also fails cleanup.
readFile: async (
path: string | undefined,
options:
@@ -72,7 +164,20 @@ const resolveSourceHead = async (
? bytes
: bytes.toString(encoding);
} catch (cause: unknown) {
if (errorCode(cause) !== "ENOENT") failedRead ??= { cause };
if (cause instanceof RegularFileCleanupFailure) {
const retry = await retryRegularFileCleanup(cause, resources);
cleanupFailures.push({
failure: cause,
...(retry.cleanup === undefined
? {}
: { cleanup: retry.cleanup }),
});
if (
retry.outcome.kind === "failed" &&
errorCode(retry.outcome.cause) !== "ENOENT"
)
failedRead ??= { cause: retry.outcome.cause };
} else if (errorCode(cause) !== "ENOENT") failedRead ??= { cause };
throw cause;
}
},
@@ -82,7 +187,19 @@ const resolveSourceHead = async (
readonly gitdir?: string;
readonly ref: string;
}) => {
const head = await resolveRef({ fs: referenceFs, dir: root, ...options });
let head: string;
try {
head = await resolveRef({ fs: referenceFs, dir: root, ...options });
} catch (cause: unknown) {
if (cleanupFailures.length > 0)
throwCleanupFailures(failedRead?.cause ?? cause);
if (failedRead !== undefined) throw failedRead.cause;
throw cause;
}
if (cleanupFailures.length > 0)
throwCleanupFailures(
failedRead?.cause ?? cleanupFailurePrimary(cleanupFailures[0]),
);
signal?.throwIfAborted();
if (failedRead !== undefined) throw failedRead.cause;
return head;
@@ -122,9 +239,38 @@ const resolveSourceHead = async (
});
};
const cleanupFailurePrimary = (
failure:
| {
readonly failure: RegularFileCleanupFailure;
}
| undefined,
): unknown =>
failure?.failure.outcome.kind === "failed"
? failure.failure.outcome.cause
: failure?.failure.cleanupCause;
const mergeCleanup = (
observations: readonly AnalysisCleanupObservation[],
): AnalysisCleanupObservation | undefined => {
if (observations.length === 0) return undefined;
const first = observations[0];
if (first === undefined) return undefined;
return observations.slice(1).reduce<AnalysisCleanupObservation>(
(merged, next) => ({
reason: `${merged.reason}; ${next.reason}`,
resources: [...new Set([...merged.resources, ...next.resources])],
}),
first,
);
};
const errorCode = (cause: unknown): string | undefined =>
typeof cause === "object" && cause !== null && "code" in cause
? String(cause.code)
: undefined;
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
+94 -8
View File
@@ -2,11 +2,15 @@ import type { Stats } from "node:fs";
import { lstat, stat, type FileHandle } from "node:fs/promises";
import {
RegularFileAdmissionFailure,
openRegularFile,
sameRegularFileState,
RegularFileChangedError,
} from "../filesystem/RegularFile.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js";
/** Filesystem admission policy for one selected regular input. */
export interface RegularFileReadOptions {
@@ -14,6 +18,51 @@ export interface RegularFileReadOptions {
readonly symlinks?: "follow" | "reject";
}
export type RegularFileReadOutcome<Value> =
| { readonly kind: "completed"; readonly value: Value }
| { readonly kind: "failed"; readonly cause: unknown };
/** A close failed after reading; this error transfers the exact handle owner. */
export class RegularFileCleanupFailure<Value = unknown> extends Error {
constructor(
readonly path: string,
readonly owner: OwnedFileHandle,
readonly outcome: RegularFileReadOutcome<Value>,
readonly cleanupCause: unknown,
) {
super(`Regular file cleanup failed: ${path}`, {
cause: outcome.kind === "failed" ? outcome.cause : cleanupCause,
});
this.name = "RegularFileCleanupFailure";
}
}
/** Retry a failed close through its retained owner and report any remaining cleanup. */
export const retryRegularFileCleanup = async <Value>(
failure: RegularFileCleanupFailure<Value>,
resources: ArtifactResourceScope,
): Promise<{
readonly outcome: RegularFileReadOutcome<Value>;
readonly cleanup?: AnalysisCleanupObservation;
}> => {
const released = await resources.release({
kind: "file-handle",
handle: failure.owner,
resource: failure.path,
});
if (released.kind === "released") return { outcome: failure.outcome };
return {
outcome: failure.outcome,
cleanup: {
reason: `${failureMessage(failure.cleanupCause)}; retry: ${failureMessage(released.cause)}`,
resources: [failure.path],
},
};
};
const failureMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
/** Admit one regular-file handle, retain it through the consumer, and always close it. */
export const withRegularFile = async <Value>(
path: string,
@@ -21,10 +70,23 @@ export const withRegularFile = async <Value>(
options: RegularFileReadOptions = {},
): Promise<Value> => {
const { signal } = options;
const handle = await openRegularFile(path, {
symlinks: options.symlinks ?? "follow",
signal,
});
let handle: FileHandle;
try {
handle = await openRegularFile(path, {
symlinks: options.symlinks ?? "follow",
signal,
});
} catch (cause: unknown) {
if (!(cause instanceof RegularFileAdmissionFailure)) throw cause;
throw new RegularFileCleanupFailure(
path,
cause.owner,
{ kind: "failed", cause: cause.cause },
cause.cleanupCause,
);
}
const owner = new OwnedFileHandle(handle);
let outcome: RegularFileReadOutcome<Value>;
try {
const stats = await handle.stat();
signal?.throwIfAborted();
@@ -39,10 +101,17 @@ export const withRegularFile = async <Value>(
!sameRegularFileState(stats, currentPath)
)
throw new RegularFileChangedError(path);
return value;
} finally {
await handle.close();
outcome = { kind: "completed", value };
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
}
try {
await owner.close();
} catch (cleanupCause: unknown) {
throw new RegularFileCleanupFailure(path, owner, outcome, cleanupCause);
}
if (outcome.kind === "failed") throw outcome.cause;
return outcome.value;
};
/** Admit a regular file without waiting for a pipe, then read its verified handle. */
@@ -69,4 +138,21 @@ export const readRegularFile = (
export const readRegularFileText = async (
path: string,
options: RegularFileReadOptions = {},
): Promise<string> => (await readRegularFile(path, options)).toString("utf8");
): Promise<string> => {
try {
return (await readRegularFile(path, options)).toString("utf8");
} catch (cause: unknown) {
if (
cause instanceof RegularFileCleanupFailure &&
cause.outcome.kind === "completed" &&
Buffer.isBuffer(cause.outcome.value)
)
throw new RegularFileCleanupFailure(
cause.path,
cause.owner,
{ kind: "completed", value: cause.outcome.value.toString("utf8") },
cause.cleanupCause,
);
throw cause;
}
};