Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions packages/app/src/components/Slos/SloAlertFields.tsx
Original file line number Diff line number Diff line change
@@ -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<SloFormValues>;
setValue: UseFormSetValue<SloFormValues>;
}) {
const target = useWatch({ control, name: `alerts.${rule}` });
const sloWindow = useWatch({ control, name: 'window' });
return (
<>
<SloFormRow
label={getSloAlertRuleLabel(rule)}
helpText={describeSloAlertRuleDetails(rule)}
inline
>
<Switch
label={`Notify when ${describeSloAlertRule(rule, sloWindow)}`}
checked={target != null}
onChange={e =>
setValue(
`alerts.${rule}`,
e.currentTarget.checked ? newSloAlertTarget() : null,
{ shouldDirty: true },
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — Turning an alert off and back on wipes its saved channels

Turning the switch off sets alerts.<rule> to null, and turning it on writes newSloAlertTarget() with one empty channel. On an existing SLO, a mis-click on the switch silently throws away the configured webhooks. Keep the last target in a ref or local state and restore it when the switch goes back on, and use newSloAlertTarget() only when there was none.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

data-testid={`slo-alert-${rule}`}
/>
</SloFormRow>
{target != null && (
<SloFormRow label="Send to">
<AlertChannelForm
control={control}
channelsName={`alerts.${rule}.channels`}
/>
</SloFormRow>
)}
</>
);
}

/** The fast and slow burn alerts, each on its own with its own channels. */
export function SloAlertFields({
control,
setValue,
}: {
control: Control<SloFormValues>;
setValue: UseFormSetValue<SloFormValues>;
}) {
return (
<>
{SLO_BURN_CONDITIONS.map(({ rule }) => (
<SloAlertRuleFields
key={rule}
rule={rule}
control={control}
setValue={setValue}
/>
))}
</>
);
}
3 changes: 2 additions & 1 deletion packages/app/src/components/Slos/SloDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -142,6 +142,7 @@ function SloDetailView({
onBucketSelect={onBucketSelect}
/>
)}
<SloAlertPanel slo={slo} />
<SloDefinitionPanel slo={slo} sourceName={source?.name} />
</Stack>
</Container>
Expand Down
82 changes: 77 additions & 5 deletions packages/app/src/components/Slos/SloDetailPanels.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -20,6 +38,7 @@ import {
formatSli,
formatSloWindow,
formatTarget,
getSloAlertStatus,
} from './sloUtils';

function Stat({
Expand Down Expand Up @@ -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 (
<Paper withBorder p="md" radius="sm" data-testid="slo-alert-panel">
<Group justify="space-between" mb="xs">
<Text fw={500}>Burn-rate alerts</Text>
<Anchor component={Link} href={`/slos/${slo.id}/edit#alerts`} size="sm">
{anyOn ? 'Edit' : 'Add an alert'}
</Anchor>
</Group>
<Stack gap="md">
{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 (
<Stack key={rule} gap={4} data-testid={`slo-alert-panel-${rule}`}>
<Group gap="xs">
<Text size="sm" fw={500}>
{getSloAlertRuleLabel(rule)}
</Text>
<SloAlertRuleBadge slo={slo} rule={rule} />
</Group>
<Text size="sm" c={target ? undefined : 'dimmed'}>
{target
? `Notifies ${channels.join(', ')} when ${sentence}.`
: `Turn it on to be notified when ${sentence}.`}
</Text>
{target && status && <SloRecentFirings alertId={status.id} />}
</Stack>
);
})}
</Stack>
</Paper>
);
}

export function SloDefinitionPanel({
slo,
sourceName,
Expand Down
12 changes: 12 additions & 0 deletions packages/app/src/components/Slos/SloEditorPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — #alerts scroll runs before the loaded SLO renders and lands under the sticky header

scrollIntoView runs in the same effect as reset(...), before the form re-renders with the loaded SLO. When the Indicator section above changes height (latency fields, editors), the alerts section moves after the scroll. The page header is also sticky, so the section's top ends up hidden under it. Scroll in a later effect or a requestAnimationFrame after reset, and give the section a scroll-margin-top the height of the header.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

document.getElementById('alerts')?.scrollIntoView();
}
}, [router.isReady, editId, existing, duplicateId, original, prefill, reset]);

const [preview, setPreview] = useState<SloPreviewRequest | null>(null);
Expand Down Expand Up @@ -242,6 +247,13 @@ function SloEditorPage() {
<SloFormSection title="Objective">
<SloObjectiveFields control={control} setValue={setValue} />
</SloFormSection>
<SloFormSection
id="alerts"
title="Burn-rate alerts"
description="Optional. Each alert notifies its own channels once when a burn starts and once when it ends."
>
<SloAlertFields control={control} setValue={setValue} />
</SloFormSection>
<SloFormSection title="Details">
<SloDetailsFields control={control} />
</SloFormSection>
Expand Down
108 changes: 108 additions & 0 deletions packages/app/src/components/Slos/SloRecentFirings.tsx
Original file line number Diff line number Diff line change
@@ -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 <Skeleton h={40} />;
if (episodes.length === 0) {
return (
<Text size="sm" c="dimmed" data-testid="slo-recent-firings">
Did not fire in the last 7 days.
</Text>
);
}
const hidden = episodes.length - MAX_FIRINGS_SHOWN;
return (
<Stack gap={4} data-testid="slo-recent-firings">
<Text size="sm" fw={500}>
Fired {episodes.length === 1 ? 'once' : `${episodes.length} times`} in
the last 7 days
</Text>
<Table verticalSpacing={4} withRowBorders={false} maw={560}>
<Table.Thead>
<Table.Tr>
<Table.Th>Fired</Table.Th>
<Table.Th>Resolved</Table.Th>
<Table.Th>For</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{episodes.slice(0, MAX_FIRINGS_SHOWN).map(({ start, end }) => (
<Table.Tr key={start}>
<Table.Td>
<FormatTime value={start} />
</Table.Td>
<Table.Td>
{end ? (
<FormatTime value={end} />
) : (
<Text span size="sm" c="var(--color-text-danger)">
Still firing
</Text>
)}
</Table.Td>
<Table.Td>
{/* An open episode runs until the history was read. */}
{formatDistanceStrict(
new Date(start),
end ? new Date(end) : dateRange[1],
)}
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
{hidden > 0 && (
<Text size="xs" c="dimmed">
{hidden} earlier {hidden === 1 ? 'firing is' : 'firings are'} not
shown.
</Text>
)}
</Stack>
);
}
Loading
Loading