Automatically retry DB connection on startup

This adds retry logic to the initial DB connection on startup.
HedgeDoc now tries connecting to the database up to 30 times, waiting
one second after each try.
This gives a database that was simultaneously started (e.g. via
docker-compose) enough time to get ready to accept connections.

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2021-05-04 18:25:30 +02:00
parent 936b87f3b4
commit 44ebf12d25
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3

41
app.js
View file

@ -272,21 +272,38 @@ function startListen () {
} }
} }
// sync db then start listen const maxDBTries = 30
models.sequelize.authenticate().then(function () { let currentDBTry = 1
models.runMigrations().then(() => { function syncAndListen () {
sessionStore.sync() // sync db then start listen
// check if realtime is ready models.sequelize.authenticate().then(function () {
if (realtime.isReady()) { models.runMigrations().then(() => {
models.Revision.checkAllNotesRevision(function (err, notes) { sessionStore.sync()
if (err) throw new Error(err) // check if realtime is ready
if (!notes || notes.length <= 0) return startListen() if (realtime.isReady()) {
}) models.Revision.checkAllNotesRevision(function (err, notes) {
if (err) throw new Error(err)
if (!notes || notes.length <= 0) return startListen()
})
} else {
logger.error('server still not ready after db synced')
process.exit(1)
}
})
}).catch(() => {
if (currentDBTry < maxDBTries) {
logger.warn(`Database cannot be reached. Try ${currentDBTry} of ${maxDBTries}.`)
currentDBTry++
setTimeout(function () {
syncAndListen()
}, 1000)
} else { } else {
throw new Error('server still not ready after db synced') logger.error('Cannot reach database! Exiting.')
process.exit(1)
} }
}) })
}) }
syncAndListen()
// log uncaught exception // log uncaught exception
process.on('uncaughtException', function (err) { process.on('uncaughtException', function (err) {