From eb6329e6f74105a10446b9eb546da8faf00464d5 Mon Sep 17 00:00:00 2001 From: "D. Berge" Date: Tue, 6 Oct 2020 19:44:07 +0200 Subject: [PATCH] Catch DB connection errors. If we can't connect straight away (either first time or after a disconnection), keep retrying until we manage. --- lib/www/server/ws/db.js | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/lib/www/server/ws/db.js b/lib/www/server/ws/db.js index 669ea99..c9a9a17 100644 --- a/lib/www/server/ws/db.js +++ b/lib/www/server/ws/db.js @@ -27,29 +27,41 @@ function reconnect () { async function listen (addChannels, callback) { if (!client) { - client = await pool.connect(); + try { + client = await pool.connect(); + } catch (err) { + console.error("Error connecting to DB", err); + console.log("Will try again in 15 seconds"); + setImmediate(() => client = null); + setTimeout(() => { + listen(addChannels, callback); + }, 15000); + return; + } client.on('notification', notify); - console.log("Client connected"); + console.log("Client connected", Object.keys(channels)); client.on('error', (err) => console.error("Events client error: ", err)); client.on('end', () => { - console.warning("Events client disconnected. Will attempt to reconnect in five seconds"); + console.warn("Events client disconnected. Will attempt to reconnect in five seconds"); setImmediate(() => client = null); setTimeout(reconnect, 5000); }); } - if (addChannels && !Array.isArray(addChannels)) { - addChannels = [addChannels]; - } - - for (const channel of addChannels) { - if (!(channel in channels)) { - await client.query("LISTEN "+channel); - channels[channel] = []; - console.log("Listening to ", channel); + if (addChannels) { + if (!Array.isArray(addChannels)) { + addChannels = [addChannels]; } - channels[channel].push(callback); + for (const channel of addChannels) { + if (!(channel in channels)) { + await client.query("LISTEN "+channel); + channels[channel] = []; + console.log("Listening to ", channel); + } + + channels[channel].push(callback); + } } }