From a440b36a9e5ef6bc5a0103fdf4b45cdfb790738a Mon Sep 17 00:00:00 2001 From: Reinaldy Rafli Date: Sun, 7 Apr 2024 12:06:50 +0700 Subject: [PATCH] feat: uptime monitor --- src/app.js | 2 ++ src/uptime.js | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 src/uptime.js diff --git a/src/app.js b/src/app.js index d40060d..4e28a4b 100644 --- a/src/app.js +++ b/src/app.js @@ -52,11 +52,13 @@ const mongo = mongoose.createConnection(String(process.env.MONGO_URL), { // Fork processes const hackernewsFork = fork(pathTo(import.meta.url, "./hackernews.js"), { detached: true }); +const uptimeFork = fork(pathTo(import.meta.url, "./uptime.js", { detached: true })); async function terminate(caller) { const t = Date.now(); bot.stop(caller); hackernewsFork.kill(); + uptimeFork.kill(); await mongo.close(); await Sentry.flush(); terminal.info(`${caller}: ${Date.now() - t}ms`); diff --git a/src/uptime.js b/src/uptime.js new file mode 100644 index 0000000..e54c42b --- /dev/null +++ b/src/uptime.js @@ -0,0 +1,51 @@ +import dotenv from "dotenv"; +import got from "got"; +import * as Sentry from "@sentry/node"; +import { pathTo } from "#utils/path.js"; + +dotenv.config({ path: pathTo(import.meta.url, "../.env") }); + +const UPTIME_MONITOR_URL = process.env.UPTIME_MONITOR_URL; + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function run(url) { + const searchParams = new URLSearchParams(); + searchParams.set("msg", "OK"); + searchParams.set("ping", "0"); + searchParams.set("status", "up"); + + await got.post(url + "?" + searchParams.toString()); +} + +for (;;) { + // Don't start the uptime service if the monitor url is empty. + if (!UPTIME_MONITOR_URL) { + break; + } + + let done = false; + + // eslint-disable-next-line no-await-in-loop + await run(UPTIME_MONITOR_URL) + .catch((error) => { + Sentry.captureException(error); + }) + .finally(() => { + done = true; + }); + + while (!done) { + // wait + await sleep(1000); + } + + // How long do we need to sleep + const now = new Date(); + const nextTime = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes() + 1, now.getUTCSeconds(), 0); + + // eslint-disable-next-line no-await-in-loop + await sleep(nextTime.getTime() - now.getTime()); +}