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

server.test.ts

116 lines6.4 KB

1import { postgresTestLimits } from '../fixtures/postgres-limits.js'
2import { randomUUID } from 'node:crypto'
3import { once } from 'node:events'
4import { createServer } from 'node:http'
5import { Readable } from 'node:stream'
6import pg from 'pg'
7import { afterAll, beforeAll } from 'vitest'
8import { runConformanceTests } from '@durable-streams/server-conformance-tests'
9import { createDurableStreams } from '../../src/index.js'
10import { migrate } from '../../src/migrations.js'
11import { createNeonRealtimeNotifier } from '../../src/neon.js'
12import { createS3ChunkStorage } from '../../src/s3.js'
13import { initializeSubscriptions, parseSubscriptionKeyring } from '../../src/subscriptions.js'
14import { beginRecovery, configureReclamation, finishRecovery, inspectInstallation, verifyRecovery } from '../../src/operations.js'
15​
16if (!process.env.TEST_DATABASE_URL) throw new Error('Provision an isolated Neon test environment; see docs/development.md')
17if (!process.env.NEON_REALTIME_URL || !process.env.NEON_REALTIME_SECRET) throw new Error('Full conformance requires real Neon Realtime credentials')
18if (!process.env.AWS_ENDPOINT_URL_S3 || !process.env.AWS_REGION || !process.env.NEON_TEST_BUCKET) throw new Error('Full conformance requires real Neon Object Storage credentials')
19if (!process.env.DURABLE_STREAMS_KEYRING) throw new Error('Full conformance requires a persistent subscription keyring')
20const keyring = parseSubscriptionKeyring(process.env.DURABLE_STREAMS_KEYRING)
21const pool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL, max: 10, connectionTimeoutMillis: 120_000 })
22const migrationPool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL_UNPOOLED ?? process.env.TEST_DATABASE_URL, max: 1, connectionTimeoutMillis: 15000 })
23pool.on('error', () => {})
24migrationPool.on('error', () => {})
25const schema = `ds_test_${randomUUID().replaceAll('-', '')}`
26const notifier = createNeonRealtimeNotifier({ url: process.env.NEON_REALTIME_URL, secret: process.env.NEON_REALTIME_SECRET,
27 database: new URL(process.env.TEST_DATABASE_URL).pathname.slice(1) })
28const objects = createS3ChunkStorage({ endpoint: process.env.AWS_ENDPOINT_URL_S3, region: process.env.AWS_REGION, bucket: process.env.NEON_TEST_BUCKET })
29const environmentId = 'conformance-fixture'
30const handler = createDurableStreams({ postgres: { ...postgresTestLimits, pool, schema, environmentId },
31 live: { notifier, longPollTimeoutMs: 5000 },
32 storage: { objects, targetChunkBytes: 4096, maxChunkFrames: 16 },
33 subscriptions: { keyring, allowLocalhostWebhooks: true },
34 allowedOrigins: ['https://example.com'],
35 // Explicit anonymous access is confined to the disposable test fixture.
36 auth: { authenticate: () => ({ tenantId: 'conformance', subject: 'fixture' }), authorize: () => true },
37})
38// Upstream adds only one second to this budget, including all test setup HTTP
39// requests. Allow remote Neon round trips while preserving every assertion.
40const config = { baseUrl: '', subscriptions: true, longPollTimeoutMs: 20_000 }
41let maintenanceTimer: ReturnType<typeof setTimeout> | undefined
42let maintenance: Promise<unknown> | undefined
43let stopped = false
44const maintenanceErrors: unknown[] = []
45function scheduleMaintenance() {
46 maintenanceTimer = setTimeout(() => {
47 maintenance = handler.maintain({ maxChunks: 8 }).catch((error: unknown) => { maintenanceErrors.push(error) })
48 .finally(() => { if (!stopped) scheduleMaintenance() })
49 }, 500)
51const http = createServer(async (incoming, outgoing) => {
52 const controller = new AbortController()
53 incoming.once('aborted', () => controller.abort())
54 outgoing.once('close', () => { if (!outgoing.writableFinished) controller.abort() })
55 try {
56 const headers = new Headers()
57 for (const [name, value] of Object.entries(incoming.headers)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(', ') : value)
58 const init: RequestInit & { duplex?: 'half' } = { method: incoming.method ?? 'GET', headers, signal: controller.signal }
59 if (!['GET', 'HEAD'].includes(init.method!)) {
60 init.body = Readable.toWeb(incoming) as ReadableStream<Uint8Array>
61 init.duplex = 'half'
62 }
63 const response = await handler.fetch(new Request(`${config.baseUrl}${incoming.url}`, init))
64 outgoing.writeHead(response.status, Object.fromEntries(response.headers))
65 if (response.body) {
66 const reader = response.body.getReader()
67 try {
68 for (;;) {
69 const { done, value } = await reader.read()
70 if (done) break
71 if (!outgoing.write(value)) await once(outgoing, 'drain', { signal: controller.signal })
72 }
73 } finally { await reader.cancel(); reader.releaseLock() }
74 }
75 outgoing.end()
76 } catch {
77 if (!outgoing.headersSent) outgoing.writeHead(500)
78 outgoing.end()
79 }
80})
81​
82beforeAll(async () => {
83 await migrate(migrationPool, { schema, storageIdentity: objects.identity, environmentId })
84 // Exercise the production collector alongside the unchanged upstream suite.
85 // Configuration happens before serving; historical object recovery remains a provider responsibility.
86 const identity = await inspectInstallation(migrationPool, { schema })
87 const recovery = await beginRecovery(migrationPool, { schema, operationId: randomUUID(), expectedInstallationId: identity.id,
88 expectedServingEpoch: identity.serving_epoch, environmentId, storageIdentity: objects.identity })
89 await configureReclamation(migrationPool, { schema, token: recovery.token, enabled: true })
90 await verifyRecovery(migrationPool, { schema, token: recovery.token, objects })
91 await finishRecovery(migrationPool, { schema, token: recovery.token })
92 await initializeSubscriptions(migrationPool, { schema, keyring })
93 http.listen(0, '127.0.0.1')
94 await once(http, 'listening')
95 const address = http.address()
96 if (!address || typeof address === 'string') throw new Error('Missing HTTP test address')
97 config.baseUrl = `http://127.0.0.1:${address.port}`
98 scheduleMaintenance()
99})
100​
101afterAll(async () => {
102 stopped = true
103 clearTimeout(maintenanceTimer)
104 await maintenance
105 http.closeAllConnections()
106 if (http.listening) await new Promise<void>((resolve, reject) => http.close((error) => error ? reject(error) : resolve()))
107 await handler.close()
108 notifier.close()
109 objects.close()
110 await pool.query(`DROP SCHEMA "${schema}" CASCADE`)
111 await pool.end()
112 await migrationPool.end()
113 if (maintenanceErrors.length) throw new AggregateError(maintenanceErrors, 'Background Neon chunk maintenance failed')
114})
115​
116runConformanceTests(config)