Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

storage.test.ts

257 lines15.5 KB

1import { postgresTestLimits } from '../fixtures/postgres-limits.js'
2import { randomUUID } from 'node:crypto'
3import { fork } from 'node:child_process'
4import { once } from 'node:events'
5import { fileURLToPath } from 'node:url'
6import pg from 'pg'
7import { afterAll, beforeAll, describe, expect, test } from 'vitest'
8import { createDurableStreams } from '../../src/index.js'
9import type { DurableStreamsServer } from '../../src/index.js'
10import { MIGRATION_IDS, migrate, STORAGE_VERSION } from '../../src/migrations.js'
11import { transaction } from '../../src/transaction.js'
12​
13const database = process.env.TEST_DATABASE_URL
14if (!database) throw new Error('Provision an isolated Neon test environment; see docs/development.md')
15const pool = new pg.Pool({ connectionString: database, max: 8, connectionTimeoutMillis: 120_000 })
16const migrationPool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL_UNPOOLED ?? database, max: 6, connectionTimeoutMillis: 15000 })
17pool.on('error', () => {})
18migrationPool.on('error', () => {})
19const schema = `ds_test_${randomUUID().replaceAll('-', '')}`
20const errors: unknown[] = []
21const config = { postgres: { ...postgresTestLimits, pool, schema }, auth: {
22 authenticate(request: Request) {
23 const identities = new Map([['Bearer a', 'tenant-a'], ['Bearer b', 'tenant-b']])
24 const tenantId = identities.get(request.headers.get('authorization') ?? '')
25 return tenantId ? { tenantId, subject: 'test-user' } : null
26 }, authorize: () => true,
27}, onError: (error: unknown) => errors.push(error) }
28let server: DurableStreamsServer
29​
30async function request(path: string, method = 'GET', body?: string | Uint8Array, headers: Record<string, string> = {}) {
31 const requestHeaders = new Headers({ Authorization: 'Bearer a', ...headers })
32 if ((body !== undefined || method === 'PUT') && !requestHeaders.has('content-type')) requestHeaders.set('content-type', 'text/plain')
33 const init: RequestInit = { method, headers: requestHeaders }
34 if (body !== undefined) init.body = typeof body === 'string' ? body : new Uint8Array(body)
35 return server.fetch(new Request(`https://example.test/v1/stream/${path}`, init))
37​
38async function readAll(path: string) {
39 let offset = '-1'
40 const parts: string[] = []
41 for (let i = 0; i < 100; i++) {
42 const response = await request(`${path}?offset=${offset}`)
43 expect(response.status).toBe(200)
44 parts.push(await response.text())
45 if (response.headers.get('stream-up-to-date') === 'true') return parts.join('')
46 offset = response.headers.get('stream-next-offset')!
47 }
48 throw new Error('Replay failed to converge')
50​
51beforeAll(async () => {
52 const version = await pool.query<{ version: string }>("SELECT current_setting('server_version_num') AS version")
53 expect(Number(version.rows[0]!.version)).toBeGreaterThanOrEqual(180000)
54 expect(await migrate(migrationPool, { schema })).toEqual([...MIGRATION_IDS])
55 expect(await migrate(migrationPool, { schema })).toEqual([])
56 server = createDurableStreams(config)
57})
58​
59afterAll(async () => {
60 await server?.close()
61 if (!schema.startsWith('ds_test_')) throw new Error('Refusing to drop a non-test schema')
62 await pool.query(`DROP SCHEMA "${schema}" CASCADE`)
63 await pool.end()
64 await migrationPool.end()
65 expect(errors).toEqual([])
66})
67​
68describe('transaction and migration guarantees', () => {
69 test('concurrent migrators initialize an installation once', async () => {
70 const other = `${schema}_migration`
71 try {
72 const outcomes = await Promise.all(Array.from({ length: 6 }, () => migrate(migrationPool, { schema: other })))
73 expect(outcomes.filter((value) => value.length)).toHaveLength(1)
74 expect((await pool.query(`SELECT count(*) FROM "${other}".installation`)).rows[0].count).toBe('1')
75 } finally { await pool.query(`DROP SCHEMA IF EXISTS "${other}" CASCADE`) }
76 })
77 test('local durability and timeout settings override inherited sessions and revert', async () => {
78 const one = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL_UNPOOLED ?? database!, max: 1 })
79 try {
80 await one.query("SET synchronous_commit = off; SET statement_timeout = 0")
81 await transaction(one, {}, async (client) => {
82 const result = await client.query<{ synchronous_commit: string; statement_timeout: string }>('SHOW synchronous_commit; SHOW statement_timeout')
83 const results = result as unknown as pg.QueryResult[]
84 expect(results[0]!.rows[0]).toEqual({ synchronous_commit: 'on' })
85 expect(results[1]!.rows[0]).toEqual({ statement_timeout: '10s' })
86 })
87 expect((await one.query('SHOW synchronous_commit')).rows[0]).toEqual({ synchronous_commit: 'off' })
88 } finally { await one.end() }
89 })
90 test('failed work rolls back the entire transaction', async () => {
91 await expect(transaction(pool, {}, async (client) => {
92 await client.query(`INSERT INTO "${schema}".paths (tenant_id, path) VALUES ('test', 'rolled-back')`)
93 throw new Error('simulated interruption')
94 })).rejects.toThrow('simulated interruption')
95 expect((await pool.query(`SELECT 1 FROM "${schema}".paths WHERE path = 'rolled-back'`)).rowCount).toBe(0)
96 })
97 test('unknown migration history blocks migration and preserves existing data', async () => {
98 await pool.query(`INSERT INTO "${schema}".migrations (id, checksum) VALUES ('9999_future', 'unknown')`)
99 await expect(migrate(pool, { schema })).rejects.toThrow('Unknown or modified')
100 await pool.query(`DELETE FROM "${schema}".migrations WHERE id = '9999_future'`)
101 })
102 test('an existing installation identity cannot be silently regenerated', async () => {
103 const prior = (await pool.query(`SELECT id FROM "${schema}".installation`)).rows[0].id as string
104 await pool.query(`DELETE FROM "${schema}".installation`)
105 try { await expect(migrate(pool, { schema })).rejects.toThrow('explicit recovery') }
106 finally { await pool.query(`INSERT INTO "${schema}".installation (id, storage_version) VALUES ($1, $2)`, [prior, STORAGE_VERSION]) }
107 })
108})
109​
110describe('durable HTTP hot log', () => {
111 test('concurrent creates establish exactly one stream identity', async () => {
112 const responses = await Promise.all(Array.from({ length: 24 }, () => request('create-race', 'PUT')))
113 expect(responses.filter((r) => r.status === 201)).toHaveLength(1)
114 expect(responses.filter((r) => r.status === 200)).toHaveLength(23)
115 expect((await pool.query(`SELECT count(*) FROM "${schema}".streams WHERE path = 'create-race'`)).rows[0].count).toBe('1')
116 })
117 test('concurrent duplicate producer retries append exactly once and create one change', async () => {
118 await request('dedup', 'PUT')
119 const headers = { 'Producer-Id': 'writer', 'Producer-Epoch': '0', 'Producer-Seq': '0' }
120 const responses = await Promise.all(Array.from({ length: 24 }, () => request('dedup', 'POST', 'once', headers)))
121 expect(responses.filter((r) => r.status === 200)).toHaveLength(1)
122 expect(responses.filter((r) => r.status === 204)).toHaveLength(23)
123 expect(await readAll('dedup')).toBe('once')
124 const outbox = await pool.query(`SELECT c.* FROM "${schema}".stream_changes c JOIN "${schema}".streams s ON s.id = c.stream_id WHERE s.path = 'dedup' ORDER BY version`)
125 expect(outbox.rows.map((r) => r.kind)).toEqual(['created', 'appended'])
126 })
127 test('sequence gaps and stale epochs do not mutate data', async () => {
128 await request('fencing', 'PUT')
129 const base = { 'Producer-Id': 'writer', 'Producer-Epoch': '2', 'Producer-Seq': '0' }
130 expect((await request('fencing', 'POST', 'a', base)).status).toBe(200)
131 const gap = await request('fencing', 'POST', 'bad', { ...base, 'Producer-Seq': '2' })
132 expect(gap.status).toBe(409)
133 expect(gap.headers.get('producer-expected-seq')).toBe('1')
134 expect((await request('fencing', 'POST', 'bad', { ...base, 'Producer-Epoch': '1' })).status).toBe(403)
135 expect(await readAll('fencing')).toBe('a')
136 })
137 test('JSON failure does not advance producer state and numbers retain precision', async () => {
138 await request('json', 'PUT', '[]', { 'Content-Type': 'application/json' })
139 const headers = { 'Content-Type': 'application/json', 'Producer-Id': 'json-writer', 'Producer-Epoch': '0', 'Producer-Seq': '0' }
140 expect((await request('json', 'POST', '{bad', headers)).status).toBe(400)
141 expect((await request('json', 'POST', '[9007199254740993,[1,2]]', headers)).status).toBe(200)
142 expect(await readAll('json')).toBe('[9007199254740993,[1,2]]')
143 })
144 test('replay survives a new pool and server instance', async () => {
145 await request('restart', 'PUT', 'persisted')
146 const freshPool = new pg.Pool({ connectionString: database! })
147 const fresh = createDurableStreams({ ...config, postgres: { ...postgresTestLimits, pool: freshPool, schema } })
148 try {
149 const response = await fresh.fetch(new Request('https://example.test/v1/stream/restart', { headers: { Authorization: 'Bearer a' } }))
150 expect(response.status).toBe(200)
151 expect(await response.text()).toBe('persisted')
152 await fresh.close()
153 expect((await freshPool.query('SELECT 1 AS alive')).rows[0].alive).toBe(1)
154 } finally { await fresh.close(); await freshPool.end() }
155 })
156 test.each(['committed', 'uncommitted'])('SIGKILL of a writer preserves the %s transaction outcome', async (mode) => {
157 const child = fork(fileURLToPath(new URL('../fixtures/crash-worker.mjs', import.meta.url)), [mode], {
158 execArgv: [], env: { ...process.env, TEST_SCHEMA: schema }, stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
159 })
160 let stderr = ''
161 child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
162 try {
163 const message = await Promise.race([
164 once(child, 'message').then(([value]) => value as { ready: boolean }),
165 once(child, 'exit').then(() => { throw new Error(`Writer exited before test barrier: ${stderr}`) }),
166 ])
167 expect(message.ready).toBe(true)
168 } finally {
169 if (child.exitCode === null && child.signalCode === null) {
170 const exited = once(child, 'exit')
171 child.kill('SIGKILL')
172 await exited
173 }
174 }
175 if (mode === 'committed') expect(await readAll('crash-committed')).toBe('acknowledged bytes')
176 else {
177 expect((await pool.query(`SELECT 1 FROM "${schema}".paths WHERE path = 'crash-uncommitted'`)).rowCount).toBe(0)
178 expect((await request('crash-uncommitted', 'PUT', 'new transaction')).status).toBe(201)
179 }
180 })
181 test('pages across complete frames and resumes without gaps', async () => {
182 await request('pages', 'PUT')
183 const frames = Array.from({ length: 40 }, (_, i) => `frame-${i}|`)
184 for (const frame of frames) expect((await request('pages', 'POST', frame)).status).toBe(204)
185 expect(await readAll('pages')).toBe(frames.join(''))
186 })
187 test('closing changes the ETag and deduplicates its producer tuple', async () => {
188 await request('closed', 'PUT', 'start')
189 const before = await request('closed')
190 const headers = { 'Producer-Id': 'closer', 'Producer-Epoch': '0', 'Producer-Seq': '0', 'Stream-Closed': 'true' }
191 expect((await request('closed', 'POST', 'end', headers)).status).toBe(200)
192 expect((await request('closed', 'POST', 'different body', headers)).status).toBe(204)
193 const closed = await request('closed', 'GET', undefined, { 'If-None-Match': before.headers.get('etag')! })
194 expect(closed.status).toBe(200)
195 expect(closed.headers.get('stream-closed')).toBe('true')
196 expect(await closed.text()).toBe('startend')
197 expect((await request('closed', 'GET', undefined, { 'If-None-Match': closed.headers.get('etag')! })).status).toBe(304)
198 expect((await request('closed', 'POST', 'rejected')).status).toBe(409)
199 })
200 test('delete/recreate isolates producer state, bytes, ETags, and identities', async () => {
201 await request('recreate', 'PUT', 'old')
202 const old = await request('recreate')
203 expect((await request('recreate', 'DELETE')).status).toBe(204)
204 expect((await request('recreate', 'PUT', 'new')).status).toBe(201)
205 const fresh = await request('recreate')
206 expect(await fresh.text()).toBe('new')
207 expect(fresh.headers.get('etag')).not.toBe(old.headers.get('etag'))
208 expect((await pool.query(`SELECT count(*) FROM "${schema}".streams WHERE path = 'recreate'`)).rows[0].count).toBe('2')
209 })
210 test('expiry commits its lifecycle change; HEAD never touches access time', async () => {
211 await request('ttl', 'PUT', undefined, { 'Stream-TTL': '60' })
212 const initial = await pool.query(`SELECT accessed_at FROM "${schema}".streams WHERE path = 'ttl'`)
213 expect((await request('ttl', 'HEAD')).status).toBe(200)
214 expect((await pool.query(`SELECT accessed_at FROM "${schema}".streams WHERE path = 'ttl'`)).rows[0]).toEqual(initial.rows[0])
215 await pool.query(`UPDATE "${schema}".streams SET accessed_at = clock_timestamp() - interval '61 seconds' WHERE path = 'ttl'`)
216 expect((await request('ttl')).status).toBe(404)
217 expect((await pool.query(`SELECT active_stream_id FROM "${schema}".paths WHERE path = 'ttl'`)).rows[0].active_stream_id).toBeNull()
218 expect((await request('ttl', 'PUT')).status).toBe(201)
219 })
220 test('tenant identity isolates a shared URL and authentication precedes body parsing', async () => {
221 await request('private', 'PUT', 'a')
222 expect((await request('private', 'GET', undefined, { Authorization: 'Bearer b' })).status).toBe(404)
223 expect((await request('private', 'POST', 'x', { Authorization: 'bad', 'Content-Length': '999999999' })).status).toBe(401)
224 })
225 test('unsupported reserved features fail explicitly and never create streams', async () => {
226 expect((await request('__ds/subscriptions/sub', 'PUT', '{}')).status).toBe(501)
227 expect((await request('fork', 'PUT', undefined, { 'Stream-Fork-Sub-Offset': '0' })).status).toBe(400)
228 expect((await request('private?offset=-1&live=sse')).status).toBe(503)
229 expect((await request('fork', 'HEAD')).status).toBe(404)
230 })
231 test('unknown methods cannot fall through to reads and invalid calendar expiry is rejected', async () => {
232 const unknown = await server.fetch(new Request('https://example.test/v1/stream/private', { method: 'constructor', headers: { Authorization: 'Bearer a' } }))
233 expect(unknown.status).toBe(405)
234 expect((await request('invalid-date', 'PUT', undefined, { 'Stream-Expires-At': '2027-02-30T00:00:00Z' })).status).toBe(400)
235 expect((await request('invalid-date', 'HEAD')).status).toBe(404)
236 })
237 test('streamed bodies are byte-limited even when Content-Length understates their size', async () => {
238 const limited = createDurableStreams({ ...config, limits: { maxAppendBytes: 16 } })
239 try {
240 const body = new ReadableStream<Uint8Array>({ start(controller) { controller.enqueue(new Uint8Array(32)); controller.close() } })
241 const init: RequestInit & { duplex: 'half' } = { method: 'PUT', headers: { Authorization: 'Bearer a', 'Content-Length': '1' }, body, duplex: 'half' }
242 expect((await limited.fetch(new Request('https://example.test/v1/stream/oversized', init))).status).toBe(413)
243 expect((await request('oversized', 'HEAD')).status).toBe(404)
244 } finally { await limited.close() }
245 })
246 test('a stalled body is canceled and never creates a stream', async () => {
247 let canceled = false
248 const limited = createDurableStreams({ ...config, limits: { bodyTimeoutMs: 10 } })
249 try {
250 const body = new ReadableStream<Uint8Array>({ cancel() { canceled = true } })
251 const init: RequestInit & { duplex: 'half' } = { method: 'PUT', headers: { Authorization: 'Bearer a' }, body, duplex: 'half' }
252 expect((await limited.fetch(new Request('https://example.test/v1/stream/stalled', init))).status).toBe(408)
253 expect(canceled).toBe(true)
254 expect((await request('stalled', 'HEAD')).status).toBe(404)
255 } finally { await limited.close() }
256 })
257})