- system_alerts: Zustand je Alarm, Meldung nach Karenzzeit genau einmal, Entwarnung nur nach vorheriger Meldung; aktive Alarme im Dashboard. - Lizenzprüfung unterscheidet config/outage/rejected; Ausfall wird alle 10 min wiederholt und nach 30 min gemeldet, Konfigurations-/Ablehnungs- fehler und ungültige Lizenz sofort; Testmodus ohne Schlüssel bleibt still. - Worker meldet Warteschlangen-Stau und needs_review per Discord. - Worker-Herzschlag; die API meldet einen ausgefallenen Worker per Mail an die Superadmins (Discord läuft im Worker). - Migration 040, Doku-Tabelle in betrieb-backup-restore.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8eb8c54aab
commit
e9836f0efd
11 changed files with 227 additions and 11 deletions
|
|
@ -4,6 +4,7 @@ import { requirePermission } from '../../core/auth.js';
|
|||
import { query } from '../../core/db.js';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import type { KcModule } from '../../core/module.js';
|
||||
import { activeAlerts, ALERT_LABEL, heartbeatAgeMs } from '@kc/platform/monitor';
|
||||
|
||||
/** Backup-Zustand aus der Statusdatei des Backup-Laufs (siehe docs/betrieb-backup-restore.md). Ohne Datei: nicht eingerichtet. */
|
||||
async function backupState() {
|
||||
|
|
@ -29,7 +30,10 @@ export const systemModule: KcModule = {
|
|||
requirePermission(req, 'jobs.read');
|
||||
const jobs = await query('SELECT status, COUNT(*) AS n FROM jobs GROUP BY status');
|
||||
const oldest = await one('SELECT MIN(run_at) AS t FROM jobs WHERE status IN (\'scheduled\',\'retrying\')');
|
||||
return { jobs: Object.fromEntries(jobs.map((j) => [j.status, Number(j.n)])), oldestPendingJob: oldest?.t ?? null, serverTime: new Date().toISOString(), backup: await backupState() };
|
||||
const workerAge = await heartbeatAgeMs('worker');
|
||||
const alerts = (await activeAlerts()).map((a) => ({ ...a, label: ALERT_LABEL[a.key] ?? a.key }));
|
||||
return { jobs: Object.fromEntries(jobs.map((j) => [j.status, Number(j.n)])), oldestPendingJob: oldest?.t ?? null, serverTime: new Date().toISOString(), backup: await backupState(),
|
||||
worker: { lastHeartbeatSecondsAgo: workerAge === null ? null : Math.round(workerAge / 1000) }, alerts };
|
||||
});
|
||||
},
|
||||
};
|
||||
|
|
|
|||
27
apps/api/src/ops/watchdog.ts
Normal file
27
apps/api/src/ops/watchdog.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { query } from '../core/db.js';
|
||||
import { sendMail } from '@kc/platform/mail';
|
||||
import { alertText, applyConditions, heartbeatAgeMs, type Condition } from '@kc/platform/monitor';
|
||||
|
||||
/** Ab dieser Herzschlag-Lücke gilt der Worker als ausgefallen (er schreibt jede Minute). */
|
||||
const STALE_MS = 3 * 60_000;
|
||||
|
||||
/** Zustand „Worker arbeitet nicht“ aus dem Herzschlag. Noch nie geschrieben (frische Installation/alter Worker): kein Alarm. */
|
||||
export async function workerDownCondition(): Promise<Condition> {
|
||||
const age = await heartbeatAgeMs('worker');
|
||||
const down = age !== null && age > STALE_MS;
|
||||
return { key: 'worker.down', active: down, detail: down ? `letzter Herzschlag vor ${Math.round(age! / 60_000)} Minuten` : null, graceMs: 2 * 60_000 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Den Ausfall des Workers kann der Worker nicht selbst melden – und Discord läuft im Worker. Die API prüft deshalb
|
||||
* minütlich den Herzschlag und schreibt bei Ausfall/Entwarnung direkt per SMTP an alle aktiven Superadmins (#20/#38).
|
||||
*/
|
||||
export function startWorkerWatchdog(): void {
|
||||
const notify = async (key: string, kind: 'alarm' | 'recovery', detail: string | null) => {
|
||||
const text = alertText(key, kind, detail);
|
||||
const admins = await query("SELECT email FROM users WHERE kind = 'staff' AND staff_role = 'superadmin' AND status = 'active'");
|
||||
for (const a of admins) await sendMail(a.email, 'system_alert', `Kundencenter: ${text}`, `${text}\n\nPrüfen: systemctl status kc-worker; journalctl -u kc-worker -n 100`);
|
||||
};
|
||||
const tick = () => workerDownCondition().then((c) => applyConditions([c], notify)).catch(() => undefined);
|
||||
setInterval(tick, 60_000).unref();
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ import { registerPermissions } from './core/policy.js';
|
|||
import { AppError } from './core/errors.js';
|
||||
import { InvalidTransition } from '@kc/platform/statemachine';
|
||||
import { modules } from './modules/index.js';
|
||||
import { startWorkerWatchdog } from './ops/watchdog.js';
|
||||
|
||||
export async function buildApp() {
|
||||
const app = Fastify({
|
||||
|
|
@ -40,4 +41,5 @@ export async function buildApp() {
|
|||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
const app = await buildApp();
|
||||
await app.listen({ port: config.port, host: '127.0.0.1' });
|
||||
startWorkerWatchdog();
|
||||
}
|
||||
|
|
|
|||
48
apps/api/test/monitor.test.ts
Normal file
48
apps/api/test/monitor.test.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { run } from '../src/core/db.js';
|
||||
import { applyConditions, heartbeat, workerConditions } from '@kc/platform/monitor';
|
||||
import { workerDownCondition } from '../src/ops/watchdog.js';
|
||||
|
||||
describe('Betriebsalarme mit Entwarnung (#20/#38)', () => {
|
||||
it('meldet erst nach der Karenzzeit, genau einmal, und entwarnt danach einmal', async () => {
|
||||
const sent: string[] = []; const notify = async (k: string, kind: string) => { sent.push(`${k}:${kind}`); };
|
||||
const t0 = new Date('2026-10-06T10:00:00Z'); const at = (min: number) => new Date(t0.getTime() + min * 60_000);
|
||||
const c = (active: boolean) => [{ key: 'test.queue', active, detail: active ? 'Stau' : null, graceMs: 5 * 60_000 }];
|
||||
await applyConditions(c(true), notify, at(0)); await applyConditions(c(true), notify, at(3));
|
||||
expect(sent).toEqual([]); // kurzer Aussetzer: noch nichts
|
||||
await applyConditions(c(true), notify, at(6)); await applyConditions(c(true), notify, at(7));
|
||||
expect(sent).toEqual(['test.queue:alarm']); // dedupliziert
|
||||
await applyConditions(c(false), notify, at(8)); await applyConditions(c(false), notify, at(9));
|
||||
expect(sent).toEqual(['test.queue:alarm', 'test.queue:recovery']);
|
||||
});
|
||||
it('kurzer Vorfall unterhalb der Karenz: weder Alarm noch Entwarnung', async () => {
|
||||
const sent: string[] = []; const notify = async (k: string, kind: string) => { sent.push(`${k}:${kind}`); };
|
||||
const t = new Date('2026-10-06T11:00:00Z');
|
||||
await applyConditions([{ key: 'test.blip', active: true, graceMs: 60_000 }], notify, t);
|
||||
await applyConditions([{ key: 'test.blip', active: false }], notify, new Date(t.getTime() + 30_000));
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
it('unterscheidet Lizenzserver-Ausfall von Konfigurationsproblemen; ohne Schlüssel (Testmodus) kein Alarm', async () => {
|
||||
await run("UPDATE license_state SET license_key_enc = 'x', last_error = 'Netzwerkfehler: timeout', last_error_kind = 'outage', valid = 1, checked_at = UTC_TIMESTAMP(3) WHERE id = 1");
|
||||
let c = Object.fromEntries((await workerConditions()).map((x) => [x.key, x.active]));
|
||||
expect(c['license.unreachable']).toBe(true); expect(c['license.problem']).toBe(false);
|
||||
await run("UPDATE license_state SET last_error = 'Program-Key ungültig', last_error_kind = 'config' WHERE id = 1");
|
||||
c = Object.fromEntries((await workerConditions()).map((x) => [x.key, x.active]));
|
||||
expect(c['license.unreachable']).toBe(false); expect(c['license.problem']).toBe(true);
|
||||
await run('UPDATE license_state SET license_key_enc = NULL WHERE id = 1');
|
||||
c = Object.fromEntries((await workerConditions()).map((x) => [x.key, x.active]));
|
||||
expect(c['license.unreachable']).toBe(false); expect(c['license.problem']).toBe(false);
|
||||
await run('UPDATE license_state SET last_error = NULL, last_error_kind = NULL WHERE id = 1');
|
||||
});
|
||||
it('Warteschlangen-Stau und Aufträge zur Prüfung werden erkannt', async () => {
|
||||
await run("INSERT INTO jobs (id, type, payload, status, run_at) VALUES (UUID(), 'x.test', '{}', 'scheduled', DATE_SUB(UTC_TIMESTAMP(3), INTERVAL 30 MINUTE)), (UUID(), 'x.test', '{}', 'needs_review', UTC_TIMESTAMP(3))");
|
||||
const c = Object.fromEntries((await workerConditions()).map((x) => [x.key, x.active]));
|
||||
expect(c['jobs.backlog']).toBe(true); expect(c['jobs.needs_review']).toBe(true);
|
||||
await run("DELETE FROM jobs WHERE type = 'x.test'");
|
||||
});
|
||||
it('Worker-Herzschlag: frisch = in Ordnung, veraltet = ausgefallen', async () => {
|
||||
await heartbeat('worker'); expect((await workerDownCondition()).active).toBe(false);
|
||||
await run("UPDATE system_heartbeats SET at = DATE_SUB(UTC_TIMESTAMP(3), INTERVAL 10 MINUTE) WHERE name = 'worker'");
|
||||
expect((await workerDownCondition()).active).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
@ -5,7 +5,7 @@ import { api, errMsg } from '@/lib/api';
|
|||
import { useSession } from '@/lib/session';
|
||||
import { Alert, Empty, InvoiceStatusBadge, TicketStatusBadge, eur, fmt, fmtDay } from '@/components/ui';
|
||||
|
||||
interface Sys { jobs: Record<string, number>; oldestPendingJob: string | null; backup?: { configured: boolean; lastRunAt?: string | null; ok?: boolean; ageHours?: number | null; stale?: boolean; error?: string | null; sizeBytes?: number | null; targets?: { name: string; ok: boolean }[]; lastRestoreTestAt?: string | null; restoreOk?: boolean | null; restoreStale?: boolean } }
|
||||
interface Sys { jobs: Record<string, number>; oldestPendingJob: string | null; alerts?: { key: string; label: string; since: string; detail: string | null }[]; worker?: { lastHeartbeatSecondsAgo: number | null }; backup?: { configured: boolean; lastRunAt?: string | null; ok?: boolean; ageHours?: number | null; stale?: boolean; error?: string | null; sizeBytes?: number | null; targets?: { name: string; ok: boolean }[]; lastRestoreTestAt?: string | null; restoreOk?: boolean | null; restoreStale?: boolean } }
|
||||
interface RecentTicket { id: string; number: string; orgName: string; subject: string; status: string; lastMessageAt: string }
|
||||
interface OpenInvoice { id: string; number: string | null; orgName: string; status: string; overdue: boolean; dueDate: string | null; totalGrossCents: number }
|
||||
|
||||
|
|
@ -64,6 +64,8 @@ export default function Dashboard() {
|
|||
{customers !== null && <div className="card"><div className="stat">{customers}</div><p className="muted">Kunden</p><Link href="/admin/kunden">Kunden verwalten</Link></div>}
|
||||
{licenses && <div className="card"><div className="stat">{licenses.active}</div><p className="muted">Aktive Lizenzen</p>{licenses.expiring > 0 && <p className="small"><span className="badge warn"><span aria-hidden="true">▲</span>{licenses.expiring} laufen in 30 Tagen ab</span></p>}{licenses.unassigned > 0 && <p className="small"><span className="badge warn"><span aria-hidden="true">▲</span>{licenses.unassigned} ohne Kunde</span></p>}<Link href="/lizenzen">Lizenzen verwalten</Link></div>}
|
||||
{sys && <div className="card"><div className="stat">{sys.jobs.scheduled ?? 0}</div><p className="muted">Wartende Aufträge</p></div>}
|
||||
{sys?.alerts && sys.alerts.length > 0 && <div className="card" role="alert"><h3>Betriebsalarme</h3>
|
||||
<ul className="small" style={{ margin: 0, paddingLeft: 18 }}>{sys.alerts.map((a) => <li key={a.key}><strong>{a.label}</strong>{a.detail ? ` – ${a.detail}` : ''} <span className="muted">(seit {new Date(a.since).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })})</span></li>)}</ul></div>}
|
||||
{sys?.backup && <div className="card"><h3>Backup</h3><p className="small"><Link href="/einstellungen/backup">Details und Einstellungen</Link></p>
|
||||
{!sys.backup.configured ? <><p className="muted">Nicht eingerichtet.</p><span className="badge warn"><span aria-hidden="true">▲</span>Kein Backup</span></>
|
||||
: <><p>{sys.backup.stale ? <span className="badge err"><span aria-hidden="true">✕</span>{sys.backup.ok ? 'Veraltet' : 'Fehlgeschlagen'}</span> : <span className="badge ok"><span aria-hidden="true">✓</span>Aktuell</span>}</p>
|
||||
|
|
|
|||
|
|
@ -49,11 +49,30 @@ setInterval(() => void checkBackup(), 3600_000);
|
|||
// Fehlschlag, solange kein Programm-Key/Lizenzschlüssel hinterlegt ist (siehe LicenseCheckError) - dann
|
||||
// einfach weiter versuchen, keine Alarmierung (Betreiber hat die Lizenzierung schlicht noch nicht eingerichtet).
|
||||
import { checkLicenseNow, LicenseCheckError } from '@kc/platform/license';
|
||||
// Ausfall des Lizenzservers (outage) wird alle 10 Minuten erneut versucht und nach 30 Minuten gemeldet (siehe
|
||||
// Betriebsalarme unten); Konfigurationsfehler/Ablehnungen werden ebenfalls gemeldet, aber nicht im Takt wiederholt.
|
||||
let licenseOutage = false;
|
||||
const checkLicense = async () => {
|
||||
try { await checkLicenseNow(); }
|
||||
catch (e) { if (!(e instanceof LicenseCheckError)) log(`Lizenzprüfung fehlgeschlagen: ${(e as Error).message}`); }
|
||||
try { await checkLicenseNow(); licenseOutage = false; }
|
||||
catch (e) {
|
||||
licenseOutage = e instanceof LicenseCheckError && e.kind === 'outage';
|
||||
const quiet = e instanceof LicenseCheckError && e.kind === 'config'; // z. B. noch kein Schlüssel hinterlegt (Testmodus)
|
||||
if (!quiet) log(`Lizenzprüfung fehlgeschlagen: ${(e as Error).message}`);
|
||||
}
|
||||
};
|
||||
setInterval(() => void checkLicense(), 12 * 3600_000); void checkLicense();
|
||||
setInterval(() => { if (licenseOutage) void checkLicense(); }, 10 * 60_000);
|
||||
|
||||
// Betriebsalarme mit Entwarnung (#20/#38): Lizenzserver, Warteschlangen-Stau, Aufträge zur Prüfung → Discord-Meldung.
|
||||
// Der Zustand ist zusätzlich im Dashboard sichtbar. Den Ausfall dieses Workers selbst meldet die API (Herzschlag).
|
||||
import { applyConditions, heartbeat, workerConditions } from '@kc/platform/monitor';
|
||||
const monitor = async () => {
|
||||
try {
|
||||
await heartbeat('worker');
|
||||
await applyConditions(await workerConditions(), (key, kind, detail) => enqueue('discord.notify', { event: 'system.alert', key, kind, detail }, { idempotencyKey: `system.alert:${key}:${kind}:${Date.now()}` }));
|
||||
} catch (e) { log(`Betriebsalarme: Prüfung fehlgeschlagen: ${(e as Error).message}`); }
|
||||
};
|
||||
setInterval(() => void monitor(), 60_000); void monitor();
|
||||
|
||||
// Vertrags-Erinnerung: ~30 Tage vor Laufzeitende Mail mit "Behalten"/"Kündigen"-Link (einmal je Vertrag,
|
||||
// markiert über renewal_reminder_sent_at). Unabhängig von processContractLifecycle oben, die nur zum
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { pool } from '@kc/platform/db';
|
|||
import { notifyAdmin, postTicketMessage } from './discord.js';
|
||||
import { JobFailure } from '@kc/platform/jobs';
|
||||
import { sendTemplateMail } from '@kc/platform/mail';
|
||||
import { alertText } from '@kc/platform/monitor';
|
||||
import { executeAction, executeChild, provisionOrder, syncInstance, type ChildPayload, type ExecutePayload } from '@kc/connectors';
|
||||
|
||||
// Kennung dieses Worker-Prozesses (nur zur Diagnose in locked_by, kein Sicherheitsmerkmal).
|
||||
|
|
@ -21,6 +22,7 @@ const handlers: Record<string, Handler> = {
|
|||
: p.event === 'restoretest.failed' ? `⚠ Wiederherstellungstest fehlgeschlagen: ${p.detail ?? ''}`.trim()
|
||||
: p.event === 'ticket.created' ? `🎫 Neues Ticket ${p.number}: ${p.subject ?? ''}`.trim()
|
||||
: p.event === 'ticket.message' ? `🎫 Neue Nachricht zu Ticket ${p.number}`
|
||||
: p.event === 'system.alert' ? alertText(String(p.key), p.kind === 'recovery' ? 'recovery' : 'alarm', p.detail ?? null)
|
||||
: p.event === 'invoice.issued' ? `🧾 Rechnung ${p.number} ausgestellt (${(Number(p.gross ?? 0) / 100).toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })})` : null; // keine personenbezogenen Daten
|
||||
if (!text) throw new Error(`Unbekanntes Ereignis: ${p.event}`);
|
||||
const r = await notifyAdmin(text, String(p.event).startsWith('ticket.') ? 'tickets' : 'admin');
|
||||
|
|
|
|||
|
|
@ -83,3 +83,16 @@ DDL ist in MariaDB nicht transaktional. Bricht eine Migration mitten drin ab, st
|
|||
1. Fehlermeldung lesen, Datenbankzustand prüfen (`SELECT * FROM schema_migrations_dirty`), Ursache beheben (z. B. Datenkonflikt bereinigen). Die Migrationsdatei dabei **nicht** ändern – sonst ist Fortsetzen nicht mehr sicher und wird abgelehnt.
|
||||
2. `pnpm migrate --resume` setzt bei der fehlgeschlagenen Anweisung fort; die bereits angewendeten werden nicht wiederholt.
|
||||
3. Lässt sich der Zustand nicht sauber herstellen: Sicherung von vor dem Deploy in eine Wegwerf-Datenbank prüfen und einspielen (siehe oben).
|
||||
|
||||
## Betriebsalarme und Entwarnung
|
||||
Zustände werden minütlich geprüft und in `system_alerts` geführt; aktive Alarme stehen im Dashboard (Karte „Betriebsalarme“), auch wenn Discord/Mail nicht eingerichtet sind. Gemeldet wird je Vorfall einmal nach der Karenzzeit, die Entwarnung folgt, sobald der Zustand behoben ist.
|
||||
|
||||
| Zustand | Prüft | Karenz | Meldung |
|
||||
|---|---|---|---|
|
||||
| Lizenzserver nicht erreichbar (Netzwerk, HTTP 5xx/429) | Worker, Wiederholung alle 10 min | 30 min | Discord (Ticket-/Admin-Kanal) |
|
||||
| Problem mit der eigenen Lizenz (Program-Key falsch, Antwort abgelehnt, Lizenz ungültig/abgelaufen) | Worker | sofort | Discord |
|
||||
| Warteschlange staut sich (fällige Aufträge > 10 min unbearbeitet) | Worker | 5 min | Discord |
|
||||
| Aufträge warten auf Prüfung (`needs_review`) | Worker | sofort | Discord |
|
||||
| kc-worker arbeitet nicht (Herzschlag > 3 min alt) | API | 2 min | Mail an alle aktiven Superadmins (Discord läuft im Worker) |
|
||||
|
||||
Ohne hinterlegten Lizenzschlüssel (Testmodus) gibt es keine Lizenzalarme.
|
||||
|
|
|
|||
16
migrations/040_system_alerts.sql
Normal file
16
migrations/040_system_alerts.sql
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
-- Betriebsalarme mit Entwarnung (#20/#38): je Zustand eine Zeile, Meldung erst nach einer Karenzzeit, Entwarnung nur,
|
||||
-- wenn vorher gemeldet wurde. Herzschlag der Dienste, damit ein ausgefallener Worker erkannt wird.
|
||||
CREATE TABLE system_alerts (
|
||||
alert_key VARCHAR(100) PRIMARY KEY,
|
||||
active TINYINT(1) NOT NULL DEFAULT 0,
|
||||
since DATETIME(3) NULL,
|
||||
detail VARCHAR(500) NULL,
|
||||
notified_at DATETIME(3) NULL,
|
||||
resolved_at DATETIME(3) NULL,
|
||||
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
|
||||
);
|
||||
CREATE TABLE system_heartbeats (
|
||||
name VARCHAR(50) PRIMARY KEY,
|
||||
at DATETIME(3) NOT NULL
|
||||
);
|
||||
ALTER TABLE license_state ADD COLUMN last_error_kind ENUM('config','outage','rejected') NULL AFTER last_error;
|
||||
|
|
@ -55,7 +55,11 @@ async function refreshSigningKeys(): Promise<void> {
|
|||
for (const k of data.keys) await run('INSERT INTO license_signing_keys (kid, alg, n_hex, e_hex, status) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE alg=VALUES(alg), n_hex=VALUES(n_hex), e_hex=VALUES(e_hex), status=VALUES(status)', [k.kid, k.alg, k.n, k.e, k.status]);
|
||||
}
|
||||
|
||||
export class LicenseCheckError extends Error {}
|
||||
/** kind: config = Einrichtung fehlt/falsch (kein Ausfall), outage = Lizenzserver nicht erreichbar/Serverfehler,
|
||||
* rejected = Antwort abgelehnt (Signatur, Replay, fremde Installation). Steuert die Alarmierung (#20). */
|
||||
export class LicenseCheckError extends Error {
|
||||
constructor(message: string, readonly kind: 'config' | 'outage' | 'rejected' = 'config') { super(message); }
|
||||
}
|
||||
|
||||
/** Fragt /license/verify live ab, prüft die Signatur und schreibt das Ergebnis in license_state.
|
||||
* Wirft bei fehlender Konfiguration oder Netzwerkfehler (ruft NICHT selbst den gecachten Zustand ab -
|
||||
|
|
@ -75,13 +79,16 @@ export async function checkLicenseNow(): Promise<VerifyResult> {
|
|||
body: JSON.stringify({ licenseKey, instanceId: row.instance_id }), signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
} catch (e) {
|
||||
await run('UPDATE license_state SET last_error = ? WHERE id = 1', [`Netzwerkfehler: ${(e as Error).message}`.slice(0, 500)]);
|
||||
throw new LicenseCheckError(`Lizenzserver nicht erreichbar: ${(e as Error).message}`);
|
||||
await run("UPDATE license_state SET last_error = ?, last_error_kind = 'outage' WHERE id = 1", [`Netzwerkfehler: ${(e as Error).message}`.slice(0, 500)]);
|
||||
throw new LicenseCheckError(`Lizenzserver nicht erreichbar: ${(e as Error).message}`, 'outage');
|
||||
}
|
||||
if (res.status === 401) { await run("UPDATE license_state SET last_error = ?, last_error_kind = 'config' WHERE id = 1", ['Program-Key ungültig (LICENSE_PROGRAM_KEY)']); throw new LicenseCheckError('Program-Key ungültig', 'config'); }
|
||||
if (!res.ok) {
|
||||
const msg = `Lizenzserver: HTTP ${res.status}`; const kind = res.status >= 500 || res.status === 429 ? 'outage' as const : 'rejected' as const;
|
||||
await run('UPDATE license_state SET last_error = ?, last_error_kind = ? WHERE id = 1', [msg, kind]); throw new LicenseCheckError(msg, kind);
|
||||
}
|
||||
if (res.status === 401) { await run('UPDATE license_state SET last_error = ? WHERE id = 1', ['Program-Key ungültig (LICENSE_PROGRAM_KEY)']); throw new LicenseCheckError('Program-Key ungültig'); }
|
||||
if (!res.ok) { const msg = `Lizenzserver: HTTP ${res.status}`; await run('UPDATE license_state SET last_error = ? WHERE id = 1', [msg]); throw new LicenseCheckError(msg); }
|
||||
const data = await res.json() as VerifyResult;
|
||||
const fail = async (msg: string): Promise<never> => { await run('UPDATE license_state SET last_error = ? WHERE id = 1', [msg]); throw new LicenseCheckError(msg); };
|
||||
const fail = async (msg: string): Promise<never> => { await run("UPDATE license_state SET last_error = ?, last_error_kind = 'rejected' WHERE id = 1", [msg]); throw new LicenseCheckError(msg, 'rejected'); };
|
||||
|
||||
// Signatur ist Pflicht: übernommen werden NUR Werte aus dem geprüften Payload, nie die äußeren JSON-Felder
|
||||
// (die könnte ein Mann-in-der-Mitte oder ein vorgetäuschter Server beliebig setzen).
|
||||
|
|
@ -111,7 +118,7 @@ export async function checkLicenseNow(): Promise<VerifyResult> {
|
|||
|
||||
await run(
|
||||
`UPDATE license_state SET valid=?, message=?, plan=?, modules_json=?, expires_at=?, user_limit=?, customer_limit=?,
|
||||
entitlement_version=?, is_trial=?, addons_json=?, server_time=?, checked_at=UTC_TIMESTAMP(3), last_error=NULL WHERE id=1`,
|
||||
entitlement_version=?, is_trial=?, addons_json=?, server_time=?, checked_at=UTC_TIMESTAMP(3), last_error=NULL, last_error_kind=NULL WHERE id=1`,
|
||||
[signed.valid, signed.message, signed.plan, JSON.stringify(signed.modules), signed.expiresAt ? new Date(signed.expiresAt) : null,
|
||||
signed.userLimit, signed.customerLimit, signed.entitlementVersion, signed.trial, JSON.stringify(signed.addons), serverTime],
|
||||
);
|
||||
|
|
|
|||
76
packages/platform/src/monitor.ts
Normal file
76
packages/platform/src/monitor.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { one, query, run, tx } from './db.js';
|
||||
|
||||
/**
|
||||
* Betriebsalarme mit Entwarnung (#20/#38). Ein Zustand (z. B. „Lizenzserver nicht erreichbar“) wird bei jeder Prüfung
|
||||
* als aktiv/inaktiv gemeldet. Gemeldet wird erst, wenn er die Karenzzeit überdauert (kurze Aussetzer lösen nichts
|
||||
* aus), und je Vorfall genau einmal; die Entwarnung folgt nur, wenn vorher gemeldet wurde. Der Zustand ist in der
|
||||
* Oberfläche auch ohne Discord/Mail sichtbar (GET /admin/system → alerts).
|
||||
*/
|
||||
export interface Condition { key: string; active: boolean; detail?: string | null; graceMs?: number }
|
||||
export type AlertNotify = (key: string, kind: 'alarm' | 'recovery', detail: string | null) => Promise<void>;
|
||||
|
||||
export async function applyConditions(conditions: Condition[], notify: AlertNotify, now = new Date()): Promise<void> {
|
||||
for (const c of conditions) {
|
||||
const action = await tx(async (cn) => {
|
||||
await run('INSERT IGNORE INTO system_alerts (alert_key, active) VALUES (?, 0)', [c.key], cn);
|
||||
const row = (await one('SELECT * FROM system_alerts WHERE alert_key = ? FOR UPDATE', [c.key], cn))!;
|
||||
const detail = c.detail?.slice(0, 500) ?? null;
|
||||
if (c.active) {
|
||||
const since = row.active ? new Date(row.since as Date) : now;
|
||||
if (!row.active) await run('UPDATE system_alerts SET active = 1, since = ?, notified_at = NULL, resolved_at = NULL, detail = ? WHERE alert_key = ?', [now, detail, c.key], cn);
|
||||
else await run('UPDATE system_alerts SET detail = ? WHERE alert_key = ?', [detail, c.key], cn);
|
||||
if (!row.notified_at && now.getTime() - since.getTime() >= (c.graceMs ?? 0)) {
|
||||
await run('UPDATE system_alerts SET notified_at = ? WHERE alert_key = ?', [now, c.key], cn);
|
||||
return { kind: 'alarm' as const, detail };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!row.active) return null;
|
||||
await run('UPDATE system_alerts SET active = 0, resolved_at = ? WHERE alert_key = ?', [now, c.key], cn);
|
||||
return row.notified_at ? { kind: 'recovery' as const, detail: row.detail as string | null } : null;
|
||||
});
|
||||
if (action) await notify(c.key, action.kind, action.detail);
|
||||
}
|
||||
}
|
||||
|
||||
export async function heartbeat(name: string): Promise<void> {
|
||||
await run('INSERT INTO system_heartbeats (name, at) VALUES (?, UTC_TIMESTAMP(3)) ON DUPLICATE KEY UPDATE at = VALUES(at)', [name]);
|
||||
}
|
||||
export async function heartbeatAgeMs(name: string): Promise<number | null> {
|
||||
const r = await one('SELECT TIMESTAMPDIFF(MICROSECOND, at, UTC_TIMESTAMP(3)) AS us FROM system_heartbeats WHERE name = ?', [name]);
|
||||
return r ? Number(r.us) / 1000 : null;
|
||||
}
|
||||
export async function activeAlerts(): Promise<{ key: string; since: Date; detail: string | null; notified: boolean }[]> {
|
||||
const rows = await query('SELECT alert_key, since, detail, notified_at FROM system_alerts WHERE active = 1 ORDER BY since');
|
||||
return rows.map((r) => ({ key: r.alert_key, since: r.since, detail: r.detail, notified: !!r.notified_at }));
|
||||
}
|
||||
|
||||
/** Texte der Meldungen (ohne personenbezogene Daten). */
|
||||
export const ALERT_LABEL: Record<string, string> = {
|
||||
'license.unreachable': 'Lizenzserver nicht erreichbar',
|
||||
'license.problem': 'Problem mit der eigenen Lizenz (Konfiguration oder Ablehnung)',
|
||||
'jobs.backlog': 'Auftragswarteschlange staut sich',
|
||||
'jobs.needs_review': 'Aufträge warten auf Prüfung',
|
||||
'worker.down': 'Hintergrunddienst (kc-worker) arbeitet nicht',
|
||||
};
|
||||
export const alertText = (key: string, kind: 'alarm' | 'recovery', detail: string | null): string =>
|
||||
kind === 'alarm' ? `⚠ ${ALERT_LABEL[key] ?? key}${detail ? `: ${detail}` : ''}` : `✅ Entwarnung: ${ALERT_LABEL[key] ?? key} – wieder in Ordnung`;
|
||||
|
||||
/** Zustände, die der Worker selbst prüft (Lizenz, Warteschlange). */
|
||||
export async function workerConditions(): Promise<Condition[]> {
|
||||
const ls = await one('SELECT license_key_enc, last_error, last_error_kind, valid, message, checked_at FROM license_state WHERE id = 1');
|
||||
const due = await one("SELECT COUNT(*) AS n, MIN(run_at) AS oldest FROM jobs WHERE status IN ('scheduled','retrying') AND run_at < DATE_SUB(UTC_TIMESTAMP(3), INTERVAL 10 MINUTE)");
|
||||
const review = await one("SELECT COUNT(*) AS n FROM jobs WHERE status = 'needs_review'");
|
||||
const kind = ls?.license_key_enc ? ls.last_error_kind as string | null : null; // ohne Schlüssel: Testmodus, kein Alarm
|
||||
return [
|
||||
{ key: 'license.unreachable', active: kind === 'outage', detail: kind === 'outage' ? ls!.last_error : null, graceMs: 30 * 60_000 },
|
||||
// Konfigurationsfehler/Ablehnung ODER Lizenzserver meldet die Lizenz als ungültig (abgelaufen, gesperrt)
|
||||
(() => {
|
||||
const bad = kind === 'config' || kind === 'rejected';
|
||||
const invalid = !!ls?.license_key_enc && !!ls.checked_at && !ls.valid;
|
||||
return { key: 'license.problem', active: bad || invalid, detail: bad ? ls!.last_error : invalid ? (ls!.message ?? 'Lizenz ungültig') : null, graceMs: 0 };
|
||||
})(),
|
||||
{ key: 'jobs.backlog', active: Number(due?.n ?? 0) > 0, detail: Number(due?.n ?? 0) > 0 ? `${due!.n} fällige Aufträge seit über 10 Minuten nicht bearbeitet` : null, graceMs: 5 * 60_000 },
|
||||
{ key: 'jobs.needs_review', active: Number(review?.n ?? 0) > 0, detail: Number(review?.n ?? 0) > 0 ? `${review!.n} Auftrag/Aufträge mit unklarem Ergebnis (Verwaltung → Aufträge)` : null, graceMs: 0 },
|
||||
];
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue