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
43 changes: 43 additions & 0 deletions static/app/utils/timeSeries/mergeTimeRanges.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {mergeTimeRanges} from './mergeTimeRanges';

describe('mergeTimeRanges', () => {
it('merges ranges that overlap or touch, in any order', () => {
expect(
mergeTimeRanges([
{start: 50, end: 60},
{start: 10, end: 20},
{start: 20, end: 30},
{start: 25, end: 28},
])
).toEqual([
{start: 10, end: 30},
{start: 50, end: 60},
]);
});

it('keeps ranges with a gap between them apart', () => {
expect(
mergeTimeRanges([
{start: 0, end: 10},
{start: 11, end: 20},
])
).toEqual([
{start: 0, end: 10},
{start: 11, end: 20},
]);
});

it('does not change the ranges it was given', () => {
const ranges = [
{start: 0, end: 10},
{start: 5, end: 20},
];

mergeTimeRanges(ranges);

expect(ranges).toEqual([
{start: 0, end: 10},
{start: 5, end: 20},
]);
});
});
22 changes: 22 additions & 0 deletions static/app/utils/timeSeries/mergeTimeRanges.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export interface TimeRange {
end: number;
start: number;
}

/**
* Sorts ranges by start and merges any that overlap or touch.
*/
export function mergeTimeRanges(ranges: readonly TimeRange[]): TimeRange[] {
const merged: TimeRange[] = [];

for (const range of ranges.toSorted((a, b) => a.start - b.start)) {
const previous = merged.at(-1);
if (previous && range.start <= previous.end) {
previous.end = Math.max(previous.end, range.end);
} else {
merged.push({...range});
}
}

return merged;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {TimeSeriesFixture} from 'sentry-fixture/timeSeries';

import {createLineSeries} from 'sentry/components/charts/series/lineSeries';
import type {TimeSeriesItem} from 'sentry/views/dashboards/widgets/common/types';

import {ContinuousTimeSeries} from './continuousTimeSeries';
import type {Plottable} from './plottable';
Expand Down Expand Up @@ -201,6 +202,60 @@ describe('ContinuousTimeSeries', () => {
});
});

describe('lowConfidenceRanges', () => {
const interval = 1_000;

function timeSeriesWith(items: Array<Partial<TimeSeriesItem>>) {
return new Dots(
TimeSeriesFixture({
meta: {valueType: 'number', valueUnit: null, interval},
values: items.map((item, index) => ({
timestamp: index * interval,
value: 1,
...item,
})),
})
);
}

it('covers half an interval either side of each low confidence bucket', () => {
const plottable = timeSeriesWith([
{},
{confidence: 'low'},
{},
{confidence: 'low'},
]);

expect(plottable.lowConfidenceRanges).toEqual([
{start: 500, end: 1_500},
{start: 2_500, end: 3_500},
]);
});

it('merges consecutive low confidence buckets', () => {
const plottable = timeSeriesWith([
{},
{confidence: 'low'},
{confidence: 'low'},
{confidence: 'low'},
{},
]);

expect(plottable.lowConfidenceRanges).toEqual([{start: 500, end: 3_500}]);
});

it('ignores high, null, empty, and incomplete buckets', () => {
const plottable = timeSeriesWith([
{confidence: 'high'},
{confidence: null},
{confidence: 'low', value: null},
{confidence: 'low', incomplete: true},
]);

expect(plottable.lowConfidenceRanges).toEqual([]);
});
});

describe('name', () => {
it('name is properly formatted', () => {
const timeSeries = TimeSeriesFixture({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type {SeriesOption} from 'echarts';

import {defined} from 'sentry/utils/defined';
import {mergeTimeRanges, type TimeRange} from 'sentry/utils/timeSeries/mergeTimeRanges';
import {scaleTimeSeriesData} from 'sentry/utils/timeSeries/scaleTimeSeriesData';
import type {TimeSeriesSegmentField} from 'sentry/utils/timeSeries/segmentTimeSeriesByDisplayStyle';
import {timeSeriesItemToEChartsDataPoint} from 'sentry/utils/timeSeries/timeSeriesItemToEChartsDataPoint';
Expand Down Expand Up @@ -110,6 +111,27 @@ export abstract class ContinuousTimeSeries<
return values.some(isExtrapolated) ? 'high' : 'full';
}

/**
* Stretches of time covered by low confidence buckets. A bucket spans half an
* interval either side of its timestamp, the slot a bar fills, so consecutive
* buckets merge into one range. Incomplete buckets don't count, as in `confidence`
*/
get lowConfidenceRanges(): TimeRange[] {
const {interval} = this.timeSeries.meta;

return mergeTimeRanges(
this.timeSeries.values
.filter(
datum =>
datum.value !== null && !datum.incomplete && isLowConfidenceDataPoint(datum)
)
.map(({timestamp}) => ({
start: timestamp - interval / 2,
end: timestamp + interval / 2,
}))
);
}

get needsColor(): boolean {
return !this.config?.color;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type {CustomSeriesRenderItemAPI, CustomSeriesRenderItemParams} from 'echarts';

import {HatchAreas} from './hatchAreas';

describe('HatchAreas', () => {
const config = {name: 'areas', color: '#f0f0f2', dataType: 'number' as const};

it('clips areas to the bounds it is plotted with', () => {
const areas = new HatchAreas(
[
{start: -10, end: 10},
{start: 40, end: 120},
{start: 150, end: 160},
],
config
);

const [series] = areas.toSeries({bounds: {start: 0, end: 100}});

expect(series?.data).toEqual([
[0, 10],
[40, 100],
]);
});

it('is empty without ranges', () => {
expect(new HatchAreas([], config).isEmpty).toBe(true);
});

it('draws a hatched area across the full plot height behind the data', () => {
const [series] = new HatchAreas([{start: 1_000, end: 3_000}], config).toSeries();

expect(series).toEqual(
expect.objectContaining({
data: [[1_000, 3_000]],
encode: {x: [0, 1]},
silent: true,
tooltip: {show: false},
z: 1,
})
);

const values = [1_000, 3_000];
const element = series!.renderItem!(
{
dataIndex: 0,
coordSys: {type: 'cartesian2d', x: 0, y: 10, width: 500, height: 200},
} as unknown as CustomSeriesRenderItemParams,
{
value: (dimension: number) => values[dimension],
coord: ([time]: number[]) => [(time ?? 0) / 10, 0],
} as unknown as CustomSeriesRenderItemAPI
);

expect(element).toEqual(
expect.objectContaining({
type: 'rect',
shape: {x: 100, y: 10, width: 200, height: 200},
style: expect.objectContaining({
decal: expect.objectContaining({color: '#f0f0f2'}),
}),
})
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import type {CustomSeriesOption, CustomSeriesRenderItem} from 'echarts';

import type {CartesianCoordSys} from 'sentry/components/charts/bands/bandShapes';
import {defined} from 'sentry/utils/defined';
import type {TimeRange} from 'sentry/utils/timeSeries/mergeTimeRanges';

import type {
Plottable,
PlottableConfidence,
PlottableTimeSeriesValueType,
} from './plottable';

type HatchAreasConfig = {
/**
* Hatch color. Areas are hatched over a transparent fill, so grid lines show
* through the gaps between stripes
*/
color: string;
/**
* Type of the Y axis to draw against. The areas don't read Y values, but the
* chart puts every plottable on an axis by its type, so this should match an
* axis the chart already has
*/
dataType: PlottableTimeSeriesValueType;
/**
* Identifies the plottable. It becomes the ECharts series ID and name, so it
* must be unique among the chart's plottables
*/
name: string;
};

type HatchAreasPlottingOptions = {
/**
* Areas are clipped to these bounds. The X axis grows to fit any series that
* runs past the plotted data, so pass the data's first and last timestamps
*/
bounds?: TimeRange;
};

/**
* Hatched areas that span the full height of the plot over stretches of time, drawn
* behind the data. Unlike time series plottables, it has no data of its own,
* so it never takes up a Y axis, a legend item, or a tooltip row.
*/
export class HatchAreas implements Plottable {
ranges: readonly TimeRange[];
config: Readonly<HatchAreasConfig>;

// Required by `Plottable`. The areas have no data, so none of it is extrapolated
confidence: PlottableConfidence = 'full';
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
dataUnit = null;
needsColor = false;

/**
* @param ranges Sorted ranges that don't overlap, such as the output of `mergeTimeRanges`
*/
constructor(ranges: readonly TimeRange[], config: HatchAreasConfig) {
this.ranges = ranges;
this.config = config;
}

get name(): string {
return this.config.name;
}

get dataType(): PlottableTimeSeriesValueType {
return this.config.dataType;
}

get label(): string {
return this.config.name;
}

get isEmpty(): boolean {
return this.ranges.length === 0;
}

get start(): number | null {
return this.ranges.at(0)?.start ?? null;
}

get end(): number | null {
return this.ranges.at(-1)?.end ?? null;
}

toSeries({bounds}: HatchAreasPlottingOptions = {}): CustomSeriesOption[] {
const ranges = bounds
? this.ranges
.map(({start, end}) => ({
start: Math.max(start, bounds.start),
end: Math.min(end, bounds.end),
}))
.filter(({start, end}) => start < end)
: this.ranges;

return [
{
id: this.name,
name: this.name,
type: 'custom',
data: ranges.map(({start, end}) => [start, end]),
// Mapping only `x` keeps the timestamps out of the Y axis extent
encode: {x: [0, 1]},
renderItem: this.renderItem,
// Behind line, area, and bar series, which default to 2
z: 1,
clip: true,
silent: true,
animation: false,
legendHoverLink: false,
tooltip: {show: false},
},
];
}

// A custom series rather than a `markArea`, because only custom series render
// a `decal`, which ECharts redraws at the device pixel ratio so the stripes
// stay crisp
private renderItem: CustomSeriesRenderItem = (params, api) => {
const [left] = api.coord([api.value(0), 0]);
const [right] = api.coord([api.value(1), 0]);
if (!defined(left) || !defined(right)) {
return null;
}

const {y, height} = params.coordSys as CartesianCoordSys;

return {
type: 'rect',
silent: true,
shape: {x: left, y, width: right - left, height},
style: {
// A decal only draws over a fill
fill: 'transparent',
decal: {
symbol: 'rect',
symbolSize: 1,
dashArrayX: [1, 0],
dashArrayY: [2, 2],
rotation: -Math.PI / 4,
color: this.config.color,
},
},
};
};
}
Loading
Loading