Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

webhooks.worker.test.ts

205 lines6.3 KB

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