mirror of
https://github.com/morluto/rea.git
synced 2026-12-06 14:59:05 +00:00
* fix(process): settle worker, scope, and capture retries against close - Return before posting a regex job that was cancelled before dispatch, and report a stop failure even when the match itself succeeded. - Keep a worker runtime closed when start races a cleanup retry, and let sibling retries wait instead of reporting runtime_closing. - Ignore owners a concurrent release settled while a scope drained. - Check scope closure before waiting on a drain, and send SIGKILL once. - Share one ASAR snapshot open across concurrent readers so a cancelled reader cannot close a peer's descriptor. - Keep a verified staged-output identity across close retries, and stop the stdio transport from counting or reading after close or repeating its input end and onclose on retry. - Clear a file deadline's timer when it ends. * fix(artifacts): close a cancelled ASAR snapshot handle before publishing it Snapshot acquisition is already serialized by the operation queue. The shared open published the descriptor and then returned cancellation without closing it, so the boundary test still saw a live fd. Close that handle before it is published and drop the duplicate waiter state. * fix(process): end the capture wait when a direct SIGKILL throws The direct kill paths recorded killSent and then called unobservedExit, which returned while finalization had not started. Settle that wait as unobserved with the initiating reason and no exit code or finalization record, including the zero-interval deadline path. * fix(process): notify stdio close once after a natural server exit Exit and output-close called onclose without the close flag, so a later close() sent it again. Route exit, output close, and explicit close through one notifier. * test(process): cover post-acquisition abort and drain-time release Abort after an idle worker is acquired and before dispatch, and fail a scope owner during drain before a concurrent release succeeds. Those are the paths the close-against-retry fixes change. * fix(domain): remember sealed JSON identities weakly The per-call completed set retained every finished row, so sealing an object-heavy Evidence tree exceeded the ancestry budget. A WeakSet still seals a shared subtree once, and the strong set stays the active ancestry. * test(resources): release the drain gate if an assertion fails The drain regression held owner2 until after its assertions. A failed barrier left close waiting. Release the gate and join close in finally. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
203 lines
6.5 KiB
TypeScript
203 lines
6.5 KiB
TypeScript
import { StagedOutputError } from "./StagedOutputError.js";
|
|
import { lstat, readdir, rmdir, unlink } from "node:fs/promises";
|
|
import type { Stats } from "node:fs";
|
|
|
|
import { OwnedFileHandle } from "./OwnedFileHandle.js";
|
|
|
|
interface Identity {
|
|
readonly dev: number;
|
|
readonly ino: number;
|
|
}
|
|
|
|
const identityOf = (stats: Stats): Identity => ({
|
|
dev: stats.dev,
|
|
ino: stats.ino,
|
|
});
|
|
|
|
const sameIdentity = (stats: Stats, identity: Identity): boolean =>
|
|
stats.dev === identity.dev && stats.ino === identity.ino;
|
|
|
|
/** One atomically staged file and directory retained through verified cleanup. */
|
|
export class OwnedStagedOutput {
|
|
#file: OwnedFileHandle | undefined;
|
|
#fileIdentity: Identity | undefined;
|
|
#fileClosed = false;
|
|
#fileRemovedByOwner = false;
|
|
#publishedRename = false;
|
|
#closeFileAttempt: Promise<void> | undefined;
|
|
#closeAttempt: Promise<void> | undefined;
|
|
#closed = false;
|
|
#identityFailure: unknown;
|
|
|
|
private constructor(
|
|
readonly directory: string,
|
|
private readonly directoryIdentity: Identity | undefined,
|
|
) {}
|
|
|
|
static async create(directory: string): Promise<OwnedStagedOutput> {
|
|
try {
|
|
const stats = await lstat(directory);
|
|
if (!stats.isDirectory() || stats.isSymbolicLink())
|
|
return new OwnedStagedOutput(directory, undefined);
|
|
return new OwnedStagedOutput(directory, identityOf(stats));
|
|
} catch (cause: unknown) {
|
|
// Keep an owner that refuses deletion when creation identity is unknown.
|
|
const owner = new OwnedStagedOutput(directory, undefined);
|
|
owner.#identityFailure = cause;
|
|
return owner;
|
|
}
|
|
}
|
|
|
|
setFile(file: OwnedFileHandle): void {
|
|
if (this.#file !== undefined)
|
|
throw new StagedOutputError("handle_already_owned");
|
|
this.#file = file;
|
|
}
|
|
|
|
/** Verify the staged name against its descriptor after the last write. */
|
|
async assertReadyForPublication(content: string): Promise<void> {
|
|
await this.#verifiedDirectory();
|
|
if (this.#file !== undefined && !this.#fileClosed)
|
|
await this.#observeFileIdentity();
|
|
if (this.#fileIdentity === undefined)
|
|
throw new StagedOutputError("identity_unverified", undefined, {
|
|
cause: this.#identityFailure,
|
|
});
|
|
const stagedFile = await lstat(content);
|
|
if (
|
|
!stagedFile.isFile() ||
|
|
stagedFile.isSymbolicLink() ||
|
|
!sameIdentity(stagedFile, this.#fileIdentity)
|
|
)
|
|
throw new StagedOutputError("identity_changed", { path: content });
|
|
}
|
|
|
|
/** Observe the descriptor's identity after its last write, then close it. */
|
|
closeFile(): Promise<void> {
|
|
const file = this.#file;
|
|
if (file === undefined || this.#fileClosed) return Promise.resolve();
|
|
if (this.#closeFileAttempt !== undefined) return this.#closeFileAttempt;
|
|
const attempt = (async () => {
|
|
await this.#observeFileIdentity();
|
|
await file.close();
|
|
this.#fileClosed = true;
|
|
})().finally(() => {
|
|
if (this.#closeFileAttempt === attempt)
|
|
this.#closeFileAttempt = undefined;
|
|
});
|
|
this.#closeFileAttempt = attempt;
|
|
return attempt;
|
|
}
|
|
|
|
async #observeFileIdentity(): Promise<void> {
|
|
const file = this.#file;
|
|
if (file === undefined) return;
|
|
// FAT and exFAT assign a file ID when the first write allocates storage,
|
|
// so only the descriptor's final identity can prove the staged pathname.
|
|
try {
|
|
this.#fileIdentity = identityOf(await file.handle.stat());
|
|
this.#identityFailure = undefined;
|
|
} catch (cause: unknown) {
|
|
// Preserve an already-verified post-write identity across cleanup retries;
|
|
// only record the failure if identity has never been observed yet.
|
|
this.#identityFailure = cause;
|
|
}
|
|
}
|
|
|
|
/** Record that the staged file moved to the published destination by rename. */
|
|
recordPublishedRename(): void {
|
|
this.#publishedRename = true;
|
|
}
|
|
|
|
/** Close the owned descriptor and remove only the exact staged entries. */
|
|
close(): Promise<void> {
|
|
if (this.#closed) return Promise.resolve();
|
|
if (this.#closeAttempt !== undefined) return this.#closeAttempt;
|
|
const attempt = Promise.resolve().then(() => this.#cleanup());
|
|
this.#closeAttempt = attempt;
|
|
void attempt.then(
|
|
() => {
|
|
this.#closed = true;
|
|
this.#closeAttempt = undefined;
|
|
},
|
|
() => {
|
|
this.#closeAttempt = undefined;
|
|
},
|
|
);
|
|
return attempt;
|
|
}
|
|
|
|
async #cleanup(): Promise<void> {
|
|
await this.closeFile();
|
|
await this.#verifiedDirectory();
|
|
|
|
// No descriptor was acquired when creating /content failed. Enumerate
|
|
// the owned directory instead of probing a possibly overlong child path.
|
|
if (this.#file !== undefined) {
|
|
const content = `${this.directory}/content`;
|
|
let stagedFile: Stats | undefined;
|
|
try {
|
|
stagedFile = await lstat(content);
|
|
} catch (cause: unknown) {
|
|
if (
|
|
errorCode(cause) === "ENOENT" &&
|
|
(this.#fileRemovedByOwner || this.#publishedRename)
|
|
) {
|
|
stagedFile = undefined;
|
|
} else if (errorCode(cause) === "ENOENT") {
|
|
throw new StagedOutputError(
|
|
"file_disappeared",
|
|
{ path: content },
|
|
{ cause },
|
|
);
|
|
} else {
|
|
throw cause;
|
|
}
|
|
}
|
|
if (stagedFile !== undefined) {
|
|
if (
|
|
!stagedFile.isFile() ||
|
|
stagedFile.isSymbolicLink() ||
|
|
this.#fileIdentity === undefined ||
|
|
!sameIdentity(stagedFile, this.#fileIdentity)
|
|
)
|
|
throw new StagedOutputError("identity_changed", { path: content });
|
|
await unlink(content);
|
|
this.#fileRemovedByOwner = true;
|
|
}
|
|
}
|
|
|
|
const remaining = await readdir(this.directory);
|
|
if (remaining.length > 0)
|
|
throw new StagedOutputError("unexpected_entries", {
|
|
count: remaining.length,
|
|
entries: remaining.join(","),
|
|
});
|
|
await this.#verifiedDirectory();
|
|
await rmdir(this.directory);
|
|
}
|
|
|
|
async #verifiedDirectory(): Promise<void> {
|
|
if (this.directoryIdentity === undefined)
|
|
throw new StagedOutputError(
|
|
"directory_unverified",
|
|
{ directory: this.directory },
|
|
{ cause: this.#identityFailure },
|
|
);
|
|
const directory = await lstat(this.directory);
|
|
if (
|
|
!directory.isDirectory() ||
|
|
directory.isSymbolicLink() ||
|
|
!sameIdentity(directory, this.directoryIdentity)
|
|
)
|
|
throw new StagedOutputError("directory_identity_changed", {
|
|
directory: this.directory,
|
|
});
|
|
}
|
|
}
|
|
|
|
const errorCode = (cause: unknown): unknown =>
|
|
typeof cause === "object" && cause !== null && "code" in cause
|
|
? cause.code
|
|
: undefined;
|