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

cache.test.ts

355 lines11.1 KB

1import { describe, expect, assert, inject } from 'vitest'
2import { exec } from 'child_process'
3import { setTimeout as sleep } from 'node:timers/promises'
4import { testWithIssuesTable } from './support/test-context'
5import { CHUNK_LAST_OFFSET_HEADER, SHAPE_HANDLE_HEADER } from '../src/constants'
6import { ShapeStream } from '../src'
7import { isUpToDateMessage } from '../src/helpers'
8​
9// FIXME: pull from environment?
10const maxAge = 1 // seconds
11const staleAge = 3 // seconds
12​
13// see https://blog.nginx.org/blog/nginx-caching-guide for details
14enum CacheStatus {
15 MISS = `MISS`, // item was not in the cache
16 BYPASS = `BYPASS`, // not used by us
17 EXPIRED = `EXPIRED`, // there was a cache entry but was expired, so we got a fresh response
18 STALE = `STALE`, // cache entry > max age but < stale-while-revalidate so we got a stale response
19 UPDATING = `UPDATING`, // same as STALE but indicates proxy is updating stale entry
20 REVALIDATED = `REVALIDATED`, // you this request revalidated at the server
21 HIT = `HIT`, // cache hit
23​
24/**
25 * Retrieve the {@link CacheStatus} from the provided response
26 */
27function getCacheStatus(res: Response): CacheStatus {
28 return res.headers.get(`X-Proxy-Cache`) as CacheStatus
30​
31/**
32 * Clear the proxy cache files to simulate an empty cache
33 */
34export async function clearProxyCache({
35 proxyCacheContainerName,
36 proxyCachePath,
37}: {
38 proxyCacheContainerName: string
39 proxyCachePath: string
40}): Promise<void> {
41 return new Promise((res) =>
42 exec(
43 `docker exec ${proxyCacheContainerName} sh -c 'rm -rf ${proxyCachePath}'`,
44 (_) => res()
45 )
46 )
48​
49const it = testWithIssuesTable.extend<{
50 proxyCacheBaseUrl: string
51 clearCache: () => Promise<void>
52}>({
53 proxyCacheBaseUrl: async ({ clearCache }, use) => {
54 await clearCache()
55 use(inject(`proxyCacheBaseUrl`))
56 },
57 clearCache: async ({}, use) => {
58 use(
59 async () =>
60 await clearProxyCache({
61 proxyCacheContainerName: inject(`proxyCacheContainerName`),
62 proxyCachePath: inject(`proxyCachePath`),
63 })
64 )
65 },
66})
67​
68describe(`HTTP Proxy Cache`, () => {
69 it(`should get a short max-age cache-conrol header in live mode`, async ({
70 insertIssues,
71 proxyCacheBaseUrl,
72 issuesTableUrl,
73 }) => {
74 // First request get initial request
75 const initialRes = await fetch(
76 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=-1`,
77 {}
78 )
79​
80 expect(initialRes.status).toBe(200)
81 expect(getCacheStatus(initialRes)).toBe(CacheStatus.MISS)
82​
83 // add some data and follow with live request
84 await insertIssues({ title: `foo` })
85 const searchParams = new URLSearchParams({
86 table: issuesTableUrl,
87 handle: initialRes.headers.get(`electric-handle`)!,
88 offset: initialRes.headers.get(`electric-offset`)!,
89 live: `true`,
90 })
91​
92 const liveRes = await fetch(
93 `${proxyCacheBaseUrl}/v1/shape?${searchParams.toString()}`,
94 {}
95 )
96 expect(liveRes.status).toBe(200)
97 expect(getCacheStatus(liveRes)).toBe(CacheStatus.MISS)
98​
99 // Second request gets a cached response
100 const cachedRes = await fetch(
101 `${proxyCacheBaseUrl}/v1/shape?${searchParams.toString()}`,
102 {}
103 )
104 expect(cachedRes.status).toBe(200)
105​
106 expect(getCacheStatus(cachedRes)).toBe(CacheStatus.HIT)
107 })
108​
109 it(`should collapse requests in live mode`, async ({
110 insertIssues,
111 proxyCacheBaseUrl,
112 issuesTableUrl,
113 aborter,
114 }) => {
115 const numClients = 10
116 const eventTarget = new EventTarget()
117​
118 let reqStats = {
119 reqs: 0,
120 cacheHits: 0,
121 }
122​
123 const resetReqStats = () => {
124 reqStats = {
125 reqs: 0,
126 cacheHits: 0,
127 }
128 }
129​
130 const fetchClient = async (...args: Parameters<typeof fetch>) => {
131 const resp = await fetch(...args)
132 reqStats.reqs++
133 if (getCacheStatus(resp) === CacheStatus.HIT) {
134 reqStats.cacheHits++
135 }
136​
137 return resp
138 }
139​
140 const waitForClients = () =>
141 new Promise<void>((res) => {
142 let ctr = 0
143 const listener = () => {
144 if (++ctr === numClients) {
145 eventTarget.removeEventListener(`up-to-date`, listener)
146 res()
147 }
148 }
149 eventTarget.addEventListener(`up-to-date`, listener)
150 })
151​
152 for (let i = 0; i < numClients; i++) {
153 const stream = new ShapeStream({
154 url: `${proxyCacheBaseUrl}/v1/shape`,
155 signal: aborter.signal,
156 fetchClient,
157 params: {
158 table: issuesTableUrl,
159 foo: `cache-test`,
160 },
161 })
162​
163 stream.subscribe((messages) => {
164 if (isUpToDateMessage(messages[messages.length - 1])) {
165 eventTarget.dispatchEvent(new Event(`up-to-date`))
166 }
167 })
168 }
169​
170 // wait for clients to catch up
171 await waitForClients()
172​
173 // add some data, should collapse requests and respond to
174 // all of them but one with cache hits
175 resetReqStats()
176 await insertIssues({ title: `foo` })
177 await waitForClients()
178 expect(reqStats.reqs).toBe(numClients)
179 expect(reqStats.cacheHits).toBe(numClients - 1)
180 })
181​
182 it(`should get cached response on second request`, async ({
183 proxyCacheBaseUrl,
184 issuesTableUrl,
185 }) => {
186 // First request gets non-cached response
187 const originalRes = await fetch(
188 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=-1`,
189 {}
190 )
191​
192 expect(originalRes.status).toBe(200)
193 expect(getCacheStatus(originalRes)).toBe(CacheStatus.MISS)
194​
195 // Second request gets cached response
196 const cachedRes = await fetch(
197 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=-1`,
198 {}
199 )
200 expect(cachedRes.status).toBe(200)
201​
202 expect(getCacheStatus(cachedRes)).toBe(CacheStatus.HIT)
203 })
204​
205 it(`should get stale response when max age is passed but cache is not yet revalidated`, async ({
206 proxyCacheBaseUrl,
207 issuesTableUrl,
208 }) => {
209 const originalRes = await fetch(
210 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=-1`,
211 {}
212 )
213 const lastOffset = originalRes.headers.get(CHUNK_LAST_OFFSET_HEADER)
214 const shapeHandle = originalRes.headers.get(SHAPE_HANDLE_HEADER)
215 const urlToTest = `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=${lastOffset}&handle=${shapeHandle}`
216​
217 // Make a first request such that response is cached
218 const originalUpToDateRes = await fetch(urlToTest, {})
219​
220 expect(originalUpToDateRes.status).toBe(200)
221 expect(getCacheStatus(originalUpToDateRes)).toBe(CacheStatus.MISS)
222​
223 // Second request gets cached response
224 const cachedRes = await fetch(urlToTest, {})
225 expect(cachedRes.status).toBe(200)
226​
227 expect(getCacheStatus(cachedRes)).toBe(CacheStatus.HIT)
228​
229 // Now wait for the response to be passed its max-age but before the stale-while-revalidate
230 await sleep(maxAge * 1000 + ((staleAge - maxAge) / 2) * 1000)
231​
232 // Third request gets cached response
233 const staleRes = await fetch(urlToTest, {})
234​
235 expect(staleRes.status).toBe(200)
236 expect(getCacheStatus(staleRes)).toBe(CacheStatus.STALE)
237 })
238​
239 it(`should get fresh response when age is passed the stale age`, async ({
240 proxyCacheBaseUrl,
241 issuesTableUrl,
242 }) => {
243 const originalRes = await fetch(
244 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=-1`,
245 {}
246 )
247 const lastOffset = originalRes.headers.get(CHUNK_LAST_OFFSET_HEADER)
248 const shapeHandle = originalRes.headers.get(SHAPE_HANDLE_HEADER)
249 const urlToTest = `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=${lastOffset}&handle=${shapeHandle}`
250​
251 // Make a first request such that response is cached
252 const originalUpToDateRes = await fetch(urlToTest, {})
253​
254 expect(originalUpToDateRes.status).toBe(200)
255 expect(getCacheStatus(originalUpToDateRes)).toBe(CacheStatus.MISS)
256​
257 // Second request gets cached response
258 const cachedRes = await fetch(urlToTest, {})
259 expect(cachedRes.status).toBe(200)
260​
261 expect(getCacheStatus(cachedRes)).toBe(CacheStatus.HIT)
262​
263 // Now wait for the response to be passed its max-age but before the stale-while-revalidate
264 await sleep(staleAge * 1000 + 2000)
265​
266 // Third request gets cached response
267 const staleRes = await fetch(urlToTest, {})
268​
269 expect(staleRes.status).toBe(200)
270 expect(getCacheStatus(staleRes)).toBe(CacheStatus.REVALIDATED)
271 }, 10_000)
272})
273​
274describe(`HTTP Initial Data Caching`, () => {
275 it(`tells client to resync when shape is out of scope`, async ({
276 proxyCacheBaseUrl,
277 issuesTableUrl,
278 clearIssuesShape,
279 insertIssues,
280 }) => {
281 // add some data
282 await insertIssues({ title: `foo1` }, { title: `foo2` })
283​
284 // Make a client that fetches a shape
285 // which forces the shape data to be cached
286 const client1Res = await fetch(
287 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=-1`,
288 {}
289 )
290 expect(client1Res.status).toBe(200)
291 const originalShapeHandle =
292 client1Res.headers.get(`electric-handle`) ?? undefined
293 assert(originalShapeHandle, `Should have shape handle`)
294 expect(getCacheStatus(client1Res)).toBe(CacheStatus.MISS)
295​
296 // Make a 2nd client that fetches the shape
297 // check that it is served from cached data
298 const client2Res = await fetch(
299 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=-1`,
300 {}
301 )
302 expect(client2Res.status).toBe(200)
303 const shapeHandle2 = client2Res.headers.get(`electric-handle`) ?? undefined
304​
305 expect(
306 originalShapeHandle,
307 `Shape handle changed but expected it to stay the same`
308 ).toBe(shapeHandle2)
309​
310 expect(getCacheStatus(client2Res)).toBe(CacheStatus.HIT)
311​
312 const latestOffset = client2Res.headers.get(`electric-offset`)
313 assert(latestOffset, `latestOffset should be defined`)
314​
315 // Now GC the shape
316 await clearIssuesShape(originalShapeHandle)
317​
318 // Now try to go live
319 // should tell you to go back to initial sync
320 // because the shape is out of scope
321 const liveRes = await fetch(
322 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=${latestOffset}&handle=${originalShapeHandle}&live`,
323 {}
324 )
325 expect(liveRes.status).toBe(409)
326 const newShapeHandle = liveRes.headers.get(SHAPE_HANDLE_HEADER)
327 assert(newShapeHandle !== originalShapeHandle)
328​
329 const newCacheIgnoredSyncRes = await fetch(
330 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=-1&handle=${newShapeHandle}`,
331 {}
332 )
333​
334 expect(newCacheIgnoredSyncRes.status).toBe(200)
335 expect(getCacheStatus(newCacheIgnoredSyncRes)).toBe(CacheStatus.MISS)
336 const cacheBustedShapeHandle =
337 newCacheIgnoredSyncRes.headers.get(SHAPE_HANDLE_HEADER)
338 assert(cacheBustedShapeHandle)
339 expect(cacheBustedShapeHandle).not.toBe(originalShapeHandle)
340​
341 // Then try do that and check that we get new shape handle
342 const newInitialSyncRes = await fetch(
343 `${proxyCacheBaseUrl}/v1/shape?table=${issuesTableUrl}&offset=-1&handle=${newShapeHandle}`,
344 {}
345 )
346 const cachedShapeHandle =
347 newInitialSyncRes.headers.get(SHAPE_HANDLE_HEADER) ?? undefined
348 expect(newInitialSyncRes.status).toBe(200)
349 expect(getCacheStatus(newInitialSyncRes)).toBe(CacheStatus.HIT)
350 expect(
351 cachedShapeHandle,
352 `Got old shape handle that is out of scope`
353 ).not.toBe(originalShapeHandle)
354 })
355})