Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import pg from 'pg'
3import { afterAll, beforeAll, expect, test } from 'vitest'
4import fc from 'fast-check'
5import { createDurableStreams } from '../../src/index.js'
6import { migrate } from '../../src/migrations.js'
7import { postgresTestLimits } from '../fixtures/postgres-limits.js'
8
9if (!process.env.TEST_DATABASE_URL_UNPOOLED) throw new Error('Lifecycle tests require an isolated Neon database')
10const pool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL_UNPOOLED, max: 2 })
11pool.on('error', () => {})
12const schema = `ds_test_${randomUUID().replaceAll('-', '')}`
13const server = createDurableStreams({ postgres: { ...postgresTestLimits, pool, schema },
14 auth: { authenticate: () => ({ tenantId: 'lifecycle', subject: 'fixture' }), authorize: () => true } })
15const request = (path: string, method = 'GET', body?: string, headers?: Record<string, string>) => server.fetch(new Request(`https://fixture.test/v1/stream/${path}`, {
16 method, headers: { 'Content-Type': 'text/plain', ...headers }, ...(body === undefined ? {} : { body }),
17}))
18beforeAll(async () => { await migrate(pool, { schema }) })
19afterAll(async () => { await server.close(); await pool.query(`DROP SCHEMA "${schema}" CASCADE`); await pool.end() })
20
21test('Postgres rejects partial recovery operations and ownerless claims/leases', async () => {
22 const sql = (text: string, values?: unknown[]) => pool.query(text.replaceAll('ds.', `"${schema}".`), values)
23 await expect(sql("UPDATE ds.installation SET serving_state='recovering'")).rejects.toMatchObject({ code: '23514' })
24 await expect(sql('UPDATE ds.installation SET recovery_verified=-1')).rejects.toMatchObject({ code: '23514' })
25 const id = randomUUID()
26 await sql(`INSERT INTO ds.subscriptions(id,tenant_id,name,config,config_hash,public_base_url)
27 VALUES($1,'lifecycle','constraints','{}','fixture','https://fixture.test/v1/stream')`, [id])
28 await expect(sql("UPDATE ds.subscriptions SET holder='worker' WHERE id=$1", [id])).rejects.toMatchObject({ code: '23514' })
29 await expect(sql("UPDATE ds.subscriptions SET holder='worker',lease_until=clock_timestamp() WHERE id=$1", [id])).rejects.toMatchObject({ code: '23514' })
30 await expect(sql(`INSERT INTO ds.subscription_wakes(id,subscription_id,tenant_id,generation,kind,state,delivery_claim)
31 VALUES($1,$2,'lifecycle',1,'webhook','ready',$1)`, [randomUUID(), id])).rejects.toMatchObject({ code: '23514' })
32 await expect(sql(`INSERT INTO ds.chunk_objects(object_key,stream_id,chunk_id,sha256,encoded_bytes,claim_token)
33 VALUES('constraint',$1,$1,$2,1,$1)`, [randomUUID(), '0'.repeat(64)])).rejects.toMatchObject({ code: '23514' })
34 expect((await request('constraint-chunk', 'PUT', 'x')).status).toBe(201)
35 const stream = (await sql("SELECT id FROM ds.streams WHERE path='constraint-chunk'")).rows[0].id
36 await expect(sql(`INSERT INTO ds.chunks(id,stream_id,start_offset,end_offset,state,frame_count,payload_bytes,claim_token)
37 VALUES($1,$2,'0000000000000000_0000000000000000','0000000000000000_0000000000000006','frozen',1,1,$1)`, [randomUUID(), stream])).rejects.toMatchObject({ code: '23514' })
38 const removed = await sql(`SELECT column_name FROM information_schema.columns
39 WHERE table_schema=$1 AND column_name IN ('processed','pull_published')`, [schema])
40 expect(removed.rows).toEqual([])
41})
42
43test('generated append, close, delete, and recreation sequences preserve bytes and generation boundaries on Neon', async () => {
44 await fc.assert(fc.asyncProperty(fc.array(fc.constantFrom('append', 'close', 'delete', 'create', 'read'), { minLength: 8, maxLength: 18 }), async (commands) => {
45 const path = `generated-${randomUUID()}`
46 let exists = true, closed = false, bytes = ''
47 expect((await request(path, 'PUT')).status).toBe(201)
48 for (const command of commands) {
49 if (command === 'create') {
50 const response = await request(path, 'PUT')
51 expect(response.status).toBe(exists ? closed ? 409 : 200 : 201)
52 if (!exists) { exists = true; closed = false; bytes = '' }
53 } else if (command === 'delete') {
54 expect((await request(path, 'DELETE')).status).toBe(exists ? 204 : 404)
55 exists = false
56 } else if (command === 'append') {
57 expect((await request(path, 'POST', 'x')).status).toBe(!exists ? 404 : closed ? 409 : 204)
58 if (exists && !closed) bytes += 'x'
59 } else if (command === 'close' && exists && !closed) {
60 expect((await request(path, 'POST', '', { 'Stream-Closed': 'true' })).status).toBe(204)
61 closed = true
62 }
63 const replay = await request(path)
64 expect(replay.status).toBe(exists ? 200 : 404)
65 if (exists) { expect(await replay.text()).toBe(bytes); expect(replay.headers.has('Stream-Closed')).toBe(closed) }
66 }
67 }), { numRuns: 8, seed: 20261123 })
68})