metricChartOption.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. import color from 'color';
  2. import type {YAXisComponentOption} from 'echarts';
  3. import moment from 'moment';
  4. import momentTimezone from 'moment-timezone';
  5. import type {AreaChartProps, AreaChartSeries} from 'sentry/components/charts/areaChart';
  6. import MarkArea from 'sentry/components/charts/components/markArea';
  7. import MarkLine from 'sentry/components/charts/components/markLine';
  8. import {CHART_PALETTE} from 'sentry/constants/chartPalette';
  9. import {t} from 'sentry/locale';
  10. import ConfigStore from 'sentry/stores/configStore';
  11. import {space} from 'sentry/styles/space';
  12. import type {Series} from 'sentry/types/echarts';
  13. import type {SessionApiResponse} from 'sentry/types/organization';
  14. import {formatMRIField} from 'sentry/utils/metrics/mri';
  15. import {getCrashFreeRateSeries} from 'sentry/utils/sessions';
  16. import {lightTheme as theme} from 'sentry/utils/theme';
  17. import type {MetricRule, Trigger} from 'sentry/views/alerts/rules/metric/types';
  18. import {AlertRuleTriggerType, Dataset} from 'sentry/views/alerts/rules/metric/types';
  19. import type {Incident} from 'sentry/views/alerts/types';
  20. import {IncidentActivityType, IncidentStatus} from 'sentry/views/alerts/types';
  21. import {
  22. ALERT_CHART_MIN_MAX_BUFFER,
  23. alertAxisFormatter,
  24. alertTooltipValueFormatter,
  25. SESSION_AGGREGATE_TO_FIELD,
  26. shouldScaleAlertChart,
  27. } from 'sentry/views/alerts/utils';
  28. import {AlertWizardAlertNames} from 'sentry/views/alerts/wizard/options';
  29. import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
  30. import {isCrashFreeAlert} from '../utils/isCrashFreeAlert';
  31. function formatTooltipDate(date: moment.MomentInput, format: string): string {
  32. const {
  33. options: {timezone},
  34. } = ConfigStore.get('user');
  35. return momentTimezone.tz(date, timezone).format(format);
  36. }
  37. function createStatusAreaSeries(
  38. lineColor: string,
  39. startTime: number,
  40. endTime: number,
  41. yPosition: number
  42. ): AreaChartSeries {
  43. return {
  44. seriesName: '',
  45. type: 'line',
  46. markLine: MarkLine({
  47. silent: true,
  48. lineStyle: {color: lineColor, type: 'solid', width: 4},
  49. data: [[{coord: [startTime, yPosition]}, {coord: [endTime, yPosition]}]],
  50. }),
  51. data: [],
  52. };
  53. }
  54. function createThresholdSeries(lineColor: string, threshold: number): AreaChartSeries {
  55. return {
  56. seriesName: 'Threshold Line',
  57. type: 'line',
  58. markLine: MarkLine({
  59. silent: true,
  60. lineStyle: {color: lineColor, type: 'dashed', width: 1},
  61. data: [{yAxis: threshold}],
  62. label: {
  63. show: false,
  64. },
  65. }),
  66. data: [],
  67. };
  68. }
  69. function createIncidentSeries(
  70. incident: Incident,
  71. lineColor: string,
  72. incidentTimestamp: number,
  73. dataPoint?: AreaChartSeries['data'][0],
  74. seriesName?: string,
  75. aggregate?: string,
  76. handleIncidentClick?: (incident: Incident) => void
  77. ): AreaChartSeries {
  78. const formatter = ({value, marker}: any) => {
  79. const time = formatTooltipDate(moment(value), 'MMM D, YYYY LT');
  80. return [
  81. `<div class="tooltip-series"><div>`,
  82. `<span class="tooltip-label">${marker} <strong>${t('Alert')} #${
  83. incident.identifier
  84. }</strong></span>${
  85. dataPoint?.value
  86. ? `${seriesName} ${alertTooltipValueFormatter(
  87. dataPoint.value,
  88. seriesName ?? '',
  89. aggregate ?? ''
  90. )}`
  91. : ''
  92. }`,
  93. `</div></div>`,
  94. `<div class="tooltip-footer">${time}</div>`,
  95. '<div class="tooltip-arrow"></div>',
  96. ].join('');
  97. };
  98. return {
  99. seriesName: 'Incident Line',
  100. type: 'line',
  101. markLine: MarkLine({
  102. silent: false,
  103. lineStyle: {color: lineColor, type: 'solid'},
  104. data: [
  105. {
  106. xAxis: incidentTimestamp,
  107. // @ts-expect-error onClick not in echart types
  108. onClick: () => handleIncidentClick?.(incident),
  109. },
  110. ],
  111. label: {
  112. silent: true,
  113. show: !!incident.identifier,
  114. position: 'insideEndBottom',
  115. formatter: incident.identifier,
  116. color: lineColor,
  117. fontSize: 10,
  118. fontFamily: 'Rubik',
  119. },
  120. tooltip: {
  121. formatter,
  122. },
  123. }),
  124. data: [],
  125. tooltip: {
  126. trigger: 'item',
  127. alwaysShowContent: true,
  128. formatter,
  129. },
  130. };
  131. }
  132. export type MetricChartData = {
  133. rule: MetricRule;
  134. timeseriesData: Series[];
  135. handleIncidentClick?: (incident: Incident) => void;
  136. incidents?: Incident[];
  137. selectedIncident?: Incident | null;
  138. showWaitingForData?: boolean;
  139. };
  140. type MetricChartOption = {
  141. chartOption: AreaChartProps;
  142. criticalDuration: number;
  143. totalDuration: number;
  144. waitingForDataDuration: number;
  145. warningDuration: number;
  146. };
  147. export function getMetricAlertChartOption({
  148. timeseriesData,
  149. rule,
  150. incidents,
  151. selectedIncident,
  152. handleIncidentClick,
  153. showWaitingForData,
  154. }: MetricChartData): MetricChartOption {
  155. let criticalTrigger: Trigger | undefined;
  156. let warningTrigger: Trigger | undefined;
  157. for (const trigger of rule.triggers) {
  158. if (trigger.label === AlertRuleTriggerType.CRITICAL) {
  159. criticalTrigger ??= trigger;
  160. }
  161. if (trigger.label === AlertRuleTriggerType.WARNING) {
  162. warningTrigger ??= trigger;
  163. }
  164. if (criticalTrigger && warningTrigger) {
  165. break;
  166. }
  167. }
  168. const series: AreaChartSeries[] = timeseriesData.map(s => ({
  169. ...s,
  170. seriesName: s.seriesName && formatMRIField(s.seriesName),
  171. }));
  172. const areaSeries: AreaChartSeries[] = [];
  173. // Ensure series data appears below incident/mark lines
  174. series[0].z = 1;
  175. series[0].color = CHART_PALETTE[0][0];
  176. const dataArr = timeseriesData[0].data;
  177. let maxSeriesValue = Number.NEGATIVE_INFINITY;
  178. let minSeriesValue = Number.POSITIVE_INFINITY;
  179. for (const coord of dataArr) {
  180. if (coord.value > maxSeriesValue) {
  181. maxSeriesValue = coord.value;
  182. }
  183. if (coord.value < minSeriesValue) {
  184. minSeriesValue = coord.value;
  185. }
  186. }
  187. // find the lowest value between chart data points, warning threshold,
  188. // critical threshold and then apply some breathing space
  189. const minChartValue = shouldScaleAlertChart(rule.aggregate)
  190. ? Math.floor(
  191. Math.min(
  192. minSeriesValue,
  193. typeof warningTrigger?.alertThreshold === 'number'
  194. ? warningTrigger.alertThreshold
  195. : Infinity,
  196. typeof criticalTrigger?.alertThreshold === 'number'
  197. ? criticalTrigger.alertThreshold
  198. : Infinity
  199. ) / ALERT_CHART_MIN_MAX_BUFFER
  200. )
  201. : 0;
  202. const firstPoint = new Date(dataArr[0]?.name).getTime();
  203. const lastPoint = new Date(dataArr[dataArr.length - 1]?.name).getTime();
  204. const totalDuration = lastPoint - firstPoint;
  205. let waitingForDataDuration = 0;
  206. let criticalDuration = 0;
  207. let warningDuration = 0;
  208. series.push(
  209. createStatusAreaSeries(theme.green300, firstPoint, lastPoint, minChartValue)
  210. );
  211. if (showWaitingForData) {
  212. const {startIndex, endIndex} = getWaitingForDataRange(dataArr);
  213. const startTime = new Date(dataArr[startIndex]?.name).getTime();
  214. const endTime = new Date(dataArr[endIndex]?.name).getTime();
  215. waitingForDataDuration = Math.abs(endTime - startTime);
  216. series.push(createStatusAreaSeries(theme.gray200, startTime, endTime, minChartValue));
  217. }
  218. if (incidents) {
  219. // select incidents that fall within the graph range
  220. incidents
  221. .filter(
  222. incident =>
  223. !incident.dateClosed || new Date(incident.dateClosed).getTime() > firstPoint
  224. )
  225. .forEach(incident => {
  226. const activities = incident.activities ?? [];
  227. const statusChanges = activities
  228. .filter(
  229. ({type, value}) =>
  230. type === IncidentActivityType.STATUS_CHANGE &&
  231. [IncidentStatus.WARNING, IncidentStatus.CRITICAL].includes(Number(value))
  232. )
  233. .sort(
  234. (a, b) =>
  235. new Date(a.dateCreated).getTime() - new Date(b.dateCreated).getTime()
  236. );
  237. const incidentEnd = incident.dateClosed ?? new Date().getTime();
  238. const timeWindowMs = rule.timeWindow * 60 * 1000;
  239. const incidentColor =
  240. warningTrigger &&
  241. !statusChanges.find(({value}) => Number(value) === IncidentStatus.CRITICAL)
  242. ? theme.yellow300
  243. : theme.red300;
  244. const incidentStartDate = new Date(incident.dateStarted).getTime();
  245. const incidentCloseDate = incident.dateClosed
  246. ? new Date(incident.dateClosed).getTime()
  247. : lastPoint;
  248. const incidentStartValue = dataArr.find(
  249. point => new Date(point.name).getTime() >= incidentStartDate
  250. );
  251. series.push(
  252. createIncidentSeries(
  253. incident,
  254. incidentColor,
  255. incidentStartDate,
  256. incidentStartValue,
  257. series[0].seriesName,
  258. rule.aggregate,
  259. handleIncidentClick
  260. )
  261. );
  262. const areaStart = Math.max(new Date(incident.dateStarted).getTime(), firstPoint);
  263. const areaEnd = Math.min(
  264. statusChanges.length && statusChanges[0].dateCreated
  265. ? new Date(statusChanges[0].dateCreated).getTime() - timeWindowMs
  266. : new Date(incidentEnd).getTime(),
  267. lastPoint
  268. );
  269. const areaColor = warningTrigger ? theme.yellow300 : theme.red300;
  270. if (areaEnd > areaStart) {
  271. series.push(
  272. createStatusAreaSeries(areaColor, areaStart, areaEnd, minChartValue)
  273. );
  274. if (areaColor === theme.yellow300) {
  275. warningDuration += Math.abs(areaEnd - areaStart);
  276. } else {
  277. criticalDuration += Math.abs(areaEnd - areaStart);
  278. }
  279. }
  280. statusChanges.forEach((activity, idx) => {
  281. const statusAreaStart = Math.max(
  282. new Date(activity.dateCreated).getTime() - timeWindowMs,
  283. firstPoint
  284. );
  285. const statusAreaEnd = Math.min(
  286. idx === statusChanges.length - 1
  287. ? new Date(incidentEnd).getTime()
  288. : new Date(statusChanges[idx + 1].dateCreated).getTime() - timeWindowMs,
  289. lastPoint
  290. );
  291. const statusAreaColor =
  292. activity.value === `${IncidentStatus.CRITICAL}`
  293. ? theme.red300
  294. : theme.yellow300;
  295. if (statusAreaEnd > statusAreaStart) {
  296. series.push(
  297. createStatusAreaSeries(
  298. statusAreaColor,
  299. statusAreaStart,
  300. statusAreaEnd,
  301. minChartValue
  302. )
  303. );
  304. if (statusAreaColor === theme.yellow300) {
  305. warningDuration += Math.abs(statusAreaEnd - statusAreaStart);
  306. } else {
  307. criticalDuration += Math.abs(statusAreaEnd - statusAreaStart);
  308. }
  309. }
  310. });
  311. if (selectedIncident && incident.id === selectedIncident.id) {
  312. const selectedIncidentColor =
  313. incidentColor === theme.yellow300 ? theme.yellow100 : theme.red100;
  314. areaSeries.push({
  315. seriesName: '',
  316. type: 'line',
  317. markArea: MarkArea({
  318. silent: true,
  319. itemStyle: {
  320. color: color(selectedIncidentColor).alpha(0.42).rgb().string(),
  321. },
  322. data: [[{xAxis: incidentStartDate}, {xAxis: incidentCloseDate}]],
  323. }),
  324. data: [],
  325. });
  326. }
  327. });
  328. }
  329. let maxThresholdValue = 0;
  330. if (!rule.comparisonDelta && warningTrigger?.alertThreshold) {
  331. const {alertThreshold} = warningTrigger;
  332. const warningThresholdLine = createThresholdSeries(theme.yellow300, alertThreshold);
  333. series.push(warningThresholdLine);
  334. maxThresholdValue = Math.max(maxThresholdValue, alertThreshold);
  335. }
  336. if (!rule.comparisonDelta && criticalTrigger?.alertThreshold) {
  337. const {alertThreshold} = criticalTrigger;
  338. const criticalThresholdLine = createThresholdSeries(theme.red300, alertThreshold);
  339. series.push(criticalThresholdLine);
  340. maxThresholdValue = Math.max(maxThresholdValue, alertThreshold);
  341. }
  342. if (!rule.comparisonDelta && rule.resolveThreshold) {
  343. const resolveThresholdLine = createThresholdSeries(
  344. theme.green300,
  345. rule.resolveThreshold
  346. );
  347. series.push(resolveThresholdLine);
  348. maxThresholdValue = Math.max(maxThresholdValue, rule.resolveThreshold);
  349. }
  350. const yAxis: YAXisComponentOption = {
  351. axisLabel: {
  352. formatter: (value: number) =>
  353. alertAxisFormatter(value, timeseriesData[0].seriesName, rule.aggregate),
  354. },
  355. max: isCrashFreeAlert(rule.dataset)
  356. ? 100
  357. : maxThresholdValue > maxSeriesValue
  358. ? maxThresholdValue
  359. : undefined,
  360. min: minChartValue || undefined,
  361. };
  362. return {
  363. criticalDuration,
  364. warningDuration,
  365. waitingForDataDuration,
  366. totalDuration,
  367. chartOption: {
  368. isGroupedByDate: true,
  369. yAxis,
  370. series,
  371. grid: {
  372. left: space(0.25),
  373. right: space(2),
  374. top: space(3),
  375. bottom: 0,
  376. },
  377. },
  378. };
  379. }
  380. function getWaitingForDataRange(dataArr) {
  381. if (dataArr[0].value > 0) {
  382. return {startIndex: 0, endIndex: 0};
  383. }
  384. for (let i = 0; i < dataArr.length; i++) {
  385. const dataPoint = dataArr[i];
  386. if (dataPoint.value > 0) {
  387. return {startIndex: 0, endIndex: i - 1};
  388. }
  389. }
  390. return {startIndex: 0, endIndex: dataArr.length - 1};
  391. }
  392. export function transformSessionResponseToSeries(
  393. response: SessionApiResponse | null,
  394. rule: MetricRule
  395. ): MetricChartData['timeseriesData'] {
  396. const {aggregate} = rule;
  397. return [
  398. {
  399. seriesName:
  400. AlertWizardAlertNames[
  401. getAlertTypeFromAggregateDataset({
  402. aggregate,
  403. dataset: Dataset.SESSIONS,
  404. })
  405. ],
  406. data: getCrashFreeRateSeries(
  407. response?.groups,
  408. response?.intervals,
  409. SESSION_AGGREGATE_TO_FIELD[aggregate]
  410. ),
  411. },
  412. ];
  413. }