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:
@@ -1,5 +1,7 @@
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
import { traverseDirectory } from "./ReferenceSourceReaderEntries.js";
|
||||
import {
|
||||
type ReferenceSourceReaderOptions,
|
||||
@@ -19,7 +21,27 @@ const PATH_RACE_LIMITATION =
|
||||
/** Read a source tree without intentionally following symbolic links. */
|
||||
export const readReferenceSource = async (
|
||||
root: string,
|
||||
resources: ArtifactResourceScope,
|
||||
options: ReferenceSourceReaderOptions = {},
|
||||
): Promise<ReferenceSourceResult<ReferenceSourceRead>> => {
|
||||
try {
|
||||
return await resources.run(() => readSource(root, resources, options));
|
||||
} catch (cause: unknown) {
|
||||
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 readSource = async (
|
||||
root: string,
|
||||
resources: ArtifactResourceScope,
|
||||
options: ReferenceSourceReaderOptions,
|
||||
): Promise<ReferenceSourceResult<ReferenceSourceRead>> => {
|
||||
if (!noFollowOpenSupported())
|
||||
return err({
|
||||
@@ -31,6 +53,7 @@ export const readReferenceSource = async (
|
||||
if (!prepared.ok) return prepared;
|
||||
const { canonicalRoot, rootIdentity } = prepared.value;
|
||||
const state: TraversalState = {
|
||||
resources,
|
||||
root: canonicalRoot,
|
||||
rootIdentity,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
@@ -42,16 +65,16 @@ export const readReferenceSource = async (
|
||||
bytesRead: 0,
|
||||
};
|
||||
const traversal = await traverse(state);
|
||||
if (!traversal.ok) return traversal;
|
||||
state.entries.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.path, right.path),
|
||||
);
|
||||
return ok({
|
||||
const read: ReferenceSourceRead = {
|
||||
root: canonicalRoot,
|
||||
entries: state.entries,
|
||||
bytesRead: state.bytesRead,
|
||||
limitations: [PATH_RACE_LIMITATION],
|
||||
});
|
||||
};
|
||||
return traversal.ok ? ok(read) : err({ ...traversal.error, partial: read });
|
||||
};
|
||||
|
||||
const traverse = async (
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import type { BigIntStats, Dir, Dirent } from "node:fs";
|
||||
import { opendir, readlink, realpath } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import type { ArtifactCleanupAttempt } from "../artifacts/ArtifactResourceScope.js";
|
||||
import { OwnedDirectoryHandle } from "../filesystem/OwnedDirectoryHandle.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
|
||||
import {
|
||||
cancelled,
|
||||
entryFailure,
|
||||
failure,
|
||||
filesystemFailureDetail,
|
||||
safeSize,
|
||||
} from "./ReferenceSourceReaderErrors.js";
|
||||
@@ -56,28 +61,68 @@ export const traverseDirectory = async (
|
||||
readFailure = directoryReadFailure(cause);
|
||||
}
|
||||
if (handle !== undefined) {
|
||||
const iterator = handle[Symbol.asyncIterator]();
|
||||
const owner = new OwnedDirectoryHandle(handle);
|
||||
let result: ReferenceSourceResult<undefined> = ok(undefined);
|
||||
let cleanup: ArtifactCleanupAttempt;
|
||||
try {
|
||||
for (;;) {
|
||||
let child: IteratorResult<Dirent>;
|
||||
let child: Dirent | null;
|
||||
try {
|
||||
child = await iterator.next();
|
||||
child = await handle.read();
|
||||
} catch (cause: unknown) {
|
||||
readFailure = directoryReadFailure(cause);
|
||||
break;
|
||||
}
|
||||
if (child.done) break;
|
||||
const result = await processEntry(
|
||||
state,
|
||||
current,
|
||||
child.value.name,
|
||||
directories,
|
||||
);
|
||||
if (!result.ok) return result;
|
||||
if (child === null) break;
|
||||
result = await processEntry(state, current, child.name, directories);
|
||||
if (!result.ok) break;
|
||||
}
|
||||
} finally {
|
||||
await handle.close().catch(() => undefined);
|
||||
cleanup = await state.resources.release({
|
||||
kind: "directory-handle",
|
||||
handle: owner,
|
||||
resource: current.path,
|
||||
});
|
||||
}
|
||||
if (cleanup.kind === "failed") {
|
||||
if (result.ok && !isAborted(state.signal) && readFailure !== undefined)
|
||||
state.entries.push(
|
||||
entryFailure(
|
||||
pathFromRoot(state.root, current.path),
|
||||
"directory",
|
||||
"io",
|
||||
readFailure,
|
||||
),
|
||||
);
|
||||
const observation = ArtifactReaderFailure.cleanupObservation(
|
||||
cleanup.cause,
|
||||
current.path,
|
||||
);
|
||||
const previous = result.ok ? undefined : result.error.cleanup;
|
||||
const primary = result.ok
|
||||
? isAborted(state.signal)
|
||||
? cancelled()
|
||||
: failure(
|
||||
"io",
|
||||
readFailure ??
|
||||
`Reference directory cleanup failed: ${current.path}`,
|
||||
)
|
||||
: result.error;
|
||||
return err({
|
||||
...primary,
|
||||
cleanup:
|
||||
previous === undefined
|
||||
? observation
|
||||
: {
|
||||
reason: `${previous.reason}; ${observation.reason}`,
|
||||
resources: [
|
||||
...new Set([...previous.resources, ...observation.resources]),
|
||||
],
|
||||
},
|
||||
cause: primary.cause ?? cleanup.cause,
|
||||
});
|
||||
}
|
||||
if (!result.ok) return result;
|
||||
}
|
||||
if (isAborted(state.signal)) return { ok: false, error: cancelled() };
|
||||
if (readFailure !== undefined) {
|
||||
@@ -194,7 +239,7 @@ const processEntry = async (
|
||||
safeSize(metadata.value.size),
|
||||
),
|
||||
);
|
||||
else await processFileEntry(state, absolute, path, metadata.value);
|
||||
else return processFileEntry(state, absolute, path, metadata.value);
|
||||
return { ok: true, value: undefined };
|
||||
};
|
||||
|
||||
@@ -203,8 +248,9 @@ const processFileEntry = async (
|
||||
absolute: string,
|
||||
path: string,
|
||||
metadata: BigIntStats,
|
||||
): Promise<void> => {
|
||||
): Promise<ReferenceSourceResult<undefined>> => {
|
||||
const result = await readStableFile({
|
||||
resources: state.resources,
|
||||
root: state.root,
|
||||
rootIdentity: state.rootIdentity,
|
||||
absolute,
|
||||
@@ -212,9 +258,24 @@ const processFileEntry = async (
|
||||
expected: metadata,
|
||||
...(state.signal === undefined ? {} : { signal: state.signal }),
|
||||
});
|
||||
if (result.status === "read" && result.kind === "file")
|
||||
state.bytesRead += result.bytes.byteLength;
|
||||
state.entries.push(result);
|
||||
const { entry } = result;
|
||||
if (entry.status === "read" && entry.kind === "file")
|
||||
state.bytesRead += entry.bytes.byteLength;
|
||||
state.entries.push(entry);
|
||||
if (result.cleanup !== undefined)
|
||||
return err({
|
||||
tag: "reference-source-reader",
|
||||
code:
|
||||
entry.status === "failed" && entry.code === "cancelled"
|
||||
? "cancelled"
|
||||
: "io",
|
||||
message:
|
||||
entry.status === "failed"
|
||||
? entry.message
|
||||
: `Reference file cleanup failed: ${path}`,
|
||||
cleanup: result.cleanup,
|
||||
});
|
||||
return ok(undefined);
|
||||
};
|
||||
|
||||
const describeSymlink = async (
|
||||
|
||||
@@ -4,8 +4,12 @@ import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
NonRegularFileReadError,
|
||||
RegularFileAdmissionFailure,
|
||||
openRegularFile,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js";
|
||||
|
||||
import {
|
||||
entryFailure,
|
||||
@@ -195,9 +199,39 @@ const finalizeFileRead = async (
|
||||
|
||||
export const readStableFile = async (
|
||||
request: StableFileRequest,
|
||||
): Promise<{
|
||||
readonly entry: ReferenceSourceEntry;
|
||||
readonly cleanup?: AnalysisCleanupObservation;
|
||||
}> => {
|
||||
let owner: OwnedFileHandle | undefined;
|
||||
let cleanup: AnalysisCleanupObservation | undefined;
|
||||
let entry: ReferenceSourceEntry;
|
||||
try {
|
||||
entry = await readStableFileEntry(request, (admitted) => {
|
||||
owner = admitted;
|
||||
});
|
||||
} finally {
|
||||
if (owner !== undefined) {
|
||||
const result = await request.resources.release({
|
||||
kind: "file-handle",
|
||||
handle: owner,
|
||||
resource: request.absolute,
|
||||
});
|
||||
if (result.kind === "failed")
|
||||
cleanup = ArtifactReaderFailure.cleanupObservation(
|
||||
result.cause,
|
||||
request.absolute,
|
||||
);
|
||||
}
|
||||
}
|
||||
return { entry, ...(cleanup === undefined ? {} : { cleanup }) };
|
||||
};
|
||||
|
||||
const readStableFileEntry = async (
|
||||
request: StableFileRequest,
|
||||
retain: (owner: OwnedFileHandle) => void,
|
||||
): Promise<ReferenceSourceEntry> => {
|
||||
const { root, rootIdentity, absolute, path, expected, signal } = request;
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
const parentBefore = await validateDirectory(
|
||||
root,
|
||||
@@ -213,7 +247,11 @@ export const readStableFile = async (
|
||||
parentBefore.message,
|
||||
safeSize(expected.size),
|
||||
);
|
||||
handle = await openRegularFile(absolute, { symlinks: "reject", signal });
|
||||
const handle = await openRegularFile(absolute, {
|
||||
symlinks: "reject",
|
||||
signal,
|
||||
});
|
||||
retain(new OwnedFileHandle(handle));
|
||||
const prepared = await prepareFileRead(request, handle);
|
||||
if (prepared.status === "failed") return prepared.entry;
|
||||
const contents = await readFileContents({
|
||||
@@ -236,6 +274,10 @@ export const readStableFile = async (
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileAdmissionFailure) {
|
||||
retain(cause.owner);
|
||||
cause = cause.cause;
|
||||
}
|
||||
if (isAborted(signal))
|
||||
return entryFailure(
|
||||
path,
|
||||
@@ -258,8 +300,5 @@ export const readStableFile = async (
|
||||
);
|
||||
if (message === undefined) throw cause;
|
||||
return entryFailure(path, "file", "io", message, safeSize(expected.size));
|
||||
} finally {
|
||||
// best-effort cleanup: file-handle close must not mask the read result.
|
||||
await handle?.close().catch(() => undefined);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { type BigIntStats } from "node:fs";
|
||||
|
||||
import { type Result } from "../domain/result.js";
|
||||
import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js";
|
||||
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
|
||||
export type ReferenceSourceEntryKind =
|
||||
| "file"
|
||||
@@ -65,6 +67,10 @@ export interface ReferenceSourceReaderError {
|
||||
readonly tag: "reference-source-reader";
|
||||
readonly code: "cancelled" | "invalid-root" | "io" | "unsupported";
|
||||
readonly message: string;
|
||||
readonly cleanup?: AnalysisCleanupObservation;
|
||||
/** Captured entries before failure; this does not establish complete tree coverage. */
|
||||
readonly partial?: ReferenceSourceRead;
|
||||
readonly cause?: unknown;
|
||||
}
|
||||
|
||||
export type PendingDirectory = {
|
||||
@@ -72,6 +78,7 @@ export type PendingDirectory = {
|
||||
};
|
||||
|
||||
export type TraversalState = {
|
||||
readonly resources: ArtifactResourceScope;
|
||||
readonly root: string;
|
||||
readonly rootIdentity: BigIntStats;
|
||||
readonly signal?: AbortSignal;
|
||||
@@ -85,6 +92,7 @@ export type TraversalState = {
|
||||
};
|
||||
|
||||
export type StableFileRequest = {
|
||||
readonly resources: ArtifactResourceScope;
|
||||
readonly root: string;
|
||||
readonly rootIdentity: BigIntStats;
|
||||
readonly absolute: string;
|
||||
|
||||
Reference in New Issue
Block a user