Open History to see the last commit
1// Private benchmark consumer. Instrumentation lives outside the library API.
2import { AsyncLocalStorage } from 'node:async_hooks'
3import { createHash, randomUUID, timingSafeEqual } from 'node:crypto'
4import { attachDatabasePool } from '@neon/functions'
5import pg from 'pg'
6import { createDurableStreams } from '@samwillis/durable-streams-neon'
7import { createNeonRealtimeNotifier } from '@samwillis/durable-streams-neon/neon'
8import { createS3ChunkStorage } from '@samwillis/durable-streams-neon/s3'
9import { parseSubscriptionKeyring } from '@samwillis/durable-streams-neon/subscriptions'
10import { replayProfiles, replayFrame } from './replay-data.mjs'
11
12const required = (name) => {
13 if (!process.env[name]) throw new Error(`Missing ${name}`)
14 return process.env[name]
15}
16const schema = required('DS_SCHEMA')
17if (!/^ds_test_[a-f0-9]{32}$/.test(schema)) throw new Error('Replay fixture requires a test schema')
18const hash = (value) => createHash('sha256').update(value).digest()
19const key = hash(required('DS_BENCHMARK_KEY'))
20const authorized = (request) => {
21 const token = request.headers.get('authorization')
22 return !!token && token.length < 1024 && timingSafeEqual(hash(token), key)
23}
24const settings = JSON.parse(required('DS_BENCHMARK_SETTINGS'))
25const instanceId = randomUUID()
26const context = new AsyncLocalStorage()
27const pool = new pg.Pool({ connectionString: required('DATABASE_URL'), max: 5, connectionTimeoutMillis: 10000, query_timeout: 15000 })
28attachDatabasePool(pool)
29pool.on('connect', (client) => {
30 const original = client.query.bind(client)
31 client.query = (...args) => {
32 const metrics = context.getStore()
33 if (!metrics) return original(...args)
34 const sql = typeof args[0] === 'string' ? args[0] : args[0].text ?? ''
35 metrics.sqlCalls++
36 if (/^BEGIN/.test(sql)) metrics.transactions++
37 if (/INSERT INTO .*replay_pins/.test(sql)) metrics.pinInsertCalls++
38 if (/DELETE FROM .*replay_pins/.test(sql)) metrics.pinDeleteCalls++
39 const started = performance.now()
40 const finish = () => { metrics.sqlMs += performance.now() - started }
41 const callback = args.at(-1)
42 if (typeof callback === 'function') {
43 args[args.length - 1] = (...result) => { finish(); callback(...result) }
44 return original(...args)
45 }
46 return original(...args).finally(finish)
47 }
48})
49const notifier = createNeonRealtimeNotifier({ url: required('DS_REALTIME_URL'), secret: required('DS_REALTIME_SECRET'),
50 database: new URL(required('DATABASE_URL')).pathname.slice(1) })
51const rawObjects = createS3ChunkStorage({ endpoint: required('AWS_ENDPOINT_URL_S3'), region: required('AWS_REGION'), bucket: required('DS_BUCKET') })
52async function objectRead(method, args) {
53 const metrics = context.getStore()
54 const started = performance.now()
55 if (metrics) { metrics.objectGets++; if (method === 'getRange') metrics.objectRangeGets++ }
56 try {
57 const bytes = await rawObjects[method](...args)
58 if (metrics) metrics.objectBytes += bytes.byteLength
59 return bytes
60 } finally { if (metrics) metrics.objectMs += performance.now() - started }
61}
62async function rangeRead(key, range, consume, signal) {
63 const metrics = context.getStore(), started = performance.now()
64 if (metrics) { metrics.objectGets++; metrics.objectRangeGets++ }
65 try { return await rawObjects.readRange(key, range, async (bytes) => {
66 if (metrics) metrics.objectBytes += bytes.byteLength
67 await consume(bytes)
68 }, signal) } finally { if (metrics) metrics.objectMs += performance.now() - started }
69}
70const objects = { ...rawObjects, readRange: rangeRead, get: (...args) => objectRead('get', args), getRange: (...args) => objectRead('getRange', args) }
71function server(cacheBytes = settings.cacheBytes, pageBytes) {
72 return createDurableStreams({ postgres: { pool, schema, environmentId: required('DS_ENVIRONMENT_ID') },
73 auth: { authenticate: () => ({ tenantId: 'replay', subject: 'benchmark' }), authorize: () => true },
74 storage: { objects, targetChunkBytes: settings.targetChunkBytes, maxChunkFrames: settings.maxChunkFrames, blockBytes: settings.blockBytes, readAhead: settings.readAhead ?? 1, cacheBytes },
75 ...(pageBytes ? { limits: { maxPageBytes: pageBytes, maxStoredBytes: pageBytes - 2 } } : {}),
76 subscriptions: { keyring: parseSubscriptionKeyring(required('DS_KEYRING_JSON')) },
77 live: { notifier, maxReaders: 64, maxSseDurationMs: 10000, heartbeatMs: 1000 },
78 })
79}
80const shared = server()
81const request = (handler, path, method = 'GET', body, headers = {}) => handler.fetch(new Request(`https://benchmark.invalid/v1/stream/${path}`, {
82 method, headers: { 'Content-Type': 'application/octet-stream', ...headers }, ...(body === undefined ? {} : { body }),
83}))
84
85async function seed(input) {
86 const profile = replayProfiles[input.profile]
87 if (!profile || !/^replay-[a-f0-9-]{36}$/.test(input.run) || !Number.isSafeInteger(input.frames) || input.frames < 1 || input.frames > profile.frames) throw new Error('Invalid replay dataset')
88 const path = `${input.run}/${input.profile}`
89 const created = await request(shared, path, 'PUT', undefined, { 'Content-Type': profile.contentType })
90 if (created.status !== 201) throw new Error('Benchmark stream already exists')
91 const offsets = [created.headers.get('Stream-Next-Offset')]
92 for (let index = 0; index < input.frames; index++) {
93 const response = await request(shared, path, 'POST', replayFrame(input.profile, index), { 'Content-Type': profile.contentType })
94 await response.arrayBuffer()
95 if (response.status !== 204) throw new Error(`Benchmark append failed at ${index} with ${response.status}`)
96 offsets.push(response.headers.get('Stream-Next-Offset'))
97 }
98 return { path, offsets, profile: input.profile, frames: input.frames }
99}
100
101async function handle(request) {
102 if (!authorized(request)) return new Response(null, { status: 401 })
103 const url = new URL(request.url)
104 if (url.pathname === '/_benchmark/health') return Response.json({ instanceId, settings, build: required('DS_BUILD_HASH'), sourceCommit: required('DS_SOURCE_COMMIT'), ready: (await shared.inspectHealth()).ready })
105 if (url.pathname === '/_benchmark/seed' && request.method === 'POST') return Response.json(await seed(await request.json()))
106 if (url.pathname === '/_benchmark/maintain' && request.method === 'POST') {
107 const memoryBefore = process.memoryUsage(), started = performance.now()
108 const result = await shared.maintain({ forceHot: true, maxChunks: 128, timeBudgetMs: 40000 })
109 return Response.json({ ...result, benchmark: { instanceId, memoryBefore, memoryAfter: process.memoryUsage(),
110 lifetimeMaxRssKiB: process.resourceUsage().maxRSS, durationMs: performance.now() - started } })
111 }
112 if (url.pathname === '/_benchmark/storage') {
113 const relations = await pool.query(`SELECT relname,pg_relation_size(c.oid) AS heap_bytes,pg_indexes_size(c.oid) AS index_bytes,
114 pg_total_relation_size(c.oid) AS total_bytes FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
115 WHERE n.nspname=$1 AND c.relkind='r' ORDER BY relname`, [schema])
116 const counts = await pool.query(`SELECT (SELECT count(*) FROM ${schema}.appends) AS appends,
117 (SELECT count(*) FROM ${schema}.chunks WHERE state='frozen') AS frozen,
118 (SELECT count(*) FROM ${schema}.chunks WHERE state='sealed') AS sealed,
119 (SELECT sum(encoded_bytes) FROM ${schema}.chunks WHERE state='sealed') AS object_bytes,
120 (SELECT count(*) FROM ${schema}.replay_pins) AS replay_pins`)
121 return Response.json({ relations: relations.rows, counts: counts.rows[0] })
122 }
123 if (!url.pathname.startsWith('/v1/stream/replay-')) return new Response(null, { status: 404 })
124 const cold = request.headers.get('x-replay-cache') === 'cold'
125 const firstBlock = request.headers.get('x-replay-first-block') === '1'
126 const isolated = cold || firstBlock
127 const handler = isolated ? server(0, firstBlock ? settings.blockBytes : undefined) : shared
128 const metrics = { sqlCalls: 0, transactions: 0, pinInsertCalls: 0, pinDeleteCalls: 0, sqlMs: 0, objectGets: 0, objectRangeGets: 0, objectBytes: 0, objectMs: 0 }
129 const started = performance.now()
130 const before = process.memoryUsage()
131 let response
132 try { response = await context.run(metrics, () => handler.fetch(request)) }
133 catch (error) { if (isolated) await handler.close(); throw error }
134 if (isolated && !response.body) await handler.close()
135 const headers = new Headers(response.headers)
136 headers.set('x-replay-metrics', JSON.stringify({ ...metrics, handlerMs: performance.now() - started,
137 instanceId, cache: cold ? 'disabled' : 'shared', memoryBefore: before, memoryAfter: process.memoryUsage(),
138 pool: { total: pool.totalCount, idle: pool.idleCount, waiting: pool.waitingCount } }))
139 let body = response.body
140 if (isolated && body) {
141 const reader = body.getReader()
142 body = new ReadableStream({
143 async pull(controller) {
144 try {
145 const next = await reader.read()
146 if (next.done) { controller.close(); await handler.close() }
147 else controller.enqueue(next.value)
148 } catch (error) { controller.error(error); await handler.close() }
149 },
150 async cancel(reason) { try { await reader.cancel(reason) } finally { await handler.close() } },
151 }, { highWaterMark: 0 })
152 }
153 return new Response(body, { status: response.status, headers })
154}
155
156process.once('SIGINT', () => { void shared.close().finally(async () => { notifier.close(); rawObjects.close(); await pool.end() }) })
157export default { fetch: handle }