1 import { ILockingProvider } from "@medusajs/framework/types"
2 import { isDefined, MedusaService } from "@medusajs/framework/utils"
3 import { EntityManager } from "@medusajs/framework/mikro-orm/core"
4 import { Locking } from "@models"
5
6 type InjectedDependencies = {
7 manager: EntityManager
8 }
9
10 export class PostgresAdvisoryLockProvider
11 extends MedusaService({ Locking })
12 implements ILockingProvider
13 {
14 static identifier = "locking-postgres"
15
16 protected manager: EntityManager
17
18 constructor(container: InjectedDependencies) {
19 // @ts-ignore
20 super(...arguments)
21 this.manager = container.manager
22 }
23
24 private getManager(): any {
25 return this.manager
26 }
27
28 /**
29 * Runs `job` while holding `keys` as transaction-scoped advisory locks. They
30 * are held by the transaction below for as long as it is open, so lease renewal
31 * is not necessary.
32 */
33 async execute<T>(
34 keys: string | string[],
35 job: (signal?: AbortSignal) => Promise<T>,
36 args?: {
37 timeout?: number
38 expire?: number
39 }
40 ): Promise<T> {
41 const timeout = Math.max(args?.timeout ?? 5, 1)
42 const timeoutSeconds = Number.isNaN(timeout) ? 1 : timeout
43
44 return await this.getManager().transactional(async (manager) => {
45 const ops: Promise<unknown>[] = []
46 if (timeoutSeconds > 0) {
47 ops.push(this.getTimeout(timeoutSeconds))
48 }
49
50 const fnName = "pg_advisory_xact_lock"
51
52 const allKeys = Array.isArray(keys) ? keys : [keys]
53 const numKeys = allKeys.map(this.hashStringToInt)
54 const lockPromises = numKeys.map((numKey) =>
55 manager.execute(`SELECT ${fnName}(?)`, [numKey])
56 )
57
58 const lock = Promise.all(lockPromises)
59
60 ops.push(lock)
61
62 try {
63 await Promise.race(ops)
64
65 const ret = await job()
66 await manager.commit()
67
68 return ret
69 } catch (e) {
70 await manager.rollback()
71 throw e
72 }
73 })
74 }
75
76 private async loadLock(key: string): Promise<{
77 owner_id: string | null
78 expiration: number | null
79 now: number
80 }> {
81 const [row] = await this.getManager().execute(
82 `SELECT owner_id, expiration, NOW() AS now FROM locking WHERE id = ?`,
83 [key]
84 )
85
86 return row
87 }
88
89 async acquire(
90 keys: string | string[],
91 args?: {
92 ownerId?: string | null
93 expire?: number
94 }
95 ): Promise<void> {
96 keys = Array.isArray(keys) ? keys : [keys]
97
98 const { ownerId, expire } = args ?? {}
99 for (const key of keys) {
100 const row = await this.loadLock(key)
101
102 if (!row) {
103 const expireSql = expire
104 ? `NOW() + INTERVAL '${+expire} SECONDS'`
105 : "NULL"
106
107 try {
108 await this.getManager().execute(
109 `INSERT INTO locking (id, owner_id, expiration) VALUES (?, ?, ${expireSql})`,
110 [key, ownerId ?? null]
111 )
112 } catch (err) {
113 if (err.toString().includes("locking_pkey")) {
114 const owner = await this.loadLock(key)
115 if (ownerId != owner.owner_id) {
116 throw new Error(`"${key}" is already locked.`)
117 }
118 } else {
119 throw err
120 }
121 }
122 continue
123 }
124
125 const errMessage = `Failed to acquire lock for key "${key}"`
126 if (row.owner_id === null || row.owner_id !== ownerId) {
127 throw new Error(errMessage)
128 }
129
130 if (!row.expiration && row.owner_id == ownerId) {
131 continue
132 }
133
134 const canRefresh =
135 row.owner_id == ownerId && (expire || row.expiration! <= row.now)
136
137 if (!canRefresh || !expire) {
138 continue
139 }
140
141 await this.getManager().execute(
142 `UPDATE locking SET owner_id = ?, expiration = NOW() + INTERVAL '${+expire} SECONDS' WHERE id = ?`,
143 [ownerId ?? null, key]
144 )
145 }
146 }
147
148 async release(
149 keys: string | string[],
150 args?: {
151 ownerId?: string | null
152 }
153 ): Promise<boolean> {
154 const { ownerId } = args ?? {}
155
156 keys = Array.isArray(keys) ? keys : [keys]
157
158 let success = true
159 for (const key of keys) {
160 const row = await this.loadLock(key)
161
162 if (!row || row.owner_id != ownerId) {
163 success = false
164 continue
165 }
166
167 await this.getManager().execute(`DELETE FROM locking WHERE id = ?`, [key])
168
169 success = success && (!row.expiration || row.expiration > row.now)
170 }
171 return success
172 }
173
174 async releaseAll(args?: { ownerId?: string | null }): Promise<void> {
175 const { ownerId } = args ?? {}
176
177 if (!isDefined(ownerId)) {
178 await this.getManager().execute(`TRUNCATE TABLE locking`)
179 } else {
180 await this.getManager().execute(
181 `DELETE FROM locking WHERE owner_id = ?`,
182 [ownerId]
183 )
184 }
185 }
186
187 private hashStringToInt(str: string): number {
188 let hash = 5381
189 for (let i = str.length; i--; ) {
190 hash = (hash * 33) ^ str.charCodeAt(i)
191 }
192 return hash >>> 0
193 }
194
195 private async getTimeout(seconds: number): Promise<void> {
196 return new Promise((_, reject) => {
197 setTimeout(() => {
198 reject(new Error("Timed-out acquiring lock."))
199 }, seconds * 1000)
200 })
201 }
202 }