-
-
Notifications
You must be signed in to change notification settings - Fork 756
Expand file tree
/
Copy pathcache-store-test-utils.js
More file actions
434 lines (363 loc) · 11.2 KB
/
cache-store-test-utils.js
File metadata and controls
434 lines (363 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
'use strict'
const { equal, notEqual, deepStrictEqual } = require('node:assert')
const { describe, test, after } = require('node:test')
const { Readable } = require('node:stream')
const { once } = require('node:events')
const FakeTimers = require('@sinonjs/fake-timers')
const fakeTimersOpts = { toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'setImmediate', 'clearImmediate', 'Date', 'hrtime', 'performance', ...(typeof Intl !== 'undefined' ? ['Intl'] : [])] }
/**
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore
*
* @param {{ new(...any): CacheStore }} CacheStore
* @param {object} [options]
* @param {boolean} [options.skip]
*/
function cacheStoreTests (CacheStore, options) {
describe(CacheStore.prototype.constructor.name, () => {
test('matches interface', options, () => {
equal(typeof CacheStore.prototype.get, 'function')
equal(typeof CacheStore.prototype.createWriteStream, 'function')
equal(typeof CacheStore.prototype.delete, 'function')
})
test('caches request', options, async () => {
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
const key = {
origin: 'localhost',
path: '/',
method: 'GET',
headers: {}
}
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const value = {
statusCode: 200,
statusMessage: '',
headers: { foo: 'bar' },
cacheControlDirectives: {},
cachedAt: Date.now(),
staleAt: Date.now() + 10000,
deleteAt: Date.now() + 20000
}
const body = [Buffer.from('asd'), Buffer.from('123')]
const store = new CacheStore()
// Sanity check
equal(await store.get(key), undefined)
// Write response to store
{
const writable = store.createWriteStream(key, value)
notEqual(writable, undefined)
writeBody(writable, body)
}
// Now let's try fetching the response from the store
{
const result = await store.get(structuredClone(key))
notEqual(result, undefined)
await compareGetResults(result, value, body)
}
/**
* Let's try out a request to a different resource to make sure it can
* differentiate between the two
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
const anotherKey = {
origin: 'localhost',
path: '/asd',
method: 'GET',
headers: {}
}
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const anotherValue = {
statusCode: 200,
statusMessage: '',
headers: { foo: 'bar' },
cacheControlDirectives: {},
cachedAt: Date.now(),
staleAt: Date.now() + 10000,
deleteAt: Date.now() + 20000
}
const anotherBody = [Buffer.from('asd'), Buffer.from('123')]
equal(store.get(anotherKey), undefined)
{
const writable = store.createWriteStream(anotherKey, anotherValue)
notEqual(writable, undefined)
writeBody(writable, anotherBody)
}
{
const result = await store.get(structuredClone(anotherKey))
notEqual(result, undefined)
await compareGetResults(result, anotherValue, anotherBody)
}
})
test('returns stale response before deleteAt', options, async () => {
const clock = FakeTimers.install({ ...fakeTimersOpts, shouldClearNativeTimers: true })
after(() => clock.uninstall())
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
const key = {
origin: 'localhost',
path: '/',
method: 'GET',
headers: {}
}
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const value = {
statusCode: 200,
statusMessage: '',
headers: { foo: 'bar' },
cacheControlDirectives: {},
cachedAt: Date.now(),
staleAt: Date.now() + 1000,
// deleteAt is different because stale-while-revalidate, stale-if-error, ...
deleteAt: Date.now() + 5000
}
const body = [Buffer.from('asd'), Buffer.from('123')]
const store = new CacheStore()
// Sanity check
equal(store.get(key), undefined)
{
const writable = store.createWriteStream(key, value)
notEqual(writable, undefined)
writeBody(writable, body)
}
clock.tick(1500)
{
const result = await store.get(structuredClone(key))
notEqual(result, undefined)
await compareGetResults(result, value, body)
}
clock.tick(6000)
// Past deleteAt, shouldn't be returned
equal(await store.get(key), undefined)
})
test('a stale request is overwritten', options, async () => {
const clock = FakeTimers.install({ ...fakeTimersOpts, shouldClearNativeTimers: true })
after(() => clock.uninstall())
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
const key = {
origin: 'localhost',
path: '/',
method: 'GET',
headers: {}
}
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const value = {
statusCode: 200,
statusMessage: '',
headers: { foo: 'bar' },
cacheControlDirectives: {},
cachedAt: Date.now(),
staleAt: Date.now() + 1000,
// deleteAt is different because stale-while-revalidate, stale-if-error, ...
deleteAt: Date.now() + 5000
}
const body = [Buffer.from('asd'), Buffer.from('123')]
const store = new CacheStore()
// Sanity check
equal(store.get(key), undefined)
{
const writable = store.createWriteStream(key, value)
notEqual(writable, undefined)
writeBody(writable, body)
}
clock.tick(1500)
{
const result = await store.get(structuredClone(key))
notEqual(result, undefined)
await compareGetResults(result, value, body)
}
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const value2 = {
statusCode: 200,
statusMessage: '',
headers: { foo: 'baz' },
cacheControlDirectives: {},
cachedAt: Date.now(),
staleAt: Date.now() + 1000,
// deleteAt is different because stale-while-revalidate, stale-if-error, ...
deleteAt: Date.now() + 5000
}
const body2 = [Buffer.from('foo'), Buffer.from('123')]
{
const writable = store.createWriteStream(key, value2)
notEqual(writable, undefined)
writeBody(writable, body2)
}
{
const result = await store.get(structuredClone(key))
notEqual(result, undefined)
await compareGetResults(result, value2, body2)
}
})
test('vary directives used to decide which response to use', options, async () => {
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
const key = {
origin: 'localhost',
path: '/',
method: 'GET',
headers: {
'some-header': 'hello world'
}
}
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const value = {
statusCode: 200,
statusMessage: '',
headers: { foo: 'bar' },
vary: {
'some-header': 'hello world'
},
cacheControlDirectives: {},
cachedAt: Date.now(),
staleAt: Date.now() + 1000,
deleteAt: Date.now() + 1000
}
const body = [Buffer.from('asd'), Buffer.from('123')]
const store = new CacheStore()
// Sanity check
equal(store.get(key), undefined)
{
const writable = store.createWriteStream(key, value)
notEqual(writable, undefined)
writeBody(writable, body)
}
{
const result = await store.get(structuredClone(key))
notEqual(result, undefined)
await compareGetResults(result, value, body)
}
/**
* Let's make another key to the same resource but with a different vary
* header
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
const anotherKey = {
origin: 'localhost',
path: '/',
method: 'GET',
headers: {
'some-header': 'hello world2'
}
}
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const anotherValue = {
statusCode: 200,
statusMessage: '',
headers: { foo: 'bar' },
vary: {
'some-header': 'hello world2'
},
cacheControlDirectives: {},
cachedAt: Date.now(),
staleAt: Date.now() + 1000,
deleteAt: Date.now() + 1000
}
const anotherBody = [Buffer.from('asd'), Buffer.from('123')]
equal(await store.get(anotherKey), undefined)
{
const writable = store.createWriteStream(anotherKey, anotherValue)
notEqual(writable, undefined)
writeBody(writable, anotherBody)
}
{
const result = await store.get(structuredClone(key))
notEqual(result, undefined)
await compareGetResults(result, value, body)
}
{
const result = await store.get(structuredClone(anotherKey))
notEqual(result, undefined)
await compareGetResults(result, anotherValue, anotherBody)
}
})
})
}
/**
* @param {import('node:stream').Writable} stream
* @param {Buffer[]} body
*/
function writeBody (stream, body) {
for (const chunk of body) {
stream.write(chunk)
}
stream.end()
return stream
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.GetResult} param0
* @returns {Promise<Buffer[] | undefined>}
*/
async function readBody ({ body }) {
if (!body) {
return undefined
}
if (typeof body === 'string') {
return [Buffer.from(body)]
}
if (body.constructor.name === 'Buffer') {
return [body]
}
const stream = Readable.from(body)
/**
* @type {Buffer[]}
*/
const streamedBody = []
stream.on('data', chunk => {
streamedBody.push(Buffer.from(chunk))
})
await once(stream, 'end')
return streamedBody
}
/**
* @param {Buffer[]} buffers
* @returns {Buffer}
*/
function joinBufferArray (buffers) {
const data = []
for (const buffer of buffers) {
buffer.forEach((chunk) => {
data.push(chunk)
})
}
return Buffer.from(data)
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.GetResult} actual
* @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} expected
* @param {Buffer[]} expectedBody
*/
async function compareGetResults (actual, expected, expectedBody) {
const actualBody = await readBody(actual)
deepStrictEqual(
actualBody ? joinBufferArray(actualBody) : undefined,
joinBufferArray(expectedBody)
)
for (const key of Object.keys(expected)) {
deepStrictEqual(actual[key], expected[key])
}
}
module.exports = {
cacheStoreTests,
writeBody,
readBody,
compareGetResults
}