Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import pg from 'pg'
3import { afterAll, beforeAll, expect, test } from 'vitest'
4import { createDurableStreams } from '../../src/index.js'
5import type { ChunkStorage, DurableStreamsServer } from '../../src/index.js'
6import { migrate } from '../../src/migrations.js'
7import { createS3ChunkStorage } from '../../src/s3.js'
8import { advanceOffset, ZERO_OFFSET } from '../../src/offset.js'
9import { transaction } from '../../src/transaction.js'
10import { initializeSubscriptions, parseSubscriptionKeyring } from '../../src/subscriptions.js'
11import { postgresTestLimits } from '../fixtures/postgres-limits.js'
12
13const env = process.env
14if (
15 !env.TEST_DATABASE_URL ||
16 !env.TEST_DATABASE_URL_UNPOOLED ||
17 !env.AWS_ENDPOINT_URL_S3 ||
18 !env.AWS_REGION ||
19 !env.NEON_TEST_BUCKET ||
20 !env.DURABLE_STREAMS_KEYRING
21)
22 throw new Error('Compact storage qualification requires actual Neon')
23const schema = `ds_test_${randomUUID().replaceAll('-', '')}`
24const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL, max: 6 }),
25 direct = new pg.Pool({ connectionString: env.TEST_DATABASE_URL_UNPOOLED, max: 2 })
26pool.on('error', () => {})
27direct.on('error', () => {})
28const objects = createS3ChunkStorage({ endpoint: env.AWS_ENDPOINT_URL_S3, region: env.AWS_REGION, bucket: env.NEON_TEST_BUCKET })
29const keyring = parseSubscriptionKeyring(env.DURABLE_STREAMS_KEYRING),
30 servers: DurableStreamsServer[] = [],
31 errors: unknown[] = []
32function server(storage: ChunkStorage = objects, maxChunkAgeMs = 3_600_000, cacheBytes = 32 * 1024 * 1024) {
33 const value = createDurableStreams({
34 postgres: { ...postgresTestLimits, pool, schema },
35 storage: { objects: storage, maxChunkAgeMs, cacheBytes, maxChunkFrames: 1024 },
36 subscriptions: { keyring },
37 auth: { authenticate: () => ({ tenantId: 'compact', subject: 'fixture' }), authorize: () => true },
38 onError: (error) => errors.push(error),
39 })
40 servers.push(value)
41 return value
42}
43const request = (value: DurableStreamsServer, path: string, method = 'GET', body?: string, headers: Record<string, string> = {}) =>
44 value.fetch(
45 new Request(`https://fixture.test/v1/stream/${path}`, {
46 method,
47 headers: { 'Content-Type': 'text/plain', ...headers },
48 ...(body === undefined ? {} : { body }),
49 }),
50 )
51beforeAll(async () => {
52 await migrate(direct, { schema, storageIdentity: objects.identity })
53 await initializeSubscriptions(direct, { schema, keyring })
54})
55afterAll(async () => {
56 await Promise.all(servers.map((value) => value.close()))
57 objects.close()
58 await direct.query(`DROP SCHEMA "${schema}" CASCADE`)
59 await pool.end()
60 await direct.end()
61 expect(errors).toEqual([])
62})
63
64test('1024 variable-size frames seal without retained rows; one replay page fetches one verified object', async () => {
65 const writer = server()
66 expect((await request(writer, 'packed', 'PUT')).status).toBe(201)
67 const id = (await pool.query(`SELECT id FROM "${schema}".streams WHERE path='packed'`)).rows[0].id
68 const parts = Array.from({ length: 1023 }, (_, i) => String.fromCharCode(97 + (i % 26)).repeat((i % 23) + 1)),
69 offsets = [ZERO_OFFSET]
70 for (let index = 0; index < 1024; index++) offsets.push(advanceOffset(offsets.at(-1)!, id.replaceAll('-', '')))
71 await transaction(pool, {}, async (client) => {
72 await client.query(
73 `INSERT INTO "${schema}".appends(stream_id,start_offset,end_offset,payload,payload_bytes)
74 SELECT $1,x.start,x.end,decode(x.payload,'hex'),x.bytes FROM jsonb_to_recordset($2::jsonb) x(start text,"end" text,payload text,bytes integer)`,
75 [
76 id,
77 JSON.stringify(
78 parts.map((part, i) => ({ start: offsets[i], end: offsets[i + 1], payload: Buffer.from(part).toString('hex'), bytes: part.length })),
79 ),
80 ],
81 )
82 await client.query(`UPDATE "${schema}".streams SET tail_offset=$2,hot_frames=1023,hot_bytes=$3 WHERE id=$1`, [
83 id,
84 offsets[1023],
85 parts.join('').length,
86 ])
87 await client.query(`INSERT INTO "${schema}".hot_chunks VALUES($1,clock_timestamp()+interval '1 hour')`, [id])
88 })
89 expect((await request(writer, 'packed', 'POST', 'last')).status).toBe(204)
90 expect((await writer.maintain()).sealed).toBe(1)
91 expect((await pool.query(`SELECT count(*) FROM "${schema}".appends WHERE stream_id=$1`, [id])).rows[0].count).toBe('0')
92 const manifest = (await pool.query(`SELECT frame_count,block_directory FROM "${schema}".chunks WHERE stream_id=$1`, [id])).rows[0]
93 expect(manifest.frame_count).toBe(1024)
94 expect(manifest.block_directory.byteLength).toBeLessThan(512)
95 let gets = 0
96 const reader = server({
97 ...objects,
98 async get(key, max) {
99 gets++
100 return objects.get(key, max)
101 },
102 })
103 let cursor = '-1',
104 actual = '',
105 pages = 0
106 do {
107 const response = await request(reader, `packed?offset=${cursor}`)
108 expect(response.status).toBe(200)
109 actual += await response.text()
110 pages++
111 cursor = response.headers.get('Stream-Next-Offset')!
112 if (response.headers.has('Stream-Up-To-Date')) break
113 } while (pages < 10)
114 expect(actual).toBe(parts.join('') + 'last')
115 expect(pages).toBe(1)
116 expect(gets).toBe(1)
117 const invalid = offsets[1]!.slice(0, 17) + 'f'.repeat(32)
118 expect(offsets).not.toContain(invalid)
119 expect((await request(reader, `packed?offset=${invalid}`)).status).toBe(400)
120 const forkHeaders = { 'Stream-Forked-From': '/v1/stream/packed', 'Stream-Fork-Offset': offsets[300]! }
121 expect((await request(reader, 'child', 'PUT', undefined, forkHeaders)).status).toBe(201)
122 expect(
123 (
124 await request(reader, 'grandchild', 'PUT', undefined, {
125 ...forkHeaders,
126 'Stream-Forked-From': '/v1/stream/child',
127 'Stream-Fork-Offset': offsets[100]!,
128 })
129 ).status,
130 ).toBe(201)
131 expect((await request(reader, 'packed', 'DELETE')).status).toBe(204)
132 expect(await (await request(reader, 'grandchild')).text()).toBe(parts.slice(0, 100).join(''))
133 // Cache eviction/restart is never required for correctness.
134 const cold = server(objects, 3_600_000, 0)
135 expect(await (await request(cold, `child?offset=${offsets[256]}`)).text()).toBe(parts.slice(256, 300).join(''))
136})
137
138test('normal cron passes preserve small tails; first-append age and explicit drain seal them', async () => {
139 const value = server()
140 await request(value, 'age', 'PUT', 'first')
141 const due = (await pool.query(`SELECT h.due_at FROM "${schema}".hot_chunks h JOIN "${schema}".streams s ON s.id=h.stream_id WHERE s.path='age'`))
142 .rows[0].due_at
143 for (let i = 0; i < 3; i++) await value.maintain()
144 expect(
145 (await pool.query(`SELECT count(*) FROM "${schema}".chunks c JOIN "${schema}".streams s ON s.id=c.stream_id WHERE s.path='age'`)).rows[0].count,
146 ).toBe('0')
147 await request(value, 'age', 'POST', 'second')
148 expect(
149 (await pool.query(`SELECT h.due_at FROM "${schema}".hot_chunks h JOIN "${schema}".streams s ON s.id=h.stream_id WHERE s.path='age'`)).rows[0]
150 .due_at,
151 ).toEqual(due)
152 await pool.query(
153 `UPDATE "${schema}".hot_chunks SET due_at=clock_timestamp()-interval '1 second' WHERE stream_id=(SELECT id FROM "${schema}".streams WHERE path='age')`,
154 )
155 expect((await value.maintain()).sealed).toBe(1)
156 expect(await (await request(value, 'age')).text()).toBe('firstsecond')
157 await request(value, 'drain', 'PUT', 'tiny')
158 expect((await value.maintain({ forceHot: true })).sealed).toBe(1)
159})
160
161test('an ordinary append updates its stream head once and leaves the due record unchanged', async () => {
162 const value = server()
163 await request(value, 'head-updates', 'PUT', 'initial;')
164 const id = (await pool.query(`SELECT id FROM "${schema}".streams WHERE path='head-updates'`)).rows[0].id
165 await direct.query(`CREATE TABLE "${schema}".head_audit(id uuid);
166 CREATE FUNCTION "${schema}".audit_head() RETURNS trigger LANGUAGE plpgsql AS $fn$ BEGIN INSERT INTO "${schema}".head_audit VALUES(NEW.id);RETURN NEW;END $fn$;
167 CREATE TRIGGER audit_head AFTER UPDATE ON "${schema}".streams FOR EACH ROW EXECUTE FUNCTION "${schema}".audit_head()`)
168 try {
169 const due = (await pool.query(`SELECT xmin,due_at FROM "${schema}".hot_chunks WHERE stream_id=$1`, [id])).rows[0]
170 expect((await request(value, 'head-updates', 'POST', 'ordinary;')).status).toBe(204)
171 expect((await pool.query(`SELECT count(*) FROM "${schema}".head_audit WHERE id=$1`, [id])).rows[0].count).toBe('1')
172 expect((await pool.query(`SELECT xmin,due_at FROM "${schema}".hot_chunks WHERE stream_id=$1`, [id])).rows[0]).toEqual(due)
173 } finally {
174 await direct.query(`DROP TRIGGER audit_head ON "${schema}".streams;DROP FUNCTION "${schema}".audit_head();DROP TABLE "${schema}".head_audit`)
175 }
176})
177
178test('atomic ack batches validate sealed interior boundaries, inherited ranges and post-snapshot appends', async () => {
179 const value = server(),
180 json = { 'Content-Type': 'application/json' }
181 for (const path of ['acks/a', 'acks/b']) await request(value, path, 'PUT')
182 await request(value, 'acks/wake', 'PUT', '[]', json)
183 const sub = '__ds/subscriptions/packed'
184 expect(
185 (
186 await request(
187 value,
188 sub,
189 'PUT',
190 JSON.stringify({ type: 'pull-wake', streams: ['acks/a', 'acks/b'], wake_stream: 'acks/wake', lease_ttl_ms: 600_000 }),
191 json,
192 )
193 ).status,
194 ).toBe(201)
195 const anchors: Record<string, string> = {}
196 for (const path of ['acks/a', 'acks/b']) {
197 const response = await request(value, path, 'POST', 'first;')
198 anchors[path] = response.headers.get('Stream-Next-Offset')!
199 await request(value, path, 'POST', 'second;')
200 }
201 await value.maintain({ forceHot: true })
202 const claim = (await (await request(value, `${sub}/claim`, 'POST', '{"worker":"fixture"}', json)).json()) as {
203 token: string
204 wake_id: string
205 generation: number
206 }
207 const auth = { ...json, Authorization: `Bearer ${claim.token}` }
208 const before = (await pool.query(`SELECT path,acked_offset FROM "${schema}".subscription_members ORDER BY path`)).rows
209 const body = (acks: unknown[]) => JSON.stringify({ wake_id: claim.wake_id, generation: claim.generation, acks })
210 expect(
211 (
212 await request(
213 value,
214 `${sub}/ack`,
215 'POST',
216 body([
217 { stream: 'acks/a', offset: anchors['acks/a'] },
218 { stream: 'acks/b', offset: advanceOffset(ZERO_OFFSET) },
219 ]),
220 auth,
221 )
222 ).status,
223 ).toBe(409)
224 expect((await pool.query(`SELECT path,acked_offset FROM "${schema}".subscription_members ORDER BY path`)).rows).toEqual(before)
225 const late = (await request(value, 'acks/a', 'POST', 'later;')).headers.get('Stream-Next-Offset')!
226 await request(value, 'acks/a', 'POST', 'tail;')
227 await value.maintain({ forceHot: true })
228 expect(
229 (
230 await request(
231 value,
232 `${sub}/ack`,
233 'POST',
234 body([
235 { stream: 'acks/a', offset: late },
236 { stream: 'acks/b', offset: anchors['acks/b'] },
237 ]),
238 auth,
239 )
240 ).status,
241 ).toBe(200)
242 expect((await pool.query(`SELECT acked_offset FROM "${schema}".subscription_members WHERE path='acks/a'`)).rows[0].acked_offset).toBe(late)
243 expect(
244 (await request(value, 'acks/child', 'PUT', undefined, { 'Stream-Forked-From': '/v1/stream/acks/a', 'Stream-Fork-Offset': anchors['acks/a']! }))
245 .status,
246 ).toBe(201)
247 expect(await (await request(value, 'acks/child')).text()).toBe('first;')
248})
249
250test('explicitly enabling object storage enrolls existing hot-only tails and fences the old binding', async () => {
251 const isolated = `ds_test_${randomUUID().replaceAll('-', '')}`
252 const auth = { authenticate: () => ({ tenantId: 'compact', subject: 'fixture' }), authorize: () => true }
253 const hot = createDurableStreams({ postgres: { ...postgresTestLimits, pool, schema: isolated }, auth })
254 const tiered = createDurableStreams({ postgres: { ...postgresTestLimits, pool, schema: isolated }, storage: { objects }, auth })
255 try {
256 await migrate(direct, { schema: isolated })
257 expect((await request(hot, 'existing', 'PUT', 'pre-binding;')).status).toBe(201)
258 await migrate(direct, { schema: isolated, storageIdentity: objects.identity })
259 expect((await pool.query(`SELECT count(*) FROM "${isolated}".hot_chunks`)).rows[0].count).toBe('1')
260 expect((await request(hot, 'existing', 'POST', 'fenced;')).status).toBe(503)
261 expect((await tiered.maintain({ forceHot: true })).sealed).toBe(1)
262 expect(await (await request(tiered, 'existing')).text()).toBe('pre-binding;')
263 } finally {
264 await hot.close()
265 await tiered.close()
266 await direct.query(`DROP SCHEMA "${isolated}" CASCADE`)
267 }
268})