pingql/apps/web/src/routes/internal.ts

30 lines
918 B
TypeScript

/// Internal endpoints used by the Rust monitor runner.
/// Protected by MONITOR_TOKEN — not exposed to users.
import { Elysia } from "elysia";
import sql from "../db";
export const internal = new Elysia({ prefix: "/internal", detail: { hide: true } })
.derive(({ headers, error }) => {
if (headers["x-monitor-token"] !== process.env.MONITOR_TOKEN)
return error(401, { error: "Unauthorized" });
return {};
})
// Returns monitors that are due for a check
.get("/due", async () => {
return sql`
SELECT m.id, m.url, m.interval_s, m.query
FROM monitors m
LEFT JOIN LATERAL (
SELECT checked_at FROM check_results
WHERE monitor_id = m.id
ORDER BY checked_at DESC LIMIT 1
) last ON true
WHERE m.enabled = true
AND (last.checked_at IS NULL
OR last.checked_at < now() - (m.interval_s || ' seconds')::interval)
`;
});