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

test-browser-integrations.mjs

288 lines9.4 KB

1import assert from 'node:assert/strict'
2import { createRequire } from 'node:module'
3import { pathToFileURL, fileURLToPath } from 'node:url'
4import { mkdir, writeFile } from 'node:fs/promises'
5import pg from 'pg'
6const root = fileURLToPath(new URL('../', import.meta.url))
7const cwd = `${root}.artifacts/integration-packages/candidate`
8const require = createRequire(`${cwd}/package.json`)
9const { chromium } = require('playwright-core')
10const { preview } = await import(pathToFileURL(require.resolve('vite')).href)
11assert(
12 process.env.DATABASE_URL,
13 'Browser integration requires 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 serving = await preview({
21 root: cwd,
22 configFile: false,
23 preview: {
24 host: '127.0.0.1',
25 port: 0,
26 proxy: {
27 '/application/shapes': {
28 target: process.env.SHAPE_URL ?? 'http://localhost:4327',
29 rewrite: (url) => url.replace(/^\/application\/shapes/, '/api/shape'),
30 },
31 },
32 },
33})
34const origin = `http://127.0.0.1:${serving.httpServer.address().port}`
35const browser = await chromium.launch({
36 executablePath:
37 process.env.CHROME_PATH ??
38 '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
39 headless: true,
40})
41const report = {
42 startedAt: new Date().toISOString(),
43 status: 'running',
44 modes: [],
45 responses: [],
47const id = 100 + Math.floor(Math.random() * 1_000_000_000)
48const handles = new Set()
49await db.connect()
50try {
51 await db.query(
52 'insert into public.electric_items(id,label,enabled) values($1,$2,true)',
53 [id, 'browser baseline']
54 )
55 for (const mode of [
56 'basic',
57 'custom',
58 'react',
59 'tanstack',
60 'basic-sse',
61 'custom-sse',
62 'react-sse',
63 'tanstack-sse',
64 ]) {
65 const context = await browser.newContext()
66 const page = await context.newPage()
67 let rejected = false
68 await page.route('**/application/shapes?**', async (route) => {
69 if (!rejected) {
70 rejected = true
71 await route.fulfill({
72 status: 401,
73 contentType: 'application/json',
74 body: '{"error":"Expired example token"}',
75 })
76 } else await route.continue()
77 })
78 const errors = []
79 const requests = []
80 page.on('pageerror', (error) => errors.push(error.message))
81 page.on('request', (request) => {
82 if (new URL(request.url()).pathname === '/application/shapes')
83 requests.push(request)
84 })
85 page.on('response', (response) => {
86 const handle = response.headers()['electric-handle']
87 if (handle) handles.add(handle)
88 if (new URL(response.url()).pathname === '/application/shapes') {
89 const entry = {
90 mode,
91 status: response.status(),
92 offset: new URL(response.url()).searchParams.get('offset'),
93 schema: response.headers()['electric-schema'],
94 handle,
95 }
96 report.responses.push(entry)
97 void response
98 .json()
99 .then((body) => {
100 entry.kinds = Array.isArray(body) ? body.map((e) => e.kind) : []
101 })
102 .catch(() => {})
103 }
104 })
105 const rows = async () => {
106 const value = JSON.parse(await page.getByTestId('rows').innerText())
107 return mode.startsWith('custom')
108 ? value.map((row) => ({
109 id: row.itemId,
110 label: row.title,
111 enabled: row.enabled,
112 }))
113 : value
114 }
115 const expected = (label) =>
116 mode.startsWith('custom') ? label.toUpperCase() : label
117 const until = async (predicate) => {
118 const end = Date.now() + 25_000
119 while (Date.now() < end) {
120 assert.deepEqual(errors, [])
121 if (await predicate()) return
122 await new Promise((resolve) => setTimeout(resolve, 50))
123 }
124 throw new Error(`${mode}: condition timed out`)
125 }
126 await page.goto(`${origin}/?mode=${mode}&item=${id}`)
127 await page.getByTestId('rows').waitFor()
128 await until(async () =>
129 (await rows()).some(
130 (r) => r.id === id && r.label === expected('browser baseline')
131 )
132 )
133 const label = `${mode} live`
134 await db.query('update public.electric_items set label=$2 where id=$1', [
135 id,
136 label,
137 ])
138 await until(async () =>
139 (await rows()).some((r) => r.id === id && r.label === expected(label))
140 )
141 // Kill only this owner and require transparent refetch through the same proxy.
142 const oldHandle = [...requests]
143 .reverse()
144 .map((r) => new URL(r.url()).searchParams.get('handle'))
145 .find(Boolean)
146 assert(oldHandle)
147 const deleteUrl = new URL(
148 '/api/shape?table=electric_items',
149 process.env.SHAPE_URL ?? 'http://localhost:4327'
150 )
151 deleteUrl.searchParams.set('handle', oldHandle)
152 assert.equal((await fetch(deleteUrl, { method: 'DELETE' })).status, 204)
153 await until(
154 async () =>
155 requests.some((r) => {
156 const h = new URL(r.url()).searchParams.get('handle')
157 return h && h !== oldHandle
158 }) &&
159 (await rows()).some((r) => r.id === id && r.label === expected(label))
160 )
161 if (mode.startsWith('tanstack')) {
162 let release
163 const gate = new Promise((resolve) => {
164 release = resolve
165 })
166 let mutation
167 await page.route('**/api/items', async (route) => {
168 mutation = route.request().postDataJSON()
169 await gate
170 const result = await db.query(
171 'update public.electric_items set label=$2 where id=$1 returning pg_current_xact_id()::text as txid',
172 [mutation.id, mutation.label]
173 )
174 await route.fulfill({
175 status: 200,
176 contentType: 'application/json',
177 body: JSON.stringify({
178 txid: Number(BigInt.asUintN(32, BigInt(result.rows[0].txid))),
179 }),
180 })
181 })
182 await page.getByRole('button', { name: 'Update first row' }).click()
183 await until(
184 async () =>
185 mutation &&
186 (await rows()).some(
187 (r) => r.id === mutation.id && r.label === 'optimistic'
188 )
189 )
190 assert.equal(await page.getByTestId('mutation').innerText(), 'pending')
191 const sqlBefore = await db.query(
192 'select label from public.electric_items where id=$1',
193 [mutation.id]
194 )
195 assert.notEqual(sqlBefore.rows[0].label, 'optimistic')
196 release()
197 await until(
198 async () =>
199 (await page.getByTestId('mutation').innerText()) === 'persisted'
200 )
201 await page.unroute('**/api/items')
202 await page.route('**/api/items', async (route) => {
203 const body = route.request().postDataJSON()
204 assert.equal(body.noop, true)
205 assert.equal(body.id, id)
206 const result = await db.query(
207 'update public.electric_items set label=label where id=$1 returning pg_current_xact_id()::text as txid',
208 [id]
209 )
210 await route.fulfill({
211 status: 200,
212 contentType: 'application/json',
213 body: JSON.stringify({
214 txid: Number(BigInt.asUintN(32, BigInt(result.rows[0].txid))),
215 }),
216 })
217 })
218 await page
219 .getByRole('button', { name: 'Acknowledge unchanged row' })
220 .click()
221 await until(
222 async () =>
223 (await page.getByTestId('mutation').innerText()) === 'acknowledged'
224 )
225 }
226 if (mode.endsWith('-sse'))
227 assert(
228 requests.some(
229 (request) =>
230 new URL(request.url()).searchParams.get('live_sse') === 'true'
231 ),
232 'SSE mode never opened an SSE request'
233 )
234 assert(requests.length > 2)
235 for (const request of requests) {
236 const url = new URL(request.url())
237 assert.equal(url.origin, origin)
238 assert.equal(url.pathname, '/application/shapes')
239 assert.equal(url.searchParams.get('table'), 'electric_items')
240 assert.equal(url.searchParams.get('example'), 'integration')
241 assert.equal(request.method(), 'GET')
242 }
243 assert(
244 new Set(requests.map((r) => r.headers().authorization)).size > 1,
245 'Dynamic auth was not refreshed'
246 )
247 assert(
248 requests.some((r) =>
249 r.headers().authorization?.startsWith('refreshed-token-')
250 ),
251 'Public FetchError identity or onError auth recovery failed'
252 )
253 report.modes.push({ mode, requests: requests.length, status: 'passed' })
254 await context.close()
255 await db.query('update public.electric_items set label=$2 where id=$1', [
256 id,
257 'browser baseline',
258 ])
259 }
260 report.status = 'passed'
261 console.log(
262 'Packed basic, published React hook and eager TanStack browser integrations passed against local neon dev/staging data'
263 )
264} catch (error) {
265 report.status = 'failed'
266 report.error = String(error)
267 throw error
268} finally {
269 report.completedAt = new Date().toISOString()
270 await browser.close()
271 serving.httpServer.closeAllConnections?.()
272 await new Promise((resolve) => serving.httpServer.close(resolve))
273 await db.query('delete from public.electric_items where id=$1', [id])
274 for (const handle of handles) {
275 const url = new URL(
276 '/api/shape?table=electric_items',
277 process.env.SHAPE_URL ?? 'http://localhost:4327'
278 )
279 url.searchParams.set('handle', handle)
280 await fetch(url, { method: 'DELETE', signal: AbortSignal.timeout(10_000) })
281 }
282 await db.end()
283 await mkdir(`${root}.artifacts/staging`, { recursive: true })
284 await writeFile(
285 `${root}.artifacts/staging/browser-integrations.json`,
286 JSON.stringify(report, null, 2)
287 )