Add status pages (a share link kind) and a downloadable Grafana dashboard
- Share links can open a status page: an admin picks servers, integrations and Uptime Kuma monitors and names them; the public sees only those names, Working / Not working / Being worked on / Can't tell, an optional message and the 30-day figure (share_links.kind/ title/message and status_items, migration 0033). A status address doesn't open the wall and the other way round; Uptime Kuma is asked at most every 30 seconds - Grafana dashboard built from code (download in Settings -> API and webhooks); a test checks it only uses series /metrics serves - Tests and docs Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2744a84719
commit
5cc51c57de
24 files changed
+4880
-35
No files matched your search
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* A status page: the one thing someone at home wants to know — "is Plex working?" — without a sign-in and without anything that isn't
|
||||
* theirs to see. An administrator makes a share link of the status kind and picks what is on it, each with a name people will recognise
|
||||
* ("Movies", "Photos") instead of what the machine is called. Each is a server (reporting, or not), an integration (its latest calls work,
|
||||
* or don't) or an Uptime Kuma monitor (up, down, or in maintenance).
|
||||
*
|
||||
* What the public gets back is only: the page's title and message, and for each item its name, whether it is up, down, being worked on
|
||||
* or can't be told, and — where known — how it has done over 30 days. No addresses, no ids, no alert text.
|
||||
*/
|
||||
import { and, asc, eq } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { integrations, servers, statusItems, type StatusItemKind } from "../db/schema.js";
|
||||
import { createUptimeKumaAdapter, type UptimeKumaMonitor } from "../integrations/uptimekuma/adapter.js";
|
||||
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
||||
import { getSourceStatus } from "./integrationHealthMonitor.js";
|
||||
import { activeSubjects } from "./maintenance.js";
|
||||
import { effectiveThresholds, parseThresholds } from "./serverThresholds.js";
|
||||
import { getSettings } from "./settingsStore.js";
|
||||
import { getUptime } from "./uptimeHistory.js";
|
||||
|
||||
export type ItemState = "up" | "down" | "maintenance" | "unknown";
|
||||
export type PageLevel = "ok" | "issue" | "maintenance" | "unknown";
|
||||
|
||||
export const MAX_ITEMS = 30;
|
||||
export const MAX_LABEL = 60;
|
||||
export const MAX_TITLE = 60;
|
||||
export const MAX_MESSAGE = 300;
|
||||
|
||||
export interface StatusItemInput {
|
||||
label: string;
|
||||
kind: StatusItemKind;
|
||||
/** The server, the integration, or the Uptime Kuma integration a monitor belongs to. */
|
||||
targetId: number;
|
||||
/** For a monitor: Uptime Kuma's own id for it. */
|
||||
monitorId?: string | null;
|
||||
}
|
||||
|
||||
export class StatusPageError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export interface StoredItem {
|
||||
id: number;
|
||||
label: string;
|
||||
kind: StatusItemKind;
|
||||
targetId: number;
|
||||
monitorId: string | null;
|
||||
/** What it points at, for the editor: the server's or integration's name, or the monitor's. */
|
||||
targetName: string | null;
|
||||
}
|
||||
|
||||
export async function getStatusItems(linkId: number): Promise<StoredItem[]> {
|
||||
const rows = await db.select().from(statusItems).where(eq(statusItems.linkId, linkId)).orderBy(asc(statusItems.position), asc(statusItems.id));
|
||||
if (rows.length === 0) return [];
|
||||
const serverNames = new Map((await db.select({ id: servers.id, name: servers.name }).from(servers)).map((s) => [s.id, s.name]));
|
||||
const integrationNames = new Map((await db.select({ id: integrations.id, name: integrations.name }).from(integrations)).map((i) => [i.id, i.name]));
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
label: r.label,
|
||||
kind: r.kind,
|
||||
targetId: r.targetId,
|
||||
monitorId: r.monitorId,
|
||||
targetName: r.kind === "server" ? (serverNames.get(r.targetId) ?? null) : (integrationNames.get(r.targetId) ?? null),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Replaces the whole list, in the order given. Everything it points at has to exist; nothing is changed if anything is wrong. */
|
||||
export async function setStatusItems(linkId: number, items: StatusItemInput[]): Promise<void> {
|
||||
if (items.length > MAX_ITEMS) throw new StatusPageError(400, "too_many", `A status page can show up to ${MAX_ITEMS} things.`);
|
||||
const serverIds = new Set((await db.select({ id: servers.id }).from(servers)).map((s) => s.id));
|
||||
const integrationRows = new Map((await db.select({ id: integrations.id, type: integrations.type }).from(integrations)).map((i) => [i.id, i.type]));
|
||||
for (const [i, item] of items.entries()) {
|
||||
const where = `"${item.label}"`;
|
||||
if (!item.label.trim() || item.label.length > MAX_LABEL) throw new StatusPageError(400, "invalid_label", `Give each thing a name of up to ${MAX_LABEL} characters (item ${i + 1}).`);
|
||||
if (item.kind === "server" && !serverIds.has(item.targetId)) throw new StatusPageError(400, "unknown_target", `${where} points at a server that doesn't exist.`);
|
||||
if (item.kind === "integration" && !integrationRows.has(item.targetId)) throw new StatusPageError(400, "unknown_target", `${where} points at an integration that doesn't exist.`);
|
||||
if (item.kind === "monitor") {
|
||||
if (integrationRows.get(item.targetId) !== "uptimekuma") throw new StatusPageError(400, "unknown_target", `${where} points at an Uptime Kuma that doesn't exist.`);
|
||||
if (!item.monitorId || item.monitorId.length > 100) throw new StatusPageError(400, "invalid_monitor", `${where} needs one of Uptime Kuma's monitors.`);
|
||||
}
|
||||
}
|
||||
await db.delete(statusItems).where(eq(statusItems.linkId, linkId));
|
||||
if (items.length > 0) {
|
||||
await db.insert(statusItems).values(items.map((item, position) => ({ linkId, position, label: item.label.trim(), kind: item.kind, targetId: item.targetId, monitorId: item.kind === "monitor" ? (item.monitorId ?? null) : null })));
|
||||
}
|
||||
}
|
||||
|
||||
// ─── The picture the public gets ────────────────────────────────────────────
|
||||
|
||||
export interface PublicStatusItem {
|
||||
id: number;
|
||||
label: string;
|
||||
state: ItemState;
|
||||
/** Percent over the last 30 days, where it is known. */
|
||||
uptime30d: number | null;
|
||||
}
|
||||
|
||||
export interface PublicStatus {
|
||||
title: string;
|
||||
message: string | null;
|
||||
level: PageLevel;
|
||||
counts: Record<ItemState, number>;
|
||||
items: PublicStatusItem[];
|
||||
generatedAt: string;
|
||||
display: { dateFormat: string; timeFormat: string };
|
||||
}
|
||||
|
||||
/** How the whole page reads: anything down is an issue; otherwise anything being worked on says so; otherwise fine — unless nothing could be told at all. */
|
||||
export function pageLevel(counts: Record<ItemState, number>): PageLevel {
|
||||
if (counts.down > 0) return "issue";
|
||||
if (counts.maintenance > 0) return "maintenance";
|
||||
if (counts.up === 0 && counts.unknown > 0) return "unknown";
|
||||
return "ok";
|
||||
}
|
||||
|
||||
// Uptime Kuma is asked at most this often per instance, however many people have the page open.
|
||||
const KUMA_CACHE_MS = 30_000;
|
||||
const kumaCache = new Map<number, { at: number; monitors: Map<string, UptimeKumaMonitor> | null }>();
|
||||
let kumaLoader: ((integrationId: number) => Promise<UptimeKumaMonitor[] | null>) | null = null;
|
||||
|
||||
/** For tests: read monitors from this instead of a real Uptime Kuma. */
|
||||
export function setKumaLoaderForTests(loader: typeof kumaLoader): void {
|
||||
kumaLoader = loader;
|
||||
kumaCache.clear();
|
||||
}
|
||||
|
||||
async function monitorsOf(integrationId: number, now: number): Promise<Map<string, UptimeKumaMonitor> | null> {
|
||||
const cached = kumaCache.get(integrationId);
|
||||
if (cached && now - cached.at < KUMA_CACHE_MS) return cached.monitors;
|
||||
let monitors: Map<string, UptimeKumaMonitor> | null = null;
|
||||
try {
|
||||
let list: UptimeKumaMonitor[] | null;
|
||||
if (kumaLoader) list = await kumaLoader(integrationId);
|
||||
else {
|
||||
const loaded = await loadIntegrationConfig(integrationId);
|
||||
list = loaded && loaded.integration.type === "uptimekuma" && loaded.integration.enabled ? await createUptimeKumaAdapter(loaded.config as never).listMonitors() : null;
|
||||
}
|
||||
monitors = list ? new Map(list.map((m) => [m.id, m])) : null;
|
||||
} catch {
|
||||
monitors = null; // can't be told, so it says so — never "up"
|
||||
}
|
||||
kumaCache.set(integrationId, { at: now, monitors });
|
||||
return monitors;
|
||||
}
|
||||
|
||||
export async function buildPublicStatus(link: { id: number; label: string; title: string | null; message: string | null }, now: Date = new Date()): Promise<PublicStatus> {
|
||||
const items = await db.select().from(statusItems).where(eq(statusItems.linkId, link.id)).orderBy(asc(statusItems.position), asc(statusItems.id));
|
||||
const settings = await getSettings();
|
||||
const subjects = await activeSubjects(now);
|
||||
const serverRows = new Map((await db.select().from(servers)).map((s) => [s.id, s]));
|
||||
const integrationRows = new Map((await db.select({ id: integrations.id, type: integrations.type, enabled: integrations.enabled }).from(integrations)).map((i) => [i.id, i]));
|
||||
const uptime = items.some((i) => i.kind !== "monitor") ? await getUptime(now, 30).catch(() => null) : null;
|
||||
|
||||
const out: PublicStatusItem[] = [];
|
||||
for (const item of items) {
|
||||
let state: ItemState = "unknown";
|
||||
let uptime30d: number | null = null;
|
||||
|
||||
if (item.kind === "server") {
|
||||
const s = serverRows.get(item.targetId);
|
||||
if (s?.lastSeenAt) {
|
||||
const limit = effectiveThresholds({ ...settings.healthChecks }, parseThresholds(s.thresholds)).serverOfflineMinutes * 60_000;
|
||||
const quiet = now.getTime() - Date.parse(s.lastSeenAt) > limit;
|
||||
state = subjects.has(`server:${s.id}`) ? "maintenance" : quiet ? "down" : "up";
|
||||
}
|
||||
uptime30d = uptime?.servers[item.targetId]?.percent ?? null;
|
||||
} else if (item.kind === "integration") {
|
||||
const i = integrationRows.get(item.targetId);
|
||||
if (i?.enabled) {
|
||||
const status = getSourceStatus(i.type).status;
|
||||
state = subjects.has(`integration:${i.id}`) ? "maintenance" : status === "ok" ? "up" : status === "failing" ? "down" : "unknown";
|
||||
}
|
||||
uptime30d = uptime?.integrations[item.targetId]?.percent ?? null;
|
||||
} else {
|
||||
const monitor = item.monitorId ? (await monitorsOf(item.targetId, now.getTime()))?.get(item.monitorId) : undefined;
|
||||
if (monitor) {
|
||||
state = monitor.status === "up" ? "up" : monitor.status === "down" ? "down" : monitor.status === "maintenance" ? "maintenance" : "unknown";
|
||||
uptime30d = monitor.uptime30d;
|
||||
}
|
||||
}
|
||||
out.push({ id: item.id, label: item.label, state, uptime30d: uptime30d === null ? null : Math.round(uptime30d * 10) / 10 });
|
||||
}
|
||||
|
||||
const counts: Record<ItemState, number> = { up: 0, down: 0, maintenance: 0, unknown: 0 };
|
||||
for (const o of out) counts[o.state]++;
|
||||
return {
|
||||
title: link.title?.trim() || link.label,
|
||||
message: link.message?.trim() || null,
|
||||
level: pageLevel(counts),
|
||||
counts,
|
||||
items: out,
|
||||
generatedAt: now.toISOString(),
|
||||
display: { dateFormat: settings.display.dateFormat, timeFormat: settings.display.timeFormat },
|
||||
};
|
||||
}
|
||||
|
||||
/** What an administrator can choose from, for the editor: servers and integrations (monitors are read from each Uptime Kuma on request). */
|
||||
export async function statusChoices(): Promise<{ servers: { id: number; name: string }[]; integrations: { id: number; name: string; type: string }[] }> {
|
||||
const s = await db.select({ id: servers.id, name: servers.name }).from(servers).orderBy(asc(servers.name));
|
||||
const i = await db.select({ id: integrations.id, name: integrations.name, type: integrations.type }).from(integrations).where(and(eq(integrations.enabled, true))).orderBy(asc(integrations.name));
|
||||
return { servers: s, integrations: i };
|
||||
}
|
||||
Reference in new issue
Block a user