SPB Git

Repository Public

RuleEditor.tsx 13.8 KB 195 lines tsx

1"use client";2import { useQueryClient } from "@tanstack/react-query";3import { useMemo, useState } from "react";4import { apiPatch, apiPost, type Schemas } from "@/api/client";5import { ApiError } from "@/api/errors";6import { invalidatePaths, useApiQuery } from "@/api/query";7import { metricLabel } from "@/features/shared/metrics";8import { NodeLink } from "@/features/shared/nodes";9import { useI18n } from "@/i18n";10import { useSession } from "@/shell/session";11import { Banner, Button, Combobox, DataTable, Drawer, EmptyState, Observed, Segmented, SelectField, Stat, Switch, TextAreaField, TextField, useToast, type Column } from "@/ui";12import { emptyRuleForm, inputToUpdate, ruleToForm, serverFieldErrors, stripRows, validateRuleForm, type Rule, type RuleErrors, type RuleField, type RuleForm, type RuleInput, type Severity } from "./logic";13import { MutationError, ScopeFields } from "./shared";1415type Validation = Schemas["AlertRuleValidation"];16type Period = "24h" | "7d" | "30d";17const PERIOD_MS: Record<Period, number> = { "24h": 86400_000, "7d": 7 * 86400_000, "30d": 30 * 86400_000 };1819export function RuleEditor({ rule, onClose }: { rule: Rule | null; onClose: () => void }) {20  const { t } = useI18n();21  const qc = useQueryClient();22  const toast = useToast();23  const session = useSession();24  const catalog = useApiQuery("/metrics/catalog", undefined, { enabled: session.can("nodes.read"), staleTime: 10 * 60_000 });25  const [form, setForm] = useState<RuleForm>(() => (rule ? ruleToForm(rule) : emptyRuleForm()));26  const [errors, setErrors] = useState<RuleErrors>({});27  const [server, setServer] = useState<Partial<Record<RuleField, string>>>({});28  const [failure, setFailure] = useState<{ error: ApiError; other: string[] } | null>(null);29  const [busy, setBusy] = useState(false);30  const [period, setPeriod] = useState<Period>("7d");31  const [preview, setPreview] = useState<{ busy: boolean; result?: Validation; error?: ApiError }>({ busy: false });3233  const canManage = session.can("alerts.manage");34  const builtin = rule?.builtin ?? false;35  const locked = !canManage || busy;36  const patch = (p: Partial<RuleForm>) => setForm((f) => ({ ...f, ...p }));37  const err = (f: RuleField): string | undefined => server[f] ?? (errors[f] ? t(`alerts.form.${errors[f]}`) : undefined);38  const entry = catalog.data?.items.find((m) => m.name === form.metric);39  const metricOptions = useMemo(() => (catalog.data?.items ?? []).map((m) => ({ value: m.name, label: metricLabel(t, m.name), hint: `${m.name} · ${m.unit}`, keywords: m.description })), [catalog.data, t]);4041  const check = (): RuleInput | null => {42    const r = validateRuleForm(form);43    setErrors(r.errors);44    setServer({});45    return r.input ?? null;46  };47  const fail = (e: unknown) => {48    const error = e instanceof ApiError ? e : new ApiError({ status: 0, code: "network", message: "network" });49    const mapped = serverFieldErrors(error.details);50    setServer(mapped.fields);51    return { error, other: mapped.other };52  };5354  const save = async () => {55    const input = check();56    if (!input) return;57    setBusy(true);58    setFailure(null);59    try {60      if (rule) await apiPatch("/alert-rules/{id}", { path: { id: rule.id }, body: inputToUpdate(input, rule) });61      else await apiPost("/alert-rules", { body: input });62      toast({ tone: "ok", title: rule ? t("alerts.rule.saved") : t("alerts.rule.created") });63      await invalidatePaths(qc, "/alert-rules", "/alerts");64      onClose();65    } catch (e) {66      setBusy(false);67      setFailure(fail(e));68    }69  };7071  const runPreview = async () => {72    const input = check();73    if (!input) return;74    setPreview({ busy: true });75    try {76      const now = Date.now();77      const result = await apiPost("/alert-rules/validate", { body: { rule: input, from: new Date(now - PERIOD_MS[period]).toISOString(), to: new Date(now).toISOString() } });78      setPreview({ busy: false, result });79    } catch (e) {80      setPreview({ busy: false, error: fail(e).error });81    }82  };8384  return (85    <Drawer open onClose={onClose} size="wide" dismissable={!busy} title={rule ? (canManage ? t("alerts.rule.editTitle") : t("alerts.rule.viewTitle")) : t("alerts.rule.createTitle")} description={rule ? rule.name : t("alerts.rule.createBody")}86      footer={<><Button onClick={onClose} disabled={busy}>{canManage ? t("common.cancel") : t("common.close")}</Button>{canManage ? <Button variant="primary" loading={busy} onClick={() => void save()} data-testid="rule-save">{rule ? t("common.save") : t("alerts.rule.create")}</Button> : null}</>}>87      {!canManage ? <Banner tone="offline">{t("alerts.rule.readOnly")}</Banner> : null}88      {builtin ? <Banner tone="info">{t("alerts.rule.builtinNote")}</Banner> : null}89      <form className="mcc-form" onSubmit={(e) => { e.preventDefault(); void save(); }} noValidate data-testid="rule-form">90        <TextField label={t("common.name")} value={form.name} onChange={(name) => patch({ name })} required maxLength={120} disabled={locked || builtin} error={err("name")} data-testid="rule-name" />91        <fieldset className="mcc-fieldset" disabled={locked || rule !== null}>92          <legend>{t("alerts.rule.kindLabel")}</legend>93          <Segmented<RuleForm["kind"]> label={t("alerts.rule.kindLabel")} value={form.kind} onChange={(kind) => patch({ kind })}94            options={(["threshold", "absence", "service_state"] as const).map((k) => ({ value: k, label: t(`alerts.rule.kind.${k}`) }))} />95          <span className="mcc-hint">{t(`alerts.rule.kindHelp.${form.kind}`)}{rule ? ` ${t("alerts.rule.kindFixed")}` : ""}</span>96        </fieldset>9798        {form.kind === "threshold" ? (99          <>100            {catalog.data ? (101              <Combobox label={t("alerts.rule.metric")} hint={entry ? `${entry.description} (${entry.unit}, ${entry.source})` : undefined} value={form.metric || null} onChange={(v) => patch({ metric: v ?? "" })} required disabled={locked || builtin} error={err("metric")}102                options={form.metric && !metricOptions.some((o) => o.value === form.metric) ? [{ value: form.metric, label: form.metric }, ...metricOptions] : metricOptions} />103            ) : (104              <TextField label={t("alerts.rule.metric")} hint={catalog.isError ? (catalog.error.notImplemented ? t("alerts.rule.catalogNotAvailable") : t("alerts.rule.catalogError")) : t("alerts.rule.metricHint")} value={form.metric} onChange={(metric) => patch({ metric })} required mono disabled={locked || builtin} error={err("metric")} data-testid="rule-metric" />105            )}106            <div className="mcc-form-row">107              <SelectField<RuleForm["op"]> label={t("alerts.rule.op")} value={form.op} onChange={(op) => patch({ op })} disabled={locked || builtin} error={err("op")}108                options={(["gt", "gte", "lt", "lte"] as const).map((o) => ({ value: o, label: t(`alerts.rule.ops.${o}`) }))} />109              <TextField label={t("alerts.rule.threshold")} hint={entry ? t("alerts.rule.unitHint", { unit: entry.unit }) : undefined} value={form.threshold} onChange={(threshold) => patch({ threshold })} required mono inputMode="decimal" disabled={locked} error={err("threshold")} data-testid="rule-threshold" />110            </div>111            <div className="mcc-form-row">112              <TextField label={t("alerts.rule.clearThreshold")} hint={t("alerts.rule.clearThresholdHint")} value={form.clearThreshold} onChange={(clearThreshold) => patch({ clearThreshold })} mono inputMode="decimal" disabled={locked} error={err("clearThreshold")} />113              {(entry?.labeled ?? form.labelMatch !== "") ? <TextField label={t("alerts.rule.labelMatch")} hint={t("alerts.rule.labelMatchHint")} value={form.labelMatch} onChange={(labelMatch) => patch({ labelMatch })} mono disabled={locked || builtin} error={err("labelMatch")} /> : null}114            </div>115          </>116        ) : null}117118        <div className="mcc-form-row">119          <TextField label={form.kind === "absence" ? t("alerts.rule.forAbsence") : t("alerts.rule.for")} hint={t("alerts.rule.durationHint")} value={form.forText} onChange={(forText) => patch({ forText })} required disabled={locked} error={err("forText")} data-testid="rule-for" />120          <TextField label={t("alerts.rule.clear")} hint={t("alerts.rule.clearHint")} value={form.clearText} onChange={(clearText) => patch({ clearText })} required disabled={locked} error={err("clearText")} />121        </div>122        <ScopeFields form={form} onChange={patch} error={err("scope")} disabled={locked} />123        <SelectField<Severity> label={t("alerts.col.severity")} value={form.severity} onChange={(severity) => patch({ severity })} disabled={locked} error={err("severity")}124          options={(["critical", "warning", "info"] as const).map((s) => ({ value: s, label: t(`states.severity.${s}`) }))} />125        <div className="mcc-form-row">126          <Switch label={t("alerts.rule.enabled")} checked={form.enabled} onChange={(enabled) => patch({ enabled })} disabled={locked} />127          <Switch label={t("alerts.rule.notify")} hint={t("alerts.rule.notifyHint")} checked={form.notify} onChange={(notify) => patch({ notify })} disabled={locked} />128        </div>129        <TextAreaField label={t("common.description")} value={form.description} onChange={(description) => patch({ description })} maxLength={1000} disabled={locked || builtin} error={err("description")} />130      </form>131      {failure ? <MutationError error={failure.error} extra={failure.other.length > 0 ? <ul>{failure.other.map((o) => <li key={o} className="mono">{o}</li>)}</ul> : undefined} /> : null}132133      {canManage ? (134        <section className="section" aria-label={t("alerts.preview.title")}>135          <div className="section-head">136            <h3>{t("alerts.preview.title")}</h3>137            <div className="row-wrap">138              <Segmented<Period> label={t("alerts.preview.period")} value={period} onChange={setPeriod} options={[{ value: "24h", label: t("ui.range.24h") }, { value: "7d", label: t("ui.range.7d") }, { value: "30d", label: t("ui.range.30d") }]} />139              <Button icon="history" loading={preview.busy} onClick={() => void runPreview()} data-testid="rule-validate">{t("alerts.preview.run")}</Button>140            </div>141          </div>142          <p className="mcc-hint">{t("alerts.preview.help")}</p>143          <div aria-live="polite">144            {preview.error ? <MutationError error={preview.error} /> : null}145            {preview.result ? <PreviewResult v={preview.result} /> : null}146          </div>147        </section>148      ) : null}149    </Drawer>150  );151}152153function PreviewResult({ v }: { v: Validation }) {154  const { t, tn, fmt } = useI18n();155  const rows = useMemo(() => stripRows(v), [v]);156  type Interval = Validation["intervals"][number];157  const columns: Column<Interval>[] = [158    { id: "node", header: t("common.node"), cell: (i) => <NodeLink id={i.node_id} alias={i.node_alias} />, sortValue: (i) => i.node_alias },159    { id: "label", header: t("alerts.col.label"), cell: (i) => (i.label ? i.label : <span className="faint">{t("alerts.noLabel")}</span>), mono: true, hide: "sm" },160    { id: "start", header: t("alerts.preview.start"), cell: (i) => <span className="num">{fmt.dateTime(i.started_at, { zone: false })}</span>, sortValue: (i) => Date.parse(i.started_at) },161    { id: "end", header: t("alerts.preview.end"), cell: (i) => (i.ended_at ? <span className="num">{fmt.dateTime(i.ended_at, { zone: false })}</span> : <span className="muted">{t("alerts.preview.stillFiring")}</span>), sortValue: (i) => (i.ended_at ? Date.parse(i.ended_at) : undefined) },162    { id: "dur", header: t("alerts.preview.duration"), align: "right", cell: (i) => fmt.duration(((i.ended_at ? Date.parse(i.ended_at) : Date.parse(v.evaluated_to)) - Date.parse(i.started_at)) / 1000) },163    { id: "peak", header: t("alerts.preview.peak"), align: "right", cell: (i) => <Observed value={i.peak_value}>{(x) => fmt.number(x, 2)}</Observed>, sortValue: (i) => i.peak_value, hide: "sm" },164  ];165  const H = 18;166  return (167    <div className="stack" data-testid="rule-preview">168      <div className="al-stats">169        <Stat label={t("alerts.preview.firings")} value={<span data-testid="rule-preview-firings">{fmt.integer(v.total_firings)}</span>} />170        <Stat label={t("alerts.preview.nodesEvaluated")} value={fmt.integer(v.nodes_evaluated)} />171        <Stat label={t("alerts.preview.nodesWithoutData")} value={<Observed value={v.nodes_without_data}>{(n) => fmt.integer(n)}</Observed>} />172        <Stat label={t("alerts.preview.resolution")} value={<span className="mono">{v.resolution}</span>} context={`${fmt.dateTime(v.evaluated_from, { zone: false })} → ${fmt.dateTime(v.evaluated_to)}`} />173      </div>174      {v.warnings.map((w) => <Banner key={w} tone="warning">{w}</Banner>)}175      {v.intervals.length === 0 ? <EmptyState compact icon="ok" title={t("alerts.preview.none")}>{t("alerts.preview.noneBody")}</EmptyState> : (176        <>177          <div className="al-strip" role="img" aria-label={tn("alerts.preview.stripAria", v.total_firings, { nodes: rows.length })}>178            {rows.map((r) => (179              <div key={r.nodeId} className="al-strip-row">180                <span className="mono truncate">{r.alias}</span>181                <svg viewBox={`0 0 1000 ${H}`} preserveAspectRatio="none" aria-hidden="true">182                  <rect className="track" x="0" y="0" width="1000" height={H} />183                  {r.spans.map((s, i) => <rect key={i} className={s.open ? "span open" : "span"} x={s.x0 * 1000} y="3" width={Math.max(3, (s.x1 - s.x0) * 1000)} height={H - 6} />)}184                </svg>185              </div>186            ))}187            <div className="al-strip-axis num" aria-hidden="true"><span>{fmt.dateTime(v.evaluated_from, { zone: false })}</span><span>{fmt.dateTime(v.evaluated_to, { zone: false })}</span></div>188          </div>189          <DataTable caption={t("alerts.preview.intervals")} columns={columns} rows={v.intervals} rowKey={(i) => `${i.node_id}:${i.label}:${i.started_at}`} compact initialSort={{ id: "start", dir: "desc" }} />190        </>191      )}192    </div>193  );194}195
Files main
Menu

Theme