⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(admin): contain webhook failures and use database lease time
Tin39a91f28c60b
diff --git a/apps/api/src/admin/webhooks/claim-webhook-delivery.ts b/apps/api/src/admin/webhooks/claim-webhook-delivery.tsindex f320df9a6..fcb7cdcb4 100644--- a/apps/api/src/admin/webhooks/claim-webhook-delivery.ts+++ b/apps/api/src/admin/webhooks/claim-webhook-delivery.ts@@ -9,7 +9,6 @@ export const MAX_WEBHOOK_ATTEMPTS = 3;export async function claimWebhookDelivery() {const delivery = schema.instanceWebhookDeliveryTable;const webhook = schema.instanceWebhookTable;- const now = new Date();// A process may have stopped during its final attempt.const interrupted = await db.update(delivery)@@ -55,7 +54,10 @@ export async function claimWebhookDelivery() {const attempts = job.delivery.attempts + 1;await tx.update(delivery)- .set({ attempts, nextAttemptAt: new Date(now.getTime() + 60_000) })+ .set({+ attempts,+ nextAttemptAt: sql`(clock_timestamp() AT TIME ZONE 'utc') + interval '1 minute'`,+ }).where(eq(delivery.id, job.delivery.id));return { ...job, delivery: { ...job.delivery, attempts } };});diff --git a/apps/api/src/admin/webhooks/send-webhook-delivery.ts b/apps/api/src/admin/webhooks/send-webhook-delivery.tsindex a000ffc9e..b4bc6572e 100644--- a/apps/api/src/admin/webhooks/send-webhook-delivery.ts+++ b/apps/api/src/admin/webhooks/send-webhook-delivery.ts@@ -1,5 +1,5 @@import { createHmac } from "node:crypto";-import { and, eq } from "drizzle-orm";+import { and, eq, sql } from "drizzle-orm";import db, { schema } from "../../database";import { decryptSecret } from "../../notification-preferences/secrets";import {@@ -61,9 +61,7 @@ export async function sendWebhookDelivery() {state: retry ? "pending" : errorCode ? "failed" : "succeeded",statusCode,errorCode,- nextAttemptAt: new Date(- Date.now() + (delivery.attempts === 1 ? 5_000 : 30_000),- ),+ nextAttemptAt: sql`(clock_timestamp() AT TIME ZONE 'utc') + ${delivery.attempts === 1 ? 5 : 30} * interval '1 second'`,}).where(and(diff --git a/apps/api/src/admin/webhooks/start-webhook-worker.test.ts b/apps/api/src/admin/webhooks/start-webhook-worker.test.tsnew file mode 100644index 000000000..fd5253873--- /dev/null+++ b/apps/api/src/admin/webhooks/start-webhook-worker.test.ts@@ -0,0 +1,34 @@+import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import { sendWebhookDelivery } from "./send-webhook-delivery";+import { startWebhookWorker } from "./start-webhook-worker";++vi.mock("./send-webhook-delivery", () => ({ sendWebhookDelivery: vi.fn() }));++afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+});++describe("startWebhookWorker", () => {+ it("contains job failures without leaking their details and keeps processing", async () => {+ vi.useFakeTimers();+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ vi.mocked(sendWebhookDelivery)+ .mockResolvedValue(false)+ .mockRejectedValueOnce(new Error("sensitive database parameters"));+ const stop = startWebhookWorker();+ try {+ await vi.advanceTimersByTimeAsync(0);+ expect(log).toHaveBeenCalledExactlyOnceWith(+ "Instance webhook delivery worker failed",+ );+ expect(sendWebhookDelivery).toHaveBeenCalledTimes(5);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(sendWebhookDelivery).toHaveBeenCalledTimes(10);+ } finally {+ await stop();+ }+ await vi.advanceTimersByTimeAsync(1_000);+ expect(sendWebhookDelivery).toHaveBeenCalledTimes(10);+ });+});diff --git a/apps/api/src/admin/webhooks/start-webhook-worker.ts b/apps/api/src/admin/webhooks/start-webhook-worker.tsindex 91bc01c16..5478e47e3 100644--- a/apps/api/src/admin/webhooks/start-webhook-worker.ts+++ b/apps/api/src/admin/webhooks/start-webhook-worker.ts@@ -4,12 +4,14 @@ export function startWebhookWorker() {let running: Promise<unknown> | null = null;const tick = () => {if (running) return;- running = Promise.all(+ running = Promise.allSettled(Array.from({ length: 5 }, () => sendWebhookDelivery()),)- .catch(() => {- // Database errors may embed payloads and encrypted secrets.- console.error("Instance webhook delivery worker failed");+ .then((results) => {+ if (results.some((result) => result.status === "rejected")) {+ // Database errors may embed payloads and encrypted secrets.+ console.error("Instance webhook delivery worker failed");+ }}).finally(() => {running = null;diff --git a/tests/api-integration/admin-instance-webhooks.test.ts b/tests/api-integration/admin-instance-webhooks.test.tsindex 43ec1e2ab..8905c82c9 100644--- a/tests/api-integration/admin-instance-webhooks.test.ts+++ b/tests/api-integration/admin-instance-webhooks.test.ts@@ -62,6 +62,7 @@ beforeEach(async () => {afterEach(async () => {server.closeAllConnections();await new Promise<void>((resolve) => server.close(() => resolve()));+ vi.useRealTimers();vi.unstubAllEnvs();});@@ -312,6 +313,40 @@ describe("instance webhook delivery", () => {expect(JSON.stringify(entries)).not.toContain(admin.email);});+ it("checks saved destinations again before delivery", async () => {+ await create();+ await record();+ vi.stubEnv("KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS", "");+ expect(await sendWebhookDelivery()).toBe(true);+ expect(requests).toHaveLength(0);+ expect(await db.select().from(table)).toEqual([+ expect.objectContaining({+ state: "failed",+ errorCode: "destination",+ attempts: 1,+ }),+ ]);+ expect(await sendWebhookDelivery()).toBe(false);+ });++ it("uses the database clock for leases and backoff when an API clock is behind", async () => {+ await create();+ await record();+ const realNow = Date.now();+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(realNow - 3_600_000);+ expect(await claimWebhookDelivery()).not.toBeNull();+ const [leased] = await db.select().from(table);+ expect(leased!.nextAttemptAt.getTime()).toBeGreaterThan(realNow + 55_000);+ expect(await claimWebhookDelivery()).toBeNull();+ await due();+ status = 503;+ expect(await sendWebhookDelivery()).toBe(true);+ const [retry] = await db.select().from(table);+ expect(retry!.nextAttemptAt.getTime()).toBeGreaterThan(realNow + 25_000);+ expect(await sendWebhookDelivery()).toBe(false);+ });+it("enqueues after commit and discards rolled-back audit entries", async () => {await create();await db.transaction(async (tx) => {