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
196 changes: 196 additions & 0 deletions packages/app/src/components/Slos/SloChart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import { useMemo } from 'react';
import { Label, ReferenceArea, ReferenceLine } from 'recharts';
import type { SloHistoryPoint } from '@hyperdx/common-utils/dist/core/sloStats';
import { DisplayType, NumberFormat } from '@hyperdx/common-utils/dist/types';
import { Center, Text } from '@mantine/core';

import type { LineData } from '@/ChartUtils';
import { ChartCard } from '@/components/charts/ChartCard';
import ChartContainer from '@/components/charts/ChartContainer';
import ChartEmptyState from '@/components/charts/ChartEmptyState';
import { MemoChart } from '@/HDXMultiSeriesTimeChart';

export const TS_KEY = 'ts';

export const PERCENT_FORMAT: NumberFormat = { output: 'percent', mantissa: 2 };
export const RATE_FORMAT: NumberFormat = {
output: 'number',
mantissa: 2,
unit: 'x',
};

// Translucent enough that the series and threshold stay readable on top.
const BAD_FILL_OPACITY = 0.12;

// A dashed line rather than a shaded area: shading everything below a 99.9%
// target would cover the whole plot and pin the axis at zero.
export function thresholdLine(value: number, label: string, color: string) {
return (
<ReferenceLine
y={value}
stroke={color}
strokeDasharray="4 4"
ifOverflow="extendDomain"
>
<Label
value={label}
position="insideTopLeft"
fill={color}
fontSize={11}
/>
</ReferenceLine>
);
}

/**
* Runs of consecutive buckets where `isBad` holds, as [start, end] in seconds
* on the chart's time axis. Each bucket covers its start plus one bucket.
*/
export function badPeriods(
points: SloHistoryPoint[],
bucketSeconds: number,
isBad: (point: SloHistoryPoint) => boolean,
): [number, number][] {
const periods: [number, number][] = [];
for (const point of points) {
if (!isBad(point)) continue;
const start = point.ts / 1000;
const last = periods[periods.length - 1];
if (last != null && start <= last[1]) {
last[1] = start + bucketSeconds;
} else {
periods.push([start, start + bucketSeconds]);
}
}
return periods;
}

/** Shaded columns for the periods a series spent in a bad state. */
export function badPeriodAreas(periods: [number, number][], color: string) {
return periods.map(([x1, x2]) => (
<ReferenceArea
key={`bad-${x1}`}
x1={x1}
x2={x2}
fill={color}
fillOpacity={BAD_FILL_OPACITY}
strokeOpacity={0}
ifOverflow="hidden"
/>
));
}

/**
* Shades everything below zero, where an error budget is overspent, once the
* budget gets there. The lower edge reaches past the lowest value and is
* clipped to the plot, so the shading runs to the bottom of the axis.
*/
export function overspentZone(points: SloHistoryPoint[], color: string) {
const lowest = Math.min(...points.map(p => p.budgetRemaining ?? 0), 0);
if (lowest >= 0) return null;
return (
<ReferenceArea
y1={lowest * 10}
y2={0}
fill={color}
fillOpacity={BAD_FILL_OPACITY}
strokeOpacity={0}
ifOverflow="hidden"
>
<Label
value="Overspent"
position="insideTopLeft"
fill={color}
fontSize={11}
/>
</ReferenceArea>
);
}

export function seriesLine(key: string, name: string, color: string): LineData {
return {
dataKey: key,
currentPeriodKey: key,
previousPeriodKey: `${key}__previous`,
displayName: name,
valueColumnName: key,
groupValues: [],
color,
};
}

/**
* One SLO history chart. Clicking a bucket reports its start, for the
* bad events of that bucket.
*/
export function SloChart({
title,
rows,
lines,
dateRange,
granularity,
numberFormat,
referenceLines,
referenceLineValues,
fitYAxisToData,
isLoading,
error,
onBucketClick,
displayType = DisplayType.Line,
}: {
title: string;
rows: Record<string, number | null>[];
lines: LineData[];
dateRange: [Date, Date];
granularity: string;
numberFormat: NumberFormat;
referenceLines?: React.ReactNode;
referenceLineValues?: number[];
fitYAxisToData?: boolean;
isLoading: boolean;
error?: Error | null;
onBucketClick: (bucketStartMs: number) => void;
displayType?: DisplayType;
}) {
const formats = useMemo(
() => new Map(lines.map(line => [line.dataKey, numberFormat])),
[lines, numberFormat],
);
const chart = error ? (
<Center h="100%" px="md">
<Text size="xs" c="var(--color-text-danger)" ta="center">
Could not load the history: {error.message}
</Text>
</Center>
) : !isLoading && rows.length === 0 ? (
<ChartEmptyState />
) : (
<MemoChart
graphResults={rows}
lineData={lines}
dateRange={dateRange}
granularity={granularity}
timestampKey={TS_KEY}
isLoading={isLoading}
// A click opens the bucket's bad events instead of pinning a tooltip.
isClickActive={undefined}
setIsClickActive={payload => {
if (payload) onBucketClick(Number(payload.activeLabel) * 1000);
}}
tooltipNumberFormatsByKey={formats}
axisNumberFormat={numberFormat}
referenceLines={referenceLines}
referenceLineValues={referenceLineValues}
showLegend={false}
fitYAxisToData={fitYAxisToData}
compactXAxisLabels
displayType={displayType}
dateRangeEndInclusive={false}
/>
);
return (
<ChartCard style={{ height: 260 }}>
<ChartContainer title={title}>{chart}</ChartContainer>
</ChartCard>
);
}
183 changes: 183 additions & 0 deletions packages/app/src/components/Slos/SloCharts.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import { useMemo } from 'react';
import { getSloBurnRule } from '@hyperdx/common-utils/dist/core/slo';
import { computeSloHistory } from '@hyperdx/common-utils/dist/core/sloStats';
import { convertGranularityToSeconds } from '@hyperdx/common-utils/dist/core/utils';
import {
getSloBurnWindowMs,
type SloApiResponse,
} from '@hyperdx/common-utils/dist/slo';
import { DisplayType, type TSource } from '@hyperdx/common-utils/dist/types';
import { SimpleGrid, Stack, Text } from '@mantine/core';

import { useFormatTime } from '@/useFormatTime';
import {
getChartColorError,
getChartColorInfo,
getChartColorWarning,
} from '@/utils';

import {
badPeriodAreas,
badPeriods,
overspentZone,
PERCENT_FORMAT,
RATE_FORMAT,
seriesLine,
SloChart,
thresholdLine,
TS_KEY,
} from './SloChart';
import { describeBurnWindow, formatSloWindow } from './sloUtils';
import { useSloHistory } from './useSloLiveStatus';

/** "hour" or "30 minutes", for "per ..." titles. */
const describeBucket = (granularity: string) =>
granularity === '1 hour' ? 'hour' : granularity.replace('minute', 'minutes');

/**
* SLI, budget burndown and burn rate over the SLO window, from bucketed
* counts queried in the browser like any chart. The window ends at `now`,
* as the numbers above the charts do, so both describe the same moment.
* Clicking a bucket opens its bad events.
*/
export function SloCharts({
slo,
source,
now,
onBucketSelect,
}: {
slo: SloApiResponse;
source: TSource;
now: Date;
onBucketSelect: (start: Date, end: Date) => void;
}) {
const formatTime = useFormatTime();
const { config, granularity, buckets, isLoading, error } = useSloHistory(
slo,
source,
now,
);
const bucketMs = convertGranularityToSeconds(granularity) * 1000;
// The burn chart follows the rule's 1h condition, the one that pages first.
const burn = getSloBurnRule(slo.window)[0];
const points = useMemo(
() =>
computeSloHistory(buckets, {
target: slo.target,
bucketMs,
burnWindowMs: getSloBurnWindowMs(burn.window),
}),
[buckets, slo.target, bucketMs, burn.window],
);
// Start the axis where data starts: a source younger than the SLO window
// would otherwise squeeze every point against the right edge.
const dateRange = useMemo<[Date, Date]>(() => {
const [start, end] = config.dateRange;
const firstBucket = buckets[0]?.ts ?? start.getTime();
return [new Date(Math.max(start.getTime(), firstBucket)), end];
}, [config, buckets]);

const rows = useMemo(
() =>
points.map(p => ({
[TS_KEY]: p.ts / 1000,
sli: p.sli,
budget: p.budgetRemaining,
// Two series, so buckets at or over the threshold stand out in red.
burn:
p.burnRate != null && p.burnRate < burn.threshold ? p.burnRate : null,
burn_high:
p.burnRate != null && p.burnRate >= burn.threshold
? p.burnRate
: null,
})),
[points, burn.threshold],
);
// Chart colors come from CSS variables, so series are built on mount to
// follow the theme, and kept stable for the memoized charts.
const lines = useMemo(
() => ({
sli: [seriesLine('sli', 'SLI', getChartColorInfo())],
budget: [seriesLine('budget', 'Budget left', getChartColorWarning())],
burn: [
seriesLine('burn', 'Burn rate', getChartColorInfo()),
seriesLine(
'burn_high',
'Burn rate at or over the threshold',
getChartColorError(),
),
],
}),
[],
);
const belowTarget = badPeriods(
points,
bucketMs / 1000,
p => p.sli != null && p.sli * 100 < slo.target,
);

const common = {
dateRange,
granularity,
isLoading,
error,
onBucketClick: (start: number) =>
onBucketSelect(new Date(start), new Date(start + bucketMs)),
};
const bucket = describeBucket(granularity);

return (
<Stack gap="xs" data-testid="slo-charts">
<Text size="xs" c="dimmed">
The last {formatSloWindow(slo.window)}
{buckets.length > 0 && dateRange[0] > config.dateRange[0]
? `, with data from ${formatTime(dateRange[0], { format: 'short' })}`
: ''}
. Click a bucket to see its bad events.
</Text>
<SimpleGrid cols={{ base: 1, lg: 3 }} spacing="md">
<SloChart
{...common}
title={`SLI per ${bucket} (target ${slo.target}%)`}
rows={rows}
lines={lines.sli}
numberFormat={PERCENT_FORMAT}
referenceLines={
<>
{badPeriodAreas(belowTarget, getChartColorError())}
{thresholdLine(
slo.target / 100,
`Target ${slo.target}%`,
getChartColorWarning(),
)}
</>
}
referenceLineValues={[slo.target / 100]}
fitYAxisToData
/>
<SloChart
{...common}
title={`Error budget left (${formatSloWindow(slo.window)})`}
rows={rows}
lines={lines.budget}
numberFormat={PERCENT_FORMAT}
referenceLines={overspentZone(points, getChartColorError())}
/>
<SloChart
{...common}
title={`Burn rate over ${describeBurnWindow(burn.window)}, per ${bucket}`}
rows={rows}
lines={lines.burn}
numberFormat={RATE_FORMAT}
referenceLines={thresholdLine(
burn.threshold,
`Threshold ${burn.threshold}x`,
getChartColorError(),
)}
referenceLineValues={[burn.threshold]}
displayType={DisplayType.StackedBar}
/>
</SimpleGrid>
</Stack>
);
}
Loading
Loading