From ecfa217d74a0b0844f024a186e390174f03b07c3 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Tue, 1 Dec 2026 21:48:33 -0500 Subject: [PATCH 1/2] fix(delivery): stop polling the database every second while nothing is configured Webhook and audit sink delivery each ran a one second loop on every replica since 0.23.0, even with no endpoint or sink, which kept pooled connections open and a serverless Postgres from scaling down. Both loops now poll every second only while an endpoint exists or a sink is enabled, and every 30 seconds otherwise with one read. Creating or enabling an endpoint or sink wakes the local loop at once. Dispatch no longer runs while no endpoint exists, so creating the first endpoint moves the dispatch cursor to the newest event under the dispatch lock, keeping the rule that turning webhooks on replays no history. Closes #630 --- .changeset/idle-delivery-polling.md | 5 + docs/adr/0005-extensibility-callouts.md | 2 +- src/lib/deliveryPoller.ts | 65 ++++++++++++ src/services/auditSinkService.ts | 48 ++++----- src/services/webhookService.ts | 77 +++++++++----- tests/integration/admin/webhooks.spec.ts | 12 +++ tests/unit/lib/deliveryPoller.spec.ts | 103 +++++++++++++++++++ tests/unit/services/auditSinkService.spec.ts | 43 +++++--- tests/unit/services/webhookService.spec.ts | 83 ++++++++++++--- 9 files changed, 365 insertions(+), 73 deletions(-) create mode 100644 .changeset/idle-delivery-polling.md create mode 100644 src/lib/deliveryPoller.ts create mode 100644 tests/unit/lib/deliveryPoller.spec.ts diff --git a/.changeset/idle-delivery-polling.md b/.changeset/idle-delivery-polling.md new file mode 100644 index 00000000..67ad78b9 --- /dev/null +++ b/.changeset/idle-delivery-polling.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': patch +--- + +Webhook and audit sink delivery no longer query the database every second on every instance when nothing is configured to deliver to. Since 0.23.0 both loops ran once a second regardless, which kept pooled connections open and a serverless Postgres (Aurora Serverless v2, Neon and similar) from scaling down. Each loop now polls once a second while a webhook endpoint exists or an audit sink is enabled, and every 30 seconds otherwise, with a single read. Creating an endpoint or creating or enabling a sink wakes the loop on that instance at once; other instances pick it up within 30 seconds. Creating the first webhook endpoint starts delivery at the newest event, as before, so no history is replayed. diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md index 99141bc2..4eb82cec 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -29,7 +29,7 @@ Webhooks and login hook calls are signed with the [Standard Webhooks](https://gi A dispatcher reads `auth_events` past a cursor (`event_dispatch_cursors`) by `seq` and turns matching rows into deliveries. An event is sent only once its row has committed, nothing is lost between happening and being queued, and the SIEM stream (#420) reads the same rows with the same hashes. -The chain trigger updates the chain head row on every insert and holds that lock until commit, so committed rows always form a gapless prefix of `seq`: the cursor cannot step past a row that is still to commit. On first run the cursor starts at the newest row, so turning webhooks on does not replay history. Replicas take turns through an advisory lock. Delivery workers claim due rows with `FOR UPDATE SKIP LOCKED` and lease them past the request timeout, so a replica that dies mid-send leaves the delivery due again shortly after. The loop polls once a second. +The chain trigger updates the chain head row on every insert and holds that lock until commit, so committed rows always form a gapless prefix of `seq`: the cursor cannot step past a row that is still to commit. On first run the cursor starts at the newest row, so turning webhooks on does not replay history. Replicas take turns through an advisory lock. Delivery workers claim due rows with `FOR UPDATE SKIP LOCKED` and lease them past the request timeout, so a replica that dies mid-send leaves the delivery due again shortly after. The loop polls once a second while an endpoint exists. With none it polls every 30 seconds and reads only a count, so an instance with webhooks unused leaves the database idle; creating the first endpoint starts the cursor at the newest row under the dispatch lock, since dispatch did not run while there were none. ### E3. A small, versioned event catalog diff --git a/src/lib/deliveryPoller.ts b/src/lib/deliveryPoller.ts new file mode 100644 index 00000000..fc9bb1d9 --- /dev/null +++ b/src/lib/deliveryPoller.ts @@ -0,0 +1,65 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +export const BUSY_POLL_MS = 1000; +// Long enough that the pool drops its idle connections and a serverless database can scale +// down between ticks when nothing is configured to deliver to. +export const IDLE_POLL_MS = 30_000; + +export interface DeliveryPoller { + /** Runs a tick at once, or right after the one in flight. */ + wake(): void; + stop(): void; +} + +/** + * Runs `tick` after `BUSY_POLL_MS` when it reports work to watch for, after `IDLE_POLL_MS` + * when it does not. Ticks never overlap. + */ +export function startDeliveryPoller(tick: () => Promise): DeliveryPoller { + let timer: ReturnType | null = null; + let running = false; + let wokenWhileRunning = false; + let stopped = false; + + function schedule(delayMs: number) { + if (stopped) return; + timer = setTimeout(run, delayMs); + timer.unref(); + } + + function run() { + timer = null; + running = true; + void tick() + .catch(() => false) + .then((busy) => { + running = false; + const woken = wokenWhileRunning; + wokenWhileRunning = false; + schedule(woken ? 0 : busy ? BUSY_POLL_MS : IDLE_POLL_MS); + }); + } + + schedule(BUSY_POLL_MS); + + return { + wake() { + if (stopped) return; + if (running) { + wokenWhileRunning = true; + return; + } + if (timer) clearTimeout(timer); + schedule(0); + }, + stop() { + stopped = true; + if (timer) clearTimeout(timer); + timer = null; + }, + }; +} diff --git a/src/services/auditSinkService.ts b/src/services/auditSinkService.ts index 88f88636..d836efdb 100644 --- a/src/services/auditSinkService.ts +++ b/src/services/auditSinkService.ts @@ -10,7 +10,7 @@ import type { CreateAuditSinkRequest, UpdateAuditSinkRequest, } from '@seamless-auth/types'; -import { Op, QueryTypes } from 'sequelize'; +import { QueryTypes } from 'sequelize'; import { eventRecord, @@ -18,6 +18,7 @@ import { sinkDestinationProblem, testRecord, } from '../lib/auditSinkTransport.js'; +import { type DeliveryPoller, startDeliveryPoller } from '../lib/deliveryPoller.js'; import { AuditSink } from '../models/auditSinks.js'; import { getSequelize } from '../models/index.js'; import getLogger from '../utils/logger.js'; @@ -122,7 +123,7 @@ export async function createSink(input: CreateAuditSinkRequest, actorUserId: str assertSettings(input.settings); const cursorSeq = await startingCursor(input.startAfterSeq); - return AuditSink.create({ + const sink = await AuditSink.create({ name: input.name, kind: input.settings.kind, settings: input.settings, @@ -130,6 +131,9 @@ export async function createSink(input: CreateAuditSinkRequest, actorUserId: str cursorSeq: String(cursorSeq), createdBy: actorUserId, }); + + poller?.wake(); + return sink; } /** A change of settings or a re-enable is tried at once rather than after the backoff. */ @@ -147,6 +151,7 @@ export async function updateSink(id: string, input: UpdateAuditSinkRequest) { nextAttemptAt: null, }); + poller?.wake(); return sink; } @@ -251,34 +256,31 @@ async function drainSink(id: string) { } } -/** One pass over every enabled sink that is due. Errors are logged, not thrown. */ -export async function runAuditSinkTick() { +let poller: DeliveryPoller | null = null; + +/** + * One pass over every enabled sink that is due. Returns whether any sink is enabled, which + * decides how soon the next pass runs. Errors are logged, not thrown. + */ +export async function runAuditSinkTick(): Promise { try { const sinks = await AuditSink.findAll({ - attributes: ['id'], - where: { - enabled: true, - [Op.or]: [{ nextAttemptAt: null }, { nextAttemptAt: { [Op.lte]: now() } }], - }, + attributes: ['id', 'nextAttemptAt'], + where: { enabled: true }, }); - await Promise.all(sinks.map((sink) => drainSink(sink.id))); + const at = now(); + const due = sinks.filter((sink) => !sink.nextAttemptAt || sink.nextAttemptAt <= at); + await Promise.all(due.map((sink) => drainSink(sink.id))); + return sinks.length > 0; } catch (error) { logger.error(`Audit sink tick failed: ${(error as Error).message}`); + return false; } } -const TICK_MS = 1000; - -/** Polls once a second, like webhook delivery. Idle, it is one read of a small table. */ +/** Polls once a second while a sink is enabled, otherwise every 30 seconds. */ export function startAuditSinkDelivery() { - let running = false; - const timer = setInterval(() => { - if (running) return; - running = true; - void runAuditSinkTick().finally(() => { - running = false; - }); - }, TICK_MS); - timer.unref(); - return timer; + poller?.stop(); + poller = startDeliveryPoller(runAuditSinkTick); + return poller; } diff --git a/src/services/webhookService.ts b/src/services/webhookService.ts index 9f1d42f0..6f5280ca 100644 --- a/src/services/webhookService.ts +++ b/src/services/webhookService.ts @@ -31,6 +31,7 @@ import { signedCalloutHeaders, } from '../lib/calloutSigning.js'; import { CalloutError, calloutRequest, calloutUrlProblem } from '../lib/calloutTransport.js'; +import { type DeliveryPoller, startDeliveryPoller } from '../lib/deliveryPoller.js'; import { getSequelize } from '../models/index.js'; import { User } from '../models/users.js'; import { WebhookDelivery, type WebhookDeliveryAttributes } from '../models/webhookDeliveries.js'; @@ -148,15 +149,38 @@ export async function createEndpoint( assertSecretKey(); const secret = generateCalloutSecret(); - const endpoint = await WebhookEndpoint.create({ - url: input.url, - description: input.description ?? null, - eventTypes: input.eventTypes, - enabled: input.enabled ?? true, - createdBy: actorUserId, - ...secretColumns(secret), + const sequelize = getSequelize(); + const endpoint = await sequelize.transaction(async (transaction) => { + // Dispatch does not run while no endpoint exists, so the cursor may be far behind. The first + // endpoint starts it at the newest row, under the dispatch lock, so turning webhooks on does + // not replay what happened while there were none (ADR 0005, D2). + await sequelize.query('SELECT pg_advisory_xact_lock(:key)', { + replacements: { key: DISPATCH_LOCK_KEY }, + transaction, + }); + if ((await WebhookEndpoint.count({ transaction })) === 0) { + await sequelize.query( + `INSERT INTO public.event_dispatch_cursors (name, "lastSeq", "updatedAt") + SELECT :name, coalesce(max(seq), 0), now() FROM public.auth_events + ON CONFLICT (name) DO UPDATE SET "lastSeq" = EXCLUDED."lastSeq", "updatedAt" = now()`, + { replacements: { name: CURSOR_NAME }, transaction }, + ); + } + + return WebhookEndpoint.create( + { + url: input.url, + description: input.description ?? null, + eventTypes: input.eventTypes, + enabled: input.enabled ?? true, + createdBy: actorUserId, + ...secretColumns(secret), + }, + { transaction }, + ); }); + poller?.wake(); return { endpoint, secret }; } @@ -197,6 +221,7 @@ export async function updateEndpoint(id: string, input: UpdateWebhookEndpointReq )[0] : 0; + if (reenabling) poller?.wake(); return { endpoint, released }; } @@ -624,35 +649,39 @@ export async function pruneDeliveries(at: Date = now()) { }); } -const TICK_MS = 1000; -const PRUNE_EVERY_TICKS = 3600; +const PRUNE_INTERVAL_MS = 60 * 60 * 1000; +let lastPrunedAt = 0; +let poller: DeliveryPoller | null = null; -/** One pass of dispatch and delivery. Errors are logged, not thrown, so the loop keeps running. */ -export async function runWebhookTick(tick: number) { +/** + * One pass of dispatch and delivery. Returns whether any endpoint exists, which decides how soon + * the next pass runs. Deliveries cascade with their endpoint, so with none there is nothing to + * send or prune. Errors are logged, not thrown, so the loop keeps running. + */ +export async function runWebhookTick(at: number = Date.now()): Promise { try { + if ((await WebhookEndpoint.count()) === 0) return false; + while ((await dispatchWebhooks()) === DISPATCH_BATCH) { // A full batch means more rows are waiting. } while ((await deliverDue()) === DELIVERY_BATCH) { // Likewise for due deliveries. } - if (tick % PRUNE_EVERY_TICKS === 0) await pruneDeliveries(); + if (at - lastPrunedAt >= PRUNE_INTERVAL_MS) { + lastPrunedAt = at; + await pruneDeliveries(); + } + return true; } catch (error) { logger.error(`Webhook tick failed: ${(error as Error).message}`); + return false; } } -/** Polls once a second. The loop is cheap when idle: two indexed reads. */ +/** Polls once a second while an endpoint exists, otherwise every 30 seconds with one count. */ export function startWebhookDelivery() { - let tick = 0; - let running = false; - const timer = setInterval(() => { - if (running) return; - running = true; - void runWebhookTick(tick++).finally(() => { - running = false; - }); - }, TICK_MS); - timer.unref(); - return timer; + poller?.stop(); + poller = startDeliveryPoller(() => runWebhookTick()); + return poller; } diff --git a/tests/integration/admin/webhooks.spec.ts b/tests/integration/admin/webhooks.spec.ts index 25c6272c..7ece8125 100644 --- a/tests/integration/admin/webhooks.spec.ts +++ b/tests/integration/admin/webhooks.spec.ts @@ -2,6 +2,17 @@ import { Application } from 'express'; import request from 'supertest'; import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +const { query, transaction } = vi.hoisted(() => { + const query = vi.fn(); + const transaction = vi.fn(async (fn: (t: unknown) => unknown) => fn({})); + return { query, transaction }; +}); + +vi.mock('../../../src/models/index.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getSequelize: () => ({ query, transaction }) }; +}); + vi.mock('../../../src/lib/calloutTransport.js', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, calloutRequest: vi.fn() }; @@ -106,6 +117,7 @@ describe('webhook endpoints', () => { expect(res.status).toBe(201); expect(res.body.secret).toMatch(/^whsec_/); + expect(transaction).toHaveBeenCalledTimes(1); // The audit log is permanent, so a token in the query string must not reach it. expect(AuthEventService.log).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/tests/unit/lib/deliveryPoller.spec.ts b/tests/unit/lib/deliveryPoller.spec.ts new file mode 100644 index 00000000..3c951bec --- /dev/null +++ b/tests/unit/lib/deliveryPoller.spec.ts @@ -0,0 +1,103 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + BUSY_POLL_MS, + IDLE_POLL_MS, + startDeliveryPoller, +} from '../../../src/lib/deliveryPoller.js'; + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('startDeliveryPoller', () => { + it('polls each second while busy and every 30 seconds while idle', async () => { + let busy = true; + const tick = vi.fn(async () => busy); + const poller = startDeliveryPoller(tick); + + await vi.advanceTimersByTimeAsync(BUSY_POLL_MS); + await vi.advanceTimersByTimeAsync(BUSY_POLL_MS); + expect(tick).toHaveBeenCalledTimes(2); + + busy = false; + await vi.advanceTimersByTimeAsync(BUSY_POLL_MS); + expect(tick).toHaveBeenCalledTimes(3); + await vi.advanceTimersByTimeAsync(IDLE_POLL_MS - 1); + expect(tick).toHaveBeenCalledTimes(3); + await vi.advanceTimersByTimeAsync(1); + expect(tick).toHaveBeenCalledTimes(4); + + poller.stop(); + }); + + it('never overlaps ticks', async () => { + let release: () => void = () => {}; + const tick = vi.fn(() => new Promise((done) => (release = () => done(true)))); + const poller = startDeliveryPoller(tick); + + await vi.advanceTimersByTimeAsync(BUSY_POLL_MS * 5); + expect(tick).toHaveBeenCalledTimes(1); + + release(); + await vi.advanceTimersByTimeAsync(BUSY_POLL_MS); + expect(tick).toHaveBeenCalledTimes(2); + + poller.stop(); + }); + + it('runs at once when woken while idle', async () => { + const tick = vi.fn(async () => false); + const poller = startDeliveryPoller(tick); + await vi.advanceTimersByTimeAsync(BUSY_POLL_MS); + expect(tick).toHaveBeenCalledTimes(1); + + poller.wake(); + await vi.advanceTimersByTimeAsync(0); + expect(tick).toHaveBeenCalledTimes(2); + + poller.stop(); + }); + + it('runs again right after the tick in flight when woken during it', async () => { + let release: () => void = () => {}; + const tick = vi.fn(() => new Promise((done) => (release = () => done(false)))); + const poller = startDeliveryPoller(tick); + await vi.advanceTimersByTimeAsync(BUSY_POLL_MS); + + poller.wake(); + release(); + await vi.advanceTimersByTimeAsync(0); + expect(tick).toHaveBeenCalledTimes(2); + + poller.stop(); + }); + + it('treats a rejected tick as idle', async () => { + const tick = vi.fn(async () => { + throw new Error('database down'); + }); + const poller = startDeliveryPoller(tick); + + await vi.advanceTimersByTimeAsync(BUSY_POLL_MS + IDLE_POLL_MS - 1); + expect(tick).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + expect(tick).toHaveBeenCalledTimes(2); + + poller.stop(); + }); + + it('stops for good, and ignores a wake after stopping', async () => { + const tick = vi.fn(async () => true); + const poller = startDeliveryPoller(tick); + + poller.stop(); + poller.wake(); + await vi.advanceTimersByTimeAsync(IDLE_POLL_MS * 2); + expect(tick).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/services/auditSinkService.spec.ts b/tests/unit/services/auditSinkService.spec.ts index 818e6868..dc623b12 100644 --- a/tests/unit/services/auditSinkService.spec.ts +++ b/tests/unit/services/auditSinkService.spec.ts @@ -413,29 +413,48 @@ describe('the loop', () => { expect(readExportBatch).toHaveBeenCalledTimes(50); }); + it('skips an enabled sink still backing off', async () => { + vi.mocked(AuditSink.findAll).mockResolvedValue([ + { id: 'sink-1', nextAttemptAt: new Date(Date.now() + 60_000) }, + ] as never); + + expect(await runAuditSinkTick()).toBe(true); + expect(transaction).not.toHaveBeenCalled(); + }); + + it('reports idle when no sink is enabled', async () => { + vi.mocked(AuditSink.findAll).mockResolvedValue([] as never); + + expect(await runAuditSinkTick()).toBe(false); + }); + it('logs rather than throws when a sink or the tick fails', async () => { vi.mocked(AuditSink.findAll).mockResolvedValueOnce([{ id: 'sink-1' }] as never); transaction.mockRejectedValueOnce(new Error('database unavailable')); - await expect(runAuditSinkTick()).resolves.toBeUndefined(); + await expect(runAuditSinkTick()).resolves.toBe(true); vi.mocked(AuditSink.findAll).mockRejectedValueOnce(new Error('database unavailable')); - await expect(runAuditSinkTick()).resolves.toBeUndefined(); + await expect(runAuditSinkTick()).resolves.toBe(false); }); - it('ticks once a second and never overlaps', async () => { + it('polls every 30 seconds while no sink is enabled, and at once when one is created', async () => { vi.useFakeTimers(); - let release: () => void = () => {}; - vi.mocked(AuditSink.findAll).mockImplementation( - () => new Promise((done) => (release = () => done([]))) as never, - ); + vi.mocked(AuditSink.findAll).mockResolvedValue([] as never); - const timer = startAuditSinkDelivery(); - await vi.advanceTimersByTimeAsync(3000); + const poller = startAuditSinkDelivery(); + await vi.advanceTimersByTimeAsync(1000); + expect(AuditSink.findAll).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(29_000); expect(AuditSink.findAll).toHaveBeenCalledTimes(1); - - release(); await vi.advanceTimersByTimeAsync(1000); expect(AuditSink.findAll).toHaveBeenCalledTimes(2); - clearInterval(timer); + + bounds('42', '1'); + vi.mocked(AuditSink.create).mockImplementation(async (values: any) => sink(values)); + await createSink({ name: 'SIEM', settings: settings(), enabled: true }, null); + await vi.advanceTimersByTimeAsync(0); + expect(AuditSink.findAll).toHaveBeenCalledTimes(3); + + poller.stop(); }); }); diff --git a/tests/unit/services/webhookService.spec.ts b/tests/unit/services/webhookService.spec.ts index 67ee47c6..43bc6447 100644 --- a/tests/unit/services/webhookService.spec.ts +++ b/tests/unit/services/webhookService.spec.ts @@ -12,6 +12,7 @@ vi.mock('../../../src/models/index.js', () => ({ vi.mock('../../../src/models/webhookEndpoints.js', () => ({ WebhookEndpoint: { + count: vi.fn(), findAll: vi.fn(), findByPk: vi.fn(), create: vi.fn(), @@ -162,6 +163,38 @@ describe('endpoints', () => { }); }); + it('starts the dispatch cursor at the newest event when it creates the first endpoint', async () => { + vi.mocked(WebhookEndpoint.count).mockResolvedValue(0); + vi.mocked(WebhookEndpoint.create).mockImplementation(async (values: any) => endpoint(values)); + + await createEndpoint( + { url: 'https://hooks.example.com/a', eventTypes: ['user.created'] }, + null, + ); + + const sql = query.mock.calls.map(([statement]) => statement as string); + expect(sql[0]).toContain('pg_advisory_xact_lock'); + expect(sql[0]).not.toContain('try'); + expect(sql[1]).toContain('coalesce(max(seq), 0)'); + expect(sql[1]).toContain('ON CONFLICT (name) DO UPDATE'); + expect(vi.mocked(WebhookEndpoint.create).mock.calls[0][1]).toEqual({ + transaction: { id: 'tx' }, + }); + }); + + it('leaves the cursor alone when an endpoint already exists', async () => { + vi.mocked(WebhookEndpoint.count).mockResolvedValue(2); + vi.mocked(WebhookEndpoint.create).mockImplementation(async (values: any) => endpoint(values)); + + await createEndpoint( + { url: 'https://hooks.example.com/a', eventTypes: ['user.created'] }, + null, + ); + + expect(query).toHaveBeenCalledTimes(1); + expect(query.mock.calls[0][0]).toContain('pg_advisory_xact_lock'); + }); + it('refuses a URL no callout may reach', async () => { await expect( createEndpoint({ url: 'http://169.254.169.254/', eventTypes: ['user.created'] }, null), @@ -764,38 +797,62 @@ describe('the delivery loop', () => { expect(cutoff.toISOString()).toBe('2026-10-08T12:00:00.000Z'); }); - it('runs dispatch and delivery until each comes back short, and prunes on the hour', async () => { + it('runs dispatch and delivery until each comes back short, and prunes hourly', async () => { query.mockImplementation(async (sql: string) => sql.includes('pg_try_advisory_xact_lock') ? [{ locked: false }] : [], ); vi.mocked(WebhookDelivery.destroy).mockResolvedValue(0 as never); + vi.mocked(WebhookEndpoint.count).mockResolvedValue(1); - await runWebhookTick(0); + const hour = 60 * 60 * 1000; + expect(await runWebhookTick(10 * hour)).toBe(true); expect(WebhookDelivery.destroy).toHaveBeenCalledTimes(1); - await runWebhookTick(1); + await runWebhookTick(10 * hour + 1000); expect(WebhookDelivery.destroy).toHaveBeenCalledTimes(1); + + await runWebhookTick(11 * hour); + expect(WebhookDelivery.destroy).toHaveBeenCalledTimes(2); + }); + + it('reads nothing past one count while no endpoint exists', async () => { + vi.mocked(WebhookEndpoint.count).mockResolvedValue(0); + + expect(await runWebhookTick()).toBe(false); + + expect(transaction).not.toHaveBeenCalled(); + expect(query).not.toHaveBeenCalled(); + expect(WebhookDelivery.destroy).not.toHaveBeenCalled(); }); it('keeps going after a failed tick', async () => { + vi.mocked(WebhookEndpoint.count).mockResolvedValue(1); transaction.mockRejectedValue(new Error('database down')); - await expect(runWebhookTick(1)).resolves.toBeUndefined(); + await expect(runWebhookTick()).resolves.toBe(false); }); - it('polls once a second and skips a tick while one is running', async () => { + it('polls every 30 seconds while no endpoint exists, and at once when one is created', async () => { vi.useFakeTimers(); - let release: () => void = () => {}; - transaction.mockImplementation( - () => new Promise((resolve) => (release = () => resolve(0))) as never, - ); + vi.mocked(WebhookEndpoint.count).mockResolvedValue(0); - const timer = startWebhookDelivery(); + const poller = startWebhookDelivery(); await vi.advanceTimersByTimeAsync(1000); + expect(WebhookEndpoint.count).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(29_000); + expect(WebhookEndpoint.count).toHaveBeenCalledTimes(1); await vi.advanceTimersByTimeAsync(1000); - expect(transaction).toHaveBeenCalledTimes(1); + expect(WebhookEndpoint.count).toHaveBeenCalledTimes(2); + + vi.mocked(WebhookEndpoint.create).mockImplementation(async (values: any) => endpoint(values)); + await createEndpoint( + { url: 'https://hooks.example.com/a', eventTypes: ['user.created'] }, + null, + ); + // One count inside the create, one from the tick it woke. + await vi.advanceTimersByTimeAsync(0); + expect(WebhookEndpoint.count).toHaveBeenCalledTimes(4); - release(); - clearInterval(timer); + poller.stop(); }); }); From d29049046e7703d9160da3f96c5d410cf8603a8d Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Tue, 1 Dec 2026 21:58:51 -0500 Subject: [PATCH 2/2] fix(deps): update minimatch and glob for GHSA-cf2h-pxjq-68xw and GHSA-qxr8-q827-836c --- package-lock.json | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/package-lock.json b/package-lock.json index ab5161aa..fc82a48a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2047,9 +2047,9 @@ } }, "node_modules/@isaacs/nonrecursive-glob-match": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.0.3.tgz", - "integrity": "sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", "license": "BlueOak-1.0.0" }, "node_modules/@jridgewell/resolve-uri": { @@ -6093,12 +6093,12 @@ "license": "MIT" }, "node_modules/glob": { - "version": "14.0.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.3.tgz", - "integrity": "sha512-A1vjIwC3qpdCso45Iw127gnp7sPhqgY8lUQhDrArIs+GbmfaaVPFuoyy7WyLT9EPZCRZ7j7aLdwUhQmHWesEow==", + "version": "14.0.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.7.tgz", + "integrity": "sha512-ob8P0VbyEjcLG2ycNYmzYhZj65kkcN5b7tt5moGhTq3rkXtuU8MB+i0GIzPtLnSHVF2DkK4M+nQRojDvsOGVJw==", "license": "BlueOak-1.0.0", "dependencies": { - "minimatch": "^11.0.2", + "minimatch": "^11.0.5", "minipass": "^7.1.3", "path-scurry": "^3.0.0" }, @@ -7303,16 +7303,16 @@ } }, "node_modules/minimatch": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.3.tgz", - "integrity": "sha512-iny/40PEGkNJQ5/Pv6z3nm6FbRAby32GeZRjCUJk2WnNDbgPSTcdI+DDvLqsgBdD4cD5sMtMheqPPnehCCa8Nw==", + "version": "11.0.10", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.10.tgz", + "integrity": "sha512-L3/cjhQ5E6lft0VCp/2mO3Ic74RnutKy3rz7iGwp/6w1hKcO262g2rbfacFyw6eBig5OdI0nu5PpuA0/WQs9Tw==", "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/nonrecursive-glob-match": "^1.0.3", + "@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.12" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs"