mirror of
https://github.com/morluto/rea.git
synced 2026-11-12 01:41:21 +00:00
* fix(desktop): preserve document URLs and value formats * fix(desktop): bound added checks and omit noisy text guards * fix(desktop): exclude unseeded locks from task checks * fix(desktop): preserve draft bounds and launch URLs * fix(desktop): render draft values using their source format * fix(desktop): preserve launch URLs and JSON draft values * fix(desktop): recognize captured file URL documents * fix(desktop): render captured file URLs for runtime home * fix(desktop): distinguish phone numbers from save metadata * fix(desktop): preserve launch URLs and user text * fix(desktop): preserve captured URLs and user text * fix(desktop): preserve local file URL authority * fix(desktop): preserve local file URL authority * fix(desktop): preserve local file URL authority * fix(desktop): render captured file URLs at launch * fix(desktop): classify numeric timestamps using field context * fix(desktop): classify numeric timestamps using field context * fix(desktop): classify numeric timestamps using field context * fix(desktop): retain context for generated draft values * fix(desktop): retain context for generated draft values * fix(desktop): retain context for generated draft values * test(desktop): cover generated IDs in text guards * test(desktop): cover generated IDs in text guards * test(desktop): cover generated IDs in text guards * fix(desktop): isolate launcher URL encoding * fix(desktop): isolate launcher URL encoding * fix(desktop): isolate launcher URL encoding * fix(desktop): isolate launcher URL encoding * fix(desktop): retain clean text in noisy record fields * fix(desktop): classify added line values in one pass * fix(desktop): apply XML quote rules to text drafts * fix(desktop): distinguish XML attributes from quoted text * fix(desktop): preserve parsed XML line context * Format appTaskChecks.ts with the pinned oxfmt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): retain partial XML syntax facts * fix(desktop): recognize markdown autolinks in drafts * fix(desktop): reuse export exclusions in task drafts * fix(desktop): report unchecked client build paths * docs(desktop): clarify gzip scrub limits * fix(desktop): reuse export exclusions in task drafts * docs(desktop): keep the judge command on one line Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(desktop): clarify gzip scrub limits * fix(setup): own desktop build process cleanup * fix(doctor): compare desktop settings with resolved defaults * style(desktop): format the noisy-record draft files with the pinned oxfmt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(desktop): give the root-array draft test its own describe The records describe grew past the 150-line lint limit with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(doctor): inspect client-recorded desktop runners * fix(doctor): reuse matching runner probes * fix(setup): propagate cancellation to desktop actions * fix(setup): stop Hopper on cancel, never report a cancelled setup ready, and keep a failed action's client setting - The Hopper install gets setup's signal: Linux already honoured it, and the macOS installer now stops its downloads and stops before mounting or copying. - runSetup checks the signal after the final doctor and close, so a cancellation there raises instead of returning ready. - A failed pack or agentenv install no longer writes its archive or runner to client configs, so the setting the client already had stays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(setup): keep the completed setup result in a cancellation after cleanup A cancellation during the final doctor or host close carried only the applied actions, dropping each client's result and backup path and the doctor report. It now carries the whole result as setup_result, as doctor's cancellation carries its report. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(desktop): move launch execution to boundary suite * fix(desktop): redact build schema failure output * refactor(desktop): normalize schema failure once * fix(desktop): omit unsafe schema parser snippets * fix(desktop): preserve draft change and selected path evidence * test(desktop): group retained dconf note regressions * fix(desktop): respect archive entry format in draft checks * test(desktop): separate unowned-file draft note cases * fix(desktop): preserve explicitly selected journal documents * fix(xml): avoid scanning selected ancestors per tag * fix(desktop): exclude covered text runs from draft counts * fix: preserve text when drafting desktop checks * fix: restore nested desktop state aliases * refactor: share UUID recognition across draft checks * fix: retain multiline XML attribute context * fix: retain relationship identifiers in task drafts * docs: clarify desktop draft identifier handling * test(desktop): type formatting run cases as pairs * fix(desktop): carry document format into selector evaluation * test(desktop): separate markup boundary regression group * fix(desktop): propagate formats through draft selectors * fix(desktop): switch selector format within archive entries * test(desktop): remove duplicate seed filename case * fix(setup): retain diagnostics when cancellation overlaps failure * refactor(setup): keep command cancellation at its owner * test(setup): verify cancellation at the application boundary * test(desktop): pass JSON format in exported index parity * docs(desktop): clarify task checks before scratch export * fix(desktop): respell selected paths in file URLs * test(desktop): group captured document spelling cases * test(desktop): pin reader-free verifier to selector parent * fix(desktop): bound draft preview serialization * fix(desktop): restore selected state aliases * fix(desktop): respect entry format in draft noise * test(desktop): match exported alias evidence at its JSON boundary * fix(desktop): retain app state logs in exported seeds * fix: align desktop numeric seed comparisons * test(desktop): keep one draft exclusion fixture import * test(desktop): retain log eligibility across draft test groups * fix(doctor): resolve empty registered desktop runner * test(desktop): check retained log seed admission * style: fix desktop launch test formatting * style: format native command path schema * fix(desktop): map selected external launch paths * style(desktop): format seed document regressions * test(desktop): group launch URL regressions * fix(desktop): omit redundant nested state aliases * fix(desktop): compare added free text as a whole * fix(desktop): check recompressed seeds as shipped * docs(desktop): clarify recovered seed format * test(desktop): group shipped gzip seed checks * fix: retain quoted identifier text in task drafts * fix: recognize Unicode XML in desktop state readers * fix(desktop): bound nested draft checks * fix(desktop): explain missing arrays in truncated views * fix(desktop): find XML type references in archives * test(desktop): remove duplicated capture assertions * fix(desktop): retain nested omitted text boundaries * style(desktop): format draft value imports * test(desktop): group model and draft value checks * fix(desktop): map captured launch paths once * refactor: remove unused whole-text guard state * refactor: stop passing unused text children * test: align free-text checks with whole-note policy * fix: validate recompressed desktop archive seeds * style(desktop): format archive seed regression * fix(desktop): retain placed-item sibling guards * fix(desktop): preserve archive paths and bound doctor reads * fix(doctor): refuse non-files before descriptor admission * fix(setup): track remaining cleanup resources across retries * test(desktop): specify XML format in heap pairing fixture * fix(desktop): compare screen task views by value * fix(desktop): reject inexact reader numbers * fix(desktop): budget export for both reader passes * fix(desktop): bound reader runner argument size * test(desktop): verify chunked reader payloads and parent output * fix(doctor): query agentenv for model endpoint * style(desktop): format reader payload assertion * fix(doctor): preserve uncertainty for empty endpoint override * fix(desktop): redact runtime schema errors * fix(desktop): normalize captured file URLs * fix(desktop): report seeded files by capture path * fix(desktop): retain startup readiness failure stage * fix(desktop): retain JSON date checks * fix(desktop): preserve archive formatting checks * fix(desktop): preserve explicitly selected journal files * fix(desktop): report build command transport limits * docs(desktop): clarify unreadable dconf versions * test(desktop): remove duplicate history regression * fix(desktop): align XML names with exported reader * fix(desktop): create selected state alias targets * fix(desktop): inspect supported runtime archives * fix(desktop): retain record identity in draft checks * fix(desktop): align timestamp selector digits * fix(desktop): scrub XML independently of reader compatibility * fix(desktop): preserve file aliases and reader diagnostics * fix(desktop): retain remote reader cleanup ownership * style(desktop): format capture review fixes * fix(desktop): retain reader leases across verifier reloads * test(desktop): overlap reader cleanup retries * fix(desktop): run long exports within exec limits --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
471 lines
15 KiB
TypeScript
471 lines
15 KiB
TypeScript
import { ProcessAdmissionError } from "./ProcessAdmissionError.js";
|
|
import { PrivateRuntimeRoot } from "./PrivateRuntimeRoot.js";
|
|
import type { Readable, Writable } from "node:stream";
|
|
import {
|
|
ProviderProcessSupervisor,
|
|
spawnOwnedProviderProcess,
|
|
type OwnedProviderProcessSpawnOptions,
|
|
type ProviderProcessSupervisorOptions,
|
|
type ProviderProcessStopResult,
|
|
} from "./ProviderProcess.js";
|
|
import { cleanupOwnedProcessGroup } from "./ProcessOwnership.js";
|
|
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
|
|
|
export interface OwnedWorkerRuntimeOptions {
|
|
readonly rootPrefix: string;
|
|
readonly launcher?: typeof spawnOwnedProviderProcess;
|
|
readonly supervisorOptions?: ProviderProcessSupervisorOptions;
|
|
/** Report request-stream failure at the lifecycle owner observation point. */
|
|
readonly onInputFailure?: (cause: Error) => void;
|
|
/** Let a higher-level owner release its dependent resources before this root. */
|
|
readonly retryCleanup?: () => Promise<void>;
|
|
/** Host that retries this runtime. Omitted runtimes share the process registry. */
|
|
readonly cleanupRegistry?: WorkerCleanupRegistry;
|
|
}
|
|
|
|
/** A resource owner that can retry its own retained cleanup. */
|
|
export interface RetainedWorkerCleanup {
|
|
retryRetainedCleanup(): Promise<void>;
|
|
}
|
|
|
|
/** Retained worker resources one host retries before admitting another child. */
|
|
export class WorkerCleanupRegistry {
|
|
readonly #pending = new Set<RetainedWorkerCleanup>();
|
|
|
|
has(runtime: RetainedWorkerCleanup): boolean {
|
|
return this.#pending.has(runtime);
|
|
}
|
|
|
|
add(runtime: RetainedWorkerCleanup): void {
|
|
this.#pending.add(runtime);
|
|
}
|
|
|
|
delete(runtime: RetainedWorkerCleanup): void {
|
|
this.#pending.delete(runtime);
|
|
}
|
|
|
|
async retry(except?: RetainedWorkerCleanup): Promise<void> {
|
|
for (const owner of [...this.#pending])
|
|
if (owner !== except) await owner.retryRetainedCleanup();
|
|
}
|
|
}
|
|
|
|
/** Runtimes that were not given a host registry. */
|
|
export const processWorkerCleanup = new WorkerCleanupRegistry();
|
|
|
|
export class OwnedWorkerRuntimeCleanupError extends Error {
|
|
readonly #cleanupEpoch: OwnedWorkerRuntimeCleanupEpoch | undefined;
|
|
|
|
constructor(
|
|
readonly cleanupResources: readonly string[],
|
|
readonly processId: number | null,
|
|
message: string,
|
|
cleanupEpoch: OwnedWorkerRuntimeCleanupEpoch | undefined,
|
|
options?: ErrorOptions,
|
|
) {
|
|
super(message, options);
|
|
this.name = "OwnedWorkerRuntimeCleanupError";
|
|
this.#cleanupEpoch = cleanupEpoch;
|
|
}
|
|
|
|
bindCleanupFailure(error: OwnedWorkerCleanupFailure | AnalysisError): void {
|
|
if (this.#cleanupEpoch === undefined) {
|
|
error.bindCleanupResourceOwner(releasedCleanupOwner);
|
|
error.resolveCleanup();
|
|
return;
|
|
}
|
|
this.#cleanupEpoch.bind(error);
|
|
}
|
|
}
|
|
|
|
export interface OwnedWorkerCleanupFailure {
|
|
bindCleanupResourceOwner(owner: {
|
|
readonly cleanupResources: readonly string[] | undefined;
|
|
}): unknown;
|
|
resolveCleanup(): unknown;
|
|
}
|
|
|
|
/** A root's cleanup attribution is stable even after this runtime is reused. */
|
|
class OwnedWorkerRuntimeCleanupEpoch {
|
|
#released = false;
|
|
#runId: string | undefined;
|
|
#failures: WeakRef<OwnedWorkerCleanupFailure>[] = [];
|
|
|
|
constructor(readonly rootPath: string) {}
|
|
|
|
get cleanupResources(): readonly string[] {
|
|
return this.#released
|
|
? []
|
|
: [...(this.#runId === undefined ? [] : [this.#runId]), this.rootPath];
|
|
}
|
|
|
|
setRunId(runId: string | undefined): void {
|
|
if (!this.#released) this.#runId = runId;
|
|
}
|
|
|
|
bind(error: OwnedWorkerCleanupFailure | AnalysisError): void {
|
|
error.bindCleanupResourceOwner(this);
|
|
if (this.#released) {
|
|
error.resolveCleanup();
|
|
return;
|
|
}
|
|
this.#failures = [
|
|
...this.#failures.filter((reference) => reference.deref() !== undefined),
|
|
new WeakRef(error),
|
|
];
|
|
}
|
|
|
|
release(): void {
|
|
if (this.#released) return;
|
|
this.#released = true;
|
|
for (const reference of this.#failures) reference.deref()?.resolveCleanup();
|
|
this.#failures = [];
|
|
}
|
|
}
|
|
|
|
/** Own the private root and process lifecycle shared by sequential workers. */
|
|
export class OwnedWorkerRuntime {
|
|
readonly #registry: WorkerCleanupRegistry;
|
|
|
|
#root: PrivateRuntimeRoot | undefined;
|
|
#cleanupEpoch: OwnedWorkerRuntimeCleanupEpoch | undefined;
|
|
#supervisor: ProviderProcessSupervisor | undefined;
|
|
#acquisition: Promise<void> | undefined;
|
|
#cleanupRetryAttempt: Promise<void> | undefined;
|
|
#stopAttempt: Promise<ProviderProcessStopResult> | undefined;
|
|
#closeAttempt: Promise<void> | undefined;
|
|
#closing = false;
|
|
#closed = false;
|
|
#lastRunId: string | undefined;
|
|
#terminalCloseRequested = false;
|
|
#inputFailure: Error | undefined;
|
|
#stdinGeneration = 0;
|
|
readonly #stdoutListeners = new Set<{
|
|
readonly stream: Readable;
|
|
readonly listener: (chunk: Buffer | string) => void;
|
|
}>();
|
|
|
|
constructor(readonly options: OwnedWorkerRuntimeOptions) {
|
|
this.#registry = options.cleanupRegistry ?? processWorkerCleanup;
|
|
}
|
|
|
|
get rootPath(): string | undefined {
|
|
return this.#root?.path;
|
|
}
|
|
|
|
/** Exposes the exact supervisor so consumers retain their protocol policy. */
|
|
get supervisor(): ProviderProcessSupervisor | undefined {
|
|
return this.#supervisor;
|
|
}
|
|
|
|
get cleanupResources(): readonly string[] | undefined {
|
|
const resources = [
|
|
...(this.#supervisor === undefined
|
|
? []
|
|
: [this.#supervisor.launch.ownership?.runId ?? this.#lastRunId]),
|
|
...(this.#root === undefined ? [] : [this.#root.path]),
|
|
].filter((resource): resource is string => resource !== undefined);
|
|
return resources.length === 0 ? [] : resources;
|
|
}
|
|
|
|
/** Whether this exact owner still retains an unconfirmed resource release. */
|
|
get hasPendingCleanup(): boolean {
|
|
return this.#registry.has(this);
|
|
}
|
|
|
|
/** First error observed on the current child's request stream, if any. */
|
|
get inputFailure(): Error | undefined {
|
|
return this.#inputFailure;
|
|
}
|
|
|
|
/** Keep a returned typed cleanup error live until this exact owner releases. */
|
|
bindCleanupFailure(error: OwnedWorkerCleanupFailure | AnalysisError): void {
|
|
if (this.#cleanupEpoch === undefined) {
|
|
error.bindCleanupResourceOwner(releasedCleanupOwner);
|
|
error.resolveCleanup();
|
|
return;
|
|
}
|
|
this.#cleanupEpoch.bind(error);
|
|
}
|
|
|
|
/** Mark this still-owned runtime for retry before any consumer starts a child. */
|
|
retainForCleanup(): void {
|
|
this.#registry.add(this);
|
|
}
|
|
|
|
/** Retry every retained runtime in this host's registry. */
|
|
retryCohort(): Promise<void> {
|
|
return this.#registry.retry();
|
|
}
|
|
|
|
/** Called by the owning registry. Not a process-wide sweep. */
|
|
retryRetainedCleanup(): Promise<void> {
|
|
return this.#retryPending();
|
|
}
|
|
|
|
/** Retry runtimes left on the process registry by owners that named no host. */
|
|
static async retryPending(except?: OwnedWorkerRuntime): Promise<void> {
|
|
await processWorkerCleanup.retry(except);
|
|
}
|
|
|
|
/**
|
|
* Acquire one child and let the protocol owner complete its own handshake.
|
|
* Close waits for this entire callback, including a late handshake.
|
|
*/
|
|
start(
|
|
spawnOptions: Omit<OwnedProviderProcessSpawnOptions, "cwd">,
|
|
initialize?: (supervisor: ProviderProcessSupervisor) => Promise<void>,
|
|
): Promise<void> {
|
|
if (this.#terminalCloseRequested || this.#closing)
|
|
return Promise.reject(new ProcessAdmissionError("runtime_closing"));
|
|
if (this.#acquisition !== undefined) return this.#acquisition;
|
|
if (this.#supervisor !== undefined && !this.#registry.has(this))
|
|
return Promise.resolve();
|
|
if (this.options.retryCleanup !== undefined && this.#registry.has(this))
|
|
return this.#retryOwnedCleanup().then(() => {
|
|
if (this.#terminalCloseRequested || this.#closing)
|
|
throw new ProcessAdmissionError("runtime_closing");
|
|
return this.start(spawnOptions, initialize);
|
|
});
|
|
const ownRetry = this.#registry.has(this)
|
|
? this.#retryPending()
|
|
: Promise.resolve();
|
|
const acquisition = ownRetry.then(async () => {
|
|
if (this.#closed) this.#closed = false;
|
|
await this.#start(spawnOptions, initialize);
|
|
});
|
|
this.#acquisition = acquisition;
|
|
void acquisition
|
|
.finally(() => {
|
|
if (this.#acquisition === acquisition) this.#acquisition = undefined;
|
|
})
|
|
.catch(() => undefined);
|
|
return acquisition;
|
|
}
|
|
|
|
/** Attach protocol stdout while ensuring it is detached before process stop. */
|
|
onStdout(listener: (chunk: Buffer | string) => void): void {
|
|
const stream = this.#supervisor?.launch.process.stdout;
|
|
if (stream === null || stream === undefined)
|
|
throw new ProcessAdmissionError("stdout_missing");
|
|
stream.on("data", listener);
|
|
this.#stdoutListeners.add({ stream, listener });
|
|
}
|
|
|
|
stop(): Promise<ProviderProcessStopResult> {
|
|
if (this.#stopAttempt !== undefined) return this.#stopAttempt;
|
|
const attempt = this.#stop();
|
|
this.#stopAttempt = attempt;
|
|
void attempt
|
|
.finally(() => {
|
|
if (this.#stopAttempt === attempt) this.#stopAttempt = undefined;
|
|
})
|
|
.catch(() => undefined);
|
|
return attempt;
|
|
}
|
|
|
|
/** Stop the exact child before releasing its root; every failure is retryable. */
|
|
close(): Promise<void> {
|
|
this.#terminalCloseRequested = true;
|
|
this.#closing = true;
|
|
if (this.#closed) return Promise.resolve();
|
|
if (this.#closeAttempt !== undefined) return this.#closeAttempt;
|
|
const attempt = this.#close();
|
|
this.#closeAttempt = attempt;
|
|
void attempt
|
|
.finally(() => {
|
|
if (this.#closeAttempt === attempt) this.#closeAttempt = undefined;
|
|
})
|
|
.catch(() => undefined);
|
|
return attempt;
|
|
}
|
|
|
|
async #retryPending(): Promise<void> {
|
|
if (this.options.retryCleanup !== undefined)
|
|
return this.#retryOwnedCleanup();
|
|
if (this.#terminalCloseRequested) return this.close();
|
|
this.#closing = true;
|
|
if (this.#closeAttempt === undefined) {
|
|
const attempt = this.#close();
|
|
this.#closeAttempt = attempt;
|
|
void attempt
|
|
.finally(() => {
|
|
if (this.#closeAttempt === attempt) this.#closeAttempt = undefined;
|
|
})
|
|
.catch(() => undefined);
|
|
}
|
|
const attempt = this.#closeAttempt;
|
|
if (attempt === undefined) return;
|
|
try {
|
|
await attempt;
|
|
if (!this.#terminalCloseRequested) {
|
|
this.#closed = false;
|
|
this.#closing = false;
|
|
}
|
|
} catch (cause: unknown) {
|
|
if (!this.#terminalCloseRequested) this.#closing = false;
|
|
throw cause;
|
|
}
|
|
}
|
|
|
|
#retryOwnedCleanup(): Promise<void> {
|
|
if (this.#cleanupRetryAttempt !== undefined)
|
|
return this.#cleanupRetryAttempt;
|
|
const attempt = Promise.resolve()
|
|
.then(() => this.options.retryCleanup?.())
|
|
.then(() => {
|
|
if (this.#registry.has(this))
|
|
throw this.#cleanupError(
|
|
"Higher-level cleanup retry returned while ownership remains pending",
|
|
);
|
|
});
|
|
this.#cleanupRetryAttempt = attempt;
|
|
void attempt
|
|
.finally(() => {
|
|
if (this.#cleanupRetryAttempt === attempt)
|
|
this.#cleanupRetryAttempt = undefined;
|
|
})
|
|
.catch(() => undefined);
|
|
return attempt;
|
|
}
|
|
|
|
async #start(
|
|
spawnOptions: Omit<OwnedProviderProcessSpawnOptions, "cwd">,
|
|
initialize:
|
|
| ((supervisor: ProviderProcessSupervisor) => Promise<void>)
|
|
| undefined,
|
|
): Promise<void> {
|
|
await this.#registry.retry(this);
|
|
if (this.#closing) throw new ProcessAdmissionError("runtime_closing");
|
|
this.#root ??= await PrivateRuntimeRoot.create({
|
|
prefix: this.options.rootPrefix,
|
|
});
|
|
this.#cleanupEpoch ??= new OwnedWorkerRuntimeCleanupEpoch(this.#root.path);
|
|
if (this.#closing) throw new ProcessAdmissionError("runtime_closing");
|
|
this.#lastRunId = spawnOptions.runId;
|
|
const spawned = await (this.options.launcher ?? spawnOwnedProviderProcess)({
|
|
...spawnOptions,
|
|
cwd: this.#root.path,
|
|
});
|
|
this.#inputFailure = undefined;
|
|
this.#observeStdin(spawned.process.stdin);
|
|
this.#cleanupEpoch.setRunId(spawned.ownership?.runId ?? spawnOptions.runId);
|
|
this.#supervisor = new ProviderProcessSupervisor(
|
|
{
|
|
...spawned,
|
|
ownsProcessLifetime: true,
|
|
cleanup:
|
|
spawned.cleanup ??
|
|
(() => cleanupOwnedProcessGroup(spawned.ownership)),
|
|
},
|
|
this.options.supervisorOptions,
|
|
);
|
|
// A close may have begun while spawn was pending. Adopt the process first;
|
|
// close waits for this acquisition and then stops the exact adopted owner.
|
|
if (this.#closing) throw new ProcessAdmissionError("runtime_closing");
|
|
await initialize?.(this.#supervisor);
|
|
if (this.#closing) throw new ProcessAdmissionError("runtime_closing");
|
|
}
|
|
|
|
async #stop(): Promise<ProviderProcessStopResult> {
|
|
const acquisition = this.#acquisition;
|
|
if (acquisition !== undefined) await acquisition.catch(() => undefined);
|
|
const supervisor = this.#supervisor;
|
|
if (supervisor === undefined) return { status: "already-exited" };
|
|
this.#detachStdout();
|
|
const stopped = await supervisor.stop();
|
|
if (stopped.status === "incomplete") {
|
|
this.#registry.add(this);
|
|
const stdin = supervisor.launch.process.stdin;
|
|
if (
|
|
stdin !== undefined &&
|
|
stdin !== null &&
|
|
!stdin.destroyed &&
|
|
!stdin.writableEnded
|
|
) {
|
|
try {
|
|
stdin.end();
|
|
} catch {
|
|
// Closing stdin is cooperative only; retain the original stop failure.
|
|
}
|
|
}
|
|
return stopped;
|
|
}
|
|
supervisor.dispose();
|
|
this.#supervisor = undefined;
|
|
this.#cleanupEpoch?.setRunId(undefined);
|
|
return stopped;
|
|
}
|
|
|
|
async #close(): Promise<void> {
|
|
const acquisition = this.#acquisition;
|
|
if (acquisition !== undefined) await acquisition.catch(() => undefined);
|
|
const stopped = await this.stop();
|
|
if (stopped.status === "incomplete")
|
|
throw this.#cleanupError(stopped.reason);
|
|
if (this.#root !== undefined) {
|
|
try {
|
|
await this.#root.close();
|
|
this.#root = undefined;
|
|
this.#cleanupEpoch?.release();
|
|
this.#cleanupEpoch = undefined;
|
|
} catch (cause: unknown) {
|
|
this.#registry.add(this);
|
|
throw this.#cleanupError(message(cause), cause);
|
|
}
|
|
}
|
|
this.#closed = true;
|
|
this.#registry.delete(this);
|
|
}
|
|
|
|
#detachStdout(): void {
|
|
for (const { stream, listener } of this.#stdoutListeners)
|
|
stream.off("data", listener);
|
|
this.#stdoutListeners.clear();
|
|
}
|
|
|
|
#observeStdin(stream: Writable | null | undefined): void {
|
|
if (stream === null || stream === undefined) return;
|
|
const generation = ++this.#stdinGeneration;
|
|
const onError = (cause: unknown): void => {
|
|
if (
|
|
generation !== this.#stdinGeneration ||
|
|
this.#inputFailure !== undefined
|
|
)
|
|
return;
|
|
this.#inputFailure =
|
|
cause instanceof Error
|
|
? cause
|
|
: new ProcessAdmissionError("request_stream_failed", undefined, {
|
|
cause,
|
|
});
|
|
this.options.onInputFailure?.(this.#inputFailure);
|
|
};
|
|
const onClose = (): void => {
|
|
stream.off("error", onError);
|
|
stream.off("close", onClose);
|
|
};
|
|
stream.on("error", onError);
|
|
stream.once("close", onClose);
|
|
}
|
|
|
|
#cleanupError(
|
|
reason: string,
|
|
cause?: unknown,
|
|
): OwnedWorkerRuntimeCleanupError {
|
|
const resources = this.cleanupResources ?? [];
|
|
return new OwnedWorkerRuntimeCleanupError(
|
|
resources,
|
|
this.#supervisor?.launch.process.pid ?? null,
|
|
reason,
|
|
this.#cleanupEpoch,
|
|
cause === undefined ? undefined : { cause },
|
|
);
|
|
}
|
|
}
|
|
|
|
const releasedCleanupOwner = { cleanupResources: [] } as const;
|
|
|
|
const message = (cause: unknown): string =>
|
|
cause instanceof Error ? cause.message : String(cause);
|