mirror of
https://github.com/fosrl/pangolin.git
synced 2026-05-21 16:25:19 +00:00
Basic ui is working
This commit is contained in:
@@ -145,6 +145,7 @@ export enum ActionsEnum {
|
|||||||
updateEventStreamingDestination = "updateEventStreamingDestination",
|
updateEventStreamingDestination = "updateEventStreamingDestination",
|
||||||
deleteEventStreamingDestination = "deleteEventStreamingDestination",
|
deleteEventStreamingDestination = "deleteEventStreamingDestination",
|
||||||
listEventStreamingDestinations = "listEventStreamingDestinations",
|
listEventStreamingDestinations = "listEventStreamingDestinations",
|
||||||
|
listHealthChecks = "listHealthChecks",
|
||||||
createAlertRule = "createAlertRule",
|
createAlertRule = "createAlertRule",
|
||||||
updateAlertRule = "updateAlertRule",
|
updateAlertRule = "updateAlertRule",
|
||||||
deleteAlertRule = "deleteAlertRule",
|
deleteAlertRule = "deleteAlertRule",
|
||||||
|
|||||||
@@ -427,6 +427,13 @@ authenticated.get(
|
|||||||
resource.listResources
|
resource.listResources
|
||||||
);
|
);
|
||||||
|
|
||||||
|
authenticated.get(
|
||||||
|
"/org/:orgId/health-checks",
|
||||||
|
verifyOrgAccess,
|
||||||
|
verifyUserHasAction(ActionsEnum.listHealthChecks),
|
||||||
|
resource.listHealthChecks
|
||||||
|
);
|
||||||
|
|
||||||
authenticated.get(
|
authenticated.get(
|
||||||
"/org/:orgId/resource-names",
|
"/org/:orgId/resource-names",
|
||||||
verifyOrgAccess,
|
verifyOrgAccess,
|
||||||
|
|||||||
@@ -32,3 +32,4 @@ export * from "./addUserToResource";
|
|||||||
export * from "./removeUserFromResource";
|
export * from "./removeUserFromResource";
|
||||||
export * from "./listAllResourceNames";
|
export * from "./listAllResourceNames";
|
||||||
export * from "./removeEmailFromResourceWhitelist";
|
export * from "./removeEmailFromResourceWhitelist";
|
||||||
|
export * from "./listHealthChecks";
|
||||||
|
|||||||
138
server/routers/resource/listHealthChecks.ts
Normal file
138
server/routers/resource/listHealthChecks.ts
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
import { db, targetHealthCheck, targets, resources } from "@server/db";
|
||||||
|
import response from "@server/lib/response";
|
||||||
|
import HttpCode from "@server/types/HttpCode";
|
||||||
|
import createHttpError from "http-errors";
|
||||||
|
import logger from "@server/logger";
|
||||||
|
import { OpenAPITags, registry } from "@server/openApi";
|
||||||
|
import { eq, sql, inArray } from "drizzle-orm";
|
||||||
|
import { NextFunction, Request, Response } from "express";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { fromError } from "zod-validation-error";
|
||||||
|
|
||||||
|
const listHealthChecksParamsSchema = z.strictObject({
|
||||||
|
orgId: z.string().nonempty()
|
||||||
|
});
|
||||||
|
|
||||||
|
const listHealthChecksSchema = z.object({
|
||||||
|
limit: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.default("1000")
|
||||||
|
.transform(Number)
|
||||||
|
.pipe(z.int().positive()),
|
||||||
|
offset: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.default("0")
|
||||||
|
.transform(Number)
|
||||||
|
.pipe(z.int().nonnegative())
|
||||||
|
});
|
||||||
|
|
||||||
|
export type ListHealthChecksResponse = {
|
||||||
|
healthChecks: {
|
||||||
|
targetHealthCheckId: number;
|
||||||
|
resourceId: number;
|
||||||
|
resourceName: string;
|
||||||
|
hcEnabled: boolean;
|
||||||
|
hcHealth: "unknown" | "healthy" | "unhealthy";
|
||||||
|
}[];
|
||||||
|
pagination: {
|
||||||
|
total: number;
|
||||||
|
limit: number;
|
||||||
|
offset: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
registry.registerPath({
|
||||||
|
method: "get",
|
||||||
|
path: "/org/{orgId}/health-checks",
|
||||||
|
description: "List health checks for all resources in an organization.",
|
||||||
|
tags: [OpenAPITags.Org, OpenAPITags.PublicResource],
|
||||||
|
request: {
|
||||||
|
params: listHealthChecksParamsSchema,
|
||||||
|
query: listHealthChecksSchema
|
||||||
|
},
|
||||||
|
responses: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function listHealthChecks(
|
||||||
|
req: Request,
|
||||||
|
res: Response,
|
||||||
|
next: NextFunction
|
||||||
|
): Promise<any> {
|
||||||
|
try {
|
||||||
|
const parsedQuery = listHealthChecksSchema.safeParse(req.query);
|
||||||
|
if (!parsedQuery.success) {
|
||||||
|
return next(
|
||||||
|
createHttpError(
|
||||||
|
HttpCode.BAD_REQUEST,
|
||||||
|
fromError(parsedQuery.error)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const { limit, offset } = parsedQuery.data;
|
||||||
|
|
||||||
|
const parsedParams = listHealthChecksParamsSchema.safeParse(req.params);
|
||||||
|
if (!parsedParams.success) {
|
||||||
|
return next(
|
||||||
|
createHttpError(
|
||||||
|
HttpCode.BAD_REQUEST,
|
||||||
|
fromError(parsedParams.error)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const { orgId } = parsedParams.data;
|
||||||
|
|
||||||
|
const list = await db
|
||||||
|
.select({
|
||||||
|
targetHealthCheckId: targetHealthCheck.targetHealthCheckId,
|
||||||
|
resourceId: resources.resourceId,
|
||||||
|
resourceName: resources.name,
|
||||||
|
hcEnabled: targetHealthCheck.hcEnabled,
|
||||||
|
hcHealth: targetHealthCheck.hcHealth
|
||||||
|
})
|
||||||
|
.from(targetHealthCheck)
|
||||||
|
.innerJoin(targets, eq(targets.targetId, targetHealthCheck.targetId))
|
||||||
|
.innerJoin(resources, eq(resources.resourceId, targets.resourceId))
|
||||||
|
.where(eq(resources.orgId, orgId))
|
||||||
|
.orderBy(sql`${resources.name} ASC`)
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset);
|
||||||
|
|
||||||
|
const [{ count }] = await db
|
||||||
|
.select({ count: sql<number>`count(*)` })
|
||||||
|
.from(targetHealthCheck)
|
||||||
|
.innerJoin(targets, eq(targets.targetId, targetHealthCheck.targetId))
|
||||||
|
.innerJoin(resources, eq(resources.resourceId, targets.resourceId))
|
||||||
|
.where(eq(resources.orgId, orgId));
|
||||||
|
|
||||||
|
return response<ListHealthChecksResponse>(res, {
|
||||||
|
data: {
|
||||||
|
healthChecks: list.map((row) => ({
|
||||||
|
targetHealthCheckId: row.targetHealthCheckId,
|
||||||
|
resourceId: row.resourceId,
|
||||||
|
resourceName: row.resourceName,
|
||||||
|
hcEnabled: row.hcEnabled,
|
||||||
|
hcHealth: (row.hcHealth ?? "unknown") as
|
||||||
|
| "unknown"
|
||||||
|
| "healthy"
|
||||||
|
| "unhealthy"
|
||||||
|
})),
|
||||||
|
pagination: {
|
||||||
|
total: count,
|
||||||
|
limit,
|
||||||
|
offset
|
||||||
|
}
|
||||||
|
},
|
||||||
|
success: true,
|
||||||
|
error: false,
|
||||||
|
message: "Health checks retrieved successfully",
|
||||||
|
status: HttpCode.OK
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(error);
|
||||||
|
return next(
|
||||||
|
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,33 +1,60 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import AlertRuleGraphEditor from "@app/components/alert-rule-editor/AlertRuleGraphEditor";
|
import AlertRuleGraphEditor from "@app/components/alert-rule-editor/AlertRuleGraphEditor";
|
||||||
import { ruleToFormValues } from "@app/lib/alertRuleForm";
|
import { apiResponseToFormValues } from "@app/lib/alertRuleForm";
|
||||||
import type { AlertRule } from "@app/lib/alertRulesLocalStorage";
|
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||||
import { getRule } from "@app/lib/alertRulesLocalStorage";
|
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||||
|
import { toast } from "@app/hooks/useToast";
|
||||||
import { useParams, useRouter } from "next/navigation";
|
import { useParams, useRouter } from "next/navigation";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import type { AxiosResponse } from "axios";
|
||||||
|
import type { GetAlertRuleResponse } from "@server/private/routers/alertRule";
|
||||||
|
import type { AlertRuleFormValues } from "@app/lib/alertRuleForm";
|
||||||
|
|
||||||
export default function EditAlertRulePage() {
|
export default function EditAlertRulePage() {
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const params = useParams();
|
const params = useParams();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const orgId = params.orgId as string;
|
const orgId = params.orgId as string;
|
||||||
const ruleId = params.ruleId as string;
|
const ruleIdParam = params.ruleId as string;
|
||||||
const [rule, setRule] = useState<AlertRule | null | undefined>(undefined);
|
const alertRuleId = parseInt(ruleIdParam, 10);
|
||||||
|
|
||||||
|
const api = createApiClient(useEnvContext());
|
||||||
|
|
||||||
|
const [formValues, setFormValues] = useState<AlertRuleFormValues | null | undefined>(undefined);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const r = getRule(orgId, ruleId);
|
if (isNaN(alertRuleId)) {
|
||||||
setRule(r ?? null);
|
router.replace(`/${orgId}/settings/alerting`);
|
||||||
}, [orgId, ruleId]);
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
api.get<AxiosResponse<GetAlertRuleResponse>>(
|
||||||
|
`/org/${orgId}/alert-rule/${alertRuleId}`
|
||||||
|
)
|
||||||
|
.then((res) => {
|
||||||
|
const rule = res.data.data;
|
||||||
|
setFormValues(apiResponseToFormValues(rule));
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
toast({
|
||||||
|
title: t("error"),
|
||||||
|
description: formatAxiosError(e),
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
setFormValues(null);
|
||||||
|
});
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [orgId, alertRuleId]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (rule === null) {
|
if (formValues === null) {
|
||||||
router.replace(`/${orgId}/settings/alerting`);
|
router.replace(`/${orgId}/settings/alerting`);
|
||||||
}
|
}
|
||||||
}, [rule, orgId, router]);
|
}, [formValues, orgId, router]);
|
||||||
|
|
||||||
if (rule === undefined) {
|
if (formValues === undefined) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-[12rem] flex items-center justify-center text-muted-foreground text-sm">
|
<div className="min-h-[12rem] flex items-center justify-center text-muted-foreground text-sm">
|
||||||
{t("loading")}
|
{t("loading")}
|
||||||
@@ -35,17 +62,16 @@ export default function EditAlertRulePage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (rule === null) {
|
if (formValues === null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AlertRuleGraphEditor
|
<AlertRuleGraphEditor
|
||||||
key={rule.id}
|
key={alertRuleId}
|
||||||
orgId={orgId}
|
orgId={orgId}
|
||||||
ruleId={rule.id}
|
alertRuleId={alertRuleId}
|
||||||
createdAt={rule.createdAt}
|
initialValues={formValues}
|
||||||
initialValues={ruleToFormValues(rule)}
|
|
||||||
isNew={false}
|
isNew={false}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,39 +2,17 @@
|
|||||||
|
|
||||||
import AlertRuleGraphEditor from "@app/components/alert-rule-editor/AlertRuleGraphEditor";
|
import AlertRuleGraphEditor from "@app/components/alert-rule-editor/AlertRuleGraphEditor";
|
||||||
import { defaultFormValues } from "@app/lib/alertRuleForm";
|
import { defaultFormValues } from "@app/lib/alertRuleForm";
|
||||||
import { isoNow, newRuleId } from "@app/lib/alertRulesLocalStorage";
|
|
||||||
import { useParams } from "next/navigation";
|
import { useParams } from "next/navigation";
|
||||||
import { useTranslations } from "next-intl";
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
export default function NewAlertRulePage() {
|
export default function NewAlertRulePage() {
|
||||||
const t = useTranslations();
|
|
||||||
const params = useParams();
|
const params = useParams();
|
||||||
const orgId = params.orgId as string;
|
const orgId = params.orgId as string;
|
||||||
const [meta, setMeta] = useState<{ id: string; createdAt: string } | null>(
|
|
||||||
null
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setMeta({ id: newRuleId(), createdAt: isoNow() });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
if (!meta) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-[12rem] flex items-center justify-center text-muted-foreground text-sm">
|
|
||||||
{t("loading")}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AlertRuleGraphEditor
|
<AlertRuleGraphEditor
|
||||||
key={meta.id}
|
|
||||||
orgId={orgId}
|
orgId={orgId}
|
||||||
ruleId={meta.id}
|
|
||||||
createdAt={meta.createdAt}
|
|
||||||
initialValues={defaultFormValues()}
|
initialValues={defaultFormValues()}
|
||||||
isNew
|
isNew
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -11,123 +11,131 @@ import {
|
|||||||
} from "@app/components/ui/dropdown-menu";
|
} from "@app/components/ui/dropdown-menu";
|
||||||
import { Switch } from "@app/components/ui/switch";
|
import { Switch } from "@app/components/ui/switch";
|
||||||
import { toast } from "@app/hooks/useToast";
|
import { toast } from "@app/hooks/useToast";
|
||||||
import {
|
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||||
type AlertRule,
|
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||||
deleteRule,
|
import { orgQueries } from "@app/lib/queries";
|
||||||
isoNow,
|
|
||||||
loadRules,
|
|
||||||
upsertRule
|
|
||||||
} from "@app/lib/alertRulesLocalStorage";
|
|
||||||
import { ArrowUpDown, MoreHorizontal } from "lucide-react";
|
import { ArrowUpDown, MoreHorizontal } from "lucide-react";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useState } from "react";
|
||||||
import { Badge } from "@app/components/ui/badge";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
type AlertingRulesTableProps = {
|
type AlertingRulesTableProps = {
|
||||||
orgId: string;
|
orgId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
function ruleHref(orgId: string, ruleId: string) {
|
type AlertRuleRow = {
|
||||||
|
alertRuleId: number;
|
||||||
|
orgId: string;
|
||||||
|
name: string;
|
||||||
|
eventType: string;
|
||||||
|
enabled: boolean;
|
||||||
|
cooldownSeconds: number;
|
||||||
|
lastTriggeredAt: number | null;
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
siteIds: number[];
|
||||||
|
healthCheckIds: number[];
|
||||||
|
};
|
||||||
|
|
||||||
|
function ruleHref(orgId: string, ruleId: number) {
|
||||||
return `/${orgId}/settings/alerting/${ruleId}`;
|
return `/${orgId}/settings/alerting/${ruleId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function sourceSummary(
|
function sourceSummary(
|
||||||
rule: AlertRule,
|
rule: AlertRuleRow,
|
||||||
t: (k: string, o?: Record<string, number | string>) => string
|
t: (k: string, o?: Record<string, number | string>) => string
|
||||||
) {
|
) {
|
||||||
if (rule.source.type === "site") {
|
if (
|
||||||
return t("alertingSummarySites", {
|
rule.eventType === "site_online" ||
|
||||||
count: rule.source.siteIds.length
|
rule.eventType === "site_offline"
|
||||||
});
|
) {
|
||||||
|
return t("alertingSummarySites", { count: rule.siteIds.length });
|
||||||
}
|
}
|
||||||
return t("alertingSummaryHealthChecks", {
|
return t("alertingSummaryHealthChecks", {
|
||||||
count: rule.source.targetIds.length
|
count: rule.healthCheckIds.length
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function triggerLabel(rule: AlertRule, t: (k: string) => string) {
|
function triggerLabel(
|
||||||
switch (rule.trigger) {
|
rule: AlertRuleRow,
|
||||||
|
t: (k: string) => string
|
||||||
|
) {
|
||||||
|
switch (rule.eventType) {
|
||||||
case "site_online":
|
case "site_online":
|
||||||
return t("alertingTriggerSiteOnline");
|
return t("alertingTriggerSiteOnline");
|
||||||
case "site_offline":
|
case "site_offline":
|
||||||
return t("alertingTriggerSiteOffline");
|
return t("alertingTriggerSiteOffline");
|
||||||
case "health_check_healthy":
|
case "health_check_healthy":
|
||||||
return t("alertingTriggerHcHealthy");
|
return t("alertingTriggerHcHealthy");
|
||||||
case "health_check_unhealthy":
|
case "health_check_not_healthy":
|
||||||
return t("alertingTriggerHcUnhealthy");
|
return t("alertingTriggerHcUnhealthy");
|
||||||
default:
|
default:
|
||||||
return rule.trigger;
|
return rule.eventType;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function actionBadges(rule: AlertRule, t: (k: string) => string) {
|
|
||||||
return rule.actions.map((a, i) => {
|
|
||||||
if (a.type === "notify") {
|
|
||||||
return (
|
|
||||||
<Badge key={`notify-${i}`} variant="secondary">
|
|
||||||
{t("alertingActionNotify")}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (a.type === "sms") {
|
|
||||||
return (
|
|
||||||
<Badge key={`sms-${i}`} variant="secondary">
|
|
||||||
{t("alertingActionSms")}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<Badge key={`webhook-${i}`} variant="secondary">
|
|
||||||
{t("alertingActionWebhook")}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const [rows, setRows] = useState<AlertRule[]>([]);
|
const api = createApiClient(useEnvContext());
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||||
const [selected, setSelected] = useState<AlertRule | null>(null);
|
const [selected, setSelected] = useState<AlertRuleRow | null>(null);
|
||||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
const [togglingId, setTogglingId] = useState<number | null>(null);
|
||||||
|
|
||||||
const refreshFromStorage = useCallback(() => {
|
const {
|
||||||
setRows(loadRules(orgId));
|
data: rows = [],
|
||||||
}, [orgId]);
|
isLoading,
|
||||||
|
refetch,
|
||||||
|
isRefetching
|
||||||
|
} = useQuery(orgQueries.alertRules({ orgId }));
|
||||||
|
|
||||||
useEffect(() => {
|
const invalidate = () =>
|
||||||
refreshFromStorage();
|
queryClient.invalidateQueries(orgQueries.alertRules({ orgId }));
|
||||||
}, [refreshFromStorage]);
|
|
||||||
|
|
||||||
const refreshData = async () => {
|
const setEnabled = async (rule: AlertRuleRow, enabled: boolean) => {
|
||||||
setIsRefreshing(true);
|
setTogglingId(rule.alertRuleId);
|
||||||
try {
|
try {
|
||||||
await new Promise((r) => setTimeout(r, 200));
|
await api.post(`/org/${orgId}/alert-rule/${rule.alertRuleId}`, {
|
||||||
refreshFromStorage();
|
enabled
|
||||||
|
});
|
||||||
|
await invalidate();
|
||||||
|
} catch (e) {
|
||||||
|
toast({
|
||||||
|
title: t("error"),
|
||||||
|
description: formatAxiosError(e),
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
} finally {
|
} finally {
|
||||||
setIsRefreshing(false);
|
setTogglingId(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const setEnabled = (rule: AlertRule, enabled: boolean) => {
|
|
||||||
upsertRule(orgId, { ...rule, enabled, updatedAt: isoNow() });
|
|
||||||
refreshFromStorage();
|
|
||||||
};
|
|
||||||
|
|
||||||
const confirmDelete = async () => {
|
const confirmDelete = async () => {
|
||||||
if (!selected) return;
|
if (!selected) return;
|
||||||
deleteRule(orgId, selected.id);
|
try {
|
||||||
refreshFromStorage();
|
await api.delete(
|
||||||
setDeleteOpen(false);
|
`/org/${orgId}/alert-rule/${selected.alertRuleId}`
|
||||||
setSelected(null);
|
);
|
||||||
toast({ title: t("alertingRuleDeleted") });
|
await invalidate();
|
||||||
|
toast({ title: t("alertingRuleDeleted") });
|
||||||
|
} catch (e) {
|
||||||
|
toast({
|
||||||
|
title: t("error"),
|
||||||
|
description: formatAxiosError(e),
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setDeleteOpen(false);
|
||||||
|
setSelected(null);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const columns: ExtendedColumnDef<AlertRule>[] = [
|
const columns: ExtendedColumnDef<AlertRuleRow>[] = [
|
||||||
{
|
{
|
||||||
accessorKey: "name",
|
accessorKey: "name",
|
||||||
enableHiding: false,
|
enableHiding: false,
|
||||||
@@ -163,18 +171,6 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
|||||||
),
|
),
|
||||||
cell: ({ row }) => <span>{triggerLabel(row.original, t)}</span>
|
cell: ({ row }) => <span>{triggerLabel(row.original, t)}</span>
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: "actionsCol",
|
|
||||||
friendlyName: t("alertingColumnActions"),
|
|
||||||
header: () => (
|
|
||||||
<span className="p-3">{t("alertingColumnActions")}</span>
|
|
||||||
),
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex flex-wrap gap-1 max-w-[14rem]">
|
|
||||||
{actionBadges(row.original, t)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
accessorKey: "enabled",
|
accessorKey: "enabled",
|
||||||
friendlyName: t("alertingColumnEnabled"),
|
friendlyName: t("alertingColumnEnabled"),
|
||||||
@@ -186,6 +182,7 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
|||||||
return (
|
return (
|
||||||
<Switch
|
<Switch
|
||||||
checked={r.enabled}
|
checked={r.enabled}
|
||||||
|
disabled={togglingId === r.alertRuleId}
|
||||||
onCheckedChange={(v) => setEnabled(r, v)}
|
onCheckedChange={(v) => setEnabled(r, v)}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -230,7 +227,7 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
|||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
<Button variant="outline" asChild>
|
<Button variant="outline" asChild>
|
||||||
<Link href={ruleHref(orgId, r.id)}>
|
<Link href={ruleHref(orgId, r.alertRuleId)}>
|
||||||
{t("edit")}
|
{t("edit")}
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
@@ -270,8 +267,8 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
|||||||
onAdd={() => {
|
onAdd={() => {
|
||||||
router.push(`/${orgId}/settings/alerting/create`);
|
router.push(`/${orgId}/settings/alerting/create`);
|
||||||
}}
|
}}
|
||||||
onRefresh={refreshData}
|
onRefresh={() => refetch()}
|
||||||
isRefreshing={isRefreshing}
|
isRefreshing={isRefetching || isLoading}
|
||||||
addButtonText={t("alertingAddRule")}
|
addButtonText={t("alertingAddRule")}
|
||||||
enableColumnVisibility
|
enableColumnVisibility
|
||||||
stickyLeftColumn="name"
|
stickyLeftColumn="name"
|
||||||
|
|||||||
@@ -172,9 +172,7 @@ function SiteMultiSelect({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const ALERT_RESOURCES_PAGE_SIZE = 10;
|
function HealthCheckMultiSelect({
|
||||||
|
|
||||||
function ResourceTenMultiSelect({
|
|
||||||
orgId,
|
orgId,
|
||||||
value,
|
value,
|
||||||
onChange
|
onChange
|
||||||
@@ -185,58 +183,46 @@ function ResourceTenMultiSelect({
|
|||||||
}) {
|
}) {
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const { data: resources = [] } = useQuery(
|
const [q, setQ] = useState("");
|
||||||
orgQueries.resources({
|
const [debounced] = useDebounce(q, 150);
|
||||||
orgId,
|
|
||||||
perPage: ALERT_RESOURCES_PAGE_SIZE
|
const { data: healthChecks = [] } = useQuery(
|
||||||
})
|
orgQueries.healthChecks({ orgId })
|
||||||
);
|
);
|
||||||
const rows = useMemo(() => {
|
|
||||||
const out: {
|
const shown = useMemo(() => {
|
||||||
resourceId: number;
|
const query = debounced.trim().toLowerCase();
|
||||||
name: string;
|
const base = query
|
||||||
targetIds: number[];
|
? healthChecks.filter((hc) =>
|
||||||
}[] = [];
|
hc.resourceName.toLowerCase().includes(query)
|
||||||
for (const r of resources) {
|
)
|
||||||
const targetIds = r.targets.map((x) => x.targetId);
|
: healthChecks;
|
||||||
if (targetIds.length > 0) {
|
// Always keep already-selected items visible even if they fall outside the search
|
||||||
out.push({
|
if (query && value.length > 0) {
|
||||||
resourceId: r.resourceId,
|
const selectedNotInBase = healthChecks.filter(
|
||||||
name: r.name,
|
(hc) =>
|
||||||
targetIds
|
value.includes(hc.targetHealthCheckId) &&
|
||||||
});
|
!base.some(
|
||||||
}
|
(b) => b.targetHealthCheckId === hc.targetHealthCheckId
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return [...selectedNotInBase, ...base];
|
||||||
}
|
}
|
||||||
return out;
|
return base;
|
||||||
}, [resources]);
|
}, [healthChecks, debounced, value]);
|
||||||
|
|
||||||
const selectedResourceCount = useMemo(
|
const toggle = (id: number) => {
|
||||||
() =>
|
if (value.includes(id)) {
|
||||||
rows.filter(
|
onChange(value.filter((x) => x !== id));
|
||||||
(row) =>
|
|
||||||
row.targetIds.length > 0 &&
|
|
||||||
row.targetIds.every((id) => value.includes(id))
|
|
||||||
).length,
|
|
||||||
[rows, value]
|
|
||||||
);
|
|
||||||
|
|
||||||
const toggle = (targetIds: number[]) => {
|
|
||||||
const allOn =
|
|
||||||
targetIds.length > 0 &&
|
|
||||||
targetIds.every((id) => value.includes(id));
|
|
||||||
if (allOn) {
|
|
||||||
onChange(value.filter((id) => !targetIds.includes(id)));
|
|
||||||
} else {
|
} else {
|
||||||
onChange([...new Set([...value, ...targetIds])]);
|
onChange([...value, id]);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const summary =
|
const summary =
|
||||||
selectedResourceCount === 0
|
value.length === 0
|
||||||
? t("alertingSelectResources")
|
? t("alertingSelectHealthChecks")
|
||||||
: t("alertingResourcesSelected", {
|
: t("alertingHealthChecksSelected", { count: value.length });
|
||||||
count: selectedResourceCount
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
<Popover open={open} onOpenChange={setOpen}>
|
||||||
@@ -255,38 +241,42 @@ function ResourceTenMultiSelect({
|
|||||||
className="w-[var(--radix-popover-trigger-width)] p-0"
|
className="w-[var(--radix-popover-trigger-width)] p-0"
|
||||||
align="start"
|
align="start"
|
||||||
>
|
>
|
||||||
<div className="max-h-72 overflow-y-auto p-2 space-y-0.5">
|
<Command shouldFilter={false}>
|
||||||
{rows.length === 0 ? (
|
<CommandInput
|
||||||
<p className="text-sm text-muted-foreground px-2 py-1.5">
|
placeholder={t("alertingSearchHealthChecks")}
|
||||||
{t("alertingResourcesEmpty")}
|
value={q}
|
||||||
</p>
|
onValueChange={setQ}
|
||||||
) : (
|
/>
|
||||||
rows.map((row) => {
|
<CommandList>
|
||||||
const checked =
|
<CommandEmpty>
|
||||||
row.targetIds.length > 0 &&
|
{t("alertingHealthChecksEmpty")}
|
||||||
row.targetIds.every((id) =>
|
</CommandEmpty>
|
||||||
value.includes(id)
|
<CommandGroup>
|
||||||
);
|
{shown.map((hc) => (
|
||||||
return (
|
<CommandItem
|
||||||
<button
|
key={hc.targetHealthCheckId}
|
||||||
key={row.resourceId}
|
value={`${hc.targetHealthCheckId}:${hc.resourceName}`}
|
||||||
type="button"
|
onSelect={() =>
|
||||||
onClick={() => toggle(row.targetIds)}
|
toggle(hc.targetHealthCheckId)
|
||||||
className="flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent"
|
}
|
||||||
|
className="cursor-pointer"
|
||||||
>
|
>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={checked}
|
checked={value.includes(
|
||||||
className="pointer-events-none shrink-0"
|
hc.targetHealthCheckId
|
||||||
|
)}
|
||||||
|
className="mr-2 pointer-events-none shrink-0"
|
||||||
aria-hidden
|
aria-hidden
|
||||||
|
tabIndex={-1}
|
||||||
/>
|
/>
|
||||||
<span className="truncate">
|
<span className="truncate">
|
||||||
{row.name}
|
{hc.resourceName}
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</CommandItem>
|
||||||
);
|
))}
|
||||||
})
|
</CommandGroup>
|
||||||
)}
|
</CommandList>
|
||||||
</div>
|
</Command>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
);
|
);
|
||||||
@@ -909,11 +899,13 @@ export function AlertRuleSourceFields({
|
|||||||
) : (
|
) : (
|
||||||
<FormField
|
<FormField
|
||||||
control={control}
|
control={control}
|
||||||
name="targetIds"
|
name="healthCheckIds"
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>{t("alertingPickResources")}</FormLabel>
|
<FormLabel>
|
||||||
<ResourceTenMultiSelect
|
{t("alertingPickHealthChecks")}
|
||||||
|
</FormLabel>
|
||||||
|
<HealthCheckMultiSelect
|
||||||
orgId={orgId}
|
orgId={orgId}
|
||||||
value={field.value}
|
value={field.value}
|
||||||
onChange={field.onChange}
|
onChange={field.onChange}
|
||||||
|
|||||||
@@ -29,11 +29,14 @@ import { toast } from "@app/hooks/useToast";
|
|||||||
import {
|
import {
|
||||||
buildFormSchema,
|
buildFormSchema,
|
||||||
defaultFormValues,
|
defaultFormValues,
|
||||||
formValuesToRule,
|
formValuesToApiPayload,
|
||||||
type AlertRuleFormAction,
|
type AlertRuleFormAction,
|
||||||
type AlertRuleFormValues
|
type AlertRuleFormValues
|
||||||
} from "@app/lib/alertRuleForm";
|
} from "@app/lib/alertRuleForm";
|
||||||
import { upsertRule } from "@app/lib/alertRulesLocalStorage";
|
import { createApiClient, formatAxiosError } from "@app/lib/api";
|
||||||
|
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||||
|
import type { CreateAlertRuleResponse } from "@server/private/routers/alertRule";
|
||||||
|
import type { AxiosResponse } from "axios";
|
||||||
import { cn } from "@app/lib/cn";
|
import { cn } from "@app/lib/cn";
|
||||||
import {
|
import {
|
||||||
Background,
|
Background,
|
||||||
@@ -77,10 +80,10 @@ function summarizeSource(v: AlertRuleFormValues, t: AlertRuleT) {
|
|||||||
}
|
}
|
||||||
return t("alertingSummarySites", { count: v.siteIds.length });
|
return t("alertingSummarySites", { count: v.siteIds.length });
|
||||||
}
|
}
|
||||||
if (v.targetIds.length === 0) {
|
if (v.healthCheckIds.length === 0) {
|
||||||
return t("alertingNodeNotConfigured");
|
return t("alertingNodeNotConfigured");
|
||||||
}
|
}
|
||||||
return t("alertingSummaryHealthChecks", { count: v.targetIds.length });
|
return t("alertingSummaryHealthChecks", { count: v.healthCheckIds.length });
|
||||||
}
|
}
|
||||||
|
|
||||||
function summarizeTrigger(v: AlertRuleFormValues, t: AlertRuleT) {
|
function summarizeTrigger(v: AlertRuleFormValues, t: AlertRuleT) {
|
||||||
@@ -175,7 +178,7 @@ function stepConfigured(
|
|||||||
if (step === "source") {
|
if (step === "source") {
|
||||||
return v.sourceType === "site"
|
return v.sourceType === "site"
|
||||||
? v.siteIds.length > 0
|
? v.siteIds.length > 0
|
||||||
: v.targetIds.length > 0;
|
: v.healthCheckIds.length > 0;
|
||||||
}
|
}
|
||||||
return Boolean(v.trigger);
|
return Boolean(v.trigger);
|
||||||
}
|
}
|
||||||
@@ -300,8 +303,7 @@ function buildNodeData(
|
|||||||
|
|
||||||
type AlertRuleGraphEditorProps = {
|
type AlertRuleGraphEditorProps = {
|
||||||
orgId: string;
|
orgId: string;
|
||||||
ruleId: string;
|
alertRuleId?: number;
|
||||||
createdAt: string;
|
|
||||||
initialValues: AlertRuleFormValues;
|
initialValues: AlertRuleFormValues;
|
||||||
isNew: boolean;
|
isNew: boolean;
|
||||||
};
|
};
|
||||||
@@ -310,13 +312,14 @@ const FORM_ID = "alert-rule-graph-form";
|
|||||||
|
|
||||||
export default function AlertRuleGraphEditor({
|
export default function AlertRuleGraphEditor({
|
||||||
orgId,
|
orgId,
|
||||||
ruleId,
|
alertRuleId,
|
||||||
createdAt,
|
|
||||||
initialValues,
|
initialValues,
|
||||||
isNew
|
isNew
|
||||||
}: AlertRuleGraphEditorProps) {
|
}: AlertRuleGraphEditorProps) {
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const api = createApiClient(useEnvContext());
|
||||||
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const schema = useMemo(() => buildFormSchema(t), [t]);
|
const schema = useMemo(() => buildFormSchema(t), [t]);
|
||||||
const form = useForm<AlertRuleFormValues>({
|
const form = useForm<AlertRuleFormValues>({
|
||||||
resolver: zodResolver(schema),
|
resolver: zodResolver(schema),
|
||||||
@@ -335,8 +338,8 @@ export default function AlertRuleGraphEditor({
|
|||||||
useWatch({ control: form.control, name: "sourceType" }) ?? "site";
|
useWatch({ control: form.control, name: "sourceType" }) ?? "site";
|
||||||
const wSiteIds =
|
const wSiteIds =
|
||||||
useWatch({ control: form.control, name: "siteIds" }) ?? [];
|
useWatch({ control: form.control, name: "siteIds" }) ?? [];
|
||||||
const wTargetIds =
|
const wHealthCheckIds =
|
||||||
useWatch({ control: form.control, name: "targetIds" }) ?? [];
|
useWatch({ control: form.control, name: "healthCheckIds" }) ?? [];
|
||||||
const wTrigger =
|
const wTrigger =
|
||||||
useWatch({ control: form.control, name: "trigger" }) ??
|
useWatch({ control: form.control, name: "trigger" }) ??
|
||||||
"site_offline";
|
"site_offline";
|
||||||
@@ -349,7 +352,7 @@ export default function AlertRuleGraphEditor({
|
|||||||
enabled: wEnabled,
|
enabled: wEnabled,
|
||||||
sourceType: wSourceType,
|
sourceType: wSourceType,
|
||||||
siteIds: wSiteIds,
|
siteIds: wSiteIds,
|
||||||
targetIds: wTargetIds,
|
healthCheckIds: wHealthCheckIds,
|
||||||
trigger: wTrigger,
|
trigger: wTrigger,
|
||||||
actions: wActions
|
actions: wActions
|
||||||
}),
|
}),
|
||||||
@@ -358,7 +361,7 @@ export default function AlertRuleGraphEditor({
|
|||||||
wEnabled,
|
wEnabled,
|
||||||
wSourceType,
|
wSourceType,
|
||||||
wSiteIds,
|
wSiteIds,
|
||||||
wTargetIds,
|
wHealthCheckIds,
|
||||||
wTrigger,
|
wTrigger,
|
||||||
wActions
|
wActions
|
||||||
]
|
]
|
||||||
@@ -472,7 +475,7 @@ export default function AlertRuleGraphEditor({
|
|||||||
if (!m) {
|
if (!m) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const i = Number(m[1], 10);
|
const i = parseInt(m[1], 10);
|
||||||
if (i >= wActions.length) {
|
if (i >= wActions.length) {
|
||||||
setSelectedStep(
|
setSelectedStep(
|
||||||
wActions.length > 0
|
wActions.length > 0
|
||||||
@@ -486,12 +489,33 @@ export default function AlertRuleGraphEditor({
|
|||||||
setSelectedStep(node.id);
|
setSelectedStep(node.id);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const onSubmit = form.handleSubmit((values) => {
|
const onSubmit = form.handleSubmit(async (values) => {
|
||||||
const next = formValuesToRule(values, ruleId, createdAt);
|
setIsSaving(true);
|
||||||
upsertRule(orgId, next);
|
try {
|
||||||
toast({ title: t("alertingRuleSaved") });
|
const payload = formValuesToApiPayload(values);
|
||||||
if (isNew) {
|
if (isNew) {
|
||||||
router.replace(`/${orgId}/settings/alerting/${ruleId}`);
|
const res = await api.put<
|
||||||
|
AxiosResponse<CreateAlertRuleResponse>
|
||||||
|
>(`/org/${orgId}/alert-rule`, payload);
|
||||||
|
toast({ title: t("alertingRuleSaved") });
|
||||||
|
router.replace(
|
||||||
|
`/${orgId}/settings/alerting/${res.data.data.alertRuleId}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await api.post(
|
||||||
|
`/org/${orgId}/alert-rule/${alertRuleId}`,
|
||||||
|
payload
|
||||||
|
);
|
||||||
|
toast({ title: t("alertingRuleSaved") });
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
toast({
|
||||||
|
title: t("error"),
|
||||||
|
description: formatAxiosError(e),
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsSaving(false);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -565,8 +589,8 @@ export default function AlertRuleGraphEditor({
|
|||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<Button type="submit">
|
<Button type="submit" disabled={isSaving}>
|
||||||
{t("save")}
|
{isSaving ? t("saving") : t("save")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,17 +1,27 @@
|
|||||||
import type { Tag } from "@app/components/tags/tag-input";
|
import type { Tag } from "@app/components/tags/tag-input";
|
||||||
import {
|
|
||||||
type AlertRule,
|
|
||||||
type AlertTrigger,
|
|
||||||
isoNow,
|
|
||||||
type AlertAction as StoredAlertAction
|
|
||||||
} from "@app/lib/alertRulesLocalStorage";
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Shared primitive schemas
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export const tagSchema = z.object({
|
export const tagSchema = z.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
text: z.string()
|
text: z.string()
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Form-layer types
|
||||||
|
// NOTE: the form uses "health_check_unhealthy" internally; it maps to the
|
||||||
|
// backend's "health_check_not_healthy" at the API boundary.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type AlertTrigger =
|
||||||
|
| "site_online"
|
||||||
|
| "site_offline"
|
||||||
|
| "health_check_healthy"
|
||||||
|
| "health_check_unhealthy";
|
||||||
|
|
||||||
export type AlertRuleFormAction =
|
export type AlertRuleFormAction =
|
||||||
| {
|
| {
|
||||||
type: "notify";
|
type: "notify";
|
||||||
@@ -33,11 +43,86 @@ export type AlertRuleFormValues = {
|
|||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
sourceType: "site" | "health_check";
|
sourceType: "site" | "health_check";
|
||||||
siteIds: number[];
|
siteIds: number[];
|
||||||
targetIds: number[];
|
healthCheckIds: number[];
|
||||||
trigger: AlertTrigger;
|
trigger: AlertTrigger;
|
||||||
actions: AlertRuleFormAction[];
|
actions: AlertRuleFormAction[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// API boundary types
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type AlertRuleApiPayload = {
|
||||||
|
name: string;
|
||||||
|
eventType:
|
||||||
|
| "site_online"
|
||||||
|
| "site_offline"
|
||||||
|
| "health_check_healthy"
|
||||||
|
| "health_check_not_healthy";
|
||||||
|
enabled: boolean;
|
||||||
|
siteIds: number[];
|
||||||
|
healthCheckIds: number[];
|
||||||
|
userIds: string[];
|
||||||
|
roleIds: string[];
|
||||||
|
emails: string[];
|
||||||
|
webhookActions: {
|
||||||
|
webhookUrl: string;
|
||||||
|
enabled: boolean;
|
||||||
|
config?: string;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Shape of what GET /org/:orgId/alert-rule/:alertRuleId returns
|
||||||
|
export type AlertRuleApiResponse = {
|
||||||
|
alertRuleId: number;
|
||||||
|
orgId: string;
|
||||||
|
name: string;
|
||||||
|
eventType: string;
|
||||||
|
enabled: boolean;
|
||||||
|
cooldownSeconds: number;
|
||||||
|
lastTriggeredAt: number | null;
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
siteIds: number[];
|
||||||
|
healthCheckIds: number[];
|
||||||
|
recipients: {
|
||||||
|
recipientId: number;
|
||||||
|
userId: string | null;
|
||||||
|
roleId: string | null;
|
||||||
|
email: string | null;
|
||||||
|
}[];
|
||||||
|
webhookActions: {
|
||||||
|
webhookActionId: number;
|
||||||
|
webhookUrl: string;
|
||||||
|
enabled: boolean;
|
||||||
|
lastSentAt: number | null;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function triggerToEventType(
|
||||||
|
trigger: AlertTrigger
|
||||||
|
): AlertRuleApiPayload["eventType"] {
|
||||||
|
if (trigger === "health_check_unhealthy") {
|
||||||
|
return "health_check_not_healthy";
|
||||||
|
}
|
||||||
|
return trigger as AlertRuleApiPayload["eventType"];
|
||||||
|
}
|
||||||
|
|
||||||
|
function eventTypeToTrigger(eventType: string): AlertTrigger {
|
||||||
|
if (eventType === "health_check_not_healthy") {
|
||||||
|
return "health_check_unhealthy";
|
||||||
|
}
|
||||||
|
return eventType as AlertTrigger;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Zod form schema (for react-hook-form validation)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export function buildFormSchema(t: (k: string) => string) {
|
export function buildFormSchema(t: (k: string) => string) {
|
||||||
return z
|
return z
|
||||||
.object({
|
.object({
|
||||||
@@ -45,7 +130,7 @@ export function buildFormSchema(t: (k: string) => string) {
|
|||||||
enabled: z.boolean(),
|
enabled: z.boolean(),
|
||||||
sourceType: z.enum(["site", "health_check"]),
|
sourceType: z.enum(["site", "health_check"]),
|
||||||
siteIds: z.array(z.number()),
|
siteIds: z.array(z.number()),
|
||||||
targetIds: z.array(z.number()),
|
healthCheckIds: z.array(z.number()),
|
||||||
trigger: z.enum([
|
trigger: z.enum([
|
||||||
"site_online",
|
"site_online",
|
||||||
"site_offline",
|
"site_offline",
|
||||||
@@ -97,18 +182,15 @@ export function buildFormSchema(t: (k: string) => string) {
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
val.sourceType === "health_check" &&
|
val.sourceType === "health_check" &&
|
||||||
val.targetIds.length === 0
|
val.healthCheckIds.length === 0
|
||||||
) {
|
) {
|
||||||
ctx.addIssue({
|
ctx.addIssue({
|
||||||
code: z.ZodIssueCode.custom,
|
code: z.ZodIssueCode.custom,
|
||||||
message: t("alertingErrorPickHealthChecks"),
|
message: t("alertingErrorPickHealthChecks"),
|
||||||
path: ["targetIds"]
|
path: ["healthCheckIds"]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const siteTriggers: AlertTrigger[] = [
|
const siteTriggers: AlertTrigger[] = ["site_online", "site_offline"];
|
||||||
"site_online",
|
|
||||||
"site_offline"
|
|
||||||
];
|
|
||||||
const hcTriggers: AlertTrigger[] = [
|
const hcTriggers: AlertTrigger[] = [
|
||||||
"health_check_healthy",
|
"health_check_healthy",
|
||||||
"health_check_unhealthy"
|
"health_check_unhealthy"
|
||||||
@@ -156,7 +238,6 @@ export function buildFormSchema(t: (k: string) => string) {
|
|||||||
}
|
}
|
||||||
if (a.type === "webhook") {
|
if (a.type === "webhook") {
|
||||||
try {
|
try {
|
||||||
// eslint-disable-next-line no-new
|
|
||||||
new URL(a.url.trim());
|
new URL(a.url.trim());
|
||||||
} catch {
|
} catch {
|
||||||
ctx.addIssue({
|
ctx.addIssue({
|
||||||
@@ -170,13 +251,17 @@ export function buildFormSchema(t: (k: string) => string) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// defaultFormValues
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export function defaultFormValues(): AlertRuleFormValues {
|
export function defaultFormValues(): AlertRuleFormValues {
|
||||||
return {
|
return {
|
||||||
name: "",
|
name: "",
|
||||||
enabled: true,
|
enabled: true,
|
||||||
sourceType: "site",
|
sourceType: "site",
|
||||||
siteIds: [],
|
siteIds: [],
|
||||||
targetIds: [],
|
healthCheckIds: [],
|
||||||
trigger: "site_offline",
|
trigger: "site_offline",
|
||||||
actions: [
|
actions: [
|
||||||
{
|
{
|
||||||
@@ -189,95 +274,128 @@ export function defaultFormValues(): AlertRuleFormValues {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ruleToFormValues(rule: AlertRule): AlertRuleFormValues {
|
// ---------------------------------------------------------------------------
|
||||||
const actions: AlertRuleFormAction[] = rule.actions.map(
|
// API response → form values
|
||||||
(a: StoredAlertAction) => {
|
// ---------------------------------------------------------------------------
|
||||||
if (a.type === "notify") {
|
|
||||||
return {
|
export function apiResponseToFormValues(
|
||||||
type: "notify",
|
rule: AlertRuleApiResponse
|
||||||
userIds: a.userIds.map(String),
|
): AlertRuleFormValues {
|
||||||
roleIds: [...a.roleIds],
|
const trigger = eventTypeToTrigger(rule.eventType);
|
||||||
emailTags: a.emails.map((e) => ({ id: e, text: e }))
|
const sourceType = rule.eventType.startsWith("site_")
|
||||||
};
|
? "site"
|
||||||
}
|
: "health_check";
|
||||||
if (a.type === "sms") {
|
|
||||||
return {
|
// Collect notify recipients into a single notify action (if any)
|
||||||
type: "sms",
|
const userIds = rule.recipients
|
||||||
phoneTags: a.phoneNumbers.map((p) => ({ id: p, text: p }))
|
.filter((r) => r.userId != null)
|
||||||
};
|
.map((r) => r.userId!);
|
||||||
}
|
const roleIds = rule.recipients
|
||||||
return {
|
.filter((r) => r.roleId != null)
|
||||||
type: "webhook",
|
.map((r) => parseInt(r.roleId!, 10))
|
||||||
url: a.url,
|
.filter((n) => !isNaN(n));
|
||||||
method: a.method,
|
const emailTags = rule.recipients
|
||||||
headers:
|
.filter((r) => r.email != null)
|
||||||
a.headers.length > 0
|
.map((r) => ({ id: r.email!, text: r.email! }));
|
||||||
? a.headers.map((h) => ({ ...h }))
|
|
||||||
: [{ key: "", value: "" }],
|
const actions: AlertRuleFormAction[] = [];
|
||||||
secret: a.secret ?? ""
|
|
||||||
};
|
if (userIds.length > 0 || roleIds.length > 0 || emailTags.length > 0) {
|
||||||
}
|
actions.push({ type: "notify", userIds, roleIds, emailTags });
|
||||||
);
|
}
|
||||||
|
|
||||||
|
// Each webhook action becomes its own form webhook action
|
||||||
|
for (const w of rule.webhookActions) {
|
||||||
|
actions.push({
|
||||||
|
type: "webhook",
|
||||||
|
url: w.webhookUrl,
|
||||||
|
method: "POST",
|
||||||
|
headers: [{ key: "", value: "" }],
|
||||||
|
secret: ""
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Always ensure at least one action so the form is valid
|
||||||
|
if (actions.length === 0) {
|
||||||
|
actions.push({
|
||||||
|
type: "notify",
|
||||||
|
userIds: [],
|
||||||
|
roleIds: [],
|
||||||
|
emailTags: []
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
name: rule.name,
|
name: rule.name,
|
||||||
enabled: rule.enabled,
|
enabled: rule.enabled,
|
||||||
sourceType: rule.source.type,
|
sourceType,
|
||||||
siteIds:
|
siteIds: rule.siteIds,
|
||||||
rule.source.type === "site" ? [...rule.source.siteIds] : [],
|
healthCheckIds: rule.healthCheckIds,
|
||||||
targetIds:
|
trigger,
|
||||||
rule.source.type === "health_check"
|
|
||||||
? [...rule.source.targetIds]
|
|
||||||
: [],
|
|
||||||
trigger: rule.trigger,
|
|
||||||
actions
|
actions
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formValuesToRule(
|
// ---------------------------------------------------------------------------
|
||||||
v: AlertRuleFormValues,
|
// Form values → API payload
|
||||||
id: string,
|
// ---------------------------------------------------------------------------
|
||||||
createdAt: string
|
|
||||||
): AlertRule {
|
export function formValuesToApiPayload(
|
||||||
const source =
|
values: AlertRuleFormValues
|
||||||
v.sourceType === "site"
|
): AlertRuleApiPayload {
|
||||||
? { type: "site" as const, siteIds: v.siteIds }
|
const eventType = triggerToEventType(values.trigger);
|
||||||
: {
|
|
||||||
type: "health_check" as const,
|
// Collect all notify-type actions and merge their recipient lists
|
||||||
targetIds: v.targetIds
|
const allUserIds: string[] = [];
|
||||||
};
|
const allRoleIds: string[] = [];
|
||||||
const actions = v.actions.map((a) => {
|
const allEmails: string[] = [];
|
||||||
if (a.type === "notify") {
|
|
||||||
return {
|
const webhookActions: AlertRuleApiPayload["webhookActions"] = [];
|
||||||
type: "notify" as const,
|
|
||||||
userIds: a.userIds,
|
for (const action of values.actions) {
|
||||||
roleIds: a.roleIds,
|
if (action.type === "notify") {
|
||||||
emails: a.emailTags.map((tg) => tg.text.trim()).filter(Boolean)
|
allUserIds.push(...action.userIds);
|
||||||
};
|
allRoleIds.push(...action.roleIds.map(String));
|
||||||
}
|
allEmails.push(
|
||||||
if (a.type === "sms") {
|
...action.emailTags
|
||||||
return {
|
.map((t) => t.text.trim())
|
||||||
type: "sms" as const,
|
|
||||||
phoneNumbers: a.phoneTags
|
|
||||||
.map((tg) => tg.text.trim())
|
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
};
|
);
|
||||||
|
} else if (action.type === "webhook") {
|
||||||
|
webhookActions.push({
|
||||||
|
webhookUrl: action.url.trim(),
|
||||||
|
enabled: true,
|
||||||
|
// Encode any headers / secret as config JSON if present
|
||||||
|
...(action.secret.trim() ||
|
||||||
|
action.headers.some((h) => h.key.trim())
|
||||||
|
? {
|
||||||
|
config: JSON.stringify({
|
||||||
|
secret: action.secret.trim() || undefined,
|
||||||
|
headers: action.headers.filter(
|
||||||
|
(h) => h.key.trim()
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
: {})
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return {
|
// sms is not supported by the backend; silently skip
|
||||||
type: "webhook" as const,
|
}
|
||||||
url: a.url.trim(),
|
|
||||||
method: a.method,
|
// Deduplicate
|
||||||
headers: a.headers.filter((h) => h.key.trim() || h.value.trim()),
|
const uniqueUserIds = [...new Set(allUserIds)];
|
||||||
secret: a.secret.trim() || undefined
|
const uniqueRoleIds = [...new Set(allRoleIds)];
|
||||||
};
|
const uniqueEmails = [...new Set(allEmails)];
|
||||||
});
|
|
||||||
return {
|
return {
|
||||||
id,
|
name: values.name.trim(),
|
||||||
name: v.name.trim(),
|
eventType,
|
||||||
enabled: v.enabled,
|
enabled: values.enabled,
|
||||||
createdAt,
|
siteIds: values.siteIds,
|
||||||
updatedAt: isoNow(),
|
healthCheckIds: values.healthCheckIds,
|
||||||
source,
|
userIds: uniqueUserIds,
|
||||||
trigger: v.trigger,
|
roleIds: uniqueRoleIds,
|
||||||
actions
|
emails: uniqueEmails,
|
||||||
|
webhookActions
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -4,9 +4,11 @@ import type { ListClientsResponse } from "@server/routers/client";
|
|||||||
import type { ListDomainsResponse } from "@server/routers/domain";
|
import type { ListDomainsResponse } from "@server/routers/domain";
|
||||||
import type {
|
import type {
|
||||||
GetResourceWhitelistResponse,
|
GetResourceWhitelistResponse,
|
||||||
|
ListHealthChecksResponse,
|
||||||
ListResourceNamesResponse,
|
ListResourceNamesResponse,
|
||||||
ListResourcesResponse
|
ListResourcesResponse
|
||||||
} from "@server/routers/resource";
|
} from "@server/routers/resource";
|
||||||
|
import type { ListAlertRulesResponse } from "@server/private/routers/alertRule";
|
||||||
import type { ListRolesResponse } from "@server/routers/role";
|
import type { ListRolesResponse } from "@server/routers/role";
|
||||||
import type { ListSitesResponse } from "@server/routers/site";
|
import type { ListSitesResponse } from "@server/routers/site";
|
||||||
import type {
|
import type {
|
||||||
@@ -230,6 +232,38 @@ export const orgQueries = {
|
|||||||
|
|
||||||
return res.data.data.resources;
|
return res.data.data.resources;
|
||||||
}
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
healthChecks: ({
|
||||||
|
orgId,
|
||||||
|
perPage = 10_000
|
||||||
|
}: {
|
||||||
|
orgId: string;
|
||||||
|
perPage?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["ORG", orgId, "HEALTH_CHECKS", { perPage }] as const,
|
||||||
|
queryFn: async ({ signal, meta }) => {
|
||||||
|
const sp = new URLSearchParams({
|
||||||
|
limit: perPage.toString(),
|
||||||
|
offset: "0"
|
||||||
|
});
|
||||||
|
const res = await meta!.api.get<
|
||||||
|
AxiosResponse<ListHealthChecksResponse>
|
||||||
|
>(`/org/${orgId}/health-checks?${sp.toString()}`, { signal });
|
||||||
|
return res.data.data.healthChecks;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
alertRules: ({ orgId }: { orgId: string }) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["ORG", orgId, "ALERT_RULES"] as const,
|
||||||
|
queryFn: async ({ signal, meta }) => {
|
||||||
|
const res = await meta!.api.get<
|
||||||
|
AxiosResponse<ListAlertRulesResponse>
|
||||||
|
>(`/org/${orgId}/alert-rules`, { signal });
|
||||||
|
return res.data.data.alertRules;
|
||||||
|
}
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user