Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import pg from 'pg'
3import { afterAll, expect, test } from 'vitest'
4
5const { TEST_FUNCTION_URL, TEST_FUNCTION_API_KEY, TEST_FUNCTION_OTHER_KEY, TEST_FUNCTION_MAINTENANCE_KEY, TEST_FUNCTION_SCHEMA, TEST_FUNCTION_BUNDLE_SHA, TEST_FUNCTION_DEPLOYMENT_ID, TEST_DATABASE_URL } = process.env
6if (!TEST_FUNCTION_URL || !TEST_FUNCTION_API_KEY || !TEST_FUNCTION_OTHER_KEY || !TEST_FUNCTION_MAINTENANCE_KEY || !TEST_FUNCTION_SCHEMA || !TEST_FUNCTION_BUNDLE_SHA || !TEST_FUNCTION_DEPLOYMENT_ID || !TEST_DATABASE_URL) throw new Error('Deployed Neon Function credentials required; ingress qualification cannot skip')
7if (!/^ds_test_[a-f0-9]{32}$/.test(TEST_FUNCTION_SCHEMA) || !new URL(TEST_FUNCTION_URL).hostname.includes('.compute.')) throw new Error('Only the provisioned isolated Neon Function can be tested')
8const pool = new pg.Pool({ connectionString: TEST_DATABASE_URL, max: 2 })
9pool.on('error', () => {})
10afterAll(() => pool.end())
11const request = (path: string, method = 'GET', body?: string, headers?: Record<string, string>, signal?: AbortSignal) => fetch(new URL(path, TEST_FUNCTION_URL), {
12 method, headers: { Authorization: `Bearer ${TEST_FUNCTION_API_KEY}`, 'Content-Type': 'text/plain', ...headers },
13 ...(body !== undefined ? { body } : {}), signal: signal ?? AbortSignal.timeout(15_000),
14})
15
16test('authenticated health identifies the deployed bundle and unauthorized calls fail before application work', async () => {
17 const health = await request('health')
18 expect(health.status).toBe(200)
19 expect(await health.json()).toMatchObject({ ready: true, build: TEST_FUNCTION_BUNDLE_SHA, deploymentId: TEST_FUNCTION_DEPLOYMENT_ID })
20 expect((await request('health', 'GET', undefined, { Authorization: 'Bearer invalid' })).status).toBe(401)
21 expect((await request(`v1/stream/unauthorized-${randomUUID()}`, 'PUT', '{bad json', { Authorization: 'Bearer invalid', 'Content-Type': 'application/json' })).status).toBe(401)
22 expect((await request('_maintenance', 'POST')).status).toBe(401)
23})
24
25test('a caller cannot impersonate a Neon Function Trigger using forged platform headers', async () => {
26 const id = randomUUID()
27 const response = await request('_trigger', 'POST', JSON.stringify({ version: 1, invocation_id: id, type: 'schedule',
28 trigger: { type: 'schedule', id: 'forged', name: 'durable-streams-maintenance' }, data: { scheduled_at: new Date().toISOString() } }),
29 { 'x-neon-trigger-invocation-id': id, 'Content-Type': 'application/json' })
30 expect(response.status).toBe(401)
31})
32
33test('the same path is isolated between independently authenticated tenants at real Function ingress', async () => {
34 const path = `v1/stream/tenant-${randomUUID()}`
35 expect((await request(path, 'PUT', 'tenant-a bytes')).status).toBe(201)
36 const other = { Authorization: `Bearer ${TEST_FUNCTION_OTHER_KEY}` }
37 expect((await request(path, 'GET', undefined, other)).status).toBe(404)
38 expect((await request(path, 'PUT', 'tenant-b bytes', other)).status).toBe(201)
39 expect(await (await request(path)).text()).toBe('tenant-a bytes')
40 expect(await (await request(path, 'GET', undefined, other)).text()).toBe('tenant-b bytes')
41})
42
43test('SSE flushes its initial checkpoint and delivers a live final append before EOF through Neon ingress', async () => {
44 const path = `v1/stream/sse-${randomUUID()}`
45 const created = await request(path, 'PUT', 'history')
46 expect(created.status).toBe(201)
47 const controller = new AbortController()
48 const timer = setTimeout(() => controller.abort(), 12_000)
49 const response = await request(`${path}?live=sse&offset=${created.headers.get('Stream-Next-Offset')}`, 'GET', undefined, undefined, controller.signal)
50 expect(response.status).toBe(200)
51 expect(response.headers.get('Content-Type')).toBe('text/event-stream')
52 const reader = response.body!.getReader()
53 try {
54 let initial = ''
55 while (!initial.includes('event: control')) {
56 const part = await reader.read()
57 if (part.done) throw new Error('SSE ended before its initial checkpoint')
58 initial += new TextDecoder().decode(part.value)
59 }
60 expect(initial).not.toContain('history')
61 expect((await request(path, 'POST', 'final bytes', { 'Stream-Closed': 'true' })).status).toBe(204)
62 let content = ''
63 for (;;) {
64 const part = await reader.read()
65 if (part.done) break
66 content += new TextDecoder().decode(part.value)
67 }
68 expect(content).toContain('event: data\ndata:final bytes\n\nevent: control')
69 expect(content).toContain('"streamClosed":true')
70 } finally { clearTimeout(timer); controller.abort(); await reader.cancel(); reader.releaseLock() }
71}, 15_000)
72
73test('authenticated maintenance publishes to Neon Object Storage and the Function replays sealed data', async () => {
74 const path = `sealed-${randomUUID()}`
75 expect((await request(`v1/stream/${path}`, 'PUT', 'before')).status).toBe(201)
76 const tuple = { 'Producer-Id': 'ingress-writer', 'Producer-Epoch': '0', 'Producer-Seq': '0' }
77 expect((await request(`v1/stream/${path}`, 'POST', ' after', tuple)).status).toBe(200)
78 const maintenance = await request('_maintenance', 'POST', undefined, { 'x-ds-maintenance-key': TEST_FUNCTION_MAINTENANCE_KEY })
79 expect(maintenance.status).toBe(200)
80 await maintenance.json() // The schedule may already have sealed this batch.
81 const remote = await pool.query(`SELECT NOT EXISTS(SELECT 1 FROM "${TEST_FUNCTION_SCHEMA}".appends a JOIN "${TEST_FUNCTION_SCHEMA}".streams s ON s.id=a.stream_id WHERE s.tenant_id='function-a' AND s.path=$1)
82 AND EXISTS(SELECT 1 FROM "${TEST_FUNCTION_SCHEMA}".chunks c JOIN "${TEST_FUNCTION_SCHEMA}".streams s ON s.id=c.stream_id WHERE s.tenant_id='function-a' AND s.path=$1 AND c.state='sealed') AS sealed`,[path])
83 expect(remote.rows[0].sealed).toBe(true)
84 expect(await (await request(`v1/stream/${path}`)).text()).toBe('before after')
85 expect((await request(`v1/stream/${path}`, 'POST', 'a retried body', tuple)).status).toBe(204)
86 expect(await (await request(`v1/stream/${path}`)).text()).toBe('before after')
87})
88
89test('a real Neon schedule trigger seals idle data without an application maintenance call', async () => {
90 const path = `scheduled-${randomUUID()}`
91 expect((await request(`v1/stream/${path}`, 'PUT', 'idle bytes awaiting scheduled recovery')).status).toBe(201)
92 await expect.poll(async () => {
93 const result = await pool.query(`SELECT NOT EXISTS(SELECT 1 FROM "${TEST_FUNCTION_SCHEMA}".appends a JOIN "${TEST_FUNCTION_SCHEMA}".streams s ON s.id=a.stream_id WHERE s.tenant_id='function-a' AND s.path=$1)
94 AND EXISTS(SELECT 1 FROM "${TEST_FUNCTION_SCHEMA}".chunks c JOIN "${TEST_FUNCTION_SCHEMA}".streams s ON s.id=c.stream_id WHERE s.tenant_id='function-a' AND s.path=$1 AND c.state='sealed') AS sealed`,[path])
95 return result.rows[0].sealed
96 }, { timeout: 90_000, interval: 1000 }).toBe(true)
97 expect(await (await request(`v1/stream/${path}`)).text()).toBe('idle bytes awaiting scheduled recovery')
98}, 120_000)