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
3 changes: 3 additions & 0 deletions packages/app/pages/slos/[sloId]/edit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import SloEditorPage from '@/components/Slos/SloEditorPage';

export default SloEditorPage;
144 changes: 143 additions & 1 deletion packages/app/src/components/Slos/SloDefinitionFields.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,37 @@
import { useEffect, useRef } from 'react';
import {
type Control,
Controller,
type UseFormGetValues,
type UseFormSetValue,
useFormState,
useWatch,
} from 'react-hook-form';
import { tcFromSource } from '@hyperdx/common-utils/dist/core/metadata';
import { buildSloAvailabilityCondition } from '@hyperdx/common-utils/dist/core/slo';
import { SloWindowSchema } from '@hyperdx/common-utils/dist/slo';
import { SourceKind, type TSource } from '@hyperdx/common-utils/dist/types';
import { Input } from '@mantine/core';
import {
Button,
Group,
Input,
NumberInput,
Radio,
TagsInput,
Text,
Textarea,
} from '@mantine/core';

import SearchWhereInput from '@/components/SearchInput/SearchWhereInput';
import { SourceSelectControlled } from '@/components/SourceSelect';
import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor';

import type { SloFormValues } from './sloForm';
import { SloFormRow } from './SloFormLayout';
import { formatSloWindow } from './sloUtils';

const SLO_SOURCE_KINDS = [SourceKind.Trace, SourceKind.Log];
const TARGET_PRESETS = [99, 99.5, 99.9, 99.95];

/** Which events count, and which of them are good. */
export function SloIndicatorFields({
Expand Down Expand Up @@ -97,3 +110,132 @@ export function SloIndicatorFields({
</>
);
}

/** The target and the rolling window it applies to. */
export function SloObjectiveFields({
control,
setValue,
}: {
control: Control<SloFormValues>;
setValue: UseFormSetValue<SloFormValues>;
}) {
const [target, sloWindow] = useWatch({
control,
name: ['target', 'window'],
});
return (
<>
<SloFormRow
label="Target"
helpText="The share of eligible events that must be good over the window."
>
<Group gap="xs" align="flex-start" wrap="nowrap">
<Controller
control={control}
name="target"
render={({ field, fieldState }) => (
<NumberInput
aria-label="Target"
suffix="%"
decimalScale={3}
step={0.1}
// Out-of-range values get an error rather than a silent change.
clampBehavior="none"
value={field.value}
onChange={v => field.onChange(typeof v === 'number' ? v : 0)}
error={fieldState.error?.message}
w={120}
data-testid="slo-target"
/>
)}
/>
{TARGET_PRESETS.map(t => (
<Button
key={t}
variant={target === t ? 'primary' : 'secondary'}
onClick={() => setValue('target', t, { shouldValidate: true })}
>
{t}%
</Button>
))}
</Group>
<Text size="xs" c="dimmed" mt={4}>
Error budget: {Number((100 - (target ?? 0)).toFixed(3))}% of eligible
events may be bad over {formatSloWindow(sloWindow)}.
</Text>
</SloFormRow>
<SloFormRow
label="Window"
helpText="The SLI and the error budget cover this many days up to now."
inline
>
<Controller
control={control}
name="window"
render={({ field }) => (
<Radio.Group
value={field.value}
onChange={value => {
const next = SloWindowSchema.safeParse(value);
if (next.success) field.onChange(next.data);
}}
aria-label="Window"
data-testid="slo-window"
>
<Group>
{SloWindowSchema.options.map(w => (
<Radio
key={w}
value={w}
label={`Rolling ${formatSloWindow(w)}`}
/>
))}
</Group>
</Radio.Group>
)}
/>
</SloFormRow>
</>
);
}

/** What the SLO is for, and tags to find it by. */
export function SloDetailsFields({
control,
}: {
control: Control<SloFormValues>;
}) {
return (
<>
<SloFormRow label="Description">
<Controller
control={control}
name="description"
render={({ field }) => (
<Textarea
{...field}
aria-label="Description"
placeholder="Optional. What this SLO covers and who owns it."
autosize
minRows={2}
/>
)}
/>
</SloFormRow>
<SloFormRow label="Tags">
<Controller
control={control}
name="tags"
render={({ field }) => (
<TagsInput
aria-label="Tags"
value={field.value}
onChange={field.onChange}
clearable
/>
)}
/>
</SloFormRow>
</>
);
}
58 changes: 49 additions & 9 deletions packages/app/src/components/Slos/SloEditorPage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect, useRef } from 'react';
import dynamic from 'next/dynamic';
import Head from 'next/head';
import Link from 'next/link';
Expand All @@ -21,38 +22,57 @@ import { usePageTitle } from '@/brand';
import { InlineNameInputControlled } from '@/components/InlineNameInput/InlineNameInput';
import { PageHeader } from '@/components/PageHeader';
import { withAppNavForSurface } from '@/layout';
import { useSaveSlo, useSlosEnabledGuard } from '@/slo';
import { useSaveSlo, useSlo, useSlosEnabledGuard } from '@/slo';
import { useSource } from '@/source';
import { getApiErrorMessage } from '@/utils/apiErrors';

import { SloIndicatorFields } from './SloDefinitionFields';
import {
SloDetailsFields,
SloIndicatorFields,
SloObjectiveFields,
} from './SloDefinitionFields';
import {
DEFAULT_SLO_FORM_VALUES,
sloFormResolver,
type SloFormValues,
sloToFormValues,
toSloInput,
} from './sloForm';
import { SloFormSection } from './SloFormLayout';

function SloEditorPage() {
const enabled = useSlosEnabledGuard();
const router = useRouter();
const title = usePageTitle('New SLO');
const editId =
typeof router.query.sloId === 'string' ? router.query.sloId : undefined;
const { data: existing } = useSlo(editId);
const title = usePageTitle(editId ? 'Edit SLO' : 'New SLO');

const { control, handleSubmit, setValue, getValues } = useForm<SloFormValues>(
{
const { control, handleSubmit, reset, setValue, getValues } =
useForm<SloFormValues>({
defaultValues: DEFAULT_SLO_FORM_VALUES,
resolver: sloFormResolver,
},
);
});
const { errors } = useFormState({ control, name: 'name' });
const sourceId = useWatch({ control, name: 'source' });
const { data: source } = useSource({ id: sourceId || undefined });

// Load the SLO being edited, once.
const initializedRef = useRef(false);
useEffect(() => {

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 — Edit page shows an editable default form while loading, then overwrites any input; a failed fetch leaves a blank 'Save SLO' form

useSlo is read only for data, so while it loads the page shows the defaults (Untitled SLO, 99.9%, 30d) as an editable form. Anything typed before the response arrives is thrown away by reset(sloToFormValues(existing)). If the fetch fails (for example a 404 for a deleted id), the page stays on the empty form forever and Save PUTs to a missing id. Show a loader until existing is loaded, and an error or not-found state (using EmptyState) when isError.

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

if (initializedRef.current || !router.isReady) return;
if (editId) {
if (!existing) return;
reset(sloToFormValues(existing));
}
initializedRef.current = true;
}, [router.isReady, editId, existing, reset]);

const save = useSaveSlo();
const onSave = handleSubmit(async values => {
try {
const saved = await save.mutateAsync({
id: editId,
slo: toSloInput(values, source),
});
notifications.show({ color: 'green', message: `Saved ${saved.name}` });
Expand All @@ -79,6 +99,16 @@ function SloEditorPage() {
<Anchor component={Link} href="/slos" fz="sm" c="dimmed">
SLOs
</Anchor>
{editId && existing && (
<Anchor
component={Link}
href={`/slos/${editId}`}
fz="sm"
c="dimmed"
>
{existing.name}
</Anchor>
)}
</Breadcrumbs>
}
>
Expand All @@ -102,7 +132,11 @@ function SloEditorPage() {
)}
</Box>
<Group gap="xs" wrap="nowrap">
<Button component={Link} href="/slos" variant="secondary">
<Button
component={Link}
href={editId ? `/slos/${editId}` : '/slos'}

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 — In edit mode, Cancel and the SLO-name breadcrumb link to /slos/, which has no page in this PR

At this commit packages/app/pages/slos/ only has index.tsx, new.tsx and [sloId]/edit.tsx; the detail page arrives in #3808. Until it lands, clicking Cancel (and the breadcrumb at line 105) while editing leads to a 404. Point both at /slos for now, and switch them to /slos/${editId} in #3808.

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

variant="secondary"
>
Cancel
</Button>
<Button
Expand All @@ -111,7 +145,7 @@ function SloEditorPage() {
loading={save.isPending}
data-testid="slo-save"
>
Create SLO
{editId ? 'Save SLO' : 'Create SLO'}
</Button>
</Group>
</Flex>
Expand All @@ -132,6 +166,12 @@ function SloEditorPage() {
source={source}
/>
</SloFormSection>
<SloFormSection title="Objective">
<SloObjectiveFields control={control} setValue={setValue} />
</SloFormSection>
<SloFormSection title="Details">
<SloDetailsFields control={control} />
</SloFormSection>
</Stack>
</Grid.Col>
</Grid>
Expand Down
11 changes: 10 additions & 1 deletion packages/app/src/components/Slos/SloRowMenu.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import Link from 'next/link';
import type { SloApiResponse } from '@hyperdx/common-utils/dist/slo';
import { ActionIcon, Menu } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import { IconDots, IconTrash } from '@tabler/icons-react';
import { IconDots, IconPencil, IconTrash } from '@tabler/icons-react';

import { useDeleteSlo } from '@/slo';
import { useConfirm } from '@/useConfirm';
Expand Down Expand Up @@ -51,6 +52,14 @@ export function SloRowMenu({ slo }: { slo: SloApiResponse }) {
</ActionIcon>
</Menu.Target>
<Menu.Dropdown onClick={e => e.stopPropagation()}>
<Menu.Item
component={Link}
href={`/slos/${slo.id}/edit`}
leftSection={<IconPencil size={14} />}
>
Edit
</Menu.Item>
<Menu.Divider />
<Menu.Item
color="red"
leftSection={<IconTrash size={14} />}
Expand Down
46 changes: 46 additions & 0 deletions packages/app/src/components/Slos/__tests__/sloForm.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import type { FieldErrors } from 'react-hook-form';
import type { SloApiResponse } from '@hyperdx/common-utils/dist/slo';
import { SourceKind, type TSource } from '@hyperdx/common-utils/dist/types';

import {
DEFAULT_SLO_FORM_VALUES,
sloFormResolver,
type SloFormValues,
sloToFormValues,
toSloInput,
} from '@/components/Slos/sloForm';

Expand Down Expand Up @@ -45,6 +47,33 @@ const latency = (expression: string): SloFormValues => ({
},
});

const savedSlo: SloApiResponse = {
version: 1,
name: 'Checkout availability',
source: 'source-1',
indicator: {
template: 'availability',
eligible: {
where: "SpanKind = 'Server'",
whereLanguage: 'sql',
filters: [{ type: 'sql', condition: "ServiceName = 'checkout'" }],
},
good: "StatusCode != 'Error'",
},
target: 99.5,
window: '7d',
groupBy: 'ServiceName',
tags: ['checkout'],
description: 'Checkout requests that do not fail',
alerts: {
fastBurn: { channels: [{ type: 'webhook', webhookId: 'hook-1' }] },
},
alertStates: {},
id: 'slo-1',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
};

const resolve = (values: SloFormValues) =>
sloFormResolver(values, undefined, {
fields: {},
Expand Down Expand Up @@ -121,4 +150,21 @@ describe('SLO form', () => {
.indicator.latency?.unit,
).toBe('ms');
});

it('loads a saved SLO back into the form unchanged', () => {
const saved = savedSlo;
const values = sloToFormValues(saved);
expect(toSloInput(values)).toEqual(
expect.objectContaining({
name: saved.name,
description: saved.description,
tags: saved.tags,
indicator: saved.indicator,
target: saved.target,
window: saved.window,
groupBy: saved.groupBy,
alerts: saved.alerts,
}),
);
});
});
Loading
Loading