mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 03:33:25 +00:00
refactor(providers): finalize apktool and shared artifact resources through runOwned (#10653)
* refactor(providers): finalize apktool and shared artifact resources through runOwned runOwned moves to the provider layer so provider sites can use it without depending on application workflows. It gains a completed-value projection (partial) for values that are not themselves partial observations, an optional signal, and cleanupLeases that bind a close failure to the exact leases whose confirmed release resolves it. ArtifactAnalysisResources.finish is removed; TShark and sigrok finalize through runOwned with the shared release as close. Apktool's hand-written release, cancellation and lease-group composition is replaced by runOwned. A failed primary now keeps a cancellation observed during final cleanup as a secondary failure, as the documented precedence requires. A counted architecture guard refuses new hand-written completed-result abort reclassification outside runOwned. * refactor(adb): finalize runtime-root work through runOwned (#10660) * refactor(adb): finalize runtime-root work through runOwned The ADB runtime-root finalizer re-derived the precedence by hand and kept its own cancellation-with-cleanup combiner. It now runs through runOwned: the work body maps snapshot failures, close releases the root lease and binds its own cleanup error, and partial projects the completed execution. A cancellation whose cleanup fails is now the shared cleanup composite with the cancellation as its primary, as runOwned produces for every other owner. * refactor(providers): keep completed values as diagnostics in runOwned and migrate four finalizers (#10691) * refactor(providers): keep completed values as diagnostics in runOwned and migrate signature, Ghidra, bundle and LLDB finalization * test(providers): run the lifecycle scenarios over every runOwned adopter shape (#10707) One table of testing.md lifecycle rows runs over partial, diagnostics, publishing and lease adopters, replacing the hand-written precedence cases it covers. * chore(lint): move runOwned's classifier baseline entry with the file
This commit is contained in:
1 parent
b87b318ae7
commit
26520bd290
23 files changed
+1066
-709
No files matched your search
@@ -39,6 +39,11 @@ import {
|
||||
import { inspectEvidenceBundle } from "./investigation/InspectEvidenceBundle.js";
|
||||
import type { EvidenceRecordFilters } from "../domain/evidenceRecordSummary.js";
|
||||
import { inspectAnalysisViewValidated } from "./analysisView/AnalysisViewService.js";
|
||||
import {
|
||||
finalizedResult,
|
||||
runOwned,
|
||||
type RunOwnedOptions,
|
||||
} from "../providers/runOwned.js";
|
||||
|
||||
/** Validate a standalone bundle and report its complete record/revision counts. */
|
||||
export const importEvidenceBundleCommand = async (
|
||||
@@ -85,21 +90,25 @@ export const exportEvidenceBundleCommand = async (
|
||||
signal,
|
||||
);
|
||||
if (!loaded.ok) return loaded;
|
||||
const written = await persistEvidenceBundleCommand(
|
||||
loaded.value,
|
||||
outputPath,
|
||||
overwrite,
|
||||
signal,
|
||||
"export_evidence_bundle",
|
||||
const written = await finalizeBundleWork(
|
||||
() =>
|
||||
persistEvidenceBundleCommand(
|
||||
loaded.value,
|
||||
outputPath,
|
||||
overwrite,
|
||||
signal,
|
||||
"export_evidence_bundle",
|
||||
),
|
||||
{
|
||||
providerId: "rea",
|
||||
operation: "export_evidence_bundle",
|
||||
signal,
|
||||
// Deliver interrupts queued during publication cleanup before deciding
|
||||
// whether a written bundle survives cancellation.
|
||||
close: dispatchQueuedInterrupts,
|
||||
diagnostics: (receipt) => ({ evidence_bundle: { ...receipt } }),
|
||||
},
|
||||
);
|
||||
await dispatchQueuedInterrupts();
|
||||
if (written.ok && signal?.aborted)
|
||||
return err(
|
||||
new AnalysisCancelledError("export_evidence_bundle", {
|
||||
cause: signal.reason,
|
||||
diagnostics: { evidence_bundle: { ...written.value } },
|
||||
}),
|
||||
);
|
||||
return projectWrite(loaded.value, written);
|
||||
};
|
||||
|
||||
@@ -346,21 +355,49 @@ const withBundleReadResources = async <Value extends JsonValue>(
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<Value, AnalysisError>> => {
|
||||
const resources = new ArtifactResourceScope();
|
||||
let result: Result<Value, AnalysisError>;
|
||||
try {
|
||||
result = await read(resources);
|
||||
} finally {
|
||||
// Read errors own their retained leases and observe resolution or remaining
|
||||
// failure in place. A retry must not replace the original read failure.
|
||||
await resources.close().catch(() => undefined);
|
||||
await dispatchQueuedInterrupts();
|
||||
}
|
||||
return result.ok && signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(operation, {
|
||||
cause: signal.reason,
|
||||
diagnostics: { completed_result: result.value },
|
||||
}),
|
||||
)
|
||||
: result;
|
||||
let readFailed = false;
|
||||
return finalizeBundleWork(() => read(resources), {
|
||||
providerId: "rea",
|
||||
operation,
|
||||
signal,
|
||||
inspectPrimary: (primary) => {
|
||||
readFailed = !primary.ok;
|
||||
},
|
||||
close: async () => {
|
||||
try {
|
||||
await resources.close();
|
||||
} catch (cause: unknown) {
|
||||
// A failed read already owns its retained leases and observes their
|
||||
// resolution in place; a retry must not replace that failure. Only
|
||||
// a completed read leaves a close failure without another owner.
|
||||
if (!readFailed) throw cause;
|
||||
} finally {
|
||||
await dispatchQueuedInterrupts();
|
||||
}
|
||||
},
|
||||
fallbackResource: `${operation} bundle read resources`,
|
||||
diagnostics: (value) => ({ completed_result: value }),
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Finalize bundle work through runOwned. An unexpected throw is a defect the
|
||||
* adapters report as such, so it is rethrown after cleanup instead of being
|
||||
* typed as a provider failure.
|
||||
*/
|
||||
const finalizeBundleWork = async <Value>(
|
||||
work: () => Promise<Result<Value, AnalysisError>>,
|
||||
options: RunOwnedOptions<Value>,
|
||||
): Promise<Result<Value, AnalysisError>> => {
|
||||
let defect: { readonly cause: unknown } | undefined;
|
||||
const finalized = await runOwned(async () => {
|
||||
try {
|
||||
return await work();
|
||||
} catch (cause: unknown) {
|
||||
defect = { cause };
|
||||
throw cause;
|
||||
}
|
||||
}, options);
|
||||
if (defect !== undefined) throw defect.cause;
|
||||
return finalizedResult(finalized);
|
||||
};
|
||||
@@ -1,329 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisProtocolError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
primaryAnalysisError,
|
||||
type AnalysisError,
|
||||
type AnalysisPartialObservation,
|
||||
} from "../domain/analysisErrorBase.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { finalizedResult, runOwned } from "./runOwned.js";
|
||||
|
||||
const value: AnalysisPartialObservation = {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: "evidence-1",
|
||||
};
|
||||
const reason = { caller: "stop" };
|
||||
const completedWork = async (): Promise<
|
||||
Result<AnalysisPartialObservation, AnalysisError>
|
||||
> => ok(value);
|
||||
|
||||
/** A close that aborts the caller's signal, so cancellation lands during final cleanup. */
|
||||
const closeThenAbort =
|
||||
(controller: AbortController, failure?: unknown) => async () => {
|
||||
controller.abort(reason);
|
||||
if (failure !== undefined) throw failure;
|
||||
};
|
||||
|
||||
const options = (controller: AbortController, close: () => Promise<void>) => ({
|
||||
providerId: "fixture",
|
||||
operation: "fixture_operation",
|
||||
signal: controller.signal,
|
||||
close,
|
||||
});
|
||||
|
||||
describe("runOwned precedence", () => {
|
||||
it("completes when cleanup is released and no cancellation arrives", async () => {
|
||||
const controller = new AbortController();
|
||||
const finalized = await runOwned(
|
||||
completedWork,
|
||||
options(controller, async () => undefined),
|
||||
);
|
||||
expect(finalized).toEqual({ kind: "completed", value });
|
||||
});
|
||||
|
||||
it("cancels a completed value when cancellation arrives during final cleanup before commit", async () => {
|
||||
const controller = new AbortController();
|
||||
const finalized = await runOwned(
|
||||
completedWork,
|
||||
options(controller, closeThenAbort(controller)),
|
||||
);
|
||||
expect(finalized.kind).toBe("cancelled");
|
||||
const result = finalizedResult(finalized);
|
||||
if (result.ok) throw new Error("expected cancellation");
|
||||
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
expect(result.error.cause).toBe(reason);
|
||||
expect(result.error.partialObservation).toBe(value);
|
||||
});
|
||||
|
||||
it("keeps a committed value when cancellation arrives after the commit", async () => {
|
||||
const controller = new AbortController();
|
||||
const commits: unknown[] = [];
|
||||
const finalized = await runOwned(completedWork, {
|
||||
...options(controller, closeThenAbort(controller)),
|
||||
commit: async (committed) => {
|
||||
commits.push(committed);
|
||||
},
|
||||
});
|
||||
expect(commits).toEqual([value]);
|
||||
expect(finalized).toEqual({
|
||||
kind: "completed",
|
||||
value,
|
||||
lateCancellation: reason,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not commit after cancellation and reports it before commit", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort(reason);
|
||||
let committed = false;
|
||||
const finalized = await runOwned(completedWork, {
|
||||
...options(controller, async () => undefined),
|
||||
commit: async () => {
|
||||
committed = true;
|
||||
},
|
||||
});
|
||||
expect(committed).toBe(false);
|
||||
expect(finalized.kind).toBe("cancelled");
|
||||
});
|
||||
|
||||
it("keeps a recorded failure primary when cancellation arrives during final cleanup", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new AnalysisProtocolError("fixture failure");
|
||||
const finalized = await runOwned(
|
||||
async () => err(failure),
|
||||
options(controller, closeThenAbort(controller)),
|
||||
);
|
||||
expect(finalized.kind).toBe("failed");
|
||||
const result = finalizedResult(finalized);
|
||||
if (result.ok) throw new Error("expected failure");
|
||||
expect(primaryAnalysisError(result.error)).toBe(failure);
|
||||
expect(failure.secondaryFailures).toEqual([
|
||||
expect.objectContaining({
|
||||
_tag: "AnalysisCancelledError",
|
||||
cause: reason,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports a completed value with unconfirmed cleanup as cleanup_incomplete keeping the value", async () => {
|
||||
const controller = new AbortController();
|
||||
const finalized = await runOwned(
|
||||
completedWork,
|
||||
options(controller, async () => {
|
||||
throw new Error("close failed");
|
||||
}),
|
||||
);
|
||||
expect(finalized.kind).toBe("completed-cleanup-retained");
|
||||
const result = finalizedResult(finalized);
|
||||
if (result.ok) throw new Error("expected cleanup failure");
|
||||
expect(result.error).toBeInstanceOf(ProviderCleanupError);
|
||||
expect(result.error.cleanupIncomplete).toBe(true);
|
||||
expect(result.error.partialObservation).toBe(value);
|
||||
});
|
||||
|
||||
it("keeps the primary failure's identity when cleanup also fails", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new AnalysisProtocolError("fixture failure");
|
||||
const cleanup = new ProviderCleanupError("fixture", ["fixture-run"], {
|
||||
reason: "still running",
|
||||
});
|
||||
const finalized = await runOwned(
|
||||
async () => err(failure),
|
||||
options(controller, async () => {
|
||||
throw cleanup;
|
||||
}),
|
||||
);
|
||||
expect(finalized).toMatchObject({
|
||||
kind: "failed",
|
||||
cleanup: { kind: "retained", failure: cleanup },
|
||||
});
|
||||
const result = finalizedResult(finalized);
|
||||
if (result.ok) throw new Error("expected failure");
|
||||
expect(primaryAnalysisError(result.error)).toBe(failure);
|
||||
expect(result.error.cleanupIncomplete).toBe(true);
|
||||
});
|
||||
|
||||
it("types a thrown work failure as a provider adapter failure", async () => {
|
||||
const controller = new AbortController();
|
||||
const finalized = await runOwned(
|
||||
async () => {
|
||||
throw new Error("unexpected");
|
||||
},
|
||||
options(controller, async () => undefined),
|
||||
);
|
||||
const result = finalizedResult(finalized);
|
||||
if (result.ok) throw new Error("expected failure");
|
||||
expect(result.error._tag).toBe("ProviderAdapterError");
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies producer cancellation even when cleanup also fails", async () => {
|
||||
const controller = new AbortController();
|
||||
const cancellation = new AnalysisCancelledError("fixture_operation", {
|
||||
cause: reason,
|
||||
});
|
||||
const finalized = await runOwned(async () => err(cancellation), {
|
||||
...options(controller, async () => {
|
||||
throw new Error("still running");
|
||||
}),
|
||||
});
|
||||
expect(finalized.kind).toBe("cancelled");
|
||||
if (finalized.kind !== "cancelled") throw new Error("expected cancellation");
|
||||
expect(finalized.cleanup.kind).toBe("retained");
|
||||
expect(primaryAnalysisError(finalized.error)).toBe(cancellation);
|
||||
});
|
||||
|
||||
it("classifies a producer composite whose primary is a cancellation as cancelled", async () => {
|
||||
const controller = new AbortController();
|
||||
const cancellation = new AnalysisCancelledError("fixture_operation", {
|
||||
cause: reason,
|
||||
});
|
||||
const cleanup = new ProviderCleanupError("fixture", ["owned-process"], {
|
||||
reason: "pending",
|
||||
});
|
||||
const composite = analysisErrorWithCleanupFailure(
|
||||
cancellation,
|
||||
cleanup,
|
||||
"fixture_operation",
|
||||
).bindCleanupDependencies([cancellation, cleanup]);
|
||||
const finalized = await runOwned(
|
||||
async () => err(composite),
|
||||
options(controller, async () => {
|
||||
cleanup.resolveCleanup();
|
||||
}),
|
||||
);
|
||||
expect(finalized).toMatchObject({
|
||||
kind: "cancelled",
|
||||
error: composite,
|
||||
cleanup: { kind: "released" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a failure with a later cancellation classified as failed", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new AnalysisProtocolError("fixture failure");
|
||||
const finalized = await runOwned(
|
||||
async () => err(failure),
|
||||
options(controller, closeThenAbort(controller)),
|
||||
);
|
||||
expect(finalized.kind).toBe("failed");
|
||||
expect(failure.secondaryFailures).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps producer cleanup retained when close does not resolve it", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new ProviderCleanupError("fixture", ["owned-process"], {
|
||||
reason: "pending",
|
||||
});
|
||||
const finalized = await runOwned(
|
||||
async () => err(failure),
|
||||
options(controller, async () => undefined),
|
||||
);
|
||||
expect(finalized).toMatchObject({
|
||||
kind: "failed",
|
||||
error: failure,
|
||||
cleanup: { kind: "retained", failure },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains completed work when publication fails", async () => {
|
||||
const finalized = await runOwned(completedWork, {
|
||||
...options(new AbortController(), async () => undefined),
|
||||
commit: async () => {
|
||||
throw new Error("publication failed");
|
||||
},
|
||||
});
|
||||
const result = finalizedResult(finalized);
|
||||
if (result.ok) throw new Error("expected publication failure");
|
||||
expect(result.error.partialObservation).toBe(value);
|
||||
});
|
||||
|
||||
it("publishes recovered completion after cleanup resolves", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new ProviderCleanupError("fixture", ["owned-process"], {
|
||||
reason: "pending",
|
||||
});
|
||||
const published: AnalysisPartialObservation[] = [];
|
||||
const finalized = await runOwned(async () => err(failure), {
|
||||
...options(controller, async () => {
|
||||
failure.resolveCleanup();
|
||||
}),
|
||||
recoverCompleted: (_error, observed) =>
|
||||
observed.cleanupResolvedByClose ? { value } : undefined,
|
||||
commit: async (completed) => {
|
||||
published.push(completed);
|
||||
},
|
||||
});
|
||||
expect(published).toEqual([value]);
|
||||
expect(finalized).toEqual({ kind: "completed", value });
|
||||
});
|
||||
|
||||
it("keeps a recovered value when cancellation arrives during its publication", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new ProviderCleanupError("fixture", ["owned-process"], {
|
||||
reason: "pending",
|
||||
});
|
||||
const finalized = await runOwned(async () => err(failure), {
|
||||
...options(controller, async () => {
|
||||
failure.resolveCleanup();
|
||||
}),
|
||||
recoverCompleted: () => ({ value }),
|
||||
commit: async () => {
|
||||
controller.abort(reason);
|
||||
},
|
||||
});
|
||||
expect(finalized).toEqual({
|
||||
kind: "completed",
|
||||
value,
|
||||
lateCancellation: reason,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a cancellation that arrives while a recovered publication fails", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new ProviderCleanupError("fixture", ["owned-process"], {
|
||||
reason: "pending",
|
||||
});
|
||||
const publication = new AnalysisProtocolError("publication failed");
|
||||
const finalized = await runOwned(async () => err(failure), {
|
||||
...options(controller, async () => {
|
||||
failure.resolveCleanup();
|
||||
}),
|
||||
recoverCompleted: () => ({ value }),
|
||||
commit: async () => {
|
||||
controller.abort(reason);
|
||||
throw publication;
|
||||
},
|
||||
});
|
||||
expect(finalized.kind).toBe("failed");
|
||||
const result = finalizedResult(finalized);
|
||||
if (result.ok) throw new Error("expected publication failure");
|
||||
expect(primaryAnalysisError(result.error)).toBe(publication);
|
||||
expect(publication.secondaryFailures).toEqual([
|
||||
expect.objectContaining({ _tag: "AnalysisCancelledError", cause: reason }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains a recovered value when its publication fails", async () => {
|
||||
const failure = new ProviderCleanupError("fixture", ["owned-process"], {
|
||||
reason: "pending",
|
||||
});
|
||||
const finalized = await runOwned(async () => err(failure), {
|
||||
...options(new AbortController(), async () => {
|
||||
failure.resolveCleanup();
|
||||
}),
|
||||
recoverCompleted: () => ({ value }),
|
||||
commit: async () => {
|
||||
throw new Error("publication failed");
|
||||
},
|
||||
});
|
||||
const result = finalizedResult(finalized);
|
||||
if (result.ok) throw new Error("expected publication failure");
|
||||
expect(result.error.partialObservation).toBe(value);
|
||||
});
|
||||
@@ -1,280 +0,0 @@
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
primaryAnalysisError,
|
||||
type AnalysisPartialObservation,
|
||||
} from "../domain/analysisErrorBase.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
||||
import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
cancelledBy,
|
||||
isAborted,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
|
||||
/** What closing the work's owner established. */
|
||||
export type CleanupOutcome =
|
||||
| { readonly kind: "released" }
|
||||
| { readonly kind: "retained"; readonly failure: AnalysisError };
|
||||
|
||||
/**
|
||||
* Work, owner cleanup and cancellation composed by one precedence rule:
|
||||
* - a recorded failure stays primary; a later cancellation is attached to it;
|
||||
* - cancellation observed before commit turns a completed value into a
|
||||
* cancellation that keeps the value as its partial observation;
|
||||
* - cancellation observed after commit keeps the completed value;
|
||||
* - unconfirmed cleanup never replaces the primary. A completed value whose
|
||||
* cleanup is unconfirmed is a `cleanup_incomplete` error that keeps the
|
||||
* value as its partial observation (the documented one-shot contract).
|
||||
*/
|
||||
export type Finalized<Value> =
|
||||
| {
|
||||
readonly kind: "completed";
|
||||
readonly value: Value;
|
||||
/** A cancellation observed after the commit cutoff. */
|
||||
readonly lateCancellation?: unknown;
|
||||
}
|
||||
| {
|
||||
readonly kind: "completed-cleanup-retained";
|
||||
readonly value: Value;
|
||||
readonly error: AnalysisError;
|
||||
}
|
||||
| {
|
||||
readonly kind: "cancelled";
|
||||
readonly error: AnalysisError;
|
||||
readonly cleanup: CleanupOutcome;
|
||||
}
|
||||
| {
|
||||
readonly kind: "failed";
|
||||
readonly error: AnalysisError;
|
||||
readonly cleanup: CleanupOutcome;
|
||||
};
|
||||
|
||||
/** A completed value recovered from a failure whose only cause was cleanup. */
|
||||
export interface RecoveredCompletion<Value> {
|
||||
readonly value: Value;
|
||||
/** Diagnostics a later pre-commit cancellation carries, such as the resolved cleanup history. */
|
||||
readonly cancellationDiagnostics?: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
export interface RunOwnedOptions<Value> {
|
||||
readonly providerId: string;
|
||||
readonly operation: string;
|
||||
readonly signal: AbortSignal;
|
||||
/** Releases everything the work acquired; awaited before the signal is read. */
|
||||
readonly close: () => Promise<void>;
|
||||
/** Names the owned resources when a non-REA close failure names none. */
|
||||
readonly fallbackResource?: string;
|
||||
/**
|
||||
* Publishes a completed value. Cancellation observed before it runs cancels
|
||||
* the work; cancellation observed after it keeps the committed value.
|
||||
*/
|
||||
readonly commit?: (value: Value) => Promise<void>;
|
||||
/** Observe the primary outcome before close may change its cleanup status. */
|
||||
readonly inspectPrimary?: (primary: Result<Value, AnalysisError>) => void;
|
||||
/** Recover a completed value from a primary failure after close settled. */
|
||||
readonly recoverCompleted?: (
|
||||
primary: AnalysisError,
|
||||
observed: {
|
||||
/** The primary reported unconfirmed cleanup before close and not after. */
|
||||
readonly cleanupResolvedByClose: boolean;
|
||||
readonly cleanup: CleanupOutcome;
|
||||
},
|
||||
) => RecoveredCompletion<Value> | undefined;
|
||||
}
|
||||
|
||||
const closeFailure = (
|
||||
cause: unknown,
|
||||
options: Pick<
|
||||
RunOwnedOptions<unknown>,
|
||||
"providerId" | "operation" | "fallbackResource"
|
||||
>,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
const observation =
|
||||
cause instanceof ArtifactReaderFailure
|
||||
? ArtifactReaderFailure.cleanupObservation(
|
||||
cause,
|
||||
options.fallbackResource ?? `${options.operation} resources`,
|
||||
)
|
||||
: {
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
resources: [],
|
||||
};
|
||||
return new ProviderCleanupError(
|
||||
options.providerId,
|
||||
observation.resources,
|
||||
{ reason: observation.reason },
|
||||
{ cause, operation: options.operation },
|
||||
);
|
||||
};
|
||||
|
||||
/** Run owned work, close its owner, and apply the finalization precedence once. */
|
||||
export const runOwned = async <Value extends AnalysisPartialObservation>(
|
||||
work: () => Promise<Result<Value, AnalysisError>>,
|
||||
options: RunOwnedOptions<Value>,
|
||||
): Promise<Finalized<Value>> => {
|
||||
let primary: Result<Value, AnalysisError>;
|
||||
try {
|
||||
primary = await work();
|
||||
} catch (cause) {
|
||||
primary = {
|
||||
ok: false,
|
||||
error:
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderAdapterError(options.providerId, options.operation, {
|
||||
cause,
|
||||
}),
|
||||
};
|
||||
}
|
||||
let committed = false;
|
||||
const commit = async (
|
||||
value: Value,
|
||||
): Promise<Result<Value, AnalysisError>> => {
|
||||
try {
|
||||
await options.commit!(value);
|
||||
committed = true;
|
||||
return { ok: true, value };
|
||||
} catch (cause) {
|
||||
return {
|
||||
ok: false,
|
||||
error:
|
||||
cause instanceof AnalysisError
|
||||
? cause.retainPartialObservation(value)
|
||||
: new ProviderAdapterError(options.providerId, options.operation, {
|
||||
cause,
|
||||
partialObservation: value,
|
||||
}),
|
||||
};
|
||||
}
|
||||
};
|
||||
if (primary.ok && options.commit !== undefined && !options.signal.aborted)
|
||||
primary = await commit(primary.value);
|
||||
options.inspectPrimary?.(primary);
|
||||
const hadIncompleteCleanup = !primary.ok && primary.error.cleanupIncomplete;
|
||||
let cleanup: CleanupOutcome = { kind: "released" };
|
||||
try {
|
||||
// Owners may resolve the primary's retained cleanup during close; only
|
||||
// they can confirm it, so its status is read again afterwards.
|
||||
await options.close();
|
||||
} catch (cause) {
|
||||
cleanup = { kind: "retained", failure: closeFailure(cause, options) };
|
||||
}
|
||||
const signal = options.signal;
|
||||
let outcome:
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly value: Value;
|
||||
readonly diagnostics?: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
| { readonly ok: false; readonly error: AnalysisError } = primary;
|
||||
if (!primary.ok) {
|
||||
if (isAborted(signal))
|
||||
analysisErrorWithCancellation(
|
||||
primary.error,
|
||||
cancelledBy(options.operation, signal),
|
||||
);
|
||||
const recovered = options.recoverCompleted?.(primary.error, {
|
||||
cleanupResolvedByClose:
|
||||
hadIncompleteCleanup && !primary.error.cleanupIncomplete,
|
||||
cleanup,
|
||||
});
|
||||
if (recovered !== undefined)
|
||||
outcome = {
|
||||
ok: true,
|
||||
value: recovered.value,
|
||||
...(recovered.cancellationDiagnostics === undefined
|
||||
? {}
|
||||
: { diagnostics: recovered.cancellationDiagnostics }),
|
||||
};
|
||||
}
|
||||
if (
|
||||
outcome.ok &&
|
||||
!primary.ok &&
|
||||
options.commit !== undefined &&
|
||||
!signal.aborted
|
||||
) {
|
||||
const publication = await commit(outcome.value);
|
||||
if (!publication.ok) {
|
||||
// Publication is the last awaited step; a cancellation during it stays
|
||||
// attached to the publication failure without replacing it.
|
||||
outcome = publication;
|
||||
if (isAborted(signal))
|
||||
analysisErrorWithCancellation(
|
||||
publication.error,
|
||||
cancelledBy(options.operation, signal),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
cleanup.kind === "released" &&
|
||||
!outcome.ok &&
|
||||
outcome.error.cleanupIncomplete
|
||||
)
|
||||
cleanup = { kind: "retained", failure: outcome.error };
|
||||
// The kind follows the primary failure, so a producer's composite whose
|
||||
// primary is a cancellation is cancelled, and a failure that only retains a
|
||||
// later cancellation as a secondary stays failed.
|
||||
let cancelled =
|
||||
!outcome.ok &&
|
||||
primaryAnalysisError(outcome.error) instanceof AnalysisCancelledError;
|
||||
if (outcome.ok && isAborted(signal)) {
|
||||
if (committed && cleanup.kind === "released")
|
||||
return {
|
||||
kind: "completed",
|
||||
value: outcome.value,
|
||||
lateCancellation: signal.reason,
|
||||
};
|
||||
if (!committed) {
|
||||
cancelled = true;
|
||||
outcome = {
|
||||
ok: false,
|
||||
error: cancelledBy(options.operation, signal, {
|
||||
partialObservation: outcome.value,
|
||||
...(outcome.diagnostics === undefined
|
||||
? {}
|
||||
: { diagnostics: outcome.diagnostics }),
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
if (cleanup.kind === "retained") {
|
||||
if (outcome.ok)
|
||||
return {
|
||||
kind: "completed-cleanup-retained",
|
||||
value: outcome.value,
|
||||
error: cleanup.failure.retainPartialObservation(outcome.value),
|
||||
};
|
||||
return {
|
||||
kind: cancelled ? "cancelled" : "failed",
|
||||
error:
|
||||
cleanup.failure === outcome.error
|
||||
? outcome.error
|
||||
: analysisErrorWithCleanupFailure(
|
||||
outcome.error,
|
||||
cleanup.failure,
|
||||
options.operation,
|
||||
).bindCleanupDependencies([outcome.error, cleanup.failure]),
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
if (outcome.ok) return { kind: "completed", value: outcome.value };
|
||||
return {
|
||||
kind: cancelled ? "cancelled" : "failed",
|
||||
error: outcome.error,
|
||||
cleanup,
|
||||
};
|
||||
};
|
||||
|
||||
/** The single Result a caller sees for a finalized outcome. */
|
||||
export const finalizedResult = <Value>(
|
||||
finalized: Finalized<Value>,
|
||||
): Result<Value, AnalysisError> =>
|
||||
finalized.kind === "completed"
|
||||
? { ok: true, value: finalized.value }
|
||||
: { ok: false, error: finalized.error };
|
||||
Reference in new issue
Block a user