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
12 changes: 11 additions & 1 deletion packages/app/src/DBSearchPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,13 @@ import SearchWhereInput, {
} from '@/components/SearchInput/SearchWhereInput';
import SearchPageActionBar from '@/components/SearchPageActionBar';
import SearchTotalCountChart from '@/components/SearchTotalCountChart';
import { CreateSloButton } from '@/components/Slos/CreateSloButton';
import { TableSourceForm } from '@/components/Sources/SourceForm';
import { SourceSelectControlled } from '@/components/SourceSelect';
import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor';
import { Tags } from '@/components/Tags';
import { TimePicker } from '@/components/TimePicker';
import { IS_LOCAL_MODE } from '@/config';
import { IS_LOCAL_MODE, IS_SLOS_ENABLED } from '@/config';
import { useAliasMapFromChartConfig } from '@/hooks/useChartConfig';
import { useExplainQuery } from '@/hooks/useExplainQuery';
import { useResolvedSourceParam } from '@/hooks/useResolvedSourceParam';
Expand Down Expand Up @@ -2743,6 +2744,15 @@ function DBSearchPageContent() {
</Group>
</Button>
)}
{!IS_LOCAL_MODE && IS_SLOS_ENABLED && (
<CreateSloButton
source={searchedConfig.source}
where={searchedConfig.where}
whereLanguage={searchedConfig.whereLanguage}
filters={searchedConfig.filters}
savedSearchName={savedSearch?.name}
/>
)}
{isCompact && (
<Button
variant="subtle"
Expand Down
52 changes: 52 additions & 0 deletions packages/app/src/components/Slos/CreateSloButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import Link from 'next/link';
import type { Filter } from '@hyperdx/common-utils/dist/types';
import { Button, Tooltip } from '@mantine/core';
import { IconTargetArrow } from '@tabler/icons-react';

import {
encodeJsonUrlParamValue,
encodeUrlParamValue,
} from '@/utils/urlParamEncoding';

/**
* Opens the SLO builder with the current search as the eligible events. The
* query and filters are copied, so later edits to the search leave the SLO
* alone.
*/
export function CreateSloButton({
source,
where,
whereLanguage,
filters,
savedSearchName,
}: {
source?: string | null;
where?: string | null;
whereLanguage?: string | null;
filters?: Filter[] | null;
savedSearchName?: string | null;
}) {
if (!source) return null;
const params = new URLSearchParams({
source: encodeUrlParamValue(source),
where: encodeUrlParamValue(where ?? ''),
whereLanguage: encodeUrlParamValue(whereLanguage ?? 'lucene'),
filters: encodeJsonUrlParamValue(filters ?? []),
});
if (savedSearchName) params.set('name', encodeUrlParamValue(savedSearchName));
return (
<Tooltip label="Create an SLO from this search" withArrow openDelay={300}>
<Button
component={Link}
href={`/slos/new?${params.toString()}`}
variant="secondary"
size="xs"
leftSection={<IconTargetArrow size={14} />}
style={{ flexShrink: 0 }}
data-testid="create-slo-button"
>
SLO
</Button>
</Tooltip>
);
}
45 changes: 43 additions & 2 deletions packages/app/src/components/Slos/SloEditorPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import dynamic from 'next/dynamic';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { useQueryStates } from 'nuqs';
import {
type FieldPath,
useForm,
useFormState,
useWatch,
} from 'react-hook-form';
import type { Filter } from '@hyperdx/common-utils/dist/types';
import {
Anchor,
Box,
Expand All @@ -30,6 +32,7 @@ import { withAppNavForSurface } from '@/layout';
import { useSaveSlo, useSlo, useSlosEnabledGuard } from '@/slo';
import { useSource } from '@/source';
import { getApiErrorMessage } from '@/utils/apiErrors';
import { parseAsJsonEncoded, parseAsStringEncoded } from '@/utils/queryParsers';

import {
SloDetailsFields,
Expand All @@ -40,8 +43,10 @@ import {
buildSloPreviewRequest,
DEFAULT_SLO_FORM_VALUES,
getSloPreviewKey,
sloCopyFormValues,
sloFormResolver,
type SloFormValues,
sloFormValuesFromSearch,
type SloPreviewRequest,
sloToFormValues,
toSloInput,
Expand All @@ -57,12 +62,28 @@ const PREVIEW_FIELDS: FieldPath<SloFormValues>[] = [
'window',
];

// Carried over from Search by "Create SLO from this search".
const prefillParsers = {
source: parseAsStringEncoded,
where: parseAsStringEncoded,
whereLanguage: parseAsStringEncoded,
filters: parseAsJsonEncoded<Filter[]>(),
name: parseAsStringEncoded,
};

function SloEditorPage() {
const enabled = useSlosEnabledGuard();
const router = useRouter();
const editId =
typeof router.query.sloId === 'string' ? router.query.sloId : undefined;
// "Duplicate" on an SLO links here with ?duplicate=<id>.
const duplicateId =
!editId && typeof router.query.duplicate === 'string'
? router.query.duplicate
: undefined;
const [prefill] = useQueryStates(prefillParsers);
const { data: existing } = useSlo(editId);
const { data: original } = useSlo(duplicateId);
const title = usePageTitle(editId ? 'Edit SLO' : 'New SLO');

const { control, handleSubmit, reset, setValue, getValues, trigger } =
Expand All @@ -77,16 +98,21 @@ function SloEditorPage() {
});
const { data: source } = useSource({ id: sourceId || undefined });

// Load the SLO being edited, once.
// Load the SLO being edited or copied, or the search it starts from, once.
const initializedRef = useRef(false);
useEffect(() => {
if (initializedRef.current || !router.isReady) return;
if (editId) {
if (!existing) return;
reset(sloToFormValues(existing));
} else if (duplicateId) {
if (!original) return;
reset(sloCopyFormValues(original));
} else if (prefill.source) {
reset(sloFormValuesFromSearch({ ...prefill, source: prefill.source }));
}
initializedRef.current = true;
}, [router.isReady, editId, existing, reset]);
}, [router.isReady, editId, existing, duplicateId, original, prefill, reset]);

const [preview, setPreview] = useState<SloPreviewRequest | null>(null);
const runPreview = async () => {
Expand All @@ -100,6 +126,21 @@ function SloEditorPage() {
source,
) !== preview.key;

// A definition carried over from Search previews itself once its source
// has loaded.
const autoPreviewedRef = useRef(false);
useEffect(() => {
if (autoPreviewedRef.current || !initializedRef.current || !source) return;
if (editId || !prefill.source) return;
autoPreviewedRef.current = true;
void trigger(PREVIEW_FIELDS).then(valid => {

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 — The preview for an SLO started from Search never runs, and a validation error shows instead

sloFormValuesFromSearch uses the default availability template with good: ''. SloIndicatorSchema's superRefine (packages/common-utils/src/slo.ts:215) rejects that, so trigger(PREVIEW_FIELDS) always resolves false. The user lands on a 'A good-event condition is required' error and no preview. The fix: validate only the eligible fields here, or skip validation of indicator.good (or build the preview from the eligible counts alone). Then add a test that drives this path, because the current unit test only checks the form values.

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 (!valid) return;
setPreview(
buildSloPreviewRequest(getValues(), source, Date.now()) ?? null,
);
});
});

const save = useSaveSlo();
const onSave = handleSubmit(async values => {
try {
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
Expand Up @@ -2,7 +2,7 @@ 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, IconPencil, IconTrash } from '@tabler/icons-react';
import { IconCopy, IconDots, IconPencil, IconTrash } from '@tabler/icons-react';

import { useDeleteSlo } from '@/slo';
import { useConfirm } from '@/useConfirm';
Expand Down Expand Up @@ -59,6 +59,15 @@ export function SloRowMenu({ slo }: { slo: SloApiResponse }) {
>
Edit
</Menu.Item>
{/* A copy starts without its alerts, as a duplicated tile does. */}
<Menu.Item
component={Link}
href={`/slos/new?duplicate=${slo.id}`}
leftSection={<IconCopy size={14} />}
data-testid="slo-duplicate"
>
Duplicate
</Menu.Item>
<Menu.Divider />
<Menu.Item
color="red"
Expand Down
35 changes: 35 additions & 0 deletions packages/app/src/components/Slos/__tests__/sloForm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import {
buildSloPreviewRequest,
DEFAULT_SLO_FORM_VALUES,
getSloPreviewKey,
sloCopyFormValues,
sloFormResolver,
type SloFormValues,
sloFormValuesFromSearch,
sloToFormValues,
toSloInput,
} from '@/components/Slos/sloForm';
Expand Down Expand Up @@ -170,6 +172,39 @@ describe('SLO form', () => {
);
});

it('copies an SLO under a new name and without its alerts', () => {
const copy = sloCopyFormValues(savedSlo);
expect(copy).toEqual({
...sloToFormValues(savedSlo),
name: 'Copy of Checkout availability',
alerts: undefined,
});
});

it('starts an SLO from a search', () => {
expect(
sloFormValuesFromSearch({
source: 'source-1',
name: 'Checkout errors',
where: 'ServiceName:checkout',
whereLanguage: 'lucene',
filters: null,
}),
).toEqual({
...DEFAULT_SLO_FORM_VALUES,
name: 'Checkout errors',
source: 'source-1',
indicator: {
...DEFAULT_SLO_FORM_VALUES.indicator,
eligible: {
where: 'ServiceName:checkout',
whereLanguage: 'lucene',
filters: [],
},
},
});
});

it('marks a preview stale when its counts would change, not the target', () => {
const key = getSloPreviewKey(valid, traceSource);
const retargeted: SloFormValues = { ...valid, target: 95 };
Expand Down
38 changes: 38 additions & 0 deletions packages/app/src/components/Slos/sloForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from '@hyperdx/common-utils/dist/slo';
import type {
BuilderChartConfigWithDateRange,
Filter,
TSource,
} from '@hyperdx/common-utils/dist/types';

Expand Down Expand Up @@ -76,6 +77,43 @@ export function sloToFormValues(slo: SloApiResponse): SloFormValues {
};
}

/** A copy of an SLO, named as such, without its alerts. */
export function sloCopyFormValues(slo: SloApiResponse): SloFormValues {
return {
...sloToFormValues(slo),
name: `Copy of ${slo.name}`.slice(0, 256),
alerts: DEFAULT_SLO_FORM_VALUES.alerts,
};
}

/** A search carried over by "Create SLO from this search". */
export type SloSearchPrefill = {
source: string;
name?: string | null;
where?: string | null;
whereLanguage?: string | null;
filters?: Filter[] | null;
};

/** A new SLO counting the events of a search. */
export function sloFormValuesFromSearch(
prefill: SloSearchPrefill,
): SloFormValues {
return {
...DEFAULT_SLO_FORM_VALUES,
name: prefill.name ?? '',
source: prefill.source,
indicator: {
...DEFAULT_SLO_FORM_VALUES.indicator,
eligible: {
where: prefill.where ?? '',
whereLanguage: prefill.whereLanguage === 'lucene' ? 'lucene' : 'sql',
filters: prefill.filters ?? [],
},
},
};
}

/**
* The source's duration column and its unit, when the expression is that
* column. It needs no cast and its unit is the source's duration precision.
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/slo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ const SLO_POLL_MS = 60_000;
const SLO_FIRST_SNAPSHOT_POLL_MS = 10_000;

/**
* Direct-URL guard while the feature bakes: the nav only links to SLOs when
* the flag is on, but the routes must bounce too.
* Direct-URL guard while the feature bakes: the nav and Search only link to
* SLOs when the flag is on, but the routes must bounce too.
*/
export function useSlosEnabledGuard(): boolean {
const router = useRouter();
Expand Down
Loading