1 import { MedusaError, promiseAll } from "@medusajs/framework/utils"
2 import { ILockingProvider, Logger } from "@medusajs/types"
3 import { RedisCacheModuleOptions } from "@types"
4 import { Redis } from "ioredis"
5 import { randomUUID } from "node:crypto"
6 import { setTimeout as delay } from "node:timers/promises"
7
8 /**
9 * How long a lock taken by `execute` survives without being renewed. `execute`
10 * renews it underneath the job, so this only bounds how long the keys stay
11 * locked when the process holding them dies without releasing them.
12 */
13 const DEFAULT_LOCK_EXPIRATION = 60
14
15 type LockCommands = {
16 acquireLock: (
17 key: string,
18 ownerId: string,
19 ttl: number,
20 awaitQueue?: boolean
21 ) => Promise<number>
22 releaseLock: (key: string, ownerId: string) => Promise<number>
23 extendLock: (key: string, ownerId: string, ttl: number) => Promise<number>
24 }
25
26 type InjectedDependencies = {
27 redisClient: Redis & LockCommands
28 prefix?: string
29 logger?: Logger
30 }
31
32 export class RedisLockingProvider implements ILockingProvider {
33 static identifier = "locking-redis"
34
35 protected redisClient: Redis & LockCommands
36 protected keyNamePrefix: string
37 protected logger_?: Logger
38 protected waitLockingTimeout: number = 5
39 protected defaultRetryInterval: number = 20
40 protected maximumRetryInterval: number = 1000
41 protected backoffFactor: number = 2
42
43 constructor(
44 { redisClient, prefix, logger }: InjectedDependencies,
45 options: RedisCacheModuleOptions
46 ) {
47 this.redisClient = redisClient
48 this.keyNamePrefix = prefix ?? "medusa_lock:"
49 this.logger_ = logger
50
51 if (!isNaN(+options?.waitLockingTimeout!)) {
52 this.waitLockingTimeout = +options.waitLockingTimeout!
53 }
54
55 if (!isNaN(+options?.defaultRetryInterval!)) {
56 this.defaultRetryInterval = +options.defaultRetryInterval!
57 }
58
59 if (!isNaN(+options?.maximumRetryInterval!)) {
60 this.maximumRetryInterval = +options.maximumRetryInterval!
61 }
62
63 if (!isNaN(+options?.backoffFactor!)) {
64 this.backoffFactor = +options.backoffFactor!
65 }
66
67 // Define the custom command for acquiring locks
68 this.redisClient.defineCommand("acquireLock", {
69 numberOfKeys: 1,
70 lua: `
71 local key = KEYS[1]
72 local ownerId = ARGV[1]
73 local ttl = tonumber(ARGV[2])
74 local awaitQueue = ARGV[3] == 'true'
75
76 local setArgs = {key, ownerId, 'NX'}
77 if ttl > 0 then
78 table.insert(setArgs, 'EX')
79 table.insert(setArgs, ttl)
80 end
81
82 local setResult = redis.call('SET', unpack(setArgs))
83
84 if setResult then
85 return 1
86 elseif not awaitQueue then
87 -- Key already exists; retrieve the current ownerId
88 local currentOwnerId = redis.call('GET', key)
89 if currentOwnerId == '*' then
90 return 0
91 elseif currentOwnerId == ownerId then
92 setArgs = {key, ownerId, 'XX'}
93 if ttl > 0 then
94 table.insert(setArgs, 'EX')
95 table.insert(setArgs, ttl)
96 end
97 redis.call('SET', unpack(setArgs))
98 return 1
99 else
100 return 0
101 end
102 else
103 return 0
104 end
105
106 `,
107 })
108
109 // Define the custom command for extending a lock this owner still holds.
110 // Owner-checked like the release below, so a renewal can never revive a
111 // lease that has already lapsed and been taken over by someone else.
112 this.redisClient.defineCommand("extendLock", {
113 numberOfKeys: 1,
114 lua: `
115 local key = KEYS[1]
116 local ownerId = ARGV[1]
117 local ttl = tonumber(ARGV[2])
118
119 if redis.call('GET', key) == ownerId then
120 return redis.call('EXPIRE', key, ttl)
121 else
122 return 0
123 end
124 `,
125 })
126
127 // Define the custom command for releasing locks
128 this.redisClient.defineCommand("releaseLock", {
129 numberOfKeys: 1,
130 lua: `
131 local key = KEYS[1]
132 local ownerId = ARGV[1]
133
134 if redis.call('GET', key) == ownerId then
135 return redis.call('DEL', key)
136 else
137 return 0
138 end
139 `,
140 })
141 }
142
143 private getKeyName(key: string): string {
144 return `${this.keyNamePrefix}${key}`
145 }
146
147 /**
148 * Runs `job` while holding `keys`, and keeps holding them for as long as it
149 * runs: the lease is renewed underneath the job, so a job that outlives
150 * `expire` no longer has its keys handed to another process mid-flight.
151 *
152 * The lease itself stays short regardless of how long the job takes — it is
153 * what frees the keys if this process dies before reaching the release
154 * below. When renewal loses the race anyway (Redis unreachable long enough
155 * for the lease to lapse, or the key evicted), `job`'s signal is aborted and
156 * `execute` throws, rather than reporting a critical section that wasn't one.
157 */
158 async execute<T>(
159 keys: string | string[],
160 job: (signal?: AbortSignal) => Promise<T>,
161 args?: {
162 timeout?: number
163 expire?: number
164 }
165 ): Promise<T> {
166 const timeout = Math.max(args?.timeout ?? this.waitLockingTimeout, 1)
167 const timeoutSeconds = Number.isNaN(timeout) ? 1 : timeout
168
169 const expire = Math.max(args?.expire ?? DEFAULT_LOCK_EXPIRATION, 1)
170 const expireSeconds = Number.isNaN(expire)
171 ? DEFAULT_LOCK_EXPIRATION
172 : expire
173
174 // Unique per call, so the release at the end can only delete the lock this call took.
175 const ownerId = `execute:${randomUUID()}`
176
177 const cancellationToken = { cancelled: false }
178 const promises: Promise<any>[] = []
179 if (timeoutSeconds > 0) {
180 promises.push(this.getTimeout(timeoutSeconds, cancellationToken))
181 }
182
183 const acquisition = this.acquire_(
184 keys,
185 {
186 ownerId,
187 awaitQueue: true,
188 expire: expireSeconds,
189 },
190 cancellationToken
191 )
192 promises.push(acquisition)
193
194 try {
195 await Promise.race(promises)
196 } catch (error) {
197 // The acquire loop can be mid-`SET` when the timeout fires, and then
198 // takes keys no job is going to use. Hand them back rather than leaving
199 // them locked for a whole lease.
200 void acquisition.then(
201 () => this.release(keys, { ownerId }),
202 () => {}
203 )
204
205 throw error
206 }
207
208 const renewal = this.renewUntilStopped(keys, ownerId, expireSeconds)
209
210 try {
211 const result = await job(renewal.signal)
212
213 // The job either ignored the signal or finished before noticing it. It
214 // ran without exclusivity either way, so its result cannot be reported
215 // as if it had held the lock throughout.
216 if (renewal.signal.aborted) {
217 throw renewal.signal.reason
218 }
219
220 return result
221 } finally {
222 renewal.stop()
223 await this.release(keys, { ownerId })
224 }
225 }
226
227 /**
228 * Extends the lease on `keys` every third of its duration for as long as the
229 * returned handle is live, so two renewals can fail before the keys become
230 * available to anyone else.
231 *
232 * A renewal that reports the key as gone or owned by someone else is
233 * definitive — no later renewal can win it back — so the signal aborts.
234 */
235 private renewUntilStopped(
236 keys: string | string[],
237 ownerId: string,
238 expireSeconds: number
239 ): { signal: AbortSignal; stop: () => void } {
240 const allKeys = Array.isArray(keys) ? keys : [keys]
241 const intervalMs = Math.max(Math.floor((expireSeconds * 1000) / 3), 250)
242 const controller = new AbortController()
243
244 let timer: NodeJS.Timeout | undefined
245 let stopped = false
246
247 const schedule = () => {
248 timer = setTimeout(renew, intervalMs)
249 timer.unref?.()
250 }
251
252 const renew = async () => {
253 let extended: number[]
254
255 try {
256 extended = await promiseAll(
257 allKeys.map((key) =>
258 this.redisClient.extendLock(
259 this.getKeyName(key),
260 ownerId,
261 expireSeconds
262 )
263 )
264 )
265 } catch (error) {
266 if (!stopped) {
267 this.logger_?.warn(
268 `Failed to renew lock for key(s) "${allKeys.join('", "')}": ${
269 error.message
270 }. Retrying in ${intervalMs}ms.`
271 )
272 schedule()
273 }
274
275 return
276 }
277
278 if (stopped) {
279 return
280 }
281
282 const lost = allKeys.filter((_, index) => extended[index] !== 1)
283
284 if (!lost.length) {
285 schedule()
286 return
287 }
288
289 const message = `Lost the lock for key(s) "${lost.join(
290 '", "'
291 )}" while the job was still running: the lease expired before it could be renewed. Increase "expire" if the job is expected to run this long.`
292
293 this.logger_?.warn(message)
294 controller.abort(new MedusaError(MedusaError.Types.CONFLICT, message))
295 }
296
297 schedule()
298
299 return {
300 signal: controller.signal,
301 stop: () => {
302 stopped = true
303
304 if (timer) {
305 clearTimeout(timer)
306 }
307 },
308 }
309 }
310
311 async acquire(
312 keys: string | string[],
313 args?: {
314 ownerId?: string
315 expire?: number
316 awaitQueue?: boolean
317 }
318 ): Promise<void> {
319 return this.acquire_(keys, args)
320 }
321
322 async acquire_(
323 keys: string | string[],
324 args?: {
325 ownerId?: string
326 expire?: number
327 awaitQueue?: boolean
328 },
329 cancellationToken?: { cancelled: boolean }
330 ): Promise<void> {
331 keys = Array.isArray(keys) ? keys : [keys]
332
333 const timeout = Math.max(args?.expire ?? this.waitLockingTimeout, 1)
334 const timeoutSeconds = Number.isNaN(timeout) ? 1 : timeout
335 let retryDelay = this.defaultRetryInterval
336
337 const ownerId = args?.ownerId ?? "*"
338 const awaitQueue = args?.awaitQueue ?? false
339
340 const acquirePromises = keys.map(async (key) => {
341 const errMessage = `Failed to acquire lock for key "${key}"`
342 const keyName = this.getKeyName(key)
343
344 const acquireLock = async () => {
345 while (true) {
346 if (cancellationToken?.cancelled) {
347 throw new MedusaError(MedusaError.Types.CONFLICT, errMessage)
348 }
349
350 const result = await this.redisClient.acquireLock(
351 keyName,
352 ownerId,
353 args?.expire ? timeoutSeconds : 0,
354 awaitQueue
355 )
356
357 if (result === 1) {
358 break
359 } else {
360 if (awaitQueue) {
361 // Wait before retrying with exponential backoff and jitter
362 const jitteredDelay = retryDelay * (0.5 + Math.random() * 0.5)
363 await delay(jitteredDelay)
364
365 retryDelay = Math.min(
366 retryDelay * this.backoffFactor,
367 this.maximumRetryInterval
368 )
369 } else {
370 throw new MedusaError(MedusaError.Types.CONFLICT, errMessage)
371 }
372 }
373 }
374 }
375
376 await acquireLock()
377 })
378
379 await promiseAll(acquirePromises)
380 }
381
382 async release(
383 keys: string | string[],
384 args?: {
385 ownerId?: string | null
386 }
387 ): Promise<boolean> {
388 const ownerId = args?.ownerId ?? "*"
389 keys = Array.isArray(keys) ? keys : [keys]
390
391 const releasePromises = keys.map(async (key) => {
392 const keyName = this.getKeyName(key)
393 const result = await this.redisClient.releaseLock(keyName, ownerId)
394 return result === 1
395 })
396
397 const results = await promiseAll(releasePromises)
398
399 return results.every((released) => released)
400 }
401
402 async releaseAll(args?: { ownerId?: string | null }): Promise<void> {
403 const ownerId = args?.ownerId ?? "*"
404
405 const pattern = `${this.keyNamePrefix}*`
406 let cursor = "0"
407
408 do {
409 const result = await this.redisClient.scan(
410 cursor,
411 "MATCH",
412 pattern,
413 "COUNT",
414 100
415 )
416 cursor = result[0]
417 const keys = result[1]
418
419 if (keys.length > 0) {
420 const pipeline = this.redisClient.pipeline()
421
422 keys.forEach((key) => {
423 pipeline.get(key)
424 })
425
426 const currentOwners = await pipeline.exec()
427
428 const deletePipeline = this.redisClient.pipeline()
429 keys.forEach((key, idx) => {
430 const currentOwner = currentOwners?.[idx]?.[1]
431
432 if (currentOwner === ownerId) {
433 deletePipeline.unlink(key)
434 }
435 })
436
437 await deletePipeline.exec()
438 }
439 } while (cursor !== "0")
440 }
441
442 private async getTimeout(
443 seconds: number,
444 cancellationToken: { cancelled: boolean }
445 ): Promise<void> {
446 return new Promise(async (_, reject) => {
447 await delay(seconds * 1000)
448 cancellationToken.cancelled = true
449 reject(
450 new MedusaError(MedusaError.Types.CONFLICT, "Timed-out acquiring lock.")
451 )
452 })
453 }
454 }