-
-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathredis-cache.ts
More file actions
736 lines (621 loc) · 22.1 KB
/
Copy pathredis-cache.ts
File metadata and controls
736 lines (621 loc) · 22.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
import { Logger } from "@medusajs/framework/types"
import { RedisCacheModuleOptions } from "@types"
import { Redis } from "ioredis"
import { createGunzip, createGzip } from "zlib"
export class RedisCachingProvider {
static identifier = "cache-redis"
protected redisClient: Redis
protected keyNamePrefix: string
protected defaultTTL: number
protected compressionThreshold: number
protected hasher: (key: string) => string
protected logger: Logger
constructor(
{
redisClient,
logger,
prefix,
hasher,
}: {
redisClient: Redis
prefix: string
hasher: (key: string) => string
logger: Logger
},
options?: RedisCacheModuleOptions
) {
this.redisClient = redisClient
this.keyNamePrefix = prefix
this.defaultTTL = options?.ttl ?? 3600 // 1 hour default
this.compressionThreshold = options?.compressionThreshold ?? 2048 // 2KB default
this.hasher = hasher
this.logger = logger
}
private isConnectionError(error: any): boolean {
return (
error.code === "ECONNREFUSED" ||
error.code === "ENOTFOUND" ||
error.code === "ETIMEDOUT" ||
error.code === "ECONNRESET" ||
error.code === "EPIPE" ||
error.message?.includes("Connection is closed") ||
error.message?.includes("connect ECONNREFUSED") ||
error.message?.includes("connect ETIMEDOUT") ||
error.message?.includes("Command timed out") ||
error.message?.includes("Maximum number of retries exceeded") ||
["connecting", "reconnecting", "disconnecting", "wait", "end"].includes(
this.redisClient.status
)
)
}
private isConnectionHealthy(): boolean {
return this.redisClient.status === "ready"
}
#getKeyName(key: string): string {
return `${this.keyNamePrefix}${key}`
}
#getTagKey(
tag: string,
{ isHashed = false }: { isHashed?: boolean } = {}
): string {
return `${this.keyNamePrefix}tag:${isHashed ? tag : this.hasher(tag)}`
}
#getTagsKey(key: string): string {
return `${this.keyNamePrefix}tags:${key}`
}
#getTagDictionaryKey(): string {
return `${this.keyNamePrefix}tag:dictionary`
}
#getTagNextIdKey(): string {
return `${this.keyNamePrefix}tag:next_id`
}
#getTagRefCountKey(): string {
return `${this.keyNamePrefix}tag:refs`
}
#getTagReverseDictionaryKey(): string {
return `${this.keyNamePrefix}tag:reverse_dict`
}
async #internTags(tags: string[]): Promise<number[]> {
const pipeline = this.redisClient.pipeline()
const dictionaryKey = this.#getTagDictionaryKey()
const hashedTags = tags.map((tag) => this.hasher(tag))
// Get existing tag IDs
hashedTags.forEach((tag) => {
pipeline.hget(dictionaryKey, tag)
})
const results = await pipeline.exec()
const tagIds: number[] = []
const newTags: string[] = []
for (let i = 0; i < hashedTags.length; i++) {
const result = results?.[i]
if (result && result[1]) {
tagIds[i] = parseInt(result[1] as string)
} else {
const hashedTag = hashedTags[i]
newTags.push(hashedTag)
tagIds[i] = -1 // Placeholder for new tags
}
}
// Create IDs for new tags
if (newTags.length) {
const nextIdKey = this.#getTagNextIdKey()
const reverseDictKey = this.#getTagReverseDictionaryKey()
const refCountKey = this.#getTagRefCountKey()
const startId = await this.redisClient.incrby(nextIdKey, newTags.length)
const batchPipeline = this.redisClient.pipeline()
newTags.forEach((tag, index) => {
const newId = startId - newTags.length + index + 1
// Store in both forward and reverse dictionaries
batchPipeline.hset(dictionaryKey, tag, newId.toString())
batchPipeline.hset(reverseDictKey, newId.toString(), tag)
// Update the tagIds array
const originalIndex = hashedTags.indexOf(tag)
tagIds[originalIndex] = newId
})
// Add reference count increments to the same pipeline
tagIds.forEach((id) => {
if (id !== -1) {
batchPipeline.hincrby(refCountKey, id.toString(), 1)
}
})
await batchPipeline.exec()
} else {
// Only increment reference count for existing tags
const refCountKey = this.#getTagRefCountKey()
const refPipeline = this.redisClient.pipeline()
tagIds.forEach((id) => {
refPipeline.hincrby(refCountKey, id.toString(), 1)
})
await refPipeline.exec()
}
return tagIds
}
async #resolveTagIds(tagIds: number[]): Promise<string[]> {
if (tagIds.length === 0) return []
const reverseDictKey = this.#getTagReverseDictionaryKey()
const pipeline = this.redisClient.pipeline()
tagIds.forEach((id) => {
pipeline.hget(reverseDictKey, id.toString())
})
const results = await pipeline.exec()
return results?.map((result) => result?.[1] as string).filter(Boolean) || []
}
async #decrementTagRefs(tagIds: number[]): Promise<void> {
if (tagIds.length === 0) return
const refCountKey = this.#getTagRefCountKey()
const dictionaryKey = this.#getTagDictionaryKey()
// Decrement reference counts and collect tags with zero refs
const pipeline = this.redisClient.pipeline()
tagIds.forEach((id) => {
pipeline.hincrby(refCountKey, id.toString(), -1)
})
const results = await pipeline.exec()
const tagsToCleanup: number[] = []
// Find tags that now have zero references
results?.forEach((result, index) => {
if (result && result[1] === 0) {
tagsToCleanup.push(tagIds[index])
}
})
// Clean up tags with zero references
if (tagsToCleanup.length) {
const cleanupPipeline = this.redisClient.pipeline()
const reverseDictKey = this.#getTagReverseDictionaryKey()
// Get tag names before deleting them
const tagNames = await this.#resolveTagIds(tagsToCleanup)
tagsToCleanup.forEach((id, index) => {
const idStr = id.toString()
// Remove from reference count hash
cleanupPipeline.hdel(refCountKey, idStr)
// Remove from reverse dictionary
cleanupPipeline.hdel(reverseDictKey, idStr)
// Remove from forward dictionary
if (tagNames[index]) {
cleanupPipeline.hdel(dictionaryKey, tagNames[index])
}
})
await cleanupPipeline.exec()
}
}
async #compressData(data: string): Promise<Buffer> {
if (data.length <= this.compressionThreshold) {
const buffer = Buffer.from(data, "utf8")
const prefix = Buffer.from([0]) // 0 = uncompressed
return Buffer.concat([prefix, buffer])
}
return new Promise((resolve, reject) => {
const chunks: Buffer[] = []
const gzip = createGzip()
gzip.on("data", (chunk) => chunks.push(chunk))
gzip.on("end", () => {
const compressedBuffer = Buffer.concat(chunks)
const prefix = Buffer.from([1]) // 1 = compressed
resolve(Buffer.concat([prefix, compressedBuffer]))
})
gzip.on("error", (error) => {
const buffer = Buffer.from(data, "utf8")
const prefix = Buffer.from([0])
resolve(Buffer.concat([prefix, buffer]))
})
gzip.write(data, "utf8")
gzip.end()
})
}
async #decompressData(buffer: Buffer): Promise<string> {
if (buffer.length === 0) {
return ""
}
const formatByte = buffer[0]
const dataBuffer = buffer.subarray(1)
if (formatByte === 0) {
// Uncompressed
return dataBuffer.toString("utf8")
}
if (formatByte === 1) {
// Compressed with gzip
return new Promise((resolve, reject) => {
const chunks: Buffer[] = []
const gunzip = createGunzip()
gunzip.on("data", (chunk) => chunks.push(chunk))
gunzip.on("end", () => {
const decompressed = Buffer.concat(chunks).toString("utf8")
resolve(decompressed)
})
gunzip.on("error", (error) => {
// Fallback: return as-is if decompression fails
resolve(dataBuffer.toString("utf8"))
})
gunzip.write(dataBuffer)
gunzip.end()
})
}
// Unknown format, return as UTF-8
return buffer.toString("utf8")
}
async get({ key, tags }: { key?: string; tags?: string[] }): Promise<any> {
if (!this.isConnectionHealthy()) {
return null
}
if (key) {
try {
const keyName = this.#getKeyName(key)
const buffer = await this.redisClient.hgetBuffer(keyName, "data")
if (!buffer) {
return null
}
const finalData = await this.#decompressData(buffer)
return JSON.parse(finalData)
} catch (error) {
if (this.isConnectionError(error)) {
this.logger.warn(
`[redis-cache] Redis connection error during get operation, returning empty array to trigger fallback to original data source. Error: ${
error?.message ?? error
}`
)
return null
}
throw error
}
}
if (tags?.length) {
try {
// Get all keys associated with the tags
const pipeline = this.redisClient.pipeline()
tags.forEach((tag) => {
const tagKey = this.#getTagKey(tag)
pipeline.smembers(tagKey)
})
const tagResults = await pipeline.exec()
const allKeys = new Set<string>()
tagResults?.forEach((result, index) => {
if (result && result[1]) {
;(result[1] as string[]).forEach((key) => allKeys.add(key))
}
})
if (allKeys.size === 0) {
return []
}
// Get all hash data for the keys
const valuePipeline = this.redisClient.pipeline()
Array.from(allKeys).forEach((key) => {
valuePipeline.hgetBuffer(key, "data")
})
const valueResults = await valuePipeline.exec()
const results: any[] = []
const decompressionPromises = (valueResults || []).map(
async (result) => {
if (result && result[1]) {
const buffer = result[1] as Buffer
try {
const finalData = await this.#decompressData(buffer)
return JSON.parse(finalData)
} catch (e) {
// If JSON parsing fails, skip this entry (corrupted data)
this.logger.warn(`[redis-cache] Skipping corrupted cache entry: ${e.message}`)
return null
}
}
return null
}
)
const decompressionResults = await Promise.all(decompressionPromises)
results.push(...decompressionResults.filter(Boolean))
return results
} catch (error) {
if (this.isConnectionError(error)) {
this.logger.warn(
`[redis-cache] Redis connection error during get operation, returning empty array to trigger fallback to original data source. Error: ${
error?.message ?? error
}`
)
return null
}
throw error
}
}
return null
}
async set({
key,
data,
ttl,
tags,
options,
}: {
key: string
data: object
ttl?: number
tags?: string[]
options?: {
autoInvalidate?: boolean
}
}): Promise<void> {
try {
const keyName = this.#getKeyName(key)
const serializedData = JSON.stringify(data)
const effectiveTTL = ttl ?? this.defaultTTL
const finalData = await this.#compressData(serializedData)
let tagIds: number[] = []
if (tags?.length) {
tagIds = await this.#internTags(tags)
}
const setPipeline = this.redisClient.pipeline()
// Main data with conditional operations
setPipeline.hsetnx(keyName, "data", finalData)
if (options && Object.keys(options).length) {
setPipeline.hset(keyName, "options", JSON.stringify(options))
}
if (effectiveTTL) {
setPipeline.expire(keyName, effectiveTTL)
}
// Store tag IDs if present
if (tags?.length && tagIds.length) {
const tagsKey = this.#getTagsKey(key)
const buffer = Buffer.alloc(tagIds.length * 4)
tagIds.forEach((id, index) => {
buffer.writeUInt32LE(id, index * 4)
})
if (effectiveTTL) {
setPipeline.set(tagsKey, buffer, "EX", effectiveTTL + 60, "NX")
} else {
setPipeline.setnx(tagsKey, buffer)
}
// Add tag operations to the same pipeline
tags.forEach((tag) => {
const tagKey = this.#getTagKey(tag)
setPipeline.sadd(tagKey, keyName)
if (effectiveTTL) {
setPipeline.expire(tagKey, effectiveTTL + 60)
}
})
}
await setPipeline.exec()
} catch (error) {
if (this.isConnectionError(error)) {
this.logger.warn(
`[redis-cache] Redis connection error during set operation, relying on IORedis retry mechanism. Error: ${
error?.message ?? error
}`
)
return
}
throw error
}
}
async clear({
key,
tags,
options,
}: {
key?: string
tags?: string[]
options?: {
autoInvalidate?: boolean
}
}): Promise<void> {
try {
if (key) {
const keyName = this.#getKeyName(key)
const tagsKey = this.#getTagsKey(key)
const clearPipeline = this.redisClient.pipeline()
// Get tags for cleanup and delete main key in same pipeline
clearPipeline.getBuffer(tagsKey)
clearPipeline.unlink(keyName)
const results = await clearPipeline.exec()
const tagsBuffer = results?.[0]?.[1] as Buffer
if (tagsBuffer?.length) {
try {
// Binary format: array of 32-bit integers
const tagIds: number[] = []
for (let i = 0; i < tagsBuffer.length; i += 4) {
tagIds.push(tagsBuffer.readUInt32LE(i))
}
if (tagIds.length) {
const entryTags = await this.#resolveTagIds(tagIds)
const tagCleanupPipeline = this.redisClient.pipeline()
entryTags.forEach((tag) => {
const tagKey = this.#getTagKey(tag, { isHashed: true })
tagCleanupPipeline.srem(tagKey, keyName)
})
tagCleanupPipeline.unlink(tagsKey)
await tagCleanupPipeline.exec()
// Decrement reference counts and cleanup unused tags
await this.#decrementTagRefs(tagIds)
}
} catch (e) {
// noop - corrupted tag data, skip cleanup
}
}
return
}
if (tags?.length) {
// Handle wildcard tag to clear all cache data
if (tags.includes("*")) {
await this.flush()
return
}
// Get all keys associated with the tags
const pipeline = this.redisClient.pipeline()
tags.forEach((tag) => {
const tagKey = this.#getTagKey(tag)
pipeline.smembers(tagKey)
})
const tagResults = await pipeline.exec()
const allKeys = new Set<string>()
tagResults?.forEach((result) => {
if (result && result[1]) {
;(result[1] as string[]).forEach((key) => allKeys.add(key))
}
})
if (allKeys.size) {
// If no options provided (user explicit call), clear everything
if (!options) {
const deletePipeline = this.redisClient.pipeline()
// Delete main keys and options
Array.from(allKeys).forEach((key) => {
deletePipeline.unlink(key)
})
// Clean up tag references for each key
const tagDataPromises = Array.from(allKeys).map(async (key) => {
const keyWithoutPrefix = key.replace(this.keyNamePrefix, "")
const tagsKey = this.#getTagsKey(keyWithoutPrefix)
const tagsData = await this.redisClient.getBuffer(tagsKey)
return { key, tagsKey, tagsData }
})
const tagResults = await Promise.all(tagDataPromises)
// Build single pipeline for all tag cleanup operations
const tagCleanupPipeline = this.redisClient.pipeline()
const cleanupPromises = tagResults.map(
async ({ key, tagsKey, tagsData }) => {
if (tagsData) {
try {
// Binary format: array of 32-bit integers
const tagIds: number[] = []
for (let i = 0; i < tagsData.length; i += 4) {
tagIds.push(tagsData.readUInt32LE(i))
}
if (tagIds.length) {
const entryTags = await this.#resolveTagIds(tagIds)
entryTags.forEach((tag) => {
const tagKey = this.#getTagKey(tag, { isHashed: true })
tagCleanupPipeline.srem(tagKey, key)
})
tagCleanupPipeline.unlink(tagsKey)
// Decrement reference counts and cleanup unused tags
await this.#decrementTagRefs(tagIds)
}
} catch (e) {
// noop
}
}
}
)
await Promise.all(cleanupPromises)
await tagCleanupPipeline.exec()
await deletePipeline.exec()
return
}
// If autoInvalidate is true (strategy call), only clear entries with autoInvalidate=true (default)
if (options.autoInvalidate === true) {
const optionsPipeline = this.redisClient.pipeline()
Array.from(allKeys).forEach((key) => {
optionsPipeline.hget(key, "options")
})
const optionsResults = await optionsPipeline.exec()
const keysToDelete: string[] = []
Array.from(allKeys).forEach((key, index) => {
const optionsResult = optionsResults?.[index]
if (optionsResult && optionsResult[1]) {
try {
const entryOptions = JSON.parse(optionsResult[1] as string)
// Delete if entry has autoInvalidate=true or no setting (default true)
const shouldAutoInvalidate =
entryOptions.autoInvalidate ?? true
if (shouldAutoInvalidate) {
keysToDelete.push(key)
}
} catch (e) {
// If can't parse options, assume it's safe to delete (default true)
keysToDelete.push(key)
}
} else {
// No options stored, default to true
keysToDelete.push(key)
}
})
if (keysToDelete.length) {
const deletePipeline = this.redisClient.pipeline()
keysToDelete.forEach((key) => {
deletePipeline.unlink(key)
})
// Clean up tag references for each key to delete
const tagDataPromises = keysToDelete.map(async (key) => {
const keyWithoutPrefix = key.replace(this.keyNamePrefix, "")
const tagsKey = this.#getTagsKey(keyWithoutPrefix)
const tagsData = await this.redisClient.getBuffer(tagsKey)
return { key, tagsKey, tagsData }
})
// Wait for all tag data fetches
const tagResults = await Promise.all(tagDataPromises)
// Build single pipeline for all tag cleanup operations
const tagCleanupPipeline = this.redisClient.pipeline()
const cleanupPromises = tagResults.map(
async ({ key, tagsKey, tagsData }) => {
if (tagsData) {
try {
// Binary format: array of 32-bit integers
const tagIds: number[] = []
for (let i = 0; i < tagsData.length; i += 4) {
tagIds.push(tagsData.readUInt32LE(i))
}
if (tagIds.length) {
const entryTags = await this.#resolveTagIds(tagIds)
entryTags.forEach((tag) => {
const tagKey = this.#getTagKey(tag, {
isHashed: true,
})
tagCleanupPipeline.srem(tagKey, key)
})
tagCleanupPipeline.unlink(tagsKey) // Delete the tags key
// Decrement reference counts and cleanup unused tags
await this.#decrementTagRefs(tagIds)
}
} catch (e) {
// noop
}
}
}
)
await Promise.all(cleanupPromises)
await tagCleanupPipeline.exec()
await deletePipeline.exec()
return
}
}
}
}
} catch (error) {
if (this.isConnectionError(error)) {
this.logger.warn(
`[redis-cache] Redis connection error during clear operation, relying on IORedis retry mechanism. Error: ${
error?.message ?? error
}`
)
return
}
throw error
}
}
async flush(): Promise<void> {
try {
// Use SCAN to find ALL keys with our prefix and delete them
// This includes main cache keys, tag keys (tag:*), and tags keys (tags:*)
const pattern = `${this.keyNamePrefix}*`
let cursor = "0"
do {
const result = await this.redisClient.scan(
cursor,
"MATCH",
pattern,
"COUNT",
1000
)
cursor = result[0]
const keys = result[1]
if (keys.length) {
await this.redisClient.unlink(...keys)
}
} while (cursor !== "0")
} catch (error) {
if (this.isConnectionError(error)) {
this.logger.warn(
`[redis-cache] Redis connection error during flush operation, relying on IORedis retry mechanism. Error: ${
error?.message ?? error
}`
)
return
}
throw error
}
}
}