Open History to see the last commit
1import { randomUUID, createHash } from 'node:crypto'
2import { readFile } from 'node:fs/promises'
3import { createNeonClient } from '@neon/sdk'
4import pg from 'pg'
5import { afterAll, beforeAll, expect, test } from 'vitest'
6
7const env = process.env
8if (!env.TEST_FUNCTION_URL || !env.TEST_FUNCTION_API_KEY || !env.TEST_FUNCTION_SCHEMA || !env.TEST_DATABASE_URL || !env.NEON_API_KEY || !env.NEON_PROJECT_ID
9 || !env.NEON_TEST_BRANCH_ID || env.TEST_FUNCTION_BRANCH_ID !== env.NEON_TEST_BRANCH_ID
10 || env.TEST_FUNCTION_MAINTENANCE_HINTS !== 'on' || env.TEST_FUNCTION_HAS_CRON !== 'no'
11 || !/^ds_test_[a-f0-9]{32}$/.test(env.TEST_FUNCTION_SCHEMA)) throw new Error('Hint qualification requires a recorded isolated Function with hints enabled and no cron')
12const state = JSON.parse(await readFile(env.NEON_TEST_STATE_FILE ?? '.neon-test-state.json', 'utf8')) as { projectId: string; branchId: string; name: string }
13if (state.projectId !== env.NEON_PROJECT_ID || state.branchId !== env.NEON_TEST_BRANCH_ID || !state.name.startsWith('ds-test-')) throw new Error('Unrecorded hint qualification branch')
14const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL, max: 2, query_timeout: 10_000 })
15pool.on('error', () => {})
16const neon = createNeonClient({ apiKey: env.NEON_API_KEY, throwOnError: true })
17const request = (path: string, method = 'GET', body?: BodyInit, headers?: Record<string, string>, signal = AbortSignal.timeout(20_000)) => fetch(new URL(path, env.TEST_FUNCTION_URL), {
18 method, headers: { Authorization: `Bearer ${env.TEST_FUNCTION_API_KEY}`, 'Content-Type': 'application/octet-stream', ...headers }, ...(body !== undefined ? { body } : {}), signal,
19})
20beforeAll(async () => {
21 const triggers = await neon.triggers.list({ projectId: env.NEON_PROJECT_ID!, branchId: env.NEON_TEST_BRANCH_ID! })
22 expect(triggers).toHaveLength(0)
23})
24afterAll(async () => {
25 try {
26 const names = await pool.query<{ name: string }>(`SELECT name FROM "${env.TEST_FUNCTION_SCHEMA}".subscriptions WHERE tenant_id='function-a' AND name LIKE 'hint-%' AND deleted_at IS NULL`)
27 for (const row of names.rows) await request(`v1/stream/__ds/subscriptions/${encodeURIComponent(row.name)}`, 'DELETE')
28 } finally { await pool.end() }
29})
30
31test('an append hint publishes a pull wake through actual Realtime with no cron or manual worker', async () => {
32 const name = `hint-${randomUUID()}`, path = `${name}/events`, wake = `${name}-wake`
33 expect((await request(`v1/stream/${path}`, 'PUT')).status).toBe(201)
34 expect((await request(`v1/stream/${wake}`, 'PUT', '[]', { 'Content-Type': 'application/json' })).status).toBe(201)
35 expect((await request(`v1/stream/__ds/subscriptions/${name}`, 'PUT', JSON.stringify({ type: 'pull-wake', streams: [path], wake_stream: wake }), { 'Content-Type': 'application/json' })).status).toBe(201)
36 const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 12_000)
37 const response = await request(`v1/stream/${wake}?live=sse&offset=now`, 'GET', undefined, undefined, controller.signal)
38 expect(response.status).toBe(200)
39 const reader = response.body!.getReader()
40 try {
41 expect(new TextDecoder().decode((await reader.read()).value)).toContain('event: control')
42 expect((await request(`v1/stream/${path}`, 'POST', 'hinted append')).status).toBe(204)
43 let content = ''
44 while (!content.includes('"type":"wake"')) {
45 const next = await reader.read()
46 if (next.done) throw new Error('Wake SSE ended before hint publication')
47 content += new TextDecoder().decode(next.value)
48 }
49 expect(content).toContain(`"subscription_id":"${name}"`)
50 } finally {
51 clearTimeout(timer); await reader.cancel().catch(() => {}); controller.abort(); reader.releaseLock()
52 await request(`v1/stream/__ds/subscriptions/${name}`, 'DELETE')
53 }
54}, 20_000)
55
56test('hints seal a full chunk while small hot tails remain local, without a scheduled worker', async () => {
57 const path = `hint-storage-${randomUUID()}`, payload = new Uint8Array(256 * 1024).fill(97)
58 expect((await request(`v1/stream/${path}`, 'PUT')).status).toBe(201)
59 for (let i = 0; i < 8; i++) expect((await request(`v1/stream/${path}`, 'POST', payload)).status).toBe(204)
60 const pending = await pool.query(`SELECT count(*) FROM "${env.TEST_FUNCTION_SCHEMA}".chunks c JOIN "${env.TEST_FUNCTION_SCHEMA}".streams s ON s.id=c.stream_id WHERE s.path=$1`, [path])
61 expect(pending.rows[0].count).toBe('0')
62 for (let i = 0; i < 8; i++) expect((await request(`v1/stream/${path}`, 'POST', payload)).status).toBe(204)
63 await expect.poll(async () => (await pool.query(`SELECT NOT EXISTS(SELECT 1 FROM "${env.TEST_FUNCTION_SCHEMA}".appends a JOIN "${env.TEST_FUNCTION_SCHEMA}".streams s ON s.id=a.stream_id WHERE s.path=$1)
64 AND EXISTS(SELECT 1 FROM "${env.TEST_FUNCTION_SCHEMA}".chunks c JOIN "${env.TEST_FUNCTION_SCHEMA}".streams s ON s.id=c.stream_id WHERE s.path=$1 AND c.state='sealed') AS sealed`,[path])).rows[0].sealed,
65 { timeout: 15_000, interval: 250 }).toBe(true)
66 const hash = createHash('sha256')
67 let bytes = 0, offset = '-1'
68 for (let i = 0; i < 20; i++) {
69 const page = await request(`v1/stream/${path}?offset=${encodeURIComponent(offset)}`)
70 expect(page.status).toBe(200)
71 const part = Buffer.from(await page.arrayBuffer()); bytes += part.length; hash.update(part)
72 if (page.headers.get('Stream-Up-To-Date')) break
73 offset = page.headers.get('Stream-Next-Offset')!
74 }
75 expect(bytes).toBe(4 * 1024 * 1024)
76 expect(hash.digest('hex')).toBe(createHash('sha256').update(Buffer.alloc(4 * 1024 * 1024, 97)).digest('hex'))
77})