diff --git a/packages/app/src/components/Slos/SloAlertFields.tsx b/packages/app/src/components/Slos/SloAlertFields.tsx new file mode 100644 index 000000000..5aec2eac5 --- /dev/null +++ b/packages/app/src/components/Slos/SloAlertFields.tsx @@ -0,0 +1,80 @@ +import { type Control, type UseFormSetValue, useWatch } from 'react-hook-form'; +import { + describeSloAlertRule, + describeSloAlertRuleDetails, + getSloAlertRuleLabel, + SLO_BURN_CONDITIONS, + type SloAlertRule, +} from '@hyperdx/common-utils/dist/slo'; +import { Switch } from '@mantine/core'; + +import { AlertChannelForm } from '@/components/Alerts'; + +import { newSloAlertTarget, type SloFormValues } from './sloForm'; +import { SloFormRow } from './SloFormLayout'; + +/** One burn alert: its rule as the switch's label, and where it notifies. */ +function SloAlertRuleFields({ + rule, + control, + setValue, +}: { + rule: SloAlertRule; + control: Control; + setValue: UseFormSetValue; +}) { + const target = useWatch({ control, name: `alerts.${rule}` }); + const sloWindow = useWatch({ control, name: 'window' }); + return ( + <> + + + setValue( + `alerts.${rule}`, + e.currentTarget.checked ? newSloAlertTarget() : null, + { shouldDirty: true }, + ) + } + data-testid={`slo-alert-${rule}`} + /> + + {target != null && ( + + + + )} + + ); +} + +/** The fast and slow burn alerts, each on its own with its own channels. */ +export function SloAlertFields({ + control, + setValue, +}: { + control: Control; + setValue: UseFormSetValue; +}) { + return ( + <> + {SLO_BURN_CONDITIONS.map(({ rule }) => ( + + ))} + + ); +} diff --git a/packages/app/src/components/Slos/SloDetailPage.tsx b/packages/app/src/components/Slos/SloDetailPage.tsx index 9f04f7b23..770f185b7 100644 --- a/packages/app/src/components/Slos/SloDetailPage.tsx +++ b/packages/app/src/components/Slos/SloDetailPage.tsx @@ -26,7 +26,7 @@ import { useSlo, useSlosEnabledGuard } from '@/slo'; import { useSource } from '@/source'; import { SloCharts } from './SloCharts'; -import { SloDefinitionPanel } from './SloDetailPanels'; +import { SloAlertPanel, SloDefinitionPanel } from './SloDetailPanels'; import { SloEventsDrawer, type SloEventsRange, @@ -142,6 +142,7 @@ function SloDetailView({ onBucketSelect={onBucketSelect} /> )} + diff --git a/packages/app/src/components/Slos/SloDetailPanels.tsx b/packages/app/src/components/Slos/SloDetailPanels.tsx index 5b38fe8f9..f3e391ba1 100644 --- a/packages/app/src/components/Slos/SloDetailPanels.tsx +++ b/packages/app/src/components/Slos/SloDetailPanels.tsx @@ -1,16 +1,34 @@ +import Link from 'next/link'; import { formatDistanceToNowStrict } from 'date-fns'; import { getSloBurnRule, getSloGoodSql, } from '@hyperdx/common-utils/dist/core/slo'; import { describeFilter } from '@hyperdx/common-utils/dist/filters'; -import type { - SloApiResponse, - SloState, - SloStats, +import { + describeSloAlertRule, + getSloAlertRuleLabel, + getSloAlertTarget, + SLO_BURN_CONDITIONS, + type SloApiResponse, + type SloState, + type SloStats, } from '@hyperdx/common-utils/dist/slo'; -import { Code, Group, Paper, SimpleGrid, Stack, Text } from '@mantine/core'; +import { WebhookService } from '@hyperdx/common-utils/dist/types'; +import { + Anchor, + Code, + Group, + Paper, + SimpleGrid, + Stack, + Text, +} from '@mantine/core'; + +import api from '@/api'; +import { SloRecentFirings } from './SloRecentFirings'; +import { SloAlertRuleBadge } from './SloStateBadge'; import { budgetColorVar, describeBurnWindow, @@ -20,6 +38,7 @@ import { formatSli, formatSloWindow, formatTarget, + getSloAlertStatus, } from './sloUtils'; function Stat({ @@ -110,6 +129,59 @@ export function SloStatsGrid({ ); } +/** + * The fast and slow burn alerts the SLO owns, each with its rule, channels + * and recent firings. They are changed from the SLO's editor. + */ +export function SloAlertPanel({ slo }: { slo: SloApiResponse }) { + const { data: webhooks } = api.useWebhooks([ + WebhookService.Slack, + WebhookService.Generic, + WebhookService.IncidentIO, + ]); + const anyOn = SLO_BURN_CONDITIONS.some(({ rule }) => + getSloAlertTarget(slo.alerts, rule), + ); + return ( + + + Burn-rate alerts + + {anyOn ? 'Edit' : 'Add an alert'} + + + + {SLO_BURN_CONDITIONS.map(({ rule }) => { + const target = getSloAlertTarget(slo.alerts, rule); + const status = getSloAlertStatus(slo, rule); + const sentence = describeSloAlertRule(rule, slo.window); + const channels = (target?.channels ?? []).map( + channel => + webhooks?.data?.find(w => w._id === channel.webhookId)?.name ?? + 'a webhook', + ); + return ( + + + + {getSloAlertRuleLabel(rule)} + + + + + {target + ? `Notifies ${channels.join(', ')} when ${sentence}.` + : `Turn it on to be notified when ${sentence}.`} + + {target && status && } + + ); + })} + + + ); +} + export function SloDefinitionPanel({ slo, sourceName, diff --git a/packages/app/src/components/Slos/SloEditorPage.tsx b/packages/app/src/components/Slos/SloEditorPage.tsx index bccc7399e..a38b1708a 100644 --- a/packages/app/src/components/Slos/SloEditorPage.tsx +++ b/packages/app/src/components/Slos/SloEditorPage.tsx @@ -34,6 +34,7 @@ import { useSource } from '@/source'; import { getApiErrorMessage } from '@/utils/apiErrors'; import { parseAsJsonEncoded, parseAsStringEncoded } from '@/utils/queryParsers'; +import { SloAlertFields } from './SloAlertFields'; import { SloDetailsFields, SloIndicatorFields, @@ -112,6 +113,10 @@ function SloEditorPage() { reset(sloFormValuesFromSearch({ ...prefill, source: prefill.source })); } initializedRef.current = true; + // "Edit" on an SLO's alerts links here with #alerts. + if (window.location.hash === '#alerts') { + document.getElementById('alerts')?.scrollIntoView(); + } }, [router.isReady, editId, existing, duplicateId, original, prefill, reset]); const [preview, setPreview] = useState(null); @@ -242,6 +247,13 @@ function SloEditorPage() { + + + diff --git a/packages/app/src/components/Slos/SloRecentFirings.tsx b/packages/app/src/components/Slos/SloRecentFirings.tsx new file mode 100644 index 000000000..2c96dd013 --- /dev/null +++ b/packages/app/src/components/Slos/SloRecentFirings.tsx @@ -0,0 +1,108 @@ +import { useMemo, useState } from 'react'; +import { formatDistanceStrict } from 'date-fns'; +import { + AlertState, + type AlertTransition, +} from '@hyperdx/common-utils/dist/types'; +import { Skeleton, Stack, Table, Text } from '@mantine/core'; + +import api from '@/api'; +import { FormatTime } from '@/useFormatTime'; + +const RECENT_FIRINGS_MS = 7 * 24 * 60 * 60 * 1000; +const MAX_FIRINGS_SHOWN = 10; + +export type AlertEpisode = { start: string; end?: string }; + +/** + * The alert's firing episodes, newest first, from its state changes: each + * firing to the next recovery, or still open. Times are evaluation times, + * when the notifications went out. + */ +export function getAlertEpisodes( + transitions: AlertTransition[], +): AlertEpisode[] { + const episodes: AlertEpisode[] = []; + let start: string | undefined; + for (const { state, createdAt } of transitions) { + if (state === AlertState.ALERT) { + start ??= createdAt; + } else if (start != null) { + episodes.push({ start, end: createdAt }); + start = undefined; + } + } + if (start != null) episodes.push({ start }); + return episodes.reverse(); +} + +/** + * When one of the SLO's burn alerts fired in the last 7 days, newest + * first. + */ +export function SloRecentFirings({ alertId }: { alertId: string }) { + const [dateRange] = useState<[Date, Date]>(() => [ + new Date(Date.now() - RECENT_FIRINGS_MS), + new Date(), + ]); + const { data, isLoading } = api.useAlertHistory(alertId, dateRange); + const episodes = useMemo(() => getAlertEpisodes(data?.data ?? []), [data]); + + if (isLoading) return ; + if (episodes.length === 0) { + return ( + + Did not fire in the last 7 days. + + ); + } + const hidden = episodes.length - MAX_FIRINGS_SHOWN; + return ( + + + Fired {episodes.length === 1 ? 'once' : `${episodes.length} times`} in + the last 7 days + + + + + Fired + Resolved + For + + + + {episodes.slice(0, MAX_FIRINGS_SHOWN).map(({ start, end }) => ( + + + + + + {end ? ( + + ) : ( + + Still firing + + )} + + + {/* An open episode runs until the history was read. */} + {formatDistanceStrict( + new Date(start), + end ? new Date(end) : dateRange[1], + )} + + + ))} + +
+ {hidden > 0 && ( + + {hidden} earlier {hidden === 1 ? 'firing is' : 'firings are'} not + shown. + + )} +
+ ); +} diff --git a/packages/app/src/components/Slos/SloStateBadge.tsx b/packages/app/src/components/Slos/SloStateBadge.tsx index 9acff4e63..6563077d6 100644 --- a/packages/app/src/components/Slos/SloStateBadge.tsx +++ b/packages/app/src/components/Slos/SloStateBadge.tsx @@ -1,7 +1,19 @@ import { Badge } from '@clickhouse/click-ui'; -import { Tooltip } from '@mantine/core'; +import { + getSloAlertRuleLabel, + getSloAlertTarget, + SLO_BURN_CONDITIONS, + type SloAlertRule, + type SloApiResponse, +} from '@hyperdx/common-utils/dist/slo'; +import { AlertState } from '@hyperdx/common-utils/dist/types'; +import { Group, Text, Tooltip } from '@mantine/core'; + +import { useFormatTime } from '@/useFormatTime'; import { + getSloAlertStatus, + sloAlertStateLabel, type SloDisplayState, sloStateDescription, sloStateLabel, @@ -30,3 +42,123 @@ export function SloStateBadge({ state }: { state: SloDisplayState }) { ); } + +function AlertStateBadge({ state }: { state: AlertState }) { + const label = sloAlertStateLabel(state); + return state === AlertState.ALERT ? ( + + ) : ( + + ); +} + +function SilencedBadge({ until }: { until: string }) { + const formatTime = useFormatTime(); + return ( + + + + + + ); +} + +/** One burn alert's state: off, missing, or as it runs. */ +export function SloAlertRuleBadge({ + slo, + rule, +}: { + slo: SloApiResponse; + rule: SloAlertRule; +}) { + if (!getSloAlertTarget(slo.alerts, rule)) { + return ( + + Off + + ); + } + const status = getSloAlertStatus(slo, rule); + if (!status) { + return ( + + + + + + ); + } + return ( + + + {status.silencedUntil && } + + ); +} + +/** + * The SLO's burn alerts at a glance: the worst state among those that are + * on, each one in the tooltip, or "Off" when none is. + */ +export function SloAlertBadge({ slo }: { slo: SloApiResponse }) { + const alerts = SLO_BURN_CONDITIONS.filter( + ({ rule }) => getSloAlertTarget(slo.alerts, rule) != null, + ).map(({ rule }) => ({ + label: getSloAlertRuleLabel(rule), + status: getSloAlertStatus(slo, rule), + })); + if (alerts.length === 0) { + return ( + + Off + + ); + } + // Settings without an alert behind them: the alert was removed and the SLO + // was not updated. Saving the SLO creates it again. + const missing = alerts.find(a => a.status == null); + if (missing) { + return ( + + + + + + ); + } + const states = alerts.map(a => ({ + label: a.label, + state: a.status?.state ?? AlertState.OK, + })); + const state = + states.find(s => s.state === AlertState.ALERT)?.state ?? states[0].state; + const silencedUntil = alerts.find(a => a.status?.silencedUntil)?.status + ?.silencedUntil; + return ( + + `${s.label}: ${sloAlertStateLabel(s.state)}`) + .join('. ')} + withArrow + > + + + + + {silencedUntil && } + + ); +} diff --git a/packages/app/src/components/Slos/SloTable.tsx b/packages/app/src/components/Slos/SloTable.tsx index 8b1543fad..9541089e3 100644 --- a/packages/app/src/components/Slos/SloTable.tsx +++ b/packages/app/src/components/Slos/SloTable.tsx @@ -10,7 +10,7 @@ import { Group, Stack, Table, Text, Tooltip } from '@mantine/core'; import { useSources } from '@/source'; import { SloRowMenu } from './SloRowMenu'; -import { SloStateBadge } from './SloStateBadge'; +import { SloAlertBadge, SloStateBadge } from './SloStateBadge'; import { budgetColorVar, formatBudget, @@ -121,6 +121,9 @@ function SloRow({ + + + @@ -151,6 +154,7 @@ export function SloTable({ slos }: { slos: SloApiResponse[] }) { help="How fast the budget is being spent: 1x spends it exactly over the window." /> Target + Alert diff --git a/packages/app/src/components/Slos/__tests__/sloForm.test.ts b/packages/app/src/components/Slos/__tests__/sloForm.test.ts index 0d1885764..242eb317e 100644 --- a/packages/app/src/components/Slos/__tests__/sloForm.test.ts +++ b/packages/app/src/components/Slos/__tests__/sloForm.test.ts @@ -6,6 +6,7 @@ import { buildSloPreviewRequest, DEFAULT_SLO_FORM_VALUES, getSloPreviewKey, + newSloAlertTarget, sloCopyFormValues, sloFormResolver, type SloFormValues, @@ -101,12 +102,17 @@ describe('SLO form', () => { name: ' ', target: 100, indicator: { ...valid.indicator, good: '' }, + alerts: { fastBurn: null, slowBurn: newSloAlertTarget() }, }); expect(errors.name?.message).toBe('Name is required'); expect(errors.target?.message).toBe('Target must be below 100%'); expect(errors.indicator?.good?.message).toBe( 'A good-event condition is required', ); + // A burn alert starts with one empty channel, which has to be filled in. + expect(errors.alerts?.slowBurn?.channels?.[0]?.webhookId?.message).toBe( + "Webhook ID can't be empty", + ); }); it('validates only what the template uses', async () => { @@ -158,6 +164,10 @@ describe('SLO form', () => { it('loads a saved SLO back into the form unchanged', () => { const saved = savedSlo; const values = sloToFormValues(saved); + expect(values.alerts).toEqual({ + fastBurn: saved.alerts.fastBurn, + slowBurn: null, + }); expect(toSloInput(values)).toEqual( expect.objectContaining({ name: saved.name, @@ -167,7 +177,7 @@ describe('SLO form', () => { target: saved.target, window: saved.window, groupBy: saved.groupBy, - alerts: saved.alerts, + alerts: { fastBurn: saved.alerts.fastBurn, slowBurn: null }, }), ); }); @@ -177,7 +187,7 @@ describe('SLO form', () => { expect(copy).toEqual({ ...sloToFormValues(savedSlo), name: 'Copy of Checkout availability', - alerts: undefined, + alerts: { fastBurn: null, slowBurn: null }, }); }); diff --git a/packages/app/src/components/Slos/__tests__/sloList.test.ts b/packages/app/src/components/Slos/__tests__/sloList.test.ts index 60f7da3e2..bbba0e899 100644 --- a/packages/app/src/components/Slos/__tests__/sloList.test.ts +++ b/packages/app/src/components/Slos/__tests__/sloList.test.ts @@ -1,6 +1,8 @@ import type { SloApiResponse } from '@hyperdx/common-utils/dist/slo'; +import { AlertState } from '@hyperdx/common-utils/dist/types'; import { compareSlos } from '@/components/Slos/sloListSort'; +import { getAlertEpisodes } from '@/components/Slos/SloRecentFirings'; /** An SLO with only what the sort reads; no status means no update yet. */ const slo = ( @@ -75,3 +77,28 @@ describe('SLO list sort', () => { expect(sorted('worst')[0]).toBe('a'); }); }); + +describe('SLO alert firings', () => { + const at = (minutes: number) => + new Date(Date.UTC(2026, 10, 20, 0, minutes)).toISOString(); + const change = (minutes: number, state: AlertState) => ({ + createdAt: at(minutes), + state, + }); + + it('pairs each firing with the next recovery, newest first', () => { + expect( + getAlertEpisodes([ + change(0, AlertState.ALERT), + change(30, AlertState.OK), + change(60, AlertState.ALERT), + // Repeated firing changes extend the open episode. + change(65, AlertState.ALERT), + ]), + ).toEqual([{ start: at(60) }, { start: at(0), end: at(30) }]); + }); + + it('ignores a recovery without a firing before it', () => { + expect(getAlertEpisodes([change(5, AlertState.OK)])).toEqual([]); + }); +}); diff --git a/packages/app/src/components/Slos/sloForm.ts b/packages/app/src/components/Slos/sloForm.ts index ddcec82f6..aa3c7c748 100644 --- a/packages/app/src/components/Slos/sloForm.ts +++ b/packages/app/src/components/Slos/sloForm.ts @@ -7,6 +7,7 @@ import { } from '@hyperdx/common-utils/dist/core/slo'; import { getSloDefaultDuration } from '@hyperdx/common-utils/dist/core/sloLatency'; import { + type SloAlertTarget, type SloApiResponse, SloIndicatorSchema, type SloInput, @@ -53,8 +54,15 @@ export const DEFAULT_SLO_FORM_VALUES: SloFormValues = { }, target: 99.9, window: '30d', + // Off until the user turns one on and picks where it notifies. + alerts: { fastBurn: null, slowBurn: null }, }; +/** A burn alert that is turned on starts with one empty channel to fill in. */ +export function newSloAlertTarget(): SloAlertTarget { + return { channels: [{ type: 'webhook', webhookId: '' }] }; +} + export function sloToFormValues(slo: SloApiResponse): SloFormValues { const { template, eligible, good, latency } = slo.indicator; return { @@ -72,8 +80,10 @@ export function sloToFormValues(slo: SloApiResponse): SloFormValues { groupBy: slo.groupBy, target: slo.target, window: slo.window, - // Kept as saved, so editing an SLO keeps its alerts. - alerts: slo.alerts, + alerts: { + fastBurn: slo.alerts.fastBurn ?? null, + slowBurn: slo.alerts.slowBurn ?? null, + }, }; } diff --git a/packages/app/src/components/Slos/sloUtils.ts b/packages/app/src/components/Slos/sloUtils.ts index 4da063c0a..720b158ac 100644 --- a/packages/app/src/components/Slos/sloUtils.ts +++ b/packages/app/src/components/Slos/sloUtils.ts @@ -2,12 +2,14 @@ import { getSloBurnRule } from '@hyperdx/common-utils/dist/core/slo'; import { getSloBurnWindowMs, getSloWindowMs, + type SloAlertRule, + type SloAlertStatus, type SloApiResponse, type SloBurnWindow, type SloState, type SloWindow, } from '@hyperdx/common-utils/dist/slo'; -import type { TSource } from '@hyperdx/common-utils/dist/types'; +import { AlertState, type TSource } from '@hyperdx/common-utils/dist/types'; /** An SLO's state as shown: pending until the background computes it. */ export type SloDisplayState = SloState | 'pending'; @@ -60,6 +62,24 @@ export function sloStateDescription(state: SloDisplayState): string { } } +/** A burn alert's state, in words that read well after its name. */ +export function sloAlertStateLabel(state: AlertState): string { + switch (state) { + case AlertState.ALERT: + return 'Firing'; + case AlertState.OK: + return 'OK'; + case AlertState.PENDING: + return 'Pending'; + case AlertState.INSUFFICIENT_DATA: + return 'No data'; + case AlertState.DISABLED: + return 'Disabled'; + case AlertState.ERROR: + return 'Error'; + } +} + /** "hour" or "5 minutes", as in "the last hour". */ export function formatBurnWindow(window: SloBurnWindow): string { switch (window) { @@ -120,6 +140,16 @@ export function formatSloWindow(window: SloWindow): string { return window === '7d' ? '7 days' : '30 days'; } +/** A burn alert of the SLO as it runs, or undefined when it is not running. */ +export function getSloAlertStatus( + slo: Pick, + rule: SloAlertRule, +): SloAlertStatus | undefined { + return rule === 'slowBurn' + ? slo.alertStates.slowBurn + : slo.alertStates.fastBurn; +} + /** * A bad-events view of the burn rule's first window (the last hour) or the * SLO window, ending now.