mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
perf(chat): schedule Telegram maintenance from commits and deadlines (#16094)
Replace periodic Telegram discovery and maintenance scans with bounded startup recovery, connection-specific commit notifications, and durable action deadlines. Preserve ownership, inactive subscription parking, retry and cleanup recovery, and atomic credential binding updates. Verified full typecheck/build, 30 focused scheduler tests, 12 database-backed recovery cases, all current-head CI checks, and Greptile 5/5 with no unresolved threads. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
69f4bfc3c5
commit
833769ab55
20 files changed
+479
-99
No files matched your search
@@ -456,7 +456,20 @@ Longer polling intervals alone do not complete an item.
|
||||
for both stale-claim expiry and any saved retry time. Startup recovers unfinished
|
||||
requests. Claim and settlement writes signal in their own short transactions,
|
||||
with agent wakeup outside those transactions. Empty and terminal queues disarm.
|
||||
Remaining **1s** maintenance: provider runtimes, Telegram maintenance,
|
||||
Telegram maintenance now has separate commit-driven discovery and action
|
||||
workers. Discovery restores legacy subscription obligations on startup and
|
||||
after endpoint or chat-connection configuration commits, without recurring
|
||||
empty scans. Startup walks keyset pages with at most 100 endpoints per run,
|
||||
so endpoints beyond the first page remain discoverable. Configuration commits
|
||||
carry connection hints through outer settlement and uncertainty recovery;
|
||||
they only revisit the changed connection. Failed discovery retains its page,
|
||||
and concurrent edits queue a fresh scoped pass. Existing action rows provide retry and stale-claim
|
||||
deadlines. Stop-subscription repair parks while the endpoint or connection
|
||||
is inactive; registration and removal keep their existing eligibility.
|
||||
The explicit bounded recovery helper remains available. Provider subscription
|
||||
proof, credential ownership, and idempotent provider mutations stay in the
|
||||
Telegram service. Provider responses are simulated in the PostgreSQL tests.
|
||||
Remaining **1s** maintenance: provider runtimes,
|
||||
run milestone/wake-notice projection, GitHub operation
|
||||
recovery, and Teams protocol maintenance. GitHub pre-ingress recovery
|
||||
must still inspect provider history: a lost callback has no local queue row.
|
||||
|
||||
@@ -181,6 +181,14 @@ own policy and access review.
|
||||
|
||||
Gaps: Provider endpoint, represented agent and linked sender are operator choices today.
|
||||
|
||||
Internal recovery: Telegram discovery walks bounded pages at startup. Configuration
|
||||
commits only queue the changed connection; durable maintenance rows supply retry deadlines. Inactive subscription
|
||||
repair is parked until an endpoint or connection change. This creates no agent
|
||||
management permission or new API. Local database-backed provider-fixture tests in
|
||||
[channel integration](../../server/src/__tests__/chat-channels.integration.test.ts)
|
||||
cover recovery, rollback, retries and idle query silence; they do not establish
|
||||
live provider or agent access.
|
||||
|
||||
## `failure`
|
||||
|
||||
Review: `baseline`.
|
||||
|
||||
@@ -132,6 +132,12 @@ Automated: [setup routing](../../ui/src/pages/apps/chat/ChatEndpointSetup.routin
|
||||
[identity confirmation](../../ui/src/pages/apps/chat/ChatIdentityConfirm.test.tsx)
|
||||
cover shared UI logic with fixtures. Provider-specific live setup is not implied.
|
||||
|
||||
[Channel integration](../../server/src/__tests__/chat-channels.integration.test.ts)
|
||||
also covers bounded Telegram subscription recovery at startup and after committed
|
||||
configuration changes, saved retry deadlines, rollback, and parking pending
|
||||
repair while an endpoint or connection is inactive. The provider responses are
|
||||
fixtures. Settled maintenance leaves no discovery timer or database scans.
|
||||
|
||||
Manual: complete setup for one named provider, reload endpoint settings, link
|
||||
the intended sender, and send a disposable message. Verify one task and a useful
|
||||
reply in the originating conversation. Inspect an unlinked sender's denial and
|
||||
|
||||
@@ -48,6 +48,24 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
expect(await db.execute(sql`select * from work_signal_test where id = 'rollback'`)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("coalesces scoped hints and publishes them only when the outer transaction settles", async () => {
|
||||
const settled: string[][] = [];
|
||||
const unsubscribe = subscribeDatabaseWork(db, "scoped", (event, hints) => {
|
||||
if (event === "settled") settled.push([...(hints ?? [])]);
|
||||
});
|
||||
try {
|
||||
await db.transaction(async tx => {
|
||||
await signalDatabaseWork(tx, "scoped", "connection-a");
|
||||
await tx.transaction(async nested => {
|
||||
await signalDatabaseWork(nested, "scoped", "connection-b");
|
||||
await signalDatabaseWork(nested, "scoped", "connection-a");
|
||||
});
|
||||
expect(settled).toEqual([]);
|
||||
});
|
||||
expect(settled).toEqual([["connection-a", "connection-b"]]);
|
||||
} finally { unsubscribe(); }
|
||||
});
|
||||
|
||||
it("keeps outer ownership after a caught savepoint rollback", async () => {
|
||||
const events: string[] = [];
|
||||
const unsubscribe = subscribeDatabaseWork(db, "savepoint", event => events.push(event));
|
||||
@@ -92,19 +110,25 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
}) as typeof raw.transaction;
|
||||
const owner = installDatabaseWorkSignals(raw);
|
||||
const topic = `late-${outcome}`;
|
||||
const settled: string[][] = [];
|
||||
const unsubscribe = subscribeDatabaseWork(owner, topic, (event, hints) => {
|
||||
if (event === "settled") settled.push([...(hints ?? [])]);
|
||||
});
|
||||
try {
|
||||
await expect(owner.transaction(async tx => {
|
||||
await signalDatabaseWork(tx, topic);
|
||||
await signalDatabaseWork(tx, topic, "connection-late");
|
||||
await tx.execute(sql`insert into work_signal_test values (${topic})`);
|
||||
})).rejects.toThrow("lost transaction response");
|
||||
await reconcileDatabaseWork(owner, topic);
|
||||
expect(databaseWorkPending(owner, topic)).toBe(true);
|
||||
expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(0);
|
||||
settled.length = 0;
|
||||
release(); await serverDone.catch(() => {});
|
||||
await reconcileDatabaseWork(owner, topic);
|
||||
expect(settled).toEqual([["connection-late"]]);
|
||||
expect(databaseWorkPending(owner, topic)).toBe(false);
|
||||
expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(outcome === "commit" ? 1 : 0);
|
||||
} finally { release(); await serverDone?.catch(() => {}); }
|
||||
} finally { release(); await serverDone?.catch(() => {}); unsubscribe(); }
|
||||
});
|
||||
|
||||
it("recovers after a real backend disconnect without replaying the queue write", async () => {
|
||||
|
||||
@@ -3,16 +3,16 @@ import { sql } from "drizzle-orm";
|
||||
// Process-local hints about existing durable queues. No SQL triggers, tables,
|
||||
// background timers, or driver query replay. Only opted-in transactions fetch
|
||||
// an XID, so unrelated transactions keep their existing SQL behavior.
|
||||
type Listener = (event: "intent" | "settled") => void;
|
||||
type Transaction = { topics: Set<string>; xid?: Promise<string>; uncertain: boolean };
|
||||
type Listener = (event: "intent" | "settled", hints?: ReadonlySet<string>) => void;
|
||||
type Transaction = { topics: Set<string>; hints: Map<string, Set<string>>; xid?: Promise<string>; uncertain: boolean };
|
||||
type Scope = { listeners: Map<string, Set<Listener>>; transactions: Set<Transaction>; root: Connection };
|
||||
type Context = { scope: Scope; transaction?: Transaction };
|
||||
type Connection = { transaction: (...args: any[]) => Promise<any>; execute: (...args: any[]) => Promise<any> };
|
||||
const contexts = new WeakMap<object, Context>();
|
||||
|
||||
function publish(scope: Scope, topic: string, event: "intent" | "settled" = "settled") {
|
||||
function publish(scope: Scope, topic: string, event: "intent" | "settled" = "settled", hints?: ReadonlySet<string>) {
|
||||
for (const listener of scope.listeners.get(topic) ?? []) {
|
||||
try { listener(event); }
|
||||
try { listener(event, hints); }
|
||||
catch (error) { process.emitWarning(`Database work listener failed: ${String(error)}`); }
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ function install(connection: Connection, context: Context) {
|
||||
connection.transaction = async function (callback, ...options) {
|
||||
// Nested savepoints belong to the outermost transaction. Even a released
|
||||
// savepoint must not wake a consumer before its parent commits.
|
||||
const state = context.transaction ?? { topics: new Set<string>(), uncertain: false };
|
||||
const state = context.transaction ?? { topics: new Set<string>(), hints: new Map<string, Set<string>>(), uncertain: false };
|
||||
try {
|
||||
const result = await transaction.call(this, async (tx: Connection) => {
|
||||
install(tx, { scope: context.scope, transaction: state });
|
||||
@@ -47,20 +47,25 @@ function install(connection: Connection, context: Context) {
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (!context.transaction) for (const topic of state.topics) publish(context.scope, topic);
|
||||
if (!context.transaction) for (const topic of state.topics) publish(context.scope, topic, "settled", state.hints.get(topic));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Await BEFORE the queue write, on its transaction. Nested transactions work. */
|
||||
export async function signalDatabaseWork(connection: object, topic: string): Promise<void> {
|
||||
export async function signalDatabaseWork(connection: object, topic: string, hint?: string): Promise<void> {
|
||||
const context = contexts.get(connection);
|
||||
if (!context) return; // Lightweight service test doubles have no DB lifecycle.
|
||||
const state = context.transaction;
|
||||
if (!state) throw new Error("Database work must be registered inside a transaction");
|
||||
state.topics.add(topic);
|
||||
if (hint !== undefined) {
|
||||
let hints = state.hints.get(topic);
|
||||
if (!hints) state.hints.set(topic, hints = new Set());
|
||||
hints.add(hint);
|
||||
}
|
||||
context.scope.transactions.add(state);
|
||||
publish(context.scope, topic, "intent");
|
||||
publish(context.scope, topic, "intent", state.hints.get(topic));
|
||||
if (!state.xid) {
|
||||
state.xid = (connection as Connection).execute(sql`select pg_current_xact_id()::text as xid`)
|
||||
.then((rows: { xid: string }[]) => rows[0]!.xid);
|
||||
@@ -91,7 +96,7 @@ export async function reconcileDatabaseWork(owner: object, topic: string): Promi
|
||||
throw new Error("Unexpected database transaction status");
|
||||
}
|
||||
scope.transactions.delete(state);
|
||||
for (const affected of state.topics) publish(scope, affected);
|
||||
for (const affected of state.topics) publish(scope, affected, "settled", state.hints.get(affected));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -107,6 +107,7 @@ describe("createChatReconciliationCoordinator", () => {
|
||||
// scheduled method returns; app shutdown must also join those workers.
|
||||
expect(source).toContain("await chatChannels.shutdown()");
|
||||
expect(source).not.toContain("chatChannels.processPendingSlackSessionSyncs()");
|
||||
expect(source).not.toContain("chatChannels.processPendingChatMaintenance()");
|
||||
const service = readFileSync(new URL("../services/chat-channels.ts", import.meta.url), "utf8");
|
||||
const actionMaintenance = service.slice(service.indexOf("async function processPendingChatMaintenance("),
|
||||
service.indexOf("async function processPendingDeliveries("));
|
||||
|
||||
@@ -20,6 +20,10 @@ function setup() {
|
||||
coordinators.push(coordinator);
|
||||
const service = {
|
||||
processFailedChatRunRetries: vi.fn(async () => {}),
|
||||
processPendingTelegramActions: vi.fn(async () => {}),
|
||||
processTelegramSubscriptionDiscovery: vi.fn(async () => {}),
|
||||
scheduleTelegramSubscriptionDiscovery: vi.fn(),
|
||||
hasPendingTelegramSubscriptionDiscovery: vi.fn(() => false),
|
||||
processPendingProviderEffects: vi.fn(async () => {}),
|
||||
processPendingGitHubWebhookIngress: vi.fn(async () => {}),
|
||||
processPendingSlackSessionSyncs: vi.fn(async () => {}),
|
||||
@@ -31,17 +35,40 @@ function setup() {
|
||||
nextChatActionAt: vi.fn(async (): Promise<number | null> => null),
|
||||
nextVerificationMessageAt: vi.fn(async (): Promise<number | null> => null),
|
||||
};
|
||||
const runs = [service.processFailedChatRunRetries, service.processPendingProviderEffects, service.processPendingGitHubWebhookIngress, service.processPendingSlackSessionSyncs, service.processPendingSlackBoardMessages, service.processPendingSlackTaskStarts,
|
||||
const runs = [service.processFailedChatRunRetries, service.processPendingTelegramActions, service.processPendingProviderEffects, service.processPendingGitHubWebhookIngress, service.processPendingSlackSessionSyncs, service.processPendingSlackBoardMessages, service.processPendingSlackTaskStarts,
|
||||
service.processPendingReceiptReactions, service.processPendingSlackSessionStops, service.processPendingVerificationMessages];
|
||||
return { owner, service, runs, coordinator, enabled, onError, start: () => registerChatActionWork(coordinator, service, enabled) };
|
||||
}
|
||||
describe("chat action scheduling", () => {
|
||||
it("retains configuration commits during discovery and retries discovery failures", async () => {
|
||||
const s = setup();
|
||||
let release!: () => void;
|
||||
s.service.processTelegramSubscriptionDiscovery.mockImplementationOnce(() => new Promise<void>(resolve => { release = resolve; }));
|
||||
const work = s.start();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(1);
|
||||
await s.owner.transaction(tx => notifyChatEndpointWork(tx, "connection-fixture"));
|
||||
expect(s.service.scheduleTelegramSubscriptionDiscovery).toHaveBeenCalledWith("connection-fixture");
|
||||
s.service.processTelegramSubscriptionDiscovery.mockRejectedValueOnce(new Error("discovery unavailable"));
|
||||
release();
|
||||
await work.ready;
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(2);
|
||||
expect(s.onError).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(3);
|
||||
await vi.advanceTimersByTimeAsync(3_600_000);
|
||||
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(3);
|
||||
expect(s.coordinator.nextWakeAt()).toBeNull();
|
||||
});
|
||||
it("does one startup scan per lane and no more SQL or timers during an idle hour", async () => {
|
||||
const s = setup();
|
||||
await s.start().ready;
|
||||
await vi.advanceTimersByTimeAsync(3_600_000);
|
||||
for (const run of s.runs) expect(run).toHaveBeenCalledTimes(1);
|
||||
expect(s.service.nextChatActionAt).toHaveBeenCalledTimes(8);
|
||||
expect(s.service.nextChatActionAt).toHaveBeenCalledTimes(9);
|
||||
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(1);
|
||||
expect(s.service.scheduleTelegramSubscriptionDiscovery).not.toHaveBeenCalled();
|
||||
expect(s.service.nextVerificationMessageAt).toHaveBeenCalledTimes(1);
|
||||
expect(s.coordinator.nextWakeAt()).toBeNull();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
@@ -58,9 +85,12 @@ describe("chat action scheduling", () => {
|
||||
await s.owner.transaction(tx => notifyChatVerificationWork(tx));
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
for (const run of s.runs) expect(run).toHaveBeenCalledTimes(2);
|
||||
await s.owner.transaction(tx => notifyChatEndpointWork(tx));
|
||||
// Queue claims/settlements do not rediscover every configured endpoint.
|
||||
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(1);
|
||||
await s.owner.transaction(tx => notifyChatEndpointWork(tx, "connection-fixture"));
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
for (const run of s.runs) expect(run).toHaveBeenCalledTimes(3);
|
||||
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(2);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
it("restores durable deadlines and reschedules when a foreground send moves a retry earlier", async () => {
|
||||
@@ -101,6 +131,7 @@ describe("chat action scheduling", () => {
|
||||
await s.start().ready;
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(s.service.nextChatActionAt).not.toHaveBeenCalled();
|
||||
expect(s.service.processTelegramSubscriptionDiscovery).not.toHaveBeenCalled();
|
||||
for (const run of s.runs) expect(run).not.toHaveBeenCalled();
|
||||
s.enabled.mockReturnValue(true);
|
||||
s.service.processPendingSlackTaskStarts.mockRejectedValueOnce(new Error("DB unavailable"));
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { idleWorkSnapshot } from "../services/task-admission.js";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import * as activityLogModule from "../services/activity-log.js";
|
||||
import * as connectionCredentialBindings from "../services/connection-credential-bindings.js";
|
||||
import { chatSlackManagerGrants, chatSlackRegistrations, toolOauthStates } from "@paperclipai/db";
|
||||
import type { PaperclipCloudConnector, SealedConnectorCredentials } from "../services/paperclip-cloud-connector.js";
|
||||
import { buildSlackAppManifest, SLACK_MANAGER_SCOPES } from "@paperclipai/shared";
|
||||
@@ -33061,7 +33063,8 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
try {
|
||||
for (const kind of Object.keys(CHAT_ACTION_QUEUES) as (keyof typeof CHAT_ACTION_QUEUES)[]) {
|
||||
const [action] = await db.insert(chatActions).values({ companyId: f.companyId, endpointId: lane.endpoint.id,
|
||||
kind, providerActionId: randomUUID(), status: "received", updatedAt: at }).returning();
|
||||
kind, providerActionId: randomUUID(), status: "received", updatedAt: at,
|
||||
...(kind === "telegram_maintenance" ? { payload: { operation: "register_commands" } } : {}) }).returning();
|
||||
const set = (status: string, result: Record<string, unknown> = {}) => db.update(chatActions)
|
||||
.set({ status, result, updatedAt: at }).where(eq(chatActions.id, action!.id));
|
||||
const due = async () => db.select({ id: chatActions.id }).from(chatActions)
|
||||
@@ -70635,6 +70638,195 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
};
|
||||
}
|
||||
|
||||
it.each(["startup", "connection_commit", "rollback", "retry", "stale_claim"] as const)(
|
||||
"recovers Telegram maintenance from committed work and becomes SQL quiet: %s",
|
||||
async mode => {
|
||||
const lane = await draftFixture();
|
||||
const onError = vi.fn();
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
|
||||
const maintenance = () => db.select().from(chatActions).where(and(
|
||||
eq(chatActions.endpointId, lane.endpoint.id), eq(chatActions.kind, "telegram_maintenance"),
|
||||
sql`${chatActions.payload}->>'operation' = 'stop_subscription'`,
|
||||
));
|
||||
try {
|
||||
await db.delete(chatActions).where(and(eq(chatActions.endpointId, lane.endpoint.id),
|
||||
eq(chatActions.kind, "telegram_stop_subscription")));
|
||||
lane.setSubscriptionInfo({});
|
||||
if (mode === "connection_commit" || mode === "rollback") {
|
||||
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { enabled: false });
|
||||
}
|
||||
if (mode === "stale_claim") {
|
||||
// Leave committed legacy work behind before starting the workers.
|
||||
await lane.context.service.processTelegramSubscriptionDiscovery();
|
||||
const [action] = await maintenance();
|
||||
expect(action).toBeDefined();
|
||||
await db.update(chatActions).set({ status: "processing", updatedAt: new Date(Date.now() - 120_000) })
|
||||
.where(eq(chatActions.id, action!.id));
|
||||
}
|
||||
let failedAt = 0;
|
||||
let sends = 0;
|
||||
if (mode === "retry") lane.setMaintenanceHook(async method => {
|
||||
if (method === "setWebhook" && sends++ === 0) {
|
||||
failedAt = Date.now();
|
||||
throw new Error("temporary subscription transport outage");
|
||||
}
|
||||
if (method === "setWebhook") expect(Date.now() - failedAt).toBeGreaterThanOrEqual(1000);
|
||||
return undefined;
|
||||
});
|
||||
await registerChatActionWork(coordinator, lane.context.service, () => true).ready;
|
||||
if (mode === "connection_commit" || mode === "rollback") {
|
||||
expect(lane.maintenanceRequests).toEqual([]);
|
||||
if (mode === "rollback") {
|
||||
await expect(db.transaction(async tx => {
|
||||
await toolAccessService(tx as unknown as Db).updateConnection(lane.endpoint.connectionId, { enabled: true });
|
||||
await new Promise(resolve => setTimeout(resolve, 25));
|
||||
expect(lane.maintenanceRequests).toEqual([]);
|
||||
throw new Error("rollback connection wake");
|
||||
})).rejects.toThrow("rollback connection wake");
|
||||
await vi.waitFor(() => {
|
||||
expect(coordinator.nextWakeAt()).toBeNull();
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
}, { timeout: 10_000 });
|
||||
expect(lane.maintenanceRequests).toEqual([]);
|
||||
expect(await maintenance()).toEqual([]);
|
||||
}
|
||||
await db.transaction(async tx => {
|
||||
await toolAccessService(tx as unknown as Db).updateConnection(lane.endpoint.connectionId, { enabled: true });
|
||||
await new Promise(resolve => setTimeout(resolve, 25));
|
||||
expect(lane.maintenanceRequests).toEqual([]);
|
||||
});
|
||||
}
|
||||
await vi.waitFor(async () => {
|
||||
const actions = await maintenance();
|
||||
expect(actions).toHaveLength(1);
|
||||
expect(actions[0]?.status).toBe("processed");
|
||||
expect(actions[0]?.result.attempts).toBe(mode === "retry" ? 2 : 1);
|
||||
expect(coordinator.nextWakeAt()).toBeNull();
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
}, { timeout: 10_000 });
|
||||
expect(lane.maintenanceRequests.filter(x => x.method === "setWebhook")).toHaveLength(mode === "retry" ? 2 : 1);
|
||||
expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, lane.endpoint.id),
|
||||
eq(chatActions.kind, "telegram_stop_subscription"), eq(chatActions.status, "processed")))).toHaveLength(1);
|
||||
const scans = vi.spyOn(db, "select");
|
||||
try {
|
||||
await new Promise(resolve => setTimeout(resolve, 1200));
|
||||
expect(scans).not.toHaveBeenCalled();
|
||||
} finally { scans.mockRestore(); }
|
||||
expect(onError).not.toHaveBeenCalled();
|
||||
} finally { await coordinator.stop(); await lane.close(); }
|
||||
},
|
||||
);
|
||||
|
||||
it("commits chat connection credentials atomically before waking maintenance", async () => {
|
||||
const lane = await draftFixture();
|
||||
const onError = vi.fn();
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
|
||||
const bindings = () => db.select({ secretId: companySecretBindings.secretId, configPath: companySecretBindings.configPath })
|
||||
.from(companySecretBindings).where(and(eq(companySecretBindings.companyId, lane.fixture.companyId),
|
||||
eq(companySecretBindings.targetType, "tool_connection"), eq(companySecretBindings.targetId, lane.endpoint.connectionId)))
|
||||
.orderBy(asc(companySecretBindings.configPath));
|
||||
let release!: () => void;
|
||||
let entered!: () => void;
|
||||
const held = new Promise<void>(resolve => { release = resolve; });
|
||||
const rebuilding = new Promise<void>(resolve => { entered = resolve; });
|
||||
let update: Promise<unknown> | undefined;
|
||||
const original = connectionCredentialBindings.syncConnectionCredentialBindings;
|
||||
const spy = vi.spyOn(connectionCredentialBindings, "syncConnectionCredentialBindings");
|
||||
try {
|
||||
await db.delete(chatActions).where(and(eq(chatActions.endpointId, lane.endpoint.id),
|
||||
eq(chatActions.kind, "telegram_stop_subscription")));
|
||||
lane.setSubscriptionInfo({});
|
||||
await lane.context.service.processTelegramSubscriptionDiscovery();
|
||||
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { enabled: false });
|
||||
await registerChatActionWork(coordinator, lane.context.service, () => true).ready;
|
||||
const before = await bindings();
|
||||
expect(before.length).toBeGreaterThan(0);
|
||||
spy.mockImplementation(async (database, connection, refs, client = database) => {
|
||||
if (connection.id === lane.endpoint.connectionId) {
|
||||
// Hold the real binding rebuild after its delete boundary. Another
|
||||
// connection must still see the old bindings until outer commit.
|
||||
await client.delete(companySecretBindings).where(and(eq(companySecretBindings.companyId, connection.companyId),
|
||||
eq(companySecretBindings.targetType, "tool_connection"), eq(companySecretBindings.targetId, connection.id)));
|
||||
entered();
|
||||
await held;
|
||||
}
|
||||
return original(database, connection, refs, client);
|
||||
});
|
||||
update = toolAccessService(db).updateConnection(lane.endpoint.connectionId, { name: "Renamed fixture", enabled: true });
|
||||
await rebuilding;
|
||||
expect(await bindings()).toEqual(before);
|
||||
await new Promise(resolve => setTimeout(resolve, 25));
|
||||
expect(lane.maintenanceRequests).toEqual([]);
|
||||
release();
|
||||
await update;
|
||||
await vi.waitFor(async () => {
|
||||
expect(await db.select({ status: chatActions.status }).from(chatActions).where(and(
|
||||
eq(chatActions.endpointId, lane.endpoint.id), eq(chatActions.kind, "telegram_maintenance"),
|
||||
sql`${chatActions.payload}->>'operation' = 'stop_subscription'`,
|
||||
))).toEqual([{ status: "processed" }]);
|
||||
expect(coordinator.nextWakeAt()).toBeNull();
|
||||
}, { timeout: 10_000 });
|
||||
expect(await bindings()).toEqual(before);
|
||||
expect(lane.maintenanceRequests.filter(x => x.method === "setWebhook")).toHaveLength(1);
|
||||
expect(onError).not.toHaveBeenCalled();
|
||||
} finally { release(); await update; spy.mockRestore(); await coordinator.stop(); await lane.close(); }
|
||||
});
|
||||
|
||||
it.each(["endpoint", "connection"] as const)("parks pending Telegram subscription repair while its %s is inactive", async inactive => {
|
||||
const lane = await draftFixture();
|
||||
const onError = vi.fn();
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
|
||||
const actions = () => db.select().from(chatActions).where(and(
|
||||
eq(chatActions.endpointId, lane.endpoint.id), eq(chatActions.kind, "telegram_maintenance"),
|
||||
sql`${chatActions.payload}->>'operation' = 'stop_subscription'`,
|
||||
));
|
||||
try {
|
||||
await db.delete(chatActions).where(and(eq(chatActions.endpointId, lane.endpoint.id),
|
||||
eq(chatActions.kind, "telegram_stop_subscription")));
|
||||
lane.setSubscriptionInfo({});
|
||||
await lane.context.service.processTelegramSubscriptionDiscovery();
|
||||
expect(await actions()).toEqual([expect.objectContaining({ status: "received" })]);
|
||||
if (inactive === "endpoint") {
|
||||
await lane.context.service.configure(lane.endpoint.id, { action: "pause" }, "owner-user");
|
||||
} else {
|
||||
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { enabled: false });
|
||||
}
|
||||
await registerChatActionWork(coordinator, lane.context.service, () => true).ready;
|
||||
await vi.waitFor(() => {
|
||||
expect(coordinator.nextWakeAt()).toBeNull();
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
}, { timeout: 10_000 });
|
||||
expect(await lane.context.service.nextChatActionAt("telegram_maintenance")).toBeNull();
|
||||
expect(lane.maintenanceRequests).toEqual([]);
|
||||
expect(await actions()).toEqual([expect.objectContaining({ status: "received" })]);
|
||||
const scans = vi.spyOn(db, "select");
|
||||
try {
|
||||
await new Promise(resolve => setTimeout(resolve, 1200));
|
||||
expect(scans).not.toHaveBeenCalled();
|
||||
} finally { scans.mockRestore(); }
|
||||
if (inactive === "endpoint") {
|
||||
await lane.context.service.configure(lane.endpoint.id, { action: "resume" }, "owner-user");
|
||||
} else {
|
||||
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { enabled: true });
|
||||
}
|
||||
await vi.waitFor(async () => {
|
||||
const rows = await actions();
|
||||
expect(rows.filter(row => row.status === "processed")).toEqual([
|
||||
expect.objectContaining({ result: expect.objectContaining({ attempts: 1 }) }),
|
||||
]);
|
||||
// Endpoint pause/resume advances its ownership generation. The old
|
||||
// obligation must settle without touching the provider again.
|
||||
expect(rows.filter(row => row.status !== "processed")).toEqual(inactive === "endpoint" ? [
|
||||
expect.objectContaining({ status: "cancelled", result: expect.objectContaining({ code: "telegram_maintenance_credentials_superseded" }) }),
|
||||
] : []);
|
||||
expect(coordinator.nextWakeAt()).toBeNull();
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
}, { timeout: 10_000 });
|
||||
expect(lane.maintenanceRequests.filter(x => x.method === "setWebhook")).toHaveLength(1);
|
||||
expect(onError).not.toHaveBeenCalled();
|
||||
} finally { await coordinator.stop(); await lane.close(); }
|
||||
});
|
||||
|
||||
it("durably stops during the first draft RPC without cancelling a run, and never reuses its ID after restart", async () => {
|
||||
const lane = await draftFixture();
|
||||
try {
|
||||
@@ -70850,11 +71042,14 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["explicit", "empty", "omitted"] as const)(
|
||||
it.each(["explicit", "empty", "omitted", "worker"] as const)(
|
||||
"automatically repairs an existing %s subscription after restart without dropping updates",
|
||||
async (shape) => {
|
||||
async (mode) => {
|
||||
const shape = mode === "worker" ? "explicit" : mode;
|
||||
const lane = await draftFixture();
|
||||
const prefixIds: string[] = [];
|
||||
const onError = vi.fn();
|
||||
const coordinator = mode === "worker" ? createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError }) : null;
|
||||
try {
|
||||
// Scheduler-only fixtures model a full already-confirmed first page.
|
||||
// They have no credentials; no provider qualification is claimed for
|
||||
@@ -70862,7 +71057,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
const [templateEndpoint] = await readChatEndpointsById(lane.endpoint.id);
|
||||
const [templateConnection] = await readToolConnectionsById(lane.endpoint.connectionId);
|
||||
const fingerprint = createHash("sha256").update("[]").digest("hex");
|
||||
for (let index = 0; index < 25; index++) {
|
||||
for (let index = 0; index < (mode === "worker" ? 105 : 25); index++) {
|
||||
const id = `00000000-${randomUUID().slice(9)}`;
|
||||
expect(id < lane.endpoint.id).toBe(true);
|
||||
const connectionId = randomUUID();
|
||||
@@ -70959,7 +71154,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
const targetIndex = eligible.findIndex(
|
||||
({ id }) => id === lane.endpoint.id,
|
||||
);
|
||||
expect(targetIndex).toBeGreaterThanOrEqual(25);
|
||||
expect(targetIndex).toBeGreaterThanOrEqual(mode === "worker" ? 105 : 25);
|
||||
const discoveryPasses = Math.floor(targetIndex / 25) + 1;
|
||||
const targetActions = () =>
|
||||
db
|
||||
@@ -70972,7 +71167,17 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
sql`${chatActions.payload}->>'operation' = 'stop_subscription'`,
|
||||
),
|
||||
);
|
||||
for (let page = 1; page <= discoveryPasses; page++) {
|
||||
if (coordinator) {
|
||||
await registerChatActionWork(coordinator, lane.context.service, () => true).ready;
|
||||
// Startup recovery uses successive bounded pages. The target is
|
||||
// beyond a complete 100-row confirmed prefix and is not in page one.
|
||||
expect(await targetActions()).toEqual([]);
|
||||
await vi.waitFor(async () => {
|
||||
expect((await targetActions())[0]?.status).toBe("processed");
|
||||
expect(coordinator.nextWakeAt()).toBeNull();
|
||||
}, { timeout: 30_000 });
|
||||
expect(onError).not.toHaveBeenCalled();
|
||||
} else for (let page = 1; page <= discoveryPasses; page++) {
|
||||
await lane.context.service.processPendingDeliveries();
|
||||
if (page < discoveryPasses) {
|
||||
expect(await targetActions()).toEqual([]);
|
||||
@@ -71025,6 +71230,21 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
({ method }) => method === "setWebhook",
|
||||
);
|
||||
expect(mutations).toHaveLength(1);
|
||||
if (coordinator) {
|
||||
// A committed edit must not rediscover another connection, even
|
||||
// when its durable proof is absent. Startup covers that inventory.
|
||||
const foreignEndpoint = prefixIds[0]!;
|
||||
await db.delete(chatActions).where(and(eq(chatActions.endpointId, foreignEndpoint),
|
||||
eq(chatActions.kind, "telegram_stop_subscription")));
|
||||
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { name: "Scoped Telegram edit" });
|
||||
await vi.waitFor(() => {
|
||||
expect(coordinator.nextWakeAt()).toBeNull();
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
}, { timeout: 10_000 });
|
||||
expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, foreignEndpoint),
|
||||
eq(chatActions.kind, "telegram_maintenance")))).toEqual([]);
|
||||
expect(lane.maintenanceRequests.filter(({ method }) => method === "setWebhook")).toHaveLength(1);
|
||||
}
|
||||
expect(mutations[0]!.body).toEqual({
|
||||
url: lane.configuredWebhook.url,
|
||||
secret_token: lane.configuredWebhook.secret_token,
|
||||
@@ -71071,6 +71291,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
).toHaveLength(1);
|
||||
} finally {
|
||||
try {
|
||||
await coordinator?.stop();
|
||||
if (prefixIds.length)
|
||||
await db
|
||||
.update(chatEndpoints)
|
||||
|
||||
+3
-1
@@ -1269,7 +1269,9 @@ export async function createApp(
|
||||
await chatChannels.reconcileProviderRuntimes();
|
||||
await chatChannels.voice.reconcile();
|
||||
},
|
||||
processPendingDeliveries: () => chatChannels.processPendingChatMaintenance(),
|
||||
// Chat delivery, action, and Telegram discovery workers now own these
|
||||
// duties. Keep the coordinator's other maintenance lanes independent.
|
||||
processPendingDeliveries: async () => undefined,
|
||||
processFailedGitHubWebhookDeliveries: () =>
|
||||
chatChannels.processFailedGitHubWebhookDeliveries(),
|
||||
projectRunMilestones: () =>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { and, eq, inArray, lte, or, sql } from "drizzle-orm";
|
||||
import { chatActions, chatEndpoints, type Db } from "@paperclipai/db";
|
||||
import { chatActions, chatEndpoints, toolConnections, type Db } from "@paperclipai/db";
|
||||
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
|
||||
import { CHAT_ACTION_QUEUES, type ScheduledChatAction } from "./chat-work-notifications.js";
|
||||
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
|
||||
@@ -50,7 +50,17 @@ function pendingChatAction(kind: ScheduledChatAction) {
|
||||
? inArray(chatActions.status, ["received", "processing"])
|
||||
: or(inArray(chatActions.status, ["received", "processing"]),
|
||||
and(eq(chatActions.status, "failed"), sql`${chatActions.result}->>'retryable' = 'true'`));
|
||||
return and(eq(chatActions.kind, kind), status);
|
||||
// Subscription repair is parked while its current endpoint/connection is
|
||||
// inactive. Registration and removal retain their existing dispatch rules.
|
||||
const telegramEligible = kind === "telegram_maintenance" ? sql`(
|
||||
${chatActions.payload}->>'operation' <> 'stop_subscription' or exists (
|
||||
select 1 from ${chatEndpoints} inner join ${toolConnections}
|
||||
on ${toolConnections.id} = ${chatEndpoints.connectionId} and ${toolConnections.companyId} = ${chatEndpoints.companyId}
|
||||
where ${chatEndpoints.id} = ${chatActions.endpointId} and ${chatEndpoints.companyId} = ${chatActions.companyId}
|
||||
and ${chatEndpoints.provider} = 'telegram' and ${chatEndpoints.status} = 'active'
|
||||
and ${toolConnections.status} = 'active' and ${toolConnections.enabled} = true
|
||||
))` : undefined;
|
||||
return and(eq(chatActions.kind, kind), status, telegramEligible);
|
||||
}
|
||||
|
||||
export function dueChatAction(kind: ScheduledChatAction, now = Date.now()) {
|
||||
@@ -67,6 +77,10 @@ export async function nextChatActionAt(db: Db, kind: ScheduledChatAction): Promi
|
||||
|
||||
type ChatActionService = {
|
||||
processFailedChatRunRetries(): Promise<unknown>;
|
||||
processPendingTelegramActions(): Promise<unknown>;
|
||||
processTelegramSubscriptionDiscovery(signal?: AbortSignal): Promise<unknown>;
|
||||
scheduleTelegramSubscriptionDiscovery(connectionId: string): void;
|
||||
hasPendingTelegramSubscriptionDiscovery(): boolean;
|
||||
processPendingProviderEffects(): Promise<unknown>;
|
||||
processPendingGitHubWebhookIngress(): Promise<unknown>;
|
||||
processPendingSlackSessionSyncs(): Promise<unknown>;
|
||||
@@ -86,6 +100,7 @@ export function registerChatActionWork(
|
||||
) {
|
||||
const actions = [
|
||||
{ kind: "failed_run_retry", run: service.processFailedChatRunRetries },
|
||||
{ kind: "telegram_maintenance", run: service.processPendingTelegramActions },
|
||||
{ kind: "provider_effect", run: service.processPendingProviderEffects },
|
||||
{ kind: "github_webhook_ingress", run: service.processPendingGitHubWebhookIngress },
|
||||
{ kind: "slack_session_sync", run: service.processPendingSlackSessionSyncs },
|
||||
@@ -101,5 +116,15 @@ export function registerChatActionWork(
|
||||
queue: DELIVERY_QUEUES.chatVerification,
|
||||
run: service.processPendingVerificationMessages, next: service.nextVerificationMessageAt,
|
||||
}, canRun));
|
||||
// Startup recovery visits the full inventory in bounded pages. Configuration
|
||||
// commits only enqueue the changed connection, never restart a global sweep.
|
||||
const discovery = coordinator.register(DELIVERY_QUEUES.chatTelegramSubscriptions, {
|
||||
retryMs: 1000,
|
||||
run: signal => service.processTelegramSubscriptionDiscovery(signal),
|
||||
onSettled: hints => { for (const id of hints ?? []) service.scheduleTelegramSubscriptionDiscovery(id); },
|
||||
// Preserve a configuration wake received during idle drain without SQL.
|
||||
hasPending: async () => !canRun() || service.hasPendingTelegramSubscriptionDiscovery(),
|
||||
});
|
||||
workers.push(discovery);
|
||||
return { ready: Promise.all(workers.map(worker => worker.ready)) };
|
||||
}
|
||||
@@ -1380,7 +1380,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
const { handleTelegramSlashCommand } = createTelegramCommands({ runtime, runtimeFor, handleSdkMessage });
|
||||
const { stageGitHubWebhookIngress, githubIngressAcceptedResponse, processGitHubWebhookIngress, processFailedGitHubWebhookDeliveries, processPendingGitHubWebhookIngress } = createGitHubWebhookIngress(db, { endpointRecord, runtimeContextForRecord, resolveCredentialRefs, runtimeGeneration, credentialFingerprint, getWebhookPublicBaseUrl, redactError, handleWebhook, runtimeCallbackEndpoint, fetchImpl, persistence, withCredentialMutationLease, isShuttingDown: () => shuttingDown, get githubWebhookReplayBarrier() { return options.githubWebhookReplayBarrier; }, supportedWebhookEvents: SUPPORTED_GITHUB_WEBHOOK_EVENTS });
|
||||
const { stageSlackSessionStop, processSlackSessionStop, processPendingSlackSessionStops } = createSlackSessionStop(db, { runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, nonDirectDestinationAllowed, stageAuthorizedTaskControlPublication, getPublicBaseUrl, get heartbeat() { return options.heartbeat; }, redactError });
|
||||
const { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, hasTelegramStopSubscription, recordTelegramStopSubscription } = createTelegramMaintenance(db, { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, resolveCredentials, clearCredentials, runtimeCallbackEndpoint, getWebhookPublicBaseUrl, fetchImpl, runtimeGeneration, credentialFingerprint, redactError, credentialCheckTimeoutMs: PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS });
|
||||
const { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, processPendingTelegramActions, processTelegramSubscriptionDiscovery, scheduleTelegramSubscriptionDiscovery, hasPendingTelegramSubscriptionDiscovery, hasTelegramStopSubscription, recordTelegramStopSubscription } = createTelegramMaintenance(db, { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, resolveCredentials, clearCredentials, runtimeCallbackEndpoint, getWebhookPublicBaseUrl, fetchImpl, runtimeGeneration, credentialFingerprint, redactError, credentialCheckTimeoutMs: PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS });
|
||||
const { reconcileGitHubWebhookRepository, reconcileProviderResourceRows, listResources, listGitHubRepositories, replaceResources, toggleAllGitHubRepositories, hasNewerProcessedProviderLifecycleEffect, applyProviderAvailability } = createChatResourceReconciliation(db, { endpointRecord, withCredentialMutationLease, runtimeGeneration, maxErrorText: MAX_ERROR_TEXT });
|
||||
const { applyGitHubInstallationLifecycle } = createGitHubInstallationLifecycle(db, {
|
||||
endpointRecord, resolveCredentials, runtimeCallbackEndpoint, runtimeGeneration, credentialFingerprint,
|
||||
@@ -1546,7 +1546,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
if (!current) return;
|
||||
const connection = await tx.select().from(toolConnections).where(eq(toolConnections.id, current.connectionId)).then((rows) => rows[0]);
|
||||
if (!connection?.enabled) throw new Error("Photon endpoint requires operator recovery");
|
||||
await notifyChatEndpointWork(tx);
|
||||
await notifyChatEndpointWork(tx, endpoint.connectionId);
|
||||
await tx.update(chatEndpoints).set({ status: current.setup.step === "complete" ? "active" : "verifying", healthMessage: "Photon receiver connected", lastError: null, updatedAt: new Date() }).where(eq(chatEndpoints.id, endpoint.id));
|
||||
});
|
||||
},
|
||||
@@ -7854,6 +7854,10 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
processQueuedDeliveries: () => processPendingDeliveries(25, undefined, false),
|
||||
scheduleQueuedPublications: () => processPendingPublications(25, { waitForCompletion: false, maintenance: false }),
|
||||
processPendingChatMaintenance,
|
||||
processPendingTelegramActions,
|
||||
processTelegramSubscriptionDiscovery,
|
||||
scheduleTelegramSubscriptionDiscovery,
|
||||
hasPendingTelegramSubscriptionDiscovery,
|
||||
processPendingSlackBoardMessages,
|
||||
processPendingSlackTaskStarts,
|
||||
processPendingVerificationMessages: slackRegistration.processPendingVerificationMessages,
|
||||
|
||||
@@ -181,7 +181,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
|
||||
code: "chat_endpoint_not_active",
|
||||
});
|
||||
}
|
||||
await notifyChatEndpointWork(tx);
|
||||
await notifyChatEndpointWork(tx, endpoint.connectionId);
|
||||
await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
@@ -317,7 +317,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
|
||||
inArray(chatDeliveries.state, ["received", "retry"]),
|
||||
),
|
||||
);
|
||||
await notifyChatEndpointWork(tx);
|
||||
await notifyChatEndpointWork(tx, endpoint.connectionId);
|
||||
[activatedEndpoint] = await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
@@ -364,7 +364,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
|
||||
const failedAt = new Date();
|
||||
await db.transaction(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
await notifyChatEndpointWork(tx);
|
||||
await notifyChatEndpointWork(tx, endpoint.connectionId);
|
||||
await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
@@ -467,7 +467,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
|
||||
code: "chat_endpoint_already_removed",
|
||||
});
|
||||
}
|
||||
await notifyChatEndpointWork(tx);
|
||||
await notifyChatEndpointWork(tx, endpoint.connectionId);
|
||||
await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
@@ -698,7 +698,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
|
||||
try {
|
||||
const claimed = await db.transaction(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
await notifyChatEndpointWork(tx);
|
||||
await notifyChatEndpointWork(tx, endpoint.connectionId);
|
||||
const rows = await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
@@ -778,7 +778,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
|
||||
const preserveSlackVerification = isProvisionedSlackSetup(current.setup.slackSetupMethod)
|
||||
&& (current.setup as InternalSetupState).slackVerificationSigningFingerprint === createHash("sha256").update(credentials.signingSecret ?? "").digest("hex")
|
||||
&& Boolean(observedSlackUrl && slackCallbackMatchesPublicUrl(observedSlackUrl, `${getWebhookPublicBaseUrl()}/api/chat-webhooks/${endpoint.publicId}/slack`));
|
||||
await notifyChatEndpointWork(tx);
|
||||
await notifyChatEndpointWork(tx, endpoint.connectionId);
|
||||
await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
@@ -863,7 +863,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
|
||||
await invalidateRuntime(endpoint.id).catch(() => undefined);
|
||||
await db.transaction(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
await notifyChatEndpointWork(tx);
|
||||
await notifyChatEndpointWork(tx, endpoint.connectionId);
|
||||
await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
|
||||
@@ -157,7 +157,7 @@ export function createDiscordGatewayEvents(db: Db, options: DiscordGatewayEvents
|
||||
if (current.status === "attention" && !gatewayOwnedAttention) return;
|
||||
const status =
|
||||
current.setup.step === "complete" ? "active" : "verifying";
|
||||
if (status !== current.status) await notifyChatEndpointWork(tx);
|
||||
if (status !== current.status) await notifyChatEndpointWork(tx, current.connectionId);
|
||||
await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
|
||||
@@ -508,7 +508,7 @@ export function createChatResourceReconciliation(db: Db, options: ResourceReconc
|
||||
: currentEndpoint.status === "attention"
|
||||
? "verifying"
|
||||
: currentEndpoint.status;
|
||||
if (status !== currentEndpoint.status) await notifyChatEndpointWork(tx);
|
||||
if (status !== currentEndpoint.status) await notifyChatEndpointWork(tx, currentEndpoint.connectionId);
|
||||
await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
|
||||
@@ -296,7 +296,7 @@ export function createSetupProbes(db: Db, options: SetupProbesOptions) {
|
||||
)).limit(1).then((rows) => rows[0]);
|
||||
if (!linked || !(await lockCurrentPrincipalAuthorization(tx, endpoint, linked.principalId)).allowed) throw forbidden("Your connected account is no longer authorized");
|
||||
}
|
||||
await notifyChatEndpointWork(tx);
|
||||
await notifyChatEndpointWork(tx, endpoint.connectionId);
|
||||
const [activated] = await tx
|
||||
.update(chatEndpoints)
|
||||
.set({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { EndpointRow, DbTransaction, LifecycleRuntimeFence } from "../runtime-types.js";
|
||||
|
||||
import { PROVIDER_EFFECT_STALE_MS } from "../../chat-action-work.js";
|
||||
import { PROVIDER_EFFECT_STALE_MS, dueChatAction } from "../../chat-action-work.js";
|
||||
import { notifyChatActionWork } from "../../chat-work-notifications.js";
|
||||
|
||||
import type { chatCredentialMutationLease, CredentialMutationLeaseGuard } from "../../chat-credential-mutation-lease.js";
|
||||
|
||||
@@ -12,8 +13,6 @@ import {
|
||||
asc,
|
||||
eq,
|
||||
gt,
|
||||
lte,
|
||||
or,
|
||||
sql,
|
||||
} from "drizzle-orm";
|
||||
|
||||
@@ -103,6 +102,16 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
const { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, resolveCredentials, clearCredentials, runtimeCallbackEndpoint, getWebhookPublicBaseUrl, fetchImpl, runtimeGeneration, credentialFingerprint, redactError, credentialCheckTimeoutMs: PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS } = options;
|
||||
|
||||
let telegramSubscriptionScanAfter: string | null = null;
|
||||
let startupDiscoveryPending = true;
|
||||
let startupDiscoveryAfter: string | null = null;
|
||||
const pendingDiscovery = new Map<string, { after: string | null }>();
|
||||
|
||||
function withMaintenanceWrite<T>(write: (tx: DbTransaction) => Promise<T>): Promise<T> {
|
||||
return db.transaction(async tx => {
|
||||
await notifyChatActionWork(tx, "telegram_maintenance");
|
||||
return write(tx);
|
||||
});
|
||||
}
|
||||
|
||||
async function stageTelegramMaintenance(
|
||||
endpoint: EndpointRow,
|
||||
@@ -122,7 +131,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
? `${context.generation}:${record.endpoint.setup.testStartedAt ?? record.endpoint.updatedAt.toISOString()}`
|
||||
: String(context.generation);
|
||||
const providerActionId = `telegram_maintenance:${operation}:${operationGeneration}`;
|
||||
const [inserted] = await db
|
||||
const [inserted] = await withMaintenanceWrite(tx => tx
|
||||
.insert(chatActions)
|
||||
.values({
|
||||
companyId: endpoint.companyId,
|
||||
@@ -144,7 +153,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
status: "received",
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning();
|
||||
.returning());
|
||||
return (
|
||||
inserted ??
|
||||
(await db
|
||||
@@ -241,7 +250,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
if (action.status === "processed") return "processed";
|
||||
const payload = telegramMaintenancePayload(action.payload);
|
||||
if (!payload) {
|
||||
await db
|
||||
await withMaintenanceWrite(tx => tx
|
||||
.update(chatActions)
|
||||
.set({
|
||||
status: "failed",
|
||||
@@ -251,18 +260,18 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
},
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(chatActions.id, action.id));
|
||||
.where(eq(chatActions.id, action!.id)));
|
||||
return "failed";
|
||||
}
|
||||
if (action.status === "processing") {
|
||||
if (action.updatedAt > new Date(Date.now() - PROVIDER_EFFECT_STALE_MS))
|
||||
return "pending";
|
||||
await db
|
||||
await withMaintenanceWrite(tx => tx
|
||||
.update(chatActions)
|
||||
.set({
|
||||
status: "failed",
|
||||
result: {
|
||||
...(action.result ?? {}),
|
||||
...(action!.result ?? {}),
|
||||
retryable: true,
|
||||
retryAt: new Date().toISOString(),
|
||||
},
|
||||
@@ -270,11 +279,11 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(chatActions.id, action.id),
|
||||
eq(chatActions.id, action!.id),
|
||||
eq(chatActions.status, "processing"),
|
||||
eq(chatActions.updatedAt, action.updatedAt),
|
||||
eq(chatActions.updatedAt, action!.updatedAt),
|
||||
),
|
||||
);
|
||||
));
|
||||
action = await db
|
||||
.select()
|
||||
.from(chatActions)
|
||||
@@ -297,7 +306,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
? action.result.attempts
|
||||
: 0) + 1;
|
||||
let providerConfirmed = action.result?.providerConfirmed === true;
|
||||
const [claimed] = await db.transaction(async (tx) => {
|
||||
const [claimed] = await withMaintenanceWrite(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
const rows = await tx
|
||||
.update(chatActions)
|
||||
@@ -334,7 +343,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
// Empty refs prove removal cleanup crossed its final local boundary;
|
||||
// settle the idempotent action instead of misclassifying it as a
|
||||
// credential rotation.
|
||||
await db.transaction(async (tx) => {
|
||||
await withMaintenanceWrite(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
await tx
|
||||
.update(chatActions)
|
||||
@@ -361,7 +370,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
runtimeGeneration(record.endpoint.setup) !==
|
||||
payload.runtimeGeneration)
|
||||
) {
|
||||
await db.transaction(async (tx) => {
|
||||
await withMaintenanceWrite(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
await tx
|
||||
.update(chatActions)
|
||||
@@ -422,7 +431,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
providerConfirmed = true;
|
||||
}
|
||||
await credentialLease.assertOwned();
|
||||
await db.transaction(async (tx) => {
|
||||
await withMaintenanceWrite(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
const confirmed = await tx
|
||||
.update(chatActions)
|
||||
@@ -450,7 +459,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
await credentialLease.assertOwned();
|
||||
await clearCredentials(record.endpoint, credentialLease);
|
||||
}
|
||||
await db.transaction(async (tx) => {
|
||||
await withMaintenanceWrite(async (tx) => {
|
||||
await credentialLease.assertOwned(tx);
|
||||
const processed = await tx
|
||||
.update(chatActions)
|
||||
@@ -499,7 +508,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
? new Date(Date.now() + retryAfterMs).toISOString()
|
||||
: null;
|
||||
const diagnostic = redactError(error);
|
||||
await db
|
||||
await withMaintenanceWrite(tx => tx
|
||||
.update(chatActions)
|
||||
.set({
|
||||
status: "failed",
|
||||
@@ -507,7 +516,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
attempts: attempt,
|
||||
code: `telegram_maintenance_${disposition.kind}`,
|
||||
providerConfirmed:
|
||||
providerConfirmed || action.result?.providerConfirmed === true,
|
||||
providerConfirmed || action!.result?.providerConfirmed === true,
|
||||
redactedError: diagnostic,
|
||||
retryable,
|
||||
retryAt,
|
||||
@@ -516,11 +525,11 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(chatActions.id, action.id),
|
||||
eq(chatActions.id, action!.id),
|
||||
eq(chatActions.status, "processing"),
|
||||
sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,
|
||||
),
|
||||
);
|
||||
));
|
||||
await logActivity(db, {
|
||||
companyId: action.companyId,
|
||||
actorType: "system",
|
||||
@@ -554,7 +563,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
}
|
||||
}
|
||||
|
||||
async function processPendingTelegramMaintenance(limit = 25) {
|
||||
async function discoverTelegramSubscriptions(limit: number, after: string | null, connectionId?: string, signal?: AbortSignal) {
|
||||
// Keyset scanning bounds each sweep without starving endpoints behind a
|
||||
// page whose subscriptions were already confirmed. No provider I/O here.
|
||||
const candidates = await db
|
||||
@@ -573,18 +582,16 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
eq(chatEndpoints.status, "active"),
|
||||
eq(toolConnections.status, "active"),
|
||||
eq(toolConnections.enabled, true),
|
||||
telegramSubscriptionScanAfter
|
||||
? gt(chatEndpoints.id, telegramSubscriptionScanAfter)
|
||||
connectionId !== undefined ? eq(chatEndpoints.connectionId, connectionId) : undefined,
|
||||
after
|
||||
? gt(chatEndpoints.id, after)
|
||||
: undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(asc(chatEndpoints.id))
|
||||
.limit(Math.max(1, Math.min(limit, 100)));
|
||||
telegramSubscriptionScanAfter =
|
||||
candidates.length >= Math.max(1, Math.min(limit, 100))
|
||||
? candidates.at(-1)!.endpoint.id
|
||||
: null;
|
||||
for (const { endpoint } of candidates) {
|
||||
signal?.throwIfAborted();
|
||||
try {
|
||||
const record = await endpointRecord(endpoint.id);
|
||||
if (
|
||||
@@ -595,42 +602,58 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
))
|
||||
)
|
||||
await stageTelegramMaintenance(record.endpoint, "stop_subscription");
|
||||
} catch {
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{ endpointId: endpoint.id },
|
||||
"Telegram subscription maintenance could not be staged",
|
||||
);
|
||||
// Keep the pass recoverable. Earlier staged rows are idempotent, and
|
||||
// failed discovery must not become invisible until the next restart.
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const now = new Date();
|
||||
const staleBefore = new Date(now.getTime() - PROVIDER_EFFECT_STALE_MS);
|
||||
return candidates.length >= Math.max(1, Math.min(limit, 100))
|
||||
? candidates.at(-1)!.endpoint.id : null;
|
||||
}
|
||||
|
||||
async function processTelegramSubscriptionDiscovery(signal?: AbortSignal) {
|
||||
signal?.throwIfAborted();
|
||||
const scoped = pendingDiscovery.entries().next().value;
|
||||
if (scoped) {
|
||||
const [connectionId, request] = scoped;
|
||||
const after = await discoverTelegramSubscriptions(100, request.after, connectionId, signal);
|
||||
// A commit during this page replaces the request and requires a fresh
|
||||
// scoped pass, including changes behind its cursor.
|
||||
if (pendingDiscovery.get(connectionId) === request) {
|
||||
if (after === null) pendingDiscovery.delete(connectionId);
|
||||
else request.after = after;
|
||||
}
|
||||
} else if (startupDiscoveryPending) {
|
||||
startupDiscoveryAfter = await discoverTelegramSubscriptions(100, startupDiscoveryAfter, undefined, signal);
|
||||
startupDiscoveryPending = startupDiscoveryAfter !== null;
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleTelegramSubscriptionDiscovery(connectionId: string) {
|
||||
pendingDiscovery.set(connectionId, { after: null });
|
||||
}
|
||||
|
||||
function hasPendingTelegramSubscriptionDiscovery() {
|
||||
return startupDiscoveryPending || pendingDiscovery.size > 0;
|
||||
}
|
||||
|
||||
async function processPendingTelegramMaintenance(limit = 25) {
|
||||
// Preserve the explicit bounded recovery helper. The app's periodic
|
||||
// reconciliation no longer calls it; registered workers own both lanes.
|
||||
telegramSubscriptionScanAfter = await discoverTelegramSubscriptions(limit, telegramSubscriptionScanAfter);
|
||||
return processPendingTelegramActions(limit);
|
||||
}
|
||||
|
||||
async function processPendingTelegramActions(limit = 25) {
|
||||
const actions = await db
|
||||
.select({ id: chatActions.id })
|
||||
.from(chatActions)
|
||||
.where(
|
||||
and(
|
||||
eq(chatActions.kind, "telegram_maintenance"),
|
||||
sql`(${chatActions.payload}->>'operation' <> 'stop_subscription' or exists (
|
||||
select 1 from ${chatEndpoints} inner join ${toolConnections}
|
||||
on ${toolConnections.id} = ${chatEndpoints.connectionId} and ${toolConnections.companyId} = ${chatEndpoints.companyId}
|
||||
where ${chatEndpoints.id} = ${chatActions.endpointId} and ${chatEndpoints.companyId} = ${chatActions.companyId}
|
||||
and ${chatEndpoints.provider} = 'telegram' and ${chatEndpoints.status} = 'active'
|
||||
and ${toolConnections.status} = 'active' and ${toolConnections.enabled} = true
|
||||
))`,
|
||||
or(
|
||||
eq(chatActions.status, "received"),
|
||||
and(
|
||||
eq(chatActions.status, "processing"),
|
||||
lte(chatActions.updatedAt, staleBefore),
|
||||
),
|
||||
and(
|
||||
eq(chatActions.status, "failed"),
|
||||
sql`coalesce(${chatActions.result}->>'retryable', 'false') = 'true'`,
|
||||
sql`(${chatActions.result}->>'retryAt' is null or (${chatActions.result}->>'retryAt')::timestamptz <= ${now.toISOString()}::timestamptz)`,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.where(dueChatAction("telegram_maintenance"))
|
||||
.orderBy(asc(chatActions.createdAt))
|
||||
.limit(limit);
|
||||
for (const action of actions) await processTelegramMaintenance(action.id);
|
||||
@@ -927,5 +950,5 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
|
||||
await assertCurrent();
|
||||
await recordTelegramStopSubscription(endpoint, context, lease);
|
||||
}
|
||||
return { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, hasTelegramStopSubscription, recordTelegramStopSubscription };
|
||||
return { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, processPendingTelegramActions, processTelegramSubscriptionDiscovery, scheduleTelegramSubscriptionDiscovery, hasPendingTelegramSubscriptionDiscovery, hasTelegramStopSubscription, recordTelegramStopSubscription };
|
||||
}
|
||||
@@ -14,6 +14,7 @@ export const CHAT_ACTION_QUEUES = {
|
||||
provider_effect: DELIVERY_QUEUES.chatProviderEffects,
|
||||
github_webhook_ingress: DELIVERY_QUEUES.chatGitHubIngress,
|
||||
failed_run_retry: DELIVERY_QUEUES.chatFailedRunRetries,
|
||||
telegram_maintenance: DELIVERY_QUEUES.chatTelegramMaintenance,
|
||||
slack_session_sync: DELIVERY_QUEUES.chatSessionSyncs,
|
||||
slack_board_message: DELIVERY_QUEUES.chatBoardMessages,
|
||||
slash_task_start: DELIVERY_QUEUES.chatTaskStarts,
|
||||
@@ -30,9 +31,10 @@ export async function notifyChatVerificationWork(tx: object): Promise<void> {
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatVerification);
|
||||
}
|
||||
|
||||
export async function notifyChatEndpointWork(tx: object): Promise<void> {
|
||||
export async function notifyChatEndpointWork(tx: object, connectionId: string): Promise<void> {
|
||||
await notifyChatDeliveryWork(tx);
|
||||
await notifyChatPublicationWork(tx);
|
||||
for (const queue of Object.values(CHAT_ACTION_QUEUES)) await notifyDeliveryWork(tx, queue);
|
||||
await notifyChatVerificationWork(tx);
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatTelegramSubscriptions, connectionId);
|
||||
}
|
||||
@@ -22,6 +22,8 @@ export function createDeliveryWorkCoordinator(input: {
|
||||
retryMs: number;
|
||||
run: (signal: AbortSignal) => Promise<unknown>;
|
||||
hasPending: () => Promise<boolean>;
|
||||
// Scoped hints belong to the outer transaction, including uncertainty recovery.
|
||||
onSettled?: (hints?: ReadonlySet<string>) => void;
|
||||
// Optional maintenance/retry deadline restored from durable state.
|
||||
nextRunAt?: () => number | null;
|
||||
}) {
|
||||
@@ -72,7 +74,7 @@ export function createDeliveryWorkCoordinator(input: {
|
||||
dirty = true;
|
||||
if (!running) schedule(0);
|
||||
}
|
||||
const unsubscribe = subscribeDatabaseWork(input.owner, queue, event => {
|
||||
const unsubscribe = subscribeDatabaseWork(input.owner, queue, (event, hints) => {
|
||||
if (workerStopped) return;
|
||||
if (databaseWorkPending(input.owner, queue)) {
|
||||
finishIntent ??= beginIdleTrackedWork();
|
||||
@@ -80,7 +82,7 @@ export function createDeliveryWorkCoordinator(input: {
|
||||
// replaces this deadline with an immediate wake on the normal path.
|
||||
if (!running) schedule(task.retryMs);
|
||||
}
|
||||
if (event === "settled") wake();
|
||||
if (event === "settled") { task.onSettled?.(hints); wake(); }
|
||||
});
|
||||
const worker = { wake, async stop() {
|
||||
workerStopped = true;
|
||||
|
||||
@@ -9,6 +9,8 @@ export const DELIVERY_QUEUES = {
|
||||
chatProviderEffects: "chat-provider-effects",
|
||||
chatGitHubIngress: "chat-github-ingress",
|
||||
chatFailedRunRetries: "chat-failed-run-retries",
|
||||
chatTelegramMaintenance: "chat-telegram-maintenance",
|
||||
chatTelegramSubscriptions: "chat-telegram-subscriptions",
|
||||
chatSessionSyncs: "chat-session-syncs",
|
||||
chatVerification: "chat-verification",
|
||||
chatInbound: "chat-inbound",
|
||||
@@ -25,8 +27,8 @@ export const DELIVERY_QUEUES = {
|
||||
} as const;
|
||||
export type DeliveryQueue = typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES];
|
||||
|
||||
export async function notifyDeliveryWork(transaction: object, queue: DeliveryQueue): Promise<void> {
|
||||
await signalDatabaseWork(transaction, queue);
|
||||
export async function notifyDeliveryWork(transaction: object, queue: DeliveryQueue, hint?: string): Promise<void> {
|
||||
await signalDatabaseWork(transaction, queue, hint);
|
||||
}
|
||||
// Public delivery notification observers only see settled work. The coordinator
|
||||
// uses the lower-level lifecycle subscription to also fence in-flight writes.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { chatCredentialMutationLease } from "./chat-credential-mutation-lease.js";
|
||||
import { notifyChatEndpointWork } from "./chat-work-notifications.js";
|
||||
import { removeSlackRegistration } from "./chat-slack-registration-cleanup.js";
|
||||
import { chatEndpoints } from "@paperclipai/db";
|
||||
import { AGGREGATOR_NAMES, isAppAggregator, type AggregatorAppsResponse, type ArcadeDiscoverySetupInput } from "@paperclipai/shared/aggregator-apps";
|
||||
@@ -19047,7 +19048,7 @@ export function toolAccessService(
|
||||
...(input.credentialRefs ?? existing.credentialRefs),
|
||||
...(input.credentialSecretRefs ?? existing.credentialSecretRefs),
|
||||
]);
|
||||
const [row] = await db
|
||||
const write = (database: Db) => database
|
||||
.update(toolConnections)
|
||||
.set({
|
||||
name: input.name ?? existing.name,
|
||||
@@ -19066,7 +19067,17 @@ export function toolAccessService(
|
||||
})
|
||||
.where(eq(toolConnections.id, connectionId))
|
||||
.returning();
|
||||
await syncCredentialBindings(row);
|
||||
const [row] = existing.transport === "chat_sdk"
|
||||
? await db.transaction(async tx => {
|
||||
await notifyChatEndpointWork(tx, existing.id);
|
||||
const rows = await write(tx as unknown as Db);
|
||||
// Credential resolution must never observe the binding rebuild's
|
||||
// delete/insert gap after a configuration wake.
|
||||
await syncCredentialBindings(rows[0]!, [], tx);
|
||||
return rows;
|
||||
})
|
||||
: await write(db);
|
||||
if (existing.transport !== "chat_sdk") await syncCredentialBindings(row);
|
||||
await ensureRuntimeSlot(row);
|
||||
emitConnectionUpdated(row, existing, "api");
|
||||
return toConnection(row);
|
||||
|
||||
Reference in new issue
Block a user