Repository Public
1// Pure logic of the Alerts area: durations, rule form <-> contract mapping, filters <-> URL/query, scope helpers.2// The server stays the authority: validation here only checks shape so obvious mistakes do not cost a round trip.3import type { Schemas } from "@/api/client";45export type Scope = Schemas["AlertScope"];6export type Rule = Schemas["AlertRule"];7export type RuleInput = Schemas["AlertRuleInput"];8export type RuleUpdate = Schemas["UpdateAlertRuleRequest"];9export type Severity = Schemas["Severity"];10export type AlertState = Schemas["AlertState"];1112// ───────────── durations ─────────────13export const MAX_RULE_SECONDS = 86400;14const UNIT: Record<string, number> = {15 s: 1, sec: 1, secs: 1, seconde: 1, secondes: 1, second: 1, seconds: 1,16 m: 60, mn: 60, min: 60, mins: 60, minute: 60, minutes: 60,17 h: 3600, hr: 3600, hrs: 3600, heure: 3600, heures: 3600, hour: 3600, hours: 3600,18 j: 86400, d: 86400, jour: 86400, jours: 86400, day: 86400, days: 86400,19};2021/** "5 min", "90s", "1h30", "1 h 30 min", "2,5 h", "300" (seconds) → whole seconds; null when not understood. */22export function parseDuration(text: string): number | null {23 const src = text.trim().toLowerCase().replace(/ | /g, " ");24 if (src === "") return null;25 if (/^\d+$/.test(src)) return Number(src);26 const re = /(\d+(?:[.,]\d+)?)\s*([a-z]+)?\s*/gy;27 let total = 0;28 let pos = 0;29 let lastUnit: number | null = null;30 let count = 0;31 for (;;) {32 re.lastIndex = pos;33 const m = re.exec(src);34 if (!m) break;35 const n = Number((m[1] ?? "").replace(",", "."));36 let unit: number | undefined;37 if (m[2] === undefined) {38 // "1h30": a trailing bare number takes the next smaller unit39 unit = lastUnit === 86400 ? 3600 : lastUnit === 3600 ? 60 : lastUnit === 60 ? 1 : undefined;40 if (unit === undefined || re.lastIndex !== src.length) return null;41 } else unit = UNIT[m[2]];42 if (unit === undefined || !Number.isFinite(n)) return null;43 total += n * unit;44 lastUnit = unit;45 pos = re.lastIndex;46 count++;47 }48 if (count === 0 || pos !== src.length) return null;49 return Math.round(total);50}5152/** Seconds → editable text that `parseDuration` reads back: "0 s", "45 s", "5 min", "1 h 30 min". */53export function durationText(seconds: number): string {54 const s = Math.max(0, Math.round(seconds));55 if (s === 0) return "0 s";56 const parts: string[] = [];57 const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60), r = s % 60;58 if (d) parts.push(`${d} j`);59 if (h) parts.push(`${h} h`);60 if (m) parts.push(`${m} min`);61 if (r) parts.push(`${r} s`);62 return parts.join(" ");63}6465// ───────────── scope ─────────────66export type ScopeKind = "all" | "nodes" | "tags";67export interface ScopeForm {68 scopeKind: ScopeKind;69 nodeIds: string[];70 tagsText: string;71}72export function parseTags(text: string): string[] {73 return [...new Set(text.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean))];74}75export function scopeToForm(scope: Scope | undefined): ScopeForm {76 if (scope?.node_ids && scope.node_ids.length > 0) return { scopeKind: "nodes", nodeIds: [...scope.node_ids], tagsText: "" };77 if (scope?.tags && scope.tags.length > 0) return { scopeKind: "tags", nodeIds: [], tagsText: scope.tags.join(", ") };78 return { scopeKind: "all", nodeIds: [], tagsText: "" };79}80/** Exactly one form, as the contract requires. Null when the chosen form is empty. */81export function formToScope(f: ScopeForm): Scope | null {82 if (f.scopeKind === "all") return { all: true };83 if (f.scopeKind === "nodes") return f.nodeIds.length > 0 ? { node_ids: [...f.nodeIds] } : null;84 const tags = parseTags(f.tagsText);85 return tags.length > 0 ? { tags } : null;86}87export type ScopeSummary = { kind: "all" } | { kind: "nodes"; ids: string[] } | { kind: "tags"; tags: string[] } | { kind: "empty" };88export function summarizeScope(scope: Scope | undefined): ScopeSummary {89 if (scope?.all) return { kind: "all" };90 if (scope?.node_ids?.length) return { kind: "nodes", ids: scope.node_ids };91 if (scope?.tags?.length) return { kind: "tags", tags: scope.tags };92 return { kind: "empty" };93}9495// ───────────── rule form ─────────────96export interface RuleForm extends ScopeForm {97 name: string;98 description: string;99 enabled: boolean;100 kind: Schemas["AlertRuleKind"];101 metric: string;102 labelMatch: string;103 op: Schemas["AlertOp"];104 threshold: string;105 clearThreshold: string;106 forText: string;107 clearText: string;108 severity: Severity;109 notify: boolean;110}111export type RuleField = "name" | "description" | "metric" | "threshold" | "clearThreshold" | "forText" | "clearText" | "scope" | "labelMatch" | "op" | "severity";112export type RuleErrorCode = "required" | "number" | "duration" | "durationMax" | "tooLong" | "scopeEmpty";113export type RuleErrors = Partial<Record<RuleField, RuleErrorCode>>;114115export function emptyRuleForm(): RuleForm {116 return {117 name: "", description: "", enabled: true, kind: "threshold", metric: "", labelMatch: "", op: "gt", threshold: "", clearThreshold: "",118 forText: durationText(300), clearText: durationText(120), severity: "warning", notify: true, scopeKind: "all", nodeIds: [], tagsText: "",119 };120}121export function ruleToForm(rule: Rule): RuleForm {122 return {123 name: rule.name, description: rule.description, enabled: rule.enabled, kind: rule.kind, metric: rule.metric ?? "", labelMatch: rule.label_match ?? "",124 op: rule.op ?? "gt", threshold: rule.threshold === undefined ? "" : String(rule.threshold), clearThreshold: rule.clear_threshold === undefined ? "" : String(rule.clear_threshold),125 forText: durationText(rule.for_seconds), clearText: durationText(rule.clear_seconds), severity: rule.severity, notify: rule.notify, ...scopeToForm(rule.scope),126 };127}128129const toNumber = (text: string): number | null => {130 const t = text.trim().replace(",", ".");131 if (t === "") return null;132 const n = Number(t);133 return Number.isFinite(n) ? n : null;134};135function duration(text: string, field: "forText" | "clearText", errors: RuleErrors): number {136 const s = parseDuration(text);137 if (s === null) errors[field] = text.trim() === "" ? "required" : "duration";138 else if (s > MAX_RULE_SECONDS) errors[field] = "durationMax";139 return s ?? 0;140}141142/** Shape validation + mapping to `AlertRuleInput`. `input` is present only when `errors` is empty. */143export function validateRuleForm(form: RuleForm): { errors: RuleErrors; input?: RuleInput } {144 const errors: RuleErrors = {};145 const name = form.name.trim();146 if (name === "") errors.name = "required";147 else if (name.length > 120) errors.name = "tooLong";148 if (form.description.length > 1000) errors.description = "tooLong";149 const for_seconds = duration(form.forText, "forText", errors);150 const clear_seconds = duration(form.clearText, "clearText", errors);151 const scope = formToScope(form);152 if (!scope) errors.scope = "scopeEmpty";153154 const input: RuleInput = { name, kind: form.kind, enabled: form.enabled, notify: form.notify, for_seconds, clear_seconds, severity: form.severity, ...(scope ? { scope } : {}) };155 if (form.description.trim() !== "") input.description = form.description.trim();156 if (form.kind === "threshold") {157 if (form.metric.trim() === "") errors.metric = "required";158 else input.metric = form.metric.trim();159 input.op = form.op;160 const th = toNumber(form.threshold);161 if (th === null) errors.threshold = form.threshold.trim() === "" ? "required" : "number";162 else input.threshold = th;163 if (form.clearThreshold.trim() !== "") {164 const ct = toNumber(form.clearThreshold);165 if (ct === null) errors.clearThreshold = "number";166 else input.clear_threshold = ct;167 }168 if (form.labelMatch.trim() !== "") input.label_match = form.labelMatch.trim();169 }170 return Object.keys(errors).length > 0 ? { errors } : { errors, input };171}172173/**174 * PATCH body for an existing rule. The kind cannot change. Built-in rules only accept `enabled`, thresholds,175 * durations, severity, scope and `notify` (contract): the other fields are not sent for them.176 */177export function inputToUpdate(input: RuleInput, original: Pick<Rule, "builtin" | "kind">): RuleUpdate {178 const out: RuleUpdate = { enabled: input.enabled, notify: input.notify, for_seconds: input.for_seconds, clear_seconds: input.clear_seconds };179 if (input.severity) out.severity = input.severity;180 if (input.scope) out.scope = input.scope;181 if (original.kind === "threshold") {182 if (input.threshold !== undefined) out.threshold = input.threshold;183 if (input.clear_threshold !== undefined) out.clear_threshold = input.clear_threshold;184 }185 if (!original.builtin) {186 out.name = input.name;187 out.description = input.description ?? "";188 if (original.kind === "threshold") {189 if (input.metric !== undefined) out.metric = input.metric;190 if (input.op !== undefined) out.op = input.op;191 out.label_match = input.label_match ?? "";192 }193 }194 return out;195}196197const SERVER_FIELD: Record<string, RuleField> = {198 name: "name", description: "description", metric: "metric", threshold: "threshold", clear_threshold: "clearThreshold", for_seconds: "forText",199 clear_seconds: "clearText", scope: "scope", label_match: "labelMatch", op: "op", severity: "severity",200};201/** `validation_failed` → `details.fields` ({field: message}; `rule.` prefix tolerated) mapped onto form fields. */202export function serverFieldErrors(details: Record<string, unknown> | undefined): { fields: Partial<Record<RuleField, string>>; other: string[] } {203 const fields: Partial<Record<RuleField, string>> = {};204 const other: string[] = [];205 const raw = details?.fields;206 if (raw && typeof raw === "object" && !Array.isArray(raw)) {207 for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {208 const key = k.replace(/^rule\./, "").split(".")[0] ?? k;209 const target = SERVER_FIELD[key];210 const msg = typeof v === "string" ? v : JSON.stringify(v);211 if (target) fields[target] = msg;212 else other.push(`${k}: ${msg}`);213 }214 } else if (Array.isArray(raw)) {215 for (const k of raw) other.push(String(k));216 }217 return { fields, other };218}219220// ───────────── alert list filters ─────────────221export type StateFilter = "open" | "all" | AlertState;222export interface AlertFilters {223 state: StateFilter;224 severity?: Severity | undefined;225 nodeId?: string | undefined;226 ruleId?: string | undefined;227}228export const STATE_FILTERS: readonly StateFilter[] = ["open", "firing", "pending", "acknowledged", "resolved", "all"];229const SEVERITIES: readonly string[] = ["info", "warning", "critical"];230const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;231232export function filtersFromParams(p: { get(name: string): string | null }): AlertFilters {233 const state = p.get("state");234 const severity = p.get("severity");235 const node = p.get("node");236 const rule = p.get("rule");237 return {238 state: (STATE_FILTERS as readonly string[]).includes(state ?? "") ? (state as StateFilter) : "open",239 ...(severity && SEVERITIES.includes(severity) ? { severity: severity as Severity } : {}),240 ...(node && UUID.test(node) ? { nodeId: node } : {}),241 ...(rule && UUID.test(rule) ? { ruleId: rule } : {}),242 };243}244/** Search params of the alerts tab (defaults omitted so URLs stay short). */245export function filtersToParams(f: AlertFilters): Record<string, string> {246 return {247 ...(f.state !== "open" ? { state: f.state } : {}),248 ...(f.severity ? { severity: f.severity } : {}),249 ...(f.nodeId ? { node: f.nodeId } : {}),250 ...(f.ruleId ? { rule: f.ruleId } : {}),251 };252}253export function filtersToQuery(f: AlertFilters): { limit: number; open?: boolean; state?: AlertState; severity?: Severity; node_id?: string; rule_id?: string } {254 return {255 limit: 100,256 ...(f.state === "open" ? { open: true } : f.state === "all" ? {} : { state: f.state }),257 ...(f.severity ? { severity: f.severity } : {}),258 ...(f.nodeId ? { node_id: f.nodeId } : {}),259 ...(f.ruleId ? { rule_id: f.ruleId } : {}),260 };261}262export function countByState(alerts: readonly { state: AlertState }[]): Record<AlertState, number> {263 const out: Record<AlertState, number> = { firing: 0, pending: 0, acknowledged: 0, resolved: 0 };264 for (const a of alerts) out[a.state]++;265 return out;266}267268// ───────────── validation preview ─────────────269export interface StripRow {270 nodeId: string;271 alias: string;272 /** [x0, x1] in 0–1 of the evaluated window */273 spans: { x0: number; x1: number; open: boolean }[];274}275/** Firing intervals grouped per node and projected onto the evaluated window. */276export function stripRows(v: Pick<Schemas["AlertRuleValidation"], "evaluated_from" | "evaluated_to" | "intervals">): StripRow[] {277 const from = Date.parse(v.evaluated_from), to = Date.parse(v.evaluated_to);278 const span = to - from;279 const rows = new Map<string, StripRow>();280 if (!(span > 0)) return [];281 const clamp = (x: number) => Math.max(0, Math.min(1, x));282 for (const i of v.intervals) {283 let row = rows.get(i.node_id);284 if (!row) rows.set(i.node_id, (row = { nodeId: i.node_id, alias: i.node_alias, spans: [] }));285 const x0 = clamp((Date.parse(i.started_at) - from) / span);286 const x1 = clamp(((i.ended_at ? Date.parse(i.ended_at) : to) - from) / span);287 row.spans.push({ x0, x1: Math.max(x1, x0), open: !i.ended_at });288 }289 return [...rows.values()].sort((a, b) => a.alias.localeCompare(b.alias, undefined, { numeric: true }));290}291292// ───────────── silences ─────────────293export const QUICK_SILENCE_HOURS = [1, 4, 24] as const;294export interface SilenceForm extends ScopeForm {295 reason: string;296 ruleId: string | null;297 /** datetime-local value; empty = now */298 startsLocal: string;299 /** "1" | "4" | "24" (hours from start) or "custom" */300 duration: "1" | "4" | "24" | "custom";301 endsLocal: string;302}303export type SilenceErrors = Partial<Record<"reason" | "scope" | "starts" | "ends", "required" | "tooLong" | "scopeEmpty" | "invalid" | "endBeforeStart" | "endPast">>;304305export function validateSilence(f: SilenceForm, now: number): { errors: SilenceErrors; body?: Schemas["CreateSilenceRequest"] } {306 const errors: SilenceErrors = {};307 const reason = f.reason.trim();308 if (reason === "") errors.reason = "required";309 else if (reason.length > 500) errors.reason = "tooLong";310 const scope = formToScope(f);311 if (!scope) errors.scope = "scopeEmpty";312 let start: number | null = null;313 if (f.startsLocal !== "") {314 start = new Date(f.startsLocal).getTime();315 if (Number.isNaN(start)) {316 errors.starts = "invalid";317 start = null;318 }319 }320 let end: number;321 if (f.duration === "custom") {322 end = f.endsLocal === "" ? NaN : new Date(f.endsLocal).getTime();323 if (Number.isNaN(end)) errors.ends = f.endsLocal === "" ? "required" : "invalid";324 else if (end <= (start ?? now)) errors.ends = start !== null && end > now ? "endBeforeStart" : end <= now ? "endPast" : "endBeforeStart";325 } else end = (start ?? now) + Number(f.duration) * 3600_000;326 if (Object.keys(errors).length > 0 || !scope) return { errors };327 return {328 errors,329 body: { reason, scope, ends_at: new Date(end).toISOString(), ...(start !== null ? { starts_at: new Date(start).toISOString() } : {}), ...(f.ruleId ? { rule_id: f.ruleId } : {}) },330 };331}332