Add a since-you-last-looked summary, 30-day uptime ribbons, a maintenance timeline and hover timestamps
- Dashboard card on what changed since the user pressed Got it (users.last_looked_at, migration 0021), folding each problem and its recovery into one line. - Uptime ribbons on servers and integrations, built from the audit log; integrations' failing/working-again moments are now recorded. - Timeline of running and scheduled maintenance windows on the Maintenance page. - TimeAgo component: relative times with the exact time in the chosen format on hover. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3945c60681
commit
906220040e
32 files changed
+3380
-15
No files matched your search
+3
-1
@@ -87,6 +87,7 @@ Everyone who has signed in through Authentik. The first one becomes admin.
|
|||||||
| `created_at` | text NOT NULL | SQLite UTC. |
|
| `created_at` | text NOT NULL | SQLite UTC. |
|
||||||
| `last_login_at` | text | ISO. |
|
| `last_login_at` | text | ISO. |
|
||||||
| `favorites` | text | JSON array of the page paths this person pinned to the top of their menu (`["/servers","/alerts"]`), up to 24. Follows them to any browser. |
|
| `favorites` | text | JSON array of the page paths this person pinned to the top of their menu (`["/servers","/alerts"]`), up to 24. Follows them to any browser. |
|
||||||
|
| `last_looked_at` | text | ISO time this person last pressed "Got it" on the dashboard's "Since you last looked" card; the next summary starts there (null = never: the last day is shown). |
|
||||||
|
|
||||||
#### `audit_log`
|
#### `audit_log`
|
||||||
|
|
||||||
@@ -98,7 +99,7 @@ Who changed what. Written by the app on every change (see
|
|||||||
| `id` | integer PK | |
|
| `id` | integer PK | |
|
||||||
| `actor_user_id` | integer → `users.id`, **set null** on delete | Null for automatic actions, and for entries whose user was deleted. |
|
| `actor_user_id` | integer → `users.id`, **set null** on delete | Null for automatic actions, and for entries whose user was deleted. |
|
||||||
| `actor_label` | text | The user's name/email as it was at the time (or `system`), so an entry still reads correctly after the account is gone. |
|
| `actor_label` | text | The user's name/email as it was at the time (or `system`), so an entry still reads correctly after the account is gone. |
|
||||||
| `category` | text NOT NULL | Free text. In use: `server` (including the health check's own `went_offline`, `back_online`, `disk_full` and `disk_ok`, written as `system` and shown on a server's Activity card), `integration`, `dns`, `settings`, `ipam`, `secret`, `domain`, `tag`, `task`, `session`, `network`, `maintenance`, `consistency`, `user`, `privacy`, `diag_log`, `alert_ticket`. |
|
| `category` | text NOT NULL | Free text. In use: `server` (including the health check's own `went_offline`, `back_online`, `disk_full` and `disk_ok`, written as `system` and shown on a server's Activity card), `integration` (including the health check's `went_failing` / `recovered` for a kind of service, with `target_type` `integration_type` and the service type as `target_id`, which the dashboard summary and the uptime ribbons read), `dns`, `settings`, `ipam`, `secret`, `domain`, `tag`, `task`, `session`, `network`, `maintenance`, `consistency`, `user`, `privacy`, `diag_log`, `alert_ticket`. |
|
||||||
| `action` | text NOT NULL | `create`, `update`, `delete`, `start`, `stop`, … — free text. |
|
| `action` | text NOT NULL | `create`, `update`, `delete`, `start`, `stop`, … — free text. |
|
||||||
| `target_type`, `target_id` | text | What it happened to. `target_id` is text so it can hold any kind of ID; there's no foreign key. |
|
| `target_type`, `target_id` | text | What it happened to. `target_id` is text so it can hold any kind of ID; there's no foreign key. |
|
||||||
| `detail` | text | JSON, free-form context (what changed, names, counts). Secrets are never put here. |
|
| `detail` | text | JSON, free-form context (what changed, names, counts). Secrets are never put here. |
|
||||||
@@ -511,6 +512,7 @@ settings, and aren't part of the app's settings object:
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `_internal:secretCheckLastRunDate`, `tailscaleKeyCheckLastRunDate`, `dockerUpdateCheckLastRunDate`, `proxmoxBackupCheckLastRunDate`, `pbsVerificationCheckLastRunDate` | The date a daily check last ran, so a restart doesn't repeat it (or skip it). |
|
| `_internal:secretCheckLastRunDate`, `tailscaleKeyCheckLastRunDate`, `dockerUpdateCheckLastRunDate`, `proxmoxBackupCheckLastRunDate`, `pbsVerificationCheckLastRunDate` | The date a daily check last ran, so a restart doesn't repeat it (or skip it). |
|
||||||
| `_internal:logRetentionLastRunAt` | When the log purge last ran. |
|
| `_internal:logRetentionLastRunAt` | When the log purge last ran. |
|
||||||
|
| `_internal:integration_history_since` | When the app first began writing integrations' failing / working-again moments; the uptime ribbons claim nothing earlier for integrations. |
|
||||||
| `_internal:alertTicketsBaselineDone`, `_internal:alertTicketsLastRun` | Whether the alert-ticket starting line has been recorded since the feature was switched on, and JSON for the last check's result. |
|
| `_internal:alertTicketsBaselineDone`, `_internal:alertTicketsLastRun` | Whether the alert-ticket starting line has been recorded since the feature was switched on, and JSON for the last check's result. |
|
||||||
| `_internal:healthActiveConditions`, `_internal:automationActiveConditions` | JSON: the problems currently active, so each is announced once and again when it clears, and survives a restart. |
|
| `_internal:healthActiveConditions`, `_internal:automationActiveConditions` | JSON: the problems currently active, so each is announced once and again when it clears, and survives a restart. |
|
||||||
|
|
||||||
|
|||||||
@@ -395,6 +395,36 @@ the problems themselves, and each integration's status, refreshing every 30
|
|||||||
seconds with the screen kept awake where the browser allows. Esc returns to the
|
seconds with the screen kept awake where the browser allows. Esc returns to the
|
||||||
app.
|
app.
|
||||||
|
|
||||||
|
**Since you last looked.** The dashboard opens with a card on what happened
|
||||||
|
since you last pressed "Got it" (the first time, the last day; never more than
|
||||||
|
two weeks): servers that stopped reporting or filled a disk, services that
|
||||||
|
stopped answering, and maintenance that began or ended — each problem and its
|
||||||
|
recovery folded into one line ("elsa was offline for 12 min — reporting again";
|
||||||
|
a problem that hasn't ended says "still offline"). Operators and admins also see
|
||||||
|
how many changes other people made, with a link to the audit log. Nothing to say
|
||||||
|
means no card. The mark is stored on your user, so it follows you to any browser.
|
||||||
|
|
||||||
|
**Uptime ribbons.** Servers (list, cards and the server's page) and integration
|
||||||
|
cards show a strip of one bar per day for the last 30 days — green for a day with
|
||||||
|
nothing wrong, amber for some time down, red for half a day or more, grey where
|
||||||
|
nothing is known — and the share of time up. It is worked out from the moments
|
||||||
|
the health checks write in the audit log (a server stopped reporting / reported
|
||||||
|
again; an integration's calls started failing — the same threshold as the failure
|
||||||
|
alert — / worked again), so it can only be as old as those records: servers go
|
||||||
|
back to when they were added, integrations to the first time this version ran.
|
||||||
|
Integrations are tracked per kind of service, as the health checks are.
|
||||||
|
|
||||||
|
**Maintenance timeline.** The Maintenance page draws the running and scheduled
|
||||||
|
windows along a time axis (the next 24 hours, 7 days or 30 days), one row per
|
||||||
|
server, integration or DNS provider and a top row for "anything in
|
||||||
|
maintenance", so overlaps and gaps are visible. Windows mirrored from Uptime
|
||||||
|
Kuma are striped. The tables below still list the same windows.
|
||||||
|
|
||||||
|
**Times as people say them.** "Last seen", sync times, session activity and
|
||||||
|
similar columns read "5 min ago" and show the exact date and time, in the format
|
||||||
|
chosen under Settings → Display, on hover. Exports and the audit log keep exact
|
||||||
|
times.
|
||||||
|
|
||||||
**Activity.** Operators and admins see an Activity card on each server's page:
|
**Activity.** Operators and admins see an Activity card on each server's page:
|
||||||
what changed on it and who changed it, the moments the health check saw it stop
|
what changed on it and who changed it, the moments the health check saw it stop
|
||||||
reporting (and report again) or a disk fill (and recover) — now written to the
|
reporting (and report again) or a disk fill (and recover) — now written to the
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE `users` ADD `last_looked_at` text;
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -148,6 +148,13 @@
|
|||||||
"when": 1792093015342,
|
"when": 1792093015342,
|
||||||
"tag": "0020_salty_black_tom",
|
"tag": "0020_salty_black_tom",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 21,
|
||||||
|
"version": "6",
|
||||||
|
"when": 1792177953255,
|
||||||
|
"tag": "0021_conscious_snowbird",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -8,6 +8,7 @@ import { env } from "./env.js";
|
|||||||
import { resolveDataPath } from "./paths.js";
|
import { resolveDataPath } from "./paths.js";
|
||||||
import { authRouter } from "./auth/router.js";
|
import { authRouter } from "./auth/router.js";
|
||||||
import { meRouter } from "./routes/me.js";
|
import { meRouter } from "./routes/me.js";
|
||||||
|
import { uptimeRouter } from "./routes/uptime.js";
|
||||||
import { usersRouter } from "./routes/users.js";
|
import { usersRouter } from "./routes/users.js";
|
||||||
import { auditLogRouter } from "./routes/auditLog.js";
|
import { auditLogRouter } from "./routes/auditLog.js";
|
||||||
import { diagLogRouter } from "./routes/diagLog.js";
|
import { diagLogRouter } from "./routes/diagLog.js";
|
||||||
@@ -87,6 +88,7 @@ export function createApp() {
|
|||||||
|
|
||||||
app.use("/auth", authRouter);
|
app.use("/auth", authRouter);
|
||||||
app.use("/api/me", meRouter);
|
app.use("/api/me", meRouter);
|
||||||
|
app.use("/api/uptime", uptimeRouter);
|
||||||
app.use("/api/users", usersRouter);
|
app.use("/api/users", usersRouter);
|
||||||
app.use("/api/audit-log", auditLogRouter);
|
app.use("/api/audit-log", auditLogRouter);
|
||||||
app.use("/api/diag-log", diagLogRouter);
|
app.use("/api/diag-log", diagLogRouter);
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ export const users = sqliteTable("users", {
|
|||||||
lastLoginAt: text("last_login_at"),
|
lastLoginAt: text("last_login_at"),
|
||||||
// The pages this person pinned to the top of their menu, as a JSON array of paths ("/servers", "/alerts"). It follows them to any browser.
|
// The pages this person pinned to the top of their menu, as a JSON array of paths ("/servers", "/alerts"). It follows them to any browser.
|
||||||
favorites: text("favorites"),
|
favorites: text("favorites"),
|
||||||
|
// When this person last pressed "Got it" on the dashboard summary of what changed; the next summary starts from here (ISO).
|
||||||
|
lastLookedAt: text("last_looked_at"),
|
||||||
});
|
});
|
||||||
|
|
||||||
// ─── Audit log ──────────────────────────────────────────────────────────────
|
// ─── Audit log ──────────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { db } from "../db/client.js";
|
|||||||
import { users } from "../db/schema.js";
|
import { users } from "../db/schema.js";
|
||||||
import { requireAuth } from "../auth/middleware.js";
|
import { requireAuth } from "../auth/middleware.js";
|
||||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||||
|
import { FIRST_LOOKBACK_MS, getChangesSince } from "../services/changesSince.js";
|
||||||
|
|
||||||
export const meRouter = Router();
|
export const meRouter = Router();
|
||||||
|
|
||||||
@@ -43,3 +44,28 @@ meRouter.put("/favorites", requireAuth, asyncHandler(async (req, res) => {
|
|||||||
await db.update(users).set({ favorites: JSON.stringify(paths) }).where(eq(users.id, req.currentUser!.id));
|
await db.update(users).set({ favorites: JSON.stringify(paths) }).where(eq(users.id, req.currentUser!.id));
|
||||||
res.json({ favorites: paths });
|
res.json({ favorites: paths });
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const CHANGES_SHOWN = 8;
|
||||||
|
|
||||||
|
// What happened since this person last pressed "Got it" on the dashboard (or in the last day, the first time). Only reads.
|
||||||
|
meRouter.get("/changes", requireAuth, asyncHandler(async (req, res) => {
|
||||||
|
const user = req.currentUser!;
|
||||||
|
const now = new Date();
|
||||||
|
const stored = user.lastLookedAt ? Date.parse(user.lastLookedAt) : NaN;
|
||||||
|
const since = new Date(Number.isFinite(stored) ? stored : now.getTime() - FIRST_LOOKBACK_MS);
|
||||||
|
const report = await getChangesSince({ since, now, actorId: user.id, canSeeAudit: user.role === "admin" || user.role === "operator" });
|
||||||
|
res.json({
|
||||||
|
since: report.since,
|
||||||
|
firstTime: !Number.isFinite(stored),
|
||||||
|
events: report.events.slice(0, CHANGES_SHOWN),
|
||||||
|
moreEvents: Math.max(0, report.events.length - CHANGES_SHOWN),
|
||||||
|
changesByOthers: report.changesByOthers,
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
|
||||||
|
// "Got it": the next summary starts from now. Only ever for the signed-in person.
|
||||||
|
meRouter.post("/changes/seen", requireAuth, asyncHandler(async (req, res) => {
|
||||||
|
const at = new Date().toISOString();
|
||||||
|
await db.update(users).set({ lastLookedAt: at }).where(eq(users.id, req.currentUser!.id));
|
||||||
|
res.json({ lastLookedAt: at });
|
||||||
|
}));
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { Router } from "express";
|
||||||
|
import { requireAuth } from "../auth/middleware.js";
|
||||||
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||||
|
import { getUptime } from "../services/uptimeHistory.js";
|
||||||
|
|
||||||
|
export const uptimeRouter = Router();
|
||||||
|
|
||||||
|
// Anyone signed in who can see the server and integration lists can see how those have been doing.
|
||||||
|
uptimeRouter.get("/", requireAuth, asyncHandler(async (_req, res) => {
|
||||||
|
res.json(await getUptime());
|
||||||
|
}));
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
/**
|
||||||
|
* "Since you last looked": what happened to the homelab between one visit and the next, in the order a person would tell it —
|
||||||
|
* servers that stopped reporting or filled a disk, services that stopped answering, maintenance that began or ended — with each
|
||||||
|
* problem and its recovery folded into one line ("elsa was offline for 12 min"). Worked out from the audit log and the maintenance
|
||||||
|
* windows, so nothing is stored but the moment the person last pressed "Got it".
|
||||||
|
*/
|
||||||
|
import { and, gte } from "drizzle-orm";
|
||||||
|
import { db } from "../db/client.js";
|
||||||
|
import { auditLog, integrations, maintenanceWindows, servers } from "../db/schema.js";
|
||||||
|
import { auditTimeToIso } from "./serverActivity.js";
|
||||||
|
import { describeTarget } from "./maintenance.js";
|
||||||
|
|
||||||
|
export type ChangeTone = "good" | "bad" | "info" | "neutral";
|
||||||
|
|
||||||
|
export interface ChangeEvent {
|
||||||
|
/** ISO — when it began (or, for something already under way before, when it ended). */
|
||||||
|
at: string;
|
||||||
|
tone: ChangeTone;
|
||||||
|
kind: "server" | "integration" | "maintenance";
|
||||||
|
title: string;
|
||||||
|
detail: string | null;
|
||||||
|
/** A page in the app to look at it, or null. */
|
||||||
|
link: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChangesReport {
|
||||||
|
/** ISO — where this summary starts. */
|
||||||
|
since: string;
|
||||||
|
/** Everything worth a line, newest first, before it is cut down for display. */
|
||||||
|
events: ChangeEvent[];
|
||||||
|
/** How many entries other people (not the app itself, not the asker) wrote in the audit log in that time; null when the asker can't see the audit log. */
|
||||||
|
changesByOthers: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How far back a summary reaches at most, however long since the last visit. */
|
||||||
|
export const MAX_LOOKBACK_MS = 14 * 24 * 3600_000;
|
||||||
|
/** Where a first-ever summary starts. */
|
||||||
|
export const FIRST_LOOKBACK_MS = 24 * 3600_000;
|
||||||
|
|
||||||
|
const SERVER_PROBLEM = { went_offline: "offline", disk_full: "disk" } as const;
|
||||||
|
const SERVER_RECOVERY = { back_online: "offline", disk_ok: "disk" } as const;
|
||||||
|
|
||||||
|
function span(ms: number): string {
|
||||||
|
const minutes = Math.max(1, Math.round(ms / 60_000));
|
||||||
|
if (minutes < 60) return `${minutes} min`;
|
||||||
|
const hours = Math.floor(minutes / 60);
|
||||||
|
if (hours < 24) return minutes % 60 && hours < 10 ? `${hours} h ${minutes % 60} min` : `${hours} h`;
|
||||||
|
const days = Math.floor(hours / 24);
|
||||||
|
return hours % 24 ? `${days} d ${hours % 24} h` : `${days} d`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseDetail(detail: string | null): Record<string, unknown> {
|
||||||
|
if (!detail) return {};
|
||||||
|
try {
|
||||||
|
const v = JSON.parse(detail);
|
||||||
|
return v && typeof v === "object" ? (v as Record<string, unknown>) : {};
|
||||||
|
} catch {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Mark {
|
||||||
|
at: number;
|
||||||
|
problem: boolean;
|
||||||
|
message: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Folds an ordered run of problem / recovery marks into the story: each pair is one finished episode, a lone recovery began before, a lone problem is still going. */
|
||||||
|
export function foldMarks(marks: Mark[]): { start: number | null; end: number | null; message: string | null }[] {
|
||||||
|
const out: { start: number | null; end: number | null; message: string | null }[] = [];
|
||||||
|
let open: Mark | null = null;
|
||||||
|
for (const m of [...marks].sort((a, b) => a.at - b.at)) {
|
||||||
|
if (m.problem) {
|
||||||
|
if (!open) open = m; // a second "problem" while one is open (a restart repeating itself) adds nothing
|
||||||
|
} else if (open) {
|
||||||
|
out.push({ start: open.at, end: m.at, message: open.message });
|
||||||
|
open = null;
|
||||||
|
} else {
|
||||||
|
out.push({ start: null, end: m.at, message: null });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (open) out.push({ start: open.at, end: null, message: open.message });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getChangesSince(params: { since: Date; now?: Date; actorId: number; canSeeAudit: boolean }): Promise<ChangesReport> {
|
||||||
|
const now = params.now ?? new Date();
|
||||||
|
const sinceMs = Math.max(params.since.getTime(), now.getTime() - MAX_LOOKBACK_MS);
|
||||||
|
const nowMs = now.getTime();
|
||||||
|
// The audit log stores "2026-10-03 14:05:09"; compare in that form, then filter exactly in JS.
|
||||||
|
const sinceDb = new Date(sinceMs - 1000).toISOString().slice(0, 19).replace("T", " ");
|
||||||
|
|
||||||
|
const audits = (await db.select().from(auditLog).where(gte(auditLog.createdAt, sinceDb))).map((a) => ({ ...a, atMs: Date.parse(auditTimeToIso(a.createdAt)) })).filter((a) => a.atMs <= nowMs);
|
||||||
|
const events: ChangeEvent[] = [];
|
||||||
|
|
||||||
|
// ── Servers: stopped reporting / disk full, and the ends of those ──
|
||||||
|
const serverMarks = new Map<string, { id: number; kind: "offline" | "disk"; marks: Mark[] }>();
|
||||||
|
for (const a of audits) {
|
||||||
|
if (a.category !== "server" || a.targetType !== "server" || a.atMs < sinceMs) continue;
|
||||||
|
const problem = SERVER_PROBLEM[a.action as keyof typeof SERVER_PROBLEM];
|
||||||
|
const recovery = SERVER_RECOVERY[a.action as keyof typeof SERVER_RECOVERY];
|
||||||
|
const kind = problem ?? recovery;
|
||||||
|
if (!kind) continue;
|
||||||
|
const mount = typeof parseDetail(a.detail).mount === "string" ? (parseDetail(a.detail).mount as string) : "";
|
||||||
|
const key = `${a.targetId}:${kind}:${mount}`;
|
||||||
|
const entry = serverMarks.get(key) ?? { id: Number(a.targetId), kind, marks: [] };
|
||||||
|
const message = typeof parseDetail(a.detail).message === "string" ? (parseDetail(a.detail).message as string) : null;
|
||||||
|
entry.marks.push({ at: a.atMs, problem: Boolean(problem), message });
|
||||||
|
serverMarks.set(key, entry);
|
||||||
|
}
|
||||||
|
const serverNames = new Map((await db.select({ id: servers.id, name: servers.name }).from(servers)).map((s) => [s.id, s.name]));
|
||||||
|
for (const { id, kind, marks } of serverMarks.values()) {
|
||||||
|
const name = serverNames.get(id);
|
||||||
|
if (!name) continue; // since removed
|
||||||
|
const link = `/servers/${id}`;
|
||||||
|
for (const ep of foldMarks(marks)) {
|
||||||
|
const noun = kind === "offline" ? "offline" : "had a nearly full disk";
|
||||||
|
if (ep.start !== null && ep.end !== null) {
|
||||||
|
events.push({ at: new Date(ep.start).toISOString(), tone: "good", kind: "server", link, detail: ep.message, title: kind === "offline" ? `${name} was offline for ${span(ep.end - ep.start)} — reporting again` : `${name} had a nearly full disk for ${span(ep.end - ep.start)} — fine again` });
|
||||||
|
} else if (ep.start !== null) {
|
||||||
|
events.push({ at: new Date(ep.start).toISOString(), tone: "bad", kind: "server", link, detail: ep.message, title: kind === "offline" ? `${name} went offline ${span(nowMs - ep.start)} ago — still offline` : `${name} ${noun} — still` });
|
||||||
|
} else if (ep.end !== null) {
|
||||||
|
events.push({ at: new Date(ep.end).toISOString(), tone: "good", kind: "server", link, detail: null, title: kind === "offline" ? `${name} is reporting again` : `${name}'s disk is no longer nearly full` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Integrations: started failing / working again (kept per kind of service, as the health checks are) ──
|
||||||
|
const sourceMarks = new Map<string, Mark[]>();
|
||||||
|
for (const a of audits) {
|
||||||
|
if (a.category !== "integration" || a.targetType !== "integration_type" || !a.targetId || a.atMs < sinceMs) continue;
|
||||||
|
if (a.action !== "went_failing" && a.action !== "recovered") continue;
|
||||||
|
const list = sourceMarks.get(a.targetId) ?? [];
|
||||||
|
list.push({ at: a.atMs, problem: a.action === "went_failing", message: null });
|
||||||
|
sourceMarks.set(a.targetId, list);
|
||||||
|
}
|
||||||
|
if (sourceMarks.size > 0) {
|
||||||
|
const names = new Map<string, string[]>();
|
||||||
|
for (const i of await db.select({ name: integrations.name, type: integrations.type }).from(integrations)) names.set(i.type, [...(names.get(i.type) ?? []), i.name]);
|
||||||
|
for (const [source, marks] of sourceMarks) {
|
||||||
|
const label = names.get(source)?.join(" / ");
|
||||||
|
if (!label) continue;
|
||||||
|
for (const ep of foldMarks(marks)) {
|
||||||
|
if (ep.start !== null && ep.end !== null) {
|
||||||
|
events.push({ at: new Date(ep.start).toISOString(), tone: "good", kind: "integration", link: "/integrations", detail: null, title: `${label} stopped answering for ${span(ep.end - ep.start)} — working again` });
|
||||||
|
} else if (ep.start !== null) {
|
||||||
|
events.push({ at: new Date(ep.start).toISOString(), tone: "bad", kind: "integration", link: "/integrations", detail: null, title: `${label} stopped answering ${span(nowMs - ep.start)} ago — still failing` });
|
||||||
|
} else if (ep.end !== null) {
|
||||||
|
events.push({ at: new Date(ep.end).toISOString(), tone: "good", kind: "integration", link: "/integrations", detail: null, title: `${label} is answering again` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Maintenance: windows that began or finished in the time ──
|
||||||
|
const sinceIso = new Date(sinceMs).toISOString();
|
||||||
|
const nowIso = now.toISOString();
|
||||||
|
const windows = (await db.select().from(maintenanceWindows).where(and(gte(maintenanceWindows.endsAt, sinceIso)))).filter(
|
||||||
|
(w) => w.endsAt > w.startedAt && w.startedAt <= nowIso && (w.startedAt >= sinceIso || w.endsAt <= nowIso),
|
||||||
|
);
|
||||||
|
const groups = new Map<string, typeof windows>();
|
||||||
|
for (const w of windows) {
|
||||||
|
const key = `${w.startedAt.slice(0, 16)}|${w.endsAt.slice(0, 16)}|${w.createdBy ?? ""}|${w.reason ?? ""}`;
|
||||||
|
groups.set(key, [...(groups.get(key) ?? []), w]);
|
||||||
|
}
|
||||||
|
for (const group of groups.values()) {
|
||||||
|
const names: string[] = [];
|
||||||
|
for (const w of group) {
|
||||||
|
const t = await describeTarget(w.targetType, w.targetId);
|
||||||
|
if (t) names.push(t.name);
|
||||||
|
}
|
||||||
|
if (names.length === 0) continue;
|
||||||
|
const ended = group[0].endsAt <= nowIso;
|
||||||
|
const subject = names.length >= 4 ? `${names.length} items` : names.join(", ");
|
||||||
|
const verb = names.length === 1 ? (ended ? "was" : "is") : ended ? "were" : "are";
|
||||||
|
const lasted = span(Date.parse(group[0].endsAt) - Date.parse(group[0].startedAt));
|
||||||
|
events.push({
|
||||||
|
at: group[0].startedAt >= sinceIso ? group[0].startedAt : group[0].endsAt,
|
||||||
|
tone: "info",
|
||||||
|
kind: "maintenance",
|
||||||
|
link: "/maintenance",
|
||||||
|
title: ended ? `${subject} ${verb} in maintenance for ${lasted}` : `${subject} ${verb} in maintenance — alerts silenced`,
|
||||||
|
detail: group[0].reason,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
events.sort((a, b) => b.at.localeCompare(a.at));
|
||||||
|
|
||||||
|
let changesByOthers: number | null = null;
|
||||||
|
if (params.canSeeAudit) {
|
||||||
|
changesByOthers = audits.filter((a) => a.atMs >= sinceMs && a.actorUserId !== params.actorId && a.actorLabel !== "system").length;
|
||||||
|
}
|
||||||
|
return { since: sinceIso, events, changesByOthers };
|
||||||
|
}
|
||||||
@@ -1,3 +1,8 @@
|
|||||||
|
import { desc, eq, and } from "drizzle-orm";
|
||||||
|
import { db } from "../db/client.js";
|
||||||
|
import { auditLog } from "../db/schema.js";
|
||||||
|
import { recordAudit } from "./audit.js";
|
||||||
|
import { ensureHistoryStart } from "./uptimeHistory.js";
|
||||||
import { getSettings } from "./settingsStore.js";
|
import { getSettings } from "./settingsStore.js";
|
||||||
import { isSourceInMaintenance } from "./maintenance.js";
|
import { isSourceInMaintenance } from "./maintenance.js";
|
||||||
import { notifyIntegrationDown, notifyIntegrationRecovered } from "./notify.js";
|
import { notifyIntegrationDown, notifyIntegrationRecovered } from "./notify.js";
|
||||||
@@ -6,6 +11,36 @@ interface SourceHealth {
|
|||||||
consecutiveFailures: number;
|
consecutiveFailures: number;
|
||||||
/** True once a "down" notification has been sent for the current failure streak, so it isn't repeated on every subsequent failure. */
|
/** True once a "down" notification has been sent for the current failure streak, so it isn't repeated on every subsequent failure. */
|
||||||
alerted: boolean;
|
alerted: boolean;
|
||||||
|
/** True once the audit log has been told this streak reached the failure threshold, so it is written once and its end can be written too. */
|
||||||
|
recorded?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes a service's "started failing" / "working again" moment in the audit log (never letting a problem there hold up the call
|
||||||
|
* that triggered it), so the dashboard can say what changed and the integration pages can draw how it has done over the weeks.
|
||||||
|
*/
|
||||||
|
async function recordTransition(source: string, action: "went_failing" | "recovered", detail?: unknown): Promise<void> {
|
||||||
|
try {
|
||||||
|
await ensureHistoryStart();
|
||||||
|
await recordAudit({ category: "integration", action, targetType: "integration_type", targetId: source, detail });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[integration-health] couldn't record a transition:", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the audit log last says about a service, for the first call after a restart (the live streak is only in memory). */
|
||||||
|
async function lastRecordedTransition(source: string): Promise<"went_failing" | "recovered" | null> {
|
||||||
|
try {
|
||||||
|
const [row] = await db
|
||||||
|
.select({ action: auditLog.action })
|
||||||
|
.from(auditLog)
|
||||||
|
.where(and(eq(auditLog.category, "integration"), eq(auditLog.targetType, "integration_type"), eq(auditLog.targetId, source)))
|
||||||
|
.orderBy(desc(auditLog.createdAt), desc(auditLog.id))
|
||||||
|
.limit(1);
|
||||||
|
return row?.action === "went_failing" || row?.action === "recovered" ? row.action : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -38,18 +73,26 @@ export function getSourceStatus(source: string): { status: "ok" | "failing" | "u
|
|||||||
|
|
||||||
/** Called after every diagnostic-log entry is recorded, to track consecutive failures per source and alert on threshold-cross / recovery. */
|
/** Called after every diagnostic-log entry is recorded, to track consecutive failures per source and alert on threshold-cross / recovery. */
|
||||||
export async function trackIntegrationHealth(source: string, ok: boolean): Promise<void> {
|
export async function trackIntegrationHealth(source: string, ok: boolean): Promise<void> {
|
||||||
|
const seenBefore = health.has(source);
|
||||||
const state = health.get(source) ?? { consecutiveFailures: 0, alerted: false };
|
const state = health.get(source) ?? { consecutiveFailures: 0, alerted: false };
|
||||||
|
|
||||||
if (ok) {
|
if (ok) {
|
||||||
if (state.alerted) {
|
if (state.alerted) {
|
||||||
await notifyIntegrationRecovered(source);
|
await notifyIntegrationRecovered(source);
|
||||||
}
|
}
|
||||||
|
if (state.recorded || (!seenBefore && (await lastRecordedTransition(source)) === "went_failing")) {
|
||||||
|
await recordTransition(source, "recovered");
|
||||||
|
}
|
||||||
health.set(source, { consecutiveFailures: 0, alerted: false });
|
health.set(source, { consecutiveFailures: 0, alerted: false });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
state.consecutiveFailures += 1;
|
state.consecutiveFailures += 1;
|
||||||
const { notifications } = await getSettings();
|
const { notifications } = await getSettings();
|
||||||
|
if (!state.recorded && state.consecutiveFailures >= notifications.integrationFailureThreshold) {
|
||||||
|
state.recorded = true;
|
||||||
|
await recordTransition(source, "went_failing", { failures: state.consecutiveFailures });
|
||||||
|
}
|
||||||
if (notifications.integrationFailureAlerts && !state.alerted && state.consecutiveFailures >= notifications.integrationFailureThreshold) {
|
if (notifications.integrationFailureAlerts && !state.alerted && state.consecutiveFailures >= notifications.integrationFailureThreshold) {
|
||||||
// During maintenance the failures keep being counted but `alerted` stays false, so if the service is
|
// During maintenance the failures keep being counted but `alerted` stays false, so if the service is
|
||||||
// still failing once the window ends, the very next failed call alerts — a real outage isn't swallowed.
|
// still failing once the window ends, the very next failed call alerts — a real outage isn't swallowed.
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
/**
|
||||||
|
* How each server and integration has done over the last weeks, as one figure per day: how long it was up, how long down, and for
|
||||||
|
* how much of the day anything is known. It is worked out from the moments the health checks wrote down in the audit log (a
|
||||||
|
* server stopped reporting / reported again; an integration's calls started failing / worked again), so it needs no table of its
|
||||||
|
* own — and it can only be as old as those records.
|
||||||
|
*/
|
||||||
|
import { inArray } from "drizzle-orm";
|
||||||
|
import { db } from "../db/client.js";
|
||||||
|
import { auditLog, integrations, servers } from "../db/schema.js";
|
||||||
|
import { auditTimeToIso } from "./serverActivity.js";
|
||||||
|
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
|
||||||
|
|
||||||
|
const DAY_MS = 24 * 3600_000;
|
||||||
|
const HISTORY_FLAG = "integration_history_since";
|
||||||
|
|
||||||
|
export const DEFAULT_DAYS = 30;
|
||||||
|
|
||||||
|
export interface Transition {
|
||||||
|
/** Epoch ms. */
|
||||||
|
at: number;
|
||||||
|
down: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Minutes of one 24-hour stretch that are known, and of those, minutes spent down. */
|
||||||
|
export interface UptimeBucket {
|
||||||
|
k: number;
|
||||||
|
d: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UptimeSeries {
|
||||||
|
/** Oldest first; the last bucket ends now. */
|
||||||
|
buckets: UptimeBucket[];
|
||||||
|
/** Share of the known time spent up over the whole period. */
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits [knownFrom, now] into up and down stretches from the recorded transitions and lays them over `days` consecutive 24-hour
|
||||||
|
* buckets ending at `now`. Before the first transition the thing is taken to have been in the opposite state (a "went offline" means it
|
||||||
|
* was up until then); with no transitions at all it has been up the whole time.
|
||||||
|
*/
|
||||||
|
export function computeBuckets(transitions: Transition[], knownFrom: number, now: number, days: number): UptimeBucket[] {
|
||||||
|
const start = now - days * DAY_MS;
|
||||||
|
const sorted = [...transitions].sort((a, b) => a.at - b.at);
|
||||||
|
|
||||||
|
// State at knownFrom: after any transitions that happened before it, otherwise the opposite of the first one that follows.
|
||||||
|
let state = false;
|
||||||
|
let i = 0;
|
||||||
|
while (i < sorted.length && sorted[i].at <= knownFrom) state = sorted[i++].down;
|
||||||
|
if (i === 0 && sorted.length > 0) state = !sorted[0].down;
|
||||||
|
|
||||||
|
const segments: { from: number; to: number; down: boolean }[] = [];
|
||||||
|
let cursor = Math.min(knownFrom, now);
|
||||||
|
for (; i < sorted.length; i++) {
|
||||||
|
const t = Math.min(sorted[i].at, now);
|
||||||
|
if (t > cursor) segments.push({ from: cursor, to: t, down: state });
|
||||||
|
cursor = Math.max(cursor, t);
|
||||||
|
state = sorted[i].down;
|
||||||
|
}
|
||||||
|
if (now > cursor) segments.push({ from: cursor, to: now, down: state });
|
||||||
|
|
||||||
|
const known = new Array<number>(days).fill(0);
|
||||||
|
const down = new Array<number>(days).fill(0);
|
||||||
|
for (const seg of segments) {
|
||||||
|
if (seg.to <= start) continue;
|
||||||
|
const first = Math.max(0, Math.floor((Math.max(seg.from, start) - start) / DAY_MS));
|
||||||
|
for (let b = first; b < days; b++) {
|
||||||
|
const bStart = start + b * DAY_MS;
|
||||||
|
if (bStart >= seg.to) break;
|
||||||
|
const overlap = Math.min(seg.to, bStart + DAY_MS) - Math.max(seg.from, bStart);
|
||||||
|
if (overlap <= 0) continue;
|
||||||
|
known[b] += overlap;
|
||||||
|
if (seg.down) down[b] += overlap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return known.map((k, b) => ({ k: Math.round(k / 60_000), d: Math.round(down[b] / 60_000) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Share of the known time spent up, to one decimal; null when nothing is known. */
|
||||||
|
export function uptimePercent(buckets: UptimeBucket[]): number | null {
|
||||||
|
const known = buckets.reduce((n, b) => n + b.k, 0);
|
||||||
|
if (known === 0) return null;
|
||||||
|
const down = buckets.reduce((n, b) => n + b.d, 0);
|
||||||
|
return Math.round((1 - down / known) * 1000) / 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
function series(transitions: Transition[], knownFrom: number, now: number, days: number): UptimeSeries | null {
|
||||||
|
const buckets = computeBuckets(transitions, knownFrom, now, days);
|
||||||
|
const percent = uptimePercent(buckets);
|
||||||
|
return percent === null ? null : { buckets, percent };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Integrations' failing / working-again moments only exist from the version that began writing them, so nothing earlier can be claimed.
|
||||||
|
* The first time anything asks, that moment is written down and kept.
|
||||||
|
*/
|
||||||
|
let historyStart: number | null = null;
|
||||||
|
export async function ensureHistoryStart(now: number = Date.now()): Promise<number> {
|
||||||
|
if (historyStart !== null) return historyStart;
|
||||||
|
const stored = await getInternalFlag(HISTORY_FLAG);
|
||||||
|
const parsed = stored ? Date.parse(stored) : NaN;
|
||||||
|
if (Number.isFinite(parsed)) {
|
||||||
|
historyStart = parsed;
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
await setInternalFlag(HISTORY_FLAG, new Date(now).toISOString());
|
||||||
|
historyStart = now;
|
||||||
|
return now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** For tests: forget the remembered start. */
|
||||||
|
export function resetHistoryStartForTests(): void {
|
||||||
|
historyStart = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UptimeReport {
|
||||||
|
days: number;
|
||||||
|
/** ISO — the end of the last bucket. */
|
||||||
|
endsAt: string;
|
||||||
|
servers: Record<number, UptimeSeries>;
|
||||||
|
integrations: Record<number, UptimeSeries>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUptime(now: Date = new Date(), days: number = DEFAULT_DAYS): Promise<UptimeReport> {
|
||||||
|
const nowMs = now.getTime();
|
||||||
|
const rows = await db.select().from(auditLog).where(inArray(auditLog.action, ["went_offline", "back_online", "went_failing", "recovered"]));
|
||||||
|
|
||||||
|
const serverEvents = new Map<number, Transition[]>();
|
||||||
|
const sourceEvents = new Map<string, Transition[]>();
|
||||||
|
for (const r of rows) {
|
||||||
|
const at = Date.parse(auditTimeToIso(r.createdAt));
|
||||||
|
if (!Number.isFinite(at) || at > nowMs) continue;
|
||||||
|
if (r.category === "server" && r.targetType === "server" && (r.action === "went_offline" || r.action === "back_online")) {
|
||||||
|
const id = Number(r.targetId);
|
||||||
|
const list = serverEvents.get(id) ?? [];
|
||||||
|
list.push({ at, down: r.action === "went_offline" });
|
||||||
|
serverEvents.set(id, list);
|
||||||
|
} else if (r.category === "integration" && r.targetType === "integration_type" && r.targetId && (r.action === "went_failing" || r.action === "recovered")) {
|
||||||
|
const list = sourceEvents.get(r.targetId) ?? [];
|
||||||
|
list.push({ at, down: r.action === "went_failing" });
|
||||||
|
sourceEvents.set(r.targetId, list);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const out: UptimeReport = { days, endsAt: now.toISOString(), servers: {}, integrations: {} };
|
||||||
|
|
||||||
|
for (const s of await db.select({ id: servers.id, createdAt: servers.createdAt, lastSeenAt: servers.lastSeenAt }).from(servers)) {
|
||||||
|
const events = serverEvents.get(s.id) ?? [];
|
||||||
|
// A server that has never reported and never been seen to stop has no history to speak of.
|
||||||
|
if (!s.lastSeenAt && events.length === 0) continue;
|
||||||
|
const created = Date.parse(auditTimeToIso(s.createdAt));
|
||||||
|
const result = series(events, Number.isFinite(created) ? created : nowMs, nowMs, days);
|
||||||
|
if (result) out.servers[s.id] = result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const since = await ensureHistoryStart(nowMs);
|
||||||
|
for (const i of await db.select({ id: integrations.id, type: integrations.type, createdAt: integrations.createdAt }).from(integrations)) {
|
||||||
|
const created = Date.parse(auditTimeToIso(i.createdAt));
|
||||||
|
const knownFrom = Math.max(Number.isFinite(created) ? created : 0, since);
|
||||||
|
const result = series(sourceEvents.get(i.type) ?? [], knownFrom, nowMs, days);
|
||||||
|
if (result) out.integrations[i.id] = result;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
/**
|
||||||
|
* The 30-day uptime ribbons and the dashboard's "since you last looked" summary — both built from what the health checks wrote
|
||||||
|
* down in the audit log.
|
||||||
|
*
|
||||||
|
* Run with: npm test --workspace server
|
||||||
|
*/
|
||||||
|
import { test, describe, before, after } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { mkdtempSync, rmSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import type { AddressInfo } from "node:net";
|
||||||
|
import type { Server } from "node:http";
|
||||||
|
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), "hm-uptime-"));
|
||||||
|
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||||
|
process.env.SESSION_DIR = join(dir, "sessions");
|
||||||
|
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||||
|
|
||||||
|
const express = (await import("express")).default;
|
||||||
|
const { db } = await import("../src/db/client.js");
|
||||||
|
const { users, servers, integrations, auditLog, maintenanceWindows } = await import("../src/db/schema.js");
|
||||||
|
const { runMigrations } = await import("../src/db/migrate.js");
|
||||||
|
const { meRouter } = await import("../src/routes/me.js");
|
||||||
|
const { uptimeRouter } = await import("../src/routes/uptime.js");
|
||||||
|
const { computeBuckets, uptimePercent, getUptime } = await import("../src/services/uptimeHistory.js");
|
||||||
|
const { foldMarks, getChangesSince } = await import("../src/services/changesSince.js");
|
||||||
|
const { trackIntegrationHealth } = await import("../src/services/integrationHealthMonitor.js");
|
||||||
|
|
||||||
|
await runMigrations();
|
||||||
|
|
||||||
|
const HOUR = 3600_000;
|
||||||
|
const DAY = 24 * HOUR;
|
||||||
|
const NOW = Math.floor(Date.now() / 1000) * 1000;
|
||||||
|
const dbTime = (ms: number) => new Date(ms).toISOString().slice(0, 19).replace("T", " ");
|
||||||
|
|
||||||
|
describe("computeBuckets", () => {
|
||||||
|
test("a thing with no problems recorded has been up for as long as it has been known", () => {
|
||||||
|
const buckets = computeBuckets([], NOW - 10 * DAY, NOW, 30);
|
||||||
|
assert.equal(buckets.length, 30);
|
||||||
|
assert.deepEqual(buckets.slice(0, 20).map((b) => b.k), new Array(20).fill(0), "nothing is known before it existed");
|
||||||
|
assert.ok(buckets.slice(20).every((b) => b.k === 1440 && b.d === 0));
|
||||||
|
assert.equal(uptimePercent(buckets), 100);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a stretch offline shows as down minutes in the day it happened", () => {
|
||||||
|
const buckets = computeBuckets(
|
||||||
|
[
|
||||||
|
{ at: NOW - 2 * HOUR, down: true },
|
||||||
|
{ at: NOW - HOUR, down: false },
|
||||||
|
],
|
||||||
|
NOW - 30 * DAY,
|
||||||
|
NOW,
|
||||||
|
30,
|
||||||
|
);
|
||||||
|
assert.equal(buckets[29].d, 60);
|
||||||
|
assert.equal(buckets[29].k, 1440);
|
||||||
|
assert.equal(buckets.slice(0, 29).reduce((n, b) => n + b.d, 0), 0);
|
||||||
|
assert.equal(uptimePercent(buckets), Math.round((1 - 60 / (30 * 1440)) * 1000) / 10);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an outage that spans midnight is split between the days, and one still going counts up to now", () => {
|
||||||
|
const buckets = computeBuckets([{ at: NOW - 36 * HOUR, down: true }], NOW - 30 * DAY, NOW, 30);
|
||||||
|
assert.equal(buckets[29].d, 1440);
|
||||||
|
assert.equal(buckets[28].d, 12 * 60);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a first record of recovery means it was down before that", () => {
|
||||||
|
const buckets = computeBuckets([{ at: NOW - 12 * HOUR, down: false }], NOW - 3 * DAY, NOW, 30);
|
||||||
|
assert.equal(buckets[28].d, 1440);
|
||||||
|
assert.equal(buckets[27].d, 1440);
|
||||||
|
assert.equal(buckets[29].d, 12 * 60, "down until the recovery 12 hours ago");
|
||||||
|
assert.equal(buckets[26].k, 0, "nothing known before it existed");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("repeated 'down' marks don't double anything", () => {
|
||||||
|
const once = computeBuckets([{ at: NOW - 5 * HOUR, down: true }, { at: NOW - 3 * HOUR, down: false }], NOW - 5 * DAY, NOW, 30);
|
||||||
|
const twice = computeBuckets([{ at: NOW - 5 * HOUR, down: true }, { at: NOW - 4 * HOUR, down: true }, { at: NOW - 3 * HOUR, down: false }], NOW - 5 * DAY, NOW, 30);
|
||||||
|
assert.deepEqual(once, twice);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("foldMarks", () => {
|
||||||
|
test("pairs, lone recoveries and open problems", () => {
|
||||||
|
const folded = foldMarks([
|
||||||
|
{ at: 1, problem: false, message: null },
|
||||||
|
{ at: 5, problem: true, message: "a" },
|
||||||
|
{ at: 6, problem: true, message: "dup" },
|
||||||
|
{ at: 9, problem: false, message: null },
|
||||||
|
{ at: 20, problem: true, message: "b" },
|
||||||
|
]);
|
||||||
|
assert.deepEqual(folded, [
|
||||||
|
{ start: null, end: 1, message: null },
|
||||||
|
{ start: 5, end: 9, message: "a" },
|
||||||
|
{ start: 20, end: null, message: "b" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("recording integration transitions", () => {
|
||||||
|
test("the third failure is written down once, and the next success ends it", async () => {
|
||||||
|
await trackIntegrationHealth("ribbon-a", false);
|
||||||
|
await trackIntegrationHealth("ribbon-a", false);
|
||||||
|
assert.equal((await db.select().from(auditLog)).filter((e) => e.targetId === "ribbon-a").length, 0, "two failures are not an outage yet");
|
||||||
|
await trackIntegrationHealth("ribbon-a", false);
|
||||||
|
await trackIntegrationHealth("ribbon-a", false);
|
||||||
|
await trackIntegrationHealth("ribbon-a", true);
|
||||||
|
await trackIntegrationHealth("ribbon-a", true);
|
||||||
|
const rows = (await db.select().from(auditLog)).filter((e) => e.targetId === "ribbon-a");
|
||||||
|
assert.deepEqual(rows.map((r) => r.action), ["went_failing", "recovered"]);
|
||||||
|
assert.ok(rows.every((r) => r.category === "integration" && r.targetType === "integration_type"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a service the log last saw failing is closed off by its first success after a restart", async () => {
|
||||||
|
await db.insert(auditLog).values({ category: "integration", action: "went_failing", targetType: "integration_type", targetId: "ribbon-b", actorLabel: "system" });
|
||||||
|
await trackIntegrationHealth("ribbon-b", true); // nothing in memory about ribbon-b: this is the first call since "start"
|
||||||
|
const rows = (await db.select().from(auditLog)).filter((e) => e.targetId === "ribbon-b");
|
||||||
|
assert.deepEqual(rows.map((r) => r.action), ["went_failing", "recovered"]);
|
||||||
|
await trackIntegrationHealth("ribbon-b", true);
|
||||||
|
assert.equal((await db.select().from(auditLog)).filter((e) => e.targetId === "ribbon-b").length, 2, "and only once");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a healthy service writes nothing", async () => {
|
||||||
|
await trackIntegrationHealth("ribbon-c", true);
|
||||||
|
await trackIntegrationHealth("ribbon-c", true);
|
||||||
|
assert.equal((await db.select().from(auditLog)).filter((e) => e.targetId === "ribbon-c").length, 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("uptime and changes from the audit log", () => {
|
||||||
|
let app: Server;
|
||||||
|
let base = "";
|
||||||
|
let who = "admin";
|
||||||
|
let elsaId = 0;
|
||||||
|
let annaId = 0;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
await db.insert(users).values([
|
||||||
|
{ oidcSub: "admin", name: "Ada", role: "admin" },
|
||||||
|
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
|
||||||
|
]);
|
||||||
|
const made = await db
|
||||||
|
.insert(servers)
|
||||||
|
.values([
|
||||||
|
{ name: "elsa", apiTokenHash: "a", apiTokenPrefix: "a", createdAt: dbTime(NOW - 40 * DAY), lastSeenAt: new Date(NOW).toISOString() },
|
||||||
|
{ name: "anna", apiTokenHash: "b", apiTokenPrefix: "b", createdAt: dbTime(NOW - 40 * DAY), lastSeenAt: new Date(NOW).toISOString() },
|
||||||
|
{ name: "never", apiTokenHash: "c", apiTokenPrefix: "c", createdAt: dbTime(NOW - 40 * DAY) },
|
||||||
|
])
|
||||||
|
.returning({ id: servers.id });
|
||||||
|
elsaId = made[0].id;
|
||||||
|
annaId = made[1].id;
|
||||||
|
|
||||||
|
await db.insert(integrations).values({ type: "proxmox", name: "Felicia", baseUrl: "https://pve.lab", config: "{}", createdAt: dbTime(NOW - 40 * DAY) });
|
||||||
|
|
||||||
|
const entry = (offsetMs: number, category: string, action: string, targetType: string, targetId: string | number, extra: Record<string, unknown> = {}) => ({
|
||||||
|
category,
|
||||||
|
action,
|
||||||
|
targetType,
|
||||||
|
targetId: String(targetId),
|
||||||
|
actorLabel: "system",
|
||||||
|
createdAt: dbTime(NOW + offsetMs),
|
||||||
|
...extra,
|
||||||
|
});
|
||||||
|
await db.insert(auditLog).values([
|
||||||
|
// elsa: offline for an hour, a while ago — finished
|
||||||
|
entry(-5 * HOUR, "server", "went_offline", "server", elsaId, { detail: JSON.stringify({ message: "No report for 5 minutes" }) }),
|
||||||
|
entry(-4 * HOUR, "server", "back_online", "server", elsaId),
|
||||||
|
// anna: went offline and has not come back
|
||||||
|
entry(-3 * HOUR, "server", "went_offline", "server", annaId),
|
||||||
|
// a service that stopped answering and came back
|
||||||
|
entry(-6 * HOUR, "integration", "went_failing", "integration_type", "proxmox"),
|
||||||
|
entry(-5.5 * HOUR, "integration", "recovered", "integration_type", "proxmox"),
|
||||||
|
// somebody else's edits, and one of Ada's own
|
||||||
|
{ category: "secret", action: "update", targetType: "secret", targetId: "1", actorLabel: "Olga", createdAt: dbTime(NOW - 2 * HOUR) },
|
||||||
|
{ category: "secret", action: "update", targetType: "secret", targetId: "2", actorLabel: "Olga", createdAt: dbTime(NOW - 2 * HOUR) },
|
||||||
|
// before the window we ask about
|
||||||
|
entry(-3 * DAY, "server", "went_offline", "server", elsaId),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const a = express();
|
||||||
|
a.use(express.json());
|
||||||
|
a.use((req, _res, next) => {
|
||||||
|
(req as unknown as { session: unknown }).session = { user: { sub: who } };
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
a.use("/api/me", meRouter);
|
||||||
|
a.use("/api/uptime", uptimeRouter);
|
||||||
|
app = await new Promise<Server>((resolve) => {
|
||||||
|
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
||||||
|
});
|
||||||
|
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
|
||||||
|
});
|
||||||
|
|
||||||
|
after(() => {
|
||||||
|
app.close();
|
||||||
|
try {
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// Windows keeps the database file locked until the process exits.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uptime covers servers that have reported, gives them a percentage, and skips one that never has", async () => {
|
||||||
|
const report = await getUptime(new Date(NOW), 30);
|
||||||
|
assert.ok(report.servers[elsaId]);
|
||||||
|
assert.ok(report.servers[annaId]);
|
||||||
|
assert.equal(Object.keys(report.servers).length, 2);
|
||||||
|
assert.equal(report.servers[annaId].buckets.length, 30);
|
||||||
|
// anna stopped reporting 3 hours ago and the log has not seen her come back
|
||||||
|
assert.equal(report.servers[annaId].buckets[29].d, 180);
|
||||||
|
// elsa went offline 3 days ago, was recorded offline again and then back 4 hours ago: down from then until then
|
||||||
|
assert.equal(report.servers[elsaId].buckets[29].d, 20 * 60);
|
||||||
|
assert.equal(report.servers[elsaId].buckets[28].d, 1440);
|
||||||
|
assert.equal(report.servers[elsaId].buckets[27].d, 1440);
|
||||||
|
assert.equal(report.servers[elsaId].buckets[26].d, 0);
|
||||||
|
assert.ok(report.servers[elsaId].percent < 100 && report.servers[elsaId].percent > 90);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the uptime route answers anyone signed in", async () => {
|
||||||
|
who = "viewer";
|
||||||
|
const res = await fetch(`${base}/uptime`);
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
const body = await res.json();
|
||||||
|
assert.equal(body.days, 30);
|
||||||
|
who = "admin";
|
||||||
|
});
|
||||||
|
|
||||||
|
test("changes since: pairs, an open problem, a service blip, and what others did", async () => {
|
||||||
|
const adaId = (await db.select().from(users)).find((u) => u.oidcSub === "admin")!.id;
|
||||||
|
const report = await getChangesSince({ since: new Date(NOW - 12 * HOUR), now: new Date(NOW), actorId: adaId, canSeeAudit: true });
|
||||||
|
const titles = report.events.map((e) => e.title);
|
||||||
|
assert.ok(titles.some((t) => /^elsa was offline for 1 h — reporting again/.test(t)), titles.join(" | "));
|
||||||
|
assert.ok(titles.some((t) => /^anna went offline 3 h ago — still offline/.test(t)), titles.join(" | "));
|
||||||
|
assert.ok(titles.some((t) => /^Felicia stopped answering for 30 min — working again/.test(t)), titles.join(" | "));
|
||||||
|
const anna = report.events.find((e) => e.title.startsWith("anna"));
|
||||||
|
assert.equal(anna?.tone, "bad");
|
||||||
|
assert.equal(anna?.link, `/servers/${annaId}`);
|
||||||
|
assert.equal(report.events.find((e) => e.title.startsWith("elsa"))?.detail, "No report for 5 minutes");
|
||||||
|
// Olga's two edits count; the app's own entries don't.
|
||||||
|
assert.equal(report.changesByOthers, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a viewer isn't told about the audit log", async () => {
|
||||||
|
const viewerId = (await db.select().from(users)).find((u) => u.oidcSub === "viewer")!.id;
|
||||||
|
const report = await getChangesSince({ since: new Date(NOW - 12 * HOUR), now: new Date(NOW), actorId: viewerId, canSeeAudit: false });
|
||||||
|
assert.equal(report.changesByOthers, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("nothing before the start of the summary is in it", async () => {
|
||||||
|
const report = await getChangesSince({ since: new Date(NOW - 2 * HOUR), now: new Date(NOW), actorId: 0, canSeeAudit: true });
|
||||||
|
assert.equal(report.events.filter((e) => e.kind !== "maintenance").length, 0, "the problems were all earlier than that");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("maintenance that began, ended or was started in bulk is told in few lines", async () => {
|
||||||
|
const mk = (hoursAgoStart: number, hoursAgoEnd: number, target: number, reason: string) => ({
|
||||||
|
targetType: "server" as const,
|
||||||
|
targetId: target,
|
||||||
|
reason,
|
||||||
|
startedAt: new Date(NOW - hoursAgoStart * HOUR).toISOString(),
|
||||||
|
endsAt: new Date(NOW - hoursAgoEnd * HOUR).toISOString(),
|
||||||
|
createdBy: "Ada",
|
||||||
|
});
|
||||||
|
const extra = await db
|
||||||
|
.insert(servers)
|
||||||
|
.values([1, 2, 3, 4].map((n) => ({ name: `bulk${n}`, apiTokenHash: `h${n}`, apiTokenPrefix: `p${n}` })))
|
||||||
|
.returning({ id: servers.id });
|
||||||
|
await db.insert(maintenanceWindows).values([
|
||||||
|
mk(10, 8, elsaId, "Kernel update"), // finished
|
||||||
|
...extra.map((s) => mk(7, -2, s.id, "Power work")), // four at once, still running
|
||||||
|
mk(1, 1, annaId, "withdrawn"), // cancelled before it began
|
||||||
|
]);
|
||||||
|
const report = await getChangesSince({ since: new Date(NOW - 12 * HOUR), now: new Date(NOW), actorId: 0, canSeeAudit: false });
|
||||||
|
const maintenance = report.events.filter((e) => e.kind === "maintenance");
|
||||||
|
assert.equal(maintenance.length, 2, maintenance.map((m) => m.title).join(" | "));
|
||||||
|
assert.ok(maintenance.some((m) => m.title === "elsa was in maintenance for 2 h" && m.detail === "Kernel update"));
|
||||||
|
assert.ok(maintenance.some((m) => m.title === "4 items are in maintenance — alerts silenced" && m.detail === "Power work"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the route starts from a day ago the first time, then from where 'Got it' was pressed", async () => {
|
||||||
|
let res = await fetch(`${base}/me/changes`);
|
||||||
|
let body = await res.json();
|
||||||
|
assert.equal(body.firstTime, true);
|
||||||
|
assert.ok(Array.isArray(body.events));
|
||||||
|
|
||||||
|
assert.equal((await fetch(`${base}/me/changes/seen`, { method: "POST" })).status, 200);
|
||||||
|
res = await fetch(`${base}/me/changes`);
|
||||||
|
body = await res.json();
|
||||||
|
assert.equal(body.firstTime, false);
|
||||||
|
assert.equal(body.events.length, 0, "nothing has happened since just now");
|
||||||
|
assert.ok(Math.abs(Date.parse(body.since) - Date.now()) < 60_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("'Got it' only moves the signed-in person's own mark", async () => {
|
||||||
|
who = "viewer";
|
||||||
|
const res = await fetch(`${base}/me/changes`);
|
||||||
|
assert.equal((await res.json()).firstTime, true);
|
||||||
|
who = "admin";
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -10,6 +10,44 @@ export interface CurrentUser {
|
|||||||
favorites?: string[];
|
favorites?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One thing worth a line in "Since you last looked". */
|
||||||
|
export interface ChangeEvent {
|
||||||
|
at: string;
|
||||||
|
tone: "good" | "bad" | "info" | "neutral";
|
||||||
|
kind: "server" | "integration" | "maintenance";
|
||||||
|
title: string;
|
||||||
|
detail: string | null;
|
||||||
|
link: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChangesSummary {
|
||||||
|
since: string;
|
||||||
|
/** True the first time: the summary then covers the last day. */
|
||||||
|
firstTime: boolean;
|
||||||
|
events: ChangeEvent[];
|
||||||
|
moreEvents: number;
|
||||||
|
/** Entries other people wrote in the audit log in that time; null if this person can't see the audit log. */
|
||||||
|
changesByOthers: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Minutes known / minutes down in one 24-hour stretch. */
|
||||||
|
export interface UptimeBucket {
|
||||||
|
k: number;
|
||||||
|
d: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UptimeSeries {
|
||||||
|
buckets: UptimeBucket[];
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UptimeReport {
|
||||||
|
days: number;
|
||||||
|
endsAt: string;
|
||||||
|
servers: Record<number, UptimeSeries>;
|
||||||
|
integrations: Record<number, UptimeSeries>;
|
||||||
|
}
|
||||||
|
|
||||||
export interface UserRecord {
|
export interface UserRecord {
|
||||||
id: number;
|
id: number;
|
||||||
oidcSub: string;
|
oidcSub: string;
|
||||||
@@ -1110,7 +1148,12 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|||||||
export const api = {
|
export const api = {
|
||||||
me: Object.assign(() => request<{ user: CurrentUser }>("/api/me"), {
|
me: Object.assign(() => request<{ user: CurrentUser }>("/api/me"), {
|
||||||
setFavorites: (paths: string[]) => request<{ favorites: string[] }>("/api/me/favorites", { method: "PUT", body: JSON.stringify({ paths }) }),
|
setFavorites: (paths: string[]) => request<{ favorites: string[] }>("/api/me/favorites", { method: "PUT", body: JSON.stringify({ paths }) }),
|
||||||
|
changes: () => request<ChangesSummary>("/api/me/changes"),
|
||||||
|
markChangesSeen: () => request<{ lastLookedAt: string }>("/api/me/changes/seen", { method: "POST" }),
|
||||||
}),
|
}),
|
||||||
|
uptime: {
|
||||||
|
get: () => request<UptimeReport>("/api/uptime"),
|
||||||
|
},
|
||||||
search: {
|
search: {
|
||||||
query: (q: string) => request<SearchResponse>(`/api/search?q=${encodeURIComponent(q)}`),
|
query: (q: string) => request<SearchResponse>(`/api/search?q=${encodeURIComponent(q)}`),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import type { MaintenanceWindow } from "../api/client";
|
||||||
|
import { formatDate, formatDateTime, formatTime } from "../utils/date";
|
||||||
|
|
||||||
|
const HOUR = 3600_000;
|
||||||
|
const DAY = 24 * HOUR;
|
||||||
|
|
||||||
|
const RANGES = [
|
||||||
|
{ key: "24h", label: "Next 24 hours", span: DAY, tickEvery: 3 * HOUR },
|
||||||
|
{ key: "7d", label: "Next 7 days", span: 7 * DAY, tickEvery: DAY },
|
||||||
|
{ key: "30d", label: "Next 30 days", span: 30 * DAY, tickEvery: 5 * DAY },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
interface Span {
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Overlapping or touching spans folded into the stretches during which at least one is running. */
|
||||||
|
function union(spans: Span[]): Span[] {
|
||||||
|
const sorted = [...spans].sort((a, b) => a.from - b.from);
|
||||||
|
const out: Span[] = [];
|
||||||
|
for (const s of sorted) {
|
||||||
|
const last = out[out.length - 1];
|
||||||
|
if (last && s.from <= last.to) last.to = Math.max(last.to, s.to);
|
||||||
|
else out.push({ ...s });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The running and scheduled windows laid out along a time axis, one row per server, integration or DNS provider, plus a top row for
|
||||||
|
* "anything at all in maintenance". It shows what a list can't: which windows overlap, and where there are gaps. The tables further
|
||||||
|
* down the page hold the same windows for reading and for ending them, so this is a picture only.
|
||||||
|
*/
|
||||||
|
export default function MaintenanceTimeline({ windows, now }: { windows: MaintenanceWindow[]; now: number }) {
|
||||||
|
const [rangeKey, setRangeKey] = useState<(typeof RANGES)[number]["key"]>("7d");
|
||||||
|
const range = RANGES.find((r) => r.key === rangeKey)!;
|
||||||
|
const start = now;
|
||||||
|
const end = now + range.span;
|
||||||
|
|
||||||
|
const { rows, everything, further } = useMemo(() => {
|
||||||
|
const inRange = windows.filter((w) => Date.parse(w.endsAt) > start && Date.parse(w.startedAt) < end);
|
||||||
|
const byTarget = new Map<string, { name: string; kind: string; windows: MaintenanceWindow[] }>();
|
||||||
|
for (const w of inRange) {
|
||||||
|
const key = `${w.targetType}:${w.targetId}`;
|
||||||
|
const row = byTarget.get(key) ?? { name: w.targetName, kind: w.targetKind, windows: [] };
|
||||||
|
row.windows.push(w);
|
||||||
|
byTarget.set(key, row);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
rows: [...byTarget.values()].sort((a, b) => a.name.localeCompare(b.name)),
|
||||||
|
everything: union(inRange.map((w) => ({ from: Math.max(Date.parse(w.startedAt), start), to: Math.min(Date.parse(w.endsAt), end) }))),
|
||||||
|
further: windows.length - inRange.length,
|
||||||
|
};
|
||||||
|
}, [windows, start, end]);
|
||||||
|
|
||||||
|
const pct = (t: number) => ((Math.min(Math.max(t, start), end) - start) / range.span) * 100;
|
||||||
|
const bar = (from: number, to: number) => ({ left: `${pct(from)}%`, width: `${Math.max(pct(to) - pct(from), 0.6)}%` });
|
||||||
|
|
||||||
|
const ticks: number[] = [];
|
||||||
|
// First tick at the next whole step after now (the next midnight for day steps), so labels land on round times.
|
||||||
|
const stepStart = new Date(now);
|
||||||
|
if (range.tickEvery >= DAY) stepStart.setHours(24, 0, 0, 0);
|
||||||
|
else {
|
||||||
|
stepStart.setMinutes(0, 0, 0);
|
||||||
|
const hours = range.tickEvery / HOUR;
|
||||||
|
stepStart.setHours(Math.floor(stepStart.getHours() / hours) * hours);
|
||||||
|
}
|
||||||
|
for (let t = stepStart.getTime(); t < end; t += range.tickEvery) if (t > start) ticks.push(t);
|
||||||
|
|
||||||
|
const tickLabel = (t: number) => (range.tickEvery >= DAY ? formatDate(new Date(t)).replace(/^\d{4}-|\/\d{4}$/, "") : formatTime(new Date(t), false));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="card mb-3">
|
||||||
|
<div className="card-header">
|
||||||
|
<h3 className="card-title">Timeline</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<div className="btn-group btn-group-sm" role="group" aria-label="Time range">
|
||||||
|
{RANGES.map((r) => (
|
||||||
|
<button key={r.key} type="button" className={`btn btn-sm ${r.key === rangeKey ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={r.key === rangeKey} onClick={() => setRangeKey(r.key)}>
|
||||||
|
{r.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="card-body">
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<div className="text-secondary">Nothing running or scheduled in this time.{further > 0 ? ` ${further} further ahead.` : ""}</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="timeline-scroll" aria-hidden="true">
|
||||||
|
<div className="timeline">
|
||||||
|
<div className="timeline-row timeline-axis">
|
||||||
|
<div className="timeline-label text-secondary">From now</div>
|
||||||
|
<div className="timeline-track">
|
||||||
|
{ticks.map((t) => (
|
||||||
|
<span key={t} className="timeline-tick" style={{ left: `${pct(t)}%` }}>
|
||||||
|
{tickLabel(t)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="timeline-row timeline-union">
|
||||||
|
<div className="timeline-label fw-bold">Anything</div>
|
||||||
|
<div className="timeline-track">
|
||||||
|
{ticks.map((t) => (
|
||||||
|
<span key={t} className="timeline-grid" style={{ left: `${pct(t)}%` }} />
|
||||||
|
))}
|
||||||
|
{everything.map((s, i) => (
|
||||||
|
<span key={i} className="timeline-bar timeline-bar-union" style={bar(s.from, s.to)} title={`${formatDateTime(new Date(s.from))} – ${formatDateTime(new Date(s.to))}`} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{rows.map((row) => (
|
||||||
|
<div key={row.name + row.kind} className="timeline-row">
|
||||||
|
<div className="timeline-label" title={`${row.name} · ${row.kind}`}>
|
||||||
|
{row.name}
|
||||||
|
</div>
|
||||||
|
<div className="timeline-track">
|
||||||
|
{ticks.map((t) => (
|
||||||
|
<span key={t} className="timeline-grid" style={{ left: `${pct(t)}%` }} />
|
||||||
|
))}
|
||||||
|
{row.windows.map((w) => {
|
||||||
|
const from = Date.parse(w.startedAt);
|
||||||
|
const to = Date.parse(w.endsAt);
|
||||||
|
const running = from <= now;
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
key={w.id}
|
||||||
|
className={`timeline-bar ${running ? "timeline-bar-running" : "timeline-bar-scheduled"} ${w.source ? "timeline-bar-mirrored" : ""}`}
|
||||||
|
style={bar(from, to)}
|
||||||
|
title={`${row.name}: ${formatDateTime(new Date(from))} – ${formatDateTime(new Date(to))}${w.reason ? ` · ${w.reason}` : ""}`}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-secondary small mt-2 d-flex flex-wrap gap-3 align-items-center">
|
||||||
|
<span>
|
||||||
|
<span className="timeline-key timeline-bar-running" /> Running
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
<span className="timeline-key timeline-bar-scheduled" /> Scheduled
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
<span className="timeline-key timeline-bar-mirrored" /> From Uptime Kuma
|
||||||
|
</span>
|
||||||
|
<span>The same windows are listed in the tables below.</span>
|
||||||
|
{further > 0 && <span>{further} further ahead than this range.</span>}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useSyncExternalStore } from "react";
|
||||||
|
import { formatDateTime, parseDbTimestamp } from "../utils/date";
|
||||||
|
import { formatAgo, formatRemaining } from "../utils/duration";
|
||||||
|
|
||||||
|
// One shared clock for every TimeAgo on screen: "5 min ago" moves on by itself without each one running its own timer.
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
let tick = 0;
|
||||||
|
let timer: ReturnType<typeof setInterval> | undefined;
|
||||||
|
|
||||||
|
function subscribe(listener: () => void): () => void {
|
||||||
|
listeners.add(listener);
|
||||||
|
if (!timer) {
|
||||||
|
timer = setInterval(() => {
|
||||||
|
tick++;
|
||||||
|
listeners.forEach((l) => l());
|
||||||
|
}, 30_000);
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener);
|
||||||
|
if (listeners.size === 0 && timer) {
|
||||||
|
clearInterval(timer);
|
||||||
|
timer = undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTick = () => tick;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A time as people say it ("5 min ago", "in 2 h"), with the exact date and time — in the format chosen under Settings → Display —
|
||||||
|
* as the hover text. `fromDb` is for the plain "2026-10-02 20:27:55" timestamps SQLite writes, which are UTC without saying so.
|
||||||
|
*/
|
||||||
|
export default function TimeAgo({ value, fromDb, empty = "—" }: { value: string | Date | null | undefined; fromDb?: boolean; empty?: string }) {
|
||||||
|
useSyncExternalStore(subscribe, getTick);
|
||||||
|
if (value === null || value === undefined || value === "") return <>{empty}</>;
|
||||||
|
const date = value instanceof Date ? value : fromDb ? parseDbTimestamp(value) : new Date(value);
|
||||||
|
if (Number.isNaN(date.getTime())) return <>{empty}</>;
|
||||||
|
const iso = date.toISOString();
|
||||||
|
const future = date.getTime() > Date.now() + 60_000;
|
||||||
|
return (
|
||||||
|
<time dateTime={iso} title={formatDateTime(date)}>
|
||||||
|
{future ? `in ${formatRemaining(iso)}` : formatAgo(iso)}
|
||||||
|
</time>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { useUptime } from "../hooks/useUptime";
|
||||||
|
import { formatDate } from "../utils/date";
|
||||||
|
|
||||||
|
const DAY_MS = 24 * 3600_000;
|
||||||
|
|
||||||
|
function minutesLabel(minutes: number): string {
|
||||||
|
if (minutes < 60) return `${minutes} min`;
|
||||||
|
const h = Math.floor(minutes / 60);
|
||||||
|
return minutes % 60 && h < 10 ? `${h} h ${minutes % 60} min` : `${h} h`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A thin strip of one bar per day for the last 30 days — green for a day with nothing wrong, amber for some time down, red for
|
||||||
|
* half the day or more, grey where nothing is known (before it was added, or before the app began keeping this) — with the share of
|
||||||
|
* time up beside it. The bars are for the eye; the percentage and the hover text carry the same information in words.
|
||||||
|
*/
|
||||||
|
export default function UptimeRibbon({ kind, id, name, showPercent = true }: { kind: "servers" | "integrations"; id: number; name: string; showPercent?: boolean }) {
|
||||||
|
const report = useUptime();
|
||||||
|
const series = report?.[kind][id];
|
||||||
|
if (!report || !series) return null;
|
||||||
|
|
||||||
|
const end = Date.parse(report.endsAt);
|
||||||
|
const summary = `${name}: ${series.percent}% up over the last ${report.days} days`;
|
||||||
|
return (
|
||||||
|
<span className="uptime" title={summary}>
|
||||||
|
<span className="uptime-ribbon" aria-hidden="true">
|
||||||
|
{series.buckets.map((b, i) => {
|
||||||
|
const start = new Date(end - (report.days - i) * DAY_MS);
|
||||||
|
const state = b.k === 0 ? "none" : b.d === 0 ? "up" : b.d / b.k >= 0.5 ? "down" : "some";
|
||||||
|
const text = b.k === 0 ? "no record" : b.d === 0 ? "up all day" : `down ${minutesLabel(b.d)}`;
|
||||||
|
return <i key={i} className={`uptime-${state}`} title={`${formatDate(start)}: ${text}`} />;
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
{showPercent ? (
|
||||||
|
<span className="uptime-percent">
|
||||||
|
{series.percent}% <span className="visually-hidden">up over the last {report.days} days</span>
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="visually-hidden">{summary}</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Link } from "react-router-dom";
|
||||||
|
import { IconAlertTriangle, IconCircleCheck, IconPlugConnected, IconServer, IconTool } from "@tabler/icons-react";
|
||||||
|
import { api, type ChangeEvent, type ChangesSummary, type UserRole } from "../api/client";
|
||||||
|
import TimeAgo from "./TimeAgo";
|
||||||
|
import { toast } from "../utils/toast";
|
||||||
|
|
||||||
|
const TONE_CLASS: Record<ChangeEvent["tone"], string> = { good: "text-green", bad: "text-red", info: "text-blue", neutral: "text-secondary" };
|
||||||
|
|
||||||
|
function EventIcon({ event }: { event: ChangeEvent }) {
|
||||||
|
const cls = TONE_CLASS[event.tone];
|
||||||
|
if (event.kind === "maintenance") return <IconTool size={18} className={cls} aria-hidden="true" />;
|
||||||
|
if (event.tone === "bad") return <IconAlertTriangle size={18} className={cls} aria-hidden="true" />;
|
||||||
|
if (event.tone === "good") return <IconCircleCheck size={18} className={cls} aria-hidden="true" />;
|
||||||
|
return event.kind === "integration" ? <IconPlugConnected size={18} className={cls} aria-hidden="true" /> : <IconServer size={18} className={cls} aria-hidden="true" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What happened since this person last pressed "Got it": servers that stopped reporting, services that stopped answering, maintenance
|
||||||
|
* that began or ended. Nothing to say means nothing shown. The mark is theirs alone and follows them to any browser.
|
||||||
|
*/
|
||||||
|
export default function WhatChanged({ role }: { role: UserRole }) {
|
||||||
|
const [summary, setSummary] = useState<ChangesSummary | null>(null);
|
||||||
|
const [dismissed, setDismissed] = useState(false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
api.me
|
||||||
|
.changes()
|
||||||
|
.then((s) => alive && setSummary(s))
|
||||||
|
.catch(() => {
|
||||||
|
// Only a nicety on the dashboard: if it can't load, the dashboard simply doesn't have it.
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!summary || dismissed) return null;
|
||||||
|
const others = role !== "viewer" ? (summary.changesByOthers ?? 0) : 0;
|
||||||
|
if (summary.events.length === 0 && others === 0) return null;
|
||||||
|
|
||||||
|
async function gotIt() {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await api.me.markChangesSeen();
|
||||||
|
setDismissed(true);
|
||||||
|
} catch {
|
||||||
|
toast.error("Couldn't save that. Try again.");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="card mb-3" aria-label="Since you last looked">
|
||||||
|
<div className="card-header">
|
||||||
|
<div>
|
||||||
|
<h3 className="card-title">Since you last looked</h3>
|
||||||
|
<div className="text-secondary small">{summary.firstTime ? "In the last day" : <>Since <TimeAgo value={summary.since} /></>}</div>
|
||||||
|
</div>
|
||||||
|
<div className="card-actions">
|
||||||
|
<button type="button" className="btn btn-sm btn-primary" onClick={gotIt} disabled={busy}>
|
||||||
|
Got it
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="card-body">
|
||||||
|
{summary.events.length > 0 ? (
|
||||||
|
<ol className="activity-list">
|
||||||
|
{summary.events.map((e, i) => (
|
||||||
|
<li key={`${e.at}-${i}`}>
|
||||||
|
<EventIcon event={e} />
|
||||||
|
<div className="flex-fill" style={{ minWidth: 0 }}>
|
||||||
|
<div>{e.link ? <Link to={e.link}>{e.title}</Link> : e.title}</div>
|
||||||
|
{e.detail && <div className="text-secondary small">{e.detail}</div>}
|
||||||
|
</div>
|
||||||
|
<span className="text-secondary small text-nowrap">
|
||||||
|
<TimeAgo value={e.at} />
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
) : (
|
||||||
|
<div className="text-secondary">Nothing went wrong or came back.</div>
|
||||||
|
)}
|
||||||
|
{(summary.moreEvents > 0 || others > 0) && (
|
||||||
|
<div className="text-secondary small mt-2">
|
||||||
|
{summary.moreEvents > 0 && <>and {summary.moreEvents} more. </>}
|
||||||
|
{others > 0 && (
|
||||||
|
<>
|
||||||
|
{others} change{others === 1 ? "" : "s"} made by other people — <Link to="/audit-log">see the audit log</Link>.
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { useEffect, useSyncExternalStore } from "react";
|
||||||
|
import { api, type UptimeReport } from "../api/client";
|
||||||
|
|
||||||
|
// One report for every ribbon on a page: the first to appear fetches it, the rest share it, and it is fetched again after a few minutes.
|
||||||
|
const STALE_MS = 5 * 60_000;
|
||||||
|
let report: UptimeReport | null = null;
|
||||||
|
let fetchedAt = 0;
|
||||||
|
let loading = false;
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
function load(): void {
|
||||||
|
if (loading || (report && Date.now() - fetchedAt < STALE_MS)) return;
|
||||||
|
loading = true;
|
||||||
|
api.uptime
|
||||||
|
.get()
|
||||||
|
.then((r) => {
|
||||||
|
report = r;
|
||||||
|
fetchedAt = Date.now();
|
||||||
|
listeners.forEach((l) => l());
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
// No ribbons rather than an error on every row: this is a nicety on top of the lists.
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function subscribe(listener: () => void): () => void {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How each server and integration has done over the last 30 days; null until it has loaded (or if it couldn't). */
|
||||||
|
export function useUptime(): UptimeReport | null {
|
||||||
|
useEffect(load, []);
|
||||||
|
return useSyncExternalStore(subscribe, () => report);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { api, type ConsistencyFinding, type ConsistencyKind, type ConsistencyReport, type ConsistencySeverity, type CurrentUser } from "../api/client";
|
import { api, type ConsistencyFinding, type ConsistencyKind, type ConsistencyReport, type ConsistencySeverity, type CurrentUser } from "../api/client";
|
||||||
import { downloadCsv } from "../utils/csv";
|
import { downloadCsv } from "../utils/csv";
|
||||||
@@ -182,7 +183,7 @@ export default function Consistency({ user }: { user: CurrentUser }) {
|
|||||||
<>
|
<>
|
||||||
{" "}
|
{" "}
|
||||||
from {dns.syncedZones} of {dns.zones} synced zone{dns.zones === 1 ? "" : "s"}
|
from {dns.syncedZones} of {dns.zones} synced zone{dns.zones === 1 ? "" : "s"}
|
||||||
{dns.oldestSyncedAt && <> (oldest sync {formatAgo(dns.oldestSyncedAt)})</>}
|
{dns.oldestSyncedAt && <> (oldest sync <TimeAgo value={dns.oldestSyncedAt} />)</>}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
.
|
.
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { useEffect, useState, type ReactNode } from "react";
|
import { useEffect, useState, type ReactNode } from "react";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
|
import WhatChanged from "../components/WhatChanged";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import {
|
import {
|
||||||
api,
|
api,
|
||||||
@@ -594,6 +596,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
|
|||||||
Welcome back, {user.name ?? user.email ?? user.sub}.
|
Welcome back, {user.name ?? user.email ?? user.sub}.
|
||||||
</p>
|
</p>
|
||||||
<StatusStrip />
|
<StatusStrip />
|
||||||
|
<WhatChanged role={user.role} />
|
||||||
{isAdmin && integrations !== null && dnsStats !== null && serverSummary !== null && secrets !== null && notifyConfigured !== null && (
|
{isAdmin && integrations !== null && dnsStats !== null && serverSummary !== null && secrets !== null && notifyConfigured !== null && (
|
||||||
<SetupGuide steps={setupSteps} />
|
<SetupGuide steps={setupSteps} />
|
||||||
)}
|
)}
|
||||||
@@ -752,7 +755,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
|
|||||||
{i > 0 && ", "}
|
{i > 0 && ", "}
|
||||||
<Link to={`/servers/${s.id}`}>{s.name}</Link>{" "}
|
<Link to={`/servers/${s.id}`}>{s.name}</Link>{" "}
|
||||||
<span className="text-secondary">
|
<span className="text-secondary">
|
||||||
({formatAgo(s.lastSeenAt)}
|
(<TimeAgo value={s.lastSeenAt} empty="never seen" />
|
||||||
{s.inMaintenance ? ", in maintenance" : ""})
|
{s.inMaintenance ? ", in maintenance" : ""})
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState, type CSSProperties } from "react";
|
import { useEffect, useState, type CSSProperties } from "react";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
import { useSearchParams } from "react-router-dom";
|
import { useSearchParams } from "react-router-dom";
|
||||||
import {
|
import {
|
||||||
api,
|
api,
|
||||||
@@ -440,7 +441,7 @@ export default function Dns({ user }: { user: CurrentUser }) {
|
|||||||
<td>{z.name}</td>
|
<td>{z.name}</td>
|
||||||
<td>{z.recordCount}</td>
|
<td>{z.recordCount}</td>
|
||||||
<td className="text-secondary">
|
<td className="text-secondary">
|
||||||
{z.syncedAt ? formatDateTime(new Date(z.syncedAt)) : "never"}
|
{z.syncedAt ? <TimeAgo value={z.syncedAt} /> : "never"}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { downloadCsv } from "../utils/csv";
|
|||||||
import { confirmDialog } from "../utils/dialogs";
|
import { confirmDialog } from "../utils/dialogs";
|
||||||
import { ErrorNotice } from "../components/Notice";
|
import { ErrorNotice } from "../components/Notice";
|
||||||
import { toast } from "../utils/toast";
|
import { toast } from "../utils/toast";
|
||||||
|
import UptimeRibbon from "../components/UptimeRibbon";
|
||||||
|
|
||||||
const TYPE_LABELS: Record<IntegrationType, string> = {
|
const TYPE_LABELS: Record<IntegrationType, string> = {
|
||||||
tailscale: "Tailscale",
|
tailscale: "Tailscale",
|
||||||
@@ -223,6 +224,11 @@ export default function Integrations({ user }: { user: CurrentUser }) {
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{i.enabled && (
|
||||||
|
<div className="mb-3">
|
||||||
|
<UptimeRibbon kind="integrations" id={i.id} name={i.name} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{result && !result.ok && testingId !== i.id && <div className="text-red small mb-3">{result.error}</div>}
|
{result && !result.ok && testingId !== i.id && <div className="text-red small mb-3">{result.error}</div>}
|
||||||
<div className="btn-list mt-auto">
|
<div className="btn-list mt-auto">
|
||||||
{i.enabled && (
|
{i.enabled && (
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { readableError } from "../utils/errors";
|
|||||||
import { ErrorNotice } from "../components/Notice";
|
import { ErrorNotice } from "../components/Notice";
|
||||||
import { toast } from "../utils/toast";
|
import { toast } from "../utils/toast";
|
||||||
import { confirmDialog } from "../utils/dialogs";
|
import { confirmDialog } from "../utils/dialogs";
|
||||||
|
import MaintenanceTimeline from "../components/MaintenanceTimeline";
|
||||||
|
|
||||||
const DURATIONS: { minutes: number; label: string }[] = [
|
const DURATIONS: { minutes: number; label: string }[] = [
|
||||||
{ minutes: 30, label: "30 minutes" },
|
{ minutes: 30, label: "30 minutes" },
|
||||||
@@ -323,6 +324,8 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{((windows?.length ?? 0) > 0 || upcoming.length > 0) && <MaintenanceTimeline windows={[...(windows ?? []), ...upcoming]} now={now} />}
|
||||||
|
|
||||||
{canEdit && kumaIntegrations && kumaIntegrations.length > 0 && (
|
{canEdit && kumaIntegrations && kumaIntegrations.length > 0 && (
|
||||||
<div className="card mb-3">
|
<div className="card mb-3">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState, type FormEvent } from "react";
|
import { useEffect, useState, type FormEvent } from "react";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import {
|
import {
|
||||||
api,
|
api,
|
||||||
@@ -225,7 +226,7 @@ export default function Ports({ user }: { user: CurrentUser }) {
|
|||||||
{p.localOnly && <span className="badge bg-secondary-lt text-secondary ms-2">local only</span>}
|
{p.localOnly && <span className="badge bg-secondary-lt text-secondary ms-2">local only</span>}
|
||||||
</td>
|
</td>
|
||||||
<td className="text-secondary">{p.process ?? "—"}</td>
|
<td className="text-secondary">{p.process ?? "—"}</td>
|
||||||
<td className="text-secondary">{p.lastSeenAt ? formatAgo(p.lastSeenAt) : "—"}</td>
|
<td className="text-secondary"><TimeAgo value={p.lastSeenAt} /></td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{agentPorts !== null && agentPorts.length === 0 && (
|
{agentPorts !== null && agentPorts.length === 0 && (
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { api, type PrivacyOverview } from "../api/client";
|
import { api, type PrivacyOverview } from "../api/client";
|
||||||
import { formatDateTime } from "../utils/date";
|
import { formatDateTime } from "../utils/date";
|
||||||
@@ -114,7 +115,7 @@ export default function Privacy() {
|
|||||||
{s.ip ?? "—"} {s.current && <span className="badge bg-green-lt text-green ms-1">this browser</span>}
|
{s.ip ?? "—"} {s.current && <span className="badge bg-green-lt text-green ms-1">this browser</span>}
|
||||||
</td>
|
</td>
|
||||||
<td className="text-secondary text-break">{s.userAgent ?? "—"}</td>
|
<td className="text-secondary text-break">{s.userAgent ?? "—"}</td>
|
||||||
<td className="text-secondary">{formatAgo(s.lastAccess)}</td>
|
<td className="text-secondary"><TimeAgo value={s.lastAccess} /></td>
|
||||||
<td className="text-secondary">{s.expiresAt ? formatDateTime(new Date(s.expiresAt)) : "—"}</td>
|
<td className="text-secondary">{s.expiresAt ? formatDateTime(new Date(s.expiresAt)) : "—"}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import {
|
import {
|
||||||
api,
|
api,
|
||||||
@@ -461,7 +462,7 @@ export default function Proxmox({ user }: { user: CurrentUser }) {
|
|||||||
<td className="text-secondary">{t.node}</td>
|
<td className="text-secondary">{t.node}</td>
|
||||||
<td>{t.guestId ?? "—"}</td>
|
<td>{t.guestId ?? "—"}</td>
|
||||||
<td>{backupStatusBadge(t)}</td>
|
<td>{backupStatusBadge(t)}</td>
|
||||||
<td className="text-secondary">{formatDateTime(new Date(t.startTime))}</td>
|
<td className="text-secondary"><TimeAgo value={t.startTime} /></td>
|
||||||
<td className="text-secondary">{formatDuration(t.startTime, t.endTime)}</td>
|
<td className="text-secondary">{formatDuration(t.startTime, t.endTime)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import {
|
import {
|
||||||
api,
|
api,
|
||||||
@@ -208,9 +209,7 @@ export default function Semaphore({ user }: { user: CurrentUser }) {
|
|||||||
<td>{t.name}</td>
|
<td>{t.name}</td>
|
||||||
<td className="text-secondary">{t.projectName}</td>
|
<td className="text-secondary">{t.projectName}</td>
|
||||||
<td className="text-secondary">
|
<td className="text-secondary">
|
||||||
{t.lastTask
|
{t.lastTask ? <TimeAgo value={t.lastTask.end ?? t.lastTask.start ?? t.lastTask.created} /> : "—"}
|
||||||
? formatDateTime(new Date(t.lastTask.end ?? t.lastTask.start ?? t.lastTask.created ?? ""))
|
|
||||||
: "—"}
|
|
||||||
</td>
|
</td>
|
||||||
<td>{semaphoreStatusBadge(t)}</td>
|
<td>{semaphoreStatusBadge(t)}</td>
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ import {
|
|||||||
import ServerPorts from "../components/ServerPorts";
|
import ServerPorts from "../components/ServerPorts";
|
||||||
import ServerTrends from "../components/ServerTrends";
|
import ServerTrends from "../components/ServerTrends";
|
||||||
import ServerActivity from "../components/ServerActivity";
|
import ServerActivity from "../components/ServerActivity";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
|
import UptimeRibbon from "../components/UptimeRibbon";
|
||||||
import ServerTags from "../components/ServerTags";
|
import ServerTags from "../components/ServerTags";
|
||||||
import ServerTaskTable, { SCHEDULE_TYPE_LABELS } from "../components/ServerTaskTable";
|
import ServerTaskTable, { SCHEDULE_TYPE_LABELS } from "../components/ServerTaskTable";
|
||||||
import { formatDateTime } from "../utils/date";
|
import { formatDateTime } from "../utils/date";
|
||||||
@@ -748,7 +750,11 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
|||||||
<dt className="col-5">Created</dt>
|
<dt className="col-5">Created</dt>
|
||||||
<dd className="col-7">{formatDateTime(new Date(server.createdAt))}</dd>
|
<dd className="col-7">{formatDateTime(new Date(server.createdAt))}</dd>
|
||||||
<dt className="col-5">Last seen</dt>
|
<dt className="col-5">Last seen</dt>
|
||||||
<dd className="col-7">{server.lastSeenAt ? formatDateTime(new Date(server.lastSeenAt)) : "never"}</dd>
|
<dd className="col-7">{server.lastSeenAt ? <TimeAgo value={server.lastSeenAt} /> : "never"}</dd>
|
||||||
|
<dt className="col-5">Last 30 days</dt>
|
||||||
|
<dd className="col-7">
|
||||||
|
<UptimeRibbon kind="servers" id={server.id} name={server.name} />
|
||||||
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { Link, useSearchParams } from "react-router-dom";
|
|||||||
import { api, type CurrentUser, type ServerRecord } from "../api/client";
|
import { api, type CurrentUser, type ServerRecord } from "../api/client";
|
||||||
import CopyButton from "../components/CopyButton";
|
import CopyButton from "../components/CopyButton";
|
||||||
import { formatDateTime } from "../utils/date";
|
import { formatDateTime } from "../utils/date";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
|
import UptimeRibbon from "../components/UptimeRibbon";
|
||||||
import { useSortable } from "../hooks/useSortable";
|
import { useSortable } from "../hooks/useSortable";
|
||||||
import SortableTh from "../components/SortableTh";
|
import SortableTh from "../components/SortableTh";
|
||||||
import { usePagination } from "../hooks/usePagination";
|
import { usePagination } from "../hooks/usePagination";
|
||||||
@@ -291,6 +293,7 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
|||||||
direction={sortDir}
|
direction={sortDir}
|
||||||
onSort={requestSort}
|
onSort={requestSort}
|
||||||
/>
|
/>
|
||||||
|
<th>Last 30 days</th>
|
||||||
<th className="w-1">Actions</th>
|
<th className="w-1">Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -307,7 +310,10 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
|||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="text-secondary">{s.apiTokenPrefix}…</td>
|
<td className="text-secondary">{s.apiTokenPrefix}…</td>
|
||||||
<td>{s.lastSeenAt ? formatDateTime(new Date(s.lastSeenAt)) : "never"}</td>
|
<td>{s.lastSeenAt ? <TimeAgo value={s.lastSeenAt} /> : "never"}</td>
|
||||||
|
<td>
|
||||||
|
<UptimeRibbon kind="servers" id={s.id} name={s.name} />
|
||||||
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<div className="btn-list flex-nowrap">
|
<div className="btn-list flex-nowrap">
|
||||||
<button className="btn btn-sm" onClick={() => rotateToken(s.id)}>
|
<button className="btn btn-sm" onClick={() => rotateToken(s.id)}>
|
||||||
@@ -325,7 +331,7 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
|||||||
))}
|
))}
|
||||||
{sortedServers?.length === 0 && (
|
{sortedServers?.length === 0 && (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={6} className="text-secondary text-center">
|
<td colSpan={7} className="text-secondary text-center">
|
||||||
No servers registered yet.
|
No servers registered yet.
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -410,7 +416,10 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="text-secondary small mt-2">
|
<div className="text-secondary small mt-2">
|
||||||
{s.lastSeenAt ? `Last seen ${formatDateTime(new Date(s.lastSeenAt))}` : "Never reported"}
|
{s.lastSeenAt ? <>Last seen <TimeAgo value={s.lastSeenAt} /></> : "Never reported"}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2">
|
||||||
|
<UptimeRibbon kind="servers" id={s.id} name={s.name} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import TimeAgo from "../components/TimeAgo";
|
||||||
import { api, type SessionSummary } from "../api/client";
|
import { api, type SessionSummary } from "../api/client";
|
||||||
import { formatDateTime } from "../utils/date";
|
import { formatDateTime } from "../utils/date";
|
||||||
import { useSortable } from "../hooks/useSortable";
|
import { useSortable } from "../hooks/useSortable";
|
||||||
@@ -148,7 +149,7 @@ export default function Sessions() {
|
|||||||
<td>{s.role ?? <span className="text-secondary">unknown user</span>}</td>
|
<td>{s.role ?? <span className="text-secondary">unknown user</span>}</td>
|
||||||
<td>{s.ip ?? "—"}</td>
|
<td>{s.ip ?? "—"}</td>
|
||||||
<td className="text-secondary">{friendlyUserAgent(s.userAgent)}</td>
|
<td className="text-secondary">{friendlyUserAgent(s.userAgent)}</td>
|
||||||
<td>{formatDateTime(new Date(s.lastAccess))}</td>
|
<td><TimeAgo value={s.lastAccess} /></td>
|
||||||
<td>{s.expiresAt ? formatDateTime(new Date(s.expiresAt)) : "—"}</td>
|
<td>{s.expiresAt ? formatDateTime(new Date(s.expiresAt)) : "—"}</td>
|
||||||
<td>
|
<td>
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -492,6 +492,159 @@ main:focus {
|
|||||||
border-bottom: 0;
|
border-bottom: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Uptime ribbon: one bar per day for the last 30 days. ── */
|
||||||
|
.uptime {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 260px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The bars share whatever width there is, so the strip fits a narrow card as well as a table cell. */
|
||||||
|
.uptime-ribbon {
|
||||||
|
display: flex;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 60px;
|
||||||
|
gap: 1px;
|
||||||
|
height: 18px;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.uptime-ribbon > i {
|
||||||
|
display: block;
|
||||||
|
flex: 1 1 0;
|
||||||
|
min-width: 1px;
|
||||||
|
border-radius: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table .uptime {
|
||||||
|
min-width: 190px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.uptime-up {
|
||||||
|
background: var(--tblr-green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.uptime-some {
|
||||||
|
background: var(--tblr-yellow);
|
||||||
|
}
|
||||||
|
|
||||||
|
.uptime-down {
|
||||||
|
background: var(--tblr-red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.uptime-none {
|
||||||
|
background: var(--tblr-border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.uptime-percent {
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
white-space: nowrap;
|
||||||
|
color: var(--tblr-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Maintenance timeline: windows along a time axis, one row per target. ── */
|
||||||
|
.timeline-scroll {
|
||||||
|
overflow: auto;
|
||||||
|
max-height: 420px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline {
|
||||||
|
min-width: 640px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
min-height: 28px;
|
||||||
|
border-bottom: 1px solid var(--tblr-border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-label {
|
||||||
|
flex: 0 0 160px;
|
||||||
|
padding-right: 0.75rem;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
position: sticky;
|
||||||
|
left: 0;
|
||||||
|
z-index: 2;
|
||||||
|
background: var(--tblr-card-bg, var(--tblr-bg-surface));
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-track {
|
||||||
|
position: relative;
|
||||||
|
flex: 1;
|
||||||
|
height: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-axis {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 3;
|
||||||
|
background: var(--tblr-card-bg, var(--tblr-bg-surface));
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-axis .timeline-track {
|
||||||
|
height: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-tick {
|
||||||
|
position: absolute;
|
||||||
|
top: 4px;
|
||||||
|
padding-left: 3px;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
color: var(--tblr-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-grid {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
width: 1px;
|
||||||
|
background: var(--tblr-border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-bar,
|
||||||
|
.timeline-key {
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-bar {
|
||||||
|
position: absolute;
|
||||||
|
top: 6px;
|
||||||
|
bottom: 6px;
|
||||||
|
min-width: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-key {
|
||||||
|
display: inline-block;
|
||||||
|
width: 1.25rem;
|
||||||
|
height: 0.7rem;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-bar-running {
|
||||||
|
background-color: var(--tblr-blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-bar-scheduled {
|
||||||
|
background-color: color-mix(in srgb, var(--tblr-blue) 25%, transparent);
|
||||||
|
border: 1px solid var(--tblr-blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
.timeline-bar-union {
|
||||||
|
background-color: var(--tblr-orange);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Windows mirrored from Uptime Kuma's own schedule get diagonal stripes on top of their colour. */
|
||||||
|
.timeline-bar-mirrored {
|
||||||
|
background-image: repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.45) 0 3px, transparent 3px 6px);
|
||||||
|
}
|
||||||
|
|
||||||
/* ── The wall display: a full-screen status board, big enough to read across a room. ── */
|
/* ── The wall display: a full-screen status board, big enough to read across a room. ── */
|
||||||
.wall {
|
.wall {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
Reference in new issue
Block a user