feat(monitor): add alert monitoring page with KPI dashboard, alert list, and incident management

- Add Tauri plugins for file dialog and filesystem access
- Create Rust backend for processing Grafana alerts (pairing, KPI calculation)
- Add virtualized alert list with invalid toggle and incident attachment
- Add incident manager with create, attach, and detach functionality
- Add KPI dashboard showing coverage ratio, downtime, and invalid rate
- Add date-fns for date formatting
This commit is contained in:
Syahdan 2025-12-29 05:44:21 +07:00
parent ee3c0c156b
commit ea1c9105a7
15 changed files with 1757 additions and 19 deletions

View file

@ -0,0 +1,159 @@
import { cva } from "class-variance-authority";
import { format } from "date-fns";
import { Activity, Link as LinkIcon } from "lucide-react";
import * as React from "react";
import { Checkbox } from "@/components/ui/checkbox";
import type { ProcessedAlert } from "@/lib/types/alerts";
import { cn } from "@/lib/utils";
function formatDuration(ms: number): string {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (days > 0) return `${days}d ${hours % 24}h`;
if (hours > 0) return `${hours}h ${minutes % 60}m`;
if (minutes > 0) return `${minutes}m`;
return `${seconds}s`;
}
function formatTimeRange(start: number, end: number): string {
return `${format(start, "HH:mm:ss")} - ${format(end, "HH:mm:ss")}`;
}
const alertItemVariants = cva(
"group relative flex w-full items-center gap-3 border-b border-border p-3 transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
{
variants: {
status: {
firing:
"bg-destructive/5 hover:bg-destructive/10 border-l-2 border-l-destructive",
resolved: "border-l-2 border-l-transparent",
pending: "border-l-2 border-l-yellow-500/50",
},
invalid: {
true: "opacity-60 grayscale bg-muted/30",
false: "",
},
},
defaultVariants: {
status: "resolved",
invalid: false,
},
},
);
interface AlertListItemProps {
alert: ProcessedAlert;
isSelected?: boolean;
onToggleInvalid: (id: number, isInvalid: boolean) => void;
onSelect: (alert: ProcessedAlert) => void;
style?: React.CSSProperties;
}
export const AlertListItem = React.memo(
({
alert,
isSelected,
onToggleInvalid,
onSelect,
style,
}: AlertListItemProps) => {
const status = alert.isFiring ? "firing" : "resolved";
return (
<div
style={style}
className={cn(
alertItemVariants({ status, invalid: alert.isInvalid }),
isSelected && "bg-muted border-l-primary",
)}
onClick={() => onSelect(alert)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
onSelect(alert);
}
}}
>
<div
className="flex h-full items-start pt-0.5"
onClick={(e) => e.stopPropagation()}
>
<Checkbox
checked={alert.isInvalid}
onCheckedChange={(checked) =>
onToggleInvalid(alert.id, checked === true)
}
aria-label="Mark as invalid"
/>
</div>
<div className="flex min-w-0 flex-1 flex-col gap-1">
<div className="flex items-center justify-between gap-2">
<span className="truncate text-xs font-semibold text-foreground">
{alert.alertName || `Unknown Alert #${alert.alertId}`}
</span>
<span className="flex shrink-0 items-center gap-1 text-[10px] font-mono text-muted-foreground">
{alert.durationMs > 0 && (
<span>{formatDuration(alert.durationMs)}</span>
)}
</span>
</div>
<div className="flex items-center justify-between gap-2 text-[10px] text-muted-foreground">
<div className="flex items-center gap-2">
<span
className={cn(
"uppercase tracking-wider",
alert.isFiring
? "text-destructive font-bold"
: "text-green-600 dark:text-green-500",
)}
>
{alert.newState}
</span>
<span className="text-border">|</span>
<span className="font-mono">
{formatTimeRange(alert.time, alert.timeEnd)}
</span>
</div>
<div className="flex items-center gap-1.5">
{alert.attachedIncidentId && (
<div
className="flex items-center gap-0.5 text-primary"
title="Attached to incident"
>
<LinkIcon className="size-3" />
<span className="font-mono">{alert.attachedIncidentId}</span>
</div>
)}
{alert.isInvalid && (
<Activity className="size-3 text-muted-foreground/50" />
)}
</div>
</div>
<div className="truncate text-[10px] text-muted-foreground/70 font-mono">
{Object.entries(alert.values)
.map(
([k, v]) =>
`${k}=${Number.isFinite(v) ? v.toFixed(1) : String(v)}`,
)
.join(", ")}
</div>
</div>
{alert.isFiring && !alert.isInvalid && (
<div className="absolute right-0 top-0 h-full w-0.5 bg-destructive" />
)}
</div>
);
},
);
AlertListItem.displayName = "AlertListItem";

View file

@ -0,0 +1,74 @@
import * as React from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
import { cn } from "@/lib/utils";
import type { ProcessedAlert } from "@/lib/types/alerts";
import { AlertListItem } from "./alert-list-item";
interface AlertListProps {
alerts: ProcessedAlert[];
onToggleInvalid: (alertId: number, isInvalid: boolean) => void;
onSelectAlert: (alert: ProcessedAlert) => void;
selectedAlertId?: number;
className?: string;
}
export function AlertList({
alerts,
onToggleInvalid,
onSelectAlert,
selectedAlertId,
className,
}: AlertListProps) {
const parentRef = React.useRef<HTMLDivElement>(null);
const getItemKey = React.useCallback(
(index: number) => alerts[index]?.id ?? index,
[alerts],
);
const virtualizer = useVirtualizer({
count: alerts.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 80,
overscan: 5,
getItemKey,
});
return (
<div
ref={parentRef}
className={cn("h-full w-full overflow-y-auto contain-strict", className)}
>
<div
style={{
height: `${virtualizer.getTotalSize()}px`,
width: "100%",
position: "relative",
}}
>
{virtualizer.getVirtualItems().map((virtualItem) => {
const alert = alerts[virtualItem.index];
if (!alert) return null;
return (
<AlertListItem
key={virtualItem.key}
alert={alert}
isSelected={selectedAlertId === alert.id}
onToggleInvalid={onToggleInvalid}
onSelect={onSelectAlert}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: `${virtualItem.size}px`,
transform: `translateY(${virtualItem.start}px)`,
}}
/>
);
})}
</div>
</div>
);
}

View file

@ -0,0 +1,224 @@
import * as React from "react";
import { format } from "date-fns";
import { Plus, Link, Link2Off } from "lucide-react";
import { cn } from "@/lib/utils";
import type { Incident, ProcessedAlert } from "@/lib/types/alerts";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
interface IncidentManagerProps {
incidents: Incident[];
selectedAlert: ProcessedAlert | null;
onAddIncident: (incident: Omit<Incident, "attachedAlertIds">) => void;
onAttachAlert: (alertId: number, incidentId: string) => void;
onDetachAlert: (alertId: number) => void;
}
export function IncidentManager({
incidents,
selectedAlert,
onAddIncident,
onAttachAlert,
onDetachAlert,
}: IncidentManagerProps) {
const [title, setTitle] = React.useState("");
const [description, setDescription] = React.useState("");
const [startTime, setStartTime] = React.useState("");
const [endTime, setEndTime] = React.useState("");
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!title || !startTime || !endTime) return;
const newIncident: Omit<Incident, "attachedAlertIds"> = {
id: crypto.randomUUID(),
title,
description,
startTime: new Date(startTime).getTime(),
endTime: new Date(endTime).getTime(),
};
onAddIncident(newIncident);
setTitle("");
setDescription("");
setStartTime("");
setEndTime("");
};
return (
<div className="flex flex-col gap-4 h-full">
<Card className="shrink-0 rounded-none border-x-0 border-t-0 border-b">
<CardHeader className="pb-3">
<CardTitle>Create Incident</CardTitle>
<CardDescription>
Log a confirmed Redis incident to track downtime.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="title">Title</Label>
<Input
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="e.g., Redis Master OOM"
required
/>
</div>
<div className="grid gap-2">
<Label htmlFor="description">Description</Label>
<Input
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Brief details about the incident"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="grid gap-2">
<Label htmlFor="startTime">Start Time</Label>
<Input
id="startTime"
type="datetime-local"
value={startTime}
onChange={(e) => setStartTime(e.target.value)}
required
/>
</div>
<div className="grid gap-2">
<Label htmlFor="endTime">End Time</Label>
<Input
id="endTime"
type="datetime-local"
value={endTime}
onChange={(e) => setEndTime(e.target.value)}
required
/>
</div>
</div>
<Button type="submit" className="w-full mt-2" size="sm">
<Plus className="mr-2 size-4" />
Create Incident
</Button>
</form>
</CardContent>
</Card>
<div className="flex-1 overflow-auto px-1">
<div className="space-y-4 pb-4">
<h3 className="text-xs font-medium text-muted-foreground px-4 uppercase tracking-wider">
Active Incidents ({incidents.length})
</h3>
{incidents.length === 0 ? (
<div className="px-4 py-8 text-center text-muted-foreground text-xs border border-dashed mx-4">
No incidents recorded
</div>
) : (
<div className="grid gap-3 px-1">
{incidents.map((incident) => {
const isCurrentAlertAttached =
selectedAlert?.attachedIncidentId === incident.id;
return (
<Card
key={incident.id}
className={cn(
"relative transition-colors",
isCurrentAlertAttached &&
"border-primary/50 bg-primary/5",
)}
>
<CardHeader className="pb-2">
<div className="flex items-start justify-between gap-2">
<div className="grid gap-1">
<CardTitle className="leading-tight">
{incident.title}
</CardTitle>
<CardDescription className="font-mono text-[10px]">
ID: {incident.id.slice(0, 8)}
</CardDescription>
</div>
{selectedAlert && (
<Button
variant={
isCurrentAlertAttached
? "destructive"
: "secondary"
}
size="xs"
onClick={() =>
isCurrentAlertAttached
? onDetachAlert(selectedAlert.id)
: onAttachAlert(selectedAlert.id, incident.id)
}
className={cn(
"shrink-0",
isCurrentAlertAttached &&
"bg-destructive/10 text-destructive hover:bg-destructive/20",
)}
>
{isCurrentAlertAttached ? (
<>
<Link2Off className="mr-1 size-3" />
Detach Alert
</>
) : (
<>
<Link className="mr-1 size-3" />
Attach Alert
</>
)}
</Button>
)}
</div>
</CardHeader>
<CardContent className="pb-2 grid gap-1.5">
<p className="text-xs text-muted-foreground">
{incident.description || "No description provided."}
</p>
<div className="grid grid-cols-2 gap-2 text-[10px] text-muted-foreground font-mono mt-1 pt-2 border-t border-border/50">
<div>
<span className="opacity-50 block mb-0.5">START</span>
{format(incident.startTime, "yyyy-MM-dd HH:mm")}
</div>
<div>
<span className="opacity-50 block mb-0.5">END</span>
{format(incident.endTime, "yyyy-MM-dd HH:mm")}
</div>
</div>
</CardContent>
<CardFooter className="pt-0 pb-3 text-[10px] text-muted-foreground">
<div className="flex items-center gap-1.5 w-full">
<div
className={cn(
"size-1.5 rounded-full",
incident.attachedAlertIds.length > 0
? "bg-primary"
: "bg-muted-foreground/30",
)}
/>
{incident.attachedAlertIds.length} alerts attached
</div>
</CardFooter>
</Card>
);
})}
</div>
)}
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,117 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import type { KpiMetrics } from "@/lib/types/alerts";
interface KpiDashboardProps {
kpis: KpiMetrics | null;
isLoading?: boolean;
}
export function KpiDashboard({ kpis, isLoading = false }: KpiDashboardProps) {
if (isLoading) {
return (
<div className="grid gap-4 md:grid-cols-3">
<Card className="rounded-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Error Coverage
</CardTitle>
</CardHeader>
<CardContent>
<Skeleton className="h-7 w-20 rounded-none" />
<Skeleton className="mt-1 h-4 w-32 rounded-none" />
</CardContent>
</Card>
<Card className="rounded-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Total Downtime
</CardTitle>
</CardHeader>
<CardContent>
<Skeleton className="h-7 w-20 rounded-none" />
</CardContent>
</Card>
<Card className="rounded-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Invalid Alerts
</CardTitle>
</CardHeader>
<CardContent>
<Skeleton className="h-7 w-20 rounded-none" />
<Skeleton className="mt-1 h-4 w-32 rounded-none" />
</CardContent>
</Card>
</div>
);
}
if (!kpis) {
return (
<Card className="rounded-none">
<CardContent className="pt-6 text-center text-xs text-muted-foreground">
No KPI data available
</CardContent>
</Card>
);
}
const coverageColor =
kpis.errorCoverageRatio > 80
? "text-green-500"
: kpis.errorCoverageRatio > 50
? "text-yellow-500"
: "text-destructive";
const invalidColor =
kpis.invalidAlertRatio < 10
? "text-green-500"
: kpis.invalidAlertRatio < 25
? "text-yellow-500"
: "text-destructive";
return (
<div className="grid gap-4 md:grid-cols-3">
<Card className="rounded-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Error Coverage</CardTitle>
</CardHeader>
<CardContent>
<div className={cn("text-2xl font-bold", coverageColor)}>
{kpis.errorCoverageRatio.toFixed(1)}%
</div>
<p className="text-xs text-muted-foreground">
{kpis.coveredIncidents} of {kpis.totalIncidents} incidents
</p>
</CardContent>
</Card>
<Card className="rounded-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Downtime</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{kpis.overallDowntimeFormatted}
</div>
</CardContent>
</Card>
<Card className="rounded-none">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Invalid Alerts</CardTitle>
</CardHeader>
<CardContent>
<div className={cn("text-2xl font-bold", invalidColor)}>
{kpis.invalidAlertRatio.toFixed(1)}%
</div>
<p className="text-xs text-muted-foreground">
{kpis.invalidAlerts} of {kpis.totalFiringAlerts} alerts
</p>
</CardContent>
</Card>
</div>
);
}