Open History to see the last commit
1import { createServer } from 'node:http'
2import { once } from 'node:events'
3import { describe, expect, it } from 'vitest'
4import { Shape, ShapeStream } from '../../packages/client/src/index.js'
5import { createShapeHandler } from '../../packages/server/src/handler.js'
6import { resolveConfiguredShape } from '../../packages/server/src/definition.js'
7import type { SourceObserver } from '../../packages/server/src/realtime-source.js'
8import { ObjectShapeLog } from '../../packages/server/src/object-log.js'
9import { FixtureObjectStore } from './support/object-store.js'
10import { proxyFixture } from '../compatibility/proxies/fixtures.js'
11
12for (const backend of ['memory', 'objects'])
13 describe(`production handler through unchanged proxy routes (${backend})`, () => {
14 for (const mode of [
15 'transparent',
16 'electric-allowlist',
17 'trusted-predicate',
18 ] as const)
19 it(`preserves eager/live/refetch through ${mode}`, async () => {
20 const observers: SourceObserver[] = []
21 const queries: unknown[] = []
22 let label = 'initial'
23 const schema = {
24 id: { type: 'int4' },
25 label: { type: 'text' },
26 tenant_id: { type: 'text' },
27 }
28 const baseline = (observer: SourceObserver) =>
29 observer.event({
30 type: 'baseline',
31 rows: [
32 {
33 row_key: 'a'.repeat(64),
34 values: ['1', label, 'trusted-tenant'],
35 },
36 ],
37 mvcc: { xmin: '1', xmax: '2', xip: [] },
38 })
39 const store = new FixtureObjectStore()
40 const handler = createShapeHandler({
41 longPollMs: 20,
42 createLog:
43 backend === 'objects'
44 ? ({ handle, expiresAt }) =>
45 new ObjectShapeLog({
46 store,
47 prefix: `proxies/${expiresAt}/${handle}`,
48 sealBytes: 1,
49 })
50 : undefined,
51 source: {
52 async subscribe(query, observer) {
53 queries.push(query)
54 observers.push(observer)
55 observer.event({
56 type: 'schema',
57 columns: [
58 { name: 'id', type_oid: 23, typmod: -1, codec: 'pg_text' },
59 { name: 'label', type_oid: 25, typmod: -1, codec: 'pg_text' },
60 {
61 name: 'tenant_id',
62 type_oid: 25,
63 typmod: -1,
64 codec: 'pg_text',
65 },
66 ],
67 })
68 if (observers.length > 1) baseline(observer)
69 return { close() {} }
70 },
71 close() {},
72 },
73 async authorize(request) {
74 const url = new URL(request.url)
75 // Fixed server-side table supplies the route's trusted shape when
76 // an unchanged Electric allowlist intentionally drops table/where.
77 if (!url.searchParams.has('table'))
78 url.searchParams.set('table', 'items')
79 return {
80 authorizationKey: 'proxy-test',
81 definition: resolveConfiguredShape(url, [
82 {
83 namespace: 'public',
84 table: 'items',
85 primaryKey: ['id'],
86 columns: schema,
87 },
88 ]),
89 }
90 },
91 })
92 const http = createServer((req, res) => {
93 void (async () => {
94 const abort = new AbortController()
95 res.on('close', () => abort.abort())
96 const response = await handler.fetch(
97 new Request(`http://local${req.url}`, { signal: abort.signal })
98 )
99 res.writeHead(
100 response.status,
101 Object.fromEntries(response.headers.entries())
102 )
103 res.end(Buffer.from(await response.arrayBuffer()))
104 })().catch(() => {
105 if (!res.destroyed) res.writeHead(500).end()
106 })
107 })
108 http.listen(0, '127.0.0.1')
109 await once(http, 'listening')
110 const proxy = await proxyFixture(
111 `http://127.0.0.1:${(http.address() as { port: number }).port}/api/shape`,
112 mode,
113 500
114 )
115 const abort = new AbortController()
116 try {
117 const stream = new ShapeStream({
118 url: `${proxy.url}/application/shapes?custom=a%2Bb`,
119 params: { table: 'items' },
120 signal: abort.signal,
121 })
122 const shape = new Shape(stream)
123 await expect.poll(() => stream.shapeHandle).toBeTruthy()
124 expect(shape.isUpToDate).toBe(false)
125 baseline(observers[0])
126 await expect
127 .poll(() => shape.currentRows)
128 .toEqual([{ id: 1, label: 'initial', tenant_id: 'trusted-tenant' }])
129 label = 'changed'
130 observers[0].event({
131 type: 'publication',
132 changes: [
133 {
134 op: 'upsert',
135 row_key: 'a'.repeat(64),
136 values: ['1', label, 'trusted-tenant'],
137 },
138 ],
139 txids: ['2'],
140 frontier: { lsn: '0/12' },
141 })
142 await expect.poll(() => shape.currentRows[0]?.label).toBe('changed')
143 const previous = stream.shapeHandle
144 observers[0].error(new Error('intentional owner loss'))
145 await expect.poll(() => stream.shapeHandle).not.toBe(previous)
146 await expect.poll(() => shape.currentRows[0]?.label).toBe('changed')
147 expect(queries.length).toBe(2)
148 if (mode === 'trusted-predicate')
149 expect(queries[0]).toMatchObject({ parameters: ['trusted-tenant'] })
150 for (const url of proxy.requests) {
151 expect(url.pathname).toBe('/application/shapes')
152 expect(url.searchParams.get('custom')).toBe('a+b')
153 }
154 } finally {
155 abort.abort()
156 await proxy.stop()
157 handler.close()
158 await handler.drain()
159 http.closeAllConnections()
160 await new Promise<void>((resolve) => http.close(() => resolve()))
161 }
162 })
163 })