-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatterns.test.ts
More file actions
411 lines (341 loc) · 11.1 KB
/
patterns.test.ts
File metadata and controls
411 lines (341 loc) · 11.1 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
import type { CacheManager } from '../src/manager'
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import { createCache } from '../src/manager'
import {
CacheAside,
ReadThrough,
RefreshAhead,
WriteAround,
WriteBack,
WriteThrough,
} from '../src/patterns'
describe('Cache Patterns', () => {
let cache: CacheManager
beforeEach(() => {
cache = createCache({
driver: 'memory',
stdTTL: 60,
checkPeriod: 0,
})
})
afterEach(async () => {
await cache.flush()
await cache.close()
})
describe('CacheAside', () => {
test('should load data from source on cache miss', async () => {
// Arrange
const pattern = new CacheAside(cache)
let loadCount = 0
const loader = async (key: string) => {
loadCount++
return `data-${key}`
}
// Act
const result = await pattern.get('key1', loader)
// Assert
expect(result).toBe('data-key1')
expect(loadCount).toBe(1)
expect(await cache.get('key1')).toBe('data-key1')
})
test('should return cached data on cache hit', async () => {
// Arrange
const pattern = new CacheAside(cache)
await cache.set('key2', 'cached-data')
let loadCount = 0
const loader = async () => {
loadCount++
return 'fresh-data'
}
// Act
const result = await pattern.get('key2', loader)
// Assert
expect(result).toBe('cached-data')
expect(loadCount).toBe(0) // Loader should not be called
})
test('should invalidate cache entry', async () => {
// Arrange
const pattern = new CacheAside(cache)
await cache.set('key3', 'old-data')
// Act
await pattern.invalidate('key3')
// Assert
expect(await cache.has('key3')).toBe(false)
})
test('should support TTL', async () => {
// Arrange
const pattern = new CacheAside(cache)
const loader = async () => 'data'
// Act
await pattern.get('key4', loader, 300)
const ttl = await cache.getTtl('key4')
// Assert
expect(ttl).toBeGreaterThan(Date.now())
})
})
describe('ReadThrough', () => {
test('should load and cache data transparently', async () => {
// Arrange
let loadCount = 0
const loader = async (key: string) => {
loadCount++
return `value-${key}`
}
const pattern = new ReadThrough(cache, loader)
// Act
const result1 = await pattern.get('rt1')
const result2 = await pattern.get('rt1')
// Assert
expect(result1).toBe('value-rt1')
expect(result2).toBe('value-rt1')
expect(loadCount).toBe(1) // Only loaded once
})
test('should handle multiple keys independently', async () => {
// Arrange
const loader = async (key: string) => `value-${key}`
const pattern = new ReadThrough(cache, loader)
// Act
const result1 = await pattern.get('a')
const result2 = await pattern.get('b')
// Assert
expect(result1).toBe('value-a')
expect(result2).toBe('value-b')
})
test('should respect custom TTL', async () => {
// Arrange
const loader = async () => 'data'
const pattern = new ReadThrough(cache, loader, 300)
// Act
await pattern.get('ttl-key')
const ttl = await cache.getTtl('ttl-key')
// Assert
expect(ttl).toBeGreaterThan(Date.now())
})
})
describe('WriteThrough', () => {
test('should write to cache and store simultaneously', async () => {
// Arrange
const store: Record<string, any> = {}
const writer = async (key: string, value: any) => {
store[key] = value
}
const pattern = new WriteThrough(cache, writer)
// Act
await pattern.set('wt1', 'data1')
// Assert
expect(await cache.get('wt1')).toBe('data1')
expect(store.wt1).toBe('data1')
})
test('should handle write failures', async () => {
// Arrange
const writer = async () => {
throw new Error('write failed')
}
const pattern = new WriteThrough(cache, writer)
// Act & Assert
await expect(pattern.set('wt2', 'data')).rejects.toThrow('write failed')
})
test('should support TTL', async () => {
// Arrange
const store: Record<string, any> = {}
const writer = async (key: string, value: any) => {
store[key] = value
}
const pattern = new WriteThrough(cache, writer)
// Act
await pattern.set('wt3', 'data', 300)
const ttl = await cache.getTtl('wt3')
// Assert
expect(ttl).toBeGreaterThan(Date.now())
})
})
describe('WriteAround', () => {
test('should write to store but invalidate cache', async () => {
// Arrange
const store: Record<string, any> = {}
const writer = async (key: string, value: any) => {
store[key] = value
}
const pattern = new WriteAround(cache, writer)
await cache.set('wa1', 'old-value')
// Act
await pattern.set('wa1', 'new-value')
// Assert
expect(store.wa1).toBe('new-value')
expect(await cache.has('wa1')).toBe(false) // Cache invalidated
})
test('should prevent stale cache reads', async () => {
// Arrange
const store: Record<string, any> = { wa2: 'initial' }
const writer = async (key: string, value: any) => {
store[key] = value
}
const pattern = new WriteAround(cache, writer)
await cache.set('wa2', 'cached')
// Act
await pattern.set('wa2', 'updated')
// Assert
expect(await cache.get('wa2')).toBeUndefined() // Not in cache
expect(store.wa2).toBe('updated') // Updated in store
})
})
describe('WriteBack', () => {
test('should write to cache immediately', async () => {
// Arrange
const store: Record<string, any> = {}
const writer = async (key: string, value: any) => {
store[key] = value
}
const pattern = new WriteBack(cache, writer, 100)
// Act
await pattern.set('wb1', 'data1')
// Assert
expect(await cache.get('wb1')).toBe('data1')
expect(store.wb1).toBeUndefined() // Not written yet
})
test('should flush writes after delay', async () => {
// Arrange
const store: Record<string, any> = {}
const writer = async (key: string, value: any) => {
store[key] = value
}
const pattern = new WriteBack(cache, writer, 100)
// Act
await pattern.set('wb2', 'data2')
await new Promise(resolve => setTimeout(resolve, 150))
// Assert
expect(store.wb2).toBe('data2')
})
test('should batch multiple writes', async () => {
// Arrange
const store: Record<string, any> = {}
let writeCount = 0
const writer = async (key: string, value: any) => {
writeCount++
store[key] = value
}
const pattern = new WriteBack(cache, writer, 100)
// Act
await pattern.set('wb3', 'v1')
await pattern.set('wb3', 'v2')
await pattern.set('wb3', 'v3')
await new Promise(resolve => setTimeout(resolve, 150))
// Assert
expect(store.wb3).toBe('v3') // Last value
expect(writeCount).toBe(1) // Only one write (batched)
})
test('should flush on demand', async () => {
// Arrange
const store: Record<string, any> = {}
const writer = async (key: string, value: any) => {
store[key] = value
}
const pattern = new WriteBack(cache, writer, 1000)
// Act
await pattern.set('wb4', 'data4')
await pattern.flush()
// Assert
expect(store.wb4).toBe('data4') // Immediately flushed
})
})
describe('RefreshAhead', () => {
test('should return cached value and refresh in background', async () => {
// Arrange
let loadCount = 0
const loader = async (_key: string) => {
loadCount++
return `value-${loadCount}`
}
const pattern = new RefreshAhead(cache, loader, 1) // 1 second TTL
// Act
const result1 = await pattern.get('ra1')
await new Promise(resolve => setTimeout(resolve, 1100))
const result2 = await pattern.get('ra1')
// Assert
expect(result1).toBe('value-1')
expect(result2).toBeDefined() // Should return old value while refreshing
expect(loadCount).toBeGreaterThanOrEqual(1)
})
test('should trigger refresh before expiration', async () => {
// Arrange
let loadCount = 0
const loader = async () => {
loadCount++
return loadCount
}
const pattern = new RefreshAhead(cache, loader, 2, 0.5) // Refresh at 50%
// Act
await pattern.get('ra2')
await new Promise(resolve => setTimeout(resolve, 1100)) // Past 50% of TTL
await pattern.get('ra2')
// Wait for background refresh
await new Promise(resolve => setTimeout(resolve, 100))
// Assert
expect(loadCount).toBe(2) // Initial load + refresh
})
test('should handle concurrent requests during refresh', async () => {
// Arrange
let loadCount = 0
const loader = async () => {
loadCount++
await new Promise(resolve => setTimeout(resolve, 50))
return loadCount
}
const pattern = new RefreshAhead(cache, loader, 1)
// Act
await pattern.get('ra3')
await new Promise(resolve => setTimeout(resolve, 1100))
// Make concurrent requests
const [r1, r2, r3] = await Promise.all([
pattern.get('ra3'),
pattern.get('ra3'),
pattern.get('ra3'),
])
// Assert
expect(r1).toBeDefined()
expect(r2).toBeDefined()
expect(r3).toBeDefined()
// Should not trigger too many refreshes (some timing variation allowed)
expect(loadCount).toBeLessThanOrEqual(5)
})
})
describe('Pattern Integration', () => {
test('should combine cache-aside with write-through', async () => {
// Arrange
const store: Record<string, any> = {}
const reader = new CacheAside(cache)
const writer = new WriteThrough(cache, async (key, value) => {
store[key] = value
})
// Act
await writer.set('key1', 'value1')
const result = await reader.get('key1', async () => {
return store.key1
})
// Assert
expect(result).toBe('value1')
})
test('should use read-through with write-back', async () => {
// Arrange
const store: Record<string, any> = { initial: 'data' }
const reader = new ReadThrough(cache, async key => store[key])
const writer = new WriteBack(cache, async (key, value) => {
store[key] = value
}, 100)
// Act
await writer.set('new', 'value')
const result = await reader.get('initial')
// Assert
expect(result).toBe('data')
expect(await cache.get('new')).toBe('value')
})
test('should handle pattern errors gracefully', async () => {
// Arrange
const pattern = new ReadThrough(cache, async () => {
throw new Error('loader failed')
})
// Act & Assert
await expect(pattern.get('error-key')).rejects.toThrow('loader failed')
})
})
})