Support all resources,sites,health checks

This commit is contained in:
Owen
2026-04-20 20:48:14 -07:00
parent d7a9e1a517
commit 5e88862e29
5 changed files with 266 additions and 61 deletions

View File

@@ -1376,6 +1376,18 @@
"alertingPickSites": "Sites", "alertingPickSites": "Sites",
"alertingPickHealthChecks": "Health checks", "alertingPickHealthChecks": "Health checks",
"alertingPickResources": "Resources", "alertingPickResources": "Resources",
"alertingAllSites": "All sites",
"alertingAllSitesDescription": "Alert fires for any site",
"alertingSpecificSites": "Specific sites",
"alertingSpecificSitesDescription": "Choose specific sites to watch",
"alertingAllHealthChecks": "All health checks",
"alertingAllHealthChecksDescription": "Alert fires for any health check",
"alertingSpecificHealthChecks": "Specific health checks",
"alertingSpecificHealthChecksDescription": "Choose specific health checks to watch",
"alertingAllResources": "All resources",
"alertingAllResourcesDescription": "Alert fires for any resource",
"alertingSpecificResources": "Specific resources",
"alertingSpecificResourcesDescription": "Choose specific resources to watch",
"alertingSelectResources": "Select resources…", "alertingSelectResources": "Select resources…",
"alertingResourcesSelected": "{count} resources selected", "alertingResourcesSelected": "{count} resources selected",
"alertingResourcesEmpty": "No resources with targets in the first 10 results.", "alertingResourcesEmpty": "No resources with targets in the first 10 results.",

View File

@@ -66,14 +66,17 @@ const bodySchema = z
cooldownSeconds: z.number().int().nonnegative().optional().default(300), cooldownSeconds: z.number().int().nonnegative().optional().default(300),
// Source join tables - which is required depends on eventType // Source join tables - which is required depends on eventType
siteIds: z.array(z.number().int().positive()).optional().default([]), siteIds: z.array(z.number().int().positive()).optional().default([]),
allSites: z.boolean().optional().default(false),
healthCheckIds: z healthCheckIds: z
.array(z.number().int().positive()) .array(z.number().int().positive())
.optional() .optional()
.default([]), .default([]),
allHealthChecks: z.boolean().optional().default(false),
resourceIds: z resourceIds: z
.array(z.number().int().positive()) .array(z.number().int().positive())
.optional() .optional()
.default([]), .default([]),
allResources: z.boolean().optional().default(false),
// Email recipients (flat) // Email recipients (flat)
userIds: z.array(z.string().nonempty()).optional().default([]), userIds: z.array(z.string().nonempty()).optional().default([]),
roleIds: z.array(z.number()).optional().default([]), roleIds: z.array(z.number()).optional().default([]),
@@ -92,19 +95,19 @@ const bodySchema = z
val.eventType val.eventType
); );
if (isSiteEvent && val.siteIds.length === 0) { if (isSiteEvent && !val.allSites && val.siteIds.length === 0) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: "At least one siteId is required for site event types", message: "At least one siteId is required for site event types when allSites is false",
path: ["siteIds"] path: ["siteIds"]
}); });
} }
if (isHcEvent && val.healthCheckIds.length === 0) { if (isHcEvent && !val.allHealthChecks && val.healthCheckIds.length === 0) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: message:
"At least one healthCheckId is required for health check event types", "At least one healthCheckId is required for health check event types when allHealthChecks is false",
path: ["healthCheckIds"] path: ["healthCheckIds"]
}); });
} }
@@ -125,10 +128,10 @@ const bodySchema = z
}); });
} }
if (isResourceEvent && val.resourceIds.length === 0) { if (isResourceEvent && !val.allResources && val.resourceIds.length === 0) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: "At least one resourceId is required for resource event types", message: "At least one resourceId is required for resource event types when allResources is false",
path: ["resourceIds"] path: ["resourceIds"]
}); });
} }
@@ -222,8 +225,11 @@ export async function createAlertRule(
enabled, enabled,
cooldownSeconds, cooldownSeconds,
siteIds, siteIds,
allSites,
healthCheckIds, healthCheckIds,
allHealthChecks,
resourceIds, resourceIds,
allResources,
userIds, userIds,
roleIds, roleIds,
emails, emails,
@@ -245,8 +251,8 @@ export async function createAlertRule(
}) })
.returning(); .returning();
// Insert site associations // Insert site associations (skipped when allSites=true — empty junction = match all)
if (siteIds.length > 0) { if (!allSites && siteIds.length > 0) {
await db.insert(alertSites).values( await db.insert(alertSites).values(
siteIds.map((siteId) => ({ siteIds.map((siteId) => ({
alertRuleId: rule.alertRuleId, alertRuleId: rule.alertRuleId,
@@ -255,8 +261,8 @@ export async function createAlertRule(
); );
} }
// Insert health check associations // Insert health check associations (skipped when allHealthChecks=true)
if (healthCheckIds.length > 0) { if (!allHealthChecks && healthCheckIds.length > 0) {
await db.insert(alertHealthChecks).values( await db.insert(alertHealthChecks).values(
healthCheckIds.map((healthCheckId) => ({ healthCheckIds.map((healthCheckId) => ({
alertRuleId: rule.alertRuleId, alertRuleId: rule.alertRuleId,
@@ -265,8 +271,8 @@ export async function createAlertRule(
); );
} }
// Insert resource associations // Insert resource associations (skipped when allResources=true)
if (resourceIds.length > 0) { if (!allResources && resourceIds.length > 0) {
await db.insert(alertResources).values( await db.insert(alertResources).values(
resourceIds.map((resourceId) => ({ resourceIds.map((resourceId) => ({
alertRuleId: rule.alertRuleId, alertRuleId: rule.alertRuleId,

View File

@@ -33,6 +33,7 @@ import { and, eq } from "drizzle-orm";
import { encrypt } from "@server/lib/crypto"; import { encrypt } from "@server/lib/crypto";
import config from "@server/lib/config"; import config from "@server/lib/config";
import { HC_EVENT_TYPES, SITE_EVENT_TYPES, RESOURCE_EVENT_TYPES } from "./createAlertRule"; import { HC_EVENT_TYPES, SITE_EVENT_TYPES, RESOURCE_EVENT_TYPES } from "./createAlertRule";
import { invalidateAllRemoteExitNodeSessions } from "@server/private/auth/sessions/remoteExitNode";
const paramsSchema = z const paramsSchema = z
.object({ .object({
@@ -62,8 +63,11 @@ const bodySchema = z
cooldownSeconds: z.number().int().nonnegative().optional(), cooldownSeconds: z.number().int().nonnegative().optional(),
// Source join tables - if provided the full set is replaced // Source join tables - if provided the full set is replaced
siteIds: z.array(z.number().int().positive()).optional(), siteIds: z.array(z.number().int().positive()).optional(),
allSites: z.boolean().optional(),
healthCheckIds: z.array(z.number().int().positive()).optional(), healthCheckIds: z.array(z.number().int().positive()).optional(),
allHealthChecks: z.boolean().optional(),
resourceIds: z.array(z.number().int().positive()).optional(), resourceIds: z.array(z.number().int().positive()).optional(),
allResources: z.boolean().optional(),
// Recipient arrays - if any are provided the full recipient set is replaced // Recipient arrays - if any are provided the full recipient set is replaced
userIds: z.array(z.string().nonempty()).optional(), userIds: z.array(z.string().nonempty()).optional(),
roleIds: z.array(z.number()).optional(), roleIds: z.array(z.number()).optional(),
@@ -84,6 +88,30 @@ const bodySchema = z
val.eventType val.eventType
); );
if (isSiteEvent && val.siteIds !== undefined && val.siteIds.length === 0 && !val.allSites) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "At least one siteId is required for site event types when allSites is false",
path: ["siteIds"]
});
}
if (isHcEvent && val.healthCheckIds !== undefined && val.healthCheckIds.length === 0 && !val.allHealthChecks) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "At least one healthCheckId is required for health check event types when allHealthChecks is false",
path: ["healthCheckIds"]
});
}
if (isResourceEvent && val.resourceIds !== undefined && val.resourceIds.length === 0 && !val.allResources) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "At least one resourceId is required for resource event types when allResources is false",
path: ["resourceIds"]
});
}
if (isSiteEvent && val.healthCheckIds !== undefined && val.healthCheckIds.length > 0) { if (isSiteEvent && val.healthCheckIds !== undefined && val.healthCheckIds.length > 0) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
@@ -363,4 +391,4 @@ export async function updateAlertRule(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
); );
} }
} }

View File

@@ -35,6 +35,7 @@ import {
RadioGroupItem RadioGroupItem
} from "@app/components/ui/radio-group"; } from "@app/components/ui/radio-group";
import { Label } from "@app/components/ui/label"; import { Label } from "@app/components/ui/label";
import { StrategySelect } from "@app/components/StrategySelect";
import { TagInput, type Tag } from "@app/components/tags/tag-input"; import { TagInput, type Tag } from "@app/components/tags/tag-input";
import { getUserDisplayName } from "@app/lib/getUserDisplayName"; import { getUserDisplayName } from "@app/lib/getUserDisplayName";
import { import {
@@ -957,6 +958,58 @@ export function AlertRuleSourceFields({
const t = useTranslations(); const t = useTranslations();
const { setValue, getValues } = useFormContext<AlertRuleFormValues>(); const { setValue, getValues } = useFormContext<AlertRuleFormValues>();
const sourceType = useWatch({ control, name: "sourceType" }); const sourceType = useWatch({ control, name: "sourceType" });
const allSites = useWatch({ control, name: "allSites" });
const allHealthChecks = useWatch({ control, name: "allHealthChecks" });
const allResources = useWatch({ control, name: "allResources" });
const siteStrategyOptions = useMemo(
() => [
{
id: "all" as const,
title: t("alertingAllSites"),
description: t("alertingAllSitesDescription")
},
{
id: "specific" as const,
title: t("alertingSpecificSites"),
description: t("alertingSpecificSitesDescription")
}
],
[t]
);
const healthCheckStrategyOptions = useMemo(
() => [
{
id: "all" as const,
title: t("alertingAllHealthChecks"),
description: t("alertingAllHealthChecksDescription")
},
{
id: "specific" as const,
title: t("alertingSpecificHealthChecks"),
description: t("alertingSpecificHealthChecksDescription")
}
],
[t]
);
const resourceStrategyOptions = useMemo(
() => [
{
id: "all" as const,
title: t("alertingAllResources"),
description: t("alertingAllResourcesDescription")
},
{
id: "specific" as const,
title: t("alertingSpecificResources"),
description: t("alertingSpecificResourcesDescription")
}
],
[t]
);
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<FormField <FormField
@@ -1029,55 +1082,131 @@ export function AlertRuleSourceFields({
)} )}
/> />
{sourceType === "site" ? ( {sourceType === "site" ? (
<FormField <>
control={control} <FormField
name="siteIds" control={control}
render={({ field }) => ( name="allSites"
<FormItem> render={({ field }) => (
<FormLabel>{t("alertingPickSites")}</FormLabel> <FormItem>
<SiteMultiSelect <StrategySelect
orgId={orgId} options={siteStrategyOptions}
value={field.value} value={field.value ? "all" : "specific"}
onChange={field.onChange} onChange={(v) => {
/> field.onChange(v === "all");
<FormMessage /> if (v === "all") {
</FormItem> setValue("siteIds", []);
}
}}
cols={2}
/>
<FormMessage />
</FormItem>
)}
/>
{!allSites && (
<FormField
control={control}
name="siteIds"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("alertingPickSites")}
</FormLabel>
<SiteMultiSelect
orgId={orgId}
value={field.value}
onChange={field.onChange}
/>
<FormMessage />
</FormItem>
)}
/>
)} )}
/> </>
) : sourceType === "resource" ? ( ) : sourceType === "resource" ? (
<FormField <>
control={control} <FormField
name="resourceIds" control={control}
render={({ field }) => ( name="allResources"
<FormItem> render={({ field }) => (
<FormLabel>{t("alertingPickResources")}</FormLabel> <FormItem>
<ResourceMultiSelect <StrategySelect
orgId={orgId} options={resourceStrategyOptions}
value={field.value} value={field.value ? "all" : "specific"}
onChange={field.onChange} onChange={(v) => {
/> field.onChange(v === "all");
<FormMessage /> if (v === "all") {
</FormItem> setValue("resourceIds", []);
}
}}
cols={2}
/>
<FormMessage />
</FormItem>
)}
/>
{!allResources && (
<FormField
control={control}
name="resourceIds"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("alertingPickResources")}
</FormLabel>
<ResourceMultiSelect
orgId={orgId}
value={field.value}
onChange={field.onChange}
/>
<FormMessage />
</FormItem>
)}
/>
)} )}
/> </>
) : ( ) : (
<FormField <>
control={control} <FormField
name="healthCheckIds" control={control}
render={({ field }) => ( name="allHealthChecks"
<FormItem> render={({ field }) => (
<FormLabel> <FormItem>
{t("alertingPickHealthChecks")} <StrategySelect
</FormLabel> options={healthCheckStrategyOptions}
<HealthCheckMultiSelect value={field.value ? "all" : "specific"}
orgId={orgId} onChange={(v) => {
value={field.value} field.onChange(v === "all");
onChange={field.onChange} if (v === "all") {
/> setValue("healthCheckIds", []);
<FormMessage /> }
</FormItem> }}
cols={2}
/>
<FormMessage />
</FormItem>
)}
/>
{!allHealthChecks && (
<FormField
control={control}
name="healthCheckIds"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("alertingPickHealthChecks")}
</FormLabel>
<HealthCheckMultiSelect
orgId={orgId}
value={field.value}
onChange={field.onChange}
/>
<FormMessage />
</FormItem>
)}
/>
)} )}
/> </>
)} )}
</div> </div>
); );

View File

@@ -50,8 +50,11 @@ export type AlertRuleFormValues = {
name: string; name: string;
enabled: boolean; enabled: boolean;
sourceType: "site" | "health_check" | "resource"; sourceType: "site" | "health_check" | "resource";
allSites: boolean;
siteIds: number[]; siteIds: number[];
allHealthChecks: boolean;
healthCheckIds: number[]; healthCheckIds: number[];
allResources: boolean;
resourceIds: number[]; resourceIds: number[];
trigger: AlertTrigger; trigger: AlertTrigger;
actions: AlertRuleFormAction[]; actions: AlertRuleFormAction[];
@@ -74,8 +77,11 @@ export type AlertRuleApiPayload = {
| "resource_unhealthy" | "resource_unhealthy"
| "resource_toggle"; | "resource_toggle";
enabled: boolean; enabled: boolean;
allSites: boolean;
siteIds: number[]; siteIds: number[];
allHealthChecks: boolean;
healthCheckIds: number[]; healthCheckIds: number[];
allResources: boolean;
resourceIds: number[]; resourceIds: number[];
userIds: string[]; userIds: string[];
roleIds: number[]; roleIds: number[];
@@ -136,8 +142,11 @@ export function buildFormSchema(t: (k: string) => string) {
.min(1, { message: t("alertingErrorNameRequired") }), .min(1, { message: t("alertingErrorNameRequired") }),
enabled: z.boolean(), enabled: z.boolean(),
sourceType: z.enum(["site", "health_check", "resource"]), sourceType: z.enum(["site", "health_check", "resource"]),
allSites: z.boolean(),
siteIds: z.array(z.number()), siteIds: z.array(z.number()),
allHealthChecks: z.boolean(),
healthCheckIds: z.array(z.number()), healthCheckIds: z.array(z.number()),
allResources: z.boolean(),
resourceIds: z.array(z.number()), resourceIds: z.array(z.number()),
trigger: z.enum([ trigger: z.enum([
"site_online", "site_online",
@@ -185,7 +194,11 @@ export function buildFormSchema(t: (k: string) => string) {
path: ["actions"] path: ["actions"]
}); });
} }
if (val.sourceType === "site" && val.siteIds.length === 0) { if (
val.sourceType === "site" &&
!val.allSites &&
val.siteIds.length === 0
) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: t("alertingErrorPickSites"), message: t("alertingErrorPickSites"),
@@ -194,6 +207,7 @@ export function buildFormSchema(t: (k: string) => string) {
} }
if ( if (
val.sourceType === "health_check" && val.sourceType === "health_check" &&
!val.allHealthChecks &&
val.healthCheckIds.length === 0 val.healthCheckIds.length === 0
) { ) {
ctx.addIssue({ ctx.addIssue({
@@ -204,6 +218,7 @@ export function buildFormSchema(t: (k: string) => string) {
} }
if ( if (
val.sourceType === "resource" && val.sourceType === "resource" &&
!val.allResources &&
val.resourceIds.length === 0 val.resourceIds.length === 0
) { ) {
ctx.addIssue({ ctx.addIssue({
@@ -295,8 +310,11 @@ export function defaultFormValues(): AlertRuleFormValues {
name: "", name: "",
enabled: true, enabled: true,
sourceType: "site", sourceType: "site",
allSites: true,
siteIds: [], siteIds: [],
allHealthChecks: true,
healthCheckIds: [], healthCheckIds: [],
allResources: true,
resourceIds: [], resourceIds: [],
trigger: "site_toggle", trigger: "site_toggle",
actions: [ actions: [
@@ -371,12 +389,21 @@ export function apiResponseToFormValues(
}); });
} }
const allSites = sourceType === "site" && rule.siteIds.length === 0;
const allHealthChecks =
sourceType === "health_check" && rule.healthCheckIds.length === 0;
const allResources =
sourceType === "resource" && (rule.resourceIds?.length ?? 0) === 0;
return { return {
name: rule.name, name: rule.name,
enabled: rule.enabled, enabled: rule.enabled,
sourceType, sourceType,
allSites,
siteIds: rule.siteIds, siteIds: rule.siteIds,
allHealthChecks,
healthCheckIds: rule.healthCheckIds, healthCheckIds: rule.healthCheckIds,
allResources,
resourceIds: rule.resourceIds ?? [], resourceIds: rule.resourceIds ?? [],
trigger: trigger as AlertTrigger, trigger: trigger as AlertTrigger,
actions actions
@@ -432,9 +459,12 @@ export function formValuesToApiPayload(
name: values.name.trim(), name: values.name.trim(),
eventType, eventType,
enabled: values.enabled, enabled: values.enabled,
siteIds: values.siteIds, allSites: values.allSites,
healthCheckIds: values.healthCheckIds, siteIds: values.allSites ? [] : values.siteIds,
resourceIds: values.resourceIds, allHealthChecks: values.allHealthChecks,
healthCheckIds: values.allHealthChecks ? [] : values.healthCheckIds,
allResources: values.allResources,
resourceIds: values.allResources ? [] : values.resourceIds,
userIds: uniqueUserIds, userIds: uniqueUserIds,
roleIds: uniqueRoleIds, roleIds: uniqueRoleIds,
emails: uniqueEmails, emails: uniqueEmails,