// PEP-224: platform features follow their monitors (PEP-202). A feature is `unavailable` while one // of its monitors has been down longer than the feature's threshold (default 5 min), `degraded` // while one is unstable, `available` otherwise — recovery follows the monitor's own // recover_threshold. Reading is cheap (one query of observe.db, cached 15 s per process) and never // blocks: any trouble with observe.db means «available». The observer announces changes // (`featureTick`): the journal, one message to the «services» channel, a poke for live pages. import type { Db } from "@peppa/db"; import { m as tr } from "@peppa/shared/i18n"; import { PeppaError } from "./errors.ts"; import { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts"; import { alertAdmins } from "./monitor.ts"; import { notify } from "./notify.ts"; import { listMonitors, observeDb, type Monitor } from "./observe.ts"; import { getPlatformChannel, platformProjectKey, postToChannel } from "./platform-channel.ts"; import { logEvent } from "./audit.ts"; import { getProject } from "./projects.ts"; export { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts"; export type FeatureState = "available" | "degraded" | "unavailable"; export interface FeatureInfo { /** For people (a key of the translations). */ label: string; /** What a person sees on a grey button. */ unavailableText: string; } const GENERIC = tr("Временно недоступно — технические неполадки. Попробуйте позже"); export const FEATURES: Record = { egov_login: { label: tr("Вход через eGov"), unavailableText: tr("Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже") }, mcp: { label: tr("Подключение к Claude и ChatGPT"), unavailableText: tr("MCP временно недоступен — технические неполадки. Попробуйте позже") }, google_login: { label: tr("Вход через Google"), unavailableText: tr("Временно недоступно — технические неполадки на стороне Google. Попробуйте позже") }, bot: { label: tr("Telegram-бот"), unavailableText: GENERIC }, voice: { label: tr("Голосовой ввод"), unavailableText: GENERIC }, bugsink: { label: tr("Отслеживание ошибок"), unavailableText: GENERIC }, }; export const DEGRADED_TEXT = tr("Может работать с задержками"); export const DEFAULT_DISABLE_AFTER_MIN = 5; const CACHE_MS = 15_000; export interface FeatureStatus { name: FeatureName; state: FeatureState; /** Since when the linked service fails (unavailable / degraded). */ since: string | null; disableAfterMin: number; /** Linked monitors (not on pause). */ monitors: Array>; /** Monitors that make the state, with their last reason. */ failing: Array<{ id: number; name: string; state: Monitor["state"]; since: string | null; reason: string }>; } type MonitorLike = Pick; /** The rule, pure: monitors + thresholds → the state of every feature. */ export function computeFeatures(monitors: MonitorLike[], thresholds: Partial>, now = new Date()): Record { const out = {} as Record; for (const name of FEATURE_NAMES) { const disableAfterMin = thresholds[name] ?? DEFAULT_DISABLE_AFTER_MIN; const linked = monitors.filter((m) => !m.paused && m.features.includes(name)); const longDown = linked.filter((m) => m.state === "down" && now.getTime() - Date.parse(m.stateSince ?? now.toISOString()) >= disableAfterMin * 60_000); const shaky = linked.filter((m) => m.state === "degraded"); const state: FeatureState = longDown.length ? "unavailable" : shaky.length ? "degraded" : "available"; const failing = (state === "unavailable" ? longDown : state === "degraded" ? shaky : []).map((m) => ({ id: m.id, name: m.name, state: m.state, since: m.stateSince, reason: String(m.lastDetail?.reason ?? ""), })); const since = failing.map((f) => f.since).filter((s): s is string => !!s).sort()[0] ?? null; out[name] = { name, state, since, disableAfterMin, monitors: linked.map((m) => ({ id: m.id, name: m.name, state: m.state, stateSince: m.stateSince })), failing }; } return out; } const allAvailable = (): Record => computeFeatures([], {}); /** Per-feature thresholds set by the superadmin (no row = 5 min). */ export function featureThresholds(): Partial> { const out: Partial> = {}; for (const r of observeDb().prepare("SELECT name, disable_after_min FROM features WHERE disable_after_min IS NOT NULL").all() as Array<{ name: string; disable_after_min: number }>) if (isFeatureName(r.name)) out[r.name] = Number(r.disable_after_min); return out; } let cache: { at: number; print: string; value: Record } | null = null; /** Tests and the superadmin's changes: read afresh next time. */ export function resetFeatureCache(): void { cache = null; } /** Every feature's state (cached 15 s); trouble with observe.db = everything available. */ export function featureStatuses(o: { now?: Date; fresh?: boolean } = {}): Record { const now = o.now ?? new Date(); // The announced states (written by the observer) are part of the key: a change shows at once, even in // another copy of this module (Next bundles route handlers and pages separately). const print = o.now ? "" : featureFingerprint(); if (!o.fresh && !o.now && cache && cache.print === print && Date.now() - cache.at < CACHE_MS) return cache.value; let value: Record; try { value = computeFeatures(listMonitors(), featureThresholds(), now); } catch (e) { console.error("feature-status: observe.db unavailable, everything counts as available:", (e as Error).message); value = allAvailable(); } if (!o.now) cache = { at: Date.now(), print, value }; return value; } export const featureStatus = (name: FeatureName, o: { now?: Date; fresh?: boolean } = {}): FeatureStatus => featureStatuses(o)[name]; /** Servers check too: refuses (PeppaError with the person's text) when the feature is unavailable. */ export function assertFeatureAvailable(name: FeatureName, o: { now?: Date } = {}): void { if (featureStatus(name, o).state === "unavailable") throw new PeppaError(FEATURES[name].unavailableText); } /** A grey control's data for the web (kept small: it goes to client components). */ export interface FeatureGateView { name: FeatureName; state: FeatureState; since: string | null; text: string; } export function featureGateView(name: FeatureName, o: { now?: Date } = {}): FeatureGateView { const s = featureStatus(name, o); return { name, state: s.state, since: s.since, text: s.state === "unavailable" ? FEATURES[name].unavailableText : s.state === "degraded" ? DEGRADED_TEXT : "" }; } export function setFeatureThreshold(name: string, minutes: number): void { if (!isFeatureName(name)) throw new PeppaError(tr("Неизвестная функция: {name}. Есть: {list}", { name, list: FEATURE_NAMES.join(", ") })); if (!Number.isInteger(minutes) || minutes < 0 || minutes > 1440) throw new PeppaError(tr("{field}: целое число от {min} до {max}", { field: "disableAfterMin", min: 0, max: 1440 })); observeDb().prepare("INSERT INTO features (name, disable_after_min) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET disable_after_min = excluded.disable_after_min").run(name, minutes); resetFeatureCache(); } export interface FeatureLogEntry { id: number; name: FeatureName; state: FeatureState; reason: string; at: string; } export function featureLog(limit = 50): FeatureLogEntry[] { return (observeDb().prepare("SELECT * FROM feature_log ORDER BY at DESC, id DESC LIMIT ?").all(limit) as Array>) .filter((r) => isFeatureName(r.name)) .map((r) => ({ id: Number(r.id), name: r.name as FeatureName, state: r.state as FeatureState, reason: String(r.reason), at: String(r.at) })); } /** Live pages (scope `features`): the announced states; "" when observe.db is unavailable. */ export function featureFingerprint(): string { try { return (observeDb().prepare("SELECT coalesce(group_concat(name || ':' || coalesce(state,'') || ':' || coalesce(changed_at,''), ','), '') AS f FROM features").get() as { f: string }).f; } catch { return ""; } } const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); function why(s: FeatureStatus, now: Date): string { return s.failing .map((f) => { const n = Math.max(1, Math.round((now.getTime() - Date.parse(f.since ?? now.toISOString())) / 60_000)); return f.reason ? `${f.name} — ${f.reason}, ${n} мин` : `${f.name}, ${n} мин`; }) .join("; "); } /** Text of the message to the «services» channel (superadmin's: monitor names as they are). */ export function featureChangeText(s: FeatureStatus, now = new Date()): string { return s.state === "unavailable" ? tr("⛔ «{feature}» отключено для пользователей: не работает {why}", { feature: FEATURES[s.name].label, why: why(s, now) }) : tr("✅ «{feature}» снова включено для пользователей", { feature: FEATURES[s.name].label }); } export interface FeatureTickOptions { now?: Date; log?: (s: string) => void; } /** * The observer, after its checks: compares the computed states with the announced ones. A change * to/from «unavailable» goes to the feature journal, the platform project's events and the * «services» channel (no channel — the superadmins); every change pokes live pages. The first * computation only remembers. Returns the changed features. */ export async function featureTick(db: Db, o: FeatureTickOptions = {}): Promise { const now = o.now ?? new Date(); const log = o.log ?? (() => {}); const iso = now.toISOString(); const odb = observeDb(); const statuses = computeFeatures(listMonitors(), featureThresholds(), now); const known = new Map((odb.prepare("SELECT name, state FROM features").all() as Array<{ name: string; state: string | null }>).map((r) => [r.name, r.state])); const changed: FeatureName[] = []; for (const name of FEATURE_NAMES) { const s = statuses[name]; const prev = known.get(name) ?? null; if (prev === s.state) continue; const reason = s.state === "available" ? "" : why(s, now); odb .prepare("INSERT INTO features (name, state, since, reason, changed_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET state = excluded.state, since = excluded.since, reason = excluded.reason, changed_at = excluded.changed_at") .run(name, s.state, s.since, reason, iso); changed.push(name); // The first computation (no state yet) and degraded ↔ available are not announced. if (prev === null || (prev === "unavailable") === (s.state === "unavailable")) continue; odb.prepare("INSERT INTO feature_log (name, state, reason, at) VALUES (?, ?, ?, ?)").run(name, s.state === "unavailable" ? "unavailable" : "available", reason, iso); const text = featureChangeText(s, now); log(`feature: ${name} ${prev} → ${s.state}${reason ? ` (${reason})` : ""}`); const p = await getProject(db, platformProjectKey()).catch(() => null); if (p) await logEvent(db, { projectId: p.id, type: s.state === "unavailable" ? "feature_disabled" : "feature_enabled", payload: { feature: name, reason, since: s.since } }).catch(() => {}); const key = `feature:${name}:${s.state === "unavailable" ? "off" : "on"}:${iso}`; try { const channel = await getPlatformChannel(db); if (!(await postToChannel(db, "services", `mon:ch:${key}`, esc(text), channel))) await alertAdmins(db, `mon:${key}`, text, log); } catch (e) { log(`feature: announce failed: ${(e as Error).message}`); } } if (changed.length) { resetFeatureCache(); for (const name of changed) await notify(db, { type: "feature", name }).catch(() => {}); } return changed; }