Open History to see the last commit
1import { postgresTestLimits } from '../fixtures/postgres-limits.js'
2import { randomInt, randomUUID, createPublicKey, verify } from 'node:crypto'
3import { createServer } from 'node:http'
4import { once } from 'node:events'
5import pg from 'pg'
6import { afterAll, beforeAll, expect, test } from 'vitest'
7import { createDurableStreams } from '../../src/index.js'
8import type { AuthorizationContext, DurableStreamsServer } from '../../src/index.js'
9import { initializeSubscriptions, parseSubscriptionKeyring } from '../../src/subscriptions.js'
10import { createS3ChunkStorage } from '../../src/s3.js'
11import { createNeonRealtimeNotifier } from '../../src/neon.js'
12import { migrate } from '../../src/migrations.js'
13import { advanceOffset, ZERO_OFFSET } from '../../src/offset.js'
14import { transaction } from '../../src/transaction.js'
15
16const env = process.env
17if (!env.TEST_DATABASE_URL || !env.TEST_DATABASE_URL_UNPOOLED || !env.AWS_ENDPOINT_URL_S3 || !env.AWS_REGION || !env.NEON_TEST_BUCKET || !env.DURABLE_STREAMS_KEYRING || !env.NEON_REALTIME_URL || !env.NEON_REALTIME_SECRET) throw new Error('Subscription qualification requires real Neon data services and wrapping keys')
18const schema = `ds_test_${randomUUID().replaceAll('-', '')}`
19const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL, max: 12 })
20const direct = new pg.Pool({ connectionString: env.TEST_DATABASE_URL_UNPOOLED, max: 2 })
21pool.on('error', () => {})
22direct.on('error', () => {})
23const keyring = parseSubscriptionKeyring(env.DURABLE_STREAMS_KEYRING)
24const objects = createS3ChunkStorage({ endpoint: env.AWS_ENDPOINT_URL_S3, region: env.AWS_REGION, bucket: env.NEON_TEST_BUCKET })
25const reported: unknown[] = []
26const notifier = createNeonRealtimeNotifier({ url: env.NEON_REALTIME_URL, secret: env.NEON_REALTIME_SECRET, database: new URL(env.TEST_DATABASE_URL).pathname.slice(1) })
27const servers: DurableStreamsServer[] = []
28const subscriptions = new Set<string>()
29const server = (maxStreams = 1000, authorize: (context: AuthorizationContext) => boolean = () => true) => {
30 const handler = createDurableStreams({ postgres: { ...postgresTestLimits, pool, schema }, storage: { objects, targetChunkBytes: 32, maxChunkFrames: 8 },
31 live: { notifier, fallbackIntervalMs: 60_000, validationIntervalMs: 60_000 }, subscriptions: { keyring, allowLocalhostWebhooks: true, maxStreams },
32 auth: { authenticate: (request) => { const key = request.headers.get('authorization'); return key === 'Bearer a' || key === 'Bearer b' ? { tenantId: key.slice(-1), subject: 'fixture' } : null }, authorize },
33 onError: (error) => reported.push(error) })
34 servers.push(handler)
35 return handler
36}
37const handler = server()
38const request = (path: string, method = 'GET', body?: string, headers?: Record<string, string>, target = handler) => target.fetch(new Request(`https://fixture.test/v1/stream/${path}`, {
39 method, headers: { Authorization: 'Bearer a', 'Content-Type': 'text/plain', ...headers }, ...(body !== undefined ? { body } : {}),
40}))
41const subPath = (name: string, action = '') => `__ds/subscriptions/${name}${action ? `/${action}` : ''}`
42async function register(name: string, config: object, target = handler) {
43 const response = await request(subPath(name), 'PUT', JSON.stringify(config), { 'Content-Type': 'application/json' }, target)
44 expect(response.status).toBe(201)
45 subscriptions.add(name)
46 return response.json() as Promise<{ webhook?: { signing: { kid: string; jwks_url: string } } }>
47}
48async function createPull(name: string, pattern: string, lease = 30_000, target = handler) {
49 const wake = `wake/${name}`
50 expect((await request(wake, 'PUT', '[]', { 'Content-Type': 'application/json' }, target)).status).toBe(201)
51 await register(name, { type: 'pull-wake', pattern, wake_stream: wake, lease_ttl_ms: lease }, target)
52 return wake
53}
54const maintain = (target = handler) => target.maintain({ maxChunks: 1, maxSubscriptionWork: 64 })
55interface Claim { wake_id: string; generation: number; token: string; streams: { path: string; acked_offset: string; tail_offset: string; has_pending: boolean }[] }
56async function claim(name: string, worker = 'worker', target = handler): Promise<Claim> {
57 const response = await request(subPath(name, 'claim'), 'POST', JSON.stringify({ worker }), { 'Content-Type': 'application/json' }, target)
58 expect(response.status).toBe(200)
59 return response.json() as Promise<Claim>
60}
61const ack = (name: string, value: Claim, acks: readonly { stream: string; offset: string }[], done = true, target = handler) => request(subPath(name, 'ack'), 'POST', JSON.stringify({ wake_id: value.wake_id, generation: value.generation, acks, done }), { 'Content-Type': 'application/json', Authorization: `Bearer ${value.token}` }, target)
62const deferred = () => { let resolve!: () => void; const promise = new Promise<void>((accept) => { resolve = accept }); return { promise, resolve } }
63async function poll(check: () => Promise<boolean>, timeout = 5000) {
64 const deadline = Date.now() + timeout
65 while (!await check()) { if (Date.now() >= deadline) throw new Error('Timed out at the SQL concurrency barrier'); await new Promise((resolve) => setTimeout(resolve, 25)) }
66}
67interface Notification { raw: Buffer; signature: string; body: { subscription_id: string; wake_id: string; generation: number; callback_token: string; callback_url: string; streams: { path: string; acked_offset: string; tail_offset: string }[] } }
68async function receiver(response: (notification: Notification, index: number) => Promise<{ status?: number; done?: boolean }> = async () => ({ done: true })) {
69 const received: Notification[] = []
70 const http = createServer(async (request, outgoing) => {
71 const chunks: Buffer[] = []
72 for await (const chunk of request) chunks.push(Buffer.from(chunk as Uint8Array))
73 const raw = Buffer.concat(chunks)
74 const notification: Notification = { raw, signature: String(request.headers['webhook-signature']), body: JSON.parse(raw.toString('utf8')) as Notification['body'] }
75 const index = received.push(notification) - 1
76 const result = await response(notification, index)
77 outgoing.writeHead(result.status ?? 200, { 'Content-Type': 'application/json' })
78 outgoing.end(JSON.stringify({ done: result.done ?? false }))
79 })
80 http.listen(0, '127.0.0.1')
81 await once(http, 'listening')
82 const address = http.address()
83 if (!address || typeof address === 'string') throw new Error('Missing webhook fixture address')
84 return { url: `http://127.0.0.1:${address.port}/hook`, received,
85 close: async () => { http.closeAllConnections(); await new Promise<void>((resolve, reject) => http.close((error) => error ? reject(error) : resolve())) } }
86}
87async function remove(name: string) {
88 expect((await request(subPath(name), 'DELETE')).status).toBe(204)
89 subscriptions.delete(name)
90}
91
92beforeAll(async () => { await migrate(direct, { schema, storageIdentity: objects.identity }); await initializeSubscriptions(direct, { schema, keyring }) })
93afterAll(async () => {
94 for (const name of subscriptions) await request(subPath(name), 'DELETE')
95 await Promise.all(servers.map((value) => value.close()))
96 notifier.close(); objects.close()
97 await direct.query(`DROP SCHEMA "${schema}" CASCADE`)
98 await pool.end(); await direct.end()
99 expect(reported).toEqual([])
100})
101
102test('one bounded dispatch coalesces committed appends without consuming intent beyond its cutoff', async () => {
103 const name = 'coalesced-prefix', path = 'coalesced/source'
104 await request(path, 'PUT')
105 await createPull(name, 'coalesced/*')
106 await maintain()
107 let tail = ''
108 for (let i = 0; i < 12; i++) tail = (await request(path, 'POST', String(i))).headers.get('Stream-Next-Offset')!
109 const key = randomInt(1, 2_000_000_000), gate = await direct.connect()
110 await gate.query('SELECT pg_advisory_lock($1::bigint)', [key])
111 await direct.query(`CREATE FUNCTION "${schema}".pause_coalesced() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.name = 'coalesced-prefix' THEN PERFORM pg_advisory_xact_lock(${key}::bigint); END IF; RETURN NEW; END $$`)
112 await direct.query(`CREATE TRIGGER pause_coalesced AFTER UPDATE ON "${schema}".subscriptions FOR EACH ROW EXECUTE FUNCTION "${schema}".pause_coalesced()`)
113 const work = handler.maintain({ maxChunks: 1, maxSubscriptionWork: 1 })
114 void work.catch(() => {})
115 try {
116 await poll(async () => Boolean((await pool.query(`SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND objid = $1::oid AND NOT granted`, [key])).rowCount))
117 tail = (await request(path, 'POST', 'after cutoff')).headers.get('Stream-Next-Offset')!
118 } finally { await gate.query('SELECT pg_advisory_unlock($1::bigint)', [key]); gate.release() }
119 // Remove the barrier before the same bounded maintenance pass prepares a
120 // wake. The unlocked trigger is harmless while the first pass finishes.
121 const stats = await work
122 await direct.query(`DROP TRIGGER pause_coalesced ON "${schema}".subscriptions`)
123 await direct.query(`DROP FUNCTION "${schema}".pause_coalesced()`)
124 expect(stats.changes).toBe(12)
125 expect((await pool.query(`SELECT count(*) FROM "${schema}".stream_changes c JOIN "${schema}".streams s ON s.id = c.stream_id WHERE s.path = $1`, [path])).rows[0].count).toBe('1')
126 await maintain()
127 const value = await claim(name)
128 expect(value.streams.find((stream) => stream.path === path)?.tail_offset).toBe(tail)
129 expect((await ack(name, value, [{ stream: path, offset: tail }])).status).toBe(200)
130 await remove(name)
131})
132
133test('resumed multi-batch fan-out preserves appends needed by a newly registered lower UUID', async () => {
134 const name = 'fanout-cursor', path = 'fanout/source'
135 await request(path, 'PUT')
136 await createPull(name, 'fanout/*')
137 await maintain()
138 // Equivalent empty-tail registrations, seeded in one fixture transaction so
139 // this test exercises cursor recovery rather than 17 repetitions of setup.
140 await pool.query(`INSERT INTO "${schema}".subscriptions (id, tenant_id, name, config, config_hash, pattern_regex, public_base_url)
141 SELECT gen_random_uuid(), s.tenant_id, s.name || '-' || n, s.config, s.config_hash, s.pattern_regex, s.public_base_url
142 FROM "${schema}".subscriptions s CROSS JOIN generate_series(1,16) n WHERE s.name = $1`, [name])
143 try {
144 await request(path, 'POST', 'one')
145 const baseline = (await request(path, 'POST', 'two')).headers.get('Stream-Next-Offset')!
146 await handler.maintain({ maxChunks: 1, maxSubscriptionWork: 1 })
147 const pending = () => pool.query<{ count: string }>(`SELECT count(*) FROM "${schema}".stream_changes c JOIN "${schema}".streams s ON s.id = c.stream_id WHERE s.path = $1`, [path])
148 expect((await pending()).rows[0]!.count).toBe('2')
149 const lateId = '00000000-0000-4000-8000-000000000001'
150 const registryKey = `durable-streams:subscription-registry:"${schema}":a`
151 await transaction(pool, {}, async (client) => {
152 await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [registryKey])
153 await client.query(`INSERT INTO "${schema}".subscriptions (id, tenant_id, name, config, config_hash, pattern_regex, public_base_url, member_count)
154 SELECT $2, tenant_id, name || '-late', config, config_hash, pattern_regex, public_base_url, 1 FROM "${schema}".subscriptions WHERE name = $1`, [name, lateId])
155 await client.query(`INSERT INTO "${schema}".subscription_members (subscription_id,tenant_id,path,stream_id,glob_link,acked_offset)
156 SELECT $1, tenant_id,path,id,true,$2 FROM "${schema}".streams WHERE path = $3`, [lateId, baseline, path])
157 })
158 const tail = (await request(path, 'POST', 'three')).headers.get('Stream-Next-Offset')!
159 const fresh = server()
160 await fresh.maintain({ maxChunks: 1, maxSubscriptionWork: 1 })
161 // Completing the older partial fan-out must not consume either later
162 // record: the late UUID was deliberately below the persisted cursor.
163 expect((await pending()).rows[0]!.count).toBe('2')
164 for (let i = 0; i < 5; i++) await fresh.maintain({ maxChunks: 1, maxSubscriptionWork: 1 })
165 expect((await pending()).rows[0]!.count).toBe('0')
166 const late = await pool.query(`SELECT m.acked_offset, s.next_work_at IS NOT NULL OR s.current_wake IS NOT NULL AS scheduled
167 FROM "${schema}".subscriptions s JOIN "${schema}".subscription_members m ON m.subscription_id = s.id WHERE s.id = $1`, [lateId])
168 expect(late.rows).toEqual([{ acked_offset: baseline, scheduled: true }])
169 expect(tail).not.toBe(baseline)
170 } finally {
171 await pool.query(`UPDATE "${schema}".subscriptions SET deleted_at = clock_timestamp() WHERE name = $1 OR name LIKE $2`, [name, `${name}-%`])
172 subscriptions.delete(name)
173 }
174}, 180_000)
175
176test('registration backfill cannot be overtaken by dispatch when an append commits before registration does', async () => {
177 const source = 'barrier/x', name = 'registration-barrier'
178 await request(source, 'PUT', 'old')
179 const before = (await request(source, 'HEAD')).headers.get('Stream-Next-Offset')!
180 await maintain()
181 const gateKey = randomInt(1, 2_000_000_000)
182 const gate = await direct.connect()
183 await gate.query('SELECT pg_advisory_lock($1::bigint)', [gateKey])
184 await direct.query(`CREATE FUNCTION "${schema}".pause_backfill() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.path = 'barrier/x' THEN PERFORM pg_advisory_xact_lock(${gateKey}::bigint); END IF; RETURN NEW; END $$`)
185 await direct.query(`CREATE TRIGGER pause_backfill AFTER INSERT ON "${schema}".subscription_members FOR EACH ROW EXECUTE FUNCTION "${schema}".pause_backfill()`)
186 let registration: Promise<unknown> | undefined, dispatch: Promise<unknown> | undefined
187 try {
188 registration = createPull(name, 'barrier/*')
189 void registration.catch(() => {})
190 await poll(async () => Boolean((await pool.query(`SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND objid = $1::oid AND NOT granted`, [gateKey])).rowCount))
191 const append = await request(source, 'POST', ' new')
192 expect(append.status).toBe(204)
193 dispatch = maintain()
194 void dispatch.catch(() => {})
195 const registry = (await pool.query<{ key: string }>('SELECT hashtextextended($1,0) AS key', [`durable-streams:subscription-registry:"${schema}":a`])).rows[0]!.key
196 const unsigned = BigInt.asUintN(64, BigInt(registry))
197 await poll(async () => Boolean((await pool.query(`SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND classid = $1::oid AND objid = $2::oid AND mode = 'ShareLock' AND NOT granted`, [String(unsigned >> 32n), String(unsigned & 0xffffffffn)])).rowCount))
198 expect((await pool.query(`SELECT c.version FROM "${schema}".stream_changes c JOIN "${schema}".streams s ON s.id = c.stream_id WHERE s.path = $1 ORDER BY c.version DESC LIMIT 1`, [source])).rowCount).toBe(1)
199 } finally {
200 await gate.query('SELECT pg_advisory_unlock($1::bigint)', [gateKey]); gate.release()
201 await registration; await dispatch
202 await direct.query(`DROP TRIGGER pause_backfill ON "${schema}".subscription_members`)
203 await direct.query(`DROP FUNCTION "${schema}".pause_backfill()`)
204 }
205 await maintain()
206 const value = await claim(name)
207 expect(value.streams.find((stream) => stream.path === source)).toMatchObject({ acked_offset: before, has_pending: true })
208 expect(await (await request(source)).text()).toBe('old new')
209 await remove(name)
210})
211
212test('a late-committing earlier change is delivered after a later change was already processed', async () => {
213 const name = 'commit-order'
214 await request('ordering/a', 'PUT')
215 await request('ordering/b', 'PUT')
216 await createPull(name, 'ordering/*')
217 await maintain()
218 const entered = deferred(), resume = deferred()
219 const late = transaction(pool, { timeoutMs: 60_000 }, async (client) => {
220 const stream = (await client.query<{ id: string; tail_offset: string; change_version: string }>(`SELECT * FROM "${schema}".streams WHERE tenant_id = 'a' AND path = 'ordering/a' FOR NO KEY UPDATE`)).rows[0]!
221 const payload = Buffer.from('late commit'), next = advanceOffset(stream.tail_offset)
222 await client.query(`INSERT INTO "${schema}".appends (stream_id,start_offset,end_offset,payload,payload_bytes) VALUES ($1,$2,$3,$4,$5)`, [stream.id, stream.tail_offset, next, payload, payload.length])
223 await client.query(`UPDATE "${schema}".streams SET tail_offset = $2, change_version = change_version + 1, hot_frames = hot_frames + 1, hot_bytes = hot_bytes + $3 WHERE id = $1`, [stream.id, next, payload.length])
224 await client.query(`INSERT INTO "${schema}".stream_changes (stream_id,version,before_offset,after_offset,kind) VALUES ($1,$2,$3,$4,'appended')`, [stream.id, String(BigInt(stream.change_version) + 1n), stream.tail_offset, next])
225 entered.resolve(); await resume.promise
226 })
227 try {
228 await entered.promise
229 const later = await request('ordering/b', 'POST', 'commits first')
230 expect(later.status).toBe(204)
231 await maintain()
232 const first = await claim(name)
233 expect(first.streams.find((stream) => stream.path === 'ordering/a')?.has_pending).toBe(false)
234 expect((await ack(name, first, [{ stream: 'ordering/b', offset: later.headers.get('Stream-Next-Offset')! }])).status).toBe(200)
235 } finally { resume.resolve(); await late }
236 await maintain()
237 const second = await claim(name)
238 expect(second.generation).toBeGreaterThan(1)
239 expect(second.streams.find((stream) => stream.path === 'ordering/a')).toMatchObject({ has_pending: true, acked_offset: ZERO_OFFSET })
240 await remove(name)
241})
242
243test('synchronous webhook completion acks only its snapshot and wakes again for a concurrent append', async () => {
244 const name = 'snapshot-webhook', received = deferred(), release = deferred()
245 const webhook = await receiver(async (_notification, index) => { if (!index) { received.resolve(); await release.promise } return { done: true } })
246 await register(name, { type: 'webhook', pattern: 'snapshot-events/*', webhook: { url: webhook.url } })
247 const first = await request('snapshot-events/a', 'PUT', 'first')
248 const delivery = maintain()
249 let final: Response
250 try {
251 await received.promise
252 final = await request('snapshot-events/a', 'POST', ' second')
253 } finally { release.resolve() }
254 await delivery
255 await maintain()
256 expect(webhook.received).toHaveLength(2)
257 const next = webhook.received[1]!.body
258 expect(next.generation).toBeGreaterThan(webhook.received[0]!.body.generation)
259 expect(next.streams.find((stream) => stream.path === 'snapshot-events/a')).toMatchObject({ acked_offset: first.headers.get('Stream-Next-Offset'), tail_offset: final!.headers.get('Stream-Next-Offset') })
260 await remove(name); await webhook.close()
261})
262
263test('webhook retries honor a persisted deadline after a fresh handler and keep stable signing keys', async () => {
264 await maintain()
265 const name = 'retry-state'
266 const webhook = await receiver(async (_notification, index) => ({ status: index ? 200 : 500, done: Boolean(index) }))
267 const created = await register(name, { type: 'webhook', pattern: 'retry-events/*', webhook: { url: webhook.url } })
268 await request('retry-events/a', 'PUT', 'retry payload')
269 await handler.maintain({ maxChunks: 1, maxSubscriptionWork: 1 })
270 expect(webhook.received).toHaveLength(1)
271 await pool.query(`UPDATE "${schema}".subscriptions SET retry_at = clock_timestamp() + interval '30 seconds', next_work_at = clock_timestamp() + interval '30 seconds' WHERE name = $1`, [name])
272 const fresh = server()
273 await maintain(fresh)
274 expect(webhook.received).toHaveLength(1)
275 const metadata = await (await request(subPath(name))).json() as { status: string }
276 expect(metadata.status).toBe('failed')
277 await pool.query(`UPDATE "${schema}".subscriptions SET retry_at = clock_timestamp() - interval '1 second', next_work_at = clock_timestamp() - interval '1 second' WHERE name = $1`, [name])
278 await maintain(fresh)
279 expect(webhook.received).toHaveLength(2)
280 expect(webhook.received[1]!.body.callback_token).toBe(webhook.received[0]!.body.callback_token)
281 expect(webhook.received[1]!.signature).toContain(`kid=${created.webhook!.signing.kid},`)
282 const record = (await pool.query(`SELECT token_cipher FROM "${schema}".subscription_wakes w JOIN "${schema}".subscriptions s ON s.id = w.subscription_id WHERE s.name = $1`, [name])).rows[0]
283 expect((record.token_cipher as Buffer).includes(Buffer.from(webhook.received[1]!.body.callback_token))).toBe(false)
284 await remove(name); await webhook.close()
285})
286
287test('leases use database time, heartbeat, and generation fencing; invalid ack batches are atomic', async () => {
288 const name = 'lease-fences'
289 await createPull(name, 'leased/*', 5000)
290 const first = await request('leased/a', 'PUT', 'a')
291 await request('leased/b', 'PUT', 'b')
292 await maintain()
293 const value = await claim(name)
294 expect((await request(subPath(name, 'ack'), 'POST', JSON.stringify({ wake_id: value.wake_id, generation: value.generation, done: true }), { 'Content-Type': 'application/json' })).status).toBe(401)
295 expect((await request('leased/a', 'GET', undefined, { Authorization: `Bearer ${value.token}` })).status).toBe(401)
296 expect((await ack(name, value, [{ stream: 'leased/a', offset: first.headers.get('Stream-Next-Offset')! }, { stream: 'leased/b', offset: '9999999999999999_9999999999999999' }])).status).toBe(409)
297 const cursor = (await (await request(subPath(name))).json() as { streams: { acked_offset: string }[] }).streams
298 expect(cursor.every((stream) => stream.acked_offset === ZERO_OFFSET)).toBe(true)
299 const oldDeadline = (await pool.query(`SELECT lease_until FROM "${schema}".subscriptions WHERE name = $1`, [name])).rows[0].lease_until as Date
300 expect((await ack(name, value, [], false)).status).toBe(200)
301 const renewed = (await pool.query(`SELECT lease_until FROM "${schema}".subscriptions WHERE name = $1`, [name])).rows[0].lease_until as Date
302 expect(renewed.getTime()).toBeGreaterThan(oldDeadline.getTime())
303 await pool.query(`UPDATE "${schema}".subscriptions SET lease_until = clock_timestamp() - interval '1 second', next_work_at = clock_timestamp() - interval '1 second' WHERE name = $1`, [name])
304 expect((await ack(name, value, [], true)).status).toBe(409)
305 const replacement = await claim(name, 'replacement')
306 expect(replacement.generation).toBeGreaterThan(value.generation)
307 expect((await ack(name, value, [], true)).status).toBe(409)
308 await remove(name)
309 await register(name, { type: 'pull-wake', pattern: 'leased/*', wake_stream: `wake/${name}` })
310 expect((await ack(name, replacement, [], true)).status).toBe(409)
311 await remove(name)
312})
313
314test('quota-blocked glob discovery preserves the earliest cursor when capacity grows before the next append', async () => {
315 const name = 'quota-recovery', limited = server(1)
316 await createPull(name, 'quota-events/*', 30_000, limited)
317 await request('quota-events/a', 'PUT', 'one')
318 await maintain(limited)
319 const first = await claim(name, 'first', limited)
320 expect((await ack(name, first, first.streams.map((stream) => ({ stream: stream.path, offset: stream.tail_offset })), true, limited)).status).toBe(200)
321 await request('quota-events/b', 'PUT', 'earliest')
322 await maintain(limited)
323 expect((await (await request(subPath(name), 'GET', undefined, undefined, limited)).json() as { status: string }).status).toBe('failed')
324 await request('quota-events/b', 'POST', ' later')
325 const expanded = server(2)
326 await maintain(expanded)
327 const recovered = await claim(name, 'expanded', expanded)
328 expect(recovered.streams.find((stream) => stream.path === 'quota-events/b')).toMatchObject({ acked_offset: ZERO_OFFSET, has_pending: true })
329 expect(await (await request('quota-events/b')).text()).toBe('earliest later')
330 expect((await pool.query(`SELECT blocked_members FROM "${schema}".subscriptions WHERE name = $1`, [name])).rows[0].blocked_members).toBe(0)
331 await remove(name)
332})
333
334test('pull-wake appends are observable through actual Neon Realtime', async () => {
335 const name = 'realtime-wake'
336 const wake = await createPull(name, 'rt-events/*')
337 const response = await request(`${wake}?live=sse&offset=now`)
338 expect(response.status).toBe(200)
339 const reader = response.body!.getReader()
340 try {
341 expect(new TextDecoder().decode((await reader.read()).value)).toContain('event: control')
342 await request('rt-events/a', 'PUT', 'real wake')
343 await maintain()
344 let received = ''
345 while (!received.includes('"type":"wake"')) {
346 const chunk = await reader.read()
347 if (chunk.done) throw new Error('Wake SSE ended before the internal append')
348 received += new TextDecoder().decode(chunk.value)
349 }
350 expect(received).toContain(`"subscription_id":"${name}"`)
351 } finally { await reader.cancel(); reader.releaseLock() }
352 await remove(name)
353}, 45_000)
354
355test('signing-key rotation preserves old JWKS verification while new deliveries use the new key', async () => {
356 const name = 'signing-rotation'
357 const webhook = await receiver()
358 await register(name, { type: 'webhook', pattern: 'rotation-events/*', webhook: { url: webhook.url } })
359 await request('rotation-events/a', 'PUT', 'first')
360 await maintain()
361 const old = webhook.received[0]!
362 const next = await initializeSubscriptions(direct, { schema, keyring, rotateSigningKey: true })
363 await request('rotation-events/a', 'POST', ' second')
364 await maintain()
365 expect(webhook.received[1]!.signature).toContain(`kid=${next.kid},`)
366 const jwks = await (await request('__ds/jwks.json', 'GET', undefined, { Authorization: '' })).json() as { keys: { kid: string; kty: string; crv: string; x: string }[] }
367 const parameters = Object.fromEntries(old.signature.split(',').map((part) => { const n = part.indexOf('='); return [part.slice(0, n), part.slice(n + 1)] }))
368 const key = jwks.keys.find((key) => key.kid === parameters.kid)!
369 expect(key).toBeDefined()
370 expect(verify(null, Buffer.concat([Buffer.from(`${parameters.t}.`), old.raw]), createPublicKey({ key, format: 'jwk' }), Buffer.from(parameters.ed25519!, 'base64url'))).toBe(true)
371 expect(jwks.keys.every((key) => !('d' in key))).toBe(true)
372 await remove(name); await webhook.close()
373})
374
375test('acks validate inherited sealed frame boundaries before advancing a fork cursor', async () => {
376 const name = 'ack-boundaries'
377 await createPull(name, 'ack-child/*')
378 const first = await request('ack-source', 'PUT', 'abc')
379 await request('ack-source', 'POST', 'def')
380 expect((await request('ack-child/a', 'PUT', undefined, { 'Stream-Forked-From': '/v1/stream/ack-source' })).status).toBe(201)
381 await request('ack-source', 'DELETE')
382 await maintain()
383 const value = await claim(name)
384 expect((await ack(name, value, [{ stream: 'ack-child/a', offset: advanceOffset(ZERO_OFFSET) }])).status).toBe(409)
385 expect((await ack(name, value, [{ stream: 'ack-child/a', offset: first.headers.get('Stream-Next-Offset')! }], false)).status).toBe(200)
386 const body = await (await request(subPath(name))).json() as { streams: { acked_offset: string }[] }
387 expect(body.streams[0]!.acked_offset).toBe(first.headers.get('Stream-Next-Offset'))
388 await remove(name)
389})
390
391test('explicit and glob membership retain independent links and at-tail baselines', async () => {
392 const name = 'membership-modes'
393 const created = await request('member-events/a', 'PUT', 'history')
394 await register(name, { type: 'webhook', pattern: 'member-events/*', streams: ['member-events/a'], webhook: { url: 'http://127.0.0.1:9/unused' } })
395 expect((await request(subPath(name, `streams/${encodeURIComponent('member-events/a')}`), 'DELETE')).status).toBe(204)
396 const glob = await (await request(subPath(name))).json() as { streams: { path: string; link_type: string; acked_offset: string }[] }
397 expect(glob.streams).toEqual([{ path: 'member-events/a', link_type: 'glob', acked_offset: created.headers.get('Stream-Next-Offset') }])
398 expect((await request(subPath(name, 'streams'), 'POST', JSON.stringify({ streams: ['member-events/a'] }), { 'Content-Type': 'application/json' })).status).toBe(204)
399 const explicit = await (await request(subPath(name))).json() as { streams: { link_type: string; acked_offset: string }[] }
400 expect(explicit.streams[0]).toMatchObject({ link_type: 'explicit', acked_offset: created.headers.get('Stream-Next-Offset') })
401 expect((await request(subPath(name), 'GET', undefined, { Authorization: 'Bearer b' })).status).toBe(404)
402 await remove(name)
403})
404
405test('authorization sees the normalized selector and destination and can deny wake-stream writes', async () => {
406 let seen: AuthorizationContext | undefined
407 const restricted = server(1000, (context) => {
408 if (context.operation === 'subscribe') { seen = context; return context.subscription?.type !== 'webhook' }
409 return context.operation !== 'append' || context.path !== 'wake/forbidden'
410 })
411 const denied = await request(subPath('denied-destination'), 'PUT', JSON.stringify({ type: 'webhook', pattern: 'private/*', webhook: { url: 'http://127.0.0.1:9/denied' } }), { 'Content-Type': 'application/json' }, restricted)
412 expect(denied.status).toBe(403)
413 expect(seen?.subscription).toMatchObject({ pattern: 'private/*', webhook: { url: 'http://127.0.0.1:9/denied' } })
414 const noWrite = await request(subPath('denied-wake-write'), 'PUT', JSON.stringify({ type: 'pull-wake', pattern: 'private/*', wake_stream: 'wake/forbidden' }), { 'Content-Type': 'application/json' }, restricted)
415 expect(noWrite.status).toBe(403)
416 expect((await pool.query(`SELECT 1 FROM "${schema}".subscriptions WHERE name IN ('denied-destination','denied-wake-write')`)).rowCount).toBe(0)
417})