From 906220040e1809c49285f995e8bb2dd3221701ce Mon Sep 17 00:00:00 2001 From: Bobban Rydh Date: Fri, 16 Oct 2026 21:55:04 +0200 Subject: [PATCH] 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 --- DATABASE.md | 4 +- README.md | 30 + server/drizzle/0021_conscious_snowbird.sql | 1 + server/drizzle/meta/0021_snapshot.json | 1966 +++++++++++++++++ server/drizzle/meta/_journal.json | 7 + server/src/app.ts | 2 + server/src/db/schema.ts | 2 + server/src/routes/me.ts | 26 + server/src/routes/uptime.ts | 11 + server/src/services/changesSince.ts | 194 ++ .../src/services/integrationHealthMonitor.ts | 43 + server/src/services/uptimeHistory.ts | 164 ++ server/test/uptimeAndChanges.test.ts | 299 +++ web/src/api/client.ts | 43 + web/src/components/MaintenanceTimeline.tsx | 161 ++ web/src/components/TimeAgo.tsx | 45 + web/src/components/UptimeRibbon.tsx | 43 + web/src/components/WhatChanged.tsx | 101 + web/src/hooks/useUptime.ts | 40 + web/src/pages/Consistency.tsx | 3 +- web/src/pages/Dashboard.tsx | 5 +- web/src/pages/Dns.tsx | 3 +- web/src/pages/Integrations.tsx | 6 + web/src/pages/Maintenance.tsx | 3 + web/src/pages/Ports.tsx | 3 +- web/src/pages/Privacy.tsx | 3 +- web/src/pages/Proxmox.tsx | 3 +- web/src/pages/Semaphore.tsx | 5 +- web/src/pages/ServerDetail.tsx | 8 +- web/src/pages/Servers.tsx | 15 +- web/src/pages/Sessions.tsx | 3 +- web/src/styles.css | 153 ++ 32 files changed, 3380 insertions(+), 15 deletions(-) create mode 100644 server/drizzle/0021_conscious_snowbird.sql create mode 100644 server/drizzle/meta/0021_snapshot.json create mode 100644 server/src/routes/uptime.ts create mode 100644 server/src/services/changesSince.ts create mode 100644 server/src/services/uptimeHistory.ts create mode 100644 server/test/uptimeAndChanges.test.ts create mode 100644 web/src/components/MaintenanceTimeline.tsx create mode 100644 web/src/components/TimeAgo.tsx create mode 100644 web/src/components/UptimeRibbon.tsx create mode 100644 web/src/components/WhatChanged.tsx create mode 100644 web/src/hooks/useUptime.ts diff --git a/DATABASE.md b/DATABASE.md index df3d09d..2170a52 100644 --- a/DATABASE.md +++ b/DATABASE.md @@ -87,6 +87,7 @@ Everyone who has signed in through Authentik. The first one becomes admin. | `created_at` | text NOT NULL | SQLite UTC. | | `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. | +| `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` @@ -98,7 +99,7 @@ Who changed what. Written by the app on every change (see | `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_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. | | `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. | @@ -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: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:healthActiveConditions`, `_internal:automationActiveConditions` | JSON: the problems currently active, so each is announced once and again when it clears, and survives a restart. | diff --git a/README.md b/README.md index 5d7311b..6f697be 100644 --- a/README.md +++ b/README.md @@ -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 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: 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 diff --git a/server/drizzle/0021_conscious_snowbird.sql b/server/drizzle/0021_conscious_snowbird.sql new file mode 100644 index 0000000..04a9490 --- /dev/null +++ b/server/drizzle/0021_conscious_snowbird.sql @@ -0,0 +1 @@ +ALTER TABLE `users` ADD `last_looked_at` text; \ No newline at end of file diff --git a/server/drizzle/meta/0021_snapshot.json b/server/drizzle/meta/0021_snapshot.json new file mode 100644 index 0000000..9f660dd --- /dev/null +++ b/server/drizzle/meta/0021_snapshot.json @@ -0,0 +1,1966 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "59b200f0-033b-4a48-8c8a-7dd8396af8e0", + "prevId": "8a381026-898f-476a-b1be-7990175568a2", + "tables": { + "alert_tickets": { + "name": "alert_tickets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "alert_key": { + "name": "alert_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seen_count": { + "name": "seen_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ticket_number": { + "name": "ticket_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "grouped": { + "name": "grouped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ticketed_at": { + "name": "ticketed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cleared_at": { + "name": "cleared_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "alert_tickets_key_idx": { + "name": "alert_tickets_key_idx", + "columns": [ + "alert_key" + ], + "isUnique": false + } + }, + "foreignKeys": { + "alert_tickets_integration_id_integrations_id_fk": { + "name": "alert_tickets_integration_id_integrations_id_fk", + "tableFrom": "alert_tickets", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "audit_log": { + "name": "audit_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_label": { + "name": "actor_label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "audit_log_actor_user_id_users_id_fk": { + "name": "audit_log_actor_user_id_users_id_fk", + "tableFrom": "audit_log", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "consistency_ignores": { + "name": "consistency_ignores", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "consistency_ignores_key_unique": { + "name": "consistency_ignores_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "diag_log": { + "name": "diag_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation": { + "name": "operation", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "latency_ms": { + "name": "latency_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_providers": { + "name": "dns_providers", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_type": { + "name": "provider_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "dns_providers_credential_id_integration_credentials_id_fk": { + "name": "dns_providers_credential_id_integration_credentials_id_fk", + "tableFrom": "dns_providers", + "tableTo": "integration_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_records_cache": { + "name": "dns_records_cache", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_id": { + "name": "provider_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_id": { + "name": "record_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ttl": { + "name": "ttl", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "priority": { + "name": "priority", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxied": { + "name": "proxied", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "dns_records_cache_provider_id_dns_providers_id_fk": { + "name": "dns_records_cache_provider_id_dns_providers_id_fk", + "tableFrom": "dns_records_cache", + "tableTo": "dns_providers", + "columnsFrom": [ + "provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_zones_cache": { + "name": "dns_zones_cache", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_id": { + "name": "provider_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_name": { + "name": "zone_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "synced_at": { + "name": "synced_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "dns_zones_cache_provider_zone_idx": { + "name": "dns_zones_cache_provider_zone_idx", + "columns": [ + "provider_id", + "zone_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "dns_zones_cache_provider_id_dns_providers_id_fk": { + "name": "dns_zones_cache_provider_id_dns_providers_id_fk", + "tableFrom": "dns_zones_cache", + "tableTo": "dns_providers", + "columnsFrom": [ + "provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "domains": { + "name": "domains", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'manual'" + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "registrar": { + "name": "registrar", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lookup_source": { + "name": "lookup_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_ok_at": { + "name": "last_checked_ok_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "domains_name_unique": { + "name": "domains_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "integration_credentials": { + "name": "integration_credentials", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encrypted_secret": { + "name": "encrypted_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "integrations": { + "name": "integrations", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_url": { + "name": "base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "integrations_credential_id_integration_credentials_id_fk": { + "name": "integrations_credential_id_integration_credentials_id_fk", + "tableFrom": "integrations", + "tableTo": "integration_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ipam_entries": { + "name": "ipam_entries", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "vendor": { + "name": "vendor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "ipam_entries_ip_address_unique": { + "name": "ipam_entries_ip_address_unique", + "columns": [ + "ip_address" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_aliases": { + "name": "maintenance_aliases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "address": { + "name": "address", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "maintenance_aliases_unique_idx": { + "name": "maintenance_aliases_unique_idx", + "columns": [ + "address", + "target_type", + "target_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_windows": { + "name": "maintenance_windows", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ends_at": { + "name": "ends_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "notification_queue": { + "name": "notification_queue", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "port_forwards": { + "name": "port_forwards", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_port": { + "name": "external_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'tcp'" + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "destination": { + "name": "destination", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "internal_port": { + "name": "internal_port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "port_forwards_server_id_servers_id_fk": { + "name": "port_forwards_server_id_servers_id_fk", + "tableFrom": "port_forwards", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "scheduled_tasks": { + "name": "scheduled_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "schedule_type": { + "name": "schedule_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'agent'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "command": { + "name": "command", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schedule_expression": { + "name": "schedule_expression", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "next_run_at": { + "name": "next_run_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_metadata": { + "name": "raw_metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_stale": { + "name": "is_stale", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "scheduled_tasks_server_id_servers_id_fk": { + "name": "scheduled_tasks_server_id_servers_id_fk", + "tableFrom": "scheduled_tasks", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "secrets": { + "name": "secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'generic'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expiry_date": { + "name": "expiry_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "warn_days": { + "name": "warn_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 30 + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_host": { + "name": "check_host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_port": { + "name": "check_port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_links": { + "name": "server_links", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "server_links_server_id_servers_id_fk": { + "name": "server_links_server_id_servers_id_fk", + "tableFrom": "server_links", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_metrics": { + "name": "server_metrics", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metric": { + "name": "metric", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recorded_at": { + "name": "recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "server_metrics_lookup_idx": { + "name": "server_metrics_lookup_idx", + "columns": [ + "server_id", + "metric", + "recorded_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "server_metrics_server_id_servers_id_fk": { + "name": "server_metrics_server_id_servers_id_fk", + "tableFrom": "server_metrics", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_ports": { + "name": "server_ports", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "port": { + "name": "port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'tcp'" + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "open": { + "name": "open", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "last_seen_open_at": { + "name": "last_seen_open_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "server_ports_unique": { + "name": "server_ports_unique", + "columns": [ + "server_id", + "port", + "protocol" + ], + "isUnique": true + } + }, + "foreignKeys": { + "server_ports_server_id_servers_id_fk": { + "name": "server_ports_server_id_servers_id_fk", + "tableFrom": "server_ports", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "servers": { + "name": "servers", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hostname": { + "name": "hostname", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "os_type": { + "name": "os_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'linux'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "api_token_hash": { + "name": "api_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "api_token_prefix": { + "name": "api_token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ip_addresses": { + "name": "ip_addresses", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_model": { + "name": "cpu_model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_cores": { + "name": "cpu_cores", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_load_percent": { + "name": "cpu_load_percent", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mem_total_bytes": { + "name": "mem_total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mem_used_bytes": { + "name": "mem_used_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disks": { + "name": "disks", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "listening_ports": { + "name": "listening_ports", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_port_scan": { + "name": "last_port_scan", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_integration_id": { + "name": "proxmox_integration_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_node": { + "name": "proxmox_node", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_guest_type": { + "name": "proxmox_guest_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_vmid": { + "name": "proxmox_vmid", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hide_proxmox_link": { + "name": "hide_proxmox_link", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + } + }, + "indexes": {}, + "foreignKeys": { + "servers_proxmox_integration_id_integrations_id_fk": { + "name": "servers_proxmox_integration_id_integrations_id_fk", + "tableFrom": "servers", + "tableTo": "integrations", + "columnsFrom": [ + "proxmox_integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tag_definitions": { + "name": "tag_definitions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "tag_definitions_name_unique": { + "name": "tag_definitions_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "oidc_sub": { + "name": "oidc_sub", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'viewer'" + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_login_at": { + "name": "last_login_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "favorites": { + "name": "favorites", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_looked_at": { + "name": "last_looked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_oidc_sub_unique": { + "name": "users_oidc_sub_unique", + "columns": [ + "oidc_sub" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json index 065b3fd..87bb9d1 100644 --- a/server/drizzle/meta/_journal.json +++ b/server/drizzle/meta/_journal.json @@ -148,6 +148,13 @@ "when": 1792093015342, "tag": "0020_salty_black_tom", "breakpoints": true + }, + { + "idx": 21, + "version": "6", + "when": 1792177953255, + "tag": "0021_conscious_snowbird", + "breakpoints": true } ] } \ No newline at end of file diff --git a/server/src/app.ts b/server/src/app.ts index 9a1ba3c..2827196 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -8,6 +8,7 @@ import { env } from "./env.js"; import { resolveDataPath } from "./paths.js"; import { authRouter } from "./auth/router.js"; import { meRouter } from "./routes/me.js"; +import { uptimeRouter } from "./routes/uptime.js"; import { usersRouter } from "./routes/users.js"; import { auditLogRouter } from "./routes/auditLog.js"; import { diagLogRouter } from "./routes/diagLog.js"; @@ -87,6 +88,7 @@ export function createApp() { app.use("/auth", authRouter); app.use("/api/me", meRouter); + app.use("/api/uptime", uptimeRouter); app.use("/api/users", usersRouter); app.use("/api/audit-log", auditLogRouter); app.use("/api/diag-log", diagLogRouter); diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 15dde20..764f4d4 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -18,6 +18,8 @@ export const users = sqliteTable("users", { 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. 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 ────────────────────────────────────────────────────────────── diff --git a/server/src/routes/me.ts b/server/src/routes/me.ts index e69c6d6..235f7da 100644 --- a/server/src/routes/me.ts +++ b/server/src/routes/me.ts @@ -5,6 +5,7 @@ import { db } from "../db/client.js"; import { users } from "../db/schema.js"; import { requireAuth } from "../auth/middleware.js"; import { asyncHandler } from "../utils/asyncHandler.js"; +import { FIRST_LOOKBACK_MS, getChangesSince } from "../services/changesSince.js"; 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)); 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 }); +})); diff --git a/server/src/routes/uptime.ts b/server/src/routes/uptime.ts new file mode 100644 index 0000000..011ccb8 --- /dev/null +++ b/server/src/routes/uptime.ts @@ -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()); +})); diff --git a/server/src/services/changesSince.ts b/server/src/services/changesSince.ts new file mode 100644 index 0000000..126b389 --- /dev/null +++ b/server/src/services/changesSince.ts @@ -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 { + if (!detail) return {}; + try { + const v = JSON.parse(detail); + return v && typeof v === "object" ? (v as Record) : {}; + } 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 { + 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(); + 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(); + 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(); + 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(); + 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 }; +} diff --git a/server/src/services/integrationHealthMonitor.ts b/server/src/services/integrationHealthMonitor.ts index 161b2b9..e1a392c 100644 --- a/server/src/services/integrationHealthMonitor.ts +++ b/server/src/services/integrationHealthMonitor.ts @@ -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 { isSourceInMaintenance } from "./maintenance.js"; import { notifyIntegrationDown, notifyIntegrationRecovered } from "./notify.js"; @@ -6,6 +11,36 @@ interface SourceHealth { consecutiveFailures: number; /** True once a "down" notification has been sent for the current failure streak, so it isn't repeated on every subsequent failure. */ 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 { + 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. */ export async function trackIntegrationHealth(source: string, ok: boolean): Promise { + const seenBefore = health.has(source); const state = health.get(source) ?? { consecutiveFailures: 0, alerted: false }; if (ok) { if (state.alerted) { await notifyIntegrationRecovered(source); } + if (state.recorded || (!seenBefore && (await lastRecordedTransition(source)) === "went_failing")) { + await recordTransition(source, "recovered"); + } health.set(source, { consecutiveFailures: 0, alerted: false }); return; } state.consecutiveFailures += 1; 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) { // 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. diff --git a/server/src/services/uptimeHistory.ts b/server/src/services/uptimeHistory.ts new file mode 100644 index 0000000..b74191a --- /dev/null +++ b/server/src/services/uptimeHistory.ts @@ -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(days).fill(0); + const down = new Array(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 { + 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; + integrations: Record; +} + +export async function getUptime(now: Date = new Date(), days: number = DEFAULT_DAYS): Promise { + 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(); + const sourceEvents = new Map(); + 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; +} diff --git a/server/test/uptimeAndChanges.test.ts b/server/test/uptimeAndChanges.test.ts new file mode 100644 index 0000000..3e7f756 --- /dev/null +++ b/server/test/uptimeAndChanges.test.ts @@ -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 = {}) => ({ + 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((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"; + }); +}); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 23ac73c..9917edf 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -10,6 +10,44 @@ export interface CurrentUser { 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; + integrations: Record; +} + export interface UserRecord { id: number; oidcSub: string; @@ -1110,7 +1148,12 @@ async function request(path: string, init?: RequestInit): Promise { export const api = { me: Object.assign(() => request<{ user: CurrentUser }>("/api/me"), { setFavorites: (paths: string[]) => request<{ favorites: string[] }>("/api/me/favorites", { method: "PUT", body: JSON.stringify({ paths }) }), + changes: () => request("/api/me/changes"), + markChangesSeen: () => request<{ lastLookedAt: string }>("/api/me/changes/seen", { method: "POST" }), }), + uptime: { + get: () => request("/api/uptime"), + }, search: { query: (q: string) => request(`/api/search?q=${encodeURIComponent(q)}`), }, diff --git a/web/src/components/MaintenanceTimeline.tsx b/web/src/components/MaintenanceTimeline.tsx new file mode 100644 index 0000000..463236d --- /dev/null +++ b/web/src/components/MaintenanceTimeline.tsx @@ -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(); + 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 ( +
+
+

Timeline

+
+
+ {RANGES.map((r) => ( + + ))} +
+
+
+
+ {rows.length === 0 ? ( +
Nothing running or scheduled in this time.{further > 0 ? ` ${further} further ahead.` : ""}
+ ) : ( + <> + +
+ + Running + + + Scheduled + + + From Uptime Kuma + + The same windows are listed in the tables below. + {further > 0 && {further} further ahead than this range.} +
+ + )} +
+
+ ); +} diff --git a/web/src/components/TimeAgo.tsx b/web/src/components/TimeAgo.tsx new file mode 100644 index 0000000..b541280 --- /dev/null +++ b/web/src/components/TimeAgo.tsx @@ -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 | 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 ( + + ); +} diff --git a/web/src/components/UptimeRibbon.tsx b/web/src/components/UptimeRibbon.tsx new file mode 100644 index 0000000..27230c0 --- /dev/null +++ b/web/src/components/UptimeRibbon.tsx @@ -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 ( + + + {showPercent ? ( + + {series.percent}% up over the last {report.days} days + + ) : ( + {summary} + )} + + ); +} diff --git a/web/src/components/WhatChanged.tsx b/web/src/components/WhatChanged.tsx new file mode 100644 index 0000000..d37251c --- /dev/null +++ b/web/src/components/WhatChanged.tsx @@ -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 = { 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