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

index.ts

168 lines5.2 KB

1import {
2 createNeonRealtimeSource,
3 createShapeHandler,
4 resolveConfiguredShape,
5 createS3LogStore,
6 ObjectShapeLog,
7} from '@neon/realtime-electric-server'
8import { appendFileSync } from 'node:fs'
9import { randomUUID } from 'node:crypto'
10​
11const instance = randomUUID()
12function diagnose(entry: Record<string, unknown>) {
13 if (process.env.NEON_SHAPE_DIAGNOSTICS !== 'true') return
14 const line = JSON.stringify({ ...entry, instance, pid: process.pid })
15 console.log(line)
16 if (process.env.NEON_SHAPE_DIAGNOSTICS_FILE)
17 appendFileSync(process.env.NEON_SHAPE_DIAGNOSTICS_FILE, line + '\n')
19diagnose({
20 event: 'function_started',
21 timestamp: Date.now(),
22 nodeVersion: process.version,
23})
24​
25function required(name: string): string {
26 const value = process.env[name]
27 if (!value) throw new Error(`Local shape Function requires ${name}`)
28 return value
30const source = createNeonRealtimeSource({
31 url: required('NEON_REALTIME_URL'),
32 secret: required('NEON_REALTIME_SECRET'),
33 db: new URL(required('DATABASE_URL')).pathname.slice(1),
34 logLevel: process.env.NEON_SHAPE_DIAGNOSTICS === 'true' ? 'debug' : 'silent',
35 logger: (entry) =>
36 diagnose({
37 event: entry.event,
38 timestamp: entry.timestamp,
39 ...('code' in entry ? { code: entry.code } : {}),
40 }),
41})
42const storage = process.env.NEON_SHAPE_LOG_BUCKET
43 ? createS3LogStore({ bucket: process.env.NEON_SHAPE_LOG_BUCKET })
44 : undefined
45const objectPrefix = 'electric-shapes'
46// Opt-in local measurements. Values and object keys never enter diagnostics.
47const measuredStore =
48 storage && process.env.NEON_SHAPE_DIAGNOSTICS === 'true'
49 ? {
50 async put(...args: Parameters<typeof storage.put>) {
51 const started = performance.now()
52 try {
53 await storage.put(...args)
54 diagnose({
55 event: 'object_put',
56 bytes: args[1].byteLength,
57 elapsedMs: performance.now() - started,
58 timestamp: Date.now(),
59 })
60 } catch (error) {
61 diagnose({
62 event: 'object_put_failed',
63 aborted: args[2]?.aborted === true,
64 timestamp: Date.now(),
65 })
66 throw error
67 }
68 },
69 async get(...args: Parameters<typeof storage.get>) {
70 const started = performance.now()
71 try {
72 const bytes = await storage.get(...args)
73 diagnose({
74 event: 'object_get',
75 bytes: bytes.byteLength,
76 elapsedMs: performance.now() - started,
77 timestamp: Date.now(),
78 })
79 return bytes
80 } catch (error) {
81 diagnose({
82 event: 'object_get_failed',
83 aborted: args[1]?.aborted === true,
84 timestamp: Date.now(),
85 })
86 throw error
87 }
88 },
89 async delete(...args: Parameters<typeof storage.delete>) {
90 await storage.delete(...args)
91 diagnose({ event: 'object_delete', timestamp: Date.now() })
92 },
93 }
94 : storage
95const sweep = () =>
96 storage
97 ?.sweepExpired(objectPrefix)
98 .catch(() => console.error('Expired shape object sweep failed'))
99void sweep()
100const sweepTimer = storage ? setInterval(() => void sweep(), 60_000) : undefined
101sweepTimer?.unref()
102const handler = createShapeHandler({
103 source,
104 createLog: storage
105 ? ({ handle, expiresAt }) =>
106 new ObjectShapeLog({
107 store: measuredStore!,
108 prefix: `${objectPrefix}/${expiresAt}/${handle}`,
109 sealBytes: process.env.NEON_SHAPE_SEAL_BYTES
110 ? Number(process.env.NEON_SHAPE_SEAL_BYTES)
111 : undefined,
112 })
113 : undefined,
114 onOwnerClosed: ({ handle, error }) => {
115 diagnose({
116 event: 'shape_owner_closed',
117 handle,
118 timestamp: Date.now(),
119 reason: error.message,
120 })
121 },
122 async authorize(request) {
123 // This local example exposes only its dedicated test table. Applications must
124 // supply their own authentication and trusted tenant predicate here.
125 return {
126 authorizationKey: 'local-example',
127 definition: resolveConfiguredShape(new URL(request.url), [
128 {
129 namespace: 'public',
130 table: 'electric_items',
131 primaryKey: ['id'],
132 columns: {
133 id: { type: 'int4', not_null: true },
134 label: { type: 'text', not_null: true },
135 enabled: { type: 'bool', not_null: true },
136 },
137 },
138 ]),
139 }
140 },
141})
142const metricsTimer =
143 process.env.NEON_SHAPE_DIAGNOSTICS === 'true'
144 ? setInterval(
145 () =>
146 diagnose({
147 event: 'function_metrics',
148 timestamp: Date.now(),
149 memory: process.memoryUsage(),
150 shapes: handler.diagnostics,
151 pendingObjectCleanups: handler.pendingObjectCleanups,
152 }),
153 100
154 )
155 : undefined
156metricsTimer?.unref()
157const stop = () => {
158 clearInterval(sweepTimer)
159 clearInterval(metricsTimer)
160 handler.close()
161 void handler
162 .drain()
163 .catch(() => console.error('Shape object cleanup failed'))
164 .finally(() => storage?.close())
166process.once('SIGINT', stop)
167process.once('SIGTERM', stop)
168export default { fetch: (request: Request) => handler.fetch(request) }