|
1
|
import { MedusaModule } from "@medusajs/framework/modules-sdk" |
|
2
|
import type { |
|
3
|
ICachingModuleService, |
|
4
|
ICachingStrategy, |
|
5
|
Logger, |
|
6
|
} from "@medusajs/framework/types" |
|
7
|
import { |
|
8
|
deduplicate, |
|
9
|
GraphQLUtils, |
|
10
|
MedusaError, |
|
11
|
} from "@medusajs/framework/utils" |
|
12
|
import { CachingDefaultProvider, InjectedDependencies } from "@types" |
|
13
|
import CacheProviderService from "./cache-provider" |
|
14
|
|
|
15
|
const ONE_HOUR_IN_SECOND = 60 * 60 |
|
16
|
|
|
17
|
export default class CachingModuleService implements ICachingModuleService { |
|
18
|
protected container: InjectedDependencies |
|
19
|
protected providerService: CacheProviderService |
|
20
|
protected strategyCtr: new (...args: any[]) => ICachingStrategy |
|
21
|
protected strategy: ICachingStrategy |
|
22
|
protected defaultProviderId: string |
|
23
|
|
|
24
|
protected logger: Logger |
|
25
|
protected ongoingRequests: Map<string, Promise<any>> = new Map() |
|
26
|
|
|
27
|
protected ttl: number |
|
28
|
|
|
29
|
static traceGet?: ( |
|
30
|
cacheGetFn: () => Promise<any>, |
|
31
|
key: string, |
|
32
|
tags: string[] |
|
33
|
) => Promise<any> |
|
34
|
|
|
35
|
static traceSet?: ( |
|
36
|
cacheSetFn: () => Promise<any>, |
|
37
|
key: string, |
|
38
|
tags: string[], |
|
39
|
options: { autoInvalidate?: boolean } |
|
40
|
) => Promise<any> |
|
41
|
|
|
42
|
static traceClear?: ( |
|
43
|
cacheClearFn: () => Promise<any>, |
|
44
|
key: string, |
|
45
|
tags: string[], |
|
46
|
options: { autoInvalidate?: boolean } |
|
47
|
) => Promise<any> |
|
48
|
|
|
49
|
constructor( |
|
50
|
container: InjectedDependencies, |
|
51
|
protected readonly moduleDeclaration: |
|
52
|
| { options: { ttl?: number } } |
|
53
|
| { ttl?: number } |
|
54
|
) { |
|
55
|
this.container = container |
|
56
|
this.providerService = container.cacheProviderService |
|
57
|
this.defaultProviderId = container[CachingDefaultProvider] |
|
58
|
this.strategyCtr = container.strategy as new ( |
|
59
|
...args: any[] |
|
60
|
) => ICachingStrategy |
|
61
|
this.strategy = new this.strategyCtr(this.container, this) |
|
62
|
|
|
63
|
const moduleOptions = |
|
64
|
"options" in moduleDeclaration |
|
65
|
? moduleDeclaration.options |
|
66
|
: moduleDeclaration |
|
67
|
|
|
68
|
this.ttl = moduleOptions.ttl ?? ONE_HOUR_IN_SECOND |
|
69
|
|
|
70
|
this.logger = container.logger ?? (console as unknown as Logger) |
|
71
|
} |
|
72
|
|
|
73
|
__hooks = { |
|
74
|
onApplicationStart: async () => { |
|
75
|
await this.onApplicationStart() |
|
76
|
}, |
|
77
|
onApplicationShutdown: async () => { |
|
78
|
await this.onApplicationShutdown() |
|
79
|
}, |
|
80
|
onApplicationPrepareShutdown: async () => { |
|
81
|
await this.onApplicationPrepareShutdown() |
|
82
|
}, |
|
83
|
} |
|
84
|
|
|
85
|
protected async onApplicationStart() { |
|
86
|
const loadedSchema = MedusaModule.getAllJoinerConfigs() |
|
87
|
.map((joinerConfig) => joinerConfig?.schema ?? "") |
|
88
|
.join("\n") |
|
89
|
|
|
90
|
const defaultMedusaSchema = ` |
|
91
|
scalar DateTime |
|
92
|
scalar JSON |
|
93
|
directive @enumValue(value: String) on ENUM_VALUE |
|
94
|
` |
|
95
|
|
|
96
|
const { schema: cleanedSchema } = GraphQLUtils.cleanGraphQLSchema( |
|
97
|
defaultMedusaSchema + loadedSchema |
|
98
|
) |
|
99
|
const mergedSchema = GraphQLUtils.mergeTypeDefs(cleanedSchema) |
|
100
|
const schema = GraphQLUtils.makeExecutableSchema({ |
|
101
|
typeDefs: mergedSchema, |
|
102
|
}) |
|
103
|
|
|
104
|
await this.strategy.onApplicationStart?.( |
|
105
|
schema, |
|
106
|
MedusaModule.getAllJoinerConfigs() |
|
107
|
) |
|
108
|
} |
|
109
|
|
|
110
|
protected async onApplicationShutdown() { |
|
111
|
await this.strategy.onApplicationShutdown?.() |
|
112
|
} |
|
113
|
|
|
114
|
protected async onApplicationPrepareShutdown() { |
|
115
|
await this.strategy.onApplicationPrepareShutdown?.() |
|
116
|
} |
|
117
|
|
|
118
|
protected static normalizeProviders( |
|
119
|
providers: string[] | { id: string; ttl?: number }[] |
|
120
|
): { id: string; ttl?: number }[] { |
|
121
|
const providers_ = Array.isArray(providers) ? providers : [providers] |
|
122
|
return providers_.map((provider) => { |
|
123
|
return typeof provider === "string" ? { id: provider } : provider |
|
124
|
}) |
|
125
|
} |
|
126
|
|
|
127
|
protected getRequestKey( |
|
128
|
key?: string, |
|
129
|
tags?: string[], |
|
130
|
providers?: string[] |
|
131
|
): string { |
|
132
|
const keyPart = key || "" |
|
133
|
const tagsPart = tags?.sort().join(",") || "" |
|
134
|
const providersPart = providers?.join(",") || this.defaultProviderId |
|
135
|
return `${keyPart}|${tagsPart}|${providersPart}` |
|
136
|
} |
|
137
|
|
|
138
|
protected getClearRequestKey( |
|
139
|
key?: string, |
|
140
|
tags?: string[], |
|
141
|
providers?: string[] |
|
142
|
): string { |
|
143
|
const keyPart = key || "" |
|
144
|
const tagsPart = tags?.sort().join(",") || "" |
|
145
|
const providersPart = providers?.join(",") || this.defaultProviderId |
|
146
|
return `clear:${keyPart}|${tagsPart}|${providersPart}` |
|
147
|
} |
|
148
|
|
|
149
|
async get(options: { key?: string; tags?: string[]; providers?: string[] }) { |
|
150
|
if (CachingModuleService.traceGet) { |
|
151
|
return await CachingModuleService.traceGet( |
|
152
|
() => this.get_(options), |
|
153
|
options.key ?? "", |
|
154
|
options.tags ?? [] |
|
155
|
) |
|
156
|
} |
|
157
|
|
|
158
|
return await this.get_(options) |
|
159
|
} |
|
160
|
|
|
161
|
private async get_({ |
|
162
|
key, |
|
163
|
tags, |
|
164
|
providers, |
|
165
|
}: { |
|
166
|
key?: string |
|
167
|
tags?: string[] |
|
168
|
providers?: string[] |
|
169
|
}) { |
|
170
|
if (!key && !tags) { |
|
171
|
throw new MedusaError( |
|
172
|
MedusaError.Types.INVALID_ARGUMENT, |
|
173
|
"Either key or tags must be provided" |
|
174
|
) |
|
175
|
} |
|
176
|
|
|
177
|
const requestKey = this.getRequestKey(key, tags, providers) |
|
178
|
|
|
179
|
const existingRequest = this.ongoingRequests.get(requestKey) |
|
180
|
if (existingRequest) { |
|
181
|
return await existingRequest |
|
182
|
} |
|
183
|
|
|
184
|
const requestPromise = this.performCacheGet(key, tags, providers) |
|
185
|
this.ongoingRequests.set(requestKey, requestPromise) |
|
186
|
|
|
187
|
try { |
|
188
|
const result = await requestPromise |
|
189
|
return result |
|
190
|
} finally { |
|
191
|
// Clean up the completed request |
|
192
|
this.ongoingRequests.delete(requestKey) |
|
193
|
} |
|
194
|
} |
|
195
|
|
|
196
|
protected async performCacheGet( |
|
197
|
key?: string, |
|
198
|
tags?: string[], |
|
199
|
providers?: string[] |
|
200
|
): Promise<any> { |
|
201
|
const providersToCheck = providers ?? [this.defaultProviderId] |
|
202
|
|
|
203
|
for (const providerId of providersToCheck) { |
|
204
|
try { |
|
205
|
const provider_ = this.providerService.retrieveProvider(providerId) |
|
206
|
const result = await provider_.get({ key, tags }) |
|
207
|
|
|
208
|
if (result != null) { |
|
209
|
return result |
|
210
|
} |
|
211
|
} catch (error) { |
|
212
|
this.logger.warn( |
|
213
|
`Cache provider ${providerId} failed: ${error.message}\n${error.stack}` |
|
214
|
) |
|
215
|
continue |
|
216
|
} |
|
217
|
} |
|
218
|
|
|
219
|
return null |
|
220
|
} |
|
221
|
|
|
222
|
async set(options: { |
|
223
|
key: string |
|
224
|
data: object |
|
225
|
ttl?: number |
|
226
|
tags?: string[] |
|
227
|
computeAutomaticTags?: boolean |
|
228
|
providers?: string[] |
|
229
|
options?: { autoInvalidate?: boolean } |
|
230
|
}) { |
|
231
|
if (CachingModuleService.traceSet) { |
|
232
|
return await CachingModuleService.traceSet( |
|
233
|
() => this.set_(options), |
|
234
|
options.key, |
|
235
|
options.tags ?? [], |
|
236
|
options.options ?? {} |
|
237
|
) |
|
238
|
} |
|
239
|
|
|
240
|
return await this.set_(options) |
|
241
|
} |
|
242
|
|
|
243
|
private async set_({ |
|
244
|
key, |
|
245
|
data, |
|
246
|
ttl, |
|
247
|
tags, |
|
248
|
computeAutomaticTags, |
|
249
|
providers, |
|
250
|
options, |
|
251
|
}: { |
|
252
|
key: string |
|
253
|
data: object |
|
254
|
tags?: string[] |
|
255
|
computeAutomaticTags?: boolean |
|
256
|
ttl?: number |
|
257
|
providers?: string[] | { id: string; ttl?: number }[] |
|
258
|
options?: { |
|
259
|
autoInvalidate?: boolean |
|
260
|
} |
|
261
|
}) { |
|
262
|
if (!key) { |
|
263
|
throw new MedusaError( |
|
264
|
MedusaError.Types.INVALID_ARGUMENT, |
|
265
|
"[CachingModuleService] Key must be provided" |
|
266
|
) |
|
267
|
} |
|
268
|
|
|
269
|
const key_ = key |
|
270
|
// Given tags are used on their own, unless the caller asked for the computed ones |
|
271
|
// to be applied along with them. The union is what anything the computation can't |
|
272
|
// see from the data needs: link tables, relations selected without their id, or |
|
273
|
// entities that affect the data without appearing in it. |
|
274
|
const computed = |
|
275
|
!tags || computeAutomaticTags ? await this.strategy.computeTags(data) : [] |
|
276
|
const tags_ = tags ? deduplicate([...tags, ...computed]) : computed |
|
277
|
|
|
278
|
let providers_: string[] | { id: string; ttl?: number }[] = [ |
|
279
|
this.defaultProviderId, |
|
280
|
] |
|
281
|
providers_ = CachingModuleService.normalizeProviders( |
|
282
|
providers ?? providers_ |
|
283
|
) |
|
284
|
|
|
285
|
const providerIds = providers_.map((p) => p.id) |
|
286
|
const requestKey = this.getRequestKey(key_, tags_, providerIds) |
|
287
|
|
|
288
|
const existingRequest = this.ongoingRequests.get(requestKey) |
|
289
|
if (existingRequest) { |
|
290
|
return await existingRequest |
|
291
|
} |
|
292
|
|
|
293
|
const requestPromise = this.performCacheSet( |
|
294
|
key_, |
|
295
|
tags_, |
|
296
|
data, |
|
297
|
ttl, |
|
298
|
providers_, |
|
299
|
options |
|
300
|
) |
|
301
|
this.ongoingRequests.set(requestKey, requestPromise) |
|
302
|
|
|
303
|
try { |
|
304
|
await requestPromise |
|
305
|
} finally { |
|
306
|
// Clean up the completed request |
|
307
|
this.ongoingRequests.delete(requestKey) |
|
308
|
} |
|
309
|
} |
|
310
|
|
|
311
|
protected async performCacheSet( |
|
312
|
key: string, |
|
313
|
tags: string[], |
|
314
|
data: object, |
|
315
|
ttl?: number, |
|
316
|
providers?: { id: string; ttl?: number }[], |
|
317
|
options?: { |
|
318
|
autoInvalidate?: boolean |
|
319
|
} |
|
320
|
): Promise<void> { |
|
321
|
await Promise.all( |
|
322
|
(providers || []).map((providerOptions) => |
|
323
|
this.providerService.retrieveProvider(providerOptions.id).set({ |
|
324
|
key, |
|
325
|
tags, |
|
326
|
data, |
|
327
|
ttl: providerOptions.ttl ?? ttl ?? this.ttl, |
|
328
|
options, |
|
329
|
}) |
|
330
|
) |
|
331
|
) |
|
332
|
} |
|
333
|
|
|
334
|
async clear(options: { |
|
335
|
key?: string |
|
336
|
tags?: string[] |
|
337
|
options?: { autoInvalidate?: boolean } |
|
338
|
providers?: string[] |
|
339
|
}) { |
|
340
|
if (CachingModuleService.traceClear) { |
|
341
|
return await CachingModuleService.traceClear( |
|
342
|
() => this.clear_(options), |
|
343
|
options.key ?? "", |
|
344
|
options.tags ?? [], |
|
345
|
options.options ?? {} |
|
346
|
) |
|
347
|
} |
|
348
|
|
|
349
|
return await this.clear_(options) |
|
350
|
} |
|
351
|
|
|
352
|
private async clear_({ |
|
353
|
key, |
|
354
|
tags, |
|
355
|
options, |
|
356
|
providers, |
|
357
|
}: { |
|
358
|
key?: string |
|
359
|
tags?: string[] |
|
360
|
options?: { |
|
361
|
autoInvalidate?: boolean |
|
362
|
} |
|
363
|
providers?: string[] |
|
364
|
}) { |
|
365
|
if (!key && !tags) { |
|
366
|
throw new MedusaError( |
|
367
|
MedusaError.Types.INVALID_ARGUMENT, |
|
368
|
"Either key or tags must be provided" |
|
369
|
) |
|
370
|
} |
|
371
|
|
|
372
|
const requestKey = this.getClearRequestKey(key, tags, providers) |
|
373
|
|
|
374
|
const existingRequest = this.ongoingRequests.get(requestKey) |
|
375
|
if (existingRequest) { |
|
376
|
return await existingRequest |
|
377
|
} |
|
378
|
|
|
379
|
const requestPromise = this.performCacheClear(key, tags, options, providers) |
|
380
|
this.ongoingRequests.set(requestKey, requestPromise) |
|
381
|
|
|
382
|
try { |
|
383
|
await requestPromise |
|
384
|
} finally { |
|
385
|
// Clean up the completed request |
|
386
|
this.ongoingRequests.delete(requestKey) |
|
387
|
} |
|
388
|
} |
|
389
|
|
|
390
|
protected async performCacheClear( |
|
391
|
key?: string, |
|
392
|
tags?: string[], |
|
393
|
options?: { |
|
394
|
autoInvalidate?: boolean |
|
395
|
}, |
|
396
|
providers?: string[] |
|
397
|
): Promise<void> { |
|
398
|
let providerIds_: string[] = [this.defaultProviderId] |
|
399
|
if (providers) { |
|
400
|
providerIds_ = Array.isArray(providers) ? providers : [providers] |
|
401
|
} |
|
402
|
|
|
403
|
await Promise.all( |
|
404
|
providerIds_ |
|
405
|
.map((id) => this.providerService.retrieveProvider(id)) |
|
406
|
.map((provider) => provider.clear({ key, tags, options })) |
|
407
|
) |
|
408
|
} |
|
409
|
|
|
410
|
async computeKey(input: object): Promise<string> { |
|
411
|
return await this.strategy.computeKey(input) |
|
412
|
} |
|
413
|
|
|
414
|
async computeTags( |
|
415
|
input: object, |
|
416
|
options?: Record<string, any> |
|
417
|
): Promise<string[]> { |
|
418
|
return await this.strategy.computeTags(input, options) |
|
419
|
} |
|
420
|
} |