A year of history, one chart, and a read API with personal tokens
History: server load, memory and disks are also kept as hourly (four months) and daily (over two years) averages with lowest and highest; endpoint answers as hourly (four months) beside the daily figures. Charts ask for 24 hours to a year and are drawn from whichever is fine enough. A disk that two weeks call flat is looked at again over ninety days for the forecast. Built once from what is kept. One chart: TimeChart replaces the sparkline and the multi-line chart: hover and arrow-key readout, a lowest/highest band, gaps shown as gaps, the same ranges everywhere and the choice remembered. Used for server trends, comparing servers, a check's availability and answer times (Endpoints > History) and a server's availability. Read API: /api/v1 (servers, metrics, alerts, incidents, inventory, network, endpoints and their history, maintenance) with personal read-only tokens made under the user menu: shown once, hashed, 30/90/365 days or none, ten at most, removed with their owner. GET only. Documented in API.md. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5e26e77340
commit
68b41b5586
47 files changed
+12360
-247
No files matched your search
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* What the read API (/api/v1) says. Each of these is a deliberate, stable shape — not the app's own page payloads, which change with the pages — and only things
|
||||
* any signed-in person can already see: no tokens, no secrets, no passwords, no settings. Dates are ISO 8601 in UTC; sizes are bytes; percentages are 0–100.
|
||||
*/
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { assets, endpointChecks, servers } from "../db/schema.js";
|
||||
import { env } from "../env.js";
|
||||
import { attentionCounts, loadAcks } from "./alertAcks.js";
|
||||
import { getAlerts } from "./alerts.js";
|
||||
import { loadStats } from "./endpointChecks.js";
|
||||
import { describeTarget, listActiveWindows, listUpcomingWindows } from "./maintenance.js";
|
||||
import { parseHostHealth } from "./hostHealth.js";
|
||||
import { parsePendingUpdates } from "./pendingUpdates.js";
|
||||
import { parseTags } from "./serverTags.js";
|
||||
import { parseThresholds } from "./serverThresholds.js";
|
||||
import { getSettings } from "./settingsStore.js";
|
||||
import { serverStatus } from "./topology.js";
|
||||
|
||||
/** An address inside the app as a full address, for a script that has no idea where the app lives. */
|
||||
export function absoluteUrl(path: string | null): string | null {
|
||||
return path === null ? null : `${env.appBaseUrl.replace(/\/+$/, "")}${path.startsWith("/") ? "" : "/"}${path}`;
|
||||
}
|
||||
|
||||
const json = <T>(text: string | null, fallback: T): T => {
|
||||
if (!text) return fallback;
|
||||
try {
|
||||
return JSON.parse(text) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
type ServerRow = typeof servers.$inferSelect;
|
||||
|
||||
export function serverV1(row: ServerRow, offlineMinutes: number, now: Date) {
|
||||
const status = serverStatus(row, offlineMinutes, now);
|
||||
const disks = json<{ mount: string; sizeBytes: number; usedBytes: number }[]>(row.disks, []);
|
||||
const updates = parsePendingUpdates(row.pendingUpdates);
|
||||
const health = parseHostHealth(row.hostHealth);
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
hostname: row.hostname,
|
||||
description: row.description,
|
||||
os: row.osType,
|
||||
tags: parseTags(row.tags),
|
||||
ipAddresses: json<string[]>(row.ipAddresses, []),
|
||||
// "online" while its agent has reported within its limit, "offline" after, "unknown" if it never has.
|
||||
status: status === "ok" ? "online" : status === "bad" ? "offline" : "unknown",
|
||||
lastSeenAt: row.lastSeenAt,
|
||||
createdAt: row.createdAt,
|
||||
agentVersion: row.agentVersion ?? null,
|
||||
runsOnServerId: row.parentServerId ?? null,
|
||||
hardware: { manufacturer: row.hwManufacturer ?? null, model: row.hwModel ?? null, serial: row.hwSerial ?? null },
|
||||
cpu: { model: row.cpuModel, cores: row.cpuCores, loadPercent: row.cpuLoadPercent },
|
||||
memory: { totalBytes: row.memTotalBytes, usedBytes: row.memUsedBytes },
|
||||
disks: disks.map((d) => ({ mount: d.mount, sizeBytes: d.sizeBytes, usedBytes: d.usedBytes, usedPercent: d.sizeBytes > 0 ? Math.round((d.usedBytes / d.sizeBytes) * 1000) / 10 : null })),
|
||||
updates: updates ? { manager: updates.manager, count: updates.count, security: updates.security ?? null, rebootRequired: !!updates.rebootRequired, reportedAt: updates.reportedAt ?? null } : null,
|
||||
health: health ? { failedUnits: health.failedUnits?.length ?? 0, reportedAt: health.reportedAt ?? null } : null,
|
||||
thresholds: parseThresholds(row.thresholds),
|
||||
url: absoluteUrl(`/servers/${row.id}`),
|
||||
};
|
||||
}
|
||||
|
||||
export async function serversV1(now: Date = new Date()) {
|
||||
const [rows, settings] = await Promise.all([db.select().from(servers).orderBy(servers.name), getSettings()]);
|
||||
return rows.map((r) => serverV1(r, settings.healthChecks.serverOfflineMinutes, now));
|
||||
}
|
||||
|
||||
export async function oneServerV1(id: number, now: Date = new Date()) {
|
||||
const [row] = await db.select().from(servers).where(eq(servers.id, id)).limit(1);
|
||||
if (!row) return null;
|
||||
return serverV1(row, (await getSettings()).healthChecks.serverOfflineMinutes, now);
|
||||
}
|
||||
|
||||
export async function alertsV1() {
|
||||
const [report, acks] = await Promise.all([getAlerts(false), loadAcks()]);
|
||||
const attention = attentionCounts(report.alerts, acks);
|
||||
return {
|
||||
generatedAt: report.generatedAt,
|
||||
// What is on the page: those nobody has looked at, by severity, and how many somebody has.
|
||||
needingAttention: { critical: attention.critical, warning: attention.warning, acknowledged: attention.acknowledged },
|
||||
counts: report.counts,
|
||||
couldntCheck: report.couldntCheck,
|
||||
alerts: report.alerts.map((a) => {
|
||||
const ack = acks.get(a.id);
|
||||
return {
|
||||
id: a.id,
|
||||
severity: a.severity,
|
||||
category: a.category,
|
||||
source: a.source,
|
||||
message: a.message,
|
||||
url: absoluteUrl(a.link),
|
||||
silenced: a.silenced,
|
||||
flapping: !!a.flapping,
|
||||
target: a.target,
|
||||
causedBy: a.causedBy ?? null,
|
||||
affects: a.affects ?? [],
|
||||
acknowledgement: ack?.active ? { by: ack.ackedBy, at: ack.ackedAt, note: ack.note, until: ack.until, assignee: ack.assignee?.name ?? null } : null,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function inventoryV1() {
|
||||
const [rows, serverRows] = await Promise.all([db.select().from(assets).orderBy(assets.name), db.select({ id: servers.id, name: servers.name }).from(servers)]);
|
||||
const serverName = new Map(serverRows.map((s) => [s.id, s.name]));
|
||||
return rows.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
kind: a.kind,
|
||||
manufacturer: a.manufacturer,
|
||||
model: a.model,
|
||||
serial: a.serial,
|
||||
location: a.location,
|
||||
rackUnit: a.rackUnit,
|
||||
purchaseDate: a.purchaseDate,
|
||||
purchasePrice: a.purchasePrice,
|
||||
warrantyUntil: a.warrantyUntil,
|
||||
endOfSupport: a.endOfSupport,
|
||||
replacementCost: a.replacementCost,
|
||||
powerWatts: a.powerWatts,
|
||||
notes: a.notes,
|
||||
server: a.serverId !== null && serverName.has(a.serverId) ? { id: a.serverId, name: serverName.get(a.serverId)! } : null,
|
||||
updatedAt: a.updatedAt,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function maintenanceV1(now: Date = new Date()) {
|
||||
const shape = async (w: Awaited<ReturnType<typeof listActiveWindows>>[number]) => {
|
||||
const target = await describeTarget(w.targetType, w.targetId);
|
||||
return target ? { id: w.id, target: { type: w.targetType, id: w.targetId, name: target.name, kind: target.kind }, reason: w.reason, startsAt: w.startedAt, endsAt: w.endsAt, createdBy: w.createdBy } : null;
|
||||
};
|
||||
const active = (await Promise.all((await listActiveWindows(now)).map(shape))).filter((w): w is NonNullable<typeof w> => w !== null);
|
||||
const upcoming = (await Promise.all((await listUpcomingWindows(now)).map(shape))).filter((w): w is NonNullable<typeof w> => w !== null);
|
||||
return { active, upcoming };
|
||||
}
|
||||
|
||||
export async function endpointsV1(now: Date = new Date()) {
|
||||
const rows = await db.select().from(endpointChecks).orderBy(endpointChecks.name);
|
||||
const stats = await loadStats(rows.map((r) => r.id), now);
|
||||
return rows.map((r) => {
|
||||
const st = stats.get(r.id);
|
||||
return {
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
kind: r.kind,
|
||||
target: r.target,
|
||||
port: r.port,
|
||||
enabled: r.enabled,
|
||||
status: !r.enabled ? "paused" : r.lastOk === null ? "unknown" : r.lastOk ? "up" : "down",
|
||||
lastCheckedAt: r.lastCheckedAt,
|
||||
lastResponseMs: r.lastResponseMs,
|
||||
lastMessage: r.lastOk === false ? r.lastMessage : null,
|
||||
certificateExpiresAt: r.certExpiresAt,
|
||||
uptime24hPercent: st?.uptime24h ?? null,
|
||||
uptime7dPercent: st?.uptime7d ?? null,
|
||||
averageResponseMs24h: st?.avgMs24h ?? null,
|
||||
serverId: r.serverId,
|
||||
};
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user