1 import { MedusaContainer } from "@medusajs/types"
2 import { dynamicImport, isFileSkipped, Modules } from "@medusajs/utils"
3 import { basename } from "path"
4 import { logger } from "../logger"
5 import { Migrator } from "./migrator"
6
7 export class MigrationScriptsMigrator extends Migrator {
8 protected migration_table_name = "script_migrations"
9
10 constructor({ container }: { container: MedusaContainer }) {
11 super({ container })
12 }
13
14 /**
15 * Run the migration scripts
16 * @param paths - The paths from which to load the scripts
17 */
18 async run(paths: string[]): Promise<void> {
19 const lockService = this.container.resolve(Modules.LOCKING)
20
21 const lockKey = "migration-scripts-running"
22 await lockService.acquire(lockKey, {
23 expire: 60 * 60,
24 })
25
26 try {
27 const scriptPaths = await this.getPendingMigrations(paths)
28 for (const script of scriptPaths) {
29 const scriptFn = await dynamicImport(script)
30
31 if (isFileSkipped(scriptFn)) {
32 continue
33 }
34
35 if (!scriptFn.default) {
36 throw new Error(
37 `Failed to load migration script ${script}. No default export found.`
38 )
39 }
40
41 const scriptName = basename(script)
42
43 /**
44 * The script is skipped when it has already been executed, or when
45 * another process is running it right now.
46 */
47 const claim = await this.#claimMigration(scriptName)
48 if (!claim.claimed) {
49 if (claim.reason === "running-elsewhere") {
50 /**
51 * When a previous run died without closing its connection cleanly,
52 * Postgres keeps that connection, and the advisory lock it holds,
53 * until it detects the half-open connection. Until then the script
54 * is reported as running elsewhere. It is picked up again by a
55 * later run, once the connection has been reaped.
56 */
57 logger.info(
58 `Skipping migration script ${script}. It is being executed by another process`
59 )
60 }
61 continue
62 }
63
64 if (claim.wasInterrupted) {
65 logger.warn(
66 `Migration script ${script} did not complete during a previous run and is being executed again`
67 )
68 }
69
70 logger.info(`Running migration script ${script}`)
71 try {
72 const tracker = this.trackDuration()
73
74 await scriptFn.default({ container: this.container })
75
76 /**
77 * The script is only considered executed once it ran to completion.
78 * Until `finished_at` is set, the record is treated as pending and
79 * the script will be picked up again by the next run.
80 */
81 await this.#updateMigrationFinishedAt(scriptName)
82
83 logger.info(
84 `Migration script ${script} completed (${tracker.getSeconds()}s)`
85 )
86 } catch (error) {
87 logger.error(`Failed to run migration script ${script}:`, error)
88 throw error
89 } finally {
90 await claim.release()
91 }
92 }
93 } finally {
94 await lockService.release(lockKey)
95 }
96 }
97
98 async getPendingMigrations(migrationPaths: string[]): Promise<string[]> {
99 /**
100 * A script is only considered executed once it has finished running. Scripts
101 * that were interrupted (e.g. a deadlock, a crash or a killed process) have
102 * a record without a `finished_at` and must be run again.
103 */
104 const executedMigrations = new Set(
105 (await this.getExecutedMigrations())
106 .filter((item) => !!item.finished_at)
107 .map((item) => item.script_name)
108 )
109
110 const all = await this.loadMigrationFiles(migrationPaths)
111
112 return all.filter((item) => !executedMigrations.has(basename(item)))
113 }
114
115 protected async createMigrationTable(): Promise<void> {
116 await this.pgConnection.raw(`
117 CREATE TABLE IF NOT EXISTS ${this.migration_table_name} (
118 id SERIAL PRIMARY KEY,
119 script_name VARCHAR(255) NOT NULL,
120 created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
121 finished_at TIMESTAMP WITH TIME ZONE
122 );
123
124 CREATE UNIQUE INDEX IF NOT EXISTS idx_script_name_unique ON ${this.migration_table_name} (script_name);
125 `)
126 }
127
128 /**
129 * Hashes a string into a signed 32-bit integer, as required by the Postgres
130 * advisory lock functions.
131 */
132 #hashStringToInt(str: string): number {
133 let hash = 5381
134 for (let i = str.length; i--; ) {
135 hash = (hash * 33) ^ str.charCodeAt(i)
136 }
137 return hash | 0
138 }
139
140 /**
141 * Claims a migration script before running it.
142 *
143 * Two guarantees are needed here, and they pull in opposite directions:
144 *
145 * - A script that was interrupted (deadlock, crash, killed process) must be
146 * picked up again by a later run.
147 * - A script that another process is running right now must not be run a
148 * second time in parallel.
149 *
150 * The database record alone cannot tell those two apart: in both cases the
151 * record exists without a `finished_at`. The difference is whether the
152 * process that claimed it is still alive, so a session-level advisory lock is
153 * held on a dedicated connection for as long as the script runs. Postgres
154 * releases that lock by itself once the connection goes away, which is
155 * exactly what happens when a process dies, while a live process keeps
156 * holding it.
157 *
158 * @param scriptName - The name of the script to claim
159 * @returns The outcome of the claim, and a `release` to call once the script
160 * is done.
161 */
162 async #claimMigration(scriptName: string): Promise<{
163 claimed: boolean
164 /**
165 * Whether a previous run of this script was interrupted before completing.
166 */
167 wasInterrupted?: boolean
168 reason?: "already-executed" | "running-elsewhere"
169 release: () => Promise<void>
170 }> {
171 const lockKey = this.#hashStringToInt(
172 `${this.migration_table_name}:${scriptName}`
173 )
174
175 const client = this.pgConnection.client
176 const connection = await client.acquireConnection()
177
178 let released = false
179 const release = async (unlock: boolean) => {
180 if (released) {
181 return
182 }
183 released = true
184
185 try {
186 if (unlock) {
187 await connection.query("SELECT pg_advisory_unlock($1)", [lockKey])
188 }
189 } finally {
190 await client.releaseConnection(connection)
191 }
192 }
193
194 try {
195 /**
196 * `pg_try_advisory_lock` never waits. It either takes the lock and
197 * returns true, or returns false when someone else is holding it.
198 */
199 const lock = await connection.query(
200 "SELECT pg_try_advisory_lock($1) AS acquired",
201 [lockKey]
202 )
203
204 if (!lock.rows[0].acquired) {
205 await release(false)
206 return {
207 claimed: false,
208 reason: "running-elsewhere",
209 release: async () => {},
210 }
211 }
212
213 /**
214 * The lock is held, so no other process can be claiming this script at
215 * the same time and the existing record can be read safely.
216 */
217 const existing = await connection.query(
218 `SELECT finished_at FROM ${this.migration_table_name} WHERE script_name = $1`,
219 [scriptName]
220 )
221
222 const record = existing.rows[0]
223
224 if (record?.finished_at) {
225 await release(true)
226 return {
227 claimed: false,
228 reason: "already-executed",
229 release: async () => {},
230 }
231 }
232
233 /**
234 * A record without a `finished_at` belongs to a run that was interrupted.
235 */
236 const wasInterrupted = !!record
237
238 /**
239 * The record is inserted, or re-claimed when a previous run left it
240 * without a `finished_at`. The `WHERE` clause keeps the statement safe on
241 * its own, so a finished record can never be re-claimed by it.
242 */
243 await connection.query(
244 `INSERT INTO ${this.migration_table_name} (script_name) VALUES ($1)
245 ON CONFLICT (script_name) DO UPDATE SET created_at = NOW()
246 WHERE ${this.migration_table_name}.finished_at IS NULL`,
247 [scriptName]
248 )
249
250 return { claimed: true, wasInterrupted, release: () => release(true) }
251 } catch (error) {
252 await release(true)
253 throw error
254 }
255 }
256
257 #updateMigrationFinishedAt(scriptName: string) {
258 return this.pgConnection.raw(
259 `UPDATE ${this.migration_table_name} SET finished_at = NOW() WHERE script_name = ?`,
260 [scriptName]
261 )
262 }
263 }