Open History to see the last commit
1import assert from 'node:assert/strict'
2import { once } from 'node:events'
3import { readFile } from 'node:fs/promises'
4import { createServer } from 'node:http'
5import { createRequire } from 'node:module'
6import path from 'node:path'
7import { Readable } from 'node:stream'
8import { pathToFileURL } from 'node:url'
9import { createShapeHandler } from '../../../packages/server/src/handler.ts'
10import { ObjectShapeLog } from '../../../packages/server/src/object-log.ts'
11import { FixtureObjectStore } from '../../server/support/object-store.ts'
12
13const fixture = process.argv[2]
14assert.ok(fixture, 'Pass the isolated package fixture directory')
15const require = createRequire(path.join(fixture, 'package.json'))
16async function load(name, format) {
17 if (format === 'cjs') return require(name)
18 const metadataPath = require.resolve(`${name}/package.json`)
19 const metadata = JSON.parse(await readFile(metadataPath, 'utf8'))
20 return import(
21 pathToFileURL(
22 path.resolve(
23 path.dirname(metadataPath),
24 metadata.exports['.'].import.default
25 )
26 ).href
27 )
28}
29
30let scenarios = 0
31for (const originalFormat of ['esm', 'cjs'])
32 for (const candidateFormat of ['esm', 'cjs']) {
33 const original = await load('electric-reference', originalFormat)
34 const candidate = await load('electric-candidate', candidateFormat)
35 assert.notEqual(original.Shape, candidate.Shape)
36 for (const backend of ['memory', 'objects'])
37 for (const liveSse of [false, true]) {
38 await scenario(original, candidate, backend, liveSse)
39 scenarios++
40 }
41 }
42console.log(`Cross-package materializers: ${scenarios} scenarios passed`)
43
44async function scenario(original, candidate, backend, liveSse) {
45 const observers = []
46 const requests = []
47 const errors = []
48 const store = new FixtureObjectStore()
49 const date = '2026-10-15T12:00:00+00:00'
50 let title = 'initial'
51 let txid = 10
52 const key = (id) => String(id).repeat(64)
53 const handler = createShapeHandler({
54 longPollMs: 30,
55 sseConnectionMs: 100,
56 createLog:
57 backend === 'objects'
58 ? ({ handle, expiresAt }) =>
59 new ObjectShapeLog({
60 store,
61 prefix: `interop/${expiresAt}/${handle}`,
62 sealBytes: 1,
63 })
64 : undefined,
65 source: {
66 async subscribe(_, observer) {
67 observers.push(observer)
68 observer.event({
69 type: 'schema',
70 columns: [
71 { name: 'id', type_oid: 23, typmod: -1, codec: 'pg_text' },
72 { name: 'title', type_oid: 25, typmod: -1, codec: 'pg_text' },
73 {
74 name: 'created_at',
75 type_oid: 1184,
76 typmod: -1,
77 codec: 'pg_text',
78 },
79 ],
80 })
81 observer.event({
82 type: 'baseline',
83 rows: [{ row_key: key(1), values: ['1', title, date] }],
84 mvcc: { xmin: '10', xmax: '10', xip: [] },
85 })
86 return { close() {} }
87 },
88 close() {},
89 },
90 async authorize() {
91 return {
92 authorizationKey: 'interop-fixture',
93 definition: {
94 namespace: 'public',
95 table: 'tasks',
96 primaryKey: ['id'],
97 projection: ['id', 'title', 'created_at'],
98 schema: {
99 id: { type: 'int4' },
100 title: { type: 'text' },
101 created_at: { type: 'timestamptz' },
102 },
103 query: { sql: 'select id, title, created_at from public.tasks' },
104 },
105 }
106 },
107 })
108 const server = createServer((req, res) => {
109 void (async () => {
110 const url = new URL(req.url, 'http://fixture')
111 requests.push({ url, method: req.method })
112 const abort = new AbortController()
113 res.on('close', () => abort.abort())
114 const response = await handler.fetch(
115 new Request(url, { method: req.method, signal: abort.signal })
116 )
117 res.writeHead(response.status, Object.fromEntries(response.headers))
118 if (response.body)
119 Readable.fromWeb(response.body)
120 .on('error', () => res.destroy())
121 .pipe(res)
122 else res.end()
123 })().catch((error) => {
124 errors.push(error)
125 res.destroy()
126 })
127 })
128 server.listen(0, '127.0.0.1')
129 await once(server, 'listening')
130 const abort = new AbortController()
131 let stream
132 const shapes = []
133 try {
134 stream = new candidate.ShapeStream({
135 url: `http://127.0.0.1:${server.address().port}/application/shapes?tenant=a%2Bb`,
136 params: { table: 'tasks' },
137 parser: { timestamptz: (value) => new Date(value) },
138 columnMapper: candidate.snakeCamelMapper(),
139 signal: abort.signal,
140 liveSse,
141 onError: (error) => {
142 errors.push(error)
143 },
144 })
145 shapes.push(new original.Shape(stream), new candidate.Shape(stream))
146 const row = (id, title) => ({ id, title, createdAt: new Date(date) })
147 const expectRows = (rows) =>
148 Promise.all(shapes.map((shape) => waitRows(shape, rows)))
149 await expectRows([row(1, title)])
150 const firstHandle = stream.shapeHandle
151 assert.ok(firstHandle)
152 const publish = (changes) => {
153 txid++
154 observers[0].event({
155 type: 'publication',
156 changes,
157 txids: [String(txid)],
158 frontier: { lsn: `0/${txid.toString(16).toUpperCase()}` },
159 })
160 }
161 publish([
162 { op: 'upsert', row_key: key(2), values: ['2', 'inserted', date] },
163 ])
164 await expectRows([row(1, title), row(2, 'inserted')])
165 title = 'updated'
166 publish([{ op: 'upsert', row_key: key(1), values: ['1', title, date] }])
167 await expectRows([row(1, title), row(2, 'inserted')])
168 publish([{ op: 'remove', row_key: key(2) }])
169 await expectRows([row(1, title)])
170 // A distinct baseline proves that both materializers consume the reset.
171 title = 'after owner loss'
172 observers[0].error(new Error('intentional interop owner loss'))
173 await expectRows([row(1, title)])
174 assert.notEqual(stream.shapeHandle, firstHandle)
175 assert.equal(observers.length, 2)
176 for (const shape of shapes) {
177 assert.equal(shape.handle, stream.shapeHandle)
178 assert.equal(shape.lastOffset, stream.lastOffset)
179 assert.equal(shape.isUpToDate, true)
180 assert.deepEqual(await shape.rows, [row(1, title)])
181 }
182 for (const { url, method } of requests) {
183 assert.equal(url.pathname, '/application/shapes')
184 assert.equal(url.searchParams.get('tenant'), 'a+b')
185 assert.equal(method, 'GET')
186 }
187 assert.ok(requests.some(({ url }) => url.searchParams.has('handle')))
188 if (liveSse)
189 assert.ok(
190 requests.some(({ url }) => url.searchParams.get('live_sse') === 'true')
191 )
192 if (backend === 'objects') assert.ok(store.gets.length > 0)
193 assert.deepEqual(errors, [])
194 } finally {
195 abort.abort()
196 for (const shape of shapes) shape.unsubscribeAll()
197 stream?.unsubscribeAll()
198 handler.close()
199 await handler.drain()
200 server.closeAllConnections()
201 await new Promise((resolve) => server.close(resolve))
202 }
203}
204
205function waitRows(shape, expected) {
206 return new Promise((resolve, reject) => {
207 let unsubscribe = () => {}
208 const timer = setTimeout(() => {
209 unsubscribe()
210 reject(
211 new Error(
212 `Materializer did not reach ${JSON.stringify(expected)}; got ${JSON.stringify(shape.currentRows)}`
213 )
214 )
215 }, 5_000)
216 const check = () => {
217 try {
218 assert.deepEqual(shape.currentRows, expected)
219 assert.equal(shape.isUpToDate, true)
220 } catch {
221 return
222 }
223 clearTimeout(timer)
224 unsubscribe()
225 resolve()
226 }
227 unsubscribe = shape.subscribe(check)
228 check()
229 })
230}