mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 23:06:17 +01:00
feat(chat): hand Photon ingress to Cloud custody
Keep provider transport and receipt ownership in the Photon modules. Preserve current audit and notification writes inside the actual transaction. Name the public SDK event return type and keep prepared replacement and attachment IDs stable across async client calls. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
0030ef7eed
commit
7128495d1b
28 files changed
+5344
-96
No files matched your search
@@ -114,6 +114,8 @@
|
||||
"packageManager": "pnpm@9.15.4",
|
||||
"pnpm": {
|
||||
"patchedDependencies": {
|
||||
"@grpc/grpc-js@1.14.5": "patches/@grpc__grpc-js@1.14.5.patch",
|
||||
"@photon-ai/advanced-imessage@2.2.0": "patches/@photon-ai__advanced-imessage@2.2.0.patch",
|
||||
"embedded-postgres@18.1.0-beta.16": "patches/embedded-postgres@18.1.0-beta.16.patch",
|
||||
"acpx@0.12.0": "patches/acpx@0.12.0.patch",
|
||||
"acpx@0.13.1": "patches/acpx@0.13.1.patch",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
||||
--- a/dist/chunk-5WYZRCOS.js
|
||||
+++ b/dist/chunk-5WYZRCOS.js
|
||||
@@ -7246,15 +7246,20 @@
|
||||
// Lifecycle
|
||||
// -------------------------------------------------------------------------
|
||||
/** Signal the stream is done. Interrupts any pending iteration. */
|
||||
- async close() {
|
||||
- if (this._closed) {
|
||||
- return;
|
||||
- }
|
||||
+ close() {
|
||||
+ if (this._cleanupComplete) return Promise.resolve();
|
||||
+ if (this._closeAttempt) return this._closeAttempt;
|
||||
this._closed = true;
|
||||
this._cancelResolve?.();
|
||||
- if (this._cleanup) {
|
||||
- await this._cleanup();
|
||||
- }
|
||||
+ let resolveCleanup, rejectCleanup;
|
||||
+ const attempt = new Promise((resolve, reject) => { resolveCleanup = resolve; rejectCleanup = reject; });
|
||||
+ this._closeAttempt = attempt;
|
||||
+ try { Promise.resolve(this._cleanup?.()).then(resolveCleanup, rejectCleanup); }
|
||||
+ catch (error) { rejectCleanup(error); }
|
||||
+ void attempt.then(() => { this._cleanupComplete = true; }, () => {
|
||||
+ if (this._closeAttempt === attempt) this._closeAttempt = undefined;
|
||||
+ });
|
||||
+ return attempt;
|
||||
}
|
||||
/** `Symbol.asyncDispose` -- enables `await using`. */
|
||||
async [Symbol.asyncDispose]() {
|
||||
@@ -16,6 +16,8 @@ packages:
|
||||
# Keep in sync with package.json#pnpm.patchedDependencies. Newer pnpm
|
||||
# versions read patch configuration only from the workspace manifest.
|
||||
patchedDependencies:
|
||||
"@grpc/grpc-js@1.14.5": patches/@grpc__grpc-js@1.14.5.patch
|
||||
"@photon-ai/advanced-imessage@2.2.0": patches/@photon-ai__advanced-imessage@2.2.0.patch
|
||||
postgres@3.4.9: patches/postgres@3.4.9.patch
|
||||
embedded-postgres@18.1.0-beta.16: patches/embedded-postgres@18.1.0-beta.16.patch
|
||||
acpx@0.12.0: patches/acpx@0.12.0.patch
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { describe, expect, it } from "vitest";
|
||||
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";
|
||||
import { createPhotonExternalOwner, PhotonLocalResources, handoffCheckpoint, recordPhotonCheckpointAuthority } from "../../services/chat-channels/imessage-photon/external-owner.js";
|
||||
import { photonHash, readPhotonExternalState, parsePhotonExternalDelivery, type PhotonExternalIdentity, type PhotonExternalState } from "../../services/chat-channels/imessage-photon/external-contract.js";
|
||||
import { PHOTON_EXTERNAL_STATE, type PhotonExternalStore } from "../../services/chat-channels/imessage-photon/external-store.js";
|
||||
import { writePhotonCheckpoint } from "../../services/photon/receiver.js";
|
||||
|
||||
const identity: PhotonExternalIdentity = { companyId: "company", endpointId: "endpoint", connectionId: "connection", runtimeGeneration: 1,
|
||||
credentialReferences: "a".repeat(64), subject: "current-company-manager" };
|
||||
const config = { provider: "imessage-photon" as const, userName: "Photon", intakeAfter: 1,
|
||||
credentials: { projectId: "project", projectSecret: "controlled-project-secret", lineId: "line", phoneNumber: "+15555550101", allocation: "dedicated" as const } };
|
||||
function fixture() {
|
||||
let rows = new Map<string, ChatSdkStateRecord>(), currentLease = "lease", currentGeneration = 1;
|
||||
const persistence: ChatSdkStatePersistence = {
|
||||
read: async (_scope, key) => structuredClone(rows.get(key) ?? null),
|
||||
compareAndSet: async input => {
|
||||
const current = rows.get(input.key);
|
||||
if ((current?.version ?? null) !== input.expectedVersion) return false;
|
||||
// Exercise JSON persistence rather than keeping shared reference identity.
|
||||
rows.set(input.key, { value: JSON.parse(JSON.stringify(input.value)), version: (current?.version ?? 0) + 1, expiresAt: null }); return true;
|
||||
},
|
||||
deleteIfVersion: async input => rows.get(input.key)?.version === input.expectedVersion && rows.delete(input.key),
|
||||
};
|
||||
const state = new PhotonState(identity, persistence);
|
||||
async function read() { return readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE)); }
|
||||
const store: PhotonExternalStore = {
|
||||
read: async () => read(),
|
||||
inspect: async () => read(),
|
||||
current: async (selected, lease, work) => {
|
||||
if (selected.companyId !== identity.companyId || selected.runtimeGeneration !== currentGeneration || lease.token !== currentLease) throw new Error("current authority changed");
|
||||
const before = structuredClone(rows);
|
||||
try { return await work(state, await read()); } catch (error) { rows = before; throw error; }
|
||||
},
|
||||
retained: async (expected, update) => state.update<PhotonExternalState>(PHOTON_EXTERNAL_STATE, raw => {
|
||||
const actual = readPhotonExternalState(raw);
|
||||
if (!actual || !isDeepStrictEqual(actual, expected)) throw new Error("retained CAS failed");
|
||||
return update(actual);
|
||||
}),
|
||||
noEffect: async () => { throw new Error("no revocation in this owner-port fixture"); },
|
||||
};
|
||||
let lostEnrollment = false, retirement = "retiring", enrollments = 0, joins = 0;
|
||||
const requests: Record<string, unknown>[] = [];
|
||||
const resources = new PhotonLocalResources(), resource = {};
|
||||
const resourceId = resources.capture(resource, async () => {
|
||||
joins++;
|
||||
await writePhotonCheckpoint(state, "line", 2);
|
||||
await recordPhotonCheckpointAuthority(state, identity, 2);
|
||||
});
|
||||
const broker = { instanceIdentity: () => ({ instanceId: "instance", environment: "test" as const }),
|
||||
photonReceiverOperation: async ({ operation }: { operation: Record<string, unknown> }) => {
|
||||
requests.push(structuredClone(operation));
|
||||
const retained = await read(); if (!retained) throw new Error("missing durable intent");
|
||||
if (operation.kind === "enroll") {
|
||||
enrollments++;
|
||||
if (lostEnrollment) { lostEnrollment = false; throw new Error("lost enrollment reply"); }
|
||||
return { binding: retained.binding };
|
||||
}
|
||||
if (operation.kind === "retire") return { binding: retained.binding, pending: true };
|
||||
return { binding: retained.binding, handoffId: retained.handoffId, phase: retirement };
|
||||
} };
|
||||
const create = (selectedResources = resources) => createPhotonExternalOwner({ store, broker, resources: selectedResources, notify: () => {}, now: () => new Date("2099-01-01T00:00:00.000Z") });
|
||||
const reconcile = () => create().reconcile({ identity, config, lease: { token: currentLease }, localResourceId: resourceId });
|
||||
return { state, store, resources, resourceId, resource, requests, create, reconcile, read,
|
||||
loseReply: () => { lostEnrollment = true; }, replaceGeneration: () => { currentGeneration++; }, replaceLease: () => { currentLease = "next-lease"; },
|
||||
finishRetirement: () => { retirement = "retired"; }, counts: () => ({ enrollments, joins }) };
|
||||
}
|
||||
// Actual pinned protobuf: CatchUpEventsResponse.sequence=1/chat_changed=13;
|
||||
// ChatChangeEvent.chat_guid=1/occurred_at=2/marked_read=12. The REAL SDK decoder
|
||||
// owns interpretation; these controls do not mock or replace it.
|
||||
function delivery(state: PhotonExternalState, sequence = 3, previousSequence: number | null = 2) {
|
||||
const raw = Buffer.from([8, sequence, 106, 12, 10, 4, 99, 104, 97, 116, 18, 2, 8, 1, 98, 0]);
|
||||
const createdAt = "2099-01-01T00:00:00.000Z";
|
||||
return { id: `photon_${photonHash([state.binding.bindingId, sequence])}`, event: "chat.markedRead", createdAt, installationId: state.binding.bindingId, bindingIds: [state.binding.bindingId],
|
||||
payload: { version: 1, binding: state.binding, sequence, previousSequence, acceptedAt: createdAt, rawFrame: raw.toString("base64") } };
|
||||
}
|
||||
describe("Photon normal external-owner handoff (controlled owner ports, not real SQL or gRPC)", () => {
|
||||
it("stages the exact enrollment before broker use and joins before external placement", async () => {
|
||||
const f = fixture(), accepted = await f.reconcile();
|
||||
expect(accepted.phase).toBe("external"); expect(accepted.joinedSequence).toBe(2);
|
||||
expect(f.counts()).toEqual({ enrollments: 1, joins: 1 });
|
||||
expect(f.requests[0].enrollment).toMatchObject({ initialized: false, sequence: null, handoffId: accepted.handoffId });
|
||||
});
|
||||
it("lost enrollment reply retains the same input and retries without an early join", async () => {
|
||||
const f = fixture(); f.loseReply(); await expect(f.reconcile()).rejects.toThrow("lost enrollment reply");
|
||||
const original = await f.read(); expect(original?.phase).toBe("enrolling"); expect(f.counts().joins).toBe(0);
|
||||
const accepted = await f.reconcile(); expect(accepted.handoffId).toBe(original?.handoffId);
|
||||
expect(f.requests[0]).toEqual(f.requests[1]); expect(f.counts().joins).toBe(1);
|
||||
});
|
||||
it("a replacement process cannot use absent local resources as physical-close proof", async () => {
|
||||
const f = fixture(); f.loseReply(); await expect(f.reconcile()).rejects.toThrow();
|
||||
await expect(f.create(new PhotonLocalResources()).reconcile({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId })).rejects.toThrow("closure is unknown");
|
||||
expect(await f.read()).toMatchObject({ phase: "joining", failure: { code: "local_join" } });
|
||||
});
|
||||
it("unknown initialized legacy checkpoint provenance remains attention", async () => {
|
||||
const f = fixture(); await writePhotonCheckpoint(f.state, "line", 17);
|
||||
await expect(handoffCheckpoint(f.state, identity, "line")).rejects.toThrow("provenance");
|
||||
await expect(f.reconcile()).rejects.toThrow("provenance"); expect(f.counts().enrollments).toBe(0);
|
||||
});
|
||||
it("real SDK decoded event commits normal callback before checkpoint and normal ACK permission", async () => {
|
||||
const f = fixture(), state = await f.reconcile(), event = delivery(state); let calls = 0;
|
||||
await f.create().dispatch({ identity, lease: { token: "lease" }, delivery: event, admit: async decoded => {
|
||||
expect(await f.state.read("checkpoint")).toMatchObject({ sequence: 2 }); expect(decoded).toMatchObject({ type: "chat.markedRead", chatGuid: "chat", sequence: 3 }); calls++;
|
||||
} });
|
||||
expect(await f.state.read("checkpoint")).toMatchObject({ sequence: 3 });
|
||||
await f.create().dispatch({ identity, lease: { token: "lease" }, delivery: event, admit: async () => { calls++; } });
|
||||
expect(calls).toBe(1); expect(await f.read()).toMatchObject({ acceptedSequence: 3, pending: null });
|
||||
});
|
||||
it("out-of-order cross-batch delivery cannot advance an opaque admitted predecessor", async () => {
|
||||
const f = fixture(), state = await f.reconcile(); let calls = 0;
|
||||
await expect(f.create().dispatch({ identity, lease: { token: "lease" }, delivery: delivery(state, 5, 4), admit: async () => { calls++; } })).rejects.toThrow("predecessor");
|
||||
expect(calls).toBe(0); expect(await f.read()).toMatchObject({ acceptedSequence: 2, pending: null });
|
||||
});
|
||||
it("lease replacement after callback retains the same pending receipt and no cursor advance", async () => {
|
||||
const f = fixture(), state = await f.reconcile(); const effects = new Set<number>(); let calls = 0;
|
||||
const admit = async () => { effects.add(3); calls++; if (calls === 1) f.replaceLease(); };
|
||||
await expect(f.create().dispatch({ identity, lease: { token: "lease" }, delivery: delivery(state), admit })).rejects.toThrow("authority");
|
||||
expect(await f.read()).toMatchObject({ acceptedSequence: 2, pending: { sequence: 3 } });
|
||||
expect(await f.state.read("checkpoint")).toMatchObject({ sequence: 2 });
|
||||
await f.create().dispatch({ identity, lease: { token: "next-lease" }, delivery: delivery(state), admit });
|
||||
expect(calls).toBe(2); expect(effects.size).toBe(1);
|
||||
});
|
||||
it("foreign company/environment/delivery and altered original frame fail before callback", async () => {
|
||||
const f = fixture(), state = await f.reconcile(), event = delivery(state);
|
||||
for (const binding of [{ ...state.binding, companyId: "foreign" }, { ...state.binding, environment: "production" }])
|
||||
expect(() => parsePhotonExternalDelivery({ ...event, payload: { ...event.payload, binding } }, state)).toThrow();
|
||||
expect(() => parsePhotonExternalDelivery({ ...event, id: "foreign" }, state)).toThrow();
|
||||
expect(() => parsePhotonExternalDelivery({ ...event, payload: { ...event.payload, rawFrame: event.payload.rawFrame + "=" } }, state)).toThrow();
|
||||
});
|
||||
it("retirement keeps the exact original fact until normal SQL acceptance", async () => {
|
||||
const f = fixture(), state = await f.reconcile();
|
||||
await expect(f.create().retire(state)).rejects.toThrow("remains outstanding");
|
||||
const pending = await f.read(); expect(pending?.phase).toBe("retiring");
|
||||
f.finishRetirement(); if (!pending) throw new Error("missing retirement");
|
||||
await f.create().retire(pending); expect(await f.read()).toMatchObject({ phase: "retired", handoffId: state.handoffId, binding: state.binding });
|
||||
});
|
||||
});
|
||||
describe("Photon actual resource join and useful-channel owner", () => {
|
||||
it("joins concurrent calls, retries only failed close and never confirms an unknown object", async () => {
|
||||
const resources = new PhotonLocalResources(); let calls = 0, release = () => {};
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const id = resources.capture({}, async () => { if (++calls === 1) throw new Error("close failed"); await gate; });
|
||||
await expect(resources.join(id)).rejects.toThrow("close failed");
|
||||
let closed = false; const second = resources.join(id).then(() => { closed = true; }), concurrent = resources.join(id);
|
||||
await Promise.resolve(); expect(closed).toBe(false); expect(calls).toBe(2); release(); await Promise.all([second, concurrent]);
|
||||
await resources.join(id); expect(calls).toBe(2); await expect(resources.join("unknown")).rejects.toThrow("unknown");
|
||||
});
|
||||
it("fresh useful work opens and physically closes its own channel every time", async () => {
|
||||
let opens = 0, closes = 0; const owner = new PhotonUsefulClient(() => { opens++; return { close: async () => { closes++; } }; });
|
||||
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("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++; });
|
||||
expect(await owner.run(async () => { sends++; return { messageId: "known-original" }; })).toEqual({ messageId: "known-original" });
|
||||
expect({ opens, closes, sends, debt }).toEqual({ opens: 1, closes: 1, sends: 1, debt: 1 });
|
||||
await owner.drain(); expect({ opens, closes, sends }).toEqual({ opens: 1, closes: 2, sends: 1 }); await owner.close();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { Client, Server, ServerCredentials, credentials } from "@grpc/grpc-js";
|
||||
import { IMessageError, type LiveEvent } from "@photon-ai/advanced-imessage";
|
||||
import { IMessageError, TypedEventStream, type LiveEvent } from "@photon-ai/advanced-imessage";
|
||||
import type { AskUserQuestionsInteraction } from "@paperclipai/shared";
|
||||
import {
|
||||
PhotonCloudClient,
|
||||
@@ -64,6 +64,7 @@ const question = (id = "interaction"): AskUserQuestionsInteraction =>
|
||||
},
|
||||
}) as AskUserQuestionsInteraction;
|
||||
const guard = async () => {};
|
||||
const recordedFailure = async (): Promise<{ kind: "recorded" }> => ({ kind: "recorded" });
|
||||
|
||||
describe("Photon Cloud and fixed line identity", () => {
|
||||
it("uses Basic project auth, verifies dedicated allocation, and never exposes tokens", async () => {
|
||||
@@ -302,6 +303,108 @@ describe("Photon publication receipts", () => {
|
||||
});
|
||||
|
||||
describe("Photon durable event recovery", () => {
|
||||
it("initial obsolete failure receipt cannot certify stopped responsibility", async () => {
|
||||
const f = photonFixture(); let attempted!: () => void, releaseLive!: () => void;
|
||||
const reported = new Promise<void>(resolve => { attempted = resolve; });
|
||||
const live = new Promise<void>(resolve => { releaseLive = resolve; });
|
||||
for (const resource of [f.client.messages, f.client.chats, f.client.groups, f.client.polls])
|
||||
resource.subscribeEvents.mockImplementation(() => new TypedEventStream((async function* () { await live; })(), async () => { releaseLive(); }));
|
||||
const failure = vi.fn<() => Promise<void | { kind: "recorded" | "obsolete" }>>(async () => { attempted(); return { kind: "obsolete" }; });
|
||||
const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0,
|
||||
assertOwned: guard, admit: guard, failure, catchUp: () => new TypedEventStream((async function* () { throw new Error("controlled CatchUp failure"); })()) });
|
||||
try {
|
||||
receiver.start(); await reported; await new Promise<void>(resolve => setImmediate(resolve));
|
||||
await expect(receiver.close()).rejects.toThrow("shutdown remains unconfirmed");
|
||||
expect(await f.state.read("checkpoint")).toBeNull();
|
||||
failure.mockResolvedValue({ kind: "recorded" }); await receiver.close();
|
||||
} finally { failure.mockResolvedValue({ kind: "recorded" }); await receiver.close(); }
|
||||
});
|
||||
|
||||
it("retains completed request reporting debt until the same owner durably records it on close retry", async () => {
|
||||
const f = photonFixture(), source = new Error("controlled catch-up failure"), reporting = new Error("controlled attention persistence failure");
|
||||
let attempted!: () => void;
|
||||
const reported = new Promise<void>(resolve => { attempted = resolve; });
|
||||
// Live subscriptions stay open; only the normal CatchUp request fails.
|
||||
let releaseLive!: () => void;
|
||||
const live = new Promise<void>(resolve => { releaseLive = resolve; });
|
||||
for (const resource of [f.client.messages, f.client.chats, f.client.groups, f.client.polls])
|
||||
resource.subscribeEvents.mockImplementation(() => new TypedEventStream((async function* () { await live; })(), async () => { releaseLive(); }));
|
||||
const failure = vi.fn<() => Promise<void | { kind: "recorded" | "obsolete" }>>(async () => { attempted(); throw reporting; });
|
||||
const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0,
|
||||
assertOwned: guard, admit: guard, failure, catchUp: () => new TypedEventStream((async function* () { throw source; })()) });
|
||||
try {
|
||||
receiver.start(); await reported;
|
||||
// The failure callback and request have completed BEFORE shutdown starts.
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
expect(failure).toHaveBeenCalledTimes(1);
|
||||
await expect(receiver.close()).rejects.toThrow("shutdown remains unconfirmed");
|
||||
expect(failure).toHaveBeenCalledTimes(2);
|
||||
failure.mockImplementation(async () => ({ kind: "recorded" as const }));
|
||||
const repaired = receiver.close(); expect(receiver.close()).toBe(repaired);
|
||||
await repaired; expect(receiver.close()).toBe(repaired);
|
||||
expect(failure).toHaveBeenCalledTimes(3);
|
||||
expect(await f.state.read("checkpoint")).toBeNull();
|
||||
} finally {
|
||||
failure.mockImplementation(async () => ({ kind: "recorded" as const }));
|
||||
await receiver.close();
|
||||
}
|
||||
});
|
||||
it("does not treat a stale or void reporting retry as current durable responsibility", async () => {
|
||||
const f = photonFixture(); let attempted!: () => void;
|
||||
const reported = new Promise<void>(resolve => { attempted = resolve; });
|
||||
// Live subscriptions stay open; only the normal CatchUp request fails.
|
||||
let releaseLive!: () => void;
|
||||
const live = new Promise<void>(resolve => { releaseLive = resolve; });
|
||||
for (const resource of [f.client.messages, f.client.chats, f.client.groups, f.client.polls])
|
||||
resource.subscribeEvents.mockImplementation(() => new TypedEventStream((async function* () { await live; })(), async () => { releaseLive(); }));
|
||||
const failure = vi.fn<() => Promise<void | { kind: "recorded" | "obsolete" }>>(async () => { attempted(); throw new Error("controlled persistence failure"); });
|
||||
const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0,
|
||||
assertOwned: guard, admit: guard, failure, catchUp: () => new TypedEventStream((async function* () { throw new Error("controlled catch-up failure"); })()) });
|
||||
try {
|
||||
receiver.start(); await reported; await new Promise<void>(resolve => setImmediate(resolve));
|
||||
failure.mockResolvedValue({ kind: "obsolete" });
|
||||
await expect(receiver.close()).rejects.toThrow("shutdown remains unconfirmed");
|
||||
failure.mockResolvedValue(undefined);
|
||||
await expect(receiver.close()).rejects.toThrow("shutdown remains unconfirmed");
|
||||
} finally {
|
||||
failure.mockResolvedValue({ kind: "recorded" }); await receiver.close();
|
||||
}
|
||||
});
|
||||
it("joins in-flight durable admission before close completes and never admits new work after stop", async () => {
|
||||
const f = photonFixture(); let release!: () => void, entered!: () => void, finished = false;
|
||||
const pending = new Promise<void>(resolve => { release = resolve; }), admitting = new Promise<void>(resolve => { entered = resolve; });
|
||||
const admit = vi.fn(async () => { entered(); await pending; });
|
||||
const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0,
|
||||
assertOwned: guard, admit, failure: recordedFailure, catchUp: () => stream([photonEvent(1), { type: "catchup.complete", headSequence: 1 }]) });
|
||||
receiver.start(); await admitting;
|
||||
const closing = receiver.close(); expect(receiver.close()).toBe(closing);
|
||||
void closing.then(() => { finished = true; }); await Promise.resolve(); expect(finished).toBe(false);
|
||||
release(); await closing; expect(finished).toBe(true); expect(admit).toHaveBeenCalledTimes(1);
|
||||
await receiver.catchUp(); expect(admit).toHaveBeenCalledTimes(1); expect(f.client.close).toHaveBeenCalledTimes(1);
|
||||
expect(await f.state.read("checkpoint")).toMatchObject({ sequence: 1 });
|
||||
});
|
||||
it("retries the same client close after failure and memoizes only successful joined shutdown", async () => {
|
||||
const f = photonFixture(), original = new Error("controlled actual client close failure");
|
||||
f.client.close.mockRejectedValueOnce(original);
|
||||
const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0,
|
||||
assertOwned: guard, admit: guard, failure: recordedFailure });
|
||||
const first = receiver.close(); expect(receiver.close()).toBe(first);
|
||||
await expect(first).rejects.toMatchObject({ errors: [original] });
|
||||
const second = receiver.close(); expect(second).not.toBe(first); expect(receiver.close()).toBe(second);
|
||||
await second; expect(receiver.close()).toBe(second); expect(f.client.close).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("never converts an unresolved SDK stream cleanup rejection into a successful repeated close", async () => {
|
||||
const f = photonFixture(), original = new Error("controlled actual stream cleanup failure"); let unblock!: () => void;
|
||||
const blocked = new Promise<void>(resolve => { unblock = resolve; });
|
||||
f.client.messages.subscribeEvents.mockReturnValue(new TypedEventStream((async function* () { await blocked; })(), async () => { unblock(); throw original; }));
|
||||
const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0,
|
||||
assertOwned: guard, admit: guard, failure: recordedFailure });
|
||||
receiver.start();
|
||||
await expect(receiver.close()).rejects.toMatchObject({ errors: expect.arrayContaining([original]) });
|
||||
await expect(receiver.close()).rejects.toMatchObject({ errors: expect.arrayContaining([original]) });
|
||||
expect(f.client.close).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("records preceding events, deduplicates, and does not checkpoint an unadmitted event", async () => {
|
||||
const f = photonFixture();
|
||||
const events = [photonEvent(1), photonEvent(2)];
|
||||
@@ -316,7 +419,7 @@ describe("Photon durable event recovery", () => {
|
||||
intakeAfter: 0,
|
||||
assertOwned: guard,
|
||||
admit: admitted,
|
||||
failure: guard,
|
||||
failure: recordedFailure,
|
||||
catchUp: () =>
|
||||
stream([...events, { type: "catchup.complete", headSequence: 2 }]),
|
||||
});
|
||||
@@ -339,7 +442,7 @@ describe("Photon durable event recovery", () => {
|
||||
intakeAfter: Date.now() + 1000,
|
||||
assertOwned: guard,
|
||||
admit,
|
||||
failure: guard,
|
||||
failure: recordedFailure,
|
||||
catchUp: () =>
|
||||
stream([
|
||||
photonEvent(10),
|
||||
@@ -357,7 +460,7 @@ describe("Photon durable event recovery", () => {
|
||||
intakeAfter: 0,
|
||||
assertOwned: guard,
|
||||
admit,
|
||||
failure: guard,
|
||||
failure: recordedFailure,
|
||||
catchUp: () =>
|
||||
stream([
|
||||
photonEvent(13),
|
||||
@@ -374,7 +477,7 @@ describe("Photon durable event recovery", () => {
|
||||
throw new Error("lease lost");
|
||||
},
|
||||
admit,
|
||||
failure: guard,
|
||||
failure: recordedFailure,
|
||||
});
|
||||
await expect(lost.catchUp()).rejects.toThrow("lease lost");
|
||||
expect(admit).not.toHaveBeenCalled();
|
||||
@@ -384,7 +487,7 @@ describe("Photon durable event recovery", () => {
|
||||
const admit = vi.fn(guard);
|
||||
await f.state.update("checkpoint", () => ({schema:1, lineId:"line", sequence:0}));
|
||||
let events: any[] = [photonEvent(1_008_648_034), {type:"catchup.complete",headSequence:1_008_648_034}];
|
||||
const receiver = new PhotonReceiver({client:f.adapter.client,state:f.state,lineId:"line",allocation:"shared",intakeAfter:0,assertOwned:guard,admit,failure:guard,catchUp:()=>stream(events)});
|
||||
const receiver = new PhotonReceiver({client:f.adapter.client,state:f.state,lineId:"line",allocation:"shared",intakeAfter:0,assertOwned:guard,admit,failure:recordedFailure,catchUp:()=>stream(events)});
|
||||
await receiver.catchUp();
|
||||
expect(admit).toHaveBeenCalledTimes(1);
|
||||
expect(await f.state.read("checkpoint")).toMatchObject({sequence:1_008_648_034});
|
||||
@@ -443,7 +546,7 @@ describe("Photon durable event recovery", () => {
|
||||
{ type: "catchup.complete", headSequence: 3 },
|
||||
]);
|
||||
} finally {
|
||||
transport.close();
|
||||
await transport.close();
|
||||
server.forceShutdown();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6,6 +6,9 @@ export type { ActivityPublication } from "../types/activity-publication.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
|
||||
/** Activity persistence needs query/transaction capability, not a pool client. */
|
||||
type ActivityDb = Pick<Db, "select" | "insert" | "update" | "transaction">;
|
||||
import { activityLog, agentApiKeys, companies, heartbeatRuns, issues } from "@paperclipai/db";
|
||||
import { isUuidLike, PLUGIN_EVENT_TYPES, type PluginEventType } from "@paperclipai/shared";
|
||||
import type { PluginEvent } from "@paperclipai/plugin-sdk";
|
||||
@@ -73,7 +76,7 @@ export interface LogActivityInput {
|
||||
}
|
||||
|
||||
|
||||
export async function createActivityDetailsRedactor(db: Db) {
|
||||
export async function createActivityDetailsRedactor(db: ActivityDb) {
|
||||
const currentUserRedactionOptions = {
|
||||
enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs,
|
||||
};
|
||||
@@ -82,7 +85,7 @@ export async function createActivityDetailsRedactor(db: Db) {
|
||||
);
|
||||
}
|
||||
|
||||
export async function redactActivityDetails(db: Db, details: Record<string, unknown> | null) {
|
||||
export async function redactActivityDetails(db: ActivityDb, details: Record<string, unknown> | null) {
|
||||
if (!details) return null;
|
||||
return (await createActivityDetailsRedactor(db))(details);
|
||||
}
|
||||
@@ -91,7 +94,7 @@ function readNonEmptyString(value: unknown) {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
export async function resolveResponsibleUserIdForActivity(db: Db, input: LogActivityInput) {
|
||||
export async function resolveResponsibleUserIdForActivity(db: ActivityDb, input: LogActivityInput) {
|
||||
if (input.responsibleUserIdOverride !== undefined) {
|
||||
return readNonEmptyString(input.responsibleUserIdOverride);
|
||||
}
|
||||
@@ -164,10 +167,10 @@ export function publishActivity(publication: ActivityPublication) {
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
export async function persistActivity(db: Db, input: LogActivityInput, receipt?: { id: string }) {
|
||||
export async function persistActivity(db: ActivityDb, input: LogActivityInput, receipt?: { id: string }) {
|
||||
const redactedDetails = await redactActivityDetails(db, input.authorization ? { ...input.details, permissionDecision: input.authorization, ...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}) } : input.details ?? null);
|
||||
const responsibleUserId = await resolveResponsibleUserIdForActivity(db, input);
|
||||
const insert = (runner: Db) => runner.insert(activityLog).values({
|
||||
const insert = (runner: Pick<Db, "insert">) => runner.insert(activityLog).values({
|
||||
...(receipt ? { id: receipt.id } : {}),
|
||||
companyId: input.companyId,
|
||||
actorType: input.actorType,
|
||||
@@ -185,7 +188,7 @@ export async function persistActivity(db: Db, input: LogActivityInput, receipt?:
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpEvents, `task:${input.entityId}`);
|
||||
if (input.runId && input.action === "issue.updated" && ["done", "cancelled"].includes(String(input.details?.status)))
|
||||
await notifyActiveRunSilence(tx, { companyId: input.companyId, runId: input.runId });
|
||||
return insert(tx as unknown as Db);
|
||||
return insert(tx);
|
||||
})
|
||||
: await insert(db);
|
||||
|
||||
@@ -232,7 +235,7 @@ export async function persistActivity(db: Db, input: LogActivityInput, receipt?:
|
||||
}
|
||||
|
||||
export async function logActivity(
|
||||
db: Db,
|
||||
db: ActivityDb,
|
||||
input: LogActivityInput,
|
||||
postCommitPublications?: ActivityPublication[],
|
||||
) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createPhotonExternalRuntimeOwner, stagePhotonExternalConfiguration } from "./chat-channels/imessage-photon/external-runtime.js";
|
||||
import { createPaperclipCloudConnector, paperclipCloudConnectorConfigFromEnv } from "./paperclip-cloud-connector.js";
|
||||
import { retrySlackFormAcknowledgement } from "./chat-channels/slack/form-retry.js";
|
||||
import { createSlackFormConnectorAccess, registerSlackFormWorkOwner, reconcilePendingSlackFormWork, stageSlackFormOwnerConfiguration } from "./chat-channels/slack/form-owner.js";
|
||||
import { createSlackFormDeliveryOwner } from "./chat-channels/slack/form-delivery.js";
|
||||
@@ -830,8 +832,10 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
allowedStatuses: EndpointRow["status"][],
|
||||
) {
|
||||
const record = await endpointRecord(endpointId);
|
||||
const externalPhoton = record?.endpoint.provider === "imessage-photon" && context.discordGatewayOwned !== true
|
||||
&& await photonExternalRuntimeOwner.placement(record);
|
||||
if (
|
||||
record && leasedChatProvider(record.endpoint.provider) &&
|
||||
record && leasedChatProvider(record.endpoint.provider) && !externalPhoton &&
|
||||
!(await ensureDiscordGatewayRuntimeIsCurrent(endpointId, context))
|
||||
) {
|
||||
return null;
|
||||
@@ -843,7 +847,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
credentialFingerprint(record.credentialSecretRefs) ===
|
||||
context.credentialFingerprint &&
|
||||
runtime.get(endpointId) === context.endpointRuntime &&
|
||||
(!leasedChatProvider(record.endpoint.provider) ||
|
||||
(!leasedChatProvider(record.endpoint.provider) || externalPhoton ||
|
||||
discordGatewayRuntimeIsCurrent(endpointId, context))
|
||||
? record
|
||||
: null;
|
||||
@@ -905,6 +909,22 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
const { admitDiscordRootMention, discordRootThreadPending, reconcileDiscordRootThread, promoteDiscordRootReceipt } = createDiscordRootThreads(db, { ensureDiscordGatewayRuntimeIsCurrent, withCredentialMutationLease, runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, processMessage, redactError, scheduleConversationDrain, lifecycleRuntimeFence, runtimeFor, DISCORD_ROOT_THREAD_CONFIRMATION_DELAY_MS, discordRootThreadTransportBarrier: () => options.discordRootThreadTransportBarrier?.() ?? Promise.resolve() });
|
||||
const { handleDiscordGatewayEvent } = createDiscordGatewayEvents(db, { ensureDiscordGatewayRuntimeIsCurrent, discordGatewayRuntimeIsCurrent, runtimeCallbackRecord, runtimeCallbackEndpoint, applyProviderLifecycleEffect, runtimeGeneration, discordGatewayEventBarrier: (event) => options.discordGatewayEventBarrier?.(event) ?? Promise.resolve() });
|
||||
const { handlePhotonFailure, handlePhotonEvent } = createPhotonEvents(db, { runtimeCallbackRecord, runtimeCallbackEndpoint, invalidateRuntime, ensurePrincipal, requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, scheduleMessageProcessing, processPendingPublications, questionResponses, redactError, renewDiscordGatewayOwnershipForMessageAdmission, handleSdkMessage });
|
||||
const photonConnectorConfig = paperclipCloudConnectorConfigFromEnv();
|
||||
const photonConnector = photonConnectorConfig ? createPaperclipCloudConnector({ config: photonConnectorConfig }) : undefined;
|
||||
const photonExternalRuntimeOwner = createPhotonExternalRuntimeOwner(db, {
|
||||
broker: () => photonConnector,
|
||||
endpointRecord, runtimeFor, context: instance => runtimeContexts.get(instance),
|
||||
ownership: id => discordGatewayOwnerships.get(id), currentRuntime: id => runtime.get(id),
|
||||
release: ownership => stopDiscordGatewayOwnership(ownership, { removeRuntime: false, notifyStopped: false }),
|
||||
removeRuntime: async id => { runtimeVersions.delete(id); return runtime.removeEndpoint(id); },
|
||||
config: async record => {
|
||||
const config = runtimeConfig(record.endpoint, record.endpoint.botUsername ?? record.assignedAgentName, await resolveCredentials(record.endpoint));
|
||||
if (config.provider !== "imessage-photon") throw new Error("Photon external provider changed");
|
||||
return config;
|
||||
},
|
||||
admit: handlePhotonEvent,
|
||||
notify: id => { receiverWork?.changed(id); },
|
||||
});
|
||||
const { handleTelegramGenerationStopped, reserveTelegramPublicationDraft } = createTelegramPublicationDrafts(db, { runtimeCallbackRecord, runtimeCallbackEndpoint, runtimeFor, runtime, runtimeContexts, credentialFingerprint, authorizeRetainedChatSourcePublication });
|
||||
const { recordSlackFileUploadReceipt, stageSlackFilePublicationSuccess, processPendingSlackFileUploadReceipts, nextSlackReceiptAt } = createSlackFileReceipts(db, { endpointRecord, withCredentialMutationLease, runtimeCallbackEndpoint, nonDirectDestinationAllowed, runtimeFor, isExplicitOperatorPublication, recordExactOutboundPublicationLink });
|
||||
const { processPendingSlackSessionSyncs } = createSlackSessionStatus(db, { endpointRecord, withCredentialMutationLease, runtimeCallbackEndpoint, nonDirectDestinationAllowed, runIdFromMilestonePublication, resolveCredentials, fetchImpl, redactError, get slackSessionSyncSelectionBarrier() { return options.slackSessionSyncSelectionBarrier; } });
|
||||
@@ -967,6 +987,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
}
|
||||
const context = runtimeContextForRecord(record);
|
||||
const current = runtime.get(endpoint.id);
|
||||
const photonPlacement = record.endpoint.provider === "imessage-photon" ? await photonExternalRuntimeOwner.placement(record) : null;
|
||||
const currentDiscordOwnership = discordGatewayOwnerships.get(endpoint.id);
|
||||
const currentOwnsDiscordGateway =
|
||||
currentDiscordOwnership !== undefined &&
|
||||
@@ -974,6 +995,15 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
currentDiscordOwnership.context.version === context.version &&
|
||||
currentDiscordOwnership.context.endpointRuntime === current &&
|
||||
currentDiscordOwnership.expiresAt.getTime() > Date.now();
|
||||
if (current && photonPlacement && runtimeVersions.get(endpoint.id) === context.version
|
||||
&& optionsForRuntime.requireDiscordOwnership === true && !currentOwnsDiscordGateway) {
|
||||
const exactContext = runtimeContexts.get(current);
|
||||
if (!exactContext) throw new Error("Photon current sender context is unavailable");
|
||||
const owned = await acquireDiscordGatewayOwnership(record.endpoint, exactContext, optionsForRuntime.waitForDiscordOwnership === true);
|
||||
if (!owned) throw discordGatewayNotOwnedError();
|
||||
exactContext.discordGatewayOwned = true;
|
||||
return current;
|
||||
}
|
||||
if (
|
||||
current &&
|
||||
runtimeVersions.get(endpoint.id) === context.version &&
|
||||
@@ -1033,7 +1063,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
};
|
||||
const promise = (async () => {
|
||||
const discordOwnership =
|
||||
leasedChatProvider(record.endpoint.provider)
|
||||
leasedChatProvider(record.endpoint.provider) && (!photonPlacement || optionsForRuntime.requireDiscordOwnership === true)
|
||||
? await acquireDiscordGatewayOwnership(
|
||||
record.endpoint,
|
||||
context,
|
||||
@@ -1075,8 +1105,17 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
callbacks: {
|
||||
onMessage: (event) => handleSdkMessage(event, context),
|
||||
...createPhotonRuntimeCallbacks(db, { endpointId: endpoint.id, connectionId: endpoint.connectionId, companyId: record.endpoint.companyId, assignedAgentId: record.endpoint.assignedAgentId, context, lineId: credentials.lineId, runtimeCallbackRecord, runtimeCallbackEndpoint, renewDiscordGatewayOwnershipForMessageAdmission }),
|
||||
onPhotonUsefulClientDebt: () => photonExternalRuntimeOwner.senderDebt(endpoint.id),
|
||||
onPhotonIntakePlacement: async () => {
|
||||
const latest = await endpointRecord(endpoint.id);
|
||||
const external = latest && await photonExternalRuntimeOwner.placement(latest);
|
||||
return external ? { kind: "cloud", bindingId: external.binding.bindingId } : { kind: "local" };
|
||||
},
|
||||
onPhotonEvent: (event) => handlePhotonEvent(endpoint.id, event, context),
|
||||
onPhotonFailure: (error) => handlePhotonFailure(endpoint.id, error, context),
|
||||
onPhotonFailure: async error => {
|
||||
const result = await handlePhotonFailure(endpoint.id, error, context);
|
||||
return result?.kind === "recorded" ? result : photonExternalRuntimeOwner.cleanupFailure(endpoint.id, context);
|
||||
},
|
||||
onDiscordRootMentionAdmission:
|
||||
record.endpoint.provider === "discord"
|
||||
? (event) =>
|
||||
@@ -1187,7 +1226,9 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
}
|
||||
|
||||
const receiverSchedule = chatReceiverSchedule(db, {
|
||||
retained: scope => photonExternalRuntimeOwner.retained(scope),
|
||||
stop: async id => {
|
||||
await photonExternalRuntimeOwner.retire(id);
|
||||
const ownership = discordGatewayOwnerships.get(id);
|
||||
// Discovery already observed removal; only independent ownership loss needs another wake.
|
||||
if (ownership) await stopDiscordGatewayOwnership(ownership, { notifyStopped: false });
|
||||
@@ -1196,6 +1237,10 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
const record = await endpointRecord(id);
|
||||
if (!record) return "owned";
|
||||
try {
|
||||
if (record.endpoint.provider === "imessage-photon" && photonConnector) {
|
||||
await photonExternalRuntimeOwner.reconcile(id);
|
||||
if (await photonExternalRuntimeOwner.placement(record)) return "owned";
|
||||
}
|
||||
const instance = await runtimeFor(record.endpoint, { requireDiscordOwnership: true });
|
||||
await reconcileDiscordRuntime(id, instance);
|
||||
return "owned";
|
||||
@@ -3458,6 +3503,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
const { configure, configureWithCredentialLease, runtimeConfig } = createChatConfiguration(db, {
|
||||
stageConfigurationEffects: async (tx, endpointId, actorUserId) => {
|
||||
await stageSlackCloudEnrollmentIntent(tx, endpointId, actorUserId);
|
||||
await stagePhotonExternalConfiguration(tx, endpointId, actorUserId);
|
||||
const identity = slackForms.identity();
|
||||
if (identity) await stageSlackFormOwnerConfiguration(tx, endpointId, false, actorUserId ?? "", identity);
|
||||
},
|
||||
@@ -3602,6 +3648,8 @@ return {
|
||||
test,
|
||||
retrySlackFormReceipt: async (endpointId: string, actionId: string, management?: ConnectionManagementContext) => {
|
||||
if (!management) throw forbidden("Connection management authority is required");
|
||||
const retryRecord = await endpointRecord(endpointId);
|
||||
if (retryRecord?.endpoint.provider === "imessage-photon") return photonExternalRuntimeOwner.retry(endpointId, actionId, management);
|
||||
return retrySlackFormAcknowledgement(db, { companyId: management.resource.companyId, endpointId, actionId,
|
||||
identity: slackForms.identity, management });
|
||||
},
|
||||
@@ -3676,6 +3724,7 @@ return {
|
||||
voice.unregisterAgentTools();
|
||||
unregisterGitHubCloudIngress();
|
||||
unregisterSlackCloudIngress();
|
||||
await photonExternalRuntimeOwner.close();
|
||||
unregisterSlackFormWork();
|
||||
unregisterSlackCloudEnrollment();
|
||||
unregisterCommittedResponseAuthority();
|
||||
|
||||
@@ -97,13 +97,13 @@ export function createPhotonEvents(db: Db, options: PhotonEventsOptions) {
|
||||
error instanceof PhotonError
|
||||
? error.message
|
||||
: "Photon connection interrupted; reconnecting";
|
||||
await db.transaction(async (tx) => {
|
||||
const responsibility = await db.transaction(async (tx) => {
|
||||
const endpoint = await runtimeCallbackEndpoint(tx, endpointId, context, [
|
||||
"verifying",
|
||||
"active",
|
||||
"attention",
|
||||
]);
|
||||
if (!endpoint) return;
|
||||
if (!endpoint) return { kind: "obsolete" as const };
|
||||
await notifyChatReceiver(tx, endpoint);
|
||||
await tx
|
||||
.update(chatEndpoints)
|
||||
@@ -123,9 +123,11 @@ export function createPhotonEvents(db: Db, options: PhotonEventsOptions) {
|
||||
healthMessage: message,
|
||||
})
|
||||
.where(eq(toolConnections.id, endpoint.connectionId));
|
||||
return { kind: "recorded" as const };
|
||||
});
|
||||
// Retirement is queued outside the receiver callback to avoid self-joining.
|
||||
void invalidateRuntime(endpointId).catch(() => undefined);
|
||||
return responsibility;
|
||||
}
|
||||
|
||||
async function processPhotonResponse(
|
||||
@@ -759,11 +761,11 @@ export function createPhotonEvents(db: Db, options: PhotonEventsOptions) {
|
||||
// Late events from a removed chat must still advance recovery without a
|
||||
// now-forbidden chat lookup holding every other conversation behind them.
|
||||
if (removedGroup?.metadata.photonRemoved === true && !readded) return;
|
||||
const chat = await adapter.client.chats
|
||||
const chat = await adapter.withClient(client => client.chats
|
||||
.get(event.chatGuid)
|
||||
.catch((error) => {
|
||||
throw photonFailure(error);
|
||||
});
|
||||
}));
|
||||
if (chat.guid !== event.chatGuid || chat.service !== "iMessage" || (chat.isGroup && adapter.authentication.identity.allocation === "shared")) return;
|
||||
const threadId = photonThreadId({
|
||||
lineId: adapter.authentication.identity.lineId,
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { LiveEvent } from "@photon-ai/advanced-imessage";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { createHash } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import { decodePhotonRecoveryFrame } from "../../photon/recovery-transport.js";
|
||||
|
||||
const id = z.string().min(1).max(200);
|
||||
const sequence = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
export const photonExternalBindingSchema = z.object({
|
||||
version: z.literal(1), instanceId: id, environment: z.enum(["development", "test", "staging", "production"]),
|
||||
companyId: id, endpointId: id, connectionId: id, runtimeGeneration: sequence.positive(),
|
||||
projectId: z.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/), lineId: id, phoneNumber: id,
|
||||
allocation: z.enum(["dedicated", "shared"]), credentialFingerprint: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
bindingId: z.string().regex(/^photon-receiver:[a-f0-9]{64}$/), intakeAfter: z.string().datetime(),
|
||||
maxFrameBytes: sequence.positive(),
|
||||
}).strict();
|
||||
export type PhotonExternalBinding = z.infer<typeof photonExternalBindingSchema>;
|
||||
export const photonHash = (value: string | readonly (string | number | boolean | null)[]) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
||||
export const photonExternalIdentitySchema = z.object({
|
||||
companyId: id, endpointId: id, connectionId: id, runtimeGeneration: sequence.positive(),
|
||||
credentialReferences: z.string().regex(/^[a-f0-9]{64}$/), subject: id,
|
||||
}).strict();
|
||||
export type PhotonExternalIdentity = z.infer<typeof photonExternalIdentitySchema>;
|
||||
const identityKeys = ["companyId", "endpointId", "connectionId", "runtimeGeneration"] as const;
|
||||
export function assertPhotonExternalBinding(identity: PhotonExternalIdentity, binding: PhotonExternalBinding): void {
|
||||
if (identityKeys.some(key => identity[key] !== binding[key]) || binding.bindingId !== `photon-receiver:${photonHash([
|
||||
binding.instanceId, binding.companyId, binding.endpointId, binding.connectionId, binding.runtimeGeneration, binding.credentialFingerprint,
|
||||
])}`) throw new Error("Photon external owner identity changed");
|
||||
}
|
||||
export const photonExternalStateSchema = z.object({
|
||||
version: z.literal(1), identity: photonExternalIdentitySchema,
|
||||
handoffId: z.string().uuid(), localResourceId: z.string().uuid().nullable(),
|
||||
phase: z.enum(["enrolling", "joining", "external", "retiring", "retired"]),
|
||||
// The complete non-secret enrollment input survives an ambiguous broker reply.
|
||||
binding: photonExternalBindingSchema,
|
||||
acceptedRetirement: z.object({ binding: photonExternalBindingSchema, handoffId: z.string().uuid() }).strict().nullable(),
|
||||
initialSequence: sequence.nullable(),
|
||||
joinedSequence: sequence.nullable(), acceptedSequence: sequence.nullable(),
|
||||
pending: z.object({ deliveryId: id, sequence, previousSequence: sequence.nullable(), frameDigest: z.string().regex(/^[a-f0-9]{64}$/) }).strict().nullable(),
|
||||
failure: z.object({ code: z.enum(["enrollment", "local_join", "dispatch", "authority", "retirement", "sender_close"]), attempts: sequence.positive(), nextAttemptAt: z.string().datetime().nullable() }).strict().nullable(),
|
||||
}).strict();
|
||||
export type PhotonExternalState = z.infer<typeof photonExternalStateSchema>;
|
||||
export function readPhotonExternalState(value: unknown): PhotonExternalState | null {
|
||||
if (value === null) return null;
|
||||
const state = photonExternalStateSchema.parse(value);
|
||||
assertPhotonExternalBinding(state.identity, state.binding);
|
||||
if (state.phase === "external" && state.joinedSequence === null && state.initialSequence !== null
|
||||
|| state.pending && state.pending.sequence <= (state.acceptedSequence ?? -1)) throw new Error("Photon external custody invariant changed");
|
||||
return state;
|
||||
}
|
||||
export type PhotonExternalDeliveryPacket = {
|
||||
version: 1; binding: PhotonExternalBinding; sequence: number; previousSequence: number | null;
|
||||
acceptedAt: string; rawFrame: string;
|
||||
};
|
||||
export type ParsedPhotonExternalDelivery = {
|
||||
packet: PhotonExternalDeliveryPacket;
|
||||
event: LiveEvent;
|
||||
receipt: { deliveryId: string; sequence: number; previousSequence: number | null; frameDigest: string };
|
||||
};
|
||||
export function parsePhotonExternalDelivery(input: { id: string; event: string; createdAt: string; installationId: string | null; bindingIds: readonly string[]; payload: unknown }, state: PhotonExternalState): ParsedPhotonExternalDelivery {
|
||||
const packet = z.object({ version: z.literal(1), binding: photonExternalBindingSchema, sequence,
|
||||
previousSequence: sequence.nullable(), acceptedAt: z.string().datetime(), rawFrame: z.string().min(4),
|
||||
}).strict().parse(input.payload);
|
||||
if (!isDeepStrictEqual(packet.binding, state.binding) || packet.acceptedAt !== input.createdAt
|
||||
|| input.installationId !== state.binding.bindingId || input.bindingIds.length !== 1 || input.bindingIds[0] !== state.binding.bindingId
|
||||
|| input.id !== `photon_${photonHash([state.binding.bindingId, packet.sequence])}`
|
||||
|| packet.previousSequence !== null && packet.previousSequence >= packet.sequence)
|
||||
throw new Error("Photon external delivery binding changed");
|
||||
if (packet.rawFrame.length > Math.ceil(state.binding.maxFrameBytes / 3) * 4) throw new Error("Photon external encoded frame exceeds its bound");
|
||||
const bytes = Buffer.from(packet.rawFrame, "base64");
|
||||
if (bytes.toString("base64") !== packet.rawFrame || bytes.byteLength > state.binding.maxFrameBytes) throw new Error("Photon external frame bounds changed");
|
||||
const event = decodePhotonRecoveryFrame(bytes);
|
||||
if (!event || event.type === "catchup.complete" || event.type === "photon.ignored" || event.sequence !== packet.sequence || event.type !== input.event)
|
||||
throw new Error("Photon external recovery event changed");
|
||||
return { packet, event, receipt: { deliveryId: input.id, sequence: packet.sequence,
|
||||
previousSequence: packet.previousSequence, frameDigest: photonHash(packet.rawFrame) } };
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import type { LiveEvent } from "@photon-ai/advanced-imessage";
|
||||
import { PhotonState } from "../../photon/state.js";
|
||||
import { writePhotonCheckpoint } from "../../photon/receiver.js";
|
||||
import type { ResolvedPhotonChatConfig } from "../../chat-sdk-runtime.js";
|
||||
import { MAX_ATTACHMENT_BYTES } from "../../../attachment-types.js";
|
||||
import { PHOTON_EXTERNAL_STATE, type PhotonExternalStore, type PhotonExternalLease } from "./external-store.js";
|
||||
import { assertPhotonExternalBinding, photonExternalBindingSchema, photonHash, readPhotonExternalState,
|
||||
parsePhotonExternalDelivery, type PhotonExternalBinding, type PhotonExternalIdentity, type PhotonExternalState } from "./external-contract.js";
|
||||
|
||||
const CHECKPOINT_AUTHORITY = "checkpoint-authority";
|
||||
const checkpointIdentity = ({ subject: _subject, ...identity }: PhotonExternalIdentity) => identity;
|
||||
type Checkpoint = { schema: 1; lineId: string; sequence: number };
|
||||
export type PhotonCheckpointAuthority = Omit<PhotonExternalIdentity, "subject"> & { sequence: number };
|
||||
/** Called INSIDE the ordinary checkpoint SQL transaction before writing it.
|
||||
* Untagged initialized legacy history remains local-only attention for handoff;
|
||||
* neither a newer generation nor one successful request proves its provenance. */
|
||||
export async function checkpointAuthorityMayAdvance(state: PhotonState, identity: PhotonExternalIdentity): Promise<boolean> {
|
||||
const checkpoint = await state.read<Checkpoint>("checkpoint");
|
||||
const authority = await state.read<PhotonCheckpointAuthority>(CHECKPOINT_AUTHORITY);
|
||||
if (!checkpoint) return !(await state.read("receiver-initialized")) && authority === null;
|
||||
return authority !== null && isDeepStrictEqual(authority, { ...checkpointIdentity(identity), sequence: checkpoint.sequence });
|
||||
}
|
||||
export async function recordPhotonCheckpointAuthority(state: PhotonState, identity: PhotonExternalIdentity, sequence: number): Promise<void> {
|
||||
await state.update<PhotonCheckpointAuthority>(CHECKPOINT_AUTHORITY, () => ({ ...checkpointIdentity(identity), sequence }));
|
||||
}
|
||||
export async function handoffCheckpoint(state: PhotonState, identity: PhotonExternalIdentity, lineId: string): Promise<number | null> {
|
||||
const checkpoint = await state.read<Checkpoint>("checkpoint");
|
||||
if (!checkpoint) {
|
||||
if (await state.read("receiver-initialized")) throw new Error("Photon initialized history has no checkpoint");
|
||||
return null;
|
||||
}
|
||||
if (checkpoint.schema !== 1 || checkpoint.lineId !== lineId || !Number.isSafeInteger(checkpoint.sequence) || checkpoint.sequence < 0
|
||||
|| !await checkpointAuthorityMayAdvance(state, identity)) throw new Error("Photon legacy checkpoint provenance requires operator recovery");
|
||||
return checkpoint.sequence;
|
||||
}
|
||||
export interface PhotonExternalBroker {
|
||||
instanceIdentity(): { instanceId: string; environment: PhotonExternalBinding["environment"] };
|
||||
photonReceiverOperation(input: { subject: string; companyId: string; operation: Record<string, unknown> }): Promise<unknown>;
|
||||
}
|
||||
/** Resource IDs identify a retained object; ONLY awaiting its real close confirms
|
||||
* closure. An unknown object after restart is attention, never a lease-expiry proof. */
|
||||
export class PhotonLocalResources {
|
||||
private readonly resources = new Map<string, { close(): Promise<void>; closing?: Promise<void>; closed: boolean }>();
|
||||
private readonly objects = new WeakMap<object, string>();
|
||||
capture(object: object, close: () => Promise<void>): string {
|
||||
const existing = this.objects.get(object); if (existing) return existing;
|
||||
const id = randomUUID(); this.objects.set(object, id); this.resources.set(id, { close, closed: false }); return id;
|
||||
}
|
||||
async join(id: string): Promise<void> {
|
||||
const resource = this.resources.get(id);
|
||||
if (!resource) throw new Error("Photon original local resource closure is unknown");
|
||||
if (resource.closed) return;
|
||||
resource.closing ??= resource.close().then(() => { resource.closed = true; });
|
||||
try { await resource.closing; } catch (error) { resource.closing = undefined; throw error; }
|
||||
}
|
||||
known(id: string): boolean { return this.resources.has(id); }
|
||||
owns(id: string, object: object): boolean { return this.objects.get(object) === id && this.resources.has(id); }
|
||||
}
|
||||
export function createPhotonExternalOwner(options: { store: PhotonExternalStore; broker: PhotonExternalBroker;
|
||||
resources: PhotonLocalResources; notify(identity: PhotonExternalIdentity): void; now?: () => Date }) {
|
||||
const now = options.now ?? (() => new Date());
|
||||
async function failure(expected: PhotonExternalState, code: NonNullable<PhotonExternalState["failure"]>["code"]) {
|
||||
const attempts = (expected.failure?.attempts ?? 0) + 1;
|
||||
// Existing receiver coordinator consumes this deadline/notification; no timer.
|
||||
const nextAttemptAt = new Date(now().getTime() + Math.min(300_000, 30_000 * 2 ** Math.min(attempts - 1, 4))).toISOString();
|
||||
await options.store.retained(expected, value => ({ ...value, failure: { code, attempts, nextAttemptAt } }));
|
||||
options.notify(expected.identity);
|
||||
}
|
||||
async function fail(expected: PhotonExternalState, code: NonNullable<PhotonExternalState["failure"]>["code"], primary: unknown): Promise<never> {
|
||||
try { await failure(expected, code); }
|
||||
catch (cleanup) { throw new AggregateError([primary, cleanup], "Photon operation and responsibility persistence failed"); }
|
||||
throw primary;
|
||||
}
|
||||
async function reconcile(input: { identity: PhotonExternalIdentity; lease: PhotonExternalLease; config: ResolvedPhotonChatConfig;
|
||||
localResourceId: string | null }): Promise<PhotonExternalState> {
|
||||
const { identity, lease, config } = input;
|
||||
const instance = options.broker.instanceIdentity();
|
||||
const fingerprint = photonHash([instance.instanceId, instance.environment, identity.companyId, identity.endpointId, identity.connectionId,
|
||||
identity.runtimeGeneration, config.credentials.projectId, config.credentials.lineId, config.credentials.phoneNumber,
|
||||
(config.credentials.allocation ?? "dedicated"), photonHash(config.credentials.projectSecret)]);
|
||||
const binding = photonExternalBindingSchema.parse({ version: 1, ...instance, companyId: identity.companyId, endpointId: identity.endpointId,
|
||||
connectionId: identity.connectionId, runtimeGeneration: identity.runtimeGeneration, projectId: config.credentials.projectId,
|
||||
lineId: config.credentials.lineId, phoneNumber: config.credentials.phoneNumber, allocation: config.credentials.allocation ?? "dedicated",
|
||||
credentialFingerprint: fingerprint, bindingId: `photon-receiver:${photonHash([instance.instanceId, identity.companyId, identity.endpointId, identity.connectionId, identity.runtimeGeneration, fingerprint])}`,
|
||||
intakeAfter: new Date(config.intakeAfter).toISOString(), maxFrameBytes: MAX_ATTACHMENT_BYTES + 1024 * 1024 });
|
||||
let retained = await options.store.current(identity, lease, async (state, current) => {
|
||||
if (current && current.phase !== "retired") {
|
||||
if (!isDeepStrictEqual(current.binding, binding)) throw new Error("Photon original enrollment must finish retirement");
|
||||
return current;
|
||||
}
|
||||
const initialSequence = await handoffCheckpoint(state, identity, binding.lineId);
|
||||
return state.update<PhotonExternalState>(PHOTON_EXTERNAL_STATE, raw => {
|
||||
if (!isDeepStrictEqual(readPhotonExternalState(raw), current)) throw new Error("Photon external intent was installed concurrently");
|
||||
return { version: 1, identity, binding, handoffId: randomUUID(), localResourceId: input.localResourceId,
|
||||
phase: "enrolling", acceptedRetirement: current ? { binding: current.binding, handoffId: current.handoffId } : null, initialSequence, joinedSequence: null, acceptedSequence: null, pending: null, failure: null };
|
||||
});
|
||||
});
|
||||
if (retained.phase === "external") return retained;
|
||||
if (!["enrolling", "joining"].includes(retained.phase)) throw new Error("Photon receiver requires retirement reconciliation");
|
||||
if (retained.phase === "enrolling") {
|
||||
try {
|
||||
const reply = await options.broker.photonReceiverOperation({ subject: identity.subject, companyId: identity.companyId,
|
||||
operation: { kind: "enroll", enrollment: { companyId: identity.companyId, endpointId: identity.endpointId, connectionId: identity.connectionId,
|
||||
runtimeGeneration: identity.runtimeGeneration, projectId: binding.projectId, lineId: binding.lineId, phoneNumber: binding.phoneNumber,
|
||||
allocation: binding.allocation, intakeAfter: binding.intakeAfter, maxFrameBytes: binding.maxFrameBytes,
|
||||
...(retained.acceptedRetirement ? { acceptedRetirement: retained.acceptedRetirement } : {}),
|
||||
projectSecret: config.credentials.projectSecret, handoffId: retained.handoffId, initialized: retained.initialSequence !== null, sequence: retained.initialSequence } } });
|
||||
const response = z.object({ binding: photonExternalBindingSchema }).strict().parse(reply).binding;
|
||||
assertPhotonExternalBinding(identity, response);
|
||||
if (!isDeepStrictEqual(response, retained.binding)) throw new Error("Photon broker enrollment tuple changed");
|
||||
// Known external custody commits even if configure won after the request.
|
||||
retained = await options.store.retained(retained, value => ({ ...value, phase: "joining", failure: null }));
|
||||
} catch (error) { return fail(retained, "enrollment", error); }
|
||||
}
|
||||
try {
|
||||
if (retained.localResourceId !== null) await options.resources.join(retained.localResourceId);
|
||||
const expected = retained;
|
||||
retained = await options.store.current(identity, lease, async (state, current) => {
|
||||
if (!current || !isDeepStrictEqual(current, expected)) throw new Error("Photon handoff changed while joining");
|
||||
const joinedSequence = await handoffCheckpoint(state, identity, binding.lineId);
|
||||
if (expected.initialSequence !== null && (joinedSequence === null || joinedSequence < expected.initialSequence)) throw new Error("Photon joined checkpoint regressed");
|
||||
return state.update<PhotonExternalState>(PHOTON_EXTERNAL_STATE, () => ({ ...expected, phase: "external", joinedSequence, acceptedSequence: joinedSequence, failure: null }));
|
||||
});
|
||||
options.notify(identity);
|
||||
return retained;
|
||||
} catch (error) { return fail(retained, "local_join", error); }
|
||||
}
|
||||
async function dispatch(input: { identity: PhotonExternalIdentity; lease: PhotonExternalLease;
|
||||
delivery: { id: string; event: string; createdAt: string; installationId: string | null; bindingIds: readonly string[]; payload: unknown }; admit(event: LiveEvent): Promise<void> }): Promise<void> {
|
||||
const retained = await options.store.read(input.identity);
|
||||
if (!retained || retained.phase !== "external") throw new Error("Photon local join or retirement remains outstanding");
|
||||
const decoded = parsePhotonExternalDelivery(input.delivery, retained);
|
||||
const pending = await options.store.current(input.identity, input.lease, async (state, current) => {
|
||||
if (!current || current.phase !== "external" || !isDeepStrictEqual(current.binding, retained.binding)) throw new Error("Photon delivery owner changed");
|
||||
// The joined checkpoint already admitted the complete local prefix.
|
||||
if (decoded.packet.sequence <= (current.joinedSequence ?? -1)) return false;
|
||||
if (decoded.packet.sequence <= (current.acceptedSequence ?? -1)) return false;
|
||||
if (current.pending && !isDeepStrictEqual(current.pending, decoded.receipt)) throw new Error("Photon earlier delivery admission remains outstanding");
|
||||
const previous = decoded.packet.previousSequence;
|
||||
if (previous !== (current.acceptedSequence ?? null)
|
||||
&& !(current.acceptedSequence === current.joinedSequence && (previous ?? -1) <= (current.joinedSequence ?? -1)))
|
||||
throw new Error("Photon durable predecessor has not been admitted");
|
||||
await state.update<PhotonExternalState>(PHOTON_EXTERNAL_STATE, () => ({ ...current, pending: decoded.receipt }));
|
||||
return true;
|
||||
});
|
||||
if (!pending) return;
|
||||
// Actual normal Photon callback owns company authorization and idempotent
|
||||
// task/interaction admission. It may perform provider I/O, never inside SQL.
|
||||
await input.admit(decoded.event);
|
||||
await options.store.current(input.identity, input.lease, async (state, current) => {
|
||||
if (!current || current.phase !== "external" || !isDeepStrictEqual(current.pending, decoded.receipt)) throw new Error("Photon admission commit lost its current lease");
|
||||
await writePhotonCheckpoint(state, current.binding.lineId, decoded.packet.sequence);
|
||||
await recordPhotonCheckpointAuthority(state, input.identity, decoded.packet.sequence);
|
||||
await state.update<PhotonExternalState>(PHOTON_EXTERNAL_STATE, () => ({ ...current, pending: null, acceptedSequence: decoded.packet.sequence, failure: null }));
|
||||
});
|
||||
// Caller can now use ONLY the ordinary authenticated delivery ACK.
|
||||
}
|
||||
async function retire(retained: PhotonExternalState): Promise<void> {
|
||||
if (retained.phase === "retired") return;
|
||||
if (retained.phase !== "retiring") retained = await options.store.retained(retained, value => ({ ...value, phase: "retiring" }));
|
||||
try {
|
||||
if (retained.localResourceId !== null) await options.resources.join(retained.localResourceId);
|
||||
const request = { subject: retained.identity.subject, companyId: retained.identity.companyId };
|
||||
await options.broker.photonReceiverOperation({ ...request, operation: { kind: "retire", binding: retained.binding } });
|
||||
const response = z.object({ binding: photonExternalBindingSchema, handoffId: z.string().uuid(),
|
||||
phase: z.enum(["staged", "active", "retiring", "retired"]) }).strict().parse(await options.broker.photonReceiverOperation({ ...request, operation: { kind: "status", binding: retained.binding } }));
|
||||
if (!isDeepStrictEqual(response.binding, retained.binding) || response.handoffId !== retained.handoffId) throw new Error("Photon retirement tuple changed");
|
||||
if (response.phase !== "retired") throw new Error("Photon original physical close or queue drain remains outstanding");
|
||||
await options.store.retained(retained, value => ({ ...value, phase: "retired", failure: null }));
|
||||
options.notify(retained.identity);
|
||||
} catch (error) { return fail(retained, "retirement", error); }
|
||||
}
|
||||
return { reconcile, dispatch, retire };
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import type { ConnectionManagementContext } from "../../connection-management.js";
|
||||
import { logActivity } from "../../activity-log.js";
|
||||
import { forbidden, conflict, notFound } from "../../../errors.js";
|
||||
import { notifyChatReceiver } from "../runtime/receiver-work-notifications.js";
|
||||
import { PhotonChatAdapter } from "../../photon/adapter.js";
|
||||
import { and, eq, sql, gt, lte, desc } from "drizzle-orm";
|
||||
import { chatEndpoints, chatSdkState, type Db } from "@paperclipai/db";
|
||||
import type { LiveEvent } from "@photon-ai/advanced-imessage";
|
||||
import type { ChatEndpointRuntime } from "../../voice/voice-runtime.js";
|
||||
import type { ResolvedPhotonChatConfig } from "../../chat-sdk-runtime.js";
|
||||
import type { EndpointRecord, RuntimeContext, DiscordGatewayOwnership, InternalSetupState } from "../runtime-types.js";
|
||||
import { credentialFingerprint } from "../credential-fingerprint.js";
|
||||
import { createPhotonExternalStore, PHOTON_EXTERNAL_STATE } from "./external-store.js";
|
||||
import { createPhotonExternalOwner, PhotonLocalResources, type PhotonExternalBroker } from "./external-owner.js";
|
||||
import { readPhotonExternalState, parsePhotonExternalDelivery, type PhotonExternalIdentity } from "./external-contract.js";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
export type PhotonCloudDelivery = { id: string; event: string; createdAt: string; installationId: string | null; bindingIds: readonly string[]; payload: Record<string, unknown> };
|
||||
type Ingress = (event: PhotonCloudDelivery) => Promise<void>;
|
||||
const ingress = new WeakMap<Db, Ingress>();
|
||||
export async function dispatchPhotonCloudEvent(db: Db, event: PhotonCloudDelivery) {
|
||||
const owner = ingress.get(db); if (!owner) throw new Error("Photon normal authorized ingress is not ready");
|
||||
await owner(event);
|
||||
}
|
||||
const stateKey = `photon:${createHash("sha256").update(PHOTON_EXTERNAL_STATE).digest("hex")}`;
|
||||
type PhotonReceiverScope = { kind: "endpoint" | "connection" | "company"; id: string };
|
||||
/** Same keyset reconstruction pattern as the normal receiver owner. The upper
|
||||
* bound is captured once, so concurrent inserts cannot extend this scan forever;
|
||||
* their ordinary durable endpoint notifications remain independently pending.
|
||||
* Cost is 1 + ceil(snapshot rows / 100) reads, NOT a fixed SQL-lifetime bound. */
|
||||
async function* photonExternalRows(db: Db, scope?: PhotonReceiverScope) {
|
||||
const filter = and(eq(chatSdkState.stateKey, stateKey), scope?.kind === "endpoint" ? eq(chatSdkState.endpointId, scope.id) : undefined,
|
||||
scope?.kind === "company" ? eq(chatSdkState.companyId, scope.id) : undefined);
|
||||
const [last] = await db.select({ id: chatSdkState.id }).from(chatSdkState).where(filter).orderBy(desc(chatSdkState.id)).limit(1);
|
||||
if (!last) return;
|
||||
let after: string | undefined;
|
||||
while (true) {
|
||||
const rows = await db.select({ id: chatSdkState.id, companyId: chatSdkState.companyId, endpointId: chatSdkState.endpointId,
|
||||
connectionId: chatEndpoints.connectionId, value: chatSdkState.value }).from(chatSdkState).innerJoin(chatEndpoints,
|
||||
and(eq(chatEndpoints.companyId, chatSdkState.companyId), eq(chatEndpoints.id, chatSdkState.endpointId)))
|
||||
.where(and(filter, lte(chatSdkState.id, last.id), after ? gt(chatSdkState.id, after) : undefined)).orderBy(chatSdkState.id).limit(100);
|
||||
for (const row of rows) if (scope?.kind !== "connection" || row.connectionId === scope.id) yield row;
|
||||
if (rows.length < 100 || rows[rows.length - 1].id === last.id) return;
|
||||
after = rows[rows.length - 1].id;
|
||||
}
|
||||
}
|
||||
export async function readPhotonRetainedConsumer(db: Db, identity: { instanceId: string; environment: string }) {
|
||||
// Settled history never hides an unfinished tail behind a LIMIT-before-filter.
|
||||
const attention: string[] = [];
|
||||
let owner: { subject: string; companyId: string } | null = null;
|
||||
for await (const row of photonExternalRows(db)) {
|
||||
try {
|
||||
const retained = readPhotonExternalState(row.value);
|
||||
if (!retained || retained.identity.companyId !== row.companyId || retained.identity.endpointId !== row.endpointId
|
||||
|| retained.binding.instanceId !== identity.instanceId || retained.binding.environment !== identity.environment) throw new Error("Photon retained identity changed");
|
||||
if (retained.phase !== "retired" && !owner) owner = { subject: retained.identity.subject, companyId: row.companyId };
|
||||
} catch { if (attention.length < 100) attention.push("photon_retained_identity_invalid"); }
|
||||
}
|
||||
return { owner, attention };
|
||||
}
|
||||
export function createPhotonExternalRuntimeOwner(db: Db, options: {
|
||||
broker(): PhotonExternalBroker | undefined;
|
||||
endpointRecord(id: string): Promise<EndpointRecord | null>;
|
||||
runtimeFor(endpoint: EndpointRecord["endpoint"], input: { requireDiscordOwnership?: boolean }): Promise<ChatEndpointRuntime>;
|
||||
context(runtime: ChatEndpointRuntime): RuntimeContext | undefined;
|
||||
ownership(id: string): DiscordGatewayOwnership | undefined;
|
||||
release(ownership: DiscordGatewayOwnership): Promise<void>;
|
||||
currentRuntime(id: string): ChatEndpointRuntime | null;
|
||||
removeRuntime(id: string): Promise<boolean>;
|
||||
config(record: EndpointRecord): Promise<ResolvedPhotonChatConfig>;
|
||||
admit(id: string, event: LiveEvent, context: RuntimeContext): Promise<void>;
|
||||
notify(id: string): void;
|
||||
}) {
|
||||
const store = createPhotonExternalStore(db), resources = new PhotonLocalResources();
|
||||
const active = new Map<string, Promise<void>>();
|
||||
async function selected(record: EndpointRecord) {
|
||||
const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject;
|
||||
if (!subject) return null;
|
||||
const identity: PhotonExternalIdentity = { companyId: record.endpoint.companyId, endpointId: record.endpoint.id,
|
||||
connectionId: record.endpoint.connectionId, runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0),
|
||||
credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject };
|
||||
const retained = await store.inspect(identity), connector = options.broker()?.instanceIdentity();
|
||||
if (!retained || retained.phase !== "external" || !isDeepStrictEqual(retained.identity, identity)
|
||||
|| !connector || retained.binding.instanceId !== connector.instanceId || retained.binding.environment !== connector.environment) return null;
|
||||
return retained;
|
||||
}
|
||||
async function placement(record: EndpointRecord) {
|
||||
if (record.endpoint.provider !== "imessage-photon") return null;
|
||||
return selected(record);
|
||||
}
|
||||
async function reconcile(id: string): Promise<void> {
|
||||
const pending = active.get(id); if (pending) return pending;
|
||||
const run = (async () => {
|
||||
const record = await options.endpointRecord(id), broker = options.broker();
|
||||
if (!record || record.endpoint.provider !== "imessage-photon" || !(record.endpoint.setup as InternalSetupState).photonExternalSubject || !broker) return;
|
||||
const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject;
|
||||
if (!subject) return;
|
||||
const identity: PhotonExternalIdentity = { companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId,
|
||||
runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0), credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject };
|
||||
const previous = await store.read(identity);
|
||||
if (previous && previous.phase !== "retired" && (previous.phase === "retiring"
|
||||
|| !isDeepStrictEqual(previous.identity, identity) || !["active", "verifying", "attention"].includes(record.endpoint.status))) {
|
||||
await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).retire(previous);
|
||||
return;
|
||||
}
|
||||
const external = await placement(record);
|
||||
if (external) {
|
||||
const adapter = options.currentRuntime(id)?.getProviderAdapter();
|
||||
if (adapter instanceof PhotonChatAdapter) await adapter.drainUsefulClient();
|
||||
else if (external.failure?.code === "sender_close" && !await options.removeRuntime(id)) throw new Error("Photon original sender physical closure is unknown");
|
||||
if (external.failure?.code === "sender_close") await store.retained(external, value => ({ ...value, failure: null }));
|
||||
return;
|
||||
}
|
||||
const runtime = await options.runtimeFor(record.endpoint, { requireDiscordOwnership: true });
|
||||
const context = options.context(runtime), lease = options.ownership(id);
|
||||
if (!context || !lease || lease.context !== context || context.endpointRuntime !== runtime || lease.stopping) throw new Error("Photon normal local resource lease changed");
|
||||
const currentIdentity: PhotonExternalIdentity = { companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId,
|
||||
runtimeGeneration: context.generation, credentialReferences: context.credentialFingerprint, subject };
|
||||
const owner = createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) });
|
||||
// Keep the real runtime in the normal registry through shutdown. Its failure
|
||||
// persistence callbacks still see the exact current object/lease; removing
|
||||
// it first would turn cleanup debt into an obsolete-context no-op.
|
||||
const resourceId = resources.capture(runtime, async () => { await runtime.shutdown(); });
|
||||
await owner.reconcile({ identity: currentIdentity, lease, config: await options.config(record), localResourceId: resourceId });
|
||||
await options.removeRuntime(id);
|
||||
await options.release(lease);
|
||||
context.discordGatewayOwned = false;
|
||||
// The SDK client was physically closed. Normal runtimeFor builds a NEW
|
||||
// useful sender, with placement verified from committed external state.
|
||||
// No eager sender/client is created merely to be idle. The next genuine
|
||||
// ordinary publication or Cloud admission calls normal runtimeFor.
|
||||
})();
|
||||
active.set(id, run);
|
||||
try { await run; } finally { if (active.get(id) === run) active.delete(id); }
|
||||
}
|
||||
const receive: Ingress = async event => {
|
||||
const packet = event.payload.photonEvent;
|
||||
if (!packet || typeof packet !== "object" || Array.isArray(packet)) throw new Error("Photon sealed packet is missing");
|
||||
const raw = Reflect.get(packet, "binding");
|
||||
if (!raw || typeof raw !== "object" || typeof Reflect.get(raw, "endpointId") !== "string") throw new Error("Photon sealed binding is invalid");
|
||||
const record = await options.endpointRecord(Reflect.get(raw, "endpointId"));
|
||||
if (!record) throw new Error("Photon retained endpoint requires retirement attention");
|
||||
const retained = await placement(record), broker = options.broker();
|
||||
if (!retained) {
|
||||
const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject;
|
||||
if (!subject) throw new Error("Photon original subject is unavailable");
|
||||
const previous = await store.read({ companyId: record.endpoint.companyId, endpointId: record.endpoint.id, connectionId: record.endpoint.connectionId,
|
||||
runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0), credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject });
|
||||
if (!previous || previous.phase !== "retiring" || !broker) throw new Error("Photon exact retired delivery owner is unavailable");
|
||||
const decoded = parsePhotonExternalDelivery({ ...event, payload: packet }, previous);
|
||||
await store.noEffect(previous, decoded.packet.sequence);
|
||||
options.notify(record.endpoint.id);
|
||||
return;
|
||||
}
|
||||
if (!broker) throw new Error("Photon exact external owner is not currently dispatchable");
|
||||
const runtime = await options.runtimeFor(record.endpoint, { requireDiscordOwnership: true });
|
||||
const context = options.context(runtime), lease = options.ownership(record.endpoint.id);
|
||||
if (!context || !lease || lease.context !== context || lease.stopping) throw new Error("Photon short admission lease is unavailable");
|
||||
try {
|
||||
const owner = createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) });
|
||||
await owner.dispatch({ identity: retained.identity, lease, delivery: { ...event, payload: packet },
|
||||
admit: value => options.admit(record.endpoint.id, value, context) });
|
||||
} finally {
|
||||
// Keep the useful sender; retire ONLY the short receiver admission lease.
|
||||
await options.release(lease); context.discordGatewayOwned = false;
|
||||
}
|
||||
};
|
||||
async function senderDebt(id: string) {
|
||||
const record = await options.endpointRecord(id);
|
||||
if (!record) throw new Error("Photon sender debt has no retained endpoint");
|
||||
const external = await placement(record);
|
||||
if (!external) 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);
|
||||
}
|
||||
async function retire(id: string) {
|
||||
const record = await options.endpointRecord(id), broker = options.broker();
|
||||
if (!record || !broker) return;
|
||||
const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject;
|
||||
if (!subject) return;
|
||||
const retained = await store.read({ companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId,
|
||||
runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0), credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject });
|
||||
if (retained && retained.phase !== "retired") await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).retire(retained);
|
||||
}
|
||||
async function retained(scope?: { kind: "endpoint" | "connection" | "company"; id: string }) {
|
||||
const values = [];
|
||||
for await (const row of photonExternalRows(db, scope)) {
|
||||
let state;
|
||||
try {
|
||||
state = readPhotonExternalState(row.value);
|
||||
if (!state || state.identity.companyId !== row.companyId || state.identity.endpointId !== row.endpointId) throw new Error("Photon retained receiver identity changed");
|
||||
} catch {
|
||||
// Keep malformed debt on its own existing endpoint owner. The coordinator
|
||||
// records/retries that failure while still visiting unrelated endpoints.
|
||||
if (scope?.kind !== "connection" || row.connectionId === scope.id) values.push({ id: row.endpointId, companyId: row.companyId, connectionId: row.connectionId, dueAt: 0 });
|
||||
continue;
|
||||
}
|
||||
if (state.phase === "retired" || scope?.kind === "connection" && state.identity.connectionId !== scope.id) continue;
|
||||
values.push({ id: row.endpointId, companyId: row.companyId, connectionId: state.identity.connectionId,
|
||||
dueAt: state.phase === "external" && !state.failure ? null : state.failure?.nextAttemptAt ? Date.parse(state.failure.nextAttemptAt) : 0 });
|
||||
}
|
||||
return values;
|
||||
}
|
||||
async function cleanupFailure(id: string, context: RuntimeContext): Promise<{ kind: "recorded" } | { kind: "obsolete" }> {
|
||||
const record = await options.endpointRecord(id);
|
||||
const subject = record && (record.endpoint.setup as InternalSetupState).photonExternalSubject;
|
||||
if (!record || !subject || !context.endpointRuntime) return { kind: "obsolete" };
|
||||
const state = await store.read({ companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId,
|
||||
runtimeGeneration: context.generation, credentialReferences: context.credentialFingerprint, subject });
|
||||
if (!state?.localResourceId || !resources.owns(state.localResourceId, context.endpointRuntime)
|
||||
|| !["joining", "retiring"].includes(state.phase)) return { kind: "obsolete" };
|
||||
await store.retained(state, value => ({ ...value, failure: { code: "local_join", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } }));
|
||||
options.notify(id);
|
||||
return { kind: "recorded" };
|
||||
}
|
||||
async function retry(endpointId: string, actionId: string, management: ConnectionManagementContext) {
|
||||
await management.reauthorize();
|
||||
const record = await options.endpointRecord(endpointId), broker = options.broker();
|
||||
if (!record || record.endpoint.provider !== "imessage-photon") throw notFound("Photon endpoint not found");
|
||||
const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject;
|
||||
if (!subject || !broker || !management.responsibleUserId || !management.decision.allowed || management.decision.action !== "connections:configure"
|
||||
|| management.resource.companyId !== record.endpoint.companyId || management.resource.connectionId && management.resource.connectionId !== record.endpoint.connectionId)
|
||||
throw forbidden("Current company connection authority is required");
|
||||
const state = await store.read({ companyId: record.endpoint.companyId, endpointId, connectionId: record.endpoint.connectionId,
|
||||
runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0), credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject });
|
||||
const connector = broker.instanceIdentity();
|
||||
if (!state || state.handoffId !== actionId || state.binding.instanceId !== connector.instanceId || state.binding.environment !== connector.environment)
|
||||
throw conflict("Photon retained retry identity changed");
|
||||
if (state.phase === "retired") return { actionId, state: "complete" as const };
|
||||
if (state.localResourceId !== null && !resources.known(state.localResourceId) && ["joining", "retiring"].includes(state.phase))
|
||||
throw conflict("Photon original stream closure is unknown; restore its owning process or establish real resource closure before retry");
|
||||
if (state.phase === "external") await broker.photonReceiverOperation({ subject: management.responsibleUserId, companyId: state.identity.companyId,
|
||||
operation: { kind: "retry", binding: state.binding } });
|
||||
await management.reauthorize();
|
||||
await store.retained(state, value => ({ ...value, failure: value.failure ? { ...value.failure, nextAttemptAt: new Date().toISOString() } : null }), async tx => {
|
||||
await management.reauthorize();
|
||||
await logActivity(tx, { ...management.audit, companyId: state.identity.companyId, action: "chat.photon_external_owner.retry",
|
||||
entityType: "chat_endpoint", entityId: endpointId, details: { handoffId: actionId, phase: state.phase } });
|
||||
await notifyChatReceiver(tx, { id: endpointId, provider: "imessage-photon" });
|
||||
});
|
||||
options.notify(endpointId);
|
||||
return { actionId, state: "scheduled" as const };
|
||||
}
|
||||
ingress.set(db, receive);
|
||||
return { reconcile, placement, senderDebt, retire, retained, cleanupFailure, retry, close() { if (ingress.get(db) === receive) ingress.delete(db); return Promise.all([...active.values()]).then(() => undefined); } };
|
||||
}
|
||||
|
||||
/** Called by normal configuration SQL with its actual authorized actor. Existing
|
||||
* retained SDK state is deliberately untouched until its original owner retires. */
|
||||
export async function stagePhotonExternalConfiguration(db: Pick<Db, "select" | "update">, endpointId: string, subject: string | null | undefined) {
|
||||
if (!subject) return;
|
||||
await db.update(chatEndpoints).set({ setup: sql`jsonb_set(${chatEndpoints.setup}, '{photonExternalSubject}', ${JSON.stringify(subject)}::jsonb)` })
|
||||
.where(and(eq(chatEndpoints.id, endpointId), eq(chatEndpoints.provider, "imessage-photon")));
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { and, eq, gt } from "drizzle-orm";
|
||||
import { chatEndpoints, chatEndpointLeases, toolConnections, type Db } from "@paperclipai/db";
|
||||
import type { InternalSetupState } from "../runtime-types.js";
|
||||
import { credentialFingerprint } from "../credential-fingerprint.js";
|
||||
import { PhotonState } from "../../photon/state.js";
|
||||
import { createChatSdkStatePersistence } from "../sdk-state.js";
|
||||
import { readPhotonExternalState, type PhotonExternalIdentity, type PhotonExternalState } from "./external-contract.js";
|
||||
|
||||
export const PHOTON_EXTERNAL_STATE = "external-owner";
|
||||
type Transaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
export type PhotonExternalLease = { token: string };
|
||||
export function photonStateFor(db: Pick<Db, "select" | "insert" | "update" | "delete">, identity: Pick<PhotonExternalIdentity, "companyId" | "endpointId">) {
|
||||
return new PhotonState(identity, createChatSdkStatePersistence(db));
|
||||
}
|
||||
/** All callbacks are SQL-only. Provider I/O and resource joining happen outside. */
|
||||
export function createPhotonExternalStore(db: Db) {
|
||||
async function lock(tx: Transaction, identity: PhotonExternalIdentity) {
|
||||
const [endpoint] = await tx.select().from(chatEndpoints).where(and(eq(chatEndpoints.companyId, identity.companyId), eq(chatEndpoints.id, identity.endpointId))).for("no key update");
|
||||
if (!endpoint || endpoint.provider !== "imessage-photon") throw new Error("Photon external endpoint is unavailable");
|
||||
return endpoint;
|
||||
}
|
||||
return {
|
||||
async read(identity: PhotonExternalIdentity) {
|
||||
return readPhotonExternalState(await photonStateFor(db, identity).read(PHOTON_EXTERNAL_STATE));
|
||||
},
|
||||
async inspect(identity: PhotonExternalIdentity) {
|
||||
return db.transaction(async tx => {
|
||||
const endpoint = await lock(tx, identity);
|
||||
const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.companyId, identity.companyId), eq(toolConnections.id, identity.connectionId))).for("share");
|
||||
if (!["active", "verifying", "attention"].includes(endpoint.status) || endpoint.connectionId !== identity.connectionId
|
||||
|| (endpoint.setup as InternalSetupState).runtimeGeneration !== identity.runtimeGeneration || !connection?.enabled
|
||||
|| connection.status !== "active" || connection.healthStatus === "failed" || credentialFingerprint(connection.credentialSecretRefs) !== identity.credentialReferences) return null;
|
||||
return readPhotonExternalState(await photonStateFor(tx, identity).read(PHOTON_EXTERNAL_STATE));
|
||||
});
|
||||
},
|
||||
async current<T>(identity: PhotonExternalIdentity, lease: PhotonExternalLease, work: (state: PhotonState, current: PhotonExternalState | null) => Promise<T>): Promise<T> {
|
||||
return db.transaction(async tx => {
|
||||
const endpoint = await lock(tx, identity);
|
||||
const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.companyId, identity.companyId), eq(toolConnections.id, identity.connectionId))).for("share");
|
||||
const [owner] = await tx.select().from(chatEndpointLeases).where(and(eq(chatEndpointLeases.companyId, identity.companyId),
|
||||
eq(chatEndpointLeases.endpointId, identity.endpointId), eq(chatEndpointLeases.leaseKey, "photon_receiver_runtime"),
|
||||
eq(chatEndpointLeases.token, lease.token), gt(chatEndpointLeases.expiresAt, new Date()))).for("update");
|
||||
if (!owner || !["active", "verifying", "attention"].includes(endpoint.status) || endpoint.connectionId !== identity.connectionId
|
||||
|| (endpoint.setup as InternalSetupState).runtimeGeneration !== identity.runtimeGeneration || !connection?.enabled || connection.status !== "active" || connection.healthStatus === "failed"
|
||||
|| credentialFingerprint(connection.credentialSecretRefs) !== identity.credentialReferences)
|
||||
throw new Error("Photon external current authority changed");
|
||||
const state = photonStateFor(tx, identity), current = readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE));
|
||||
if (current && current.phase !== "retired" && !isDeepStrictEqual(current.identity, identity)) throw new Error("Photon prior owner must finish retirement");
|
||||
return work(state, current);
|
||||
});
|
||||
},
|
||||
async noEffect(expected: PhotonExternalState, sequence: number) {
|
||||
return db.transaction(async tx => {
|
||||
const endpoint = await lock(tx, expected.identity);
|
||||
const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.companyId, expected.identity.companyId), eq(toolConnections.id, endpoint.connectionId))).for("share");
|
||||
const superseded = !["active", "verifying", "attention"].includes(endpoint.status)
|
||||
|| endpoint.connectionId !== expected.identity.connectionId || (endpoint.setup as InternalSetupState).runtimeGeneration !== expected.identity.runtimeGeneration
|
||||
|| !connection?.enabled || connection.status !== "active" || connection.healthStatus === "failed" || credentialFingerprint(connection.credentialSecretRefs) !== expected.identity.credentialReferences;
|
||||
if (!superseded || expected.phase !== "retiring") throw new Error("Photon no-effect requires actual current revocation");
|
||||
const updated = await photonStateFor(tx, expected.identity).update<PhotonExternalState>(PHOTON_EXTERNAL_STATE, raw => {
|
||||
const current = readPhotonExternalState(raw);
|
||||
if (!current || !isDeepStrictEqual(current.binding, expected.binding) || current.phase !== "retiring") throw new Error("Photon no-effect owner changed");
|
||||
return { ...current, acceptedSequence: Math.max(current.acceptedSequence ?? -1, sequence), pending: null };
|
||||
});
|
||||
return updated;
|
||||
});
|
||||
},
|
||||
/** Preserve an already accepted broker/resource result even if configure won.
|
||||
* This cannot activate or grant use: it only replaces the exact retained intent. */
|
||||
async retained(expected: PhotonExternalState, update: (state: PhotonExternalState) => PhotonExternalState, after?: (tx: Transaction) => Promise<void>) {
|
||||
return db.transaction(async tx => {
|
||||
await lock(tx, expected.identity);
|
||||
const updated = await photonStateFor(tx, expected.identity).update<PhotonExternalState>(PHOTON_EXTERNAL_STATE, raw => {
|
||||
const current = readPhotonExternalState(raw);
|
||||
if (!current || !isDeepStrictEqual(current, expected)) throw new Error("Photon retained intent changed concurrently");
|
||||
const next = update(current);
|
||||
if (!isDeepStrictEqual(next.identity, current.identity) || !isDeepStrictEqual(next.binding, current.binding)
|
||||
|| next.handoffId !== current.handoffId || next.localResourceId !== current.localResourceId
|
||||
|| next.initialSequence !== current.initialSequence || next.phase === "external" && current.phase !== "external")
|
||||
throw new Error("Photon retained update cannot change authority");
|
||||
const parsed = readPhotonExternalState(next);
|
||||
if (!parsed) throw new Error("Photon retained result disappeared");
|
||||
return parsed;
|
||||
});
|
||||
await after?.(tx);
|
||||
return updated;
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
export type PhotonExternalStore = ReturnType<typeof createPhotonExternalStore>;
|
||||
@@ -1,3 +1,4 @@
|
||||
import { checkpointAuthorityMayAdvance, recordPhotonCheckpointAuthority } from "./external-owner.js";
|
||||
import { createChatSdkStatePersistence } from "../sdk-state.js";
|
||||
import { notifyChatEndpointWork } from "../../chat-work-notifications.js";
|
||||
import { writePhotonCheckpoint } from "../../photon/receiver.js";
|
||||
@@ -39,7 +40,12 @@ export function createPhotonRuntimeCallbacks(db: Db, options: PhotonRuntimeOptio
|
||||
onPhotonCheckpoint: (sequence) => db.transaction(async (tx) => {
|
||||
if (!(await runtimeCallbackEndpoint(tx, endpointId, context, ["verifying", "active"]))) throw new Error("Photon receiver is no longer current");
|
||||
if ((await renewDiscordGatewayOwnershipForMessageAdmission(tx, endpointId, context)).kind !== "owned") throw new Error("Photon receiver lease was replaced");
|
||||
await writePhotonCheckpoint(new PhotonState({ companyId: companyId, endpointId: endpointId }, createChatSdkStatePersistence(tx as unknown as Db)), lineId, sequence);
|
||||
const state = new PhotonState({ companyId, endpointId }, createChatSdkStatePersistence(tx));
|
||||
const identity = { companyId, endpointId, connectionId, runtimeGeneration: context.generation,
|
||||
credentialReferences: context.credentialFingerprint, subject: "checkpoint-only" };
|
||||
const provenance = await checkpointAuthorityMayAdvance(state, identity);
|
||||
await writePhotonCheckpoint(state, lineId, sequence);
|
||||
if (provenance) await recordPhotonCheckpointAuthority(state, identity, sequence);
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ export type SlackCallbackObservation = { url: string; observedAt: string };
|
||||
|
||||
export type InternalSetupState = ChatEndpointSetupState & {
|
||||
photonIntakeAfter?: string;
|
||||
photonExternalSubject?: string;
|
||||
runtimeGeneration?: number;
|
||||
/** Binds pre-install URL verification to the signing secret later configured. */
|
||||
slackVerificationSigningFingerprint?: string;
|
||||
|
||||
@@ -9,6 +9,7 @@ export type ReceiverDeadline = { id: string; companyId: string; connectionId: st
|
||||
export function chatReceiverSchedule(db: Db, receiver: {
|
||||
reconcile: (id: string) => Promise<"owned" | "foreign">;
|
||||
stop: (id: string) => Promise<void>;
|
||||
retained?: (scope?: ReceiverScope) => Promise<ReceiverDeadline[]>;
|
||||
}) {
|
||||
async function load(scope?: ReceiverScope, signal?: AbortSignal): Promise<ReceiverDeadline[]> {
|
||||
const result: ReceiverDeadline[] = [];
|
||||
@@ -28,7 +29,12 @@ export function chatReceiverSchedule(db: Db, receiver: {
|
||||
cursor ? gt(chatEndpoints.id, cursor) : undefined,
|
||||
)).orderBy(chatEndpoints.id).limit(100);
|
||||
result.push(...rows.map(row => ({ ...row, dueAt: 0 })));
|
||||
if (rows.length < 100) return result;
|
||||
if (rows.length < 100) {
|
||||
const retained = await receiver.retained?.(scope) ?? [];
|
||||
const merged = new Map(result.map(row => [row.id, row]));
|
||||
for (const row of retained) merged.set(row.id, row);
|
||||
return [...merged.values()];
|
||||
}
|
||||
cursor = rows[rows.length - 1].id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import type {
|
||||
ChatSdkStateScope,
|
||||
} from "../chat-sdk-state.js";
|
||||
|
||||
export function createChatSdkStatePersistence(db: Db): ChatSdkStatePersistence {
|
||||
export function createChatSdkStatePersistence(db: Pick<Db, "select" | "insert" | "update" | "delete">): ChatSdkStatePersistence {
|
||||
return {
|
||||
async read(scope: ChatSdkStateScope, key: string) {
|
||||
return db
|
||||
|
||||
@@ -2,7 +2,7 @@ import { isPassiveSlackAction, normalizeSlackSelectionAction, slackSelectionValu
|
||||
import { PhotonChatAdapter, parsePhotonThreadId } from "./photon/adapter.js";
|
||||
import { PhotonLineAuthentication } from "./photon/cloud.js";
|
||||
import { PhotonState } from "./photon/state.js";
|
||||
import { PhotonReceiver } from "./photon/receiver.js";
|
||||
import { PhotonReceiver, type PhotonFailureResponsibility } from "./photon/receiver.js";
|
||||
import { photonAttachmentLocator, photonAttachmentLocatorSchema, downloadPhotonAttachment, type PhotonAttachmentLocator } from "./photon/attachments.js";
|
||||
import type { LiveEvent as PhotonEvent } from "@photon-ai/advanced-imessage";
|
||||
import {
|
||||
@@ -469,10 +469,14 @@ export interface DiscordGatewayCallbackEvent extends ChatSdkCallbackEvent<Discor
|
||||
* Chat SDK event escape hatches; callers must never publish them directly.
|
||||
*/
|
||||
export interface ChatSdkRuntimeCallbacks {
|
||||
/** Photon leaf validates committed external custody. Absence keeps local intake. */
|
||||
onPhotonUsefulClientDebt?(): Promise<void>;
|
||||
onPhotonIntakePlacement?(): Promise<{ kind: "local" } | { kind: "cloud"; bindingId: string }>;
|
||||
|
||||
onPhotonEvent?(event: PhotonEvent): Promise<void>;
|
||||
onPhotonAssertOwned?(activeThreadId?: string): Promise<void>;
|
||||
onPhotonCheckpoint?(sequence: number): Promise<void>;
|
||||
onPhotonFailure?(error: unknown): Promise<void>;
|
||||
onPhotonFailure?(error: unknown): Promise<void | PhotonFailureResponsibility>;
|
||||
onMessage(event: ChatSdkMessageCallbackEvent): Promise<void> | void;
|
||||
onTelegramGenerationStopped?(
|
||||
event: ChatSdkCallbackEvent<TelegramGenerationStoppedProof>,
|
||||
@@ -2295,17 +2299,24 @@ export class ChatSdkEndpointRuntime {
|
||||
async initialize(): Promise<void> {
|
||||
await this.initializeChat();
|
||||
this.assertNotRetired();
|
||||
if (this.adapter instanceof PhotonChatAdapter && this.discordGatewayEnabled && !this.photonReceiver) {
|
||||
if (this.adapter instanceof PhotonChatAdapter && !this.photonReceiver) {
|
||||
const options = this.runtimeOptions;
|
||||
const config = options.providerConfig as ResolvedPhotonChatConfig;
|
||||
if (!options.callbacks.onPhotonCheckpoint || !options.callbacks.onPhotonAssertOwned || !options.callbacks.onPhotonEvent || !options.callbacks.onPhotonFailure) throw new Error("Photon receiver requires durable admission callbacks");
|
||||
this.adapter.typingGuard = async (activeThreadId) => { this.assertNotRetired(); await options.callbacks.onPhotonAssertOwned!(activeThreadId); };
|
||||
const placement = await options.callbacks.onPhotonIntakePlacement?.() ?? { kind: "local" };
|
||||
if (placement.kind === "cloud") {
|
||||
this.adapter.onUsefulClientDebt = options.callbacks.onPhotonUsefulClientDebt;
|
||||
await this.adapter.useExternalIntake();
|
||||
}
|
||||
if (placement.kind === "local" && this.discordGatewayEnabled) {
|
||||
this.photonReceiver = new PhotonReceiver({ client: this.adapter.client, state: this.adapter.state,
|
||||
lineId: config.credentials.lineId, intakeAfter: config.intakeAfter, allocation: config.credentials.allocation,
|
||||
catchUp: (sequence) => (this.adapter as PhotonChatAdapter).recoveryStream(sequence),
|
||||
assertOwned: async () => { this.assertNotRetired(); await (this.adapter as PhotonChatAdapter).authentication.token(); await options.callbacks.onPhotonAssertOwned!(); },
|
||||
commitCheckpoint: options.callbacks.onPhotonCheckpoint, admit: options.callbacks.onPhotonEvent, failure: options.callbacks.onPhotonFailure });
|
||||
this.photonReceiver.start();
|
||||
}
|
||||
}
|
||||
if (this.provider === "discord" && this.discordGatewayEnabled) {
|
||||
this.startDiscordGateway();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dispatchPhotonCloudEvent, readPhotonRetainedConsumer } from "./chat-channels/imessage-photon/external-runtime.js";
|
||||
import { parseSlackFormOperation } from "./chat-channels/slack/cloud-forms.js";
|
||||
import { acknowledgeSlackFormDeliveries } from "./chat-channels/slack/form-normal-ack.js";
|
||||
import { readSlackFormRetainedConsumer } from "./chat-channels/slack/cloud-consumer.js";
|
||||
@@ -559,6 +560,14 @@ export function githubConnectionEventService(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!identity && connector.instanceIdentity) {
|
||||
try {
|
||||
const retained = await readPhotonRetainedConsumer(db, connector.instanceIdentity());
|
||||
identity = retained.owner;
|
||||
hasConsumer ||= retained.owner !== null;
|
||||
if (retained.attention.length) logger.warn({ reason: "photon_retained_owner_invalid", count: retained.attention.length }, "Photon custody requires attention");
|
||||
} catch { logger.warn({ reason: "photon_retained_owner_unavailable" }, "Photon custody requires attention"); }
|
||||
}
|
||||
if (!identity) {
|
||||
const [history] = await db.select({ grant: connectionGrants, connection: toolConnections }).from(connectionGrants)
|
||||
.innerJoin(toolConnections, and(eq(toolConnections.id, connectionGrants.connectionId), eq(toolConnections.companyId, connectionGrants.companyId)))
|
||||
@@ -596,6 +605,11 @@ export function githubConnectionEventService(
|
||||
const acknowledge: string[] = [];
|
||||
const formCompanies = new Map<string, string>();
|
||||
for (const event of lease.events) {
|
||||
if (event.provider === "imessage-photon") {
|
||||
try { await dispatchPhotonCloudEvent(db, event); acknowledge.push(event.id); result.processed += 1; }
|
||||
catch { result.failed += 1; }
|
||||
continue;
|
||||
}
|
||||
if (event.provider === "slack") {
|
||||
try {
|
||||
await dispatchSlackCloudEvent(db, event);
|
||||
|
||||
@@ -469,7 +469,7 @@ export function stripCloudCatalogDefaultEchoes(
|
||||
return result as Partial<InstanceExperimentalSettings>;
|
||||
}
|
||||
|
||||
export function instanceSettingsService(db: Db, options: InstanceSettingsServiceOptions = {}) {
|
||||
export function instanceSettingsService(db: Pick<Db, "select" | "insert" | "update" | "transaction">, options: InstanceSettingsServiceOptions = {}) {
|
||||
// Fail closed: a malformed PAPERCLIP_MANAGED_CONFIG throws here (and at
|
||||
// boot in index.ts) rather than silently running without the overlay.
|
||||
const managedConfig = getManagedInstanceConfig(options.runtimeEnv ?? process.env);
|
||||
|
||||
@@ -36,9 +36,9 @@ export const GMAIL_CONNECTOR_SCOPES = [
|
||||
export { GOOGLE_WORKSPACE_CONNECTOR_PROFILES };
|
||||
|
||||
export type PaperclipCloudConnectorEnvironment = "development" | "test" | "staging" | "production";
|
||||
export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack" | "github-app" | "slack-events" | "slack-forms" | "mcp-client-mirror" | "mcp-revocation-index";
|
||||
export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack" | "github-app" | "slack-events" | "slack-forms" | "photon-receiver" | "mcp-client-mirror" | "mcp-revocation-index";
|
||||
export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | "slack.manager" | "github.bot";
|
||||
export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack";
|
||||
export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack" | "imessage-photon";
|
||||
|
||||
export type PaperclipCloudConnectorConfig = {
|
||||
baseUrl: string;
|
||||
@@ -76,7 +76,7 @@ export type SealedConnectorEvents = {
|
||||
leaseId: string;
|
||||
events: Array<{
|
||||
id: string;
|
||||
provider: "github" | "slack";
|
||||
provider: "github" | "slack" | "imessage-photon";
|
||||
event: string;
|
||||
action: string | null;
|
||||
installationId: string | null;
|
||||
@@ -87,7 +87,7 @@ export type SealedConnectorEvents = {
|
||||
}>;
|
||||
};
|
||||
|
||||
type SealedEnvelopeProfileId = PaperclipCloudConnectorProfileId | "slack.events.v1" | "slack.form-open.v1" | "slack.callbacks.v1";
|
||||
type SealedEnvelopeProfileId = PaperclipCloudConnectorProfileId | "slack.events.v1" | "slack.form-open.v1" | "slack.callbacks.v1" | "photon.events.v1";
|
||||
|
||||
type SealedEnvelope = {
|
||||
v: 1;
|
||||
@@ -121,12 +121,14 @@ type ConnectorResponse = {
|
||||
githubApps?: { version: number };
|
||||
slackEvents?: { version: number };
|
||||
slackForm?: unknown;
|
||||
photonReceiver?: unknown;
|
||||
enrollment?: unknown;
|
||||
retirement?: unknown;
|
||||
eventWakeVersion?: unknown;
|
||||
};
|
||||
|
||||
const ENDPOINTS: Record<PaperclipCloudConnectorOperation, string> = {
|
||||
"photon-receiver": "/v1/connector/photon-receiver",
|
||||
"mcp-client-mirror": "/v1/connector/mcp-client-mirror",
|
||||
"mcp-revocation-index": "/v1/connector/mcp-revocation-index",
|
||||
"slack-events": "/v1/connector/slack-events",
|
||||
@@ -417,6 +419,11 @@ export function createPaperclipCloudConnector(input: {
|
||||
const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" });
|
||||
return response.active === true && response.slackEvents?.version === 1;
|
||||
},
|
||||
async photonReceiverOperation(values: { subject: string; companyId: string; operation: Record<string, unknown> }): Promise<unknown> {
|
||||
const response = await call("photon-receiver", values, { field: "operation", value: JSON.stringify(values.operation) });
|
||||
if (!isRecord(response.photonReceiver)) throw badEnvelope();
|
||||
return response.photonReceiver;
|
||||
},
|
||||
async slackFormOperation(values: { subject: string; companyId: string; operation: Record<string, unknown> }) {
|
||||
const response = await call("slack-forms", values, { field: "operation", value: JSON.stringify(values.operation) });
|
||||
if (!isRecord(response.slackForm)) throw badEnvelope();
|
||||
@@ -664,6 +671,16 @@ export function createPaperclipCloudConnector(input: {
|
||||
event.payload = { slackEvent: delivery };
|
||||
}
|
||||
}
|
||||
if (event.provider === "imessage-photon") {
|
||||
const packet = event.payload.photonEvent;
|
||||
if (!isRecord(packet) || typeof packet.bindingId !== "string" || packet.sealed === undefined) throw badEnvelope();
|
||||
const sealed = parseEnvelope(packet.sealed, "events", "imessage-photon", "photon.events.v1");
|
||||
const delivery = decryptEnvelope(sealed, sealKey, config.instanceId, config.environment, "imessage-photon", "photon.events.v1", []);
|
||||
if (!isRecord(delivery) || delivery.version !== 1 || !isRecord(delivery.binding)
|
||||
|| delivery.binding.instanceId !== config.instanceId || delivery.binding.environment !== config.environment
|
||||
|| delivery.binding.bindingId !== packet.bindingId || delivery.acceptedAt !== event.createdAt) throw badEnvelope();
|
||||
event.payload = { photonEvent: delivery };
|
||||
}
|
||||
events.push(event);
|
||||
} catch {
|
||||
failedEventIds.push(event.id);
|
||||
@@ -716,8 +733,9 @@ function parseCloudHandoff(value: unknown): { kind: "paperclip_cloud"; session:
|
||||
return { kind: "paperclip_cloud", session };
|
||||
}
|
||||
|
||||
export type PaperclipCloudConnector = Omit<ReturnType<typeof createPaperclipCloudConnector>, "instanceIdentity" | "slackFormOperation"> & {
|
||||
export type PaperclipCloudConnector = Omit<ReturnType<typeof createPaperclipCloudConnector>, "instanceIdentity" | "slackFormOperation" | "photonReceiverOperation"> & {
|
||||
instanceIdentity?: () => Readonly<{ instanceId: string; environment: PaperclipCloudConnectorEnvironment }>;
|
||||
photonReceiverOperation?: ReturnType<typeof createPaperclipCloudConnector>["photonReceiverOperation"];
|
||||
slackFormOperation?: ReturnType<typeof createPaperclipCloudConnector>["slackFormOperation"];
|
||||
};
|
||||
export type PaperclipCloudGoogleWorkspaceConnector = PaperclipCloudConnector;
|
||||
@@ -867,7 +885,7 @@ function unsealEvents(
|
||||
if (parsed.v !== 1 || parsed.instanceId !== instanceId || parsed.environment !== environment
|
||||
|| typeof parsed.leaseId !== "string" || !Array.isArray(parsed.events)) throw badEnvelope();
|
||||
for (const event of parsed.events) {
|
||||
if (!isRecord(event) || typeof event.id !== "string" || !["github", "slack"].includes(event.provider)
|
||||
if (!isRecord(event) || typeof event.id !== "string" || !["github", "slack", "imessage-photon"].includes(event.provider)
|
||||
|| typeof event.event !== "string" || !isRecord(event.payload) || !Array.isArray(event.bindingIds)
|
||||
|| !event.bindingIds.every((id) => typeof id === "string")) throw badEnvelope();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { createOwnedPhotonClient } from "./owned-client.js";
|
||||
import { PhotonUsefulClient } from "./useful-client.js";
|
||||
import { PhotonRecoveryTransport } from "./recovery-transport.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
createGrpcClient,
|
||||
type GrpcAdvancedIMessage,
|
||||
type Message as PhotonMessage,
|
||||
type Chat as PhotonChat,
|
||||
@@ -101,7 +102,28 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
readonly name = "imessage-photon";
|
||||
readonly lockScope = "channel" as const;
|
||||
readonly botUserId: string;
|
||||
readonly client: GrpcAdvancedIMessage;
|
||||
private localClient?: GrpcAdvancedIMessage;
|
||||
private usefulClient?: PhotonUsefulClient<GrpcAdvancedIMessage>;
|
||||
onUsefulClientDebt?: () => Promise<void>;
|
||||
async drainUsefulClient(): Promise<void> { await this.usefulClient?.drain(); }
|
||||
private makeClient(): GrpcAdvancedIMessage {
|
||||
return createOwnedPhotonClient({ address: this.authentication.address, token: () => this.authentication.token(), tls: true,
|
||||
retry: false, autoIdempotency: false, timeout: 25_000,
|
||||
channelOptions: { "grpc.max_receive_message_length": MAX_ATTACHMENT_BYTES + 1024 * 1024 } });
|
||||
}
|
||||
get client(): GrpcAdvancedIMessage {
|
||||
if (this.usefulClient) throw new Error("External Photon unary calls require their useful-operation owner");
|
||||
if (!this.localClient) throw new Error("Photon local client is closed");
|
||||
return this.localClient;
|
||||
}
|
||||
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();
|
||||
}
|
||||
withClient<T>(action: (client: GrpcAdvancedIMessage) => Promise<T>): Promise<T> {
|
||||
return this.usefulClient ? this.usefulClient.run(action) : action(this.client);
|
||||
}
|
||||
private closed = false;
|
||||
private recovery?: PhotonRecoveryTransport;
|
||||
private readonly typing = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
@@ -117,19 +139,7 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
client?: GrpcAdvancedIMessage,
|
||||
) {
|
||||
this.botUserId = authentication.identity.phoneNumber;
|
||||
this.client =
|
||||
client ??
|
||||
createGrpcClient({
|
||||
address: authentication.address,
|
||||
token: () => authentication.token(),
|
||||
tls: true,
|
||||
retry: false,
|
||||
autoIdempotency: false,
|
||||
timeout: 25_000,
|
||||
channelOptions: {
|
||||
"grpc.max_receive_message_length": MAX_ATTACHMENT_BYTES + 1024 * 1024,
|
||||
},
|
||||
});
|
||||
this.localClient = client ?? this.makeClient();
|
||||
}
|
||||
async initialize(_chat: ChatInstance): Promise<void> {
|
||||
await this.authentication.token();
|
||||
@@ -139,8 +149,13 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
for (const timer of this.typing.values()) clearTimeout(timer);
|
||||
this.typing.clear();
|
||||
this.authentication.retire();
|
||||
this.recovery?.close();
|
||||
await this.client.close();
|
||||
const localClient = this.localClient;
|
||||
const closed = await Promise.allSettled([
|
||||
...(this.recovery ? [this.recovery.close()] : []),
|
||||
...(this.usefulClient ? [this.usefulClient.close()] : localClient ? [localClient.close().then(() => { if (this.localClient === localClient) this.localClient = undefined; })] : []),
|
||||
]);
|
||||
const errors = closed.flatMap(result => result.status === "rejected" ? [result.reason] : []);
|
||||
if (errors.length) throw new AggregateError(errors, "Photon receiver and useful sender shutdown remain incomplete");
|
||||
}
|
||||
encodeThreadId(value: PhotonThread): string {
|
||||
if (value.isGroup && this.authentication.identity.allocation === "shared")
|
||||
@@ -167,11 +182,11 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
async chatInfo(id: string): Promise<PhotonChat> {
|
||||
if (this.closed) throw new Error("Photon runtime retired");
|
||||
const identity = this.decodeThreadId(id);
|
||||
const chat = await this.client.chats
|
||||
const chat = await this.withClient(client => client.chats
|
||||
.get(identity.chatGuid)
|
||||
.catch((error) => {
|
||||
throw photonFailure(error);
|
||||
});
|
||||
}));
|
||||
if (
|
||||
chat.guid !== identity.chatGuid ||
|
||||
chat.isGroup !== identity.isGroup ||
|
||||
@@ -254,12 +269,12 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
attachmentGuid: locator.attachmentGuid,
|
||||
},
|
||||
fetchData: () =>
|
||||
downloadPhotonAttachment(
|
||||
this.client,
|
||||
this.withClient(client => downloadPhotonAttachment(
|
||||
client,
|
||||
this.authentication.identity.lineId,
|
||||
locator,
|
||||
this.authentication.identity.allocation,
|
||||
),
|
||||
)),
|
||||
};
|
||||
});
|
||||
const text = raw.content.text ?? "";
|
||||
@@ -301,22 +316,22 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
async fetchMessage(id: string, messageId: string) {
|
||||
const chat = await this.chatInfo(id);
|
||||
return this.normalize(
|
||||
await this.client.messages.get(messageId).catch((error) => {
|
||||
await this.withClient(client => client.messages.get(messageId).catch((error) => {
|
||||
throw photonFailure(error);
|
||||
}),
|
||||
})),
|
||||
chat,
|
||||
);
|
||||
}
|
||||
async fetchMessages(id: string, options?: FetchOptions) {
|
||||
const chat = await this.chatInfo(id);
|
||||
const page = await this.client.messages
|
||||
const page = await this.withClient(client => client.messages
|
||||
.listInChat(chat.guid, {
|
||||
pageSize: Math.min(options?.limit ?? 50, 100),
|
||||
pageToken: options?.cursor,
|
||||
})
|
||||
.catch((error) => {
|
||||
throw photonFailure(error);
|
||||
});
|
||||
}));
|
||||
return {
|
||||
messages: page.messages
|
||||
.map((message) => this.normalize(message, chat))
|
||||
@@ -348,11 +363,11 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
if (this.closed) return;
|
||||
if (this.typing.has(id)) clearTimeout(this.typing.get(id));
|
||||
await this.typingGuard?.(refresh ? id : undefined);
|
||||
await this.client.chats
|
||||
await this.withClient(client => client.chats
|
||||
.setTyping(this.decodeThreadId(id).chatGuid, true)
|
||||
.catch((error) => {
|
||||
throw photonFailure(error);
|
||||
});
|
||||
}));
|
||||
if (this.closed) return;
|
||||
// Refresh while work is running; final/prompt publication or runtime
|
||||
// retirement clears this timer. Every refresh checks endpoint ownership.
|
||||
@@ -367,9 +382,9 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
if (this.typing.has(id)) clearTimeout(this.typing.get(id));
|
||||
this.typing.delete(id);
|
||||
if (!this.closed)
|
||||
await this.client.chats
|
||||
await this.withClient(client => client.chats
|
||||
.setTyping(this.decodeThreadId(id).chatGuid, false)
|
||||
.catch(() => {});
|
||||
.catch(() => {}));
|
||||
}
|
||||
async postMessage(
|
||||
_id: string,
|
||||
@@ -506,10 +521,10 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
await options.assertCurrent();
|
||||
await save({ phase: "uploading" });
|
||||
try {
|
||||
const uploaded = await this.client.attachments.upload({
|
||||
const uploaded = await this.withClient(client => client.attachments.upload({
|
||||
fileName: file.filename,
|
||||
data: file.data as Buffer,
|
||||
});
|
||||
}));
|
||||
if (!uploaded.attachment.guid)
|
||||
throw new PhotonError(
|
||||
"delivery_unknown",
|
||||
@@ -527,8 +542,9 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
}
|
||||
}
|
||||
await options.assertCurrent();
|
||||
if (payload.replaceMessageId) {
|
||||
const original = await this.client.messages.get(payload.replaceMessageId);
|
||||
const replaceMessageId = payload.replaceMessageId;
|
||||
if (replaceMessageId) {
|
||||
const original = await this.withClient(client => client.messages.get(replaceMessageId));
|
||||
if (
|
||||
!original.isFromMe ||
|
||||
!original.chatGuids.includes(payload.chatGuid) ||
|
||||
@@ -543,25 +559,26 @@ export class PhotonChatAdapter implements Adapter<PhotonThread, PhotonMessage> {
|
||||
const clientMessageId = createHash("sha256")
|
||||
.update(`${this.state.scope.endpointId}:${publicationId}:${part}`)
|
||||
.digest("hex");
|
||||
const attachmentGuid = record.attachmentGuid;
|
||||
try {
|
||||
const result = record.attachmentGuid
|
||||
? await this.client.messages.sendAttachment(
|
||||
const result = attachmentGuid
|
||||
? await this.withClient(client => client.messages.sendAttachment(
|
||||
payload.chatGuid,
|
||||
record.attachmentGuid,
|
||||
attachmentGuid,
|
||||
{ clientMessageId, replyTo: payload.replyTo },
|
||||
)
|
||||
: payload.replaceMessageId
|
||||
? await this.client.messages.edit(
|
||||
))
|
||||
: replaceMessageId
|
||||
? await this.withClient(client => client.messages.edit(
|
||||
payload.chatGuid,
|
||||
payload.replaceMessageId,
|
||||
replaceMessageId,
|
||||
payload.text!,
|
||||
{ clientMessageId },
|
||||
)
|
||||
: await this.client.messages.sendText(
|
||||
))
|
||||
: await this.withClient(client => client.messages.sendText(
|
||||
payload.chatGuid,
|
||||
payload.text!,
|
||||
{ clientMessageId, replyTo: payload.replyTo },
|
||||
);
|
||||
));
|
||||
if (!result.guid || !result.chatGuids.includes(payload.chatGuid))
|
||||
throw new Error("Photon returned an invalid send receipt");
|
||||
await save({ phase: "sent", messageGuid: result.guid });
|
||||
|
||||
@@ -291,7 +291,7 @@ export async function publishPhotonPrompt(input: {
|
||||
throw new PhotonAnswerValidationError("Photon poll already claimed");
|
||||
return { schema: 1, phase: "creating" };
|
||||
});
|
||||
const poll = await adapter.client.polls
|
||||
const poll = await adapter.withClient(client => client.polls
|
||||
.create(
|
||||
adapter.decodeThreadId(input.threadId).chatGuid,
|
||||
title,
|
||||
@@ -310,7 +310,7 @@ export async function publishPhotonPrompt(input: {
|
||||
phase: "prepared",
|
||||
}));
|
||||
throw failure;
|
||||
});
|
||||
}));
|
||||
if (
|
||||
!poll.pollMessageGuid ||
|
||||
poll.options.length !== choices.length ||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { createGrpcClient, type GrpcClientOptions, type GrpcAdvancedIMessage } from "@photon-ai/advanced-imessage";
|
||||
import { PhotonTransportResources } from "./transport-resources.js";
|
||||
const require = createRequire(import.meta.url);
|
||||
const deliveredGrpc = {
|
||||
"build/src/http_proxy.js": "56e1e38a2e933025212512edfebde611c80471e6b27b0570b29f1275fab46c85",
|
||||
"build/src/transport.js": "9b142290b2bcdf9eb4e75e70adbe6301689ff31e8f2e8bc957d22a6590e4be8c",
|
||||
"build/src/channel-options.js": "3d83c36164c8b0499ba39da0864b5a3e12a77c6f455ad7cfed55e942dbf8d4f0",
|
||||
"build/src/channel-credentials.js": "553fff7957c883c85925fe8fec9d912e02ddc29d073419747ed1737a00b66bc0"
|
||||
};
|
||||
const inspectedSdk = {
|
||||
"dist/chunk-5WYZRCOS.js": "f26e3ed5d8a076f0bb214fe05680c317d7c1123fb29f7dc727e3dd1ac54a0c69",
|
||||
"dist/chunk-EUYUM3KD.js": "1538679fbe4c509e80571c5096c7af9c5343975f6e171d9af89e4476eb951f2e",
|
||||
"dist/client-UZMHAKPA.js": "dd078953c237ed11abb42856739f547ba952acb8a8a42e77aefb3f9d130f6c15"
|
||||
};
|
||||
function installedRoot(name: string, version: string): string {
|
||||
let path = dirname(require.resolve(name));
|
||||
for (let parents = 0; parents < 6; parents++, path = dirname(path)) {
|
||||
let pkg: unknown;
|
||||
try { pkg = JSON.parse(readFileSync(join(path, "package.json"), "utf8")); } catch { continue; }
|
||||
if (pkg && typeof pkg === "object" && Reflect.get(pkg, "name") === name) {
|
||||
if (Reflect.get(pkg, "version") !== version) throw new Error("Photon transport dependency version changed");
|
||||
return path;
|
||||
}
|
||||
}
|
||||
throw new Error("Photon transport dependency ownership is unavailable");
|
||||
}
|
||||
export function assertInstalledPhotonTransportJoin(): void {
|
||||
for (const [root, files] of [[installedRoot("@grpc/grpc-js", "1.14.5"), deliveredGrpc],
|
||||
[installedRoot("@photon-ai/advanced-imessage", "2.2.0"), inspectedSdk]] as const) {
|
||||
for (const [path, expected] of Object.entries(files)) {
|
||||
if (createHash("sha256").update(readFileSync(join(root, path))).digest("hex") !== expected)
|
||||
throw new Error("Photon transport close-and-join delivery is incomplete");
|
||||
}
|
||||
}
|
||||
}
|
||||
export function createOwnedPhotonClient(options: GrpcClientOptions): GrpcAdvancedIMessage {
|
||||
// Check exact installed delivery BEFORE allocating either SDK channel. This
|
||||
// prevents an unpatched dependency from silently turning no observations into
|
||||
// a successful close receipt.
|
||||
assertInstalledPhotonTransportJoin();
|
||||
const resources = new PhotonTransportResources();
|
||||
const client = createGrpcClient({ ...options, channelOptions: { ...options.channelOptions,
|
||||
"grpc.use_local_subchannel_pool": 1, "grpc-node.transport_owner": resources } });
|
||||
const closeSdk = client.close.bind(client);
|
||||
let closing: Promise<void> | undefined, joined = false;
|
||||
client.close = () => {
|
||||
if (joined) return Promise.resolve();
|
||||
if (closing) return closing;
|
||||
resources.beginClose();
|
||||
const attempt = (async () => {
|
||||
const errors: unknown[] = [];
|
||||
try { await closeSdk(); } catch (error) { errors.push(error); }
|
||||
try { await resources.close(); } catch (error) { errors.push(error); }
|
||||
if (errors.length) throw new AggregateError(errors, "Photon SDK and physical transport close remain incomplete");
|
||||
})();
|
||||
closing = attempt;
|
||||
void attempt.then(() => { joined = true; }, () => { if (closing === attempt) closing = undefined; });
|
||||
return attempt;
|
||||
};
|
||||
return client;
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import type {
|
||||
import { PhotonError } from "./cloud.js";
|
||||
import { PhotonState } from "./state.js";
|
||||
|
||||
export type PhotonFailureResponsibility = { kind: "recorded" } | { kind: "obsolete" };
|
||||
|
||||
interface Checkpoint {
|
||||
schema: 1;
|
||||
lineId: string;
|
||||
@@ -22,7 +24,7 @@ export interface PhotonReceiverOptions {
|
||||
/** Renewal verifies both the selected identity and the current endpoint lease. */
|
||||
assertOwned(): Promise<void>;
|
||||
admit(event: LiveEvent): Promise<void>;
|
||||
failure(error: unknown): Promise<void>;
|
||||
failure(error: unknown): Promise<void | PhotonFailureResponsibility>;
|
||||
/** Production persists the cursor under the same transaction as its lease fence. */
|
||||
commitCheckpoint?(sequence: number): Promise<void>;
|
||||
}
|
||||
@@ -33,6 +35,11 @@ export class PhotonReceiver {
|
||||
private stopped = false;
|
||||
private streams: Array<TypedEventStream<LiveEvent>> = [];
|
||||
private running?: Promise<void>;
|
||||
private closing?: Promise<void>;
|
||||
private readonly consumers: Promise<void>[] = [];
|
||||
private readonly reads = new Set<Promise<void>>();
|
||||
private readonly closeFailures = new Map<object, unknown>();
|
||||
private readonly failureDebt = new Map<unknown, unknown>();
|
||||
private requested = false;
|
||||
private catchUpStream?: TypedEventStream<PhotonRecoveryEvent>;
|
||||
private timer?: ReturnType<typeof setInterval>;
|
||||
@@ -47,20 +54,22 @@ export class PhotonReceiver {
|
||||
client.polls.subscribeEvents(),
|
||||
];
|
||||
for (const stream of this.streams) {
|
||||
void (async () => {
|
||||
const consumer = (async () => {
|
||||
try {
|
||||
for await (const _event of stream) {
|
||||
if (this.stopped) break;
|
||||
this.request();
|
||||
}
|
||||
if (!this.stopped)
|
||||
await this.options.failure(
|
||||
await this.report(
|
||||
new PhotonError("network", "Photon event stream disconnected"),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!this.stopped) await this.options.failure(error);
|
||||
if (!this.stopped) await this.report(error);
|
||||
}
|
||||
})().catch(() => {});
|
||||
})();
|
||||
this.consumers.push(consumer);
|
||||
void consumer.catch(() => {});
|
||||
}
|
||||
this.timer = setInterval(() => this.request(), 15_000);
|
||||
this.timer.unref();
|
||||
@@ -77,14 +86,20 @@ export class PhotonReceiver {
|
||||
}
|
||||
})()
|
||||
.catch(async (error) => {
|
||||
if (!this.stopped) await this.options.failure(error);
|
||||
if (!this.stopped) await this.report(error);
|
||||
})
|
||||
.finally(() => {
|
||||
this.running = undefined;
|
||||
});
|
||||
}
|
||||
/** Exposed for deterministic recovery tests, never an external route. */
|
||||
async catchUp(): Promise<void> {
|
||||
catchUp(): Promise<void> {
|
||||
if (this.stopped) return Promise.resolve();
|
||||
const reading = this.catchUpOwned(); this.reads.add(reading);
|
||||
void reading.finally(() => this.reads.delete(reading)).catch(() => {});
|
||||
return reading;
|
||||
}
|
||||
private async catchUpOwned(): Promise<void> {
|
||||
const { state, lineId, client, assertOwned, admit, intakeAfter } =
|
||||
this.options;
|
||||
await assertOwned();
|
||||
@@ -108,6 +123,7 @@ export class PhotonReceiver {
|
||||
const shared = this.options.allocation === "shared";
|
||||
let sequence = original?.sequence;
|
||||
let batchEvents = 0;
|
||||
if (this.stopped) return;
|
||||
const stream =
|
||||
this.options.catchUp?.(sequence) ?? client.events.catchUp(sequence);
|
||||
this.catchUpStream = stream;
|
||||
@@ -116,6 +132,7 @@ export class PhotonReceiver {
|
||||
for await (const event of stream) {
|
||||
if (this.stopped) return;
|
||||
await assertOwned();
|
||||
if (this.stopped) return;
|
||||
if (event.type === "catchup.complete") {
|
||||
if (
|
||||
!Number.isSafeInteger(event.headSequence) ||
|
||||
@@ -173,7 +190,7 @@ export class PhotonReceiver {
|
||||
"Photon catch-up ended before its checkpoint barrier",
|
||||
);
|
||||
} finally {
|
||||
await stream.close();
|
||||
await this.closeStream(stream);
|
||||
if (this.catchUpStream === stream) this.catchUpStream = undefined;
|
||||
}
|
||||
}
|
||||
@@ -188,12 +205,57 @@ export class PhotonReceiver {
|
||||
);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.stopped = true;
|
||||
private async report(error: unknown): Promise<void> {
|
||||
try {
|
||||
const receipt = await this.options.failure(error);
|
||||
if (receipt?.kind !== "recorded") throw new Error("Photon failure responsibility was not recorded by the current owner");
|
||||
}
|
||||
catch (reportingError) {
|
||||
// Preserve responsibility after the request owner finishes. A stopped
|
||||
// receiver may retry reporting during close, never restart intake.
|
||||
this.failureDebt.set(error, reportingError);
|
||||
this.stopped = true;
|
||||
this.requested = false;
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
}
|
||||
}
|
||||
private async retryFailureDebt(): Promise<void> {
|
||||
for (const [error] of this.failureDebt) {
|
||||
try {
|
||||
const receipt = await this.options.failure(error);
|
||||
if (receipt?.kind === "recorded") this.failureDebt.delete(error);
|
||||
// A void/stale callback is not proof that current responsibility was
|
||||
// durably accepted. Keep the original debt for explicit owner repair.
|
||||
} catch (reportingError) { this.failureDebt.set(error, reportingError); }
|
||||
}
|
||||
}
|
||||
private async closeStream(stream: { close(): Promise<void> }): Promise<void> {
|
||||
try { await stream.close(); this.closeFailures.delete(stream); }
|
||||
catch (error) { this.closeFailures.set(stream, error); throw error; }
|
||||
}
|
||||
close(): Promise<void> {
|
||||
if (this.closing) return this.closing;
|
||||
const closing = this.closeOwned(); this.closing = closing;
|
||||
void closing.catch(() => { if (this.closing === closing) this.closing = undefined; });
|
||||
return closing;
|
||||
}
|
||||
private async closeOwned(): Promise<void> {
|
||||
this.stopped = true; this.requested = false;
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
await this.catchUpStream?.close();
|
||||
await Promise.allSettled(this.streams.map((stream) => stream.close()));
|
||||
// client.close interrupts a blocked catch-up RPC during runtime shutdown.
|
||||
const streams = [...this.streams, ...(this.catchUpStream ? [this.catchUpStream] : [])];
|
||||
const closed = await Promise.allSettled([
|
||||
...streams.map(stream => this.closeStream(stream)),
|
||||
Promise.resolve().then(() => this.options.client.close()),
|
||||
]);
|
||||
const joined = await Promise.allSettled([...this.consumers, ...this.reads, ...(this.running ? [this.running] : [])]);
|
||||
await this.retryFailureDebt();
|
||||
const errors = [...new Set([
|
||||
...this.closeFailures.values(),
|
||||
...[...this.failureDebt].map(([error, reportingError]) => new AggregateError([error, reportingError], "Photon failure responsibility remains unconfirmed")),
|
||||
...closed.flatMap(result => result.status === "rejected" ? [result.reason] : []),
|
||||
...joined.flatMap(result => result.status === "rejected" ? [result.reason] : []),
|
||||
])];
|
||||
if (errors.length) throw new AggregateError(errors, "Photon receiver shutdown remains unconfirmed");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { PhotonTransportResources } from "./transport-resources.js";
|
||||
import { assertInstalledPhotonTransportJoin } from "./owned-client.js";
|
||||
import { Client, credentials, Metadata, status } from "@grpc/grpc-js";
|
||||
import {
|
||||
decodeCatchUpEvent,
|
||||
@@ -111,13 +113,19 @@ export function decodePhotonRecoveryFrame(
|
||||
|
||||
export class PhotonRecoveryTransport {
|
||||
private readonly client: Client;
|
||||
private readonly resources = new PhotonTransportResources();
|
||||
private closing?: Promise<void>;
|
||||
private joined = false;
|
||||
constructor(
|
||||
private readonly authentication: PhotonLineAuthentication,
|
||||
client?: Client,
|
||||
) {
|
||||
if (!client) assertInstalledPhotonTransportJoin();
|
||||
this.client =
|
||||
client ??
|
||||
new Client(authentication.address, credentials.createSsl(), {
|
||||
"grpc.use_local_subchannel_pool": 1,
|
||||
"grpc-node.transport_owner": this.resources,
|
||||
"grpc.max_receive_message_length": MAX_ATTACHMENT_BYTES + 1024 * 1024,
|
||||
});
|
||||
}
|
||||
@@ -172,7 +180,18 @@ export class PhotonRecoveryTransport {
|
||||
}
|
||||
return new TypedEventStream(receive(), async () => controller.abort());
|
||||
}
|
||||
close(): void {
|
||||
this.client.close();
|
||||
close(): Promise<void> {
|
||||
if (this.joined) return Promise.resolve();
|
||||
if (this.closing) return this.closing;
|
||||
this.resources.beginClose();
|
||||
const attempt = (async () => {
|
||||
const errors: unknown[] = [];
|
||||
try { this.client.close(); } catch (error) { errors.push(error); }
|
||||
try { await this.resources.close(); } catch (error) { errors.push(error); }
|
||||
if (errors.length) throw new AggregateError(errors, "Photon CatchUp client and physical transport close remain incomplete");
|
||||
})();
|
||||
this.closing = attempt;
|
||||
void attempt.then(() => { this.joined = true; }, () => { if (this.closing === attempt) this.closing = undefined; });
|
||||
return attempt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { Socket } from "node:net";
|
||||
import type { ClientHttp2Session } from "node:http2";
|
||||
import type { ClientRequest } from "node:http";
|
||||
|
||||
// Exact resources reported by the opt-in grpc1.14.5 delivery patch. No global
|
||||
// socket interception, recurring timer, activity inference or destroyed flag.
|
||||
type Resource = Socket | ClientHttp2Session | ClientRequest;
|
||||
type Entry = { closed: Promise<void>; resolve(): void; onClose(): void; observed: boolean };
|
||||
export class PhotonTransportResources {
|
||||
private readonly abort = new AbortController();
|
||||
private readonly entries = new WeakMap<Resource, Entry>();
|
||||
private readonly resources = new Map<Resource, Entry>();
|
||||
private readonly operations = new Set<Promise<unknown>>();
|
||||
private readonly disposalErrors = new Map<Resource, unknown>();
|
||||
private attempt?: Promise<void>;
|
||||
private joined = false;
|
||||
readonly signal = this.abort.signal;
|
||||
readonly pending = (operation: Promise<unknown>): void => {
|
||||
this.operations.add(operation);
|
||||
void operation.then(() => this.operations.delete(operation), () => this.operations.delete(operation));
|
||||
};
|
||||
readonly socket = (socket: Socket): void => { this.observe(socket); };
|
||||
readonly session = (session: ClientHttp2Session): void => { this.observe(session); };
|
||||
readonly request = (request: ClientRequest): void => { this.observe(request); };
|
||||
private observe(resource: Resource): void {
|
||||
let entry = this.entries.get(resource);
|
||||
if (!entry) {
|
||||
let resolve!: () => void;
|
||||
const closed = new Promise<void>(done => { resolve = done; });
|
||||
entry = { closed, resolve, observed: false, onClose: () => {} };
|
||||
const current = entry;
|
||||
current.onClose = () => {
|
||||
current.observed = true;
|
||||
this.resources.delete(resource);
|
||||
this.disposalErrors.delete(resource);
|
||||
current.resolve();
|
||||
};
|
||||
this.entries.set(resource, current);
|
||||
this.resources.set(resource, current);
|
||||
}
|
||||
// grpc's normal CONNECT/remoteSettings transitions remove listeners. The
|
||||
// delivered hook reports that SAME object again in the same synchronous
|
||||
// transition. Reinstall the same observer; do not replace its receipt.
|
||||
if (!entry.observed && !resource.listeners("close").includes(entry.onClose)) resource.once("close", entry.onClose);
|
||||
if (this.signal.aborted && !entry.observed) this.destroy(resource);
|
||||
}
|
||||
private destroy(resource: Resource): void {
|
||||
try { resource.destroy(); this.disposalErrors.delete(resource); }
|
||||
catch (error) { this.disposalErrors.set(resource, error); }
|
||||
}
|
||||
beginClose(): void {
|
||||
this.abort.abort();
|
||||
}
|
||||
close(): Promise<void> {
|
||||
if (this.joined) return Promise.resolve();
|
||||
if (this.attempt) return this.attempt;
|
||||
const attempt = this.closeOwned(); this.attempt = attempt;
|
||||
void attempt.then(() => { this.joined = true; }, () => { if (this.attempt === attempt) this.attempt = undefined; });
|
||||
return attempt;
|
||||
}
|
||||
private async closeOwned(): Promise<void> {
|
||||
this.beginClose();
|
||||
for (const [resource, entry] of this.resources) if (!entry.observed) this.destroy(resource);
|
||||
// A synchronous destroy refusal is real retryable debt. Do not wait forever
|
||||
// on the resource that refused disposal or discard any of its identity.
|
||||
if (this.disposalErrors.size) throw new AggregateError([...this.disposalErrors.values()], "Photon transport disposal remains incomplete");
|
||||
// Every allocation after an await checks this same aborted signal. A late
|
||||
// resource is observed and destroyed before its connect promise settles.
|
||||
while (this.operations.size) {
|
||||
await Promise.allSettled([...this.operations]);
|
||||
if (this.disposalErrors.size) throw new AggregateError([...this.disposalErrors.values()], "Photon late transport disposal remains incomplete");
|
||||
}
|
||||
await Promise.all([...this.resources.values()].map(entry => entry.closed));
|
||||
if (this.disposalErrors.size) throw new AggregateError([...this.disposalErrors.values()], "Photon transport join remains incomplete");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { registerIdleLocalWorkProbe } from "../idle-local-work.js";
|
||||
|
||||
/** 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. */
|
||||
export class PhotonUsefulClient<T extends { close(): Promise<void> | void }> {
|
||||
private client?: T;
|
||||
private tail: Promise<void> = Promise.resolve();
|
||||
private pending = 0;
|
||||
private failed = false;
|
||||
private unrecordedDebt = false;
|
||||
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");
|
||||
}
|
||||
private async closeCurrent() {
|
||||
const client = this.client;
|
||||
if (!client) {
|
||||
if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; }
|
||||
return;
|
||||
}
|
||||
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; }
|
||||
}
|
||||
private enqueue<R>(action: () => Promise<R>): Promise<R> {
|
||||
this.pending += 1;
|
||||
const result = this.tail.then(action);
|
||||
this.tail = result.then(() => undefined, () => undefined);
|
||||
void this.tail.then(() => { this.pending -= 1; });
|
||||
return result;
|
||||
}
|
||||
run<R>(action: (client: T) => Promise<R>): Promise<R> {
|
||||
return this.enqueue(async () => {
|
||||
if (this.stopped) throw new Error("Photon useful client is stopped");
|
||||
await this.closeCurrent();
|
||||
const client = this.create(); this.client = client;
|
||||
let value: R;
|
||||
try { value = await action(client); }
|
||||
catch (primary) {
|
||||
try { await this.closeCurrent(); } catch (cleanup) { throw new AggregateError([primary, cleanup], "Photon useful operation and close failed"); }
|
||||
throw primary;
|
||||
}
|
||||
// The provider result is already known. Preserve it for the caller's
|
||||
// ordinary durable receipt commit; cleanup failure is separately owned.
|
||||
try { await this.closeCurrent(); } catch { /* Retained exact resource/debt, never a second provider invocation. */ }
|
||||
return value;
|
||||
});
|
||||
}
|
||||
drain(): Promise<void> { return this.enqueue(() => this.closeCurrent()); }
|
||||
close(): Promise<void> {
|
||||
this.stopped = true;
|
||||
return this.enqueue(async () => { await this.closeCurrent(); this.unregister(); });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user