Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: uptime monitor #227

Merged
merged 1 commit into from
Apr 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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());
}
Loading