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

test-local-lifecycle.ts

182 lines5.3 KB

1import assert from 'node:assert/strict'
2import { mkdir, writeFile } from 'node:fs/promises'
3import { setTimeout as delay } from 'node:timers/promises'
4import pg from 'pg'
5import {
6 Shape,
7 ShapeStream,
8 type Message,
9 type Offset,
10} from '../packages/client/src/index.js'
11​
12type Item = { id: number; label: string; enabled: boolean }
13const base = process.env.SHAPE_URL ?? 'http://localhost:4327/api/shape'
14const databaseUrl = process.env.DATABASE_URL
15assert(databaseUrl, 'Local staging lifecycle test requires DATABASE_URL')
16const db = new pg.Client({
17 connectionString: databaseUrl,
18 connectionTimeoutMillis: 15_000,
19 query_timeout: 15_000,
20})
21const controllers: AbortController[] = []
22const handles = new Set<string>()
23const errors: unknown[] = []
24const params = { table: 'electric_items', where: 'enabled = true' }
25const id = 100 + Math.floor(Math.random() * 1_000_000_000)
26const messages: Message<Item>[] = []
27const report: Record<string, unknown> = {
28 startedAt: new Date().toISOString(),
29 id,
30 status: 'running',
32const open = (
33 options: {
34 handle?: string
35 offset?: Offset
36 subscribe?: boolean
37 } = {}
38) => {
39 const abort = new AbortController()
40 controllers.push(abort)
41 const stream = new ShapeStream<Item>({
42 url: base,
43 params,
44 signal: abort.signal,
45 onError: (error) => {
46 errors.push(error)
47 },
48 ...options,
49 })
50 stream.subscribe((batch) => {
51 messages.push(...batch)
52 })
53 const shape = new Shape(stream)
54 return { stream, shape, abort }
56async function until(predicate: () => boolean) {
57 const end = Date.now() + 20_000
58 while (Date.now() < end) {
59 if (errors.length) throw errors[0]
60 if (predicate()) return
61 await delay(25)
62 }
63 throw new Error('Local lifecycle condition timed out')
65await db.connect()
66try {
67 const initial = open()
68 const baseline = await initial.shape.rows
69 await delay(30)
70 const handle = initial.stream.shapeHandle!
71 const offset = initial.stream.lastOffset
72 handles.add(handle)
73 assert(handle && offset !== '-1')
74 initial.abort.abort()
75 await db.query(
76 'insert into public.electric_items (id,label,enabled) values ($1,$2,true)',
77 [id, 'written without readers']
78 )
79 await delay(750)
80 const replay = open({ handle, offset, subscribe: false })
81 const replayed = await replay.shape.rows
82 assert(
83 replayed.some(
84 (row) => row.id === id && row.label === 'written without readers'
85 )
86 )
87 assert.equal(
88 replay.stream.shapeHandle,
89 handle,
90 'No-reader replay unexpectedly replaced the owner'
91 )
92 const combined = new Map(baseline.map((row) => [row.id, row]))
93 for (const row of replayed) combined.set(row.id, row)
94 const current = await db.query(
95 'select id,label,enabled from public.electric_items where enabled = true order by id'
96 )
97 assert.deepEqual(
98 [...combined.values()].sort((a, b) => a.id - b.id),
99 current.rows
100 )
101 replay.abort.abort()
102 const live = open()
103 await live.shape.rows
104 handles.add(live.stream.shapeHandle!)
105 const txids: string[] = []
106 for (const [sql, values, label] of [
107 [
108 'update public.electric_items set label=$2 where id=$1 returning pg_current_xact_id()::text as txid',
109 [id, 'updated'],
110 'updated',
111 ],
112 [
113 'update public.electric_items set enabled=false where id=$1 returning pg_current_xact_id()::text as txid',
114 [id],
115 null,
116 ],
117 [
118 'update public.electric_items set enabled=true where id=$1 returning pg_current_xact_id()::text as txid',
119 [id],
120 'updated',
121 ],
122 [
123 'delete from public.electric_items where id=$1 returning pg_current_xact_id()::text as txid',
124 [id],
125 null,
126 ],
127 ] as const) {
128 const result = await db.query(sql, [...values])
129 txids.push(result.rows[0].txid)
130 await until(() =>
131 label === null
132 ? !live.shape.currentRows.some((row) => row.id === id)
133 : live.shape.currentRows.some(
134 (row) => row.id === id && row.label === label
135 )
136 )
137 }
138 await until(() =>
139 txids.every((tx) =>
140 messages.some(
141 (message) =>
142 'operation' in message.headers &&
143 Array.isArray(message.headers.txids) &&
144 message.headers.txids.includes(Number(BigInt.asUintN(32, BigInt(tx))))
145 )
146 )
147 )
148 assert.equal(errors.length, 0)
149 Object.assign(report, {
150 status: 'passed',
151 completedAt: new Date().toISOString(),
152 handle,
153 offset,
154 baselineCount: baseline.length,
155 replayedCount: replayed.length,
156 txids,
157 })
158 console.log(
159 'Local neon dev lifecycle passed: no-reader replay, live update/delete/filter transitions and transaction IDs'
160 )
161} catch (error) {
162 Object.assign(report, {
163 status: 'failed',
164 error: error instanceof Error ? error.message : String(error),
165 })
166 throw error
167} finally {
168 for (const controller of controllers) controller.abort()
169 await db.query('delete from public.electric_items where id=$1', [id])
170 for (const handle of handles) {
171 const url = new URL(base)
172 for (const [key, value] of Object.entries({ ...params, handle }))
173 url.searchParams.set(key, value)
174 await fetch(url, { method: 'DELETE', signal: AbortSignal.timeout(10_000) })
175 }
176 await db.end()
177 await mkdir('.artifacts/staging', { recursive: true })
178 await writeFile(
179 '.artifacts/staging/local-lifecycle.json',
180 JSON.stringify(report, null, 2)
181 )