1 import { ILockingProvider } from "@medusajs/framework/types"
2 import { isDefined } from "@medusajs/framework/utils"
3 import { randomUUID } from "node:crypto"
4
5 type LockInfo = {
6 ownerId: string | null
7 expiration: number | null
8 currentPromise?: ResolvablePromise
9 }
10
11 type ResolvablePromise = {
12 promise: Promise<any>
13 resolve: () => void
14 }
15
16 export class InMemoryLockingProvider implements ILockingProvider {
17 static identifier = "in-memory"
18
19 private locks: Map<string, LockInfo> = new Map()
20
21 constructor() {}
22
23 private getPromise(): ResolvablePromise {
24 let resolve: any
25 const pro = new Promise((ok) => {
26 resolve = ok
27 })
28
29 return {
30 promise: pro,
31 resolve,
32 }
33 }
34
35 /**
36 * Runs `job` while holding `keys`. The lock is held for exactly as long as
37 * the job runs, lease renewal and aborts are not necessary as everything is in-memory.
38 */
39 async execute<T>(
40 keys: string | string[],
41 job: (signal?: AbortSignal) => Promise<T>,
42 args?: {
43 timeout?: number
44 expire?: number
45 }
46 ): Promise<T> {
47 const timeout = Math.max(args?.timeout ?? 5, 1)
48 const timeoutSeconds = Number.isNaN(timeout) ? 1 : timeout
49
50 // Unique per call, so the release below can only delete the lock this call
51 // took, and never one a queued caller acquired in the meantime.
52 const ownerId = `execute:${randomUUID()}`
53
54 const cancellationToken = { cancelled: false }
55 const promises: Promise<any>[] = []
56 if (timeoutSeconds > 0) {
57 promises.push(this.getTimeout(timeoutSeconds, cancellationToken))
58 }
59
60 const acquisition = this.acquire_(
61 keys,
62 {
63 ownerId,
64 awaitQueue: true,
65 },
66 cancellationToken
67 )
68 promises.push(acquisition)
69
70 try {
71 await Promise.race(promises)
72 } catch (error) {
73 // The queued acquisition can still take the keys in the same tick the
74 // timeout fires, and no job is going to use them. Since nothing expires
75 // them, they have to be given back explicitly.
76 void acquisition.then(
77 () => this.release(keys, { ownerId }),
78 () => {}
79 )
80
81 throw error
82 }
83
84 try {
85 return await job()
86 } finally {
87 await this.release(keys, { ownerId })
88 }
89 }
90
91 async acquire(
92 keys: string | string[],
93 args?: {
94 ownerId?: string | null
95 expire?: number
96 awaitQueue?: boolean
97 }
98 ): Promise<void> {
99 return this.acquire_(keys, args)
100 }
101
102 async acquire_(
103 keys: string | string[],
104 args?: {
105 ownerId?: string | null
106 expire?: number
107 awaitQueue?: boolean
108 },
109 cancellationToken?: { cancelled: boolean }
110 ): Promise<void> {
111 keys = Array.isArray(keys) ? keys : [keys]
112 const { ownerId, expire } = args ?? {}
113
114 for (const key of keys) {
115 const lock = this.locks.get(key)
116 const now = Date.now()
117
118 if (!lock) {
119 this.locks.set(key, {
120 ownerId: ownerId ?? null,
121 expiration: expire ? now + expire * 1000 : null,
122 currentPromise: this.getPromise(),
123 })
124
125 continue
126 }
127
128 if (lock.expiration && lock.expiration <= now) {
129 lock.currentPromise?.resolve?.()
130 this.locks.set(key, {
131 ownerId: ownerId ?? null,
132 expiration: expire ? now + expire * 1000 : null,
133 currentPromise: this.getPromise(),
134 })
135
136 continue
137 }
138
139 if (lock.ownerId !== null && lock.ownerId === ownerId) {
140 if (expire) {
141 lock.expiration = now + expire * 1000
142 this.locks.set(key, lock)
143 }
144
145 continue
146 }
147
148 if (lock.currentPromise && args?.awaitQueue) {
149 await lock.currentPromise.promise
150 if (cancellationToken?.cancelled) {
151 return
152 }
153
154 return this.acquire_(keys, args, cancellationToken)
155 }
156
157 throw new Error(`Failed to acquire lock for key "${key}"`)
158 }
159 }
160
161 async release(
162 keys: string | string[],
163 args?: {
164 ownerId?: string | null
165 }
166 ): Promise<boolean> {
167 const { ownerId } = args ?? {}
168 keys = Array.isArray(keys) ? keys : [keys]
169
170 let success = true
171
172 for (const key of keys) {
173 const lock = this.locks.get(key)
174 if (!lock) {
175 success = false
176 continue
177 }
178
179 if (isDefined(ownerId) && lock.ownerId !== ownerId) {
180 success = false
181 continue
182 }
183
184 lock.currentPromise?.resolve?.()
185 this.locks.delete(key)
186 }
187
188 return success
189 }
190
191 async releaseAll(args?: { ownerId?: string | null }): Promise<void> {
192 const { ownerId } = args ?? {}
193
194 if (!isDefined(ownerId)) {
195 for (const [key, lock] of this.locks.entries()) {
196 lock.currentPromise?.resolve?.()
197 this.locks.delete(key)
198 }
199 } else {
200 for (const [key, lock] of this.locks.entries()) {
201 if (lock.ownerId === ownerId) {
202 lock.currentPromise?.resolve?.()
203 this.locks.delete(key)
204 }
205 }
206 }
207 }
208
209 private async getTimeout(
210 seconds: number,
211 cancellationToken: { cancelled: boolean }
212 ): Promise<void> {
213 return new Promise((_, reject) => {
214 setTimeout(() => {
215 cancellationToken.cancelled = true
216 reject(new Error("Timed-out acquiring lock."))
217 }, seconds * 1000).unref()
218 })
219 }
220 }