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

shape-modes.test.ts

360 lines11.6 KB

1import { createServer } from 'node:http'
2import { Readable } from 'node:stream'
3import { once } from 'node:events'
4import {
5 Shape,
6 ShapeStream,
7 type Message,
8} from '../../packages/client/src/index.js'
9import { describe, expect, it } from 'vitest'
10import { ShapeOwner } from '../../packages/server/src/shape-owner.js'
11import { createShapeHandler } from '../../packages/server/src/handler.js'
12import { resolveConfiguredShape } from '../../packages/server/src/definition.js'
13import type {
14 SourceObserver,
15 RealtimeSource,
16} from '../../packages/server/src/realtime-source.js'
17import { decodeReadProof } from '../../packages/protocol/src/read-proof.js'
18import type { RawChange } from '../../packages/protocol/src/index.js'
19​
20const schema = {
21 id: { type: 'int4' },
22 label: { type: 'text' },
23 unchanged: { type: 'text' },
25function sourceFixture() {
26 const observers: SourceObserver[] = []
27 const source: RealtimeSource = {
28 async subscribe(_, observer) {
29 observers.push(observer)
30 observer.event({
31 type: 'schema',
32 columns: [
33 { name: 'id', type_oid: 23, typmod: -1, codec: 'pg_text' },
34 { name: 'label', type_oid: 25, typmod: -1, codec: 'pg_text' },
35 { name: 'unchanged', type_oid: 25, typmod: -1, codec: 'pg_text' },
36 ],
37 })
38 observer.event({
39 type: 'baseline',
40 rows: [{ row_key: 'a'.repeat(64), values: ['1', 'before', 'same'] }],
41 mvcc: { xmin: '5', xmax: '6', xip: [] },
42 })
43 return { close() {} }
44 },
45 close() {},
46 }
47 return { source, observers }
49function definition(params = '') {
50 const url = new URL(`http://local/shape?${params}`)
51 if (!url.searchParams.has('table')) url.searchParams.set('table', 'items')
52 return resolveConfiguredShape(url, [
53 {
54 namespace: 'public',
55 table: 'items',
56 primaryKey: ['id'],
57 columns: schema,
58 },
59 ])
61describe('replica and changes-only boundaries', () => {
62 it.each(['default', 'full'] as const)(
63 'emits %s replica updates/deletes with the correct projection and old changed values',
64 async (replica) => {
65 const f = sourceFixture()
66 const owner = new ShapeOwner({
67 source: f.source,
68 definition: definition(`replica=${replica}`),
69 })
70 try {
71 await owner.start()
72 await owner.settled()
73 const offset = owner.log.head.offset
74 f.observers[0].event({
75 type: 'publication',
76 changes: [
77 {
78 op: 'upsert',
79 row_key: 'a'.repeat(64),
80 values: ['1', null, 'same'],
81 },
82 ],
83 txids: ['6'],
84 frontier: { lsn: '0/16' },
85 })
86 f.observers[0].event({
87 type: 'publication',
88 changes: [{ op: 'remove', row_key: 'a'.repeat(64) }],
89 txids: ['7'],
90 frontier: { lsn: '0/18' },
91 })
92 await owner.settled()
93 const changes = (await owner.log.read(offset)).envelopes.flatMap((e) =>
94 e.kind === 'publication' ? e.changes : []
95 ) as RawChange[]
96 expect(changes[0].value).toEqual(
97 replica === 'full'
98 ? { id: '1', label: null, unchanged: 'same' }
99 : { id: '1', label: null }
100 )
101 expect(changes[0].old_value).toEqual(
102 replica === 'full' ? { label: 'before' } : undefined
103 )
104 expect(changes[1].value).toEqual(
105 replica === 'full'
106 ? { id: '1', label: null, unchanged: 'same' }
107 : { id: '1' }
108 )
109 expect(changes[1]).not.toHaveProperty('old_value')
110 } finally {
111 owner.close()
112 }
113 }
114 )
115 it.each(['log=changes_only', 'offset=now', 'log=changes_only&offset=now'])(
116 'starts empty at a real source baseline barrier for %s, then streams real update classification',
117 async (mode) => {
118 const f = sourceFixture()
119 const handler = createShapeHandler({
120 source: f.source,
121 async authorize(request) {
122 return {
123 authorizationKey: 'modes',
124 definition: definition(
125 new URL(request.url).searchParams.toString()
126 ),
127 }
128 },
129 })
130 const request = (params: string) => {
131 const url = new URL(`http://local/shape?table=items&${mode}`)
132 for (const [key, value] of new URLSearchParams(params))
133 url.searchParams.set(key, value)
134 return handler.fetch(new Request(url))
135 }
136 try {
137 const first = await request('')
138 expect(first.status).toBe(200)
139 const handle = first.headers.get('electric-handle')!
140 const firstProof = decodeReadProof(first.headers.get('electric-cursor'))
141 expect(firstProof.offset).toBe(
142 mode.includes('offset=now') ? 'now' : '-1'
143 )
144 let response = first
145 let envelopes = await first.json()
146 while (
147 !envelopes.some(
148 (e: { kind: string }) => e.kind === 'snapshot-complete'
149 )
150 ) {
151 response = await request(
152 `handle=${handle}&offset=${response.headers.get('electric-offset')}`
153 )
154 envelopes.push(...(await response.json()))
155 }
156 expect(envelopes.map((e: { kind: string }) => e.kind)).toEqual([
157 'initializing',
158 'snapshot-complete',
159 ])
160 expect(envelopes.at(-1).evidence.snapshot).toEqual({
161 xmin: '5',
162 xmax: '6',
163 xip_list: [],
164 })
165 f.observers[0].event({
166 type: 'publication',
167 changes: [
168 {
169 op: 'upsert',
170 row_key: 'a'.repeat(64),
171 values: ['1', 'live', 'same'],
172 },
173 ],
174 txids: ['6'],
175 frontier: { lsn: '0/16' },
176 })
177 const next = await request(
178 `handle=${handle}&offset=${response.headers.get('electric-offset')}`
179 )
180 const body = await next.json()
181 expect(body).toMatchObject([
182 {
183 kind: 'publication',
184 changes: [
185 {
186 headers: { operation: 'update' },
187 value: { id: '1', label: 'live' },
188 },
189 ],
190 },
191 ])
192 } finally {
193 handler.close()
194 await handler.drain()
195 }
196 }
197 )
198 it('hydrates offset=now on an existing handle without replaying its history', async () => {
199 const f = sourceFixture()
200 const handler = createShapeHandler({
201 source: f.source,
202 async authorize() {
203 return { authorizationKey: 'modes', definition: definition() }
204 },
205 })
206 try {
207 const first = await handler.fetch(new Request('http://local/shape'))
208 const handle = first.headers.get('electric-handle')!
209 await first.arrayBuffer()
210 const head = await handler.fetch(
211 new Request(`http://local/shape?handle=${handle}&offset=now`)
212 )
213 expect(head.status).toBe(200)
214 expect(await head.json()).toEqual([])
215 expect(
216 decodeReadProof(head.headers.get('electric-cursor'))
217 ).toMatchObject({ offset: 'now', baselineComplete: true })
218 expect(f.observers).toHaveLength(1)
219 } finally {
220 handler.close()
221 await handler.drain()
222 }
223 })
224})
225​
226for (const liveSse of [false, true])
227 describe(`cold changes-only/now through the real facade and reader (SSE=${liveSse})`, () => {
228 it.each([
229 { log: 'full' as const, offset: 'now' as const },
230 { log: 'changes_only' as const, offset: '-1' as const },
231 { log: 'changes_only' as const, offset: 'now' as const },
232 ])(
233 'keeps history private and classifies subsequent changes for $log/$offset',
234 async (options) => {
235 const f = sourceFixture()
236 const handler = createShapeHandler({
237 source: f.source,
238 longPollMs: 20,
239 sseConnectionMs: 100,
240 async authorize(request) {
241 return {
242 authorizationKey: 'modes',
243 definition: definition(
244 new URL(request.url).searchParams.toString()
245 ),
246 }
247 },
248 })
249 const http = createServer((req, res) => {
250 void (async () => {
251 const abort = new AbortController()
252 res.on('close', () => abort.abort())
253 const response = await handler.fetch(
254 new Request(`http://local${req.url}`, { signal: abort.signal })
255 )
256 res.writeHead(response.status, Object.fromEntries(response.headers))
257 if (response.body)
258 Readable.fromWeb(
259 response.body as import('node:stream/web').ReadableStream
260 )
261 .on('error', () => res.destroy())
262 .pipe(res)
263 else res.end()
264 })().catch(() => res.destroy())
265 })
266 http.listen(0, '127.0.0.1')
267 await once(http, 'listening')
268 const url = `http://127.0.0.1:${(http.address() as { port: number }).port}/application/shapes`
269 const abort = new AbortController()
270 const errors: unknown[] = []
271 const messages: Message[] = []
272 try {
273 const stream = new ShapeStream({
274 url,
275 params: { table: 'items' },
276 ...options,
277 liveSse,
278 signal: abort.signal,
279 onError: (e) => {
280 errors.push(e)
281 },
282 })
283 const shape = new Shape(stream)
284 stream.subscribe((batch) => {
285 messages.push(...batch)
286 })
287 await expect.poll(() => shape.isUpToDate).toBe(true)
288 expect(shape.currentRows).toEqual([])
289 f.observers[0].event({
290 type: 'publication',
291 changes: [
292 {
293 op: 'upsert',
294 row_key: 'a'.repeat(64),
295 values: ['1', 'changed', 'same'],
296 },
297 ],
298 txids: ['6'],
299 frontier: { lsn: '0/16' },
300 })
301 await expect
302 .poll(() =>
303 messages.some(
304 (m) =>
305 'operation' in m.headers && m.headers.operation === 'update'
306 )
307 )
308 .toBe(true)
309 if (options.log === 'changes_only')
310 expect(shape.currentRows).toEqual([])
311 f.observers[0].event({
312 type: 'publication',
313 changes: [
314 {
315 op: 'upsert',
316 row_key: 'b'.repeat(64),
317 values: ['2', 'new', 'same'],
318 },
319 ],
320 txids: ['7'],
321 frontier: { lsn: '0/18' },
322 })
323 await expect
324 .poll(() => shape.currentRows.some((row) => row.id === 2))
325 .toBe(true)
326 f.observers[0].event({
327 type: 'publication',
328 changes: [{ op: 'remove', row_key: 'b'.repeat(64) }],
329 txids: ['8'],
330 frontier: { lsn: '0/20' },
331 })
332 await expect
333 .poll(() => shape.currentRows.some((row) => row.id === 2))
334 .toBe(false)
335 const resume = new ShapeStream({
336 url,
337 params: { table: 'items' },
338 log: options.log,
339 handle: stream.shapeHandle,
340 offset: 'now',
341 subscribe: false,
342 signal: abort.signal,
343 onError: (e) => {
344 errors.push(e)
345 },
346 })
347 expect(await new Shape(resume).rows).toEqual([])
348 expect(resume.shapeHandle).toBe(stream.shapeHandle)
349 expect(f.observers).toHaveLength(1)
350 expect(errors).toEqual([])
351 } finally {
352 abort.abort()
353 handler.close()
354 await handler.drain()
355 http.closeAllConnections()
356 await new Promise<void>((resolve) => http.close(() => resolve()))
357 }
358 }
359 )
360 })