Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-db/src/wait-for-db.ts
2498 views
1
/**
2
* Copyright (c) 2020 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
/**
8
* Script that waits for a database to become available
9
*/
10
import "reflect-metadata";
11
import { Config } from "./config";
12
import * as mysql from "mysql";
13
14
const retryPeriod = 5000; // [ms]
15
const totalAttempts = 30;
16
const connCfg: mysql.ConnectionConfig = {
17
...new Config().mysqlConfig,
18
timeout: retryPeriod,
19
};
20
21
function connectOrReschedule(attempt: number) {
22
const con = mysql.createConnection(connCfg);
23
try {
24
con.connect((err) => {
25
if (err) {
26
rescheduleConnectionAttempt(attempt, err);
27
} else {
28
console.log("DB is available");
29
con.destroy();
30
process.exit(0);
31
}
32
});
33
} catch (err) {
34
rescheduleConnectionAttempt(attempt, err);
35
}
36
}
37
38
function rescheduleConnectionAttempt(attempt: number, err: unknown) {
39
if (attempt == totalAttempts) {
40
console.log(`Could not connect within ${totalAttempts} attempts. Stopping.`, err);
41
process.exit(1);
42
}
43
console.log(`Connection attempt ${attempt}/${totalAttempts} failed. Retrying in ${retryPeriod / 1000} seconds.`);
44
setTimeout(() => connectOrReschedule(attempt + 1), retryPeriod);
45
}
46
47
connectOrReschedule(0);
48
49