From 21c713255c04d8f489cfbcb098d386ed244132b2 Mon Sep 17 00:00:00 2001 From: Dragory Date: Sun, 5 Aug 2018 00:45:35 +0300 Subject: [PATCH] LogServer: retry starting the web server if it fails due to EADDRINUSE (probably old instance of the bot still shutting down) --- src/plugins/LogServer.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/plugins/LogServer.ts b/src/plugins/LogServer.ts index ee41c958..69c123fd 100644 --- a/src/plugins/LogServer.ts +++ b/src/plugins/LogServer.ts @@ -1,6 +1,7 @@ import http, { ServerResponse } from "http"; import { GlobalPlugin } from "knub"; import { GuildSpamLogs } from "../data/GuildSpamLogs"; +import { sleep } from "../utils"; const DEFAULT_PORT = 9920; const logUrlRegex = /^\/spam-logs\/([a-z0-9\-]+)\/?$/i; @@ -17,7 +18,7 @@ export class LogServerPlugin extends GlobalPlugin { protected spamLogs: GuildSpamLogs; protected server: http.Server; - onLoad() { + async onLoad() { this.spamLogs = new GuildSpamLogs(null); this.server = http.createServer(async (req, res) => { @@ -33,6 +34,19 @@ export class LogServerPlugin extends GlobalPlugin { } }); + let retried = false; + + this.server.on("error", async (err: any) => { + if (err.code === "EADDRINUSE" && !retried) { + console.log("Got EADDRINUSE, retrying in 2 sec..."); + retried = true; + await sleep(2000); + this.server.listen(this.configValue("port", DEFAULT_PORT)); + } else { + throw err; + } + }); + this.server.listen(this.configValue("port", DEFAULT_PORT)); }