fix(photon): retain close receipts before later useful work

This commit is contained in:
Dotta committed 2026-11-12 04:13:43 -06:00
1 parent 10c5a89ebf
commit 5eb6626624
6 files changed
+259 -26

No files matched your search

@@ -17,7 +17,7 @@ import { PhotonReceiver } from "../../services/photon/receiver.js";
import { credentialFingerprint } from "../../services/chat-channels/credential-fingerprint.js";
import { createPhotonExternalRuntimeOwner } from "../../services/chat-channels/imessage-photon/external-runtime.js";
import { PHOTON_EXTERNAL_STATE, photonStateFor } from "../../services/chat-channels/imessage-photon/external-store.js";
import { photonHash, photonExternalStateSchema, readPhotonExternalState } from "../../services/chat-channels/imessage-photon/external-contract.js";
import { photonHash, photonExternalStateSchema, readPhotonExternalState, type PhotonExternalState } from "../../services/chat-channels/imessage-photon/external-contract.js";
import { photonFixture } from "./fixture.js";
import * as photonExternalRuntime from "../../services/chat-channels/imessage-photon/external-runtime.js";
@@ -761,18 +761,23 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
});
async function unrecordedSenderFixture() {
async function unrecordedSenderFixture(effects?: { before(current: PhotonExternalState, next: PhotonExternalState): void; after?(current: PhotonExternalState, next: PhotonExternalState): void }) {
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]) };
return { ...store, retained: async (...args: Parameters<typeof store.retained>) => {
let previous: PhotonExternalState | undefined;
const result = await retained(args[0], current => {
const next = args[1](current); effects?.before(current, next);
if (failDebtWrite && next.failure?.code === "sender_close") { debtWrites.push(Date.now()); throw persistenceFailure; }
previous = current; return next;
}, args[2]);
if (previous) effects?.after?.(previous, result);
return result;
} };
});
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");
@@ -1205,4 +1210,137 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
});
});
it("normal useful receipt preserves a future hold until authorized Retry and accepts its actual lost SQL reply without duplicate provider work", async () => {
const receiptFailure = new Error("controlled exact receipt transaction rollback"), lostReply = new Error("controlled receipt commit reply loss");
let refuse = true, loseReply = true, lostReplies = 0, receiptWrites = 0;
const t = await unrecordedSenderFixture({
before(current, next) { if (current.failure?.code === "sender_close" && next.failure === null) { receiptWrites++; if (refuse) throw receiptFailure; } },
after(current, next) { if (current.failure?.code === "sender_close" && next.failure === null && loseReply) { loseReply = false; lostReplies++; throw lostReply; } },
});
let primary: { error: unknown } | undefined, coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
const later = vi.fn(async () => "later-current-result"), errors: unknown[] = [];
try {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: true });
t.arm(); await t.invoke(); t.restorePersistence();
await expect(t.adapter.drainUsefulClient()).rejects.toBeInstanceOf(Error); t.restoreClose();
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(receiptWrites).toBeGreaterThan(0), { timeout: 5000 });
await expect(t.adapter.withClient(later)).rejects.toBe(receiptFailure); expect(later).not.toHaveBeenCalled(); t.assertSingleSend();
const held = readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE)); if (!held?.failure) throw new Error("normal retained receipt failure absent");
const future = { ...held.failure, nextAttemptAt: new Date(Date.now() + 60_000).toISOString() };
await t.c.state.update(PHOTON_EXTERNAL_STATE, () => ({ ...held, failure: future }));
refuse = false;
await expect(t.adapter.withClient(later)).rejects.toThrow("current authorized cleanup retry");
expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toEqual(future); expect(later).not.toHaveBeenCalled();
const management = await connectionManagementService(db).authorize({ type: "board", userId: f.userId, source: "session" }, "connections:configure",
{ type: "connection_management", companyId: f.companyId, connectionId: t.c.connection.id, provider: "imessage-photon", purpose: "chat", operation: "POST /chat-endpoints/:endpointId/provider-work/:actionId/retry" });
await t.c.service.retrySlackFormReceipt(t.c.endpoint.id, held.handoffId, management);
await vi.advanceTimersByTimeAsync(30_001); // The existing worker error-backoff, not an extra retry policy.
await vi.waitFor(async () => { expect(lostReplies).toBe(1); expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.failure).toBeNull(); }, { timeout: 5000 });
const committedWrites = receiptWrites;
expect(await t.adapter.withClient(later)).toBe("later-current-result");
expect(receiptWrites).toBe(committedWrites); expect(later).toHaveBeenCalledTimes(1); t.assertSingleSend();
} catch (error) { primary = { error }; }
finally {
refuse = false; loseReply = false; 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 rejected-receipt retry cleanup remains owned");
}
if (primary) throw primary.error;
});
it("normal reconciliation cannot rebind an old closed useful queue onto a newer unknown sender slot or erase its failure", async () => {
const receiptFailure = new Error("controlled retained receipt rollback"); let refuse = true;
const t = await unrecordedSenderFixture({ before(current, next) { if (refuse && current.failure?.code === "sender_close" && next.failure === null) throw receiptFailure; } });
let primary: { error: unknown } | undefined, coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
const later = vi.fn(async () => "must-not-run"), errors: unknown[] = [];
try {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: true });
t.arm(); await t.invoke(); t.restorePersistence(); await expect(t.adapter.drainUsefulClient()).rejects.toBeInstanceOf(Error); t.restoreClose();
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(t.adapter.hasUnrecordedUsefulClientDebt()).toBe(true), { timeout: 5000 });
await expect(t.adapter.withClient(later)).rejects.toBe(receiptFailure);
const old = readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE)); if (!old?.senderResource) throw new Error("normal original sender allocation absent");
// Controlled unknown-record input, not a claimed allocation or close fact.
// Its only purpose is to disprove borrowing OLD physical closure for it.
const newer = { ...old, senderResource: { ...old.senderResource, id: randomUUID(), closed: false },
failure: { code: "sender_close" as const, attempts: 7, nextAttemptAt: new Date().toISOString() } };
await t.c.state.update(PHOTON_EXTERNAL_STATE, () => newer); refuse = false;
const beforeErrors = errors.length;
await db.transaction(tx => notifyChatReceiver(tx, t.c.endpoint)); await vi.advanceTimersByTimeAsync(30_001);
await vi.waitFor(() => expect(errors.length).toBeGreaterThan(beforeErrors), { timeout: 5000 });
expect(await t.c.state.read(PHOTON_EXTERNAL_STATE)).toEqual(newer);
expect(t.adapter.hasUnrecordedUsefulClientDebt(), "normal reconciliation must retire the OLD pending receipt without a useful operation").toBe(false);
// The normal mismatch path already retried the retained OLD callback.
// This useful call only observes stopped; it must not drive cleanup.
await expect(t.adapter.withClient(later)).rejects.toThrow("stopped");
expect(later).not.toHaveBeenCalled(); t.assertSingleSend(); expect(await t.c.state.read(PHOTON_EXTERNAL_STATE)).toEqual(newer);
} catch (error) { primary = { error }; }
finally {
refuse = false; 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 unknown-slot receipt cleanup remains owned");
}
if (primary) throw primary.error;
});
it("a pending useful receipt observes normal retiring publication before removeRuntime enters shutdown and blocks old business", async () => {
const receiptFailure = new Error("controlled useful receipt transaction rollback"); let refuse = true;
const makeOwner = photonExternalRuntime.createPhotonExternalRuntimeOwner;
const actualOwners: ReturnType<typeof makeOwner>[] = [];
vi.spyOn(photonExternalRuntime, "createPhotonExternalRuntimeOwner").mockImplementation((database, options) => {
const owner = makeOwner(database, options); actualOwners.push(owner); return owner;
});
const t = await unrecordedSenderFixture({ before(current, next) { if (refuse && current.failure?.code === "sender_close" && next.failure === null) throw receiptFailure; } });
let primary: { error: unknown } | undefined, coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
let releaseRemove = () => {}, enteredRemove = () => {};
const gate = new Promise<void>(resolve => { releaseRemove = resolve; }), entered = new Promise<void>(resolve => { enteredRemove = resolve; });
const normalRemove = t.c.runtime.removeEndpoint.bind(t.c.runtime), later = vi.fn(async () => "must-not-run");
let restoreRemove: (() => void) | undefined, retirement: Promise<unknown> | undefined;
const disconnect = vi.spyOn(t.adapter, "disconnect");
try {
t.arm(); await t.invoke(); t.restorePersistence(); await expect(t.adapter.drainUsefulClient()).rejects.toBeInstanceOf(Error); t.restoreClose();
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: () => {} }); coordinators.push(coordinator);
await t.c.service.registerReceiverWork(coordinator, () => true).ready;
await vi.waitFor(() => expect(t.adapter.hasUnrecordedUsefulClientDebt()).toBe(true), { timeout: 5000 });
await expect(t.adapter.withClient(later)).rejects.toBe(receiptFailure); expect(t.adapter.hasUnrecordedUsefulClientDebt()).toBe(true);
refuse = false;
const remove = vi.spyOn(t.c.runtime, "removeEndpoint").mockImplementation(async id => { if (id === t.c.endpoint.id) { enteredRemove(); await gate; } return normalRemove(id); });
restoreRemove = () => { remove.mockRestore(); };
const owner = actualOwners.at(-1);
if (!owner) throw new Error("normal reconstructed Photon owner absent");
// Exercise the actual service-created internal retirement port. Configure
// pause first pre-drains the registry, before this publication boundary.
retirement = owner.retire(t.c.endpoint.id); void retirement.catch(() => {});
await entered;
const retiring = readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE)); if (!retiring) throw new Error("normal retiring state absent");
expect(retiring.phase).toBe("retiring"); expect(disconnect).not.toHaveBeenCalled();
expect(t.adapter.hasUnrecordedUsefulClientDebt()).toBe(true);
// Only the receipt sees retiring: normal removeRuntime has not entered
// registry/adapter shutdown, so its stopped flag cannot explain refusal.
await expect(t.adapter.withClient(later)).rejects.toThrow("stopped");
expect(disconnect).not.toHaveBeenCalled(); expect(later).not.toHaveBeenCalled(); t.assertSingleSend();
const after = readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE));
expect(after?.phase).toBe("retiring"); expect(after?.failure).toEqual(retiring.failure);
expect(after?.senderResource).toEqual(retiring.senderResource); expect(after?.acceptedSequence).toBe(retiring.acceptedSequence);
releaseRemove(); await retirement;
expect(readPhotonExternalState(await t.c.state.read(PHOTON_EXTERNAL_STATE))?.phase).toBe("retired");
} catch (error) { primary = { error }; }
finally {
refuse = false; releaseRemove(); t.restorePersistence(); t.restoreClose(); const cleanup: unknown[] = [];
try { await retirement; } catch (error) { if (!primary) cleanup.push(error); }
restoreRemove?.();
try { await coordinator?.stop(); } catch (error) { cleanup.push(error); }
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); } disconnect.mockRestore();
if (cleanup.length) throw new AggregateError([...(primary ? [primary.error] : []), ...cleanup], "normal retiring-receipt cleanup remains owned");
}
if (primary) throw primary.error;
});
});
@@ -314,6 +314,46 @@ describe("Photon actual resource join and useful-channel owner", () => {
try { await f.adapter.disconnect(); } finally { create.mockRestore(); f.allocation.mockRestore(); }
}
});
it("a rejected exact post-close receipt remains owned before another useful operation", async () => {
let creates = 0, closeFails = true, receiptReady = false;
const closeFailure = new Error("controlled original useful close refusal"), receiptFailure = new Error("controlled exact post-close receipt refusal");
const closes: number[] = [], debt = vi.fn(async () => {}), knownAction = vi.fn(async () => ({ messageId: "known-original-result" }));
const laterAction = vi.fn(async () => "later-useful-result"), receipt = vi.fn(async () => { if (!receiptReady) throw receiptFailure; });
const owner = new PhotonUsefulClient(() => { const id = ++creates; return { close: async () => { closes.push(id); if (id === 1 && closeFails) throw closeFailure; } }; }, undefined, debt);
try {
expect(await owner.run(knownAction)).toEqual({ messageId: "known-original-result" });
expect(knownAction).toHaveBeenCalledTimes(1); expect(creates).toBe(1);
closeFails = false; await expect(owner.drain(receipt)).rejects.toBe(receiptFailure);
expect(closes).toEqual([1, 1]);
await expect(owner.run(laterAction), "rejected cleanup receipt must block later construction and provider work").rejects.toBe(receiptFailure);
expect(creates).toBe(1); expect(laterAction).not.toHaveBeenCalled(); expect(knownAction).toHaveBeenCalledTimes(1);
receiptReady = true; expect(await owner.run(laterAction)).toBe("later-useful-result");
expect(receipt).toHaveBeenCalledTimes(3); expect(creates).toBe(2); expect(laterAction).toHaveBeenCalledTimes(1);
expect(knownAction).toHaveBeenCalledTimes(1); expect(closes).toEqual([1, 1, 2]);
} finally { closeFails = false; receiptReady = true; await owner.close(); }
});
it("positive obsolete receipt stops the old useful queue before any later allocation or provider action", async () => {
let creates = 0, attempts = 0;
const close = vi.fn(async () => {}), action = vi.fn(async () => "must-not-run"), failure = new Error("controlled receipt persistence unavailable");
const owner = new PhotonUsefulClient(() => { creates++; return { close }; }, { close });
try {
await expect(owner.drain(async () => { if (++attempts === 1) throw failure; return "obsolete"; })).rejects.toBe(failure);
await expect(owner.run(action)).rejects.toThrow("stopped");
expect(attempts).toBe(2); expect(creates).toBe(0); expect(action).not.toHaveBeenCalled(); expect(close).toHaveBeenCalledTimes(1);
await owner.close(); expect(close).toHaveBeenCalledTimes(1);
} finally { await owner.close(); }
});
it("only explicit cleanup drain can replace a refused receipt for the same already-joined useful owner", async () => {
const failure = new Error("controlled stale receipt"), original = vi.fn(async () => { throw failure; }), current = vi.fn(async () => {});
let creates = 0; const close = vi.fn(async () => {}), action = vi.fn(async () => "current-useful-result");
const owner = new PhotonUsefulClient(() => { creates++; return { close: async () => {} }; }, { close });
try {
await expect(owner.drain(original)).rejects.toBe(failure);
await expect(owner.run(action)).rejects.toBe(failure); expect(creates).toBe(0); expect(action).not.toHaveBeenCalled();
await owner.drain(current); expect(original).toHaveBeenCalledTimes(2); expect(current).toHaveBeenCalledTimes(1); expect(close).toHaveBeenCalledTimes(1);
expect(await owner.run(action)).toBe("current-useful-result"); expect(creates).toBe(1); expect(action).toHaveBeenCalledTimes(1);
} finally { await owner.drain(current); await owner.close(); }
});
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++; });
@@ -73,7 +73,9 @@ it("saved Photon attachments use the external useful owner and retain failed clo
providerConfig:{provider:"imessage-photon",userName:"Agent",intakeAfter:0,credentials:{allocation:"dedicated",projectId:"project",projectSecret:"controlled-project-secret",lineId:"line",phoneNumber:"+15555550100"}},
callbacks:{onMessage:async()=>{},onPhotonEvent:async()=>{},onPhotonAssertOwned:async()=>{},onPhotonCheckpoint:async()=>{},onPhotonFailure:async()=>{},
onPhotonUsefulClientDebt:debt,onPhotonIntakePlacement:async()=>({kind:"cloud",bindingId:"controlled-current-binding"})} });
let closeFails = true;
let closeFails = true, receiptReady = false;
const receiptFailure = new Error("controlled saved attachment cleanup receipt refusal");
const receipt = vi.fn(async () => { if (!receiptReady) throw receiptFailure; });
const failure = new Error("controlled useful close failed");
controls[1]!.client.close.mockImplementation(async () => { if (closeFails) throw failure; });
try {
@@ -101,11 +103,17 @@ it("saved Photon attachments use the external useful owner and retain failed clo
await expect(recovered.fetchData()).rejects.toBe(failure);
expect(allocate).toHaveBeenCalledTimes(2); expect(controls[1]!.client.attachments.downloadStream).toHaveBeenCalledTimes(1);
closeFails = false;
await expect(adapter.drainUsefulClient(receipt)).rejects.toBe(receiptFailure);
await expect(recovered.fetchData(), "saved attachment provider work must wait for its rejected cleanup receipt").rejects.toBe(receiptFailure);
expect(allocate).toHaveBeenCalledTimes(2); expect(controls[1]!.client.attachments.downloadStream).toHaveBeenCalledTimes(1);
expect(controls[2]!.client.attachments.downloadStream).not.toHaveBeenCalled();
receiptReady = true;
await expect(recovered.fetchData()).resolves.toEqual(body);
expect(receipt).toHaveBeenCalledTimes(3);
expect(allocate).toHaveBeenCalledTimes(3); expect(controls[2]!.client.attachments.downloadStream).toHaveBeenCalledTimes(1);
expect(controls[2]!.client.close).toHaveBeenCalledTimes(1);
} finally {
closeFails = false;
closeFails = false; receiptReady = true;
try { await runtime.shutdown(); } finally { vi.restoreAllMocks(); }
}
});
@@ -358,14 +358,50 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
if (external.localResourceId !== null && !external.localClosureConfirmed) {
external = (await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).repair(external)).state;
}
const adapter = options.currentRuntime(id)?.getProviderAdapter();
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 }));
});
const usefulRuntime = options.currentRuntime(id), usefulContext = usefulRuntime ? options.context(usefulRuntime) : undefined;
const adapter = usefulRuntime?.getProviderAdapter();
const drainedState = external, senderResource = external.senderResource;
if (adapter instanceof PhotonChatAdapter) {
// Rebinding a receipt requires the SAME actual Runtime/sender object,
// even when the fresh state has no sender_close failure. An old queue
// cannot lend its physical close to another allocation's callback.
if (!usefulRuntime || !usefulContext || usefulContext.endpointRuntime !== usefulRuntime
|| options.context(usefulRuntime) !== usefulContext || options.currentRuntime(id) !== usefulRuntime
|| usefulRuntime.companyId !== drainedState.identity.companyId || usefulRuntime.endpointId !== drainedState.identity.endpointId
|| usefulContext.generation !== drainedState.identity.runtimeGeneration
|| usefulContext.credentialFingerprint !== drainedState.identity.credentialReferences
|| !senderResource || !resources.owns(senderResource.id, usefulRuntime)) {
// Join ONLY a previously retained receipt. Never install the new
// slot's callback using another object's physical-close fact.
await adapter.drainUsefulClient();
throw new Error("Photon useful close receipt has no exact original runtime and sender ownership");
}
await adapter.drainUsefulClient(async () => {
const current = await store.read(drainedState.identity);
if (!current) throw new Error("Photon useful close receipt has no retained scope");
// Positive replacement retires ONLY the old already-closed queue.
// It grants no close receipt or business use of the newer allocation.
if (!isDeepStrictEqual(current.identity, drainedState.identity)
|| !isDeepStrictEqual(current.binding, drainedState.binding) || current.handoffId !== drainedState.handoffId)
return "obsolete";
if (!current.senderResource) throw new Error("Photon useful close receipt sender ownership is unknown");
if (current.senderResource.id !== senderResource.id) return "obsolete";
if (!isDeepStrictEqual({ ...current.senderResource, closed: false }, { ...senderResource, closed: false }))
throw new Error("Photon useful close receipt sender descriptor changed");
if (current.phase === "retiring" || current.phase === "retired" || current.senderResource.closed) return "obsolete";
if (current.phase !== "external") throw new Error("Photon useful close receipt has no current external authority");
if (drainedState.failure?.code !== "sender_close") return;
// A committed receipt with a lost reply is already settled. Other
// failure domains remain owned and are never erased by this receipt.
if (current.failure?.code !== "sender_close") return;
if (current.failure.nextAttemptAt === null || Date.parse(current.failure.nextAttemptAt) > Date.now()
|| !isDeepStrictEqual(current.failure, drainedState.failure))
throw new Error("Photon useful close receipt requires current authorized cleanup retry");
// Preserve legitimate checkpoint progress; the SAME failure and exact
// original sender must still match, then full current-state CAS wins.
await store.retained(current, 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) });
+4 -3
View File
@@ -1,5 +1,5 @@
import { createOwnedPhotonClient } from "./owned-client.js";
import { PhotonUsefulClient } from "./useful-client.js";
import { PhotonUsefulClient, type PhotonUsefulCloseReceipt } from "./useful-client.js";
import { PhotonRecoveryTransport } from "./recovery-transport.js";
import { createHash } from "node:crypto";
import {
@@ -105,8 +105,9 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
private localClient?: GrpcAdvancedIMessage;
private usefulClient?: PhotonUsefulClient<GrpcAdvancedIMessage>;
onUsefulClientDebt?: () => Promise<void>;
async drainUsefulClient(afterClose?: () => Promise<void>): Promise<void> {
await this.externalClientOwner().drain(afterClose);
async drainUsefulClient(afterClose?: PhotonUsefulCloseReceipt): Promise<void> {
if (afterClose) await this.externalClientOwner().drain(afterClose);
else await this.usefulClient?.drain();
}
hasUnrecordedUsefulClientDebt(): boolean { return this.usefulClient?.hasUnrecordedCleanupDebt() ?? false; }
private makeClient(): GrpcAdvancedIMessage {
+16 -6
View File
@@ -1,5 +1,7 @@
import { registerIdleLocalWorkProbe } from "../idle-local-work.js";
export type PhotonUsefulCloseReceipt = () => Promise<void | "obsolete">;
/** Unary useful work owns its actual channel until close resolves. There is no
* keepalive, idle timeout or new poller. Failed close retains the same resource
* and blocks the next operation until its normal retry actually closes it. */
@@ -9,13 +11,14 @@ export class PhotonUsefulClient<T extends { close(): Promise<void> | void }> {
private pending = 0;
private failed = false;
private unrecordedDebt = false;
private closeReceipt?: PhotonUsefulCloseReceipt;
private stopped = false;
private readonly unregister: () => void;
constructor(private readonly create: () => T, initial?: T, private readonly recordDebt: () => Promise<void> = async () => {}) {
this.client = initial;
this.unregister = registerIdleLocalWorkProbe(() => this.failed || this.unrecordedDebt ? "unknown" : this.pending || this.client ? "present" : "none");
this.unregister = registerIdleLocalWorkProbe(() => this.failed || this.unrecordedDebt || this.closeReceipt ? "unknown" : this.pending || this.client ? "present" : "none");
}
private async closeCurrent(afterClose?: () => Promise<void>) {
private async closeCurrent(afterClose?: PhotonUsefulCloseReceipt) {
const client = this.client;
if (client) {
try { await client.close(); this.client = undefined; this.failed = false; }
@@ -27,10 +30,16 @@ export class PhotonUsefulClient<T extends { close(): Promise<void> | void }> {
}
// 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; }
if (afterClose) this.closeReceipt = afterClose;
const receipt = this.closeReceipt;
if (receipt) {
const outcome = await receipt();
if (this.closeReceipt === receipt) this.closeReceipt = undefined;
this.unrecordedDebt = false;
if (outcome === "obsolete") this.stopped = true;
} else if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; }
}
hasUnrecordedCleanupDebt(): boolean { return this.unrecordedDebt; }
hasUnrecordedCleanupDebt(): boolean { return this.unrecordedDebt || !!this.closeReceipt; }
private enqueue<R>(action: () => Promise<R>): Promise<R> {
this.pending += 1;
const result = this.tail.then(action);
@@ -42,6 +51,7 @@ export class PhotonUsefulClient<T extends { close(): Promise<void> | void }> {
return this.enqueue(async () => {
if (this.stopped) throw new Error("Photon useful client is stopped");
await this.closeCurrent();
if (this.stopped) throw new Error("Photon useful client is stopped");
const client = this.create(); this.client = client;
let value: R;
try { value = await action(client); }
@@ -55,7 +65,7 @@ export class PhotonUsefulClient<T extends { close(): Promise<void> | void }> {
return value;
});
}
drain(afterClose?: () => Promise<void>): Promise<void> { return this.enqueue(() => this.closeCurrent(afterClose)); }
drain(afterClose?: PhotonUsefulCloseReceipt): Promise<void> { return this.enqueue(() => this.closeCurrent(afterClose)); }
close(): Promise<void> {
this.stopped = true;
return this.enqueue(async () => { await this.closeCurrent(); this.unregister(); });