thresholdsChart.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import {PureComponent} from 'react';
  2. import color from 'color';
  3. import type {TooltipComponentFormatterCallbackParams} from 'echarts';
  4. import debounce from 'lodash/debounce';
  5. import flatten from 'lodash/flatten';
  6. import {extrapolatedAreaStyle} from 'sentry/components/alerts/onDemandMetricAlert';
  7. import {AreaChart} from 'sentry/components/charts/areaChart';
  8. import Graphic from 'sentry/components/charts/components/graphic';
  9. import {defaultFormatAxisLabel} from 'sentry/components/charts/components/tooltip';
  10. import {LineChartSeries} from 'sentry/components/charts/lineChart';
  11. import LineSeries from 'sentry/components/charts/series/lineSeries';
  12. import {DEFAULT_STATS_PERIOD} from 'sentry/constants';
  13. import {CHART_PALETTE} from 'sentry/constants/chartPalette';
  14. import {space} from 'sentry/styles/space';
  15. import {PageFilters} from 'sentry/types';
  16. import {ReactEchartsRef, Series} from 'sentry/types/echarts';
  17. import theme from 'sentry/utils/theme';
  18. import {
  19. ALERT_CHART_MIN_MAX_BUFFER,
  20. alertAxisFormatter,
  21. alertTooltipValueFormatter,
  22. isSessionAggregate,
  23. shouldScaleAlertChart,
  24. } from 'sentry/views/alerts/utils';
  25. import {getChangeStatus} from 'sentry/views/alerts/utils/getChangeStatus';
  26. import {
  27. AlertRuleThresholdType,
  28. AlertRuleTriggerType,
  29. MetricRule,
  30. Trigger,
  31. } from '../../types';
  32. type DefaultProps = {
  33. comparisonData: Series[];
  34. comparisonMarkLines: LineChartSeries[];
  35. data: Series[];
  36. };
  37. type Props = DefaultProps & {
  38. aggregate: string;
  39. hideThresholdLines: boolean;
  40. resolveThreshold: MetricRule['resolveThreshold'];
  41. thresholdType: MetricRule['thresholdType'];
  42. triggers: Trigger[];
  43. comparisonSeriesName?: string;
  44. isExtrapolatedData?: boolean;
  45. maxValue?: number;
  46. minValue?: number;
  47. minutesThresholdToDisplaySeconds?: number;
  48. } & Partial<PageFilters['datetime']>;
  49. type State = {
  50. height: number;
  51. width: number;
  52. yAxisMax: number | null;
  53. yAxisMin: number | null;
  54. };
  55. const CHART_GRID = {
  56. left: space(2),
  57. right: space(2),
  58. top: space(4),
  59. bottom: space(2),
  60. };
  61. // Colors to use for trigger thresholds
  62. const COLOR = {
  63. RESOLUTION_FILL: color(theme.green200).alpha(0.1).rgb().string(),
  64. CRITICAL_FILL: color(theme.red300).alpha(0.25).rgb().string(),
  65. WARNING_FILL: color(theme.yellow200).alpha(0.1).rgb().string(),
  66. };
  67. /**
  68. * This chart displays shaded regions that represent different Trigger thresholds in a
  69. * Metric Alert rule.
  70. */
  71. export default class ThresholdsChart extends PureComponent<Props, State> {
  72. static defaultProps: DefaultProps = {
  73. data: [],
  74. comparisonData: [],
  75. comparisonMarkLines: [],
  76. };
  77. state: State = {
  78. width: -1,
  79. height: -1,
  80. yAxisMax: null,
  81. yAxisMin: null,
  82. };
  83. componentDidMount() {
  84. this.handleUpdateChartAxis();
  85. }
  86. componentDidUpdate(prevProps: Props) {
  87. if (
  88. this.props.triggers !== prevProps.triggers ||
  89. this.props.data !== prevProps.data ||
  90. this.props.comparisonData !== prevProps.comparisonData ||
  91. this.props.comparisonMarkLines !== prevProps.comparisonMarkLines
  92. ) {
  93. this.handleUpdateChartAxis();
  94. }
  95. }
  96. ref: null | ReactEchartsRef = null;
  97. // If we have ref to chart and data, try to update chart axis so that
  98. // alertThreshold or resolveThreshold is visible in chart
  99. handleUpdateChartAxis = () => {
  100. const {triggers, resolveThreshold, hideThresholdLines} = this.props;
  101. const chartRef = this.ref?.getEchartsInstance?.();
  102. if (hideThresholdLines) {
  103. return;
  104. }
  105. if (chartRef) {
  106. const thresholds = [
  107. resolveThreshold || null,
  108. ...triggers.map(t => t.alertThreshold || null),
  109. ].filter(threshold => threshold !== null) as number[];
  110. this.updateChartAxis(Math.min(...thresholds), Math.max(...thresholds));
  111. }
  112. };
  113. /**
  114. * Updates the chart so that yAxis is within bounds of our max value
  115. */
  116. updateChartAxis = debounce((minThreshold: number, maxThreshold: number) => {
  117. const {minValue, maxValue, aggregate} = this.props;
  118. const shouldScale = shouldScaleAlertChart(aggregate);
  119. let yAxisMax =
  120. shouldScale && maxValue
  121. ? this.clampMaxValue(Math.ceil(maxValue * ALERT_CHART_MIN_MAX_BUFFER))
  122. : null;
  123. let yAxisMin =
  124. shouldScale && minValue ? Math.floor(minValue / ALERT_CHART_MIN_MAX_BUFFER) : 0;
  125. if (typeof maxValue === 'number' && maxThreshold > maxValue) {
  126. yAxisMax = maxThreshold;
  127. }
  128. if (typeof minValue === 'number' && minThreshold < minValue) {
  129. yAxisMin = Math.floor(minThreshold / ALERT_CHART_MIN_MAX_BUFFER);
  130. }
  131. // We need to force update after we set a new yAxis min/max because `convertToPixel`
  132. // can return a negative position (probably because yAxisMin/yAxisMax is not synced with chart yet)
  133. this.setState({yAxisMax, yAxisMin}, this.forceUpdate);
  134. }, 150);
  135. /**
  136. * Syncs component state with the chart's width/heights
  137. */
  138. updateDimensions = () => {
  139. const chartRef = this.ref?.getEchartsInstance?.();
  140. if (!chartRef || !chartRef.getWidth?.()) {
  141. return;
  142. }
  143. const width = chartRef.getWidth();
  144. const height = chartRef.getHeight();
  145. if (width !== this.state.width || height !== this.state.height) {
  146. this.setState({
  147. width,
  148. height,
  149. });
  150. }
  151. };
  152. handleRef = (ref: ReactEchartsRef): void => {
  153. // When chart initially renders, we want to update state with its width, as well as initialize starting
  154. // locations (on y axis) for the draggable lines
  155. if (ref && !this.ref) {
  156. this.ref = ref;
  157. this.updateDimensions();
  158. this.handleUpdateChartAxis();
  159. }
  160. if (!ref) {
  161. this.ref = null;
  162. }
  163. };
  164. /**
  165. * Draws the boundary lines and shaded areas for the chart.
  166. *
  167. * May need to refactor so that they are aware of other trigger thresholds.
  168. *
  169. * e.g. draw warning from threshold -> critical threshold instead of the entire height of chart
  170. */
  171. getThresholdLine = (
  172. trigger: Trigger,
  173. type: 'alertThreshold' | 'resolveThreshold',
  174. isResolution: boolean
  175. ) => {
  176. const {thresholdType, resolveThreshold, maxValue, hideThresholdLines} = this.props;
  177. const position =
  178. type === 'alertThreshold'
  179. ? this.getChartPixelForThreshold(trigger[type])
  180. : this.getChartPixelForThreshold(resolveThreshold);
  181. const isInverted = thresholdType === AlertRuleThresholdType.BELOW;
  182. const chartRef = this.ref?.getEchartsInstance?.();
  183. if (
  184. typeof position !== 'number' ||
  185. isNaN(position) ||
  186. !this.state.height ||
  187. !chartRef ||
  188. hideThresholdLines
  189. ) {
  190. return [];
  191. }
  192. const yAxisPixelPosition = chartRef.convertToPixel(
  193. {yAxisIndex: 0},
  194. `${this.state.yAxisMin}`
  195. );
  196. const yAxisPosition = typeof yAxisPixelPosition === 'number' ? yAxisPixelPosition : 0;
  197. // As the yAxis gets larger we want to start our line/area further to the right
  198. // Handle case where the graph max is 1 and includes decimals
  199. const yAxisMax =
  200. (Math.round(Math.max(maxValue ?? 1, this.state.yAxisMax ?? 1)) * 100) / 100;
  201. const yAxisSize = 15 + (yAxisMax <= 1 ? 15 : `${yAxisMax ?? ''}`.length * 8);
  202. // Shave off the right margin and yAxisSize from the width to get the actual area we want to render content in
  203. const graphAreaWidth =
  204. this.state.width - parseInt(CHART_GRID.right.slice(0, -2), 10) - yAxisSize;
  205. // Distance from the top of the chart to save for the legend
  206. const legendPadding = 20;
  207. // Shave off the left margin
  208. const graphAreaMargin = 7;
  209. const isCritical = trigger.label === AlertRuleTriggerType.CRITICAL;
  210. const LINE_STYLE = {
  211. stroke: isResolution ? theme.green300 : isCritical ? theme.red300 : theme.yellow300,
  212. lineDash: [2],
  213. };
  214. return [
  215. // This line is used as a "border" for the shaded region
  216. // and represents the threshold value.
  217. {
  218. type: 'line',
  219. // Resolution is considered "off" if it is -1
  220. invisible: position === null,
  221. draggable: false,
  222. position: [yAxisSize, position],
  223. shape: {y1: 1, y2: 1, x1: graphAreaMargin, x2: graphAreaWidth},
  224. style: LINE_STYLE,
  225. silent: true,
  226. z: 100,
  227. },
  228. // Shaded area for incident/resolutions to show user when they can expect to be alerted
  229. // (or when they will be considered as resolved)
  230. //
  231. // Resolution is considered "off" if it is -1
  232. ...(position !== null
  233. ? [
  234. {
  235. type: 'rect',
  236. draggable: false,
  237. silent: true,
  238. position:
  239. isResolution !== isInverted
  240. ? [yAxisSize + graphAreaMargin, position + 1]
  241. : [yAxisSize + graphAreaMargin, legendPadding],
  242. shape: {
  243. width: graphAreaWidth - graphAreaMargin,
  244. height:
  245. isResolution !== isInverted
  246. ? yAxisPosition - position
  247. : position - legendPadding,
  248. },
  249. style: {
  250. fill: isResolution
  251. ? COLOR.RESOLUTION_FILL
  252. : isCritical
  253. ? COLOR.CRITICAL_FILL
  254. : COLOR.WARNING_FILL,
  255. },
  256. // This needs to be below the draggable line
  257. z: 100,
  258. },
  259. ]
  260. : []),
  261. ];
  262. };
  263. getChartPixelForThreshold = (threshold: number | '' | null) => {
  264. const chartRef = this.ref?.getEchartsInstance?.();
  265. return (
  266. threshold !== '' &&
  267. chartRef &&
  268. chartRef.convertToPixel({yAxisIndex: 0}, `${threshold}`)
  269. );
  270. };
  271. clampMaxValue(value: number) {
  272. // When we apply top buffer to the crash free percentage (99.7% * 1.03), it
  273. // can cross 100%, so we clamp it
  274. if (isSessionAggregate(this.props.aggregate) && value > 100) {
  275. return 100;
  276. }
  277. return value;
  278. }
  279. render() {
  280. const {
  281. data,
  282. triggers,
  283. period,
  284. aggregate,
  285. comparisonData,
  286. comparisonSeriesName,
  287. comparisonMarkLines,
  288. minutesThresholdToDisplaySeconds,
  289. thresholdType,
  290. } = this.props;
  291. const dataWithoutRecentBucket = data?.map(({data: eventData, ...restOfData}) => {
  292. if (this.props.isExtrapolatedData) {
  293. return {
  294. ...restOfData,
  295. data: eventData.slice(0, -1),
  296. areaStyle: extrapolatedAreaStyle,
  297. };
  298. }
  299. return {
  300. ...restOfData,
  301. data: eventData.slice(0, -1),
  302. };
  303. });
  304. const comparisonDataWithoutRecentBucket = comparisonData?.map(
  305. ({data: eventData, ...restOfData}) => ({
  306. ...restOfData,
  307. data: eventData.slice(0, -1),
  308. })
  309. );
  310. const chartOptions = {
  311. tooltip: {
  312. // use the main aggregate for all series (main, min, max, avg, comparison)
  313. // to format all values similarly
  314. valueFormatter: (value: number) =>
  315. alertTooltipValueFormatter(value, aggregate, aggregate),
  316. formatAxisLabel: (
  317. value: number,
  318. isTimestamp: boolean,
  319. utc: boolean,
  320. showTimeInTooltip: boolean,
  321. addSecondsToTimeFormat: boolean,
  322. bucketSize: number | undefined,
  323. seriesParamsOrParam: TooltipComponentFormatterCallbackParams
  324. ) => {
  325. const date = defaultFormatAxisLabel(
  326. value,
  327. isTimestamp,
  328. utc,
  329. showTimeInTooltip,
  330. addSecondsToTimeFormat,
  331. bucketSize
  332. );
  333. const seriesParams = Array.isArray(seriesParamsOrParam)
  334. ? seriesParamsOrParam
  335. : [seriesParamsOrParam];
  336. const pointY = (
  337. seriesParams.length > 1 ? seriesParams[0].data[1] : undefined
  338. ) as number | undefined;
  339. const comparisonSeries =
  340. seriesParams.length > 1
  341. ? seriesParams.find(({seriesName: _sn}) => _sn === comparisonSeriesName)
  342. : undefined;
  343. const comparisonPointY = comparisonSeries?.data[1] as number | undefined;
  344. if (
  345. comparisonPointY === undefined ||
  346. pointY === undefined ||
  347. comparisonPointY === 0
  348. ) {
  349. return `<span>${date}</span>`;
  350. }
  351. const changePercentage = ((pointY - comparisonPointY) * 100) / comparisonPointY;
  352. const changeStatus = getChangeStatus(changePercentage, thresholdType, triggers);
  353. const changeStatusColor =
  354. changeStatus === AlertRuleTriggerType.CRITICAL
  355. ? theme.red300
  356. : changeStatus === AlertRuleTriggerType.WARNING
  357. ? theme.yellow300
  358. : theme.green300;
  359. return `<span>${date}<span style="color:${changeStatusColor};margin-left:10px;">
  360. ${Math.sign(changePercentage) === 1 ? '+' : '-'}${Math.abs(
  361. changePercentage
  362. ).toFixed(2)}%</span></span>`;
  363. },
  364. },
  365. yAxis: {
  366. min: this.state.yAxisMin ?? undefined,
  367. max: this.state.yAxisMax ?? undefined,
  368. axisLabel: {
  369. formatter: (value: number) =>
  370. alertAxisFormatter(value, data[0].seriesName, aggregate),
  371. },
  372. },
  373. };
  374. return (
  375. <AreaChart
  376. isGroupedByDate
  377. showTimeInTooltip
  378. minutesThresholdToDisplaySeconds={minutesThresholdToDisplaySeconds}
  379. period={DEFAULT_STATS_PERIOD || period}
  380. forwardedRef={this.handleRef}
  381. grid={CHART_GRID}
  382. {...chartOptions}
  383. graphic={Graphic({
  384. elements: flatten(
  385. triggers.map((trigger: Trigger) => [
  386. ...this.getThresholdLine(trigger, 'alertThreshold', false),
  387. ...this.getThresholdLine(trigger, 'resolveThreshold', true),
  388. ])
  389. ),
  390. })}
  391. colors={CHART_PALETTE[0]}
  392. series={[...dataWithoutRecentBucket, ...comparisonMarkLines]}
  393. additionalSeries={comparisonDataWithoutRecentBucket.map(
  394. ({data: _data, ...otherSeriesProps}) =>
  395. LineSeries({
  396. name: comparisonSeriesName,
  397. data: _data.map(({name, value}) => [name, value]),
  398. lineStyle: {color: theme.gray200, type: 'dashed', width: 1},
  399. itemStyle: {color: theme.gray200},
  400. animation: false,
  401. animationThreshold: 1,
  402. animationDuration: 0,
  403. ...otherSeriesProps,
  404. })
  405. )}
  406. onFinished={() => {
  407. // We want to do this whenever the chart finishes re-rendering so that we can update the dimensions of
  408. // any graphics related to the triggers (e.g. the threshold areas + boundaries)
  409. this.updateDimensions();
  410. }}
  411. />
  412. );
  413. }
  414. }