metricChartOption.tsx 12 KB

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