fet: reduce LOC by reducing comments
This commit is contained in:
@@ -1,6 +1,3 @@
|
||||
/// Internal endpoints used by the Rust monitor runner.
|
||||
/// Protected by MONITOR_TOKEN — not exposed to users.
|
||||
|
||||
import { Elysia } from "elysia";
|
||||
import sql from "../db";
|
||||
import { safeTokenCompare } from "../../../shared/auth";
|
||||
@@ -10,7 +7,6 @@ export async function pruneOldPings(retentionDays = 90) {
|
||||
return result.count;
|
||||
}
|
||||
|
||||
// Run retention cleanup every hour
|
||||
setInterval(() => {
|
||||
const days = Number(process.env.PING_RETENTION_DAYS ?? 90);
|
||||
pruneOldPings(days).catch((err) => console.error("Retention cleanup failed:", err));
|
||||
@@ -31,9 +27,6 @@ export const internal = new Elysia({ prefix: "/internal", detail: { hide: true }
|
||||
}
|
||||
})
|
||||
|
||||
// Returns monitors due within the next `lookahead_ms` milliseconds (default 2000).
|
||||
// Nodes receive scheduled_at as an exact unix ms timestamp and sleep until that
|
||||
// moment before firing — all regions coordinate to the same scheduled slot.
|
||||
.get("/due", async ({ request }) => {
|
||||
const params = new URL(request.url).searchParams;
|
||||
const region = params.get('region') || undefined;
|
||||
@@ -66,7 +59,6 @@ export const internal = new Elysia({ prefix: "/internal", detail: { hide: true }
|
||||
return monitors;
|
||||
})
|
||||
|
||||
// Manual retention cleanup trigger
|
||||
.post("/prune", async () => {
|
||||
const days = Number(process.env.PING_RETENTION_DAYS ?? 90);
|
||||
const deleted = await pruneOldPings(days);
|
||||
|
||||
@@ -19,37 +19,31 @@ const MonitorBody = t.Object({
|
||||
export const monitors = new Elysia({ prefix: "/monitors" })
|
||||
.use(requireAuth)
|
||||
|
||||
// List monitors
|
||||
.get("/", async ({ accountId }) => {
|
||||
return sql`SELECT * FROM monitors WHERE account_id = ${accountId} ORDER BY created_at DESC`;
|
||||
}, { detail: { summary: "List monitors", tags: ["monitors"] } })
|
||||
|
||||
// Create monitor
|
||||
.post("/", async ({ accountId, plan, body, set }) => {
|
||||
const limits = getPlanLimits(plan);
|
||||
|
||||
// Enforce monitor count limit
|
||||
const [{ count }] = await sql`SELECT COUNT(*)::int as count FROM monitors WHERE account_id = ${accountId}`;
|
||||
if (count >= limits.maxMonitors) {
|
||||
set.status = 403;
|
||||
return { error: `Plan limit reached: ${limits.maxMonitors} monitors (${plan}). Upgrade to create more.` };
|
||||
}
|
||||
|
||||
// Enforce minimum interval for plan
|
||||
const interval = body.interval_s ?? limits.minIntervalS;
|
||||
if (interval < limits.minIntervalS) {
|
||||
set.status = 400;
|
||||
return { error: `Minimum interval for ${plan} plan is ${limits.minIntervalS}s` };
|
||||
}
|
||||
|
||||
// Enforce region limit for plan
|
||||
const regions = body.regions ?? [];
|
||||
if (regions.length > limits.maxRegions) {
|
||||
set.status = 400;
|
||||
return { error: `Free plan allows ${limits.maxRegions} region per monitor. Upgrade to use multi-region.` };
|
||||
}
|
||||
|
||||
// SSRF protection
|
||||
const ssrfError = await validateMonitorUrl(body.url);
|
||||
if (ssrfError) { set.status = 400; return { error: ssrfError }; }
|
||||
const [monitor] = await sql`
|
||||
@@ -69,7 +63,6 @@ export const monitors = new Elysia({ prefix: "/monitors" })
|
||||
return monitor;
|
||||
}, { body: MonitorBody, detail: { summary: "Create monitor", tags: ["monitors"] } })
|
||||
|
||||
// Get monitor + recent status
|
||||
.get("/:id", async ({ accountId, params, set }) => {
|
||||
const [monitor] = await sql`
|
||||
SELECT * FROM monitors WHERE id = ${params.id} AND account_id = ${accountId}
|
||||
@@ -83,23 +76,19 @@ export const monitors = new Elysia({ prefix: "/monitors" })
|
||||
return { ...monitor, results };
|
||||
}, { detail: { summary: "Get monitor with results", tags: ["monitors"] } })
|
||||
|
||||
// Update monitor
|
||||
.patch("/:id", async ({ accountId, plan, params, body, set }) => {
|
||||
const limits = getPlanLimits(plan);
|
||||
|
||||
// Enforce minimum interval for plan
|
||||
if (body.interval_s != null && body.interval_s < limits.minIntervalS) {
|
||||
set.status = 400;
|
||||
return { error: `Minimum interval for ${plan} plan is ${limits.minIntervalS}s` };
|
||||
}
|
||||
|
||||
// Enforce region limit for plan
|
||||
if (body.regions && body.regions.length > limits.maxRegions) {
|
||||
set.status = 400;
|
||||
return { error: `Free plan allows ${limits.maxRegions} region per monitor. Upgrade to use multi-region.` };
|
||||
}
|
||||
|
||||
// SSRF protection on URL change
|
||||
if (body.url) {
|
||||
const ssrfError = await validateMonitorUrl(body.url);
|
||||
if (ssrfError) { set.status = 400; return { error: ssrfError }; }
|
||||
@@ -123,7 +112,6 @@ export const monitors = new Elysia({ prefix: "/monitors" })
|
||||
return monitor;
|
||||
}, { body: t.Partial(MonitorBody), detail: { summary: "Update monitor", tags: ["monitors"] } })
|
||||
|
||||
// Delete monitor
|
||||
.delete("/:id", async ({ accountId, params, set }) => {
|
||||
const [deleted] = await sql`
|
||||
DELETE FROM monitors WHERE id = ${params.id} AND account_id = ${accountId} RETURNING id
|
||||
@@ -132,7 +120,6 @@ export const monitors = new Elysia({ prefix: "/monitors" })
|
||||
return { deleted: true };
|
||||
}, { detail: { summary: "Delete monitor", tags: ["monitors"] } })
|
||||
|
||||
// Toggle enabled
|
||||
.post("/:id/toggle", async ({ accountId, params, set }) => {
|
||||
const [monitor] = await sql`
|
||||
UPDATE monitors SET enabled = NOT enabled
|
||||
@@ -143,7 +130,6 @@ export const monitors = new Elysia({ prefix: "/monitors" })
|
||||
return monitor;
|
||||
}, { detail: { summary: "Toggle monitor on/off", tags: ["monitors"] } })
|
||||
|
||||
// Check history
|
||||
.get("/:id/pings", async ({ accountId, params, query, set }) => {
|
||||
const [monitor] = await sql`
|
||||
SELECT id FROM monitors WHERE id = ${params.id} AND account_id = ${accountId}
|
||||
@@ -169,7 +155,6 @@ export const monitors = new Elysia({ prefix: "/monitors" })
|
||||
`;
|
||||
}
|
||||
if (filter === "events") {
|
||||
// State changes: pings where `up` differs from the previous ping's `up` for this monitor
|
||||
return sql`
|
||||
SELECT * FROM (
|
||||
SELECT *, LAG(up) OVER (ORDER BY checked_at) AS prev_up
|
||||
|
||||
@@ -3,7 +3,6 @@ import sql from "../db";
|
||||
import { resolveKey } from "./auth";
|
||||
import { extractAuthKey, safeTokenCompare } from "../../../shared/auth";
|
||||
|
||||
// ── SSE bus ───────────────────────────────────────────────────────────────────
|
||||
type SSEController = ReadableStreamDefaultController<Uint8Array>;
|
||||
const bus = new Map<string, Set<SSEController>>(); // keyed by accountId
|
||||
const enc = new TextEncoder();
|
||||
@@ -50,22 +49,18 @@ function makeSSEStream(accountId: string): Response {
|
||||
});
|
||||
}
|
||||
|
||||
// ── Routes ────────────────────────────────────────────────────────────────────
|
||||
export const ingest = new Elysia()
|
||||
|
||||
// Internal: called by Rust monitor runner
|
||||
.post("/internal/ingest", async ({ body, headers, set }) => {
|
||||
const token = headers["x-monitor-token"];
|
||||
if (!safeTokenCompare(token, process.env.MONITOR_TOKEN)) { set.status = 401; return { error: "Unauthorized" }; }
|
||||
|
||||
// Validate monitor exists
|
||||
const [monitor_check] = await sql`SELECT id FROM monitors WHERE id = ${body.monitor_id}`;
|
||||
if (!monitor_check) { set.status = 404; return { error: "Monitor not found" }; }
|
||||
|
||||
const meta = body.meta ? { ...body.meta } : {};
|
||||
if (body.cert_expiry_days != null) meta.cert_expiry_days = body.cert_expiry_days;
|
||||
|
||||
// Extract response body from meta — stored separately
|
||||
const responseBody: string | null = meta.body_preview ?? null;
|
||||
delete meta.body_preview;
|
||||
|
||||
@@ -91,12 +86,10 @@ export const ingest = new Elysia()
|
||||
RETURNING *
|
||||
`;
|
||||
|
||||
// Store response body separately
|
||||
if (responseBody != null && ping) {
|
||||
await sql`INSERT INTO ping_bodies (ping_id, body) VALUES (${ping.id}, ${responseBody})`;
|
||||
}
|
||||
|
||||
// Look up account and publish to account-level bus (without body to keep SSE lean)
|
||||
const [monitor] = await sql`SELECT account_id FROM monitors WHERE id = ${body.monitor_id}`;
|
||||
if (monitor) publish(monitor.account_id, ping);
|
||||
|
||||
@@ -119,7 +112,6 @@ export const ingest = new Elysia()
|
||||
detail: { hide: true },
|
||||
})
|
||||
|
||||
// Fetch response body for a specific ping
|
||||
.get("/pings/:id/body", async ({ params, headers, cookie, set }) => {
|
||||
const key = extractAuthKey(headers, cookie);
|
||||
if (!key) { set.status = 401; return { error: "Unauthorized" }; }
|
||||
@@ -127,7 +119,6 @@ export const ingest = new Elysia()
|
||||
const resolved = await resolveKey(key);
|
||||
if (!resolved) { set.status = 401; return { error: "Unauthorized" }; }
|
||||
|
||||
// Verify the ping belongs to this account
|
||||
const [ping] = await sql`
|
||||
SELECT p.id FROM pings p
|
||||
JOIN monitors m ON m.id = p.monitor_id
|
||||
@@ -139,7 +130,6 @@ export const ingest = new Elysia()
|
||||
return { body: row?.body ?? null };
|
||||
}, { detail: { hide: true } })
|
||||
|
||||
// SSE: single stream for all of the account's monitors
|
||||
.get("/account/stream", async ({ headers, cookie }) => {
|
||||
const key = extractAuthKey(headers, cookie);
|
||||
if (!key) return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });
|
||||
|
||||
Reference in New Issue
Block a user