mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 11:43:20 +00:00
* refactor(kernel): give error-to-message text one owner in a new src/kernel layer * fix(kernel): keep the regex worker's own error text inside its isolated source * refactor(kernel): exclude copies that run in another realm from the error-message guard by name The regex worker's source string and the page.evaluate fetch in PlaywrightScenarioRequest cannot import errorMessage. The guard now names them, so the counted baseline does not invite a later slice to rewrite them. * refactor(kernel): migrate the long tail of inline error-message copies to errorMessage (#11552) Every provider and adapter folder with six or fewer copies now calls errorMessage from src/kernel. Local helpers whose whole body was the copy (failureMessage, gdbErrorMessage, message, describe, reasonOf, recoveryFailureMessage and four local errorMessage definitions) are removed and their call sites call the owner. Refs #11548 * refactor(kernel): give byte-to-hex formatting one owner in src/kernel (#11560) byteToHex returns the two lowercase hexadecimal digits of one byte. All eight inline copies (native, contracts, domain firmware and desktop, pcap) call it, keeping their own 0x, % or \x notation, and a counted guard with an empty baseline keeps new copies out. Refs #11548 * refactor(kernel): give one-shot SHA-256 hex digests one owner in src/kernel (#11562) sha256Hex digests one in-memory value. A counted guard records the one-shot createHash("sha256").update(x).digest("hex") chains (115 in 101 files) and the first slice migrates domain, contracts and process (35 copies), removing local wrappers (sha256, sha256Text, hash) and the exported sha256Text. Incremental and streamed hashing is not counted. Refs #11548 * refactor(kernel): migrate the application layer's inline error-message copies to errorMessage (#11563) All 69 copies in src/application call errorMessage from src/kernel. Local helpers whose whole body was the copy (errorDetail, causeReason and five local errorMessage definitions) are removed and their call sites call the owner. Refs #11548 * refactor(kernel): migrate the native provider's inline error-message copies to errorMessage (#11567) All 49 copies in src/native call errorMessage from src/kernel. The local errorReason helpers in LldbCallTracer and LldbRetainedObservations, whose whole body was the copy, are removed and their call sites call the owner. Refs #11548 * refactor(kernel): migrate the remaining inline error-message copies to errorMessage (#11569)
233 lines
8.4 KiB
TypeScript
233 lines
8.4 KiB
TypeScript
import { HOST_PLATFORM } from "../../platform/HostPlatform.js";
|
|
import { constants } from "node:fs";
|
|
import { access, lstat, readdir } from "node:fs/promises";
|
|
import { basename, dirname, isAbsolute } from "node:path";
|
|
|
|
import {
|
|
ArtifactResourceScope,
|
|
type ArtifactCleanupAttempt,
|
|
SafeOutputTree,
|
|
outputDirectoryAdmissionRefusal,
|
|
SafeOutputTreeDestinationRefusal,
|
|
SafeOutputTreeCreationFailure,
|
|
} from "../../resources/index.js";
|
|
import { canonicalCallerPath } from "../../filesystem/canonicalCallerPath.js";
|
|
import { absoluteCallerPath } from "../../filesystem/callerPath.js";
|
|
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
|
import {
|
|
AnalysisCancelledError,
|
|
cancelledBy,
|
|
} from "../../domain/analysisErrorCore.js";
|
|
import { analysisErrorWithCancellation } from "../../domain/analysisErrorCancellation.js";
|
|
import type { Evidence } from "../../domain/evidence.js";
|
|
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
|
import { errorMessage } from "../../kernel/errorMessage.js";
|
|
|
|
/** A published tree whose output handles could not be released. */
|
|
type FailedRelease = Extract<
|
|
ArtifactCleanupAttempt,
|
|
{ readonly kind: "failed" }
|
|
>;
|
|
|
|
/** Facts observed by the output owner after publication and final cleanup. */
|
|
export interface DesktopOutputCompletion {
|
|
readonly kind: "published";
|
|
readonly release: FailedRelease | undefined;
|
|
readonly cancellation: AnalysisCancelledError | undefined;
|
|
}
|
|
|
|
/** A caller-selected destination and the filesystem path admitted for writing. */
|
|
export interface DesktopOutputPlan {
|
|
readonly requested: string;
|
|
readonly physical: string;
|
|
}
|
|
|
|
/** The closest existing directory above a canonical path whose leaf is absent. */
|
|
const nearestExisting = async (physical: string): Promise<string> => {
|
|
let current = dirname(physical);
|
|
for (;;) {
|
|
const found = await lstat(current).then(
|
|
() => true,
|
|
(cause: unknown) => {
|
|
if ((cause as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
throw cause;
|
|
},
|
|
);
|
|
if (found || dirname(current) === current) return current;
|
|
current = dirname(current);
|
|
}
|
|
};
|
|
|
|
/** Establish destination identity before either output tree is created. */
|
|
export const planOutputTree = async (
|
|
requested: string,
|
|
refusal: { readonly operation: string; readonly field: string },
|
|
): Promise<DesktopOutputPlan> => {
|
|
try {
|
|
if (!isAbsolute(requested))
|
|
throw new SafeOutputTreeDestinationRefusal(
|
|
"Output root must be absolute",
|
|
);
|
|
if (basename(requested) === ".." || basename(requested) === ".")
|
|
throw new SafeOutputTreeDestinationRefusal("Invalid output directory");
|
|
const physical = await canonicalCallerPath(requested);
|
|
const absolute = absoluteCallerPath(requested);
|
|
const selected =
|
|
absolute.length > 1 ? absolute.replace(/\/$/u, "") : absolute;
|
|
const existing = await lstat(selected).then(
|
|
(value) => value,
|
|
(cause: unknown) => {
|
|
if ((cause as NodeJS.ErrnoException).code === "ENOENT")
|
|
return undefined;
|
|
throw cause;
|
|
},
|
|
);
|
|
if (existing?.isSymbolicLink())
|
|
throw new SafeOutputTreeDestinationRefusal(
|
|
"Output root cannot be a symbolic link",
|
|
);
|
|
if (existing !== undefined && !existing.isDirectory())
|
|
throw new SafeOutputTreeDestinationRefusal(
|
|
"Output root must be a directory",
|
|
);
|
|
if (existing !== undefined && (await readdir(selected)).length > 0)
|
|
throw new SafeOutputTreeDestinationRefusal(
|
|
"Output directory is not empty",
|
|
);
|
|
// Publication writes into the folder, or creates it (and any missing
|
|
// parents) under its nearest existing ancestor, then opens the folder's
|
|
// parent to sync it. Check those accesses now rather than only when the
|
|
// tree is written; parents publication creates itself are owner-only.
|
|
const parent = dirname(physical);
|
|
const writable =
|
|
existing === undefined ? await nearestExisting(physical) : physical;
|
|
await access(writable, constants.W_OK | constants.X_OK).catch(
|
|
(cause: unknown) => {
|
|
throw new SafeOutputTreeDestinationRefusal(
|
|
existing === undefined
|
|
? "Output parent is not writable"
|
|
: "Output directory is not writable",
|
|
{ cause },
|
|
);
|
|
},
|
|
);
|
|
if (existing !== undefined || writable === parent)
|
|
await access(parent, constants.R_OK).catch((cause: unknown) => {
|
|
throw new SafeOutputTreeDestinationRefusal(
|
|
"Output parent is not readable",
|
|
{ cause },
|
|
);
|
|
});
|
|
return Object.freeze({ requested, physical });
|
|
} catch (cause: unknown) {
|
|
const error =
|
|
cause instanceof SafeOutputTreeDestinationRefusal
|
|
? cause
|
|
: new SafeOutputTreeDestinationRefusal(
|
|
"Output destination cannot be resolved",
|
|
{ cause },
|
|
);
|
|
throw outputDirectoryAdmissionRefusal(
|
|
refusal.operation,
|
|
refusal.field,
|
|
error,
|
|
);
|
|
}
|
|
};
|
|
|
|
/** Observe cancellation at an output-owned checkpoint without interpreting a caught cause. */
|
|
const outputCancellation = (
|
|
operation: string,
|
|
signal: AbortSignal | undefined,
|
|
) => (signal?.aborted === true ? cancelledBy(operation, signal) : undefined);
|
|
|
|
/**
|
|
* Write a new or empty folder through the safe output tree, rolling an
|
|
* unpublished tree back on any failure so no partial copy remains. A
|
|
* published tree is kept; its cleanup and cancellation facts are returned. A
|
|
* refused destination names the caller's `field` under `operation`.
|
|
*/
|
|
export const writeOutputTree = async (
|
|
plan: DesktopOutputPlan,
|
|
write: (tree: SafeOutputTree) => Promise<void>,
|
|
refusal: { readonly operation: string; readonly field: string },
|
|
signal: AbortSignal | undefined,
|
|
): Promise<DesktopOutputCompletion> => {
|
|
const cancelled = outputCancellation(refusal.operation, signal);
|
|
if (cancelled !== undefined) throw cancelled;
|
|
const resources = new ArtifactResourceScope();
|
|
let tree: SafeOutputTree | undefined;
|
|
let outcome:
|
|
| { readonly kind: "completed" }
|
|
| { readonly kind: "failed"; readonly cause: unknown };
|
|
try {
|
|
try {
|
|
tree = await SafeOutputTree.create(
|
|
plan.physical,
|
|
HOST_PLATFORM.platform,
|
|
{ acceptExistingEmpty: true, createParents: true },
|
|
);
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
|
|
throw cause;
|
|
}
|
|
await write(tree);
|
|
await tree.commit(signal);
|
|
outcome = { kind: "completed" };
|
|
} catch (cause: unknown) {
|
|
outcome = { kind: "failed", cause };
|
|
}
|
|
if (tree !== undefined) {
|
|
const released = await resources.release({
|
|
kind: "output-tree",
|
|
resource: plan.requested,
|
|
tree,
|
|
});
|
|
if (tree.published)
|
|
return {
|
|
kind: "published",
|
|
release: released.kind === "failed" ? released : undefined,
|
|
cancellation: outputCancellation(refusal.operation, signal),
|
|
};
|
|
if (released.kind === "failed")
|
|
throw resources.cleanupFailure(outcome, [released]);
|
|
}
|
|
if (outcome.kind === "failed")
|
|
throw outputDirectoryAdmissionRefusal(
|
|
refusal.operation,
|
|
refusal.field,
|
|
outcome.cause,
|
|
);
|
|
throw new Error("Output tree completed without publication");
|
|
};
|
|
|
|
/** Project publication facts after the caller has its complete Evidence. */
|
|
export const desktopOutputFailure = (
|
|
context: {
|
|
readonly provider: string;
|
|
readonly operation: string;
|
|
readonly what: string;
|
|
},
|
|
directory: string,
|
|
completion: DesktopOutputCompletion,
|
|
evidence?: Evidence,
|
|
): AnalysisError | undefined => {
|
|
const { release, cancellation } = completion;
|
|
if (cancellation !== undefined && evidence !== undefined)
|
|
cancellation.retainPartialObservation(evidence);
|
|
if (release === undefined) return cancellation;
|
|
const reason = errorMessage(release.cause);
|
|
const error = new ProviderAdapterError(context.provider, context.operation, {
|
|
cause: release.cause,
|
|
userMessage: `The ${context.what} was written to ${directory} and is complete, but its output handles could not be closed: ${reason}.`,
|
|
remediationAction: `Use the written ${context.what}; the handles are released when this process exits.`,
|
|
cleanup: { reason, resources: [directory] },
|
|
...(evidence === undefined ? {} : { partialObservation: evidence }),
|
|
diagnostics: { output_directory: directory },
|
|
});
|
|
release.lease.bindCleanupError(error);
|
|
return cancellation === undefined
|
|
? error
|
|
: analysisErrorWithCancellation(error, cancellation);
|
|
};
|