1 import { ILockingModule } from "@medusajs/framework/types"
2
3 /**
4 * In-memory locking module. Acquiring a key that is already held throws,
5 * which emulates the contention between separate processes the index
6 * module guards against (each process would have its own owner id).
7 */
8 export class FakeLocking implements ILockingModule {
9 locks: Map<string, string | null> = new Map()
10
11 async execute<T>(
12 keys: string | string[],
13 job: () => Promise<T>,
14 args?: { timeout?: number }
15 ): Promise<T> {
16 await this.acquire(keys)
17
18 try {
19 return await job()
20 } finally {
21 await this.release(keys)
22 }
23 }
24
25 async acquire(
26 keys: string | string[],
27 args?: { ownerId?: string | null; expire?: number }
28 ): Promise<void> {
29 const keys_ = Array.isArray(keys) ? keys : [keys]
30
31 for (const key of keys_) {
32 if (this.locks.has(key)) {
33 throw new Error(`Lock for key "${key}" is already acquired`)
34 }
35 }
36
37 for (const key of keys_) {
38 this.locks.set(key, args?.ownerId ?? null)
39 }
40 }
41
42 async release(
43 keys: string | string[],
44 args?: { ownerId?: string | null }
45 ): Promise<boolean> {
46 const keys_ = Array.isArray(keys) ? keys : [keys]
47
48 for (const key of keys_) {
49 this.locks.delete(key)
50 }
51
52 return true
53 }
54
55 async releaseAll(): Promise<void> {
56 this.locks.clear()
57 }
58 }