1 import { Logger } from "@medusajs/framework/types"
2 import { RedisCacheModuleOptions } from "@types"
3 import { Redis } from "ioredis"
4 import { createGunzip, createGzip } from "zlib"
5
6 export class RedisCachingProvider {
7 static identifier = "cache-redis"
8
9 protected redisClient: Redis
10 protected keyNamePrefix: string
11 protected defaultTTL: number
12 protected compressionThreshold: number
13 protected hasher: (key: string) => string
14 protected logger: Logger
15
16 constructor(
17 {
18 redisClient,
19 logger,
20 prefix,
21 hasher,
22 }: {
23 redisClient: Redis
24 prefix: string
25 hasher: (key: string) => string
26 logger: Logger
27 },
28 options?: RedisCacheModuleOptions
29 ) {
30 this.redisClient = redisClient
31 this.keyNamePrefix = prefix
32 this.defaultTTL = options?.ttl ?? 3600 // 1 hour default
33 this.compressionThreshold = options?.compressionThreshold ?? 2048 // 2KB default
34 this.hasher = hasher
35 this.logger = logger
36 }
37
38 private isConnectionError(error: any): boolean {
39 return (
40 error.code === "ECONNREFUSED" ||
41 error.code === "ENOTFOUND" ||
42 error.code === "ETIMEDOUT" ||
43 error.code === "ECONNRESET" ||
44 error.code === "EPIPE" ||
45 error.message?.includes("Connection is closed") ||
46 error.message?.includes("connect ECONNREFUSED") ||
47 error.message?.includes("connect ETIMEDOUT") ||
48 error.message?.includes("Command timed out") ||
49 error.message?.includes("Maximum number of retries exceeded") ||
50 ["connecting", "reconnecting", "disconnecting", "wait", "end"].includes(
51 this.redisClient.status
52 )
53 )
54 }
55
56 private isConnectionHealthy(): boolean {
57 return this.redisClient.status === "ready"
58 }
59
60 #getKeyName(key: string): string {
61 return `${this.keyNamePrefix}${key}`
62 }
63
64 /**
65 * Forward index: tag -> set of cache entry keys
66 */
67 #getTagKey(
68 tag: string,
69 { isHashed = false }: { isHashed?: boolean } = {}
70 ): string {
71 return `${this.keyNamePrefix}tag:${isHashed ? tag : this.hasher(tag)}`
72 }
73
74 /**
75 * Reverse index: cache entry key -> set of hashed tags
76 */
77 #getTagsKey(key: string): string {
78 return `${this.keyNamePrefix}tags:${key}`
79 }
80
81 #getLogicalKey(keyName: string): string {
82 return keyName.replace(this.keyNamePrefix, "")
83 }
84
85 /**
86 * Remove keys from forward tag sets and drop their reverse indexes.
87 * Prefer running this before deleting entries so a failed/interrupted clear
88 * cannot leave entries that still exist but are unreachable for tag invalidation.
89 */
90 async #removeTagIndexes(keyNames: string[]): Promise<void> {
91 if (!keyNames.length) {
92 return
93 }
94
95 const tagsKeys = keyNames.map((keyName) =>
96 this.#getTagsKey(this.#getLogicalKey(keyName))
97 )
98
99 const readPipeline = this.redisClient.pipeline()
100 tagsKeys.forEach((tagsKey) => {
101 readPipeline.smembers(tagsKey)
102 })
103 const tagResults = await readPipeline.exec()
104
105 const cleanupPipeline = this.redisClient.pipeline()
106 keyNames.forEach((keyName, index) => {
107 const hashedTags = (tagResults?.[index]?.[1] as string[]) ?? []
108 hashedTags.forEach((hashedTag) => {
109 cleanupPipeline.srem(
110 this.#getTagKey(hashedTag, { isHashed: true }),
111 keyName
112 )
113 })
114 cleanupPipeline.unlink(tagsKeys[index])
115 })
116 await cleanupPipeline.exec()
117 }
118
119 /**
120 * Drop tag indexes first, then delete entry hashes.
121 */
122 async #deleteEntries(keyNames: string[]): Promise<void> {
123 if (!keyNames.length) {
124 return
125 }
126
127 await this.#removeTagIndexes(keyNames)
128
129 const deletePipeline = this.redisClient.pipeline()
130 keyNames.forEach((keyName) => {
131 deletePipeline.unlink(keyName)
132 })
133 await deletePipeline.exec()
134 }
135
136 async #compressData(data: string): Promise<Buffer> {
137 if (data.length <= this.compressionThreshold) {
138 const buffer = Buffer.from(data, "utf8")
139 const prefix = Buffer.from([0]) // 0 = uncompressed
140 return Buffer.concat([prefix, buffer])
141 }
142
143 return new Promise((resolve, reject) => {
144 const chunks: Buffer[] = []
145 const gzip = createGzip()
146
147 gzip.on("data", (chunk) => chunks.push(chunk))
148 gzip.on("end", () => {
149 const compressedBuffer = Buffer.concat(chunks)
150 const prefix = Buffer.from([1]) // 1 = compressed
151 resolve(Buffer.concat([prefix, compressedBuffer]))
152 })
153 gzip.on("error", (error) => {
154 const buffer = Buffer.from(data, "utf8")
155 const prefix = Buffer.from([0])
156 resolve(Buffer.concat([prefix, buffer]))
157 })
158
159 gzip.write(data, "utf8")
160 gzip.end()
161 })
162 }
163
164 async #decompressData(buffer: Buffer): Promise<string> {
165 if (buffer.length === 0) {
166 return ""
167 }
168
169 const formatByte = buffer[0]
170 const dataBuffer = buffer.subarray(1)
171
172 if (formatByte === 0) {
173 // Uncompressed
174 return dataBuffer.toString("utf8")
175 }
176
177 if (formatByte === 1) {
178 // Compressed with gzip
179 return new Promise((resolve, reject) => {
180 const chunks: Buffer[] = []
181 const gunzip = createGunzip()
182
183 gunzip.on("data", (chunk) => chunks.push(chunk))
184 gunzip.on("end", () => {
185 const decompressed = Buffer.concat(chunks).toString("utf8")
186 resolve(decompressed)
187 })
188 gunzip.on("error", (error) => {
189 // Fallback: return as-is if decompression fails
190 resolve(dataBuffer.toString("utf8"))
191 })
192
193 gunzip.write(dataBuffer)
194 gunzip.end()
195 })
196 }
197
198 // Unknown format, return as UTF-8
199 return buffer.toString("utf8")
200 }
201
202 async get({ key, tags }: { key?: string; tags?: string[] }): Promise<any> {
203 if (!this.isConnectionHealthy()) {
204 return null
205 }
206
207 if (key) {
208 try {
209 const keyName = this.#getKeyName(key)
210 const buffer = await this.redisClient.hgetBuffer(keyName, "data")
211 if (!buffer) {
212 return null
213 }
214
215 const finalData = await this.#decompressData(buffer)
216 return JSON.parse(finalData)
217 } catch (error) {
218 if (this.isConnectionError(error)) {
219 this.logger.warn(
220 `[redis-cache] Redis connection error during get operation, returning empty array to trigger fallback to original data source. Error: ${
221 error?.message ?? error
222 }`
223 )
224 return null
225 }
226 throw error
227 }
228 }
229
230 if (tags?.length) {
231 try {
232 // Get all keys associated with the tags
233 const pipeline = this.redisClient.pipeline()
234 tags.forEach((tag) => {
235 const tagKey = this.#getTagKey(tag)
236 pipeline.smembers(tagKey)
237 })
238
239 const tagResults = await pipeline.exec()
240 const allKeys = new Set<string>()
241
242 tagResults?.forEach((result, index) => {
243 if (result && result[1]) {
244 ;(result[1] as string[]).forEach((key) => allKeys.add(key))
245 }
246 })
247
248 if (allKeys.size === 0) {
249 return []
250 }
251
252 // Get all hash data for the keys
253 const valuePipeline = this.redisClient.pipeline()
254 Array.from(allKeys).forEach((key) => {
255 valuePipeline.hgetBuffer(key, "data")
256 })
257
258 const valueResults = await valuePipeline.exec()
259 const results: any[] = []
260
261 const decompressionPromises = (valueResults || []).map(
262 async (result) => {
263 if (result && result[1]) {
264 const buffer = result[1] as Buffer
265 try {
266 const finalData = await this.#decompressData(buffer)
267 return JSON.parse(finalData)
268 } catch (e) {
269 // If JSON parsing fails, skip this entry (corrupted data)
270 this.logger.warn(
271 `[redis-cache] Skipping corrupted cache entry: ${e.message}`
272 )
273 return null
274 }
275 }
276 return null
277 }
278 )
279
280 const decompressionResults = await Promise.all(decompressionPromises)
281 results.push(...decompressionResults.filter(Boolean))
282
283 return results
284 } catch (error) {
285 if (this.isConnectionError(error)) {
286 this.logger.warn(
287 `[redis-cache] Redis connection error during get operation, returning empty array to trigger fallback to original data source. Error: ${
288 error?.message ?? error
289 }`
290 )
291 return null
292 }
293 throw error
294 }
295 }
296
297 return null
298 }
299
300 async set({
301 key,
302 data,
303 ttl,
304 tags,
305 options,
306 }: {
307 key: string
308 data: object
309 ttl?: number
310 tags?: string[]
311 options?: {
312 autoInvalidate?: boolean
313 }
314 }): Promise<void> {
315 try {
316 const keyName = this.#getKeyName(key)
317 const serializedData = JSON.stringify(data)
318 const effectiveTTL = ttl ?? this.defaultTTL
319
320 const finalData = await this.#compressData(serializedData)
321 const hashedTags = tags?.map((tag) => this.hasher(tag)) ?? []
322
323 const setPipeline = this.redisClient.pipeline()
324
325 // Main data with conditional operations
326 setPipeline.hset(keyName, "data", finalData)
327 if (options && Object.keys(options).length) {
328 setPipeline.hset(keyName, "options", JSON.stringify(options))
329 }
330 if (effectiveTTL) {
331 setPipeline.expire(keyName, effectiveTTL)
332 }
333
334 // Bidirectional tag indexes (tag -> keys, key -> tags)
335 if (hashedTags.length) {
336 const tagsKey = this.#getTagsKey(key)
337
338 setPipeline.sadd(tagsKey, ...hashedTags)
339 if (effectiveTTL) {
340 setPipeline.expire(tagsKey, effectiveTTL + 60)
341 }
342
343 hashedTags.forEach((hashedTag) => {
344 const tagKey = this.#getTagKey(hashedTag, { isHashed: true })
345 setPipeline.sadd(tagKey, keyName)
346 if (effectiveTTL) {
347 setPipeline.expire(tagKey, effectiveTTL + 60)
348 }
349 })
350 }
351
352 await setPipeline.exec()
353 } catch (error) {
354 if (this.isConnectionError(error)) {
355 this.logger.warn(
356 `[redis-cache] Redis connection error during set operation, relying on IORedis retry mechanism. Error: ${
357 error?.message ?? error
358 }`
359 )
360 return
361 }
362 throw error
363 }
364 }
365
366 async clear({
367 key,
368 tags,
369 options,
370 }: {
371 key?: string
372 tags?: string[]
373 options?: {
374 autoInvalidate?: boolean
375 }
376 }): Promise<void> {
377 try {
378 if (key) {
379 await this.#deleteEntries([this.#getKeyName(key)])
380 return
381 }
382
383 if (tags?.length) {
384 // Handle wildcard tag to clear all cache data
385 if (tags.includes("*")) {
386 await this.flush()
387 return
388 }
389
390 // Get all keys associated with the tags
391 const pipeline = this.redisClient.pipeline()
392 tags.forEach((tag) => {
393 const tagKey = this.#getTagKey(tag)
394 pipeline.smembers(tagKey)
395 })
396
397 const tagResults = await pipeline.exec()
398
399 const allKeys = new Set<string>()
400
401 tagResults?.forEach((result) => {
402 if (result && result[1]) {
403 ;(result[1] as string[]).forEach((key) => allKeys.add(key))
404 }
405 })
406
407 if (allKeys.size) {
408 // If no options provided (user explicit call), clear everything
409 if (!options) {
410 await this.#deleteEntries(Array.from(allKeys))
411 return
412 }
413
414 // If autoInvalidate is true (strategy call), only clear entries with autoInvalidate=true (default)
415 if (options.autoInvalidate === true) {
416 const optionsPipeline = this.redisClient.pipeline()
417
418 Array.from(allKeys).forEach((key) => {
419 optionsPipeline.hget(key, "options")
420 })
421
422 const optionsResults = await optionsPipeline.exec()
423 const keysToDelete: string[] = []
424
425 Array.from(allKeys).forEach((key, index) => {
426 const optionsResult = optionsResults?.[index]
427
428 if (optionsResult && optionsResult[1]) {
429 try {
430 const entryOptions = JSON.parse(optionsResult[1] as string)
431
432 // Delete if entry has autoInvalidate=true or no setting (default true)
433 const shouldAutoInvalidate =
434 entryOptions.autoInvalidate ?? true
435
436 if (shouldAutoInvalidate) {
437 keysToDelete.push(key)
438 }
439 } catch (e) {
440 // If can't parse options, assume it's safe to delete (default true)
441 keysToDelete.push(key)
442 }
443 } else {
444 // No options stored, default to true
445 keysToDelete.push(key)
446 }
447 })
448
449 if (keysToDelete.length) {
450 await this.#deleteEntries(keysToDelete)
451 }
452 }
453 }
454 }
455 } catch (error) {
456 if (this.isConnectionError(error)) {
457 this.logger.warn(
458 `[redis-cache] Redis connection error during clear operation, relying on IORedis retry mechanism. Error: ${
459 error?.message ?? error
460 }`
461 )
462 return
463 }
464 throw error
465 }
466 }
467
468 async flush(): Promise<void> {
469 try {
470 // Use SCAN to find ALL keys with our prefix and delete them
471 // This includes main cache keys, tag keys (tag:*), and tags keys (tags:*)
472 const pattern = `${this.keyNamePrefix}*`
473 let cursor = "0"
474
475 do {
476 const result = await this.redisClient.scan(
477 cursor,
478 "MATCH",
479 pattern,
480 "COUNT",
481 1000
482 )
483 cursor = result[0]
484 const keys = result[1]
485
486 if (keys.length) {
487 await this.redisClient.unlink(...keys)
488 }
489 } while (cursor !== "0")
490 } catch (error) {
491 if (this.isConnectionError(error)) {
492 this.logger.warn(
493 `[redis-cache] Redis connection error during flush operation, relying on IORedis retry mechanism. Error: ${
494 error?.message ?? error
495 }`
496 )
497 return
498 }
499 throw error
500 }
501 }
502 }