diff --git a/packages/app/pages/slos/new.tsx b/packages/app/pages/slos/new.tsx new file mode 100644 index 000000000..c21f7658e --- /dev/null +++ b/packages/app/pages/slos/new.tsx @@ -0,0 +1,3 @@ +import SloEditorPage from '@/components/Slos/SloEditorPage'; + +export default SloEditorPage; diff --git a/packages/app/src/components/Slos/SloDefinitionFields.tsx b/packages/app/src/components/Slos/SloDefinitionFields.tsx new file mode 100644 index 000000000..5a34738c8 --- /dev/null +++ b/packages/app/src/components/Slos/SloDefinitionFields.tsx @@ -0,0 +1,99 @@ +import { useEffect, useRef } from 'react'; +import { + type Control, + 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 { SourceKind, type TSource } from '@hyperdx/common-utils/dist/types'; +import { Input } 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'; + +const SLO_SOURCE_KINDS = [SourceKind.Trace, SourceKind.Log]; + +/** Which events count, and which of them are good. */ +export function SloIndicatorFields({ + control, + getValues, + setValue, + source, +}: { + control: Control; + getValues: UseFormGetValues; + setValue: UseFormSetValue; + source?: TSource; +}) { + const sourceId = useWatch({ control, name: 'source' }); + const { errors } = useFormState({ control, name: 'indicator.good' }); + const tableConnection = tcFromSource(source); + + // The availability condition starts from the source's status or severity + // column. Switching sources replaces a seeded condition, never one the + // user wrote. + const seededGoodRef = useRef(undefined); + useEffect(() => { + if (!source) return; + const current = getValues('indicator.good').trim(); + const condition = buildSloAvailabilityCondition(source); + if (current === '' || current === seededGoodRef.current) { + setValue('indicator.good', condition ?? '', { + shouldValidate: condition != null, + }); + } + seededGoodRef.current = condition; + }, [source, getValues, setValue]); + + return ( + <> + + {/* The select shows its own error. */} +
+ +
+
+ + + + + + {errors.indicator?.good?.message} + + + ); +} diff --git a/packages/app/src/components/Slos/SloEditorPage.tsx b/packages/app/src/components/Slos/SloEditorPage.tsx new file mode 100644 index 000000000..898125942 --- /dev/null +++ b/packages/app/src/components/Slos/SloEditorPage.tsx @@ -0,0 +1,150 @@ +import dynamic from 'next/dynamic'; +import Head from 'next/head'; +import Link from 'next/link'; +import { useRouter } from 'next/router'; +import { useForm, useFormState, useWatch } from 'react-hook-form'; +import { + Anchor, + Box, + Breadcrumbs, + Button, + Container, + Flex, + Grid, + Group, + Stack, + Text, +} from '@mantine/core'; +import { notifications } from '@mantine/notifications'; + +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 { useSource } from '@/source'; +import { getApiErrorMessage } from '@/utils/apiErrors'; + +import { SloIndicatorFields } from './SloDefinitionFields'; +import { + DEFAULT_SLO_FORM_VALUES, + sloFormResolver, + type SloFormValues, + toSloInput, +} from './sloForm'; +import { SloFormSection } from './SloFormLayout'; + +function SloEditorPage() { + const enabled = useSlosEnabledGuard(); + const router = useRouter(); + const title = usePageTitle('New SLO'); + + const { control, handleSubmit, setValue, getValues } = useForm( + { + 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 }); + + const save = useSaveSlo(); + const onSave = handleSubmit(async values => { + try { + const saved = await save.mutateAsync({ + slo: toSloInput(values, source), + }); + notifications.show({ color: 'green', message: `Saved ${saved.name}` }); + router.push('/slos'); + } catch (e) { + notifications.show({ + color: 'red', + title: 'Could not save the SLO', + message: await getApiErrorMessage(e, 'Something went wrong'), + }); + } + }); + + if (!enabled) return null; + + return ( +
+ + {title} + + + + SLOs + + + } + > + {/* The page title, like a dashboard's or a saved search's name. */} + + {/* Takes the free width, which the name grows into. */} + + + {errors.name?.message && ( + + {errors.name.message} + + )} + + + + + + + + {/* Keeps the form's controls under the sticky header when scrolled. */} + + + + + + + + + + + +
+ ); +} + +// Client only, like Search and the chart explorer: the SQL editors and the +// themed charts render differently on the server. +const SloEditorPageDynamic = dynamic(async () => SloEditorPage, { ssr: false }); + +// @ts-expect-error next/dynamic component type does not include the getLayout static +SloEditorPageDynamic.getLayout = withAppNavForSurface('slo'); + +export default SloEditorPageDynamic; diff --git a/packages/app/src/components/Slos/SloFormLayout.tsx b/packages/app/src/components/Slos/SloFormLayout.tsx new file mode 100644 index 000000000..17b4eedc4 --- /dev/null +++ b/packages/app/src/components/Slos/SloFormLayout.tsx @@ -0,0 +1,60 @@ +import { Flex, Paper, Stack, Text } from '@mantine/core'; + +import { EDITOR_INPUT_HEIGHTS } from '@/components/editorInputHeights'; +import { FormRow } from '@/components/Sources/SourceForm/FormRow'; + +/** A titled group of rows in the SLO builder. */ +export function SloFormSection({ + id, + title, + description, + children, +}: { + id?: string; + title: string; + description?: string; + children: React.ReactNode; +}) { + return ( + + {title} + {description && ( + + {description} + + )} + + {children} + + + ); +} + +/** + * A row of the SLO builder: the Source form's label column, with the label + * kept in sentence case. `inline` centers a control shorter than an input, + * such as a radio group or a switch, on the label. + */ +export function SloFormRow({ + label, + helpText, + inline, + children, +}: { + label: string; + helpText?: string; + inline?: boolean; + children: React.ReactNode; +}) { + return ( + {label}} helpText={helpText}> + {inline ? ( + + {children} + + ) : ( + children + )} + + ); +} diff --git a/packages/app/src/components/Slos/SlosListPage.tsx b/packages/app/src/components/Slos/SlosListPage.tsx index 12b0d3025..5cbc5069c 100644 --- a/packages/app/src/components/Slos/SlosListPage.tsx +++ b/packages/app/src/components/Slos/SlosListPage.tsx @@ -1,5 +1,6 @@ import { useMemo } from 'react'; import Head from 'next/head'; +import Link from 'next/link'; import { parseAsArrayOf, parseAsString, @@ -16,7 +17,7 @@ import { Skeleton, Text, } from '@mantine/core'; -import { IconTargetArrow } from '@tabler/icons-react'; +import { IconPlus, IconTargetArrow } from '@tabler/icons-react'; import { usePageTitle } from '@/brand'; import EmptyState from '@/components/EmptyState'; @@ -116,7 +117,20 @@ export default function SlosListPage() { {title} - + } + data-testid="new-slo-button" + > + New SLO + + } + />
{hasNone ? ( @@ -124,7 +138,11 @@ export default function SlosListPage() { icon={} title="No SLOs yet" description="Define a target for the share of good events in your logs or traces, and get alerted when the error budget burns too fast." - /> + > + + ) : ( diff --git a/packages/app/src/components/Slos/__tests__/sloForm.test.ts b/packages/app/src/components/Slos/__tests__/sloForm.test.ts new file mode 100644 index 000000000..b5e4923ac --- /dev/null +++ b/packages/app/src/components/Slos/__tests__/sloForm.test.ts @@ -0,0 +1,124 @@ +import type { FieldErrors } from 'react-hook-form'; +import { SourceKind, type TSource } from '@hyperdx/common-utils/dist/types'; + +import { + DEFAULT_SLO_FORM_VALUES, + sloFormResolver, + type SloFormValues, + toSloInput, +} from '@/components/Slos/sloForm'; + +const traceSource: TSource = { + id: 'source-1', + kind: SourceKind.Trace, + name: 'Traces', + connection: 'connection-1', + from: { databaseName: 'otel', tableName: 'otel_traces' }, + timestampValueExpression: 'Timestamp', + defaultTableSelectExpression: 'Timestamp, ServiceName', + durationExpression: 'Duration', + durationPrecision: 9, + traceIdExpression: 'TraceId', + spanIdExpression: 'SpanId', + parentSpanIdExpression: 'ParentSpanId', + spanNameExpression: 'SpanName', + spanKindExpression: 'SpanKind', +}; + +const valid: SloFormValues = { + ...DEFAULT_SLO_FORM_VALUES, + name: 'Checkout availability', + source: 'source-1', + indicator: { + ...DEFAULT_SLO_FORM_VALUES.indicator, + good: "StatusCode != 'Error'", + }, +}; + +const latency = (expression: string): SloFormValues => ({ + ...valid, + indicator: { + ...valid.indicator, + template: 'latency', + good: '', + latency: { ...valid.indicator.latency, expression }, + }, +}); + +const resolve = (values: SloFormValues) => + sloFormResolver(values, undefined, { + fields: {}, + shouldUseNativeValidation: false, + }); + +const errorsOf = async ( + values: SloFormValues, +): Promise> => (await resolve(values)).errors; + +describe('SLO form', () => { + it('submits a valid definition as the form holds it', async () => { + const result = await resolve(valid); + expect(result.errors).toEqual({}); + expect(result.values).toBe(valid); + }); + + it('puts schema errors on the fields they belong to', async () => { + const errors = await errorsOf({ + ...valid, + name: ' ', + target: 100, + indicator: { ...valid.indicator, good: '' }, + }); + 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', + ); + }); + + it('validates only what the template uses', async () => { + // The good condition is ignored for latency, the duration is not. + const errors = await errorsOf(latency('')); + expect(errors.indicator?.good).toBeUndefined(); + expect(errors.indicator?.latency?.expression?.message).toBe( + 'A duration expression is required', + ); + // And an empty duration is ignored for availability. + expect((await resolve(valid)).errors).toEqual({}); + }); + + it('saves the good condition or the latency settings, not both', () => { + expect(toSloInput(valid).indicator).toEqual({ + template: 'availability', + eligible: { where: '', whereLanguage: 'sql' }, + good: "StatusCode != 'Error'", + }); + const { indicator } = toSloInput(latency('Duration'), traceSource); + expect(indicator.good).toBeUndefined(); + // The source's own duration column is numeric; anything else is cast. + expect(indicator.latency).toEqual( + expect.objectContaining({ expression: 'Duration', numeric: true }), + ); + expect( + toSloInput(latency("SpanAttributes['duration_ms']"), traceSource) + .indicator.latency?.numeric, + ).toBe(false); + }); + + it("takes a native duration's unit from the source's duration precision", () => { + const withUnit = (expression: string): SloFormValues => { + const values = latency(expression); + values.indicator.latency.unit = 'ms'; + return values; + }; + // The source stores nanoseconds, whatever the form holds. + expect( + toSloInput(withUnit('Duration'), traceSource).indicator.latency?.unit, + ).toBe('ns'); + // Any other expression is in the unit the user picked. + expect( + toSloInput(withUnit("SpanAttributes['duration_ms']"), traceSource) + .indicator.latency?.unit, + ).toBe('ms'); + }); +}); diff --git a/packages/app/src/components/Slos/sloForm.ts b/packages/app/src/components/Slos/sloForm.ts new file mode 100644 index 000000000..c4945f831 --- /dev/null +++ b/packages/app/src/components/Slos/sloForm.ts @@ -0,0 +1,108 @@ +import type { Resolver } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { getSloDefaultDuration } from '@hyperdx/common-utils/dist/core/sloLatency'; +import { + type SloInput, + SloInputSchema, + type SloLatency, +} from '@hyperdx/common-utils/dist/slo'; +import type { TSource } from '@hyperdx/common-utils/dist/types'; + +/** + * The builder edits the API input directly, so schema errors land on the + * fields they belong to. The form keeps the good condition and the latency + * settings side by side while the user switches templates; toSloInput keeps + * the one the template uses. + */ +export type SloFormValues = Omit & { + indicator: Omit & { + good: string; + latency: Omit; + }; +}; + +const DEFAULT_LATENCY: SloFormValues['indicator']['latency'] = { + expression: '', + unit: 'ms', + thresholdMs: 500, + requireDuration: true, +}; + +export const DEFAULT_SLO_FORM_VALUES: SloFormValues = { + name: '', + description: '', + tags: [], + source: '', + indicator: { + template: 'availability', + // SQL like the good condition, so both inputs read the same way. + eligible: { where: '', whereLanguage: 'sql' }, + good: '', + latency: DEFAULT_LATENCY, + }, + target: 99.9, + window: '30d', +}; + +/** + * 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. + * Any other expression is read as a number with a cast, which also works for + * string attributes, in the unit the user picks. + */ +function getNativeDuration(expression: string, source: TSource | undefined) { + const native = source ? getSloDefaultDuration(source) : undefined; + return native != null && native.expression === expression.trim() + ? native + : undefined; +} + +/** The latency settings as saved, with the unit of a native duration. */ +function toSloLatency( + latency: SloFormValues['indicator']['latency'], + source: TSource | undefined, +): SloLatency { + const native = getNativeDuration(latency.expression, source); + return { + ...latency, + unit: native?.unit ?? latency.unit, + numeric: native != null, + }; +} + +/** The indicator as saved: the good condition or the latency settings. */ +function toSloIndicator( + indicator: SloFormValues['indicator'], + source?: TSource, +): SloInput['indicator'] { + const { good, latency, ...rest } = indicator; + return rest.template === 'latency' + ? { ...rest, latency: toSloLatency(latency, source) } + : { ...rest, good }; +} + +export function toSloInput(values: SloFormValues, source?: TSource): SloInput { + return { + ...values, + indicator: toSloIndicator(values.indicator, source), + }; +} + +const sloInputResolver = zodResolver(SloInputSchema); + +/** Validates what will be saved, not the fields the template leaves out. */ +export const sloFormResolver: Resolver = async ( + values, + context, + { criteriaMode, fields, shouldUseNativeValidation }, +) => { + const { errors } = await sloInputResolver(toSloInput(values), context, { + criteriaMode, + fields, + shouldUseNativeValidation, + }); + // Submit the form's own values; toSloInput runs again with the source. + return Object.keys(errors).length > 0 + ? { values: {}, errors } + : { values, errors: {} }; +}; diff --git a/packages/app/src/slo.ts b/packages/app/src/slo.ts index 949b23b8a..daf983dd4 100644 --- a/packages/app/src/slo.ts +++ b/packages/app/src/slo.ts @@ -1,6 +1,6 @@ import { useEffect } from 'react'; import { useRouter } from 'next/router'; -import type { SloApiResponse } from '@hyperdx/common-utils/dist/slo'; +import type { SloApiResponse, SloInput } from '@hyperdx/common-utils/dist/slo'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { hdxServer } from './api'; @@ -32,6 +32,21 @@ export function useSlos() { }); } +export function useSaveSlo() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: ({ id, slo }: { id?: string; slo: SloInput }) => + hdxServer(id ? `slos/${id}` : 'slos', { + method: id ? 'PUT' : 'POST', + json: slo, + // Saving runs the SLO's query once to check it. + timeout: 30_000, + }).json(), + onSuccess: () => + queryClient.invalidateQueries({ queryKey: SLOS_QUERY_KEY }), + }); +} + export function useDeleteSlo() { const queryClient = useQueryClient(); return useMutation({