Open History to see the last commit
1import assert from 'node:assert/strict'
2import { setTimeout as delay } from 'node:timers/promises'
3import { mkdir, writeFile } from 'node:fs/promises'
4import pg from 'pg'
5import {
6 Shape,
7 ShapeStream,
8 isChangeMessage,
9 type Message,
10} from '../packages/client/src/index.js'
11
12type Item = { id: number; label: string; enabled: boolean }
13const url = process.env.SHAPE_URL ?? 'http://localhost:4327/api/shape'
14assert(process.env.DATABASE_URL, 'Live mode tests require staging DATABASE_URL')
15const db = new pg.Client({
16 connectionString: process.env.DATABASE_URL,
17 connectionTimeoutMillis: 15_000,
18 query_timeout: 15_000,
19})
20const start = 100 + Math.floor(Math.random() * 1_000_000_000)
21const handles: { handle: string; log: string }[] = []
22const controllers: AbortController[] = []
23const report: {
24 startedAt: string
25 status: string
26 cases: unknown[]
27 error?: string
28} = { startedAt: new Date().toISOString(), status: 'running', cases: [] }
29await db.connect()
30try {
31 for (const liveSse of [false, true])
32 for (const options of [
33 { log: 'changes_only' as const, offset: '-1' as const },
34 { log: 'changes_only' as const, offset: 'now' as const },
35 { log: 'full' as const, offset: 'now' as const },
36 ]) {
37 await db.query('delete from public.electric_items where id in ($1,$2)', [
38 start,
39 start + 1,
40 ])
41 await db.query('insert into public.electric_items values($1,$2,true)', [
42 start,
43 'historical',
44 ])
45 const abort = new AbortController()
46 controllers.push(abort)
47 const messages: Message<Item>[] = []
48 const errors: unknown[] = []
49 const stream = new ShapeStream<Item>({
50 url,
51 params: { table: 'electric_items', replica: 'full' },
52 ...options,
53 liveSse,
54 signal: abort.signal,
55 onError: (error) => {
56 errors.push(error)
57 },
58 })
59 const shape = new Shape(stream)
60 stream.subscribe((batch) => {
61 messages.push(...batch)
62 })
63 const until = async (predicate: () => boolean) => {
64 const end = Date.now() + 20_000
65 while (Date.now() < end) {
66 if (errors.length) throw errors[0]
67 if (predicate()) return
68 await delay(25)
69 }
70 throw new Error(
71 `Live ${options.log}/${options.offset}/SSE=${liveSse} condition timed out`
72 )
73 }
74 await until(() => shape.isUpToDate)
75 assert.deepEqual(shape.currentRows, [])
76 handles.push({ handle: stream.shapeHandle!, log: options.log })
77 await db.query('update public.electric_items set label=$2 where id=$1', [
78 start,
79 'historical changed',
80 ])
81 await until(() =>
82 messages.some(
83 (message) =>
84 isChangeMessage(message) &&
85 message.headers.operation === 'update' &&
86 message.value.id === start &&
87 message.value.label === 'historical changed'
88 )
89 )
90 if (options.log === 'changes_only')
91 assert.deepEqual(shape.currentRows, [])
92 const change = messages.find(
93 (message) =>
94 isChangeMessage(message) &&
95 message.headers.operation === 'update' &&
96 message.value.id === start
97 )!
98 assert('value' in change && change.value.enabled === true)
99 assert('old_value' in change && change.old_value?.label === 'historical')
100 assert(
101 'old_value' in change &&
102 !Object.hasOwn(change.old_value ?? {}, 'enabled')
103 )
104 await db.query('insert into public.electric_items values($1,$2,true)', [
105 start + 1,
106 'future insert',
107 ])
108 await until(() =>
109 shape.currentRows.some(
110 (row) => row.id === start + 1 && row.label === 'future insert'
111 )
112 )
113 await db.query('update public.electric_items set label=$2 where id=$1', [
114 start + 1,
115 'future updated',
116 ])
117 await until(() =>
118 shape.currentRows.some(
119 (row) => row.id === start + 1 && row.label === 'future updated'
120 )
121 )
122 await db.query('delete from public.electric_items where id=$1', [
123 start + 1,
124 ])
125 await until(() => !shape.currentRows.some((row) => row.id === start + 1))
126 const before = stream.shapeHandle
127 const resumed = new ShapeStream<Item>({
128 url,
129 params: { table: 'electric_items', replica: 'full' },
130 log: options.log,
131 offset: 'now',
132 handle: before,
133 subscribe: false,
134 signal: abort.signal,
135 onError: (error) => {
136 errors.push(error)
137 },
138 })
139 assert.deepEqual(await new Shape(resumed).rows, [])
140 assert.equal(resumed.shapeHandle, before)
141 assert.equal(errors.length, 0)
142 report.cases.push({ ...options, liveSse, status: 'passed' })
143 abort.abort()
144 }
145 report.status = 'passed'
146 console.log(
147 'Live changes-only/now and full replica modes pass over long polling and SSE against local neon dev/staging'
148 )
149} catch (error) {
150 report.status = 'failed'
151 report.error = String(error)
152 throw error
153} finally {
154 for (const controller of controllers) controller.abort()
155 await db.query('delete from public.electric_items where id in ($1,$2)', [
156 start,
157 start + 1,
158 ])
159 for (const { handle, log } of handles) {
160 const target = new URL(url)
161 for (const [key, value] of Object.entries({
162 handle,
163 log,
164 replica: 'full',
165 table: 'electric_items',
166 }))
167 target.searchParams.set(key, value)
168 await fetch(target, {
169 method: 'DELETE',
170 signal: AbortSignal.timeout(10_000),
171 })
172 }
173 await db.end()
174 await mkdir('.artifacts/staging', { recursive: true })
175 await writeFile(
176 '.artifacts/staging/local-modes.json',
177 JSON.stringify(report, null, 2)
178 )
179}