mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 21:21:27 +01:00
Fix retained Photon sender cleanup retries
This commit is contained in:
1 parent
7b067f0f1a
commit
bec72da0e4
6 files changed
+188
-41
No files matched your search
@@ -29,6 +29,7 @@ import * as photonClients from "../../services/photon/owned-client.js";
|
||||
import * as cloudConnectors from "../../services/paperclip-cloud-connector.js";
|
||||
import { createDeliveryWorkCoordinator } from "../../services/delivery-work-coordinator.js";
|
||||
import { idleWorkSnapshot } from "../../services/task-admission.js";
|
||||
import { notifyChatReceiver } from "../../services/chat-channels/runtime/receiver-work-notifications.js";
|
||||
|
||||
import { createPhotonExternalStore } from "../../services/chat-channels/imessage-photon/external-store.js";
|
||||
import { createPhotonExternalOwner, PhotonLocalResources } from "../../services/chat-channels/imessage-photon/external-owner.js";
|
||||
@@ -759,6 +760,96 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
|
||||
await expect(c.service.configure(c.endpoint.id, { action: "remove" }, f.userId)).rejects.toMatchObject({ status: 409 });
|
||||
});
|
||||
|
||||
|
||||
async function unrecordedSenderFixture() {
|
||||
const persistenceFailure = new Error("controlled sender debt transaction rollback");
|
||||
const closeFailure = new Error("controlled exact useful close failure");
|
||||
let failDebtWrite = false, closeFails = false;
|
||||
const debtWrites: number[] = [], normalStore = photonStores.createPhotonExternalStore;
|
||||
vi.spyOn(photonStores, "createPhotonExternalStore").mockImplementation(database => {
|
||||
const store = normalStore(database), retained = store.retained.bind(store);
|
||||
return { ...store, retained: async (...args: Parameters<typeof store.retained>) => retained(args[0], current => {
|
||||
const next = args[1](current);
|
||||
if (failDebtWrite && next.failure?.code === "sender_close") { debtWrites.push(Date.now()); throw persistenceFailure; }
|
||||
return next;
|
||||
}, args[2]) };
|
||||
});
|
||||
const c = await managedConfiguration(), control = photonFixture();await c.reconstructExternal(control);
|
||||
const runtime = c.runtime.get(c.endpoint.id);if (!runtime) throw new Error("normal retained sender runtime absent");
|
||||
const adapter = runtime.getProviderAdapter();if (!(adapter instanceof PhotonChatAdapter)) throw new Error("normal Photon adapter absent");
|
||||
control.client.close.mockImplementation(async () => { if (closeFails) throw closeFailure; });
|
||||
const text = "Controlled successful useful result before unrecorded close debt",messageId = randomUUID();
|
||||
const action = vi.fn(async (client: ReturnType<typeof photonFixture>["adapter"]["client"]) => client.messages.sendText(control.chat.guid,text,{clientMessageId:messageId}));
|
||||
return { c, control, adapter, action, text, debtWrites, persistenceFailure,
|
||||
arm(){failDebtWrite=true;closeFails=true;},restorePersistence(){failDebtWrite=false;},restoreClose(){closeFails=false;},
|
||||
invoke:()=>adapter.withClient(action),
|
||||
assertSingleSend(){expect(action).toHaveBeenCalledTimes(1);expect(control.client.messages.sendText.mock.calls.filter(call=>call[1]===text)).toHaveLength(1);},
|
||||
};
|
||||
}
|
||||
it("normal receiver recovers unrecorded sender close debt after SQL restoration without repeating its successful provider action", async () => {
|
||||
// Normal service/Runtime/adapter/client queue and locked SQL transaction.
|
||||
// Only unary provider result, local close and transaction failure are controlled.
|
||||
const t=await unrecordedSenderFixture();let primary:{error:unknown}|undefined,coordinator:ReturnType<typeof createDeliveryWorkCoordinator>|undefined;
|
||||
try {
|
||||
vi.useFakeTimers({toFake:["Date","setTimeout","clearTimeout","setInterval","clearInterval"],shouldAdvanceTime:true});
|
||||
coordinator=createDeliveryWorkCoordinator({owner:db,canRun:()=>true,onError:()=>{}});coordinators.push(coordinator);
|
||||
await t.c.service.registerReceiverWork(coordinator,()=>true).ready;
|
||||
await vi.waitFor(()=>{expect(idleWorkSnapshot().active).toBe(0);expect(coordinator!.nextWakeAt()).toBeNull();},{timeout:5000});
|
||||
t.arm();const result=await t.invoke();expect(result.guid).toBeTruthy();t.assertSingleSend();
|
||||
expect(t.debtWrites.length).toBeGreaterThan(0);expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toBeNull();
|
||||
const original=readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE));if(!original?.senderResource)throw new Error("normal prebirth sender descriptor absent");
|
||||
const failedCloses=t.control.client.close.mock.calls.length;
|
||||
t.restorePersistence();t.restoreClose();
|
||||
// Restore only the controlled fault. No new message, action, explicit
|
||||
// reconcile, notify, Retry or shutdown drives this recovery.
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
await vi.waitFor(async()=>{
|
||||
expect(t.control.client.close.mock.calls.length,"unrecorded cleanup must retry through the already-idle normal receiver owner after SQL restoration").toBeGreaterThan(failedCloses);
|
||||
expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toBeNull();
|
||||
expect(idleWorkSnapshot().active).toBe(0);expect(coordinator!.nextWakeAt()).toBeNull();
|
||||
},{timeout:5000});
|
||||
const after=readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE));expect(after?.senderResource?.id).toBe(original.senderResource.id);
|
||||
expect(after?.identity).toEqual(original.identity);expect(after?.binding).toEqual(original.binding);t.assertSingleSend();
|
||||
}catch(error){primary={error};}
|
||||
finally{
|
||||
t.restorePersistence();t.restoreClose();const cleanup:unknown[]=[];
|
||||
try{await coordinator?.stop();}catch(error){cleanup.push(error);}vi.useRealTimers();
|
||||
try{await t.c.runtime.removeEndpoint(t.c.endpoint.id);}catch(error){cleanup.push(error);}
|
||||
try{await t.control.adapter.disconnect();}catch(error){cleanup.push(error);}
|
||||
if(cleanup.length)throw new AggregateError([...(primary?[primary.error]:[]),...cleanup],"normal unrecorded sender cleanup remains owned");
|
||||
}
|
||||
if(primary)throw primary.error;
|
||||
});
|
||||
|
||||
|
||||
it("unrecorded sender debt respects normal worker error backoff and a future durable failure deadline", async () => {
|
||||
const t=await unrecordedSenderFixture();let primary:{error:unknown}|undefined,coordinator:ReturnType<typeof createDeliveryWorkCoordinator>|undefined;
|
||||
try{
|
||||
vi.useFakeTimers({toFake:["Date","setTimeout","clearTimeout","setInterval","clearInterval"],shouldAdvanceTime:true});
|
||||
const errors:unknown[]=[];coordinator=createDeliveryWorkCoordinator({owner:db,canRun:()=>true,onError:error=>errors.push(error)});coordinators.push(coordinator);
|
||||
await t.c.service.registerReceiverWork(coordinator,()=>true).ready;
|
||||
await vi.waitFor(()=>{expect(idleWorkSnapshot().active).toBe(0);expect(coordinator!.nextWakeAt()).toBeNull();},{timeout:5000});
|
||||
t.arm();await t.invoke();
|
||||
await vi.waitFor(()=>{expect(errors.length).toBeGreaterThan(0);expect(t.debtWrites.length).toBeGreaterThan(1);},{timeout:5000});
|
||||
const attempts=t.debtWrites.length,failedCloses=t.control.client.close.mock.calls.length;
|
||||
await vi.advanceTimersByTimeAsync(2000);expect(t.debtWrites).toHaveLength(attempts);expect(t.control.client.close).toHaveBeenCalledTimes(failedCloses);
|
||||
t.restorePersistence();const state=readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE));if(!state)throw new Error("normal sender state absent");
|
||||
const deadline=new Date(Date.now()+60_000).toISOString();await t.c.state.update(PHOTON_EXTERNAL_STATE,()=>({...state,failure:{code:"sender_close" as const,attempts:4,nextAttemptAt:deadline}}));
|
||||
await db.transaction(tx=>notifyChatReceiver(tx,t.c.endpoint));t.restoreClose();await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(t.control.client.close).toHaveBeenCalledTimes(failedCloses);expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toEqual({code:"sender_close",attempts:4,nextAttemptAt:deadline});
|
||||
await vi.advanceTimersByTimeAsync(30_001);
|
||||
await vi.waitFor(async()=>{expect(t.control.client.close.mock.calls.length).toBeGreaterThan(failedCloses);expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toBeNull();expect(coordinator!.nextWakeAt()).toBeNull();},{timeout:5000});t.assertSingleSend();
|
||||
}catch(error){primary={error};}
|
||||
finally{
|
||||
t.restorePersistence();t.restoreClose();const cleanup:unknown[]=[];
|
||||
try{await coordinator?.stop();}catch(error){cleanup.push(error);}vi.useRealTimers();
|
||||
try{await t.c.runtime.removeEndpoint(t.c.endpoint.id);}catch(error){cleanup.push(error);}
|
||||
try{await t.control.adapter.disconnect();}catch(error){cleanup.push(error);}
|
||||
if(cleanup.length)throw new AggregateError([...(primary?[primary.error]:[]),...cleanup],"normal sender backoff cleanup remains owned");
|
||||
}
|
||||
if(primary)throw primary.error;
|
||||
});
|
||||
|
||||
it("normal receiver retries the same useful sender close without another message and replacement never treats absence as closure", async () => {
|
||||
// Actual Runtime/adapter/useful-client, service callback and retained SQL;
|
||||
// unary result/close failures and durable unknown image are controlled ports.
|
||||
|
||||
@@ -3,7 +3,9 @@ import type { ProcessProbe } from "../../services/owner-proof.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { queryObjects } from "node:v8";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { photonFixture } from "./fixture.js";
|
||||
import * as photonClients from "../../services/photon/owned-client.js";
|
||||
import type { ChatSdkStatePersistence, ChatSdkStateRecord } from "../../services/chat-sdk-state.js";
|
||||
import { PhotonState } from "../../services/photon/state.js";
|
||||
import { PhotonUsefulClient } from "../../services/photon/useful-client.js";
|
||||
@@ -287,6 +289,31 @@ describe("Photon actual resource join and useful-channel owner", () => {
|
||||
await owner.run(async () => "first-useful-result"); await owner.run(async () => "second-useful-result");
|
||||
expect({ opens, closes }).toEqual({ opens: 2, closes: 2 }); await owner.close(); expect(closes).toBe(2);
|
||||
});
|
||||
it("lazy useful ownership joins its original client and commits the held receipt before constructing or running later useful work", async () => {
|
||||
const f = photonFixture();
|
||||
const laterClient = { ...f.client, close: vi.fn(async () => {}) };
|
||||
const create = vi.spyOn(photonClients, "createOwnedPhotonClient").mockReturnValue(laterClient as unknown as ReturnType<typeof photonClients.createOwnedPhotonClient>);
|
||||
let enterReceipt = () => {}, releaseReceipt = () => {};
|
||||
const entered = new Promise<void>(resolve => { enterReceipt = resolve; });
|
||||
const receipt = new Promise<void>(resolve => { releaseReceipt = resolve; });
|
||||
const order: string[] = [], providerAction = vi.fn(async () => { order.push("provider"); return "known-later-result"; });
|
||||
let drain: Promise<void> | undefined, useful: Promise<string> | undefined;
|
||||
try {
|
||||
// Start with the real adapter's original local client and no useful queue.
|
||||
// Drain must adopt that same object without allocating an SDK replacement.
|
||||
drain = f.adapter.drainUsefulClient(async () => { order.push("receipt-entered"); enterReceipt(); await receipt; order.push("receipt-committed"); });
|
||||
await entered;
|
||||
expect(f.client.close).toHaveBeenCalledTimes(1); expect(create).not.toHaveBeenCalled();
|
||||
useful = f.adapter.withClient(providerAction); await Promise.resolve();
|
||||
expect(create).not.toHaveBeenCalled(); expect(providerAction).not.toHaveBeenCalled(); expect(laterClient.close).not.toHaveBeenCalled();
|
||||
releaseReceipt(); await drain; expect(await useful).toBe("known-later-result");
|
||||
expect(order).toEqual(["receipt-entered", "receipt-committed", "provider"]);
|
||||
expect(create).toHaveBeenCalledTimes(1); expect(providerAction).toHaveBeenCalledTimes(1); expect(laterClient.close).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
releaseReceipt(); await Promise.allSettled([...(drain ? [drain] : []), ...(useful ? [useful] : [])]);
|
||||
try { await f.adapter.disconnect(); } finally { create.mockRestore(); f.allocation.mockRestore(); }
|
||||
}
|
||||
});
|
||||
it("known provider receipt survives cleanup refusal and old physical resource retries before new send", async () => {
|
||||
let opens = 0, closes = 0, sends = 0, debt = 0;
|
||||
const owner = new PhotonUsefulClient(() => { opens++; return { close: async () => { if (++closes === 1) throw new Error("cleanup refused"); } }; }, undefined, async () => { debt++; });
|
||||
|
||||
@@ -359,7 +359,13 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
|
||||
external = (await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).repair(external)).state;
|
||||
}
|
||||
const adapter = options.currentRuntime(id)?.getProviderAdapter();
|
||||
if (adapter instanceof PhotonChatAdapter) await adapter.drainUsefulClient();
|
||||
const drainedState = external;
|
||||
if (adapter instanceof PhotonChatAdapter) await adapter.drainUsefulClient(async () => {
|
||||
if (drainedState.failure?.code !== "sender_close") return;
|
||||
// This exact pre-drain receipt cannot erase a concurrent future hold,
|
||||
// authority/allocation/checkpoint update or a different failure.
|
||||
await store.retained(drainedState, value => ({ ...value, failure: null }));
|
||||
});
|
||||
else if (external.failure?.code === "sender_close") {
|
||||
const removed = await options.removeRuntime(id);
|
||||
const owner = createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) });
|
||||
@@ -370,7 +376,8 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
|
||||
throw new Error("Photon original sender physical closure is unknown");
|
||||
}
|
||||
}
|
||||
if (external.failure?.code === "sender_close") await store.retained(external, value => ({ ...value, failure: null }));
|
||||
if (!(adapter instanceof PhotonChatAdapter) && external.failure?.code === "sender_close")
|
||||
await store.retained(external, value => ({ ...value, failure: null }));
|
||||
return;
|
||||
}
|
||||
const runtime = await options.runtimeFor(record.endpoint, { requireDiscordOwnership: true });
|
||||
@@ -430,21 +437,22 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
|
||||
}
|
||||
};
|
||||
async function senderDebt(id: string, context?: RuntimeContext) {
|
||||
const record = await options.endpointRecord(id);
|
||||
if (!record) throw new Error("Photon sender debt has no retained endpoint");
|
||||
const runtime = options.currentRuntime(id);
|
||||
context ??= runtime ? options.context(runtime) : undefined;
|
||||
const external = await store.read({ companyId: record.endpoint.companyId, endpointId: id });
|
||||
// Debt is cleanup authority for the exact original runtime, including after
|
||||
// pause/archive fences business and the registry moves it to retiring.
|
||||
if (!external || !["external", "retiring"].includes(external.phase)
|
||||
|| !context?.endpointRuntime || options.context(context.endpointRuntime) !== context
|
||||
|| external.identity.runtimeGeneration !== context.generation
|
||||
|| external.identity.credentialReferences !== context.credentialFingerprint
|
||||
|| external.senderResource && !resources.owns(external.senderResource.id, context.endpointRuntime))
|
||||
throw new Error("Photon sender debt has no exact retained owner");
|
||||
await store.retained(external, value => ({ ...value, failure: { code: "sender_close", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } }));
|
||||
options.notify(id);
|
||||
try {
|
||||
const record = await options.endpointRecord(id);
|
||||
if (!record) throw new Error("Photon sender debt has no retained endpoint");
|
||||
const runtime = options.currentRuntime(id);
|
||||
context ??= runtime ? options.context(runtime) : undefined;
|
||||
const external = await store.read({ companyId: record.endpoint.companyId, endpointId: id });
|
||||
// Debt is cleanup authority for the exact original runtime, including after
|
||||
// pause/archive fences business and the registry moves it to retiring.
|
||||
if (!external || !["external", "retiring"].includes(external.phase)
|
||||
|| !context?.endpointRuntime || options.context(context.endpointRuntime) !== context
|
||||
|| external.identity.runtimeGeneration !== context.generation
|
||||
|| external.identity.credentialReferences !== context.credentialFingerprint
|
||||
|| external.senderResource && !resources.owns(external.senderResource.id, context.endpointRuntime))
|
||||
throw new Error("Photon sender debt has no exact retained owner");
|
||||
await store.retained(external, value => ({ ...value, failure: { code: "sender_close", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } }));
|
||||
} finally { options.notify(id); }
|
||||
}
|
||||
async function retire(id: string, cleanup?: { responsibleUserId?: string | null; reauthorize(): Promise<void> }) {
|
||||
const record = await options.endpointRecord(id), broker = options.broker();
|
||||
@@ -502,10 +510,18 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
|
||||
const closedOriginalProcess = !changedExternal && state.phase === "external" && state.failure === null
|
||||
&& state.localClosureConfirmed !== true && state.localResourceDebt?.nextAttemptAt === null
|
||||
&& await photonResourceProcessEnded(state);
|
||||
// In-memory retry hint is ONLY the exact current sender whose debt
|
||||
// has not yet reached SQL. Existing durable failure/debt deadlines win.
|
||||
const runtime = options.currentRuntime(row.endpointId), context = runtime ? options.context(runtime) : undefined;
|
||||
const adapter = runtime?.getProviderAdapter();
|
||||
const unrecordedSenderDebt = state.phase === "external" && !!state.senderResource && !state.senderResource.closed
|
||||
&& !!runtime && !!context && context.endpointRuntime === runtime && options.context(runtime) === context
|
||||
&& context.generation === state.identity.runtimeGeneration && context.credentialFingerprint === state.identity.credentialReferences
|
||||
&& resources.owns(state.senderResource.id, runtime) && adapter instanceof PhotonChatAdapter && adapter.hasUnrecordedUsefulClientDebt();
|
||||
values.push({ id: row.endpointId, companyId: row.companyId, connectionId: row.connectionId,
|
||||
dueAt: changedExternal || restoredRetirementPort || closedOriginalProcess ? 0 : state.failure ? (state.failure.nextAttemptAt ? Date.parse(state.failure.nextAttemptAt) : null)
|
||||
: state.localResourceDebt ? (state.localResourceDebt.nextAttemptAt ? Date.parse(state.localResourceDebt.nextAttemptAt) : null)
|
||||
: state.phase === "external" ? null : 0 });
|
||||
: unrecordedSenderDebt ? 0 : state.phase === "external" ? null : 0 });
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
@@ -105,7 +105,10 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
private localClient?: GrpcAdvancedIMessage;
|
||||
private usefulClient?: PhotonUsefulClient<GrpcAdvancedIMessage>;
|
||||
onUsefulClientDebt?: () => Promise<void>;
|
||||
async drainUsefulClient(): Promise<void> { await this.usefulClient?.drain(); }
|
||||
async drainUsefulClient(afterClose?: () => Promise<void>): Promise<void> {
|
||||
await this.externalClientOwner().drain(afterClose);
|
||||
}
|
||||
hasUnrecordedUsefulClientDebt(): boolean { return this.usefulClient?.hasUnrecordedCleanupDebt() ?? false; }
|
||||
private makeClient(): GrpcAdvancedIMessage {
|
||||
return createOwnedPhotonClient({ address: this.authentication.address, token: () => this.authentication.token(), tls: true,
|
||||
retry: false, autoIdempotency: false, timeout: 25_000,
|
||||
@@ -116,10 +119,16 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
if (!this.localClient) throw new Error("Photon local client is closed");
|
||||
return this.localClient;
|
||||
}
|
||||
private externalClientOwner(): PhotonUsefulClient<GrpcAdvancedIMessage> {
|
||||
if (!this.usefulClient) {
|
||||
if (!this.localClient) throw new Error("Photon useful cleanup has no original client owner");
|
||||
this.usefulClient = new PhotonUsefulClient(() => this.makeClient(), this.localClient, async () => { if (!this.onUsefulClientDebt) throw new Error("Photon physical debt owner is unavailable"); await this.onUsefulClientDebt(); });
|
||||
this.localClient = undefined;
|
||||
}
|
||||
return this.usefulClient;
|
||||
}
|
||||
async useExternalIntake(): Promise<void> {
|
||||
this.usefulClient ??= new PhotonUsefulClient(() => this.makeClient(), this.localClient, async () => { if (!this.onUsefulClientDebt) throw new Error("Photon physical debt owner is unavailable"); await this.onUsefulClientDebt(); });
|
||||
this.localClient = undefined;
|
||||
await this.usefulClient.drain();
|
||||
await this.externalClientOwner().drain();
|
||||
}
|
||||
withClient<T>(action: (client: GrpcAdvancedIMessage) => Promise<T>): Promise<T> {
|
||||
return this.usefulClient ? this.usefulClient.run(action) : action(this.client);
|
||||
|
||||
@@ -15,20 +15,22 @@ export class PhotonUsefulClient<T extends { close(): Promise<void> | void }> {
|
||||
this.client = initial;
|
||||
this.unregister = registerIdleLocalWorkProbe(() => this.failed || this.unrecordedDebt ? "unknown" : this.pending || this.client ? "present" : "none");
|
||||
}
|
||||
private async closeCurrent() {
|
||||
private async closeCurrent(afterClose?: () => Promise<void>) {
|
||||
const client = this.client;
|
||||
if (!client) {
|
||||
if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; }
|
||||
return;
|
||||
if (client) {
|
||||
try { await client.close(); this.client = undefined; this.failed = false; }
|
||||
catch (error) {
|
||||
this.failed = true; this.unrecordedDebt = true;
|
||||
try { await this.recordDebt(); this.unrecordedDebt = false; } catch { /* Exact resource stays owned and the probe remains unknown. */ }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
try { await client.close(); this.client = undefined; this.failed = false; }
|
||||
catch (error) {
|
||||
this.failed = true; this.unrecordedDebt = true;
|
||||
try { await this.recordDebt(); this.unrecordedDebt = false; } catch { /* Exact resource stays owned and the probe remains unknown. */ }
|
||||
throw error;
|
||||
}
|
||||
if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; }
|
||||
// The exact cleanup receipt substitutes for recording debt after an actual
|
||||
// successful close. A failed receipt stays pending and is not a close error.
|
||||
if (afterClose) { await afterClose(); this.unrecordedDebt = false; }
|
||||
else if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; }
|
||||
}
|
||||
hasUnrecordedCleanupDebt(): boolean { return this.unrecordedDebt; }
|
||||
private enqueue<R>(action: () => Promise<R>): Promise<R> {
|
||||
this.pending += 1;
|
||||
const result = this.tail.then(action);
|
||||
@@ -53,7 +55,7 @@ export class PhotonUsefulClient<T extends { close(): Promise<void> | void }> {
|
||||
return value;
|
||||
});
|
||||
}
|
||||
drain(): Promise<void> { return this.enqueue(() => this.closeCurrent()); }
|
||||
drain(afterClose?: () => Promise<void>): Promise<void> { return this.enqueue(() => this.closeCurrent(afterClose)); }
|
||||
close(): Promise<void> {
|
||||
this.stopped = true;
|
||||
return this.enqueue(async () => { await this.closeCurrent(); this.unregister(); });
|
||||
|
||||
@@ -185,29 +185,31 @@ export async function readProcessTable(startInspector?: () => ChildProcess): Pro
|
||||
let output = "";
|
||||
let settled = false;
|
||||
let truncated = false;
|
||||
const finish = (value: ProcessObservation[] | null) => {
|
||||
const finish = (value: ProcessObservation[] | null, reason?: "timeout" | "output_limit" | "spawn_error" | "nonzero_exit", code?: string | number | null, signal?: NodeJS.Signals | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(inspectionTimeout);
|
||||
if (reason) console.error("[runner-process-inspector] " + JSON.stringify({ reason, pid: inspector.pid ?? null, code: code ?? null, signal: signal ?? null, outputLength: output.length }));
|
||||
resolve(value);
|
||||
};
|
||||
const inspectionTimeout = setTimeout(() => {
|
||||
inspector.kill("SIGKILL");
|
||||
finish(null);
|
||||
finish(null, "timeout");
|
||||
}, 5_000);
|
||||
inspectionTimeout.unref();
|
||||
inspector.stdout?.setEncoding("utf8").on("data", (chunk: string) => {
|
||||
if (output.length + chunk.length > 1024 * 1024) {
|
||||
truncated = true;
|
||||
inspector.kill("SIGKILL");
|
||||
finish(null);
|
||||
finish(null, "output_limit");
|
||||
return;
|
||||
}
|
||||
output += chunk;
|
||||
});
|
||||
inspector.once("error", () => finish(null));
|
||||
inspector.once("close", (code) => {
|
||||
if (code !== 0 || truncated) { finish(null); return; }
|
||||
inspector.once("error", (error: NodeJS.ErrnoException) => finish(null, "spawn_error",
|
||||
["EAGAIN", "EMFILE", "ENFILE", "ENOENT", "EACCES", "EPERM"].includes(error.code ?? "") ? error.code : "other"));
|
||||
inspector.once("close", (code, signal) => {
|
||||
if (code !== 0 || truncated) { finish(null, truncated ? "output_limit" : "nonzero_exit", code, signal); return; }
|
||||
const observations = output
|
||||
.split(/\r?\n/)
|
||||
.map((line) =>
|
||||
|
||||
Reference in new issue
Block a user