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

realtime-source.test.ts

241 lines7.1 KB

1import { createServer } from 'node:http'
2import { once } from 'node:events'
3import { createRequire } from 'node:module'
4import { afterEach, describe, expect, it } from 'vitest'
5import {
6 createNeonRealtimeSource,
7 SourceQueryRejectedError,
8 type SourceEvent,
9 type SourceSubscription,
10} from '../../packages/server/src/realtime-source.js'
11​
12const require = createRequire(
13 new URL('../../packages/server/package.json', import.meta.url)
15const { WebSocketServer } = require('ws') as typeof import('ws')
16const cleanup: (() => unknown)[] = []
17afterEach(async () => {
18 for (const close of cleanup.splice(0).reverse()) await close()
19})
20​
21const columns = [
22 { name: 'id', type_oid: 20, typmod: -1, codec: 'pg_text' },
23 { name: 'custom', type_oid: 99999, typmod: -1, codec: 'pg_text' },
24 { name: 'bytes', type_oid: 17, typmod: -1, codec: 'bytes' },
26const row = {
27 row_key: 'a'.repeat(64),
28 values: ['9007199254740993', '(one,two)', { base64: 'AP8=' }],
30const mvcc = {
31 xmin: '9007199254740993',
32 xmax: '9007199254740999',
33 xip: ['9007199254740996'],
35const target = { live_id: '1', epoch: '1', sequence: '1' }
36​
37async function fixture(rejectInitial = false) {
38 const http = createServer()
39 const ws = new WebSocketServer({ server: http })
40 http.listen(0, '127.0.0.1')
41 await once(http, 'listening')
42 cleanup.push(
43 () =>
44 new Promise<void>((resolve) => {
45 for (const socket of ws.clients) socket.terminate()
46 ws.close(() => http.close(() => resolve()))
47 })
48 )
49 const address = http.address() as { port: number }
50 const socketReady = once(ws, 'connection').then(
51 ([socket]) => socket as import('ws').WebSocket
52 )
53 const source = createNeonRealtimeSource({
54 url: `ws://127.0.0.1:${address.port}`,
55 // Valid local capability encryption key. Never accepted by a real service.
56 secret: `nrt_live_1${Buffer.alloc(32, 7).toString('base64url')}`,
57 db: 'neondb',
58 })
59 cleanup.push(() => source.close())
60 const events: SourceEvent[] = []
61 const errors: Error[] = []
62 const controller = new AbortController()
63 const control = await source.subscribe(
64 { sql: 'select 1' },
65 { event: (e) => events.push(e), error: (e) => errors.push(e) },
66 controller.signal
67 )
68 const socket = await socketReady
69 const send = (event: object) => socket.send(JSON.stringify(event))
70 send({ type: 'ready' })
71 const [raw] = await once(socket, 'message')
72 const request = JSON.parse(String(raw))
73 expect(request.type).toBe('subscribe')
74 if (rejectInitial)
75 send({
76 type: 'subscribe_rejected',
77 request_id: request.request_id,
78 code: 'upstream_rejected',
79 message: 'private predicate literal diagnostic',
80 })
81 else
82 send({
83 type: 'subscribed',
84 request_id: request.request_id,
85 live_id: '1',
86 epoch: '1',
87 first_sequence: '1',
88 columns,
89 })
90 const start = () =>
91 send({
92 type: 'baseline_sync_start',
93 live_id: '1',
94 epoch: '1',
95 baseline_sync_attempt: '1',
96 mvcc,
97 })
98 const baseline = () => {
99 start()
100 send({
101 type: 'baseline_sync_batch',
102 live_id: '1',
103 epoch: '1',
104 baseline_sync_attempt: '1',
105 index: 0,
106 rows: [row],
107 })
108 send({
109 type: 'baseline_sync_end',
110 live_id: '1',
111 epoch: '1',
112 baseline_sync_attempt: '1',
113 batch_count: 1,
114 })
115 }
116 const publication = () => {
117 send({ type: 'open', publication_id: 'p1' })
118 send({
119 type: 'keyed_results',
120 publication_id: 'p1',
121 index: 0,
122 targets: [target],
123 changes: [{ op: 'upsert', ...row }],
124 txids: ['9007199254740995'],
125 })
126 send({
127 type: 'commit',
128 publication_id: 'p1',
129 body_count: 1,
130 frontier: { lsn: '1/ABCDEF01' },
131 })
132 }
133 return {
134 source,
135 events,
136 errors,
137 controller,
138 control,
139 send,
140 start,
141 baseline,
142 publication,
143 }
145​
146describe('pinned patched Realtime SDK through real WebSocket delivery', () => {
147 it('classifies permanent SQL rejection without exposing upstream diagnostic text', async () => {
148 const f = await fixture(true)
149 await expect.poll(() => f.errors.length).toBe(1)
150 expect(f.errors[0]).toBeInstanceOf(SourceQueryRejectedError)
151 expect(f.errors[0].message).toBe('Realtime rejected the shape query')
152 expect(f.events).toEqual([])
153 })
154​
155 it('exposes early schema, raw PostgreSQL cells, MVCC and publication frontier in order', async () => {
156 const f = await fixture()
157 await expect.poll(() => f.events.length).toBe(1)
158 expect(f.events).toEqual([{ type: 'schema', columns }])
159 f.baseline()
160 f.publication()
161 f.send({ type: 'progress', mvcc })
162 await expect.poll(() => f.events.length).toBe(4)
163 expect(f.errors).toEqual([])
164 expect(f.events).toEqual([
165 { type: 'schema', columns },
166 { type: 'baseline', rows: [row], mvcc },
167 {
168 type: 'publication',
169 changes: [{ op: 'upsert', ...row }],
170 txids: ['9007199254740995'],
171 frontier: { lsn: '1/ABCDEF01' },
172 },
173 { type: 'progress', mvcc },
174 ])
175 })
176​
177 it('keeps a publication buffered during baseline and its progress behind installed data', async () => {
178 const f = await fixture()
179 f.start()
180 f.publication()
181 f.send({ type: 'progress', mvcc }) // SDK deliberately does not forward progress before baseline is live.
182 await expect.poll(() => f.events.length).toBe(1)
183 f.send({
184 type: 'baseline_sync_end',
185 live_id: '1',
186 epoch: '1',
187 baseline_sync_attempt: '1',
188 batch_count: 0,
189 })
190 f.send({ type: 'progress', mvcc })
191 await expect.poll(() => f.events.length).toBe(4)
192 expect(f.events.map((e) => e.type)).toEqual([
193 'schema',
194 'baseline',
195 'publication',
196 'progress',
197 ])
198 expect(f.events[2]).toMatchObject({ frontier: { lsn: '1/ABCDEF01' } })
199 expect(f.errors).toEqual([])
200 })
201​
202 it('invalidates the handle on an upstream reset without delivering a replacement baseline', async () => {
203 const f = await fixture()
204 f.baseline()
205 await expect.poll(() => f.events.length).toBe(2)
206 f.send({ type: 'open', publication_id: 'reset' })
207 f.send({
208 type: 'reset_required',
209 publication_id: 'reset',
210 index: 0,
211 targets: [{ live_id: '1', epoch: '2', first_sequence: '1' }],
212 })
213 f.send({
214 type: 'commit',
215 publication_id: 'reset',
216 body_count: 1,
217 frontier: { lsn: '1/ABCDEF02' },
218 })
219 await expect.poll(() => f.errors.length).toBe(1)
220 expect(f.errors[0].message).toContain('continuity lost')
221 expect(f.events.map((e) => e.type)).toEqual(['schema', 'baseline'])
222 })
223​
224 it('cancels without further delivery and closes all active subscriptions', async () => {
225 const f = await fixture()
226 await expect.poll(() => f.events.length).toBe(1)
227 f.controller.abort()
228 f.baseline()
229 f.source.close()
230 await new Promise((resolve) => setTimeout(resolve, 50))
231 expect(f.events).toHaveLength(1)
232 expect(f.errors).toEqual([])
233 await expect(
234 f.source.subscribe(
235 { sql: 'select 1' },
236 { event: () => {}, error: () => {} },
237 new AbortController().signal
238 )
239 ).rejects.toThrow('closed')
240 })
241})