1 import {
2 ContainerRegistrationKeys,
3 ModulesSdkUtils,
4 retryExecution,
5 stringifyCircular,
6 withDbTroubleshootingLink,
7 } from "@medusajs/utils"
8 import { asValue } from "../deps/awilix"
9 import { configManager } from "../config"
10 import { container } from "../container"
11 import { logger } from "../logger"
12
13 /**
14 * PostgreSQL error codes that indicate a permanent misconfiguration. Retrying
15 * these is pointless and only delays surfacing the actual problem.
16 */
17 const FATAL_PG_CONNECTION_ERROR_CODES = new Set([
18 "3D000", // database does not exist
19 "28P01", // invalid password
20 "28000", // invalid authorization specification
21 "42501", // insufficient privilege
22 ])
23
24 const isFatalConnectionError = (error: unknown): boolean => {
25 const code = (error as { code?: string })?.code
26 return !!code && FATAL_PG_CONNECTION_ERROR_CODES.has(code)
27 }
28
29 /**
30 * Initialize a knex connection that can then be shared to any resources if needed
31 */
32 export async function pgConnectionLoader(): Promise<
33 ReturnType<typeof ModulesSdkUtils.createPgConnection>
34 > {
35 if (container.hasRegistration(ContainerRegistrationKeys.PG_CONNECTION)) {
36 return container.resolve(
37 ContainerRegistrationKeys.PG_CONNECTION
38 ) as unknown as ReturnType<typeof ModulesSdkUtils.createPgConnection>
39 }
40
41 const configModule = configManager.config
42
43 // Share a knex connection to be consumed by the shared modules
44 const connectionString = configModule.projectConfig.databaseUrl
45 const driverOptions: any = {
46 ...(configModule.projectConfig.databaseDriverOptions || {}),
47 }
48 const schema = configModule.projectConfig.databaseSchema || "public"
49 const idleTimeoutMillis = driverOptions.pool?.idleTimeoutMillis ?? undefined // prevent null to be passed
50 const poolMin = driverOptions.pool?.min ?? 2
51 const poolMax = driverOptions.pool?.max
52 const reapIntervalMillis = driverOptions.pool?.reapIntervalMillis ?? undefined
53 const createRetryIntervalMillis =
54 driverOptions.pool?.createRetryIntervalMillis ?? undefined
55
56 delete driverOptions.pool
57
58 const clientUrl = connectionString?.replace(
59 /(\?|&)ssl_mode=[^&]*(&|$)/gi,
60 (match, prefix, suffix) => {
61 if (prefix === "?" && suffix === "&") return "?"
62 if (prefix === "?" && suffix === "") return ""
63 if (prefix === "&") return suffix
64 return ""
65 }
66 )
67
68 const pgConnection = ModulesSdkUtils.createPgConnection({
69 clientUrl,
70 schema,
71 driverOptions,
72 pool: {
73 min: poolMin,
74 max: poolMax,
75 idleTimeoutMillis,
76 reapIntervalMillis,
77 createRetryIntervalMillis,
78 },
79 })
80
81 const maxRetries = process.env.__MEDUSA_DB_CONNECTION_MAX_RETRIES
82 ? parseInt(process.env.__MEDUSA_DB_CONNECTION_MAX_RETRIES)
83 : 5
84
85 const retryDelay = process.env.__MEDUSA_DB_CONNECTION_RETRY_DELAY
86 ? parseInt(process.env.__MEDUSA_DB_CONNECTION_RETRY_DELAY)
87 : 1000
88
89 let lastConnectionError: Error | undefined
90 let fatalConnectionError: Error | undefined
91 pgConnection.client?.pool?.on?.(
92 "createFail",
93 (_eventId: unknown, error: Error) => {
94 lastConnectionError = error
95 if (isFatalConnectionError(error)) {
96 fatalConnectionError = error
97 }
98 }
99 )
100
101 const formatConnectionError = (error: unknown) => {
102 if (lastConnectionError && lastConnectionError !== error) {
103 return `${stringifyCircular(lastConnectionError)}\n(pool reported: ${
104 (error as Error)?.message ?? error
105 })`
106 }
107 return stringifyCircular(lastConnectionError ?? error)
108 }
109
110 /**
111 * A permanent misconfiguration (for example, a non-existent database or
112 * invalid credentials) surfaces on the pool's `createFail` event almost
113 * immediately, while `raw` stays pending until knex's acquire timeout (~60s)
114 * because of `propagateCreateError: false`. Reject as soon as such a fatal
115 * error is observed so the migrator/runtime doesn't wait for the full acquire
116 * timeout on every retry.
117 */
118 const probeConnection = () => {
119 if (fatalConnectionError) {
120 return Promise.reject(fatalConnectionError)
121 }
122
123 return new Promise<void>((resolve, reject) => {
124 let settled = false
125 const settle = (fn: () => void) => {
126 if (settled) {
127 return
128 }
129 settled = true
130 pgConnection.client?.pool?.removeListener?.("createFail", onFatal)
131 fn()
132 }
133
134 const onFatal = (_eventId: unknown, error: Error) => {
135 if (isFatalConnectionError(error)) {
136 settle(() => reject(error))
137 }
138 }
139
140 pgConnection.client?.pool?.on?.("createFail", onFatal)
141
142 Promise.resolve(pgConnection.raw("SELECT 1"))
143 .then(() => settle(resolve))
144 .catch((error) => settle(() => reject(error)))
145 })
146 }
147
148 try {
149 await retryExecution(probeConnection, {
150 maxRetries,
151 retryDelay,
152 shouldRetry: (error) =>
153 !isFatalConnectionError(error) && !fatalConnectionError,
154 onRetry: (error) => {
155 logger.warn(
156 `Pg connection failed to connect to the database. Retrying...\n${formatConnectionError(
157 error
158 )}`
159 )
160 },
161 })
162 } catch (error) {
163 if (lastConnectionError) {
164 lastConnectionError.message = withDbTroubleshootingLink(
165 `Failed to connect to the database: ${lastConnectionError.message}`
166 )
167 throw lastConnectionError
168 }
169
170 if (error instanceof Error) {
171 error.message = withDbTroubleshootingLink(error.message)
172 }
173 throw error
174 }
175
176 container.register(
177 ContainerRegistrationKeys.PG_CONNECTION,
178 asValue(pgConnection)
179 )
180
181 return pgConnection
182 }