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
13 changes: 11 additions & 2 deletions packages/app/src/AlertDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { AlertInterval } from '@hyperdx/common-utils/dist/types';
import { AlertInterval, AlertSource } from '@hyperdx/common-utils/dist/types';
import {
ActionIcon,
Anchor,
Expand All @@ -27,7 +27,7 @@ import { AlertStateBadge } from '@/components/alerts/AlertStateBadge';
import EmptyState from '@/components/EmptyState';
import { PageHeader } from '@/components/PageHeader';
import { TimePicker } from '@/components/TimePicker';
import { IS_ALERT_DETAILS_ENABLED } from '@/config';
import { IS_ALERT_DETAILS_ENABLED, IS_SLOS_ENABLED } from '@/config';
import { getAlertSourceLabel, getAlertSourceUrl } from '@/utils/alerts';

import api from './api';
Expand Down Expand Up @@ -237,6 +237,15 @@ export default function AlertDetailPage() {

const { data, isLoading, isError } = api.useAlert(alertId);
const alert = data?.data;

// An SLO's alert is shown, and changed, on its SLO.
const sloId =
IS_SLOS_ENABLED && alert?.source === AlertSource.SLO
? alert.sloId
: undefined;
React.useEffect(() => {
if (sloId) router.replace(`/slos/${sloId}`);
}, [sloId, router]);
const title = usePageTitle(
alert ? `${alert.displayName} - Alerts` : 'Alerts',
);
Expand Down
14 changes: 10 additions & 4 deletions packages/app/src/components/alerts/AlertDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,15 @@ import {
IconHelpCircle,
IconNote,
IconTableRow,
IconTargetArrow,
} from '@tabler/icons-react';

import { AckAlert } from '@/components/alerts/AckAlert';
import { AlertHistoryCardList } from '@/components/alerts/AlertHistoryCards';
import { AlertPropertiesSummary } from '@/components/alerts/AlertPropertiesSummary';
import { AlertRowMenu } from '@/components/alerts/AlertRowMenu';
import { AlertStateBadge } from '@/components/alerts/AlertStateBadge';
import { IS_ALERT_DETAILS_ENABLED } from '@/config';
import { IS_ALERT_DETAILS_ENABLED, IS_SLOS_ENABLED } from '@/config';
import type { AlertsPageItem } from '@/types';
import { getAlertSourceLabel, getAlertSourceUrl } from '@/utils/alerts';

Expand Down Expand Up @@ -114,6 +115,8 @@ export const AlertDetails = React.memo(function AlertDetails({
// Matches the chart explorer's nav icon: an inline alert's query is
// authored and reopened there.
return <IconChartDots size={14} aria-hidden="true" />;
case AlertSource.SLO:
return <IconTargetArrow size={14} aria-hidden="true" />;
default:
return <IconHelpCircle size={14} aria-hidden="true" />;
}
Expand Down Expand Up @@ -146,9 +149,12 @@ export const AlertDetails = React.memo(function AlertDetails({
// "Open <source>" and falls back to its own wording when blank.
const linkTitle = alert.source ? sourceLabel : '';

const nameHref = IS_ALERT_DETAILS_ENABLED
? `/alerts/${alert._id}`
: alertUrl || undefined;
// An SLO alert's status, history and settings live on its SLO.
const nameHref =
IS_ALERT_DETAILS_ENABLED &&
!(IS_SLOS_ENABLED && alert.source === AlertSource.SLO)
? `/alerts/${alert._id}`
: alertUrl || undefined;

return (
<div data-testid={`alert-card-${alert._id}`} className={styles.alertRow}>
Expand Down
25 changes: 20 additions & 5 deletions packages/app/src/components/alerts/AlertPropertiesSummary.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import * as React from 'react';
import {
describeSloAlertRule,
getSloAlertRuleLabel,
} from '@hyperdx/common-utils/dist/slo';
import {
AlertSource,
isRangeThresholdType,
WebhookService,
} from '@hyperdx/common-utils/dist/types';
Expand Down Expand Up @@ -180,12 +185,22 @@ export function AlertPropertiesSummary({
return (
<div className={`fs-8 ${styles.propertiesSummary}`}>
<span className={styles.propertySegment}>
If value {thresholdLabel}{' '}
<span className="fw-bold">{alert.threshold}</span>
{isRangeThresholdType(alert.thresholdType) && (
{alert.source === AlertSource.SLO ? (
// Its value only says how close the SLO's burn rule is to holding.
<>
{getSloAlertRuleLabel(alert.sloRule ?? 'fastBurn')}: if{' '}
{describeSloAlertRule(alert.sloRule ?? 'fastBurn')}
</>
) : (
<>
{' '}
and <span className="fw-bold">{alert.thresholdMax ?? '-'}</span>
If value {thresholdLabel}{' '}
<span className="fw-bold">{alert.threshold}</span>
{isRangeThresholdType(alert.thresholdType) && (
<>
{' '}
and <span className="fw-bold">{alert.thresholdMax ?? '-'}</span>
</>
)}
</>
)}
</span>
Expand Down
52 changes: 40 additions & 12 deletions packages/app/src/components/alerts/AlertRowMenu.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as React from 'react';
import Link from 'next/link';
import { isImportableAlert } from '@hyperdx/common-utils/dist/iac';
import { getSloAlertRuleLabel } from '@hyperdx/common-utils/dist/slo';
import { AlertSource } from '@hyperdx/common-utils/dist/types';
import { ActionIcon, Menu, Modal } from '@mantine/core';
import { notifications } from '@mantine/notifications';
Expand All @@ -19,7 +20,7 @@ import { EditAlertModal } from '@/components/alerts/EditAlertModal';
import { EditInlineAlertModal } from '@/components/alerts/EditInlineAlertModal';
import { TerraformHelperPanel } from '@/components/Iac/TerraformHelperPanel';
import { useTerraformSnippets } from '@/components/Iac/useTerraformSnippets';
import { IS_IAC_EXPORT_ENABLED } from '@/config';
import { IS_IAC_EXPORT_ENABLED, IS_SLOS_ENABLED } from '@/config';
import type { AlertsPageItem } from '@/types';
import { useConfirm } from '@/useConfirm';
import { intervalToDateRange } from '@/utils/alerts';
Expand Down Expand Up @@ -65,7 +66,20 @@ export function AlertRowMenu({
// `||`, not `??`: the empty string these arrive as for an unresolvable
// source is not nullish, and would read as "Open " and "Delete ?".
const name = alertName?.trim() || 'this alert';
const sourceLabel = linkTitle?.trim().toLowerCase() || 'source';
// An SLO owns its alert: it is edited from the SLO, and deleting it here
// turns the alert off on the SLO. With SLOs turned off there is no SLO
// page to edit it on.
const isSloAlert = alert.source === AlertSource.SLO;
const sloManaged = isSloAlert && IS_SLOS_ENABLED;
// The alert carries its SLO's name, so "Delete {name}?" would read as
// deleting the SLO.
const deleteMessage = isSloAlert
? `Delete the ${getSloAlertRuleLabel(alert.sloRule ?? 'fastBurn').toLowerCase()} alert of ${alertName?.trim() || 'this SLO'}? The SLO keeps tracking.`
: `Delete ${name}?`;
// "SLO" is an acronym, so it keeps its case mid-sentence.
const sourceLabel = isSloAlert
? 'SLO'
: linkTitle?.trim().toLowerCase() || 'source';
const [terraformOpened, setTerraformOpened] = React.useState(false);
const [editOpened, setEditOpened] = React.useState(false);
const confirm = useConfirm();
Expand Down Expand Up @@ -120,7 +134,7 @@ export function AlertRowMenu({
});

const onDelete = React.useCallback(async () => {
const confirmed = await confirm(`Delete ${name}?`, 'Delete', {
const confirmed = await confirm(deleteMessage, 'Delete', {
variant: 'danger',
});
if (!confirmed) {
Expand All @@ -134,10 +148,11 @@ export function AlertRowMenu({
autoClose: 5000,
});
// The alerts list and the source-bound edit surfaces (saved search
// modal / dashboard tile editor) all render this alert.
// modal / dashboard tile editor / SLO pages) all render this alert.
queryClient.invalidateQueries({ queryKey: api.getAlertsQueryKey() });
queryClient.invalidateQueries({ queryKey: ['saved-search'] });
queryClient.invalidateQueries({ queryKey: ['dashboards'] });
queryClient.invalidateQueries({ queryKey: ['slos'] });
onDeleted?.();
} catch (error) {
console.error('Failed to delete alert:', error);
Expand All @@ -152,7 +167,7 @@ export function AlertRowMenu({
brandName,
confirm,
deleteAlert,
name,
deleteMessage,
onDeleted,
queryClient,
]);
Expand All @@ -171,13 +186,26 @@ export function AlertRowMenu({
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
leftSection={<IconPencil size={16} />}
onClick={() => setEditOpened(true)}
data-testid={`alert-edit-${alert._id}`}
>
Edit alert
</Menu.Item>
{sloManaged ? (
<Menu.Item
component={Link}
href={`/slos/${alert.sloId}/edit#alerts`}
leftSection={<IconPencil size={16} />}
data-testid={`alert-edit-${alert._id}`}
>
Edit in SLO
</Menu.Item>
) : (
!isSloAlert && (
<Menu.Item
leftSection={<IconPencil size={16} />}
onClick={() => setEditOpened(true)}
data-testid={`alert-edit-${alert._id}`}
>
Edit alert
</Menu.Item>
)
)}
{alertUrl && (
<Menu.Item
component={Link}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { AlertThresholdType } from '@hyperdx/common-utils/dist/types';
import {
AlertSource,
AlertThresholdType,
} from '@hyperdx/common-utils/dist/types';
import { act, screen } from '@testing-library/react';

import { AlertPropertiesSummary } from '@/components/alerts/AlertPropertiesSummary';
Expand Down Expand Up @@ -154,3 +157,37 @@ describe('AlertPropertiesSummary notification targets', () => {
});
});
});

describe('AlertPropertiesSummary condition', () => {
it('states the threshold of a threshold alert', () => {
renderWithMantine(<AlertPropertiesSummary alert={baseAlert} />);

expect(screen.getByText(/If value/).textContent).toBe(
'If value is at least (≥) 3',
);
});

// An SLO alert's threshold is 1 on a value that is not a burn rate, so the
// row states the SLO's burn rule instead.
it("states an SLO alert's burn rule", () => {
renderWithMantine(
<AlertPropertiesSummary
alert={
{
...baseAlert,
source: AlertSource.SLO,
threshold: 1,
sloId: 'slo-1',
sloRule: 'slowBurn',
} satisfies AlertsPageItem
}
/>,
);

expect(
screen.getByText(
'Slow burn: if 5% of the error budget is spent within 6 hours',
),
).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,25 @@ jest.mock('@/api', () => ({
},
}));

jest.mock('@/config', () => ({
IS_IAC_EXPORT_ENABLED: true,
BASE_PATH: '',
}));
// The flag lives in the factory: modules read it while the imports load,
// before anything declared in this file exists.
jest.mock('@/config', () => {
const flags = { slos: true };
return {
IS_IAC_EXPORT_ENABLED: true,
BASE_PATH: '',
get IS_SLOS_ENABLED() {
return flags.slos;
},
setSlosEnabled: (enabled: boolean) => {
flags.slos = enabled;
},
};
});
const setSlosEnabled = (enabled: boolean) =>
jest
.requireMock<{ setSlosEnabled: (enabled: boolean) => void }>('@/config')
.setSlosEnabled(enabled);

// The edit modal pulls in the whole alert form (queries, editors, target
// picker); this suite is about the menu, so stub it down to an open/closed
Expand Down Expand Up @@ -94,6 +109,14 @@ const unaddressableTileAlert: AlertsPageItem = {
unaddressableTile: true,
};

const sloAlert: AlertsPageItem = {
...savedSearchAlert,
_id: 'alert-5',
source: AlertSource.SLO,
savedSearchId: undefined,
sloId: 'slo-1',
};

function renderMenu(ui: React.ReactElement) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
Expand Down Expand Up @@ -156,6 +179,57 @@ describe('AlertRowMenu', () => {
expect(screen.queryByTestId('edit-alert-modal')).not.toBeInTheDocument();
});

// An SLO owns its alert: edits go to the SLO.
it('sends an SLO alert to its SLO for edits', async () => {
renderMenu(
<AlertRowMenu alert={sloAlert} alertUrl="/slos/slo-1" linkTitle="SLO" />,
);
await openMenu('alert-row-menu-alert-5');

expect(screen.getByTestId('alert-edit-alert-5')).toHaveAttribute(
'href',
'/slos/slo-1/edit#alerts',
);
expect(screen.getByText('Open SLO')).toBeInTheDocument();
expect(
screen.queryByTestId('terraform-menu-item-alert-5'),
).not.toBeInTheDocument();
});

// The alert carries its SLO's name, so the generic "Delete {name}?" would
// read as deleting the SLO itself.
it('says the SLO stays when its alert is deleted', async () => {
renderMenu(
<AlertRowMenu alert={sloAlert} alertName="Checkout availability" />,
);
await openMenu('alert-row-menu-alert-5');
await userEvent.click(screen.getByTestId('alert-delete-alert-5'));

expect(confirm).toHaveBeenCalledWith(
'Delete the fast burn alert of Checkout availability? The SLO keeps tracking.',
'Delete',
expect.objectContaining({ variant: 'danger' }),
);
expect(mutateAsync).toHaveBeenCalledWith('alert-5');
});

// With SLOs turned off there is no SLO page to edit it on, but it can still
// be deleted.
it('offers only delete for an SLO alert while SLOs are turned off', async () => {
setSlosEnabled(false);
try {
renderMenu(<AlertRowMenu alert={sloAlert} />);
await openMenu('alert-row-menu-alert-5');

expect(screen.getByTestId('alert-delete-alert-5')).toBeInTheDocument();
expect(
screen.queryByTestId('alert-edit-alert-5'),
).not.toBeInTheDocument();
} finally {
setSlosEnabled(true);
}
});

it('offers Terraform export for a saved-search alert', async () => {
renderMenu(<AlertRowMenu alert={savedSearchAlert} />);
await openMenu('alert-row-menu-alert-1');
Expand Down
13 changes: 13 additions & 0 deletions packages/app/src/utils/__tests__/alerts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ describe('getAlertSourceLabel', () => {
'Dashboard tile',
);
expect(getAlertSourceLabel({ source: AlertSource.INLINE })).toBe('Chart');
expect(getAlertSourceLabel({ source: AlertSource.SLO })).toBe('SLO');
});

// The row's tooltip, the alerts-page filter and free-text search all read
Expand Down Expand Up @@ -293,6 +294,18 @@ describe('getAlertSourceUrl', () => {
).toBe('/chart?alertId=alert-1');
expect(getAlertSourceUrl(inlineAlert())).toBe('/chart?alertId=alert-1');
});

// The SLO is where its alert's state, history and settings live.
it('links an SLO alert to its SLO', () => {
expect(
getAlertSourceUrl(
inlineAlert({ source: AlertSource.SLO, sloId: 'slo-1' }),
),
).toBe('/slos/slo-1');
expect(getAlertSourceUrl(inlineAlert({ source: AlertSource.SLO }))).toBe(
'',
);
});
});

describe('buildInlineAlertPayload', () => {
Expand Down
Loading
Loading