Skip to content

Commit

Permalink
feat: uptime monitor
Browse files Browse the repository at this point in the history
  • Loading branch information
aldy505 committed Apr 7, 2024
1 parent 9313883 commit a440b36
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`);
Expand Down
51 changes: 51 additions & 0 deletions src/uptime.js
Original file line number Diff line number Diff line change
@@ -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);

Check warning on line 42 in src/uptime.js

View workflow job for this annotation

GitHub Actions / Check

Unexpected `await` inside a loop

Check warning on line 42 in src/uptime.js

View workflow job for this annotation

GitHub Actions / Check

Unexpected `await` inside a loop
}

// 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());
}

0 comments on commit a440b36

Please sign in to comment.