diff --git a/packages/app/src/components/Slos/SloEditorPage.tsx b/packages/app/src/components/Slos/SloEditorPage.tsx index 0bb222944..f64c83898 100644 --- a/packages/app/src/components/Slos/SloEditorPage.tsx +++ b/packages/app/src/components/Slos/SloEditorPage.tsx @@ -1,9 +1,14 @@ -import { useEffect, useRef } from 'react'; +import { useEffect, useRef, useState } from 'react'; 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 { + type FieldPath, + useForm, + useFormState, + useWatch, +} from 'react-hook-form'; import { Anchor, Box, @@ -32,13 +37,25 @@ import { SloObjectiveFields, } from './SloDefinitionFields'; import { + buildSloPreviewRequest, DEFAULT_SLO_FORM_VALUES, + getSloPreviewKey, sloFormResolver, type SloFormValues, + type SloPreviewRequest, sloToFormValues, toSloInput, } from './sloForm'; import { SloFormSection } from './SloFormLayout'; +import { SloPreviewPanel } from './SloPreviewPanel'; + +/** The fields a preview needs, validated before it runs. */ +const PREVIEW_FIELDS: FieldPath[] = [ + 'source', + 'indicator', + 'target', + 'window', +]; function SloEditorPage() { const enabled = useSlosEnabledGuard(); @@ -48,13 +65,16 @@ function SloEditorPage() { const { data: existing } = useSlo(editId); const title = usePageTitle(editId ? 'Edit SLO' : 'New SLO'); - const { control, handleSubmit, reset, setValue, getValues } = + const { control, handleSubmit, reset, setValue, getValues, trigger } = useForm({ defaultValues: DEFAULT_SLO_FORM_VALUES, resolver: sloFormResolver, }); const { errors } = useFormState({ control, name: 'name' }); - const sourceId = useWatch({ control, name: 'source' }); + const [sourceId, indicator, target, sloWindow] = useWatch({ + control, + name: ['source', 'indicator', 'target', 'window'], + }); const { data: source } = useSource({ id: sourceId || undefined }); // Load the SLO being edited, once. @@ -68,6 +88,18 @@ function SloEditorPage() { initializedRef.current = true; }, [router.isReady, editId, existing, reset]); + const [preview, setPreview] = useState(null); + const runPreview = async () => { + if (!source || !(await trigger(PREVIEW_FIELDS))) return; + setPreview(buildSloPreviewRequest(getValues(), source, Date.now()) ?? null); + }; + const isPreviewStale = + preview != null && + getSloPreviewKey( + { source: sourceId, indicator, window: sloWindow }, + source, + ) !== preview.key; + const save = useSaveSlo(); const onSave = handleSubmit(async values => { try { @@ -174,6 +206,14 @@ function SloEditorPage() { + + + diff --git a/packages/app/src/components/Slos/SloPreviewPanel.tsx b/packages/app/src/components/Slos/SloPreviewPanel.tsx new file mode 100644 index 000000000..bb7236175 --- /dev/null +++ b/packages/app/src/components/Slos/SloPreviewPanel.tsx @@ -0,0 +1,193 @@ +import { + parseSloCountsRow, + parseSloTotalRow, +} from '@hyperdx/common-utils/dist/core/slo'; +import { computeSloStats } from '@hyperdx/common-utils/dist/core/sloStats'; +import { + Accordion, + Alert, + Button, + Group, + Paper, + SimpleGrid, + Skeleton, + Stack, + Text, +} from '@mantine/core'; +import { IconPlayerPlay } from '@tabler/icons-react'; + +import ChartSQLPreview from '@/components/ChartSQLPreview'; +import { useQueriedChartConfig } from '@/hooks/useChartConfig'; + +import type { SloPreviewRequest } from './sloForm'; +import { + budgetColorVar, + formatBudget, + formatCount, + formatSli, +} from './sloUtils'; + +const PREVIEW_QUERY_OPTIONS = { + queryKeyPrefix: 'slo-preview', + refetchOnWindowFocus: false, + retry: false, +}; + +function PreviewStat({ + label, + value, + color, + testId, +}: { + label: string; + value: string; + color?: string; + testId?: string; +}) { + return ( +
+ + {label} + + + {value} + +
+ ); +} + +/** The preview's queries run from the browser, like any chart. */ +function SloPreviewResults({ + request, + target, +}: { + request: SloPreviewRequest; + target: number; +}) { + const counts = useQueriedChartConfig(request.counts, PREVIEW_QUERY_OPTIONS); + const total = useQueriedChartConfig(request.total, PREVIEW_QUERY_OPTIONS); + const error = counts.error; + + if (error) { + return ( + + {error.message} + + ); + } + if (!counts.data) return ; + + // The preview covers the window; burn rates show once the SLO is saved. + const stats = computeSloStats( + parseSloCountsRow(counts.data.data), + [], + target, + ); + const excluded = total.data + ? Math.max(0, parseSloTotalRow(total.data.data) - stats.eligible) + : undefined; + return ( + + + + + + + + + + Excluded events are in the source but outside the eligible events. + + + + + Generated SQL + + + + + + All rows, for the excluded count + + + + + + + + ); +} + +/** Dry-run counts for the definition being edited, before it is saved. */ +export function SloPreviewPanel({ + request, + isStale, + target, + onRun, +}: { + request: SloPreviewRequest | null; + /** The definition changed since the preview ran. */ + isStale: boolean; + target: number; + onRun: () => void; +}) { + return ( + + + Preview + + + {request == null ? ( + + See good, bad and excluded events over the SLO window before you save. + + ) : ( + + {isStale && ( + + The definition changed since this preview. Run it again to update + the counts. + + )} +
+ +
+
+ )} +
+ ); +} diff --git a/packages/app/src/components/Slos/__tests__/sloForm.test.ts b/packages/app/src/components/Slos/__tests__/sloForm.test.ts index cfa29c794..ff19d461e 100644 --- a/packages/app/src/components/Slos/__tests__/sloForm.test.ts +++ b/packages/app/src/components/Slos/__tests__/sloForm.test.ts @@ -3,7 +3,9 @@ import type { SloApiResponse } from '@hyperdx/common-utils/dist/slo'; import { SourceKind, type TSource } from '@hyperdx/common-utils/dist/types'; import { + buildSloPreviewRequest, DEFAULT_SLO_FORM_VALUES, + getSloPreviewKey, sloFormResolver, type SloFormValues, sloToFormValues, @@ -167,4 +169,37 @@ describe('SLO form', () => { }), ); }); + + it('marks a preview stale when its counts would change, not the target', () => { + const key = getSloPreviewKey(valid, traceSource); + const retargeted: SloFormValues = { ...valid, target: 95 }; + expect(getSloPreviewKey(retargeted, traceSource)).toBe(key); + expect(getSloPreviewKey({ ...valid, window: '7d' }, traceSource)).not.toBe( + key, + ); + // The latency settings play no part in an availability SLO. + expect(getSloPreviewKey(latency('Duration'), traceSource)).not.toBe(key); + expect( + getSloPreviewKey( + { + ...valid, + indicator: { + ...valid.indicator, + latency: { ...valid.indicator.latency, thresholdMs: 1 }, + }, + }, + traceSource, + ), + ).toBe(key); + }); + + it('builds the preview queries over the window ending now', () => { + const now = Date.parse('2026-11-08T00:00:00Z'); + const request = buildSloPreviewRequest(valid, traceSource, now); + expect(request?.counts.dateRange).toEqual([ + new Date('2026-10-09T00:00:00Z'), + new Date('2026-11-08T00:00:00Z'), + ]); + expect(request?.total.dateRange).toEqual(request?.counts.dateRange); + }); }); diff --git a/packages/app/src/components/Slos/sloForm.ts b/packages/app/src/components/Slos/sloForm.ts index 504d8f356..45bcffec7 100644 --- a/packages/app/src/components/Slos/sloForm.ts +++ b/packages/app/src/components/Slos/sloForm.ts @@ -1,13 +1,22 @@ import type { Resolver } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; +import { + buildSloCountsChartConfig, + buildSloSourceTotalChartConfig, + getSloWindowRange, +} from '@hyperdx/common-utils/dist/core/slo'; import { getSloDefaultDuration } from '@hyperdx/common-utils/dist/core/sloLatency'; import { type SloApiResponse, + SloIndicatorSchema, type SloInput, SloInputSchema, type SloLatency, } from '@hyperdx/common-utils/dist/slo'; -import type { TSource } from '@hyperdx/common-utils/dist/types'; +import type { + BuilderChartConfigWithDateRange, + TSource, +} from '@hyperdx/common-utils/dist/types'; /** * The builder edits the API input directly, so schema errors land on the @@ -114,6 +123,47 @@ export function toSloInput(values: SloFormValues, source?: TSource): SloInput { }; } +export type SloPreviewRequest = { + /** What the counts depend on; another key means the preview is stale. */ + key: string; + counts: BuilderChartConfigWithDateRange; + total: BuilderChartConfigWithDateRange; +}; + +/** What a preview's counts depend on. The target only changes the math. */ +export function getSloPreviewKey( + values: Pick, + source?: TSource, +): string { + return JSON.stringify([ + values.source, + values.window, + toSloIndicator(values.indicator, source), + ]); +} + +/** The preview's queries, over the SLO window that ends at `nowMs`. */ +export function buildSloPreviewRequest( + values: SloFormValues, + source: TSource, + nowMs: number, +): SloPreviewRequest | undefined { + const indicator = SloIndicatorSchema.safeParse( + toSloIndicator(values.indicator, source), + ); + if (!indicator.success) return undefined; + const dateRange = getSloWindowRange(values.window, new Date(nowMs)); + return { + key: getSloPreviewKey(values, source), + counts: buildSloCountsChartConfig({ + slo: { indicator: indicator.data }, + source, + dateRange, + }), + total: buildSloSourceTotalChartConfig({ source, dateRange }), + }; +} + const sloInputResolver = zodResolver(SloInputSchema); /** Validates what will be saved, not the fields the template leaves out. */ diff --git a/packages/app/src/components/Slos/sloUtils.ts b/packages/app/src/components/Slos/sloUtils.ts index dab360f87..985719a07 100644 --- a/packages/app/src/components/Slos/sloUtils.ts +++ b/packages/app/src/components/Slos/sloUtils.ts @@ -84,6 +84,14 @@ export function formatBurnRate(burnRate: number | null | undefined): string { return `${burnRate.toFixed(burnRate >= 10 ? 1 : 2)}x`; } +export function formatCount(n: number | null | undefined): string { + if (n == null) return '-'; + return Intl.NumberFormat('en-US', { + notation: Math.abs(n) >= 100_000 ? 'compact' : 'standard', + maximumFractionDigits: Math.abs(n) >= 100_000 ? 1 : 0, + }).format(n); +} + export function formatSloWindow(window: SloWindow): string { return window === '7d' ? '7 days' : '30 days'; }