Files
reverse-engineering-anything/src/browser/WebArtifactCleanup.ts
T
morluto 5f718ce30e refactor(kernel): give error-message, byte-hex and SHA-256 hex helpers one owner in a new src/kernel layer (#11542)
* 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)
2026-11-16 07:05:30 +08:00

171 lines
5.0 KiB
TypeScript

import {
AnalysisCleanupLease,
AnalysisCleanupLeaseGroup,
ArtifactReaderFailure,
type ArtifactResourceScope,
} from "../resources/index.js";
import type { WebScriptArtifactPort } from "../ports/WebScriptArtifactPort.js";
import { LocalWebScriptArtifacts } from "./assets/LocalWebScriptArtifacts.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { errorMessage } from "../kernel/errorMessage.js";
type WebArtifactOwner =
| "web-source-location-artifacts"
| "web-module-artifacts";
const cleanupOwner = (resource: string, close: () => Promise<void>) => {
let retained: readonly string[] = [resource];
const lease = new AnalysisCleanupLease(
async () => {
try {
await close();
} catch (cause: unknown) {
if (cause instanceof AnalysisError) lease.bindCleanupError(cause);
retained =
cause instanceof AnalysisError && cause.cleanupResources.length > 0
? cause.cleanupResources
: ArtifactReaderFailure.cleanupObservation(cause, resource)
.resources;
throw cause;
}
},
{
get cleanupResources() {
return retained;
},
},
);
return { resource, lease };
};
/** Retain each composed artifact owner's release across partial cleanup retries. */
export class WebArtifactCleanup {
readonly #owners: readonly {
readonly resource: string;
readonly lease: AnalysisCleanupLease;
}[];
readonly #operation: string;
constructor(
private readonly owner: WebArtifactOwner,
resources: ArtifactResourceScope,
scripts: WebScriptArtifactPort,
) {
const sourceLocation = owner === "web-source-location-artifacts";
this.#operation = sourceLocation
? "trace_web_source_location"
: "trace_web_module_imports";
const resource = sourceLocation
? "web source-location artifacts"
: "web module artifacts";
const closeScript =
scripts instanceof LocalWebScriptArtifacts &&
scripts.resources === resources
? undefined
: scripts.close?.bind(scripts);
this.#owners = [
cleanupOwner(resource, () => resources.close()),
...(closeScript === undefined
? []
: [cleanupOwner("web scripts", closeScript)]),
];
}
async close(): Promise<void> {
const pending = this.#owners.filter(({ lease }) => !lease.released);
const results = await Promise.allSettled(
pending.map(({ lease }) => lease.release()),
);
const failures = results.flatMap((result, index) =>
result.status === "rejected"
? [{ cause: result.reason as unknown, ...pending[index]! }]
: [],
);
const error = webArtifactCleanupFailures(
this.owner,
this.#operation,
failures,
);
if (error !== undefined) {
new AnalysisCleanupLeaseGroup(
error,
failures.map(({ lease }) => lease),
);
throw error;
}
}
}
const webArtifactCleanupFailures = (
owner: string,
operation: string,
failures: readonly { readonly resource: string; readonly cause: unknown }[],
): ProviderCleanupError | undefined => {
if (failures.length === 0) return undefined;
const normalized = failures.map(({ resource, cause }) => {
if (cause instanceof AnalysisError) {
const projection = projectAnalysisError(cause);
return {
cause,
projection,
observation: {
reason: projection.message,
resources:
cause.cleanupResources.length === 0
? [resource]
: cause.cleanupResources,
},
};
}
return {
cause,
projection: undefined,
observation: ArtifactReaderFailure.cleanupObservation(cause, resource),
};
});
const recoveryActions = [
...new Set(
normalized.flatMap(({ projection }) =>
projection === undefined ? [] : [projection.remediation.action],
),
),
];
return new ProviderCleanupError(
owner,
[
...new Set(
normalized.flatMap(({ observation }) => observation.resources),
),
],
{
reason: normalized
.map(({ observation }) => observation.reason)
.join("; "),
failures: normalized.map(({ cause, projection, observation }) =>
projection !== undefined
? projection
: {
name: cause instanceof Error ? cause.name : "UnknownError",
message: errorMessage(cause),
resource: [...observation.resources],
},
),
},
{
cause:
normalized.length === 1
? normalized[0]!.cause
: new AggregateError(
normalized.map(({ cause }) => cause),
`${owner} cleanup failed`,
),
operation,
...(recoveryActions.length === 0
? {}
: { remediationAction: recoveryActions.join("; ") }),
},
);
};