make alerts and health checks table server side

This commit is contained in:
miloschwartz
2026-04-21 16:49:45 -07:00
parent b22ac17178
commit db2942447a
11 changed files with 333 additions and 142 deletions

View File

@@ -16,7 +16,6 @@ import { useEnvContext } from "@app/hooks/useEnvContext";
import { useNavigationContext } from "@app/hooks/useNavigationContext";
import { usePaidStatus } from "@app/hooks/usePaidStatus";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { orgQueries } from "@app/lib/queries";
import { getNextSortOrder, getSortDirection } from "@app/lib/sortColumn";
import {
alertRuleAllHealthChecksSelected,
@@ -34,10 +33,9 @@ import moment from "moment";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useMemo, useState } from "react";
import { useMemo, useState, useTransition } from "react";
import z from "zod";
import { ColumnFilterButton } from "./ColumnFilterButton";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import type { PaginationState } from "@tanstack/react-table";
import type { DataTablePaginationState } from "@app/components/ui/data-table";
import { useDebouncedCallback } from "use-debounce";
@@ -47,13 +45,7 @@ const alertRulesEnabledQuerySchema = z
.optional()
.catch(undefined);
type AlertingRulesTableProps = {
orgId: string;
siteId?: number;
resourceId?: number;
};
type AlertRuleRow = {
export type AlertRuleRow = {
alertRuleId: number;
orgId: string;
name: string;
@@ -68,6 +60,12 @@ type AlertRuleRow = {
resourceIds: number[];
};
type AlertingRulesTableProps = {
orgId: string;
alertRules: AlertRuleRow[];
rowCount: number;
};
function ruleHref(orgId: string, ruleId: number) {
return `/${orgId}/settings/alerting/${ruleId}`;
}
@@ -129,13 +127,13 @@ function triggerLabel(rule: AlertRuleRow, t: (k: string) => string) {
export default function AlertingRulesTable({
orgId,
siteId,
resourceId
alertRules,
rowCount
}: AlertingRulesTableProps) {
const router = useRouter();
const t = useTranslations();
const api = createApiClient(useEnvContext());
const queryClient = useQueryClient();
const [isRefreshing, startRefresh] = useTransition();
const { isPaidUser } = usePaidStatus();
const isPaid = isPaidUser(tierMatrix.alertingRules);
@@ -167,24 +165,16 @@ export default function AlertingRulesTable({
[t]
);
const { data, isLoading, refetch, isRefetching } = useQuery(
orgQueries.alertRules({
orgId,
limit: pageSize,
offset: pageIndex * pageSize,
query,
siteId,
resourceId,
sortBy,
order,
enabled: enabledForQuery
})
);
const rows = data?.alertRules ?? [];
const total = data?.pagination.total ?? 0;
const rows = alertRules;
const total = rowCount;
const pageCount = Math.max(1, Math.ceil(total / pageSize));
function refreshList() {
startRefresh(() => {
router.refresh();
});
}
const paginationState: DataTablePaginationState = {
pageIndex,
pageSize,
@@ -223,18 +213,13 @@ export default function AlertingRulesTable({
filter({ searchParams: sp });
}
const invalidate = () =>
queryClient.invalidateQueries({
queryKey: ["ORG", orgId, "ALERT_RULES"]
});
const setEnabled = async (rule: AlertRuleRow, enabled: boolean) => {
setTogglingId(rule.alertRuleId);
try {
await api.post(`/org/${orgId}/alert-rule/${rule.alertRuleId}`, {
enabled
});
await invalidate();
refreshList();
} catch (e) {
toast({
title: t("error"),
@@ -252,7 +237,7 @@ export default function AlertingRulesTable({
await api.delete(
`/org/${orgId}/alert-rule/${selected.alertRuleId}`
);
await invalidate();
refreshList();
toast({ title: t("alertingRuleDeleted") });
} catch (e) {
toast({
@@ -442,8 +427,8 @@ export default function AlertingRulesTable({
onAdd={() => {
router.push(`/${orgId}/settings/alerting/create`);
}}
onRefresh={() => refetch()}
isRefreshing={isRefetching || isLoading || isFiltering}
onRefresh={refreshList}
isRefreshing={isRefreshing || isFiltering}
addButtonText={t("alertingAddRule")}
enableColumnVisibility
stickyLeftColumn="name"

View File

@@ -6,7 +6,6 @@ import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
import HealthCheckCredenza, {
HealthCheckRow
} from "@app/components/HealthCheckCredenza";
import { Badge } from "@app/components/ui/badge";
import { Button } from "@app/components/ui/button";
import { DataTable, ExtendedColumnDef } from "@app/components/ui/data-table";
import {
@@ -19,22 +18,23 @@ import { Switch } from "@app/components/ui/switch";
import { toast } from "@app/hooks/useToast";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { orgQueries } from "@app/lib/queries";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ArrowUpDown, ArrowUpRight, MoreHorizontal } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useState, useTransition, useEffect } from "react";
import type { PaginationState } from "@tanstack/react-table";
import type { DataTablePaginationState } from "@app/components/ui/data-table";
import { useNavigationContext } from "@app/hooks/useNavigationContext";
import { useDebouncedCallback } from "use-debounce";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import { usePaidStatus } from "@app/hooks/usePaidStatus";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
type StandaloneHealthChecksTableProps = {
orgId: string;
healthChecks: HealthCheckRow[];
rowCount: number;
};
function formatTarget(row: HealthCheckRow): string {
@@ -57,21 +57,15 @@ const healthLabel: Record<HealthCheckRow["hcHealth"], string> = {
unknown: "Unknown"
};
const healthVariant: Record<
HealthCheckRow["hcHealth"],
"green" | "red" | "secondary"
> = {
healthy: "green",
unhealthy: "red",
unknown: "secondary"
};
export default function HealthChecksTable({
orgId
orgId,
healthChecks,
rowCount
}: StandaloneHealthChecksTableProps) {
const router = useRouter();
const t = useTranslations();
const api = createApiClient(useEnvContext());
const queryClient = useQueryClient();
const [isRefreshing, startRefresh] = useTransition();
const { isPaidUser } = usePaidStatus();
const isPaid = isPaidUser(tierMatrix.standaloneHealthChecks);
@@ -91,25 +85,23 @@ export default function HealthChecksTable({
const pageIndex = page - 1;
const query = searchParams.get("query") ?? undefined;
const {
data,
isLoading,
refetch,
isRefetching
} = useQuery({
...orgQueries.standaloneHealthChecks({
orgId,
limit: pageSize,
offset: pageIndex * pageSize,
query
}),
refetchInterval: 10_000
});
const rows = data?.healthChecks ?? [];
const total = data?.pagination.total ?? 0;
const rows = healthChecks;
const total = rowCount;
const pageCount = Math.max(1, Math.ceil(total / pageSize));
function refreshList() {
startRefresh(() => {
router.refresh();
});
}
useEffect(() => {
const interval = setInterval(() => {
router.refresh();
}, 10_000);
return () => clearInterval(interval);
}, [router]);
const paginationState: DataTablePaginationState = {
pageIndex,
pageSize,
@@ -132,11 +124,6 @@ export default function HealthChecksTable({
filter({ searchParams });
}, 300);
const invalidate = () =>
queryClient.invalidateQueries({
queryKey: ["ORG", orgId, "STANDALONE_HEALTH_CHECKS"]
});
const handleToggleEnabled = async (
row: HealthCheckRow,
enabled: boolean
@@ -147,7 +134,7 @@ export default function HealthChecksTable({
`/org/${orgId}/health-check/${row.targetHealthCheckId}`,
{ hcEnabled: enabled }
);
await invalidate();
refreshList();
} catch (e) {
toast({
title: t("error"),
@@ -165,7 +152,7 @@ export default function HealthChecksTable({
await api.delete(
`/org/${orgId}/health-check/${selected.targetHealthCheckId}`
);
await invalidate();
refreshList();
toast({ title: t("standaloneHcDeleted") });
} catch (e) {
toast({
@@ -400,7 +387,7 @@ export default function HealthChecksTable({
}}
orgId={orgId}
initialValues={selected}
onSaved={invalidate}
onSaved={refreshList}
/>
<PaidFeaturesAlert tiers={tierMatrix.standaloneHealthChecks} />
@@ -418,8 +405,8 @@ export default function HealthChecksTable({
setCredenzaOpen(true);
}}
addButtonDisabled={!isPaid}
onRefresh={() => refetch()}
isRefreshing={isRefetching || isLoading || isFiltering}
onRefresh={refreshList}
isRefreshing={isRefreshing || isFiltering}
addButtonText={t("standaloneHcAddButton")}
enableColumnVisibility
stickyLeftColumn="name"

View File

@@ -11,6 +11,8 @@ import { useTranslations } from "next-intl";
export type TabItem = {
title: string;
href: string;
/** When set, active tab detection uses this path instead of `href` (link target unchanged). */
activePrefix?: string;
icon?: React.ReactNode;
showProfessional?: boolean;
exact?: boolean;
@@ -115,18 +117,33 @@ export function HorizontalTabs({
}
// Server-side mode: original behavior with routing
const activeIndex: number | null = (() => {
if (pathname.includes("create")) return null;
let best: number | null = null;
let bestLen = -1;
for (let i = 0; i < items.length; i++) {
const item = items[i];
const matchBase = hydrateHref(item.activePrefix ?? item.href);
const matched = item.exact
? pathname === matchBase
: pathname === matchBase ||
pathname.startsWith(`${matchBase}/`);
if (matched && matchBase.length > bestLen) {
bestLen = matchBase.length;
best = i;
}
}
return best;
})();
return (
<div className="space-y-3">
<div className="relative">
<div className="overflow-x-auto scrollbar-hide">
<div className="flex space-x-4 border-b min-w-max">
{items.map((item) => {
{items.map((item, index) => {
const hydratedHref = hydrateHref(item.href);
const isActive =
(item.exact
? pathname === hydratedHref
: pathname.startsWith(hydratedHref)) &&
!pathname.includes("create");
const isActive = activeIndex === index;
const isProfessional =
item.showProfessional && !isUnlocked();
@@ -135,7 +152,7 @@ export function HorizontalTabs({
return (
<Link
key={hydratedHref}
key={`${hydratedHref}-${index}`}
href={isProfessional ? "#" : hydratedHref}
className={cn(
"px-4 py-2 text-sm font-medium transition-colors whitespace-nowrap relative",

View File

@@ -158,7 +158,9 @@ export default function UptimeAlertSection({
const alertButton = alertRulesLoading ? null : hasRules ? (
<Button variant="outline" asChild>
<Link href={`/${orgId}/settings/alerting?siteId=${siteId}&resourceId=${resourceId}`}>
<Link
href={`/${orgId}/settings/alerting/rules?siteId=${siteId}&resourceId=${resourceId}`}
>
<BellRing className="size-4 mr-2" />
View Alerts
</Link>