mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
fix(slack): align form publication wait backoff with enrollment deadlines (#23819)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Slack chat channels deliver interactive question forms that depend on Cloud events and form-owner enrollment before Paperclip posts the prompt. > - When enrollment is pending and backed off for 60s to 300s, `createSlackFormPublicationStage` returns a hardcoded `retryAfterMs: 2_000` wait instead of reading the enrollment `nextAttemptAt` deadline. > - That hardcoded 2-second wait makes the publication worker claim leases, run 20 to 30 SQL queries, emit `chat publication failed` warnings every few seconds, and keep `chat_endpoint_leases` hot while blocking idle sleep. > - This pull request derives the publication wait delay from the pending `slackCloudIntent` or `slack_form_owner` deadline (bounded to `[2_000 ms, 300_000 ms]`), clears waiting publication deadlines and notifies `chatPublications` whenever enrollment commits, retires, or enters `attention`, rechecks wait state via a shared predicate inside a savepoint (`FOR SHARE NOWAIT`) in the deferral transaction, and logs pre-send waits at debug level. > - The benefit is cutting a 5-minute enrollment wait from ~100–150 publication/lease cycles to 1 while preserving immediate wake on early enrollment completion or attention settlement. ## Linked Issues or Issue Description **What happened?** A Slack form publication waiting on `form_publication_enrollment_pending` loops every ~2–3 seconds and logs `chat publication failed` warnings continuously while enrollment is backed off for up to 300 seconds. Each tick claims and deletes `chat_endpoint_leases`, writes `chat_publications`, and prevents the worker from going quiet. **Expected behavior** A Slack form publication waiting on pending enrollment schedules its `nextAttemptAt` to match the pending `slackCloudIntent.nextAttemptAt` or `slack_form_owner.result.nextAttemptAt` deadline (with a 2-second floor for past/due deadlines and a 300-second cap), emits a debug log rather than a failure warning, and wakes immediately when enrollment commits early, retires, or transitions to `attention`. **Steps to reproduce** 1. Configure a Slack endpoint with managed Cloud forms and a pending `slackCloudIntent` or staged `slack_form_owner` backed off 60s–300s in the future. 2. Create an `ask_user_questions` interaction with a Slack form prompt (`question_form_open`) on an active Slack conversation. 3. Run the `chatPublications` delivery worker and observe `chat_publications.next_attempt_at` and server logs. **Paperclip version or commit** Reproduced on `master` prior to `0c0cd68c711da5ebdb0cbaf5a2d54bc96faca7c4`. **Deployment mode** Self-hosted server ## What Changed - **`server/src/services/chat-channels/slack/form-publication.ts`**: Extract single-source-of-truth `pendingIntentDeadline` and `pendingOwnerDeadline` helpers used by both the main readiness gate and the `stillWaiting(tx)` recheck. Compute `retryAfterMs` from the actual pending deadline clamped to `[2_000 ms, 300_000 ms]`. Use `FOR SHARE NOWAIT` in `stillWaiting(tx)` so the recheck never blocks on concurrent enrollment updates. - **`server/src/services/chat-channels/publications/preparation.ts` & `publications/failures.ts`**: Extend `ChatPublicationPreparationWait` with an optional platform-agnostic `stillWaiting?: (tx: DbTransaction) => Promise<boolean>` callback. Execute `stillWaiting` inside a PostgreSQL savepoint (`tx.transaction(...)`): if `stillWaiting` returns `false`, commit `nextAttemptAt = null` so an enrollment commit racing deferral wakes immediately; if `stillWaiting` hits lock contention (`NOWAIT`) or a transient error, roll back only the savepoint and commit `state = "retry"` with a `<= 2_000 ms` fallback so a benign pre-send wait can never stay `streaming` and become `delivery_unknown`. Log `waitingBeforeSend` deferrals at `logger.debug(..., "chat publication waiting before send")` instead of `logger.warn(..., "chat publication failed")`. - **`server/src/services/chat-channels/slack/form-owner.ts` & `cloud-enrollment.ts`**: Add `clearWaitingSlackFormPublicationDeadlines(tx, endpoint)` and register `notifyChatPublicationWork(tx)` before writes across every enrollment resolution/retirement/attention transition (`reconcileSlackFormEnrollment`, `stageSlackFormEnrollment` for an already-enrolled owner, `stageSlackFormOwnerConfiguration` deactivation, `reconcilePendingSlackFormWork` permanent `attention`, `stageSlackCloudEnrollmentIntent` inactive/attention staging, and `createSlackCloudEnrollment` `intent_authority_changed` / `attention` / retirement commits). - **Tests & CI timing manifests**: Extended `server/src/__tests__/slack-cloud-forms.test.ts` and `server/src/services/chat-channels/slack/cloud-enrollment.test.ts`, added a focused real embedded-PostgreSQL suite in `server/src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts` (641 lines; keeping `slack-protocol.integration.test.ts` untouched at 726 lines), and registered its measured 8-core CI timing (`12547 ms`) in `scripts/chat-shard-durations.json` and `scripts/general-server-shard-durations.json`. ### Sleep-Aware Background Work Contract - **Trigger**: Shared `DELIVERY_QUEUES.chatPublications` transaction-aware work signals (`notifyChatPublicationWork`) and saved per-row `chat_publications.next_attempt_at` deadlines read by `nextPublicationAt()`. - **Durable source of truth**: `chat_publications` (`state`, `next_attempt_at`, `attempts`, `redacted_error`), `chat_endpoints.setup` (`slackCloudIntent`, `slackCloudForms`), and `chat_actions` (`slack_form_owner`). - **Pending-work predicate**: `publicationEligibility()` selects `chat_publications` in `pending`/`retry` whose `next_attempt_at` is `null` or due (`<= now`) on active/verifying endpoints. - **Next deadline/retry**: `nextAttemptAt` tracks `clamp(2_000, 300_000, enrollmentDeadline - now)` while enrollment is scheduled, is cleared to `null` when enrollment completes, retires, or enters `attention` (or when `stillWaiting(tx)` sees enrollment already settled), and falls back to `<= 2_000 ms` if `stillWaiting` encounters lock contention. - **Quiet condition**: Once waiting publications defer to the enrollment deadline (up to 300s), no publication sweep or lease write runs until either that deadline arrives or an enrollment producer commits a state change; once enrollment resolves, publications publish or settle to `failed`/`cancelled` and `nextPublicationAt()` returns `null`. ## Verification Verified on commit `a75b654d3d75f9b36f860b0793baa94f5811fdac`: - Reproduced pre-fix RED failures before applying the fix: unit tests confirmed hardcoded `2000 ms` waits for 60s/300s deadlines and missing publication wake on `slackCloudIntent` attention; real PostgreSQL tests confirmed 2s `nextAttemptAt` scheduling, `chat publication failed` warn logs, and 5-minute stranding on the concurrent commit race. - `pnpm check:module-boundaries` — PASS. - `node scripts/check-test-budget.mjs --base origin/master` — PASS (113 nightly suites validated, 3 test files checked). - `node --test ./scripts/__tests__/run-vitest-stable-shard.test.mjs ./scripts/__tests__/run-vitest-stable-pr-mode.test.mjs ./scripts/ci/test-selection-pr-timings.test.mjs ./scripts/check-test-budget.test.mjs .github/scripts/tests/ci-dependency-cache.test.mjs` — PASS (79/79 tests). - `pnpm --filter @paperclipai/server typecheck` — PASS (all 7 typecheck layers green; unchanged server sources since `459443a36a`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/slack-cloud-forms.test.ts src/services/chat-channels/slack/cloud-enrollment.test.ts src/services/chat-publication-errors.test.ts src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts` — PASS (4 test files, 106/106 tests passed; unchanged server sources since `459443a36a`). - Scope note: Local tests verify worker quiet, durable deadlines, and PostgreSQL reactivation; they do not by themselves prove deployed host suspension or fleet cost reduction. ## Risks - Low risk; no database schema or migration changes are introduced. - Lock ordering stays acyclic (`chat_endpoint_leases` -> `chat_endpoints` -> `chat_actions` -> `chat_publications`), and `stillWaiting(tx)` uses `FOR SHARE NOWAIT` inside a PostgreSQL savepoint so lock contention can neither block nor abort publication finalization. - `clearWaitingSlackFormPublicationDeadlines` only clears `next_attempt_at` on `state = 'retry'` rows with `redacted_error = 'form_publication_enrollment_pending'` for the affected `(company_id, endpoint_id)`, verified by test to leave unrelated provider rate-limit backoffs untouched. - Process-local transaction notifications cover supported application writers; startup reconstruction and the bounded 300s ceiling still recover any external or out-of-band state change. ## Model Used Gemini 4 Neon (Google DeepMind, XHigh reasoning, with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
1f817b495c
commit
84ca111c78
10 files changed
+1089
-46
No files matched your search
@@ -5,8 +5,8 @@
|
||||
"github-actions:45592683902@57638686dc"
|
||||
],
|
||||
"coverage": {
|
||||
"measured": 23,
|
||||
"inventory": 23
|
||||
"measured": 24,
|
||||
"inventory": 24
|
||||
},
|
||||
"durations": {
|
||||
"server/src/__tests__/chat-channels/board-and-shared-core.integration.test.ts": 62795,
|
||||
@@ -22,6 +22,7 @@
|
||||
"server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts": 58821,
|
||||
"server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts": 62020,
|
||||
"server/src/__tests__/chat-channels/github-webhook-recovery.integration.test.ts": 52606,
|
||||
"server/src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts": 12547,
|
||||
"server/src/__tests__/chat-channels/slack-ingress-and-threads.integration.test.ts": 45584,
|
||||
"server/src/__tests__/chat-channels/slack-interactions-and-files.integration.test.ts": 94522,
|
||||
"server/src/__tests__/chat-channels/slack-protocol.integration.test.ts": 17846,
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
}
|
||||
],
|
||||
"coverage": {
|
||||
"measured": 1693,
|
||||
"withSetup": 1579,
|
||||
"inventory": 1752
|
||||
"measured": 1694,
|
||||
"withSetup": 1580,
|
||||
"inventory": 1753
|
||||
},
|
||||
"durations": {
|
||||
"server/scripts/build-config.test.mjs": 10828,
|
||||
@@ -198,6 +198,7 @@
|
||||
"server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts": 58821,
|
||||
"server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts": 20202,
|
||||
"server/src/__tests__/chat-channels/github-webhook-recovery.integration.test.ts": 20859,
|
||||
"server/src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts": 12547,
|
||||
"server/src/__tests__/chat-channels/slack-ingress-and-threads.integration.test.ts": 9836,
|
||||
"server/src/__tests__/chat-channels/slack-interactions-and-files.integration.test.ts": 28768,
|
||||
"server/src/__tests__/chat-channels/slack-protocol.integration.test.ts": 8705,
|
||||
|
||||
@@ -0,0 +1,641 @@
|
||||
import { createHash, generateKeyPairSync } from "node:crypto";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { beforeAll, expect, it, vi } from "vitest";
|
||||
import { chatActions, chatEndpoints, chatPublications } from "@paperclipai/db";
|
||||
import type { InternalSetupState } from "../../services/chat-channels/runtime-types.js";
|
||||
import { createDeliveryWorkCoordinator } from "../../services/delivery-work-coordinator.js";
|
||||
import { registerChatDeliveryWork } from "../../services/chat-delivery-work.js";
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
import { HttpError } from "../../errors.js";
|
||||
import { PaperclipCloudConnectorError } from "../../services/paperclip-cloud-connector.js";
|
||||
import { createSlackCloudEnrollment } from "../../services/chat-channels/slack/cloud-enrollment.js";
|
||||
import { createSlackFormPublicationStage } from "../../services/chat-channels/slack/form-publication.js";
|
||||
import {
|
||||
reconcilePendingSlackFormWork,
|
||||
reconcileSlackFormEnrollment,
|
||||
stageSlackFormEnrollment,
|
||||
} from "../../services/chat-channels/slack/form-owner.js";
|
||||
import { parseSlackFormBinding } from "../../services/chat-channels/slack/cloud-forms.js";
|
||||
import { createChatPublicationFailures } from "../../services/chat-channels/publications/failures.js";
|
||||
import { issueThreadInteractionService } from "../../services/issue-thread-interactions.js";
|
||||
import { type TestDb, describeEmbeddedPostgres, makeThread, makeMessage } from "./providers.js";
|
||||
import { createChatChannelHarness } from "./harness.js";
|
||||
|
||||
describeEmbeddedPostgres("chat channels: slack form enrollment wait backoff", () => {
|
||||
const h = createChatChannelHarness();
|
||||
let db!: TestDb;
|
||||
beforeAll(() => { db = h.db; });
|
||||
const {
|
||||
seedCompany,
|
||||
retirePublicationFixture,
|
||||
qualifySetupRoundTrip,
|
||||
configuredSlackEndpoint,
|
||||
deliverMessage,
|
||||
} = h;
|
||||
|
||||
async function seedPendingSlackFormPublication(label: string) {
|
||||
const fixture = await seedCompany();
|
||||
const configured = await configuredSlackEndpoint(fixture);
|
||||
const { callbacks, endpoint, runtime, service } = configured;
|
||||
const rawChannelId = `CFORM${label.replace(/[^A-Za-z0-9]/g, "").toUpperCase()}`;
|
||||
const threadTs = "1788.300";
|
||||
const channel = makeThread({
|
||||
channelId: `slack:${rawChannelId}`,
|
||||
id: `slack:${rawChannelId}:${threadTs}`,
|
||||
name: `form-${label}`,
|
||||
});
|
||||
await deliverMessage({
|
||||
callbacks,
|
||||
endpointId: endpoint.id,
|
||||
thread: channel.thread,
|
||||
message: makeMessage({
|
||||
id: threadTs,
|
||||
text: "@maya ask a question",
|
||||
mentioned: true,
|
||||
}),
|
||||
trigger: "mention",
|
||||
});
|
||||
await qualifySetupRoundTrip(service, endpoint.id);
|
||||
await service.test(endpoint.id);
|
||||
const [conversation] = await service.listConversations(endpoint.id);
|
||||
if (!conversation) throw new Error("Expected Slack form conversation");
|
||||
const [currentEndpoint] = await db
|
||||
.update(chatEndpoints)
|
||||
.set({ providerAccountId: "TPAPERCLIP" })
|
||||
.where(eq(chatEndpoints.id, endpoint.id))
|
||||
.returning();
|
||||
if (!currentEndpoint?.providerAccountId) throw new Error("Expected Slack team id");
|
||||
const currentSetup = currentEndpoint.setup as InternalSetupState;
|
||||
const runtimeGeneration = Number(currentSetup.runtimeGeneration ?? 1);
|
||||
const instanceId = `instance-${label}`;
|
||||
const eventBindingId = `slack-event:${createHash("sha256").update(`event-${label}`).digest("hex")}`;
|
||||
const credentialFingerprint = createHash("sha256").update(`cred-${label}`).digest("hex");
|
||||
const binding = parseSlackFormBinding({
|
||||
version: 1,
|
||||
instanceId,
|
||||
companyId: fixture.companyId,
|
||||
endpointId: endpoint.id,
|
||||
publicId: currentEndpoint.publicId,
|
||||
connectionId: currentEndpoint.connectionId,
|
||||
runtimeGeneration,
|
||||
teamId: currentEndpoint.providerAccountId,
|
||||
appId: "ATEST",
|
||||
eventBindingId,
|
||||
credentialFingerprint,
|
||||
});
|
||||
const { credentialFingerprint: _, eventBindingId: bindingId, ...base } = binding;
|
||||
const enrollment = { ...base, bindingId };
|
||||
const interaction = await issueThreadInteractionService(db).create(
|
||||
{ id: conversation.issueId, companyId: fixture.companyId },
|
||||
{
|
||||
kind: "ask_user_questions",
|
||||
continuationPolicy: "wake_assignee",
|
||||
title: "Form wait test",
|
||||
payload: {
|
||||
version: 1,
|
||||
title: "Form wait test",
|
||||
submitLabel: "Submit",
|
||||
questions: [
|
||||
{
|
||||
id: "env",
|
||||
prompt: "Target?",
|
||||
selectionMode: "single",
|
||||
required: true,
|
||||
allowOther: false,
|
||||
options: [
|
||||
{ id: "staging", label: "Staging" },
|
||||
{ id: "prod", label: "Prod" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "reason",
|
||||
prompt: "Why?",
|
||||
selectionMode: "single",
|
||||
required: true,
|
||||
allowOther: true,
|
||||
options: [{ id: "__paperclip_text__", label: "Type an answer", freeText: true }],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{ agentId: fixture.assignedAgentId },
|
||||
);
|
||||
const [publication] = await db
|
||||
.select()
|
||||
.from(chatPublications)
|
||||
.where(
|
||||
and(
|
||||
eq(chatPublications.endpointId, endpoint.id),
|
||||
eq(chatPublications.conversationId, conversation.id),
|
||||
sql`${chatPublications.payload}->>'interactionId' = ${interaction.id}`,
|
||||
),
|
||||
);
|
||||
if (!publication) throw new Error("Expected queued form publication");
|
||||
return {
|
||||
fixture,
|
||||
configured,
|
||||
endpoint: currentEndpoint,
|
||||
currentSetup,
|
||||
runtime,
|
||||
service,
|
||||
conversation,
|
||||
interaction,
|
||||
publication,
|
||||
instanceId,
|
||||
runtimeGeneration,
|
||||
binding,
|
||||
enrollment,
|
||||
};
|
||||
}
|
||||
|
||||
it("defers Slack form publications to the pending enrollment deadline and floors past deadlines at 2s", async () => {
|
||||
const seeded = await seedPendingSlackFormPublication("backoff");
|
||||
const warnSpy = vi.spyOn(logger, "warn");
|
||||
const debugSpy = vi.spyOn(logger, "debug");
|
||||
try {
|
||||
const readPublication = async () => (await db
|
||||
.select()
|
||||
.from(chatPublications)
|
||||
.where(eq(chatPublications.id, seeded.publication.id)))[0]!;
|
||||
|
||||
for (const offsetMs of [60_000, 300_000]) {
|
||||
const deadlineMs = Date.now() + offsetMs;
|
||||
await db.update(chatEndpoints).set({
|
||||
setup: {
|
||||
...seeded.currentSetup,
|
||||
slackCloudIntent: {
|
||||
version: 1,
|
||||
id: `intent-${offsetMs}`,
|
||||
active: true,
|
||||
subject: "owner-user",
|
||||
instanceId: seeded.instanceId,
|
||||
companyId: seeded.fixture.companyId,
|
||||
endpointId: seeded.endpoint.id,
|
||||
connectionId: seeded.endpoint.connectionId,
|
||||
publicId: seeded.endpoint.publicId,
|
||||
runtimeGeneration: seeded.runtimeGeneration,
|
||||
teamId: seeded.binding.teamId,
|
||||
appId: seeded.binding.appId,
|
||||
attempts: 4,
|
||||
nextAttemptAt: new Date(deadlineMs).toISOString(),
|
||||
},
|
||||
} as InternalSetupState,
|
||||
}).where(eq(chatEndpoints.id, seeded.endpoint.id));
|
||||
await db.update(chatPublications).set({ state: "pending", attempts: 0, nextAttemptAt: null })
|
||||
.where(eq(chatPublications.id, seeded.publication.id));
|
||||
|
||||
expect(await seeded.service.processPendingPublications()).toBe(1);
|
||||
const deferred = await readPublication();
|
||||
expect(deferred.state).toBe("retry");
|
||||
expect(deferred.attempts).toBe(0);
|
||||
expect(deferred.redactedError).toBe("form_publication_enrollment_pending");
|
||||
expect(deferred.nextAttemptAt).not.toBeNull();
|
||||
expect(deferred.nextAttemptAt!.getTime()).toBeGreaterThanOrEqual(deadlineMs - 1_000);
|
||||
expect(deferred.nextAttemptAt!.getTime()).toBeLessThanOrEqual(deadlineMs + 5_000);
|
||||
expect(await seeded.service.nextPublicationAt()).toBe(deferred.nextAttemptAt!.getTime());
|
||||
expect(await seeded.service.processPendingPublications()).toBe(0);
|
||||
}
|
||||
|
||||
const pastOwnerDeadline = Date.now() - 10_000;
|
||||
await db.update(chatEndpoints).set({
|
||||
setup: {
|
||||
...seeded.currentSetup,
|
||||
slackCloudInstanceId: seeded.instanceId,
|
||||
slackCloudSubject: "owner-user",
|
||||
slackCloudEvents: {
|
||||
version: 1,
|
||||
bindingId: seeded.enrollment.bindingId,
|
||||
runtimeGeneration: seeded.runtimeGeneration,
|
||||
teamId: seeded.binding.teamId,
|
||||
appId: seeded.binding.appId,
|
||||
},
|
||||
} as InternalSetupState,
|
||||
}).where(eq(chatEndpoints.id, seeded.endpoint.id));
|
||||
const ownerId = await db.transaction((tx) => stageSlackFormEnrollment(tx, {
|
||||
enrollment: seeded.enrollment,
|
||||
subject: "owner-user",
|
||||
environment: "test",
|
||||
}));
|
||||
await db.update(chatActions).set({
|
||||
result: { phase: "staged", desiredActive: true, nextAttemptAt: new Date(pastOwnerDeadline).toISOString() },
|
||||
}).where(eq(chatActions.id, ownerId));
|
||||
await db.update(chatPublications).set({ state: "pending", attempts: 0, nextAttemptAt: null })
|
||||
.where(eq(chatPublications.id, seeded.publication.id));
|
||||
|
||||
const beforeFloor = Date.now();
|
||||
expect(await seeded.service.processPendingPublications()).toBe(1);
|
||||
const floored = await readPublication();
|
||||
expect(floored.state).toBe("retry");
|
||||
expect(floored.attempts).toBe(0);
|
||||
expect(floored.nextAttemptAt!.getTime()).toBeGreaterThanOrEqual(beforeFloor + 2_000);
|
||||
expect(floored.nextAttemptAt!.getTime()).toBeLessThanOrEqual(beforeFloor + 10_000);
|
||||
expect(seeded.runtime.endpoints.get(seeded.endpoint.id)?.posts ?? []).toHaveLength(0);
|
||||
|
||||
expect(warnSpy.mock.calls.some((args) => args[1] === "chat publication failed")).toBe(false);
|
||||
expect(debugSpy.mock.calls.some((args) => args[1] === "chat publication waiting before send")).toBe(true);
|
||||
} finally {
|
||||
warnSpy.mockRestore();
|
||||
debugSpy.mockRestore();
|
||||
await retirePublicationFixture(seeded.service, seeded.endpoint.id);
|
||||
}
|
||||
});
|
||||
|
||||
it("wakes a 5-minute-deferred Slack form publication immediately when enrollment commits early", async () => {
|
||||
const seeded = await seedPendingSlackFormPublication("early-wake");
|
||||
const coordinator = createDeliveryWorkCoordinator({
|
||||
owner: db,
|
||||
canRun: () => true,
|
||||
onError: (error) => { throw error; },
|
||||
});
|
||||
try {
|
||||
await db.update(chatEndpoints).set({
|
||||
setup: {
|
||||
...seeded.currentSetup,
|
||||
slackCloudInstanceId: seeded.instanceId,
|
||||
slackCloudSubject: "owner-user",
|
||||
slackCloudEvents: {
|
||||
version: 1,
|
||||
bindingId: seeded.enrollment.bindingId,
|
||||
runtimeGeneration: seeded.runtimeGeneration,
|
||||
teamId: seeded.binding.teamId,
|
||||
appId: seeded.binding.appId,
|
||||
},
|
||||
} as InternalSetupState,
|
||||
}).where(eq(chatEndpoints.id, seeded.endpoint.id));
|
||||
const ownerId = await db.transaction((tx) => stageSlackFormEnrollment(tx, {
|
||||
enrollment: seeded.enrollment,
|
||||
subject: "owner-user",
|
||||
environment: "test",
|
||||
}));
|
||||
const fiveMinutesLater = Date.now() + 300_000;
|
||||
await db.update(chatActions).set({
|
||||
result: { phase: "staged", desiredActive: true, nextAttemptAt: new Date(fiveMinutesLater).toISOString() },
|
||||
}).where(eq(chatActions.id, ownerId));
|
||||
|
||||
const delivery = registerChatDeliveryWork(coordinator, seeded.service, () => true);
|
||||
await delivery.ready;
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const [row] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(row?.state).toBe("retry");
|
||||
expect(row?.attempts).toBe(0);
|
||||
expect(row?.nextAttemptAt?.getTime()).toBeGreaterThanOrEqual(fiveMinutesLater - 1_000);
|
||||
const nextWake = coordinator.nextWakeAt();
|
||||
expect(nextWake).not.toBeNull();
|
||||
expect(nextWake!).toBeGreaterThanOrEqual(fiveMinutesLater - 1_000);
|
||||
});
|
||||
expect(seeded.runtime.endpoints.get(seeded.endpoint.id)?.posts ?? []).toHaveLength(0);
|
||||
|
||||
const rateLimitRetryAt = new Date(Date.now() + 180_000);
|
||||
const [rateLimitedPublication] = await db
|
||||
.insert(chatPublications)
|
||||
.values({
|
||||
companyId: seeded.fixture.companyId,
|
||||
endpointId: seeded.endpoint.id,
|
||||
conversationId: seeded.conversation.id,
|
||||
issueId: seeded.conversation.issueId,
|
||||
idempotencyKey: `rate-limit-sibling:${seeded.endpoint.id}`,
|
||||
payload: { text: "Rate limited sibling" },
|
||||
state: "retry",
|
||||
attempts: 1,
|
||||
redactedError: "rate_limited",
|
||||
nextAttemptAt: rateLimitRetryAt,
|
||||
})
|
||||
.returning({ id: chatPublications.id });
|
||||
|
||||
seeded.runtime.endpoints.get(seeded.endpoint.id)!.postResultIds.push("1788.901");
|
||||
await reconcileSlackFormEnrollment(db, {
|
||||
actionId: ownerId,
|
||||
identity: { instanceId: seeded.instanceId, environment: "test" },
|
||||
resolveBotToken: async () => "xoxb-test",
|
||||
protocol: async () => ({ binding: seeded.binding }),
|
||||
});
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const [row] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(row?.state).toBe("published");
|
||||
expect(row?.providerMessageId).toBe("1788.901");
|
||||
});
|
||||
const [untouchedSibling] = await db
|
||||
.select()
|
||||
.from(chatPublications)
|
||||
.where(eq(chatPublications.id, rateLimitedPublication!.id));
|
||||
expect(untouchedSibling?.state).toBe("retry");
|
||||
expect(untouchedSibling?.nextAttemptAt?.getTime()).toBe(rateLimitRetryAt.getTime());
|
||||
const grants = await db
|
||||
.select()
|
||||
.from(chatActions)
|
||||
.where(and(eq(chatActions.endpointId, seeded.endpoint.id), eq(chatActions.kind, "slack_form_grant")));
|
||||
expect(grants).toHaveLength(1);
|
||||
} finally {
|
||||
await coordinator.stop();
|
||||
await retirePublicationFixture(seeded.service, seeded.endpoint.id);
|
||||
}
|
||||
});
|
||||
|
||||
it("wakes a 5-minute-deferred Slack form publication immediately when enrollment transitions to attention", async () => {
|
||||
const seeded = await seedPendingSlackFormPublication("attention-wake");
|
||||
const coordinator = createDeliveryWorkCoordinator({
|
||||
owner: db,
|
||||
canRun: () => true,
|
||||
onError: (error) => { throw error; },
|
||||
});
|
||||
const warnSpy = vi.spyOn(logger, "warn");
|
||||
try {
|
||||
await db.update(chatEndpoints).set({
|
||||
setup: {
|
||||
...seeded.currentSetup,
|
||||
slackCloudInstanceId: seeded.instanceId,
|
||||
slackCloudSubject: "owner-user",
|
||||
slackCloudEvents: {
|
||||
version: 1,
|
||||
bindingId: seeded.enrollment.bindingId,
|
||||
runtimeGeneration: seeded.runtimeGeneration,
|
||||
teamId: seeded.binding.teamId,
|
||||
appId: seeded.binding.appId,
|
||||
},
|
||||
} as InternalSetupState,
|
||||
}).where(eq(chatEndpoints.id, seeded.endpoint.id));
|
||||
const ownerId = await db.transaction((tx) => stageSlackFormEnrollment(tx, {
|
||||
enrollment: seeded.enrollment,
|
||||
subject: "owner-user",
|
||||
environment: "test",
|
||||
}));
|
||||
const fiveMinutesLater = Date.now() + 300_000;
|
||||
await db.update(chatActions).set({
|
||||
result: { phase: "staged", desiredActive: true, nextAttemptAt: new Date(fiveMinutesLater).toISOString() },
|
||||
}).where(eq(chatActions.id, ownerId));
|
||||
|
||||
const delivery = registerChatDeliveryWork(coordinator, seeded.service, () => true);
|
||||
await delivery.ready;
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const [row] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(row?.state).toBe("retry");
|
||||
expect(row?.attempts).toBe(0);
|
||||
expect(row?.nextAttemptAt?.getTime()).toBeGreaterThanOrEqual(fiveMinutesLater - 1_000);
|
||||
});
|
||||
|
||||
await reconcilePendingSlackFormWork(
|
||||
db,
|
||||
{
|
||||
identity: { instanceId: seeded.instanceId, environment: "test" },
|
||||
protocol: async () => { throw new Error("unexpected protocol call"); },
|
||||
resolveBotToken: async () => { throw new HttpError(403, "bot token revoked"); },
|
||||
report: () => {},
|
||||
},
|
||||
new Date(fiveMinutesLater + 1_000),
|
||||
);
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const [row] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(row?.attempts).toBeGreaterThanOrEqual(1);
|
||||
expect(row?.state).toBe("retry");
|
||||
});
|
||||
expect(warnSpy.mock.calls.some((args) => args[1] === "chat publication failed")).toBe(true);
|
||||
|
||||
await coordinator.stop();
|
||||
for (let step = 0; step < 5; step += 1) {
|
||||
const [row] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
if (row?.state === "failed") break;
|
||||
await db.update(chatPublications).set({ nextAttemptAt: new Date(Date.now() - 1_000) })
|
||||
.where(eq(chatPublications.id, seeded.publication.id));
|
||||
await seeded.service.processPendingPublications();
|
||||
}
|
||||
const [settled] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(settled?.state).toBe("failed");
|
||||
expect(settled?.attempts).toBe(5);
|
||||
} finally {
|
||||
warnSpy.mockRestore();
|
||||
await coordinator.stop();
|
||||
await retirePublicationFixture(seeded.service, seeded.endpoint.id);
|
||||
}
|
||||
});
|
||||
|
||||
it("wakes a 5-minute-deferred Slack form publication when slackCloudIntent transitions to attention", async () => {
|
||||
const seeded = await seedPendingSlackFormPublication("intent-attention");
|
||||
const coordinator = createDeliveryWorkCoordinator({
|
||||
owner: db,
|
||||
canRun: () => true,
|
||||
onError: (error) => { throw error; },
|
||||
});
|
||||
const signing = generateKeyPairSync("ed25519").privateKey.export({ format: "jwk" }).d!;
|
||||
const sealing = generateKeyPairSync("x25519").privateKey.export({ format: "jwk" }).d!;
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_BASE_URL", "https://cloud.example.test");
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID", seeded.instanceId);
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT", "test");
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY", signing);
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY", sealing);
|
||||
try {
|
||||
const fiveMinutesLater = Date.now() + 300_000;
|
||||
await db.update(chatEndpoints).set({
|
||||
setup: {
|
||||
...seeded.currentSetup,
|
||||
slackCloudIntent: {
|
||||
version: 1,
|
||||
id: "intent-attention-1",
|
||||
active: true,
|
||||
subject: "owner-user",
|
||||
instanceId: seeded.instanceId,
|
||||
companyId: seeded.fixture.companyId,
|
||||
endpointId: seeded.endpoint.id,
|
||||
connectionId: seeded.endpoint.connectionId,
|
||||
publicId: seeded.endpoint.publicId,
|
||||
runtimeGeneration: seeded.runtimeGeneration,
|
||||
teamId: seeded.binding.teamId,
|
||||
appId: seeded.binding.appId,
|
||||
attempts: 4,
|
||||
nextAttemptAt: new Date(fiveMinutesLater).toISOString(),
|
||||
},
|
||||
} as InternalSetupState,
|
||||
}).where(eq(chatEndpoints.id, seeded.endpoint.id));
|
||||
|
||||
const delivery = registerChatDeliveryWork(coordinator, seeded.service, () => true);
|
||||
await delivery.ready;
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const [row] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(row?.state).toBe("retry");
|
||||
expect(row?.attempts).toBe(0);
|
||||
expect(row?.nextAttemptAt?.getTime()).toBeGreaterThanOrEqual(fiveMinutesLater - 1_000);
|
||||
});
|
||||
|
||||
const enroll = createSlackCloudEnrollment(db, {
|
||||
resolveCredentials: async () => ({ signingSecret: "test-signing-secret" }),
|
||||
runtimeGeneration: (setup) => Number(setup.runtimeGeneration ?? 0),
|
||||
connector: {
|
||||
slackEventsAvailable: async () => true,
|
||||
slackEventEnrollment: async () => {
|
||||
throw new PaperclipCloudConnectorError("denied", "CONNECTOR_REQUEST_FAILED", 403);
|
||||
},
|
||||
},
|
||||
});
|
||||
await enroll(seeded.endpoint.id, "owner-user", { assertOwned: async () => {} });
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const [row] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(row?.attempts).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
await coordinator.stop();
|
||||
await retirePublicationFixture(seeded.service, seeded.endpoint.id);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not strand a publication for 5 minutes when enrollment commits before deferral writes retry", async () => {
|
||||
const seeded = await seedPendingSlackFormPublication("commit-race");
|
||||
try {
|
||||
await db.update(chatEndpoints).set({
|
||||
setup: {
|
||||
...seeded.currentSetup,
|
||||
slackCloudInstanceId: seeded.instanceId,
|
||||
slackCloudSubject: "owner-user",
|
||||
slackCloudEvents: {
|
||||
version: 1,
|
||||
bindingId: seeded.enrollment.bindingId,
|
||||
runtimeGeneration: seeded.runtimeGeneration,
|
||||
teamId: seeded.binding.teamId,
|
||||
appId: seeded.binding.appId,
|
||||
},
|
||||
} as InternalSetupState,
|
||||
}).where(eq(chatEndpoints.id, seeded.endpoint.id));
|
||||
const ownerId = await db.transaction((tx) => stageSlackFormEnrollment(tx, {
|
||||
enrollment: seeded.enrollment,
|
||||
subject: "owner-user",
|
||||
environment: "test",
|
||||
}));
|
||||
const fiveMinutesLater = Date.now() + 300_000;
|
||||
await db.update(chatActions).set({
|
||||
result: { phase: "staged", desiredActive: true, nextAttemptAt: new Date(fiveMinutesLater).toISOString() },
|
||||
}).where(eq(chatActions.id, ownerId));
|
||||
|
||||
const [freshEndpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, seeded.endpoint.id));
|
||||
const stage = createSlackFormPublicationStage(db);
|
||||
const wait = await stage(freshEndpoint!, seeded.publication);
|
||||
expect(wait).toMatchObject({ kind: "wait", reason: "form_publication_enrollment_pending" });
|
||||
if (!wait || typeof wait === "function") throw new Error("Expected wait preparation result");
|
||||
|
||||
await db.update(chatPublications).set({ state: "streaming", attempts: 1 })
|
||||
.where(eq(chatPublications.id, seeded.publication.id));
|
||||
|
||||
await reconcileSlackFormEnrollment(db, {
|
||||
actionId: ownerId,
|
||||
identity: { instanceId: seeded.instanceId, environment: "test" },
|
||||
resolveBotToken: async () => "xoxb-test",
|
||||
protocol: async () => ({ binding: seeded.binding }),
|
||||
});
|
||||
|
||||
class TestFailedChatRetryPublicationReadError extends Error {}
|
||||
const { finalizePublicationFailure } = createChatPublicationFailures(db, {
|
||||
FailedChatRetryPublicationReadError: TestFailedChatRetryPublicationReadError,
|
||||
MAX_ERROR_TEXT: 500,
|
||||
getTaskBaseUrl: () => "https://paperclip.example",
|
||||
invalidateRuntime: async () => false,
|
||||
runtimeCallbackEndpoint: async () => null,
|
||||
});
|
||||
await finalizePublicationFailure(
|
||||
seeded.publication,
|
||||
new Error(wait.reason),
|
||||
false,
|
||||
null,
|
||||
undefined,
|
||||
"not_started",
|
||||
wait,
|
||||
);
|
||||
|
||||
const [afterDeferral] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(afterDeferral?.state).toBe("retry");
|
||||
expect(afterDeferral?.attempts).toBe(0);
|
||||
expect(afterDeferral?.nextAttemptAt).toBeNull();
|
||||
|
||||
seeded.runtime.endpoints.get(seeded.endpoint.id)!.postResultIds.push("1788.902");
|
||||
expect(await seeded.service.processPendingPublications()).toBe(1);
|
||||
const [published] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(published?.state).toBe("published");
|
||||
expect(published?.providerMessageId).toBe("1788.902");
|
||||
} finally {
|
||||
await retirePublicationFixture(seeded.service, seeded.endpoint.id);
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back cleanly without blocking or stranding in streaming when stillWaiting hits row lock contention", async () => {
|
||||
const seeded = await seedPendingSlackFormPublication("lock-fallback");
|
||||
let releaseLock!: () => void;
|
||||
let lockAcquired!: () => void;
|
||||
const holdLock = new Promise<void>((resolve) => { releaseLock = resolve; });
|
||||
const locked = new Promise<void>((resolve) => { lockAcquired = resolve; });
|
||||
let locker: Promise<void> | undefined;
|
||||
try {
|
||||
await db.update(chatEndpoints).set({
|
||||
setup: {
|
||||
...seeded.currentSetup,
|
||||
slackCloudInstanceId: seeded.instanceId,
|
||||
slackCloudSubject: "owner-user",
|
||||
slackCloudEvents: {
|
||||
version: 1,
|
||||
bindingId: seeded.enrollment.bindingId,
|
||||
runtimeGeneration: seeded.runtimeGeneration,
|
||||
teamId: seeded.binding.teamId,
|
||||
appId: seeded.binding.appId,
|
||||
},
|
||||
} as InternalSetupState,
|
||||
}).where(eq(chatEndpoints.id, seeded.endpoint.id));
|
||||
const ownerId = await db.transaction((tx) => stageSlackFormEnrollment(tx, {
|
||||
enrollment: seeded.enrollment,
|
||||
subject: "owner-user",
|
||||
environment: "test",
|
||||
}));
|
||||
const fiveMinutesLater = Date.now() + 300_000;
|
||||
await db.update(chatActions).set({
|
||||
result: { phase: "staged", desiredActive: true, nextAttemptAt: new Date(fiveMinutesLater).toISOString() },
|
||||
}).where(eq(chatActions.id, ownerId));
|
||||
|
||||
const [freshEndpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, seeded.endpoint.id));
|
||||
const wait = await createSlackFormPublicationStage(db)(freshEndpoint!, seeded.publication);
|
||||
expect(wait).toMatchObject({ kind: "wait", reason: "form_publication_enrollment_pending" });
|
||||
if (!wait || typeof wait === "function") throw new Error("Expected wait preparation result");
|
||||
|
||||
await db.update(chatPublications).set({ state: "streaming", attempts: 1 })
|
||||
.where(eq(chatPublications.id, seeded.publication.id));
|
||||
|
||||
locker = db.transaction(async (tx) => {
|
||||
await tx.select({ id: chatActions.id }).from(chatActions).where(eq(chatActions.id, ownerId)).for("update");
|
||||
lockAcquired();
|
||||
await holdLock;
|
||||
});
|
||||
await locked;
|
||||
|
||||
class TestFailedChatRetryPublicationReadError extends Error {}
|
||||
const { finalizePublicationFailure } = createChatPublicationFailures(db, {
|
||||
FailedChatRetryPublicationReadError: TestFailedChatRetryPublicationReadError,
|
||||
MAX_ERROR_TEXT: 500,
|
||||
getTaskBaseUrl: () => "https://paperclip.example",
|
||||
invalidateRuntime: async () => false,
|
||||
runtimeCallbackEndpoint: async () => null,
|
||||
});
|
||||
const beforeFinalize = Date.now();
|
||||
const finalized = await finalizePublicationFailure(
|
||||
seeded.publication,
|
||||
new Error(wait.reason),
|
||||
false,
|
||||
null,
|
||||
undefined,
|
||||
"not_started",
|
||||
wait,
|
||||
);
|
||||
expect(finalized).toBe(true);
|
||||
|
||||
const [afterFinalize] = await db.select().from(chatPublications).where(eq(chatPublications.id, seeded.publication.id));
|
||||
expect(afterFinalize?.state).toBe("retry");
|
||||
expect(afterFinalize?.attempts).toBe(0);
|
||||
expect(afterFinalize?.nextAttemptAt).not.toBeNull();
|
||||
expect(afterFinalize?.nextAttemptAt!.getTime()).toBeGreaterThanOrEqual(beforeFinalize + 1_500);
|
||||
expect(afterFinalize?.nextAttemptAt!.getTime()).toBeLessThanOrEqual(beforeFinalize + 10_000);
|
||||
} finally {
|
||||
releaseLock?.();
|
||||
await locker;
|
||||
await retirePublicationFixture(seeded.service, seeded.endpoint.id);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,11 +2,18 @@ import { isRetryableSlackFormUpdate } from "../services/chat-channels/slack/form
|
||||
import { slackFormConnectorIdentity, selectSlackFormRetainedConsumer } from "../services/chat-channels/slack/cloud-consumer.js";
|
||||
import { createHash, createHmac } from "node:crypto";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { chatActions, chatEndpoints, chatPublications, toolConnections, type Db } from "@paperclipai/db";
|
||||
import { slackFormSubmissionEvidence, withSlackFormSubmissionEvidence, assertSlackFormTerminalAck, lookupSlackFormDelivery, parseSlackFormOperation, type SlackFormBinding, type SlackFormView, type SlackFormOperation } from "../services/chat-channels/slack/cloud-forms.js";
|
||||
|
||||
import { parseSlackFormProofAcceptance, prepareSlackFormProofAcceptance, projectSlackFormRetainedOwner, type SlackFormTerminalIntent, type SlackFormRetainedRow, openSlackFormSubmissionIntent, prepareSlackFormSubmissionIntent } from "../services/chat-channels/slack/form-session.js";
|
||||
import { createSlackFormPublicationStage } from "../services/chat-channels/slack/form-publication.js";
|
||||
import { createLocalEncryptedCipher } from "../secrets/local-encrypted-provider.js";
|
||||
|
||||
const formPublicationInteractions = vi.hoisted(() => ({ rows: [] as unknown[] }));
|
||||
vi.mock("../services/issue-thread-interactions.js", () => ({
|
||||
issueThreadInteractionService: () => ({ listForIssue: async () => formPublicationInteractions.rows }),
|
||||
}));
|
||||
|
||||
afterEach(() => { vi.unstubAllEnvs(); });
|
||||
const hash = (s: string) => createHash("sha256").update(s).digest("hex");
|
||||
function fixture() {
|
||||
@@ -328,3 +335,221 @@ describe("Slack held-view retry boundary", () => {
|
||||
Object.assign(new Error("controlled definite view refusal"), { code: "slack_webapi_platform_error", data: { error } }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Slack form publication enrollment wait backoff", () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
formPublicationInteractions.rows = [];
|
||||
});
|
||||
|
||||
function stageFixture(setup: Record<string, unknown>, owners: unknown[] = []) {
|
||||
const f = fixture();
|
||||
const binding = f.current.binding;
|
||||
const { credentialFingerprint: _, eventBindingId, ...identity } = binding;
|
||||
const enrollment = { ...identity, bindingId: eventBindingId };
|
||||
formPublicationInteractions.rows = [{
|
||||
id: "interaction-1",
|
||||
companyId: binding.companyId,
|
||||
issueId: "issue-1",
|
||||
kind: "ask_user_questions",
|
||||
status: "pending",
|
||||
title: "Question",
|
||||
payload: {
|
||||
version: 1,
|
||||
title: "Question",
|
||||
submitLabel: "Submit",
|
||||
questions: [{
|
||||
id: "q1",
|
||||
prompt: "Choose one",
|
||||
selectionMode: "single",
|
||||
required: true,
|
||||
allowOther: false,
|
||||
options: [{ id: "o1", label: "One" }],
|
||||
}],
|
||||
},
|
||||
}];
|
||||
const endpoint = {
|
||||
id: binding.endpointId,
|
||||
companyId: binding.companyId,
|
||||
connectionId: binding.connectionId,
|
||||
publicId: binding.publicId,
|
||||
provider: "slack",
|
||||
providerAccountId: binding.teamId,
|
||||
status: "active",
|
||||
setup,
|
||||
};
|
||||
const connection = {
|
||||
id: binding.connectionId,
|
||||
companyId: binding.companyId,
|
||||
status: "active",
|
||||
enabled: true,
|
||||
};
|
||||
const publication = {
|
||||
id: "publication-1",
|
||||
companyId: binding.companyId,
|
||||
endpointId: binding.endpointId,
|
||||
conversationId: "conversation-1",
|
||||
issueId: "issue-1",
|
||||
payload: { interactionId: "interaction-1", text: "Question" },
|
||||
} as unknown as typeof chatPublications.$inferSelect;
|
||||
let actionReads = 0;
|
||||
const db = {
|
||||
select: () => {
|
||||
let table: object;
|
||||
const rows = () => {
|
||||
if (table === chatActions) {
|
||||
actionReads += 1;
|
||||
return actionReads === 1 ? [{ id: "open-1" }] : owners;
|
||||
}
|
||||
if (table === chatEndpoints) return [endpoint];
|
||||
if (table === toolConnections) return [connection];
|
||||
return [];
|
||||
};
|
||||
const query = {
|
||||
from: (value: object) => { table = value; return query; },
|
||||
where: () => query,
|
||||
limit: async () => rows(),
|
||||
};
|
||||
return query;
|
||||
},
|
||||
} as unknown as Db;
|
||||
return {
|
||||
binding,
|
||||
enrollment,
|
||||
endpoint: endpoint as unknown as Parameters<ReturnType<typeof createSlackFormPublicationStage>>[0],
|
||||
publication,
|
||||
prepare: createSlackFormPublicationStage(db),
|
||||
};
|
||||
}
|
||||
|
||||
it.each([
|
||||
["60s backoff", 60_000, 60_000],
|
||||
["300s backoff", 300_000, 300_000],
|
||||
["far future capped at 300s", 900_000, 300_000],
|
||||
["past deadline floored at 2s", -10_000, 2_000],
|
||||
["sub-2s deadline floored at 2s", 500, 2_000],
|
||||
] as const)("computes retryAfterMs from slackCloudIntent.nextAttemptAt (%s)", async (_label, offsetMs, expectedMs) => {
|
||||
vi.useFakeTimers();
|
||||
const now = Date.UTC(2099, 0, 1, 0, 0, 0);
|
||||
vi.setSystemTime(now);
|
||||
const f = fixture();
|
||||
const { binding } = f.current;
|
||||
const stage = stageFixture({
|
||||
runtimeGeneration: 1,
|
||||
slackCloudIntent: {
|
||||
version: 1,
|
||||
id: "intent-1",
|
||||
active: true,
|
||||
subject: "actor",
|
||||
instanceId: binding.instanceId,
|
||||
companyId: binding.companyId,
|
||||
endpointId: binding.endpointId,
|
||||
connectionId: binding.connectionId,
|
||||
publicId: binding.publicId,
|
||||
runtimeGeneration: 1,
|
||||
teamId: binding.teamId,
|
||||
appId: binding.appId,
|
||||
attempts: 3,
|
||||
nextAttemptAt: new Date(now + offsetMs).toISOString(),
|
||||
},
|
||||
});
|
||||
await expect(stage.prepare(stage.endpoint, stage.publication)).resolves.toMatchObject({
|
||||
kind: "wait",
|
||||
reason: "form_publication_enrollment_pending",
|
||||
retryAfterMs: expectedMs,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["60s backoff", 60_000, 60_000],
|
||||
["300s backoff", 300_000, 300_000],
|
||||
["far future capped at 300s", 900_000, 300_000],
|
||||
["past deadline floored at 2s", -10_000, 2_000],
|
||||
["sub-2s deadline floored at 2s", 500, 2_000],
|
||||
] as const)("computes retryAfterMs from slack_form_owner.result.nextAttemptAt (%s)", async (_label, offsetMs, expectedMs) => {
|
||||
vi.useFakeTimers();
|
||||
const now = Date.UTC(2099, 0, 1, 0, 0, 0);
|
||||
vi.setSystemTime(now);
|
||||
const f = fixture();
|
||||
const { binding } = f.current;
|
||||
const { credentialFingerprint: _, eventBindingId, ...identity } = binding;
|
||||
const enrollment = { ...identity, bindingId: eventBindingId };
|
||||
const owner = {
|
||||
id: "owner-1",
|
||||
companyId: binding.companyId,
|
||||
endpointId: binding.endpointId,
|
||||
kind: "slack_form_owner",
|
||||
status: "issued",
|
||||
payload: { enrollment, subject: "actor", environment: "test" },
|
||||
result: { phase: "staged", desiredActive: true, nextAttemptAt: new Date(now + offsetMs).toISOString() },
|
||||
};
|
||||
const stage = stageFixture({
|
||||
runtimeGeneration: 1,
|
||||
slackCloudInstanceId: binding.instanceId,
|
||||
slackCloudSubject: "actor",
|
||||
slackCloudEvents: {
|
||||
version: 1,
|
||||
bindingId: eventBindingId,
|
||||
runtimeGeneration: 1,
|
||||
teamId: binding.teamId,
|
||||
appId: binding.appId,
|
||||
},
|
||||
}, [owner]);
|
||||
await expect(stage.prepare(stage.endpoint, stage.publication)).resolves.toMatchObject({
|
||||
kind: "wait",
|
||||
reason: "form_publication_enrollment_pending",
|
||||
retryAfterMs: expectedMs,
|
||||
});
|
||||
});
|
||||
|
||||
it("throws retryable unavailability instead of waiting when enrollment is in attention", async () => {
|
||||
const f = fixture();
|
||||
const { binding } = f.current;
|
||||
const { credentialFingerprint: _, eventBindingId, ...identity } = binding;
|
||||
const enrollment = { ...identity, bindingId: eventBindingId };
|
||||
const attentionIntent = stageFixture({
|
||||
runtimeGeneration: 1,
|
||||
slackCloudIntent: {
|
||||
version: 1,
|
||||
id: "intent-1",
|
||||
active: true,
|
||||
subject: "actor",
|
||||
instanceId: binding.instanceId,
|
||||
companyId: binding.companyId,
|
||||
endpointId: binding.endpointId,
|
||||
connectionId: binding.connectionId,
|
||||
publicId: binding.publicId,
|
||||
runtimeGeneration: 1,
|
||||
teamId: binding.teamId,
|
||||
appId: binding.appId,
|
||||
attempts: 1,
|
||||
nextAttemptAt: null,
|
||||
},
|
||||
});
|
||||
await expect(attentionIntent.prepare(attentionIntent.endpoint, attentionIntent.publication))
|
||||
.rejects.toMatchObject({ code: "form_publication_enrollment_pending", disposition: "retry" });
|
||||
|
||||
const attentionOwner = stageFixture({
|
||||
runtimeGeneration: 1,
|
||||
slackCloudInstanceId: binding.instanceId,
|
||||
slackCloudSubject: "actor",
|
||||
slackCloudEvents: {
|
||||
version: 1,
|
||||
bindingId: eventBindingId,
|
||||
runtimeGeneration: 1,
|
||||
teamId: binding.teamId,
|
||||
appId: binding.appId,
|
||||
},
|
||||
}, [{
|
||||
id: "owner-1",
|
||||
companyId: binding.companyId,
|
||||
endpointId: binding.endpointId,
|
||||
kind: "slack_form_owner",
|
||||
status: "attention",
|
||||
payload: { enrollment, subject: "actor", environment: "test" },
|
||||
result: { phase: "staged", desiredActive: true, nextAttemptAt: null },
|
||||
}]);
|
||||
await expect(attentionOwner.prepare(attentionOwner.endpoint, attentionOwner.publication))
|
||||
.rejects.toMatchObject({ code: "form_publication_enrollment_pending", disposition: "retry" });
|
||||
});
|
||||
});
|
||||
@@ -118,8 +118,40 @@ export function createChatPublicationFailures(db: Db, options: PublicationFailur
|
||||
? runtimeContext
|
||||
: null;
|
||||
let invalidateCurrentRuntime = false;
|
||||
let effectiveWaitRetryMs: number | undefined =
|
||||
waitingBeforeSend && disposition.kind === "retry"
|
||||
? disposition.retryAfterMs
|
||||
: undefined;
|
||||
const finalized = await db.transaction(async (tx) => {
|
||||
await credentialLease?.assertOwned(tx);
|
||||
let waitRetryMs: number | null =
|
||||
disposition.kind === "retry" && !terminalRetry
|
||||
? disposition.retryAfterMs
|
||||
: null;
|
||||
if (waitingBeforeSend && preparationWait?.stillWaiting && waitRetryMs !== null) {
|
||||
const scheduledWaitRetryMs = waitRetryMs;
|
||||
try {
|
||||
const stillWaiting = await tx.transaction((savepoint) =>
|
||||
preparationWait.stillWaiting!(savepoint),
|
||||
);
|
||||
if (!stillWaiting) waitRetryMs = null;
|
||||
} catch (waitCheckError) {
|
||||
logger.debug(
|
||||
{
|
||||
endpointId: publication.endpointId,
|
||||
publicationId: publication.id,
|
||||
error: redactSensitiveText(
|
||||
waitCheckError instanceof Error
|
||||
? waitCheckError.message
|
||||
: String(waitCheckError),
|
||||
).slice(0, MAX_ERROR_TEXT),
|
||||
},
|
||||
"chat publication wait recheck skipped",
|
||||
);
|
||||
waitRetryMs = Math.min(scheduledWaitRetryMs, 2_000);
|
||||
}
|
||||
}
|
||||
effectiveWaitRetryMs = waitRetryMs ?? 0;
|
||||
const state =
|
||||
disposition.kind === "retry" && !terminalRetry
|
||||
? "retry"
|
||||
@@ -136,9 +168,7 @@ export function createChatPublicationFailures(db: Db, options: PublicationFailur
|
||||
state,
|
||||
...(waitingBeforeSend ? { attempts: publication.attempts } : {}),
|
||||
nextAttemptAt:
|
||||
disposition.kind === "retry" && !terminalRetry
|
||||
? new Date(Date.now() + disposition.retryAfterMs)
|
||||
: null,
|
||||
waitRetryMs !== null ? new Date(Date.now() + waitRetryMs) : null,
|
||||
redactedError: failure,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
@@ -324,22 +354,34 @@ export function createChatPublicationFailures(db: Db, options: PublicationFailur
|
||||
await invalidateRuntime(publication.endpointId).catch(() => undefined);
|
||||
}
|
||||
if (finalized) {
|
||||
logger.warn(
|
||||
{
|
||||
endpointId: publication.endpointId,
|
||||
publicationId: publication.id,
|
||||
error: failure,
|
||||
disposition: disposition.kind,
|
||||
...(providerAccepted
|
||||
? {
|
||||
cause: redactSensitiveText(
|
||||
error instanceof Error ? error.message : String(error),
|
||||
).slice(0, MAX_ERROR_TEXT),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
"chat publication failed",
|
||||
);
|
||||
if (waitingBeforeSend) {
|
||||
logger.debug(
|
||||
{
|
||||
endpointId: publication.endpointId,
|
||||
publicationId: publication.id,
|
||||
reason: failure,
|
||||
retryAfterMs: effectiveWaitRetryMs,
|
||||
},
|
||||
"chat publication waiting before send",
|
||||
);
|
||||
} else {
|
||||
logger.warn(
|
||||
{
|
||||
endpointId: publication.endpointId,
|
||||
publicationId: publication.id,
|
||||
error: failure,
|
||||
disposition: disposition.kind,
|
||||
...(providerAccepted
|
||||
? {
|
||||
cause: redactSensitiveText(
|
||||
error instanceof Error ? error.message : String(error),
|
||||
).slice(0, MAX_ERROR_TEXT),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
"chat publication failed",
|
||||
);
|
||||
}
|
||||
}
|
||||
return finalized;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from "drizzle-orm";
|
||||
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import type { DbTransaction } from "../runtime-types.js";
|
||||
|
||||
import {
|
||||
chatEndpoints,
|
||||
@@ -29,6 +30,7 @@ export type ChatPublicationPreparationWait = Readonly<{
|
||||
kind: "wait";
|
||||
reason: string;
|
||||
retryAfterMs: number;
|
||||
stillWaiting?: (tx: DbTransaction) => Promise<boolean>;
|
||||
}>;
|
||||
|
||||
type PublicationPreparationOptions = {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { HttpError } from "../../../errors.js";
|
||||
import { generateKeyPairSync } from "node:crypto";
|
||||
import { chatEndpoints, chatSlackRegistrations, type Db } from "@paperclipai/db";
|
||||
import { chatEndpoints, chatPublications, chatSlackRegistrations, type Db } from "@paperclipai/db";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { PaperclipCloudConnectorError } from "../../paperclip-cloud-connector.js";
|
||||
import { createSlackCloudEnrollment, stageSlackCloudEnrollmentIntent } from "./cloud-enrollment.js";
|
||||
@@ -212,3 +212,18 @@ it("removal after an unconfirmed replacement targets its pending instance withou
|
||||
expect(f.endpoint.setup.slackCloudInstanceId).toBe("replacement");
|
||||
expect(f.endpoint.setup.slackCloudRetiredGeneration).toBe(4);
|
||||
});
|
||||
|
||||
it("wakes waiting form publications on attention and retirement transitions without waking on transient retry", async () => {
|
||||
const f = fixture();
|
||||
await f.stage();
|
||||
f.update.mockClear();
|
||||
|
||||
f.connector.slackEventsAvailable.mockRejectedValueOnce(new PaperclipCloudConnectorError("offline", "CONNECTOR_UNAVAILABLE"));
|
||||
await f.run(f.endpoint.id, undefined, f.lease);
|
||||
expect(f.update.mock.calls.some(([table]) => table === chatPublications)).toBe(false);
|
||||
|
||||
f.update.mockClear();
|
||||
f.connector.slackEventEnrollment.mockRejectedValueOnce(new PaperclipCloudConnectorError("denied", "CONNECTOR_REQUEST_FAILED", 403));
|
||||
await f.run(f.endpoint.id, undefined, f.lease);
|
||||
expect(f.update.mock.calls.some(([table]) => table === chatPublications)).toBe(true);
|
||||
});
|
||||
@@ -6,11 +6,13 @@ import type { CredentialMutationLeaseGuard } from "../../chat-credential-mutatio
|
||||
import type { createChatCredentials } from "../credentials.js";
|
||||
import type { InternalSetupState } from "../runtime-types.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js";
|
||||
import { notifyChatPublicationWork } from "../../chat-work-notifications.js";
|
||||
import { logger } from "../../../middleware/logger.js";
|
||||
import { HttpError } from "../../../errors.js";
|
||||
|
||||
import { resolveSlackCloudSigningSecret } from "./cloud-signing-secret.js";
|
||||
import { SlackCloudReceiptError } from "./cloud-event.js";
|
||||
import { clearWaitingSlackFormPublicationDeadlines } from "./form-owner.js";
|
||||
|
||||
type Intent = NonNullable<InternalSetupState["slackCloudIntent"]>;
|
||||
class SlackEnrollmentFailure extends Error {
|
||||
@@ -63,11 +65,14 @@ export async function stageSlackCloudEnrollmentIntent(db: Db, endpointId: string
|
||||
publicId: endpoint.publicId, connectionId: endpoint.connectionId, runtimeGeneration: generation, active,
|
||||
...(active ? { appId: appId!, teamId: endpoint.providerAccountId! } : {}), attempts: 0, nextAttemptAt: config && !blocked ? new Date().toISOString() : null,
|
||||
...(blocked ? { failureCode: "instance_replacement_requires_retirement" } : !config ? { failureCode: "connector_configuration_unavailable" } : {}) };
|
||||
const wakePublications = !active || !config || blocked;
|
||||
await notifyDeliveryWork(db, DELIVERY_QUEUES.connectionEvents);
|
||||
if (wakePublications) await notifyChatPublicationWork(db);
|
||||
await db.update(chatEndpoints).set({
|
||||
lastError: config && !blocked ? sql`${chatEndpoints.lastError}` : "Slack Cloud event registration requires attention",
|
||||
setup: sql`jsonb_set(${chatEndpoints.setup}, '{slackCloudIntent}', ${JSON.stringify(intent)}::jsonb)` })
|
||||
.where(and(eq(chatEndpoints.id, endpointId), eq(chatEndpoints.companyId, endpoint.companyId)));
|
||||
if (wakePublications) await clearWaitingSlackFormPublicationDeadlines(db, { companyId: endpoint.companyId, id: endpointId });
|
||||
}
|
||||
|
||||
export async function reconcilePendingSlackCloudEnrollments(db: Db, now: Date): Promise<number | null> {
|
||||
@@ -163,10 +168,12 @@ export function createSlackCloudEnrollment(db: Db, options: {
|
||||
await db.transaction(async tx => {
|
||||
await lease.assertOwned(tx);
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.connectionEvents);
|
||||
await tx.update(chatEndpoints).set({
|
||||
await notifyChatPublicationWork(tx);
|
||||
const updated = await tx.update(chatEndpoints).set({
|
||||
setup: sql`jsonb_set(${chatEndpoints.setup}, '{slackCloudIntent}', ${JSON.stringify({ ...intent, nextAttemptAt: null, failureCode: "intent_authority_changed" })}::jsonb)`,
|
||||
lastError: "Slack Cloud event registration requires attention",
|
||||
}).where(and(eq(chatEndpoints.id, endpoint.id), eq(chatEndpoints.companyId, endpoint.companyId), sql`${chatEndpoints.setup}->'slackCloudIntent'->>'id'=${intent.id}`));
|
||||
}).where(and(eq(chatEndpoints.id, endpoint.id), eq(chatEndpoints.companyId, endpoint.companyId), sql`${chatEndpoints.setup}->'slackCloudIntent'->>'id'=${intent.id}`)).returning({ id: chatEndpoints.id });
|
||||
if (updated.length === 1) await clearWaitingSlackFormPublicationDeadlines(tx, { companyId: endpoint.companyId, id: endpoint.id });
|
||||
await lease.assertOwned(tx);
|
||||
});
|
||||
logger.warn({ endpointId, reason: "intent_authority_changed" }, "Slack enrollment responsibility retained");
|
||||
@@ -179,7 +186,9 @@ export function createSlackCloudEnrollment(db: Db, options: {
|
||||
nextAttemptAt: change.attention ? null : new Date(Math.max(Date.now() + Math.min(300_000, 5_000 * 2 ** Math.min(intent.attempts, 6)), change.retryAt ?? 0)).toISOString() } : null;
|
||||
const field = intent.active ? "slackCloudEvents" : "slackCloudRetiredGeneration";
|
||||
const enrolled = intent.active ? { version: 1, bindingId: change.receipt?.bindingId, runtimeGeneration: intent.runtimeGeneration, teamId: intent.teamId, appId: intent.appId } : intent.runtimeGeneration;
|
||||
const wakePublications = Boolean(change.attention || (change.receipt && (!intent.active || !options.onCommitted)));
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.connectionEvents);
|
||||
if (wakePublications) await notifyChatPublicationWork(tx);
|
||||
const updated = await tx.update(chatEndpoints).set({
|
||||
lastError: change.attention ? "Slack Cloud event registration requires attention" : change.receipt
|
||||
? sql`case when ${chatEndpoints.lastError} = 'Slack Cloud event registration requires attention' then null else ${chatEndpoints.lastError} end` : sql`${chatEndpoints.lastError}`,
|
||||
@@ -191,6 +200,7 @@ export function createSlackCloudEnrollment(db: Db, options: {
|
||||
sql`coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::integer,0)=${intent.runtimeGeneration}`)).returning({ id: chatEndpoints.id });
|
||||
if (updated.length !== 1) throw new Error("Slack configuration changed before event enrollment committed");
|
||||
if (change.receipt) await options.onCommitted?.(tx, { endpointId, active: intent.active, subject: intent.subject, instanceId: intent.instanceId, environment: config.environment });
|
||||
if (wakePublications) await clearWaitingSlackFormPublicationDeadlines(tx, { companyId: endpoint.companyId, id: endpointId });
|
||||
await lease.assertOwned(tx);
|
||||
});
|
||||
try {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { reconcileSlackFormNormalAck } from "./form-ack-work.js";
|
||||
import { HttpError } from "../../../errors.js";
|
||||
import { createPaperclipCloudConnector, paperclipCloudConnectorConfigFromEnv, PaperclipCloudConnectorError } from "../../paperclip-cloud-connector.js";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, isNotNull, sql } from "drizzle-orm";
|
||||
import { chatActions, chatEndpoints, chatPublications, issueThreadInteractions, toolConnections, type Db } from "@paperclipai/db";
|
||||
import { notifyDeliveryWork, DELIVERY_QUEUES } from "../../delivery-work-notifications.js";
|
||||
import { resolveChatQuestionFormOpen, type ResolvedChatQuestionFormOpen } from "../../chat-question-forms.js";
|
||||
@@ -17,6 +17,24 @@ import { slackFormSetupRecord, parseSlackFormBinding, parseSlackFormPublicEnroll
|
||||
import { slackFormConnectorIdentity, type SlackFormConnectorIdentity } from "./cloud-consumer.js";
|
||||
|
||||
type Tx = Pick<Db, "select" | "insert" | "update">;
|
||||
export const SLACK_FORM_ENROLLMENT_PENDING_REASON = "form_publication_enrollment_pending";
|
||||
export async function clearWaitingSlackFormPublicationDeadlines(
|
||||
tx: Pick<Db, "update">,
|
||||
endpoint: { companyId: string; id: string },
|
||||
): Promise<void> {
|
||||
await tx
|
||||
.update(chatPublications)
|
||||
.set({ nextAttemptAt: null, updatedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(chatPublications.companyId, endpoint.companyId),
|
||||
eq(chatPublications.endpointId, endpoint.id),
|
||||
eq(chatPublications.state, "retry"),
|
||||
eq(chatPublications.redactedError, SLACK_FORM_ENROLLMENT_PENDING_REASON),
|
||||
isNotNull(chatPublications.nextAttemptAt),
|
||||
),
|
||||
);
|
||||
}
|
||||
export type SlackFormProtocol = (input: { subject: string; companyId: string; operation: Record<string, unknown> }) => Promise<unknown>;
|
||||
function attention(code: string): never { throw new SlackCloudReceiptError(code, "attention"); }
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
@@ -53,6 +71,10 @@ export async function stageSlackFormEnrollment(tx: Tx, input: { enrollment: Slac
|
||||
const payload = { enrollment, subject: input.subject, environment: input.environment };
|
||||
if (existing) {
|
||||
if (existing.kind !== "slack_form_owner" || !Object.keys(payload).every(key => isDeepStrictEqual(existing.payload[key], Reflect.get(payload, key)))) return attention("form_owner_custody_changed");
|
||||
if (existing.result?.phase === "enrolled") {
|
||||
await notifyChatPublicationWork(tx);
|
||||
await clearWaitingSlackFormPublicationDeadlines(tx, { companyId: endpoint.companyId, id: endpoint.id });
|
||||
}
|
||||
return existing.id;
|
||||
}
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.connectionEvents);
|
||||
@@ -96,11 +118,12 @@ export async function reconcileSlackFormEnrollment(db: Db, input: { actionId: st
|
||||
const currentLive = intent.result?.desiredActive !== false && current && ["active", "verifying", "attention"].includes(current.status) && currentSetup?.runtimeGeneration === enrollment.runtimeGeneration
|
||||
&& currentSetup?.slackCloudInstanceId === enrollment.instanceId && currentSetup?.slackCloudSubject === subject && isDeepStrictEqual(projectSlackFormPublicEnrollment(current), enrollment);
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.connectionEvents);
|
||||
await notifyChatPublicationWork(tx);
|
||||
await tx.update(chatActions).set({ payload: { ...intent.payload, binding }, result: { phase: currentLive ? "enrolled" : "retired_cleanup", nextAttemptAt: currentLive ? null : new Date().toISOString() }, updatedAt: new Date() }).where(eq(chatActions.id, intent.id));
|
||||
if (currentLive) {
|
||||
await tx.update(chatEndpoints).set({ setup: sql`jsonb_set(${chatEndpoints.setup}, '{slackCloudForms}', ${JSON.stringify(binding)}::jsonb)` }).where(and(eq(chatEndpoints.id, current.id), eq(chatEndpoints.companyId, current.companyId)));
|
||||
await notifyChatPublicationWork(tx);
|
||||
}
|
||||
await clearWaitingSlackFormPublicationDeadlines(tx, { companyId: row.companyId, id: row.endpointId });
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -173,6 +196,7 @@ export async function stageSlackFormOwnerConfiguration(tx: Tx, endpointId: strin
|
||||
const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, endpoint.connectionId), eq(toolConnections.companyId, endpoint.companyId))).limit(1);
|
||||
const rows = await tx.select().from(chatActions).where(and(eq(chatActions.companyId, endpoint.companyId), eq(chatActions.endpointId, endpoint.id),
|
||||
eq(chatActions.kind, "slack_form_owner"))).for("update");
|
||||
let deactivated = false;
|
||||
for (const row of rows) {
|
||||
const enrollment = parseSlackFormPublicEnrollment(row.payload.enrollment);
|
||||
if (enrollment.instanceId !== identity.instanceId || row.payload.environment !== identity.environment || typeof row.payload.subject !== "string"
|
||||
@@ -181,10 +205,17 @@ export async function stageSlackFormOwnerConfiguration(tx: Tx, endpointId: strin
|
||||
&& enrollment.runtimeGeneration === setup.runtimeGeneration && setup.slackCloudRetiredGeneration !== enrollment.runtimeGeneration
|
||||
&& isDeepStrictEqual(projectSlackFormPublicEnrollment(endpoint), enrollment)) continue;
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.connectionEvents);
|
||||
if (!deactivated) {
|
||||
await notifyChatPublicationWork(tx);
|
||||
deactivated = true;
|
||||
}
|
||||
await tx.update(chatActions).set({ status: "issued", result: { ...row.result, desiredActive: false,
|
||||
phase: row.payload.binding ? "retired_cleanup" : "staged", nextAttemptAt: new Date().toISOString() }, updatedAt: new Date() })
|
||||
.where(and(eq(chatActions.id, row.id), eq(chatActions.companyId, row.companyId)));
|
||||
}
|
||||
if (deactivated) {
|
||||
await clearWaitingSlackFormPublicationDeadlines(tx, { companyId: endpoint.companyId, id: endpoint.id });
|
||||
}
|
||||
}
|
||||
export async function reconcilePendingSlackFormWork(db: Db, input: { identity: SlackFormConnectorIdentity | null; protocol: SlackFormProtocol;
|
||||
resolveBotToken(endpointId: string): Promise<string>; connector?(): unknown; report(code: string, actionId: string): void }, now = new Date()): Promise<number | null> {
|
||||
@@ -215,10 +246,13 @@ export async function reconcilePendingSlackFormWork(db: Db, input: { identity: S
|
||||
const [current] = await tx.select().from(chatActions).where(and(eq(chatActions.id, row.id), eq(chatActions.companyId, row.companyId))).for("update");
|
||||
if (!current || !isDeepStrictEqual(current, failureSnapshot)) return;
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.connectionEvents);
|
||||
const wakePublications = row.kind === "slack_form_owner" && permanent;
|
||||
if (wakePublications) await notifyChatPublicationWork(tx);
|
||||
const attempts = typeof current.result?.attempts === "number" ? Math.min(current.result.attempts + 1, 1000000) : 1;
|
||||
await tx.update(chatActions).set({ status: permanent ? "attention" : current.status, result: { ...current.result, attempts, failureCode: code,
|
||||
failureReason: error instanceof PaperclipCloudConnectorError ? error.brokerReason ?? null : null,
|
||||
nextAttemptAt: permanent ? null : new Date(Date.now() + Math.min(300000, 5000 * 2 ** Math.min(attempts - 1, 6))).toISOString() }, updatedAt: new Date() }).where(eq(chatActions.id, current.id));
|
||||
if (wakePublications) await clearWaitingSlackFormPublicationDeadlines(tx, { companyId: current.companyId, id: current.endpointId });
|
||||
});
|
||||
} catch (writeError) { throw new AggregateError([error, writeError], "Slack form owner failure and durable retry failure"); }
|
||||
input.report(code, row.id);
|
||||
|
||||
@@ -7,9 +7,15 @@ import { SlackCloudReceiptError } from "./cloud-event.js";
|
||||
import { parseSlackFormBinding, slackFormSetupRecord } from "./cloud-forms.js";
|
||||
import { issueThreadInteractionService } from "../../issue-thread-interactions.js";
|
||||
import type { EndpointRow } from "../runtime-types.js";
|
||||
import { projectSlackFormPublicEnrollment, stageSlackFormPublication } from "./form-owner.js";
|
||||
import {
|
||||
SLACK_FORM_ENROLLMENT_PENDING_REASON,
|
||||
projectSlackFormPublicEnrollment,
|
||||
stageSlackFormPublication,
|
||||
} from "./form-owner.js";
|
||||
|
||||
type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
const MIN_ENROLLMENT_WAIT_MS = 2_000;
|
||||
const MAX_ENROLLMENT_WAIT_MS = 300_000;
|
||||
function object(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? slackFormSetupRecord(value) : null;
|
||||
}
|
||||
@@ -17,17 +23,61 @@ function managedFormsExpected(setup: Record<string, unknown>): boolean {
|
||||
return setup.slackCloudIntent !== undefined || setup.slackCloudForms !== undefined
|
||||
|| setup.slackCloudEvents !== undefined || typeof setup.slackCloudInstanceId === "string";
|
||||
}
|
||||
function scheduled(value: unknown): boolean {
|
||||
return typeof value === "string" && Number.isFinite(Date.parse(value));
|
||||
function scheduledDeadline(value: unknown): number | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
function unavailable(): never {
|
||||
// Inconsistent, stopped and attention custody retains the ordinary failure
|
||||
// policy and authorized Retry path; only an actual scheduled owner can wait.
|
||||
throw new SlackCloudReceiptError("form_publication_enrollment_pending", "retry");
|
||||
throw new SlackCloudReceiptError(SLACK_FORM_ENROLLMENT_PENDING_REASON, "retry");
|
||||
}
|
||||
function enrollmentWaitFor(
|
||||
deadlineMs: number,
|
||||
stillWaiting: (tx: Tx) => Promise<boolean>,
|
||||
): ChatPublicationPreparationWait {
|
||||
return {
|
||||
kind: "wait",
|
||||
reason: SLACK_FORM_ENROLLMENT_PENDING_REASON,
|
||||
retryAfterMs: Math.min(MAX_ENROLLMENT_WAIT_MS, Math.max(MIN_ENROLLMENT_WAIT_MS, deadlineMs - Date.now())),
|
||||
stillWaiting,
|
||||
};
|
||||
}
|
||||
function pendingIntentDeadline(
|
||||
endpoint: Pick<EndpointRow, "companyId" | "id" | "publicId" | "connectionId" | "providerAccountId" | "status" | "setup">,
|
||||
generation: number,
|
||||
expectedIntentId?: string,
|
||||
): number | null {
|
||||
if (!["active", "verifying"].includes(endpoint.status)) return null;
|
||||
const setup = slackFormSetupRecord(endpoint.setup);
|
||||
if (setup.runtimeGeneration !== generation) return null;
|
||||
const intent = object(setup.slackCloudIntent);
|
||||
if (!intent) return null;
|
||||
const deadline = scheduledDeadline(intent.nextAttemptAt);
|
||||
if (intent.version !== 1 || typeof intent.id !== "string" || !intent.id
|
||||
|| (expectedIntentId !== undefined && intent.id !== expectedIntentId)
|
||||
|| intent.active !== true
|
||||
|| intent.companyId !== endpoint.companyId || intent.endpointId !== endpoint.id || intent.publicId !== endpoint.publicId
|
||||
|| intent.connectionId !== endpoint.connectionId || intent.runtimeGeneration !== generation || !/^[A-Za-z0-9_-]{43}$/.test(endpoint.publicId)
|
||||
|| typeof intent.instanceId !== "string" || !intent.instanceId || typeof intent.subject !== "string" || !intent.subject
|
||||
|| typeof intent.teamId !== "string" || !/^T[A-Z0-9]+$/.test(intent.teamId) || intent.teamId !== endpoint.providerAccountId
|
||||
|| typeof intent.appId !== "string" || !/^A[A-Z0-9]+$/.test(intent.appId)
|
||||
|| deadline === null) return null;
|
||||
return deadline;
|
||||
}
|
||||
function pendingOwnerDeadline(
|
||||
owner: Pick<typeof chatActions.$inferSelect, "status" | "payload" | "result"> | undefined,
|
||||
subject: string,
|
||||
mayWait: boolean,
|
||||
): number | null {
|
||||
if (!mayWait || !owner || owner.status !== "issued" || owner.result?.desiredActive === false
|
||||
|| owner.payload.subject !== subject
|
||||
|| typeof owner.payload.environment !== "string"
|
||||
|| !["development", "test", "staging", "production"].includes(owner.payload.environment)
|
||||
|| owner.result?.phase !== "staged" || owner.payload.binding !== undefined) return null;
|
||||
return scheduledDeadline(owner.result.nextAttemptAt);
|
||||
}
|
||||
const enrollmentWait: ChatPublicationPreparationWait = {
|
||||
kind: "wait", reason: "form_publication_enrollment_pending", retryAfterMs: 2_000,
|
||||
};
|
||||
export function createSlackFormPublicationStage(db: Db) {
|
||||
return async (endpoint: EndpointRow, publication: typeof chatPublications.$inferSelect): Promise<((tx: Tx) => Promise<void>) | ChatPublicationPreparationWait | null> => {
|
||||
if (endpoint.provider !== "slack" || !managedFormsExpected(slackFormSetupRecord(endpoint.setup)) || !publication.issueId
|
||||
@@ -54,25 +104,47 @@ export function createSlackFormPublicationStage(db: Db) {
|
||||
if (intent) {
|
||||
// This is the initial events-enrollment responsibility, before onCommitted
|
||||
// can atomically stage the forms owner. A null deadline means attention.
|
||||
if (!mayWait || intent.version !== 1 || typeof intent.id !== "string" || !intent.id || intent.active !== true
|
||||
|| intent.companyId !== current.companyId || intent.endpointId !== current.id || intent.publicId !== current.publicId
|
||||
|| intent.connectionId !== current.connectionId || intent.runtimeGeneration !== generation || !/^[A-Za-z0-9_-]{43}$/.test(current.publicId)
|
||||
|| typeof intent.instanceId !== "string" || !intent.instanceId || typeof intent.subject !== "string" || !intent.subject
|
||||
|| typeof intent.teamId !== "string" || !/^T[A-Z0-9]+$/.test(intent.teamId) || intent.teamId !== current.providerAccountId
|
||||
|| typeof intent.appId !== "string" || !/^A[A-Z0-9]+$/.test(intent.appId)
|
||||
|| !scheduled(intent.nextAttemptAt)) return unavailable();
|
||||
return enrollmentWait;
|
||||
const intentDeadline = pendingIntentDeadline(current, Number(generation));
|
||||
if (intentDeadline === null || typeof intent.id !== "string") return unavailable();
|
||||
const intentId = intent.id;
|
||||
return enrollmentWaitFor(intentDeadline, async tx => {
|
||||
const [latest] = await tx
|
||||
.select({
|
||||
companyId: chatEndpoints.companyId,
|
||||
id: chatEndpoints.id,
|
||||
publicId: chatEndpoints.publicId,
|
||||
connectionId: chatEndpoints.connectionId,
|
||||
providerAccountId: chatEndpoints.providerAccountId,
|
||||
status: chatEndpoints.status,
|
||||
setup: chatEndpoints.setup,
|
||||
})
|
||||
.from(chatEndpoints)
|
||||
.where(and(eq(chatEndpoints.id, current.id), eq(chatEndpoints.companyId, current.companyId)))
|
||||
.for("share", { noWait: true });
|
||||
return Boolean(latest && pendingIntentDeadline(latest, Number(generation), intentId) !== null);
|
||||
});
|
||||
}
|
||||
const enrollment = projectSlackFormPublicEnrollment(current);
|
||||
if (!enrollment || enrollment.runtimeGeneration !== generation || enrollment.instanceId !== setup.slackCloudInstanceId
|
||||
|| typeof setup.slackCloudSubject !== "string" || !setup.slackCloudSubject) return unavailable();
|
||||
const subject = setup.slackCloudSubject;
|
||||
const owners = await db.select().from(chatActions).where(and(eq(chatActions.companyId, current.companyId), eq(chatActions.endpointId, current.id),
|
||||
eq(chatActions.kind, "slack_form_owner"), sql`${chatActions.payload}->'enrollment' = ${JSON.stringify(enrollment)}::jsonb`)).limit(2);
|
||||
if (owners.length !== 1) return unavailable();
|
||||
const [owner] = owners;
|
||||
if (!owner || owner.status !== "issued" || owner.result?.desiredActive === false || owner.payload.subject !== setup.slackCloudSubject
|
||||
if (!owner || owner.status !== "issued" || owner.result?.desiredActive === false || owner.payload.subject !== subject
|
||||
|| typeof owner.payload.environment !== "string" || !["development", "test", "staging", "production"].includes(owner.payload.environment)) return unavailable();
|
||||
if (mayWait && owner.result?.phase === "staged" && owner.payload.binding === undefined && scheduled(owner.result.nextAttemptAt)) return enrollmentWait;
|
||||
const ownerDeadline = pendingOwnerDeadline(owner, subject, mayWait);
|
||||
if (ownerDeadline !== null) {
|
||||
return enrollmentWaitFor(ownerDeadline, async tx => {
|
||||
const [latest] = await tx
|
||||
.select({ status: chatActions.status, payload: chatActions.payload, result: chatActions.result })
|
||||
.from(chatActions)
|
||||
.where(and(eq(chatActions.id, owner.id), eq(chatActions.companyId, current.companyId)))
|
||||
.for("share", { noWait: true });
|
||||
return pendingOwnerDeadline(latest, subject, true) !== null;
|
||||
});
|
||||
}
|
||||
if (owner.result?.phase !== "enrolled" || !binding || !isDeepStrictEqual(owner.payload.binding, binding)
|
||||
|| !isDeepStrictEqual({ version: binding.version, instanceId: binding.instanceId, companyId: binding.companyId, endpointId: binding.endpointId,
|
||||
publicId: binding.publicId, connectionId: binding.connectionId, runtimeGeneration: binding.runtimeGeneration,
|
||||
|
||||
Reference in new issue
Block a user