1 import NodeCache from "node-cache"
2 import type { ICachingProviderService, Logger } from "@medusajs/framework/types"
3 import { MemoryCacheModuleOptions } from "@types"
4
5 const THREE_HUNDRED_MB = 300 * 1024 * 1024
6
7 const formatBytes = (bytes: number): string => {
8 if (bytes < 1024) return `${bytes} B`
9 if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`
10 return `${Math.round(bytes / 1024 / 1024)} MB`
11 }
12
13 export class MemoryCachingProvider implements ICachingProviderService {
14 static identifier = "cache-memory"
15
16 protected logger: Logger
17 protected cacheClient: NodeCache
18 protected tagIndex: Map<string, Set<string>> = new Map() // tag -> keys
19 protected keyTags: Map<string, Set<string>> = new Map() // key -> tags
20 protected entryOptions: Map<string, { autoInvalidate?: boolean }> = new Map() // key -> options
21 protected keySizes: Map<string, number> = new Map() // key -> approximate size in bytes
22 protected approximateMemoryUsage: number = 0
23 protected options: MemoryCacheModuleOptions
24 protected maxSize: number
25 protected hasher: (key: string) => string
26
27 constructor(
28 { logger, hasher }: { logger?: Logger; hasher: (key: string) => string },
29 options: MemoryCacheModuleOptions = {}
30 ) {
31 this.logger = logger ?? (console as unknown as Logger)
32 const { maxSize, ...rest } = options
33 this.maxSize = maxSize ?? THREE_HUNDRED_MB
34
35 this.hasher = hasher
36
37 this.options = {
38 ttl: 3600,
39 maxKeys: 25000,
40 checkPeriod: 60, // 10 minutes
41 useClones: false, // Default to false for speed, true would be slower but safer. we can ...discuss
42 ...rest,
43 }
44
45 const cacheClient = new NodeCache({
46 stdTTL: this.options.ttl,
47 maxKeys: this.options.maxKeys,
48 checkperiod: this.options.checkPeriod,
49 useClones: this.options.useClones,
50 })
51
52 this.cacheClient = cacheClient
53
54 // Clean up tag indices when keys expire
55 this.cacheClient.on("expired", (key: string) => {
56 this.cleanupTagReferences(key)
57 })
58
59 this.cacheClient.on("del", (key: string) => {
60 this.cleanupTagReferences(key)
61 })
62 }
63
64 private calculateEntrySize(
65 key: string,
66 data: object,
67 tags?: string[]
68 ): number {
69 const dataSize = Buffer.byteLength(JSON.stringify(data), "utf8")
70 const keySize = Buffer.byteLength(key, "utf8")
71
72 let tagsSize = 0
73 if (tags?.length) {
74 tagsSize = Buffer.byteLength(JSON.stringify(tags), "utf8")
75 }
76
77 return dataSize + keySize + tagsSize
78 }
79
80 private cleanupTagReferences(key: string): void {
81 const tags = this.keyTags.get(key)
82 if (tags) {
83 tags.forEach((tag) => {
84 const keysForTag = this.tagIndex.get(tag)
85 if (keysForTag) {
86 keysForTag.delete(key)
87 if (keysForTag.size === 0) {
88 this.tagIndex.delete(tag)
89 }
90 }
91 })
92 this.keyTags.delete(key)
93 }
94
95 // Clean up memory tracking
96 const keySize = this.keySizes.get(key)
97 if (keySize) {
98 this.approximateMemoryUsage -= keySize
99 this.keySizes.delete(key)
100 }
101
102 // Also clean up entry options
103 this.entryOptions.delete(key)
104 }
105
106 async get({ key, tags }: { key?: string; tags?: string[] }): Promise<any> {
107 if (key) {
108 const hashedKey = this.hasher(key)
109 return this.cacheClient.get(hashedKey) ?? null
110 }
111
112 if (tags?.length) {
113 const allKeys = new Set<string>()
114
115 tags.forEach((tag) => {
116 const hashedTag = this.hasher(tag)
117 const keysForTag = this.tagIndex.get(hashedTag)
118 if (keysForTag) {
119 keysForTag.forEach((key) => allKeys.add(key))
120 }
121 })
122
123 if (allKeys.size === 0) {
124 return []
125 }
126
127 const results: any[] = []
128 allKeys.forEach((key) => {
129 const value = this.cacheClient.get(key)
130 if (value !== undefined) {
131 results.push(value)
132 }
133 })
134
135 return results
136 }
137
138 return null
139 }
140
141 async set({
142 key,
143 data,
144 ttl,
145 tags,
146 options,
147 }: {
148 key: string
149 data: object
150 ttl?: number
151 tags?: string[]
152 options?: {
153 autoInvalidate?: boolean
154 }
155 }): Promise<void> {
156 // Only reject if we're already over the limit
157 if (this.approximateMemoryUsage > this.maxSize) {
158 this.logger.warn(
159 `Cache is full. Current usage: ${formatBytes(
160 this.approximateMemoryUsage
161 )}, Max: ${formatBytes(this.maxSize)}. Skipping cache entry.`
162 )
163 return
164 }
165
166 const hashedKey = this.hasher(key)
167 const hashedTags = tags?.map((tag) => this.hasher(tag))
168
169 const totalSize = this.calculateEntrySize(hashedKey, data, hashedTags)
170
171 // Set the cache entry
172 const effectiveTTL = ttl ?? this.options.ttl ?? 3600
173 this.cacheClient.set(hashedKey, data, effectiveTTL)
174
175 // Handle tags if provided
176 if (hashedTags?.length) {
177 // Clean up any existing tag references for this key
178 this.cleanupTagReferences(hashedKey)
179
180 const tagSet = new Set(hashedTags)
181 this.keyTags.set(hashedKey, tagSet)
182
183 // Add this key to each tag's index
184 hashedTags.forEach((tag) => {
185 if (!this.tagIndex.has(tag)) {
186 this.tagIndex.set(tag, new Set())
187 }
188 this.tagIndex.get(tag)!.add(hashedKey)
189 })
190 }
191
192 // Store entry options if provided
193 if (
194 Object.keys(options ?? {}).length &&
195 !Object.values(options ?? {}).every((value) => value === undefined)
196 ) {
197 this.entryOptions.set(hashedKey, options!)
198 }
199
200 // Track memory usage
201 const existingSize = this.keySizes.get(hashedKey) || 0
202 this.approximateMemoryUsage =
203 this.approximateMemoryUsage - existingSize + totalSize
204 this.keySizes.set(hashedKey, totalSize)
205 }
206
207 async clear({
208 key,
209 tags,
210 options,
211 }: {
212 key?: string
213 tags?: string[]
214 options?: {
215 autoInvalidate?: boolean
216 }
217 }): Promise<void> {
218 if (key) {
219 const hashedKey = this.hasher(key)
220 this.cacheClient.del(hashedKey)
221 return
222 }
223
224 if (tags?.length) {
225 // Handle wildcard tag to clear all cache data
226 if (tags?.includes("*")) {
227 this.cacheClient.flushAll()
228 this.tagIndex.clear()
229 this.keyTags.clear()
230 this.entryOptions.clear()
231 // flushAll only emits "flush", not a "del" per key, so the size
232 // bookkeeping that cleanupTagReferences maintains has to be reset here.
233 this.keySizes.clear()
234 this.approximateMemoryUsage = 0
235 return
236 }
237
238 const hashedTags = tags.map((tag) => this.hasher(tag))
239 const allKeys = new Set<string>()
240
241 hashedTags.forEach((tag) => {
242 const keysForTag = this.tagIndex.get(tag)
243 if (keysForTag) {
244 keysForTag.forEach((key) => allKeys.add(key))
245 }
246 })
247
248 if (allKeys.size) {
249 // If no options provided (user explicit call), clear everything
250 if (!options) {
251 const keysToDelete = Array.from(allKeys)
252 this.cacheClient.del(keysToDelete)
253
254 // Clean up ALL tag references for deleted keys
255 keysToDelete.forEach((key) => {
256 this.cleanupTagReferences(key)
257 })
258 return
259 }
260
261 // If autoInvalidate is true (strategy call), only clear entries with autoInvalidate=true (default)
262 if (options.autoInvalidate === true) {
263 const keysToDelete: string[] = []
264
265 allKeys.forEach((key) => {
266 const entryOptions = this.entryOptions.get(key)
267 // Delete if entry has autoInvalidate=true or no setting (default true)
268 const shouldAutoInvalidate = entryOptions?.autoInvalidate ?? true
269 if (shouldAutoInvalidate) {
270 keysToDelete.push(key)
271 }
272 })
273
274 if (keysToDelete.length) {
275 this.cacheClient.del(keysToDelete)
276
277 // Clean up ALL tag references for deleted keys
278 keysToDelete.forEach((key) => {
279 this.cleanupTagReferences(key)
280 })
281 }
282 }
283 }
284 }
285 }
286 }