|
| 1 | +import net from "node:net"; |
| 2 | +import { URL } from "node:url"; |
| 3 | +import { dbUrl } from "@dokploy/server/db/constants"; |
| 4 | + |
| 5 | +const TIMEOUT_MS = Number(process.env.POSTGRES_WAIT_TIMEOUT || 120_000); |
| 6 | +const RETRY_DELAY_MS = Number(process.env.POSTGRES_WAIT_RETRY || 2000); |
| 7 | + |
| 8 | +function sleep(ms: number) { |
| 9 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 10 | +} |
| 11 | + |
| 12 | +function resolvePostgresTarget(): { host: string; port: number } { |
| 13 | + const databaseUrl = dbUrl; |
| 14 | + |
| 15 | + if (!databaseUrl) { |
| 16 | + console.error("[wait-for-postgres] DATABASE_URL is not set"); |
| 17 | + process.exit(1); |
| 18 | + } |
| 19 | + |
| 20 | + try { |
| 21 | + const url = new URL(databaseUrl); |
| 22 | + |
| 23 | + const host = url.hostname; |
| 24 | + const port = Number(url.port || 5432); |
| 25 | + |
| 26 | + if (!host) { |
| 27 | + throw new Error("DATABASE_URL has no hostname"); |
| 28 | + } |
| 29 | + |
| 30 | + return { host, port }; |
| 31 | + } catch (err) { |
| 32 | + console.error("[wait-for-postgres] Invalid DATABASE_URL:", databaseUrl); |
| 33 | + process.exit(1); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function checkTcpConnection(host: string, port: number): Promise<void> { |
| 38 | + return new Promise((resolve, reject) => { |
| 39 | + const socket = net.createConnection({ host, port }); |
| 40 | + |
| 41 | + socket.setTimeout(3000); |
| 42 | + |
| 43 | + socket.on("connect", () => { |
| 44 | + socket.end(); |
| 45 | + resolve(); |
| 46 | + }); |
| 47 | + |
| 48 | + socket.on("timeout", () => { |
| 49 | + socket.destroy(); |
| 50 | + reject(new Error("Connection timeout")); |
| 51 | + }); |
| 52 | + |
| 53 | + socket.on("error", reject); |
| 54 | + }); |
| 55 | +} |
| 56 | + |
| 57 | +async function waitForPostgres() { |
| 58 | + const { host, port } = resolvePostgresTarget(); |
| 59 | + const start = Date.now(); |
| 60 | + |
| 61 | + console.log( |
| 62 | + `[wait-for-postgres] Waiting for postgres at ${host}:${port} (timeout ${TIMEOUT_MS}ms)`, |
| 63 | + ); |
| 64 | + |
| 65 | + while (true) { |
| 66 | + try { |
| 67 | + await checkTcpConnection(host, port); |
| 68 | + console.log("[wait-for-postgres] Postgres is reachable ✅"); |
| 69 | + return; |
| 70 | + } catch { |
| 71 | + const elapsed = Date.now() - start; |
| 72 | + |
| 73 | + if (elapsed > TIMEOUT_MS) { |
| 74 | + console.error( |
| 75 | + `[wait-for-postgres] Timeout after ${elapsed}ms. Postgres not reachable ❌`, |
| 76 | + ); |
| 77 | + process.exit(1); |
| 78 | + } |
| 79 | + |
| 80 | + console.log( |
| 81 | + `[wait-for-postgres] Postgres not ready yet, retrying in ${RETRY_DELAY_MS}ms...`, |
| 82 | + ); |
| 83 | + await sleep(RETRY_DELAY_MS); |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +waitForPostgres().catch((err) => { |
| 89 | + console.error("[wait-for-postgres] Fatal error:", err); |
| 90 | + process.exit(1); |
| 91 | +}); |
0 commit comments