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

index.ts

109 lines6.8 KB

1import { createHash, randomUUID, timingSafeEqual } from 'node:crypto'
2import { attachDatabasePool, waitUntil } from '@neon/functions'
3import { isScheduleTriggerInvocation, parseTriggerDelivery } from '@neon/functions/triggers'
4import pg from 'pg'
5import { createDurableStreams } from '@samwillis/durable-streams-neon'
6import type { Principal } 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'
10​
11function required(name: string): string {
12 const value = process.env[name]
13 if (!value) throw new Error(`Missing Function configuration: ${name}`)
14 return value
16const digest = (text: string) => createHash('sha256').update(text).digest()
17const keys = JSON.parse(required('DS_AUTH_JSON')) as unknown
18if (!Array.isArray(keys) || !keys.length || keys.some((item) => !item || typeof item !== 'object'
19 || typeof item.key !== 'string' || item.key.length < 32 || typeof item.tenantId !== 'string' || !item.tenantId
20 || typeof item.subject !== 'string' || !item.subject)) throw new Error('Invalid DS_AUTH_JSON')
21const identities: { digest: Buffer; principal: Principal }[] = keys.map((item) => ({ digest: digest(item.key), principal: { tenantId: item.tenantId, subject: item.subject } }))
22function authenticate(request: Request): Principal | null {
23 const authorization = request.headers.get('authorization')
24 if (!authorization?.startsWith('Bearer ') || authorization.length > 1024) return null
25 const supplied = digest(authorization.slice(7))
26 return identities.find((identity) => timingSafeEqual(identity.digest, supplied))?.principal ?? null
28const maintenanceKey = digest(required('DS_MAINTENANCE_KEY'))
29function maintenanceAuthorized(request: Request): boolean {
30 const key = request.headers.get('x-ds-maintenance-key')
31 return !!key && key.length <= 1024 && timingSafeEqual(digest(key), maintenanceKey)
33const origins: unknown = JSON.parse(process.env.DS_ALLOWED_ORIGINS_JSON ?? '[]')
34if (!Array.isArray(origins) || origins.some((origin) => typeof origin !== 'string')) throw new Error('Invalid DS_ALLOWED_ORIGINS_JSON')
35const pool = new pg.Pool({ connectionString: required('DATABASE_URL'), max: 5, connectionTimeoutMillis: 10_000, query_timeout: 15_000 })
36attachDatabasePool(pool)
37const instanceId = randomUUID()
38const notifier = createNeonRealtimeNotifier({ url: required('DS_REALTIME_URL'), secret: required('DS_REALTIME_SECRET'),
39 database: new URL(required('DATABASE_URL')).pathname.slice(1), onError: () => console.error('Realtime delivery degraded') })
40const objects = createS3ChunkStorage({ endpoint: required('AWS_ENDPOINT_URL_S3'), region: required('AWS_REGION'), bucket: required('DS_BUCKET') })
41const streams = createDurableStreams({
42 postgres: { pool, schema: required('DS_SCHEMA'), environmentId: required('DS_ENVIRONMENT_ID') },
43 auth: { authenticate, authorize: () => true },
44 allowedOrigins: origins,
45 ...(process.env.DS_PUBLIC_BASE_URL ? { publicBaseUrl: process.env.DS_PUBLIC_BASE_URL } : {}),
46 storage: { objects, maxChunkAgeMs: Number(process.env.DS_MAX_CHUNK_AGE_MS ?? '3600000') },
47 subscriptions: { keyring: parseSubscriptionKeyring(required('DS_KEYRING_JSON')) },
48 live: { notifier, longPollTimeoutMs: 25_000, fallbackIntervalMs: Number(process.env.DS_LIVE_FALLBACK_MS ?? '5000'),
49 validationIntervalMs: Number(process.env.DS_LIVE_VALIDATION_MS ?? '1000') },
50 onError: (error) => console.error('Durable Streams request failed', error instanceof Error ? error.name : 'unknown'),
51})
52const hintMode = process.env.DS_MAINTENANCE_HINTS ?? 'on'
53if (!['on', 'off'].includes(hintMode)) throw new Error('DS_MAINTENANCE_HINTS must be on or off')
54const batch = (name: string, fallback: number) => {
55 const value = Number(process.env[name] ?? fallback)
56 if (!Number.isSafeInteger(value) || value < 1 || value > 128) throw new Error(`Invalid ${name}`)
57 return value
59const cronChunks = batch('DS_CRON_MAX_CHUNKS', 64)
60const cronSubscriptions = batch('DS_CRON_SUBSCRIPTION_WORK', 64)
61let hintWork: Promise<void> | undefined
62let hintRequested = false
63function hintMaintenance(): void {
64 hintRequested = true
65 if (hintWork) return
66 hintWork = (async () => {
67 for (let pass = 0; pass < 2; pass++) {
68 hintRequested = false
69 await streams.maintain({ maxChunks: 2, maxSubscriptionWork: 16, timeBudgetMs: 1000 })
70 if (!hintRequested) break
71 }
72 })().catch(() => console.error('Opportunistic maintenance failed; scheduled recovery remains pending'))
73 .finally(() => { hintWork = undefined })
74 // Only the invocation starting this coalesced pass retains it. Attaching the
75 // same promise to every append would consume unnecessary invocation slots.
76 waitUntil(hintWork)
78​
79process.once('SIGINT', () => {
80 void streams.close().finally(async () => { notifier.close(); objects.close(); await pool.end() })
81})
82export default {
83 async fetch(request: Request): Promise<Response> {
84 const path = new URL(request.url).pathname
85 if (path === '/_trigger') {
86 // Neon strips client-supplied x-neon-* headers at deployed ingress.
87 // Keep this platform-authenticated route outside application API-key auth.
88 if (request.method !== 'POST' || !request.headers.has('x-neon-trigger-invocation-id')) return new Response(null, { status: 401 })
89 const parsed = await parseTriggerDelivery(request)
90 if (!parsed.ok || !isScheduleTriggerInvocation(parsed.invocation) || parsed.invocation.trigger.name !== required('DS_MAINTENANCE_TRIGGER_NAME')) return new Response(null, { status: 401 })
91 return Response.json(await streams.maintain({ maxChunks: cronChunks, maxSubscriptionWork: cronSubscriptions, timeBudgetMs: 40_000 }))
92 }
93 if (path === '/_maintenance') {
94 if (request.method !== 'POST' || !maintenanceAuthorized(request)) return new Response(null, { status: 401 })
95 return Response.json(await streams.maintain({ maxChunks: 8, timeBudgetMs: 10_000, forceHot: true }))
96 }
97 if (path === '/health') {
98 if (!authenticate(request)) return new Response(null, { status: 401 })
99 const health = await streams.inspectHealth()
100 return Response.json({ ...health, build: required('DS_BUILD_HASH'), deploymentId: process.env.DS_DEPLOYMENT_ID ?? required('DS_BUILD_HASH'),
101 ...(maintenanceAuthorized(request) ? { runtime: { instanceId, processUptimeSeconds: process.uptime(), memory: process.memoryUsage(),
102 pool: { total: pool.totalCount, idle: pool.idleCount, waiting: pool.waitingCount } } } : {}) },
103 { status: health.ready ? 200 : 503, headers: { 'Cache-Control': 'no-store' } })
104 }
105 const response = await streams.fetch(request)
106 if (hintMode === 'on' && response.ok && ['PUT', 'POST', 'DELETE'].includes(request.method)) hintMaintenance()
107 return response
108 },