Open History to see the last commit
1import { beforeAll, describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3import { eq } from 'drizzle-orm'
4
5import { getDb } from '../db/index.ts'
6import type { Db } from '../db/index.ts'
7import {
8 changes,
9 providers,
10 subscriptions,
11 user,
12 webhookDeliveries,
13} from '../db/schema.ts'
14import {
15 MAX_ATTEMPTS,
16 deliverDue,
17 enqueueNewChanges,
18 runWebhookTick,
19 signPayload,
20} from './webhooks.ts'
21
22const NOW = 1_781_150_000
23const SECRET = 'whsec_test_secret'
24let db: Db
25
26/** Local receiver: a fetcher that records every request it gets. */
27function receiver(status = 200) {
28 const received: Array<{
29 url: string
30 body: string
31 signature: string | null
32 }> = []
33 const fetcher = (async (input: RequestInfo | URL, init?: RequestInit) => {
34 received.push({
35 url: String(input),
36 body: String(init?.body ?? ''),
37 signature:
38 new Headers(init?.headers).get('x-modelschemas-signature') ?? null,
39 })
40 return new Response('ok', { status })
41 }) as typeof globalThis.fetch
42 return { received, fetcher }
43}
44
45let subSeq = 0
46async function makeSubscription(
47 events: Array<string>,
48 providerFilter: string | null = null,
49): Promise<string> {
50 const id = `wh-sub-${String(subSeq++)}`
51 await db.insert(subscriptions).values({
52 id,
53 agentId: 'wh-owner',
54 url: `https://receiver.example.com/${id}`,
55 secret: SECRET,
56 events,
57 providerFilter,
58 active: true,
59 createdAt: NOW,
60 })
61 return id
62}
63
64let changeSeq = 0
65async function makeChange(
66 type: 'model.added' | 'schema.updated',
67 createdAt: number,
68 providerId = 'wh-prov',
69): Promise<string> {
70 const id = `wh-change-${String(changeSeq++)}`
71 await db.insert(changes).values({
72 id,
73 type,
74 providerId,
75 subjectId: 'subject',
76 summary: `${type} happened`,
77 createdAt,
78 })
79 return id
80}
81
82beforeAll(async () => {
83 db = getDb(env)
84 await db.insert(user).values({
85 id: 'wh-owner',
86 name: 'Webhook Owner',
87 email: 'wh-owner@example.com',
88 createdAt: new Date(NOW * 1000),
89 updatedAt: new Date(NOW * 1000),
90 })
91 await db.insert(providers).values([
92 {
93 id: 'wh-prov',
94 displayName: 'WH Prov',
95 specSourceUrl: 'https://example.com/spec.json',
96 },
97 {
98 id: 'wh-other',
99 displayName: 'WH Other',
100 specSourceUrl: 'https://example.com/spec.json',
101 },
102 ])
103})
104
105describe('webhook fan-out + signed delivery', () => {
106 it('enqueues matching changes and delivers a verifiable signed payload', async () => {
107 const subId = await makeSubscription(['model.added'])
108 await makeChange('model.added', NOW + 1)
109 await makeChange('schema.updated', NOW + 2) // not subscribed → no delivery
110
111 const enqueued = await enqueueNewChanges(db, NOW + 10)
112 expect(enqueued).toBe(1)
113
114 const { received, fetcher } = receiver()
115 const outcomes = await deliverDue(db, { fetcher, now: NOW + 10 })
116 expect(outcomes).toHaveLength(1)
117 expect(outcomes[0]).toMatchObject({ status: 'ok', responseCode: 200 })
118
119 expect(received).toHaveLength(1)
120 const hit = received[0]
121 expect(hit?.url).toContain(subId)
122 const parsed = JSON.parse(hit?.body ?? '{}') as {
123 event: string
124 change: { provider: string; summary: string }
125 _links: Record<string, string>
126 }
127 expect(parsed.event).toBe('model.added')
128 expect(parsed.change.provider).toBe('wh-prov')
129 expect(parsed._links.changes).toContain('/v1/changes?since=')
130 // The receiver can verify the signature by recomputing the HMAC.
131 expect(hit?.signature).toBe(await signPayload(SECRET, hit?.body ?? ''))
132
133 // Checkpoint advanced: re-running enqueues nothing.
134 expect(await enqueueNewChanges(db, NOW + 20)).toBe(0)
135 })
136
137 it('respects provider filters', async () => {
138 await makeSubscription(['model.added'], 'wh-other')
139 await makeChange('model.added', NOW + 30, 'wh-prov')
140 const enqueuedForOtherProvider = await enqueueNewChanges(db, NOW + 31)
141 // The wh-other-filtered sub must not receive a wh-prov change; the
142 // unfiltered sub from the previous test does.
143 const pending = await db
144 .select()
145 .from(webhookDeliveries)
146 .where(eq(webhookDeliveries.status, 'pending'))
147 expect(enqueuedForOtherProvider).toBe(1)
148 expect(pending).toHaveLength(1)
149 })
150
151 it('backs off exponentially and auto-pauses after MAX_ATTEMPTS', async () => {
152 // Drain anything pending from prior tests first.
153 await deliverDue(db, { fetcher: receiver(200).fetcher, now: NOW + 40 })
154
155 const subId = await makeSubscription(['schema.updated'])
156 await makeChange('schema.updated', NOW + 50)
157 expect(await enqueueNewChanges(db, NOW + 51)).toBe(1)
158
159 const failing = receiver(500)
160 let clock = NOW + 60
161 // First failure: attempt 1, nextAttemptAt = clock + 120.
162 const first = await deliverDue(db, { fetcher: failing.fetcher, now: clock })
163 expect(first[0]).toMatchObject({ status: 'pending', responseCode: 500 })
164 let row = await db.query.webhookDeliveries.findFirst({
165 where: eq(webhookDeliveries.subscriptionId, subId),
166 })
167 expect(row?.attempt).toBe(1)
168 expect(row?.nextAttemptAt).toBe(clock + 120)
169
170 // Not due yet → nothing happens.
171 expect(
172 await deliverDue(db, { fetcher: failing.fetcher, now: clock + 60 }),
173 ).toHaveLength(0)
174
175 // Fail through the remaining attempts.
176 for (let attempt = 2; attempt <= MAX_ATTEMPTS; attempt++) {
177 row = await db.query.webhookDeliveries.findFirst({
178 where: eq(webhookDeliveries.subscriptionId, subId),
179 })
180 clock = (row?.nextAttemptAt ?? clock) + 1
181 await deliverDue(db, { fetcher: failing.fetcher, now: clock })
182 }
183
184 row = await db.query.webhookDeliveries.findFirst({
185 where: eq(webhookDeliveries.subscriptionId, subId),
186 })
187 expect(row?.status).toBe('failed')
188 expect(row?.attempt).toBe(MAX_ATTEMPTS)
189
190 const pausedSub = await db.query.subscriptions.findFirst({
191 where: eq(subscriptions.id, subId),
192 })
193 expect(pausedSub?.active).toBe(false)
194 })
195
196 it('runWebhookTick combines enqueue + drain', async () => {
197 await makeSubscription(['model.added'])
198 await makeChange('model.added', NOW + 100)
199 const { received, fetcher } = receiver()
200 const tick = await runWebhookTick(db, { fetcher, now: NOW + 101 })
201 expect(tick.enqueued).toBeGreaterThanOrEqual(1)
202 expect(received.length).toBeGreaterThanOrEqual(1)
203 })
204})