metricChart.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. import {PureComponent} from 'react';
  2. import {browserHistory, WithRouterProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import color from 'color';
  5. import type {LineSeriesOption} from 'echarts';
  6. import capitalize from 'lodash/capitalize';
  7. import moment from 'moment';
  8. import momentTimezone from 'moment-timezone';
  9. import {Client} from 'sentry/api';
  10. import Feature from 'sentry/components/acl/feature';
  11. import {Button} from 'sentry/components/button';
  12. import {AreaChart, AreaChartSeries} from 'sentry/components/charts/areaChart';
  13. import ChartZoom from 'sentry/components/charts/chartZoom';
  14. import MarkArea from 'sentry/components/charts/components/markArea';
  15. import MarkLine from 'sentry/components/charts/components/markLine';
  16. import EventsRequest from 'sentry/components/charts/eventsRequest';
  17. import LineSeries from 'sentry/components/charts/series/lineSeries';
  18. import SessionsRequest from 'sentry/components/charts/sessionsRequest';
  19. import {
  20. ChartControls,
  21. HeaderTitleLegend,
  22. InlineContainer,
  23. SectionHeading,
  24. SectionValue,
  25. } from 'sentry/components/charts/styles';
  26. import CircleIndicator from 'sentry/components/circleIndicator';
  27. import {
  28. parseStatsPeriod,
  29. StatsPeriodType,
  30. } from 'sentry/components/organizations/pageFilters/parse';
  31. import Panel from 'sentry/components/panels/panel';
  32. import PanelBody from 'sentry/components/panels/panelBody';
  33. import Placeholder from 'sentry/components/placeholder';
  34. import Truncate from 'sentry/components/truncate';
  35. import {IconCheckmark, IconFire, IconWarning} from 'sentry/icons';
  36. import {t} from 'sentry/locale';
  37. import ConfigStore from 'sentry/stores/configStore';
  38. import {space} from 'sentry/styles/space';
  39. import {DateString, Organization, Project} from 'sentry/types';
  40. import {ReactEchartsRef, Series} from 'sentry/types/echarts';
  41. import {getUtcDateString} from 'sentry/utils/dates';
  42. import {getDuration} from 'sentry/utils/formatters';
  43. import getDynamicText from 'sentry/utils/getDynamicText';
  44. import {MINUTES_THRESHOLD_TO_DISPLAY_SECONDS} from 'sentry/utils/sessions';
  45. import theme from 'sentry/utils/theme';
  46. import toArray from 'sentry/utils/toArray';
  47. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  48. // eslint-disable-next-line no-restricted-imports
  49. import withSentryRouter from 'sentry/utils/withSentryRouter';
  50. import {COMPARISON_DELTA_OPTIONS} from 'sentry/views/alerts/rules/metric/constants';
  51. import {makeDefaultCta} from 'sentry/views/alerts/rules/metric/metricRulePresets';
  52. import {
  53. AlertRuleTriggerType,
  54. MetricRule,
  55. TimePeriod,
  56. } from 'sentry/views/alerts/rules/metric/types';
  57. import {getChangeStatus} from 'sentry/views/alerts/utils/getChangeStatus';
  58. import {AlertWizardAlertNames} from 'sentry/views/alerts/wizard/options';
  59. import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
  60. import {Incident} from '../../../types';
  61. import {
  62. alertDetailsLink,
  63. alertTooltipValueFormatter,
  64. isSessionAggregate,
  65. SESSION_AGGREGATE_TO_FIELD,
  66. } from '../../../utils';
  67. import {getMetricDatasetQueryExtras} from '../utils/getMetricDatasetQueryExtras';
  68. import {isCrashFreeAlert} from '../utils/isCrashFreeAlert';
  69. import {TimePeriodType} from './constants';
  70. import {
  71. getMetricAlertChartOption,
  72. transformSessionResponseToSeries,
  73. } from './metricChartOption';
  74. type Props = WithRouterProps & {
  75. api: Client;
  76. filter: string[] | null;
  77. interval: string;
  78. organization: Organization;
  79. project: Project;
  80. query: string;
  81. rule: MetricRule;
  82. timePeriod: TimePeriodType;
  83. incidents?: Incident[];
  84. isOnDemandMetricAlert?: boolean;
  85. selectedIncident?: Incident | null;
  86. };
  87. type State = {
  88. height: number;
  89. width: number;
  90. };
  91. function formatTooltipDate(date: moment.MomentInput, format: string): string {
  92. const {
  93. options: {timezone},
  94. } = ConfigStore.get('user');
  95. return momentTimezone.tz(date, timezone).format(format);
  96. }
  97. function getRuleChangeSeries(
  98. rule: MetricRule,
  99. data: AreaChartSeries[]
  100. ): LineSeriesOption[] {
  101. const {dateModified} = rule;
  102. if (!data.length || !data[0].data.length || !dateModified) {
  103. return [];
  104. }
  105. const seriesData = data[0].data;
  106. const seriesStart = new Date(seriesData[0].name).getTime();
  107. const ruleChanged = new Date(dateModified).getTime();
  108. if (ruleChanged < seriesStart) {
  109. return [];
  110. }
  111. return [
  112. {
  113. type: 'line',
  114. markLine: MarkLine({
  115. silent: true,
  116. animation: false,
  117. lineStyle: {color: theme.gray200, type: 'solid', width: 1},
  118. data: [{xAxis: ruleChanged}],
  119. label: {
  120. show: false,
  121. },
  122. }),
  123. markArea: MarkArea({
  124. silent: true,
  125. itemStyle: {
  126. color: color(theme.gray100).alpha(0.42).rgb().string(),
  127. },
  128. data: [[{xAxis: seriesStart}, {xAxis: ruleChanged}]],
  129. }),
  130. data: [],
  131. },
  132. ];
  133. }
  134. class MetricChart extends PureComponent<Props, State> {
  135. state = {
  136. width: -1,
  137. height: -1,
  138. };
  139. ref: null | ReactEchartsRef = null;
  140. /**
  141. * Syncs component state with the chart's width/heights
  142. */
  143. updateDimensions = () => {
  144. const chartRef = this.ref?.getEchartsInstance?.();
  145. if (!chartRef) {
  146. return;
  147. }
  148. const width = chartRef.getWidth();
  149. const height = chartRef.getHeight();
  150. if (width !== this.state.width || height !== this.state.height) {
  151. this.setState({
  152. width,
  153. height,
  154. });
  155. }
  156. };
  157. handleRef = (ref: ReactEchartsRef): void => {
  158. if (ref && !this.ref) {
  159. this.ref = ref;
  160. this.updateDimensions();
  161. }
  162. if (!ref) {
  163. this.ref = null;
  164. }
  165. };
  166. handleZoom = (start: DateString, end: DateString) => {
  167. const {location} = this.props;
  168. browserHistory.push({
  169. pathname: location.pathname,
  170. query: {
  171. start,
  172. end,
  173. },
  174. });
  175. };
  176. renderChartActions(
  177. totalDuration: number,
  178. criticalDuration: number,
  179. warningDuration: number
  180. ) {
  181. const {rule, organization, project, timePeriod, query} = this.props;
  182. const {buttonText, ...props} = makeDefaultCta({
  183. orgSlug: organization.slug,
  184. projects: [project],
  185. rule,
  186. timePeriod,
  187. query,
  188. });
  189. const resolvedPercent =
  190. (100 * Math.max(totalDuration - criticalDuration - warningDuration, 0)) /
  191. totalDuration;
  192. const criticalPercent = 100 * Math.min(criticalDuration / totalDuration, 1);
  193. const warningPercent = 100 * Math.min(warningDuration / totalDuration, 1);
  194. return (
  195. <StyledChartControls>
  196. <StyledInlineContainer>
  197. <SectionHeading>{t('Summary')}</SectionHeading>
  198. <StyledSectionValue>
  199. <ValueItem>
  200. <IconCheckmark color="successText" isCircled />
  201. {resolvedPercent ? resolvedPercent.toFixed(2) : 0}%
  202. </ValueItem>
  203. <ValueItem>
  204. <IconWarning color="warningText" />
  205. {warningPercent ? warningPercent.toFixed(2) : 0}%
  206. </ValueItem>
  207. <ValueItem>
  208. <IconFire color="errorText" />
  209. {criticalPercent ? criticalPercent.toFixed(2) : 0}%
  210. </ValueItem>
  211. </StyledSectionValue>
  212. </StyledInlineContainer>
  213. {!isSessionAggregate(rule.aggregate) && (
  214. <Feature features={['discover-basic']}>
  215. <Button size="sm" {...props}>
  216. {buttonText}
  217. </Button>
  218. </Feature>
  219. )}
  220. </StyledChartControls>
  221. );
  222. }
  223. renderChart(
  224. loading: boolean,
  225. timeseriesData?: Series[],
  226. minutesThresholdToDisplaySeconds?: number,
  227. comparisonTimeseriesData?: Series[]
  228. ) {
  229. const {
  230. router,
  231. selectedIncident,
  232. interval,
  233. filter,
  234. incidents,
  235. rule,
  236. organization,
  237. timePeriod: {start, end},
  238. } = this.props;
  239. const {width} = this.state;
  240. const {dateModified, timeWindow} = rule;
  241. if (loading || !timeseriesData) {
  242. return this.renderEmpty();
  243. }
  244. const handleIncidentClick = (incident: Incident) => {
  245. router.push(
  246. normalizeUrl({
  247. pathname: alertDetailsLink(organization, incident),
  248. query: {alert: incident.identifier},
  249. })
  250. );
  251. };
  252. const {criticalDuration, warningDuration, totalDuration, chartOption} =
  253. getMetricAlertChartOption({
  254. timeseriesData,
  255. rule,
  256. incidents,
  257. selectedIncident,
  258. handleIncidentClick,
  259. });
  260. const comparisonSeriesName = capitalize(
  261. COMPARISON_DELTA_OPTIONS.find(({value}) => value === rule.comparisonDelta)?.label ||
  262. ''
  263. );
  264. const additionalSeries: LineSeriesOption[] = [
  265. ...(comparisonTimeseriesData || []).map(({data: _data, ...otherSeriesProps}) =>
  266. LineSeries({
  267. name: comparisonSeriesName,
  268. data: _data.map(({name, value}) => [name, value]),
  269. lineStyle: {color: theme.gray200, type: 'dashed', width: 1},
  270. itemStyle: {color: theme.gray200},
  271. animation: false,
  272. animationThreshold: 1,
  273. animationDuration: 0,
  274. ...otherSeriesProps,
  275. })
  276. ),
  277. ...getRuleChangeSeries(rule, timeseriesData),
  278. ];
  279. const queryFilter =
  280. filter?.join(' ') + t(' over ') + getDuration(rule.timeWindow * 60);
  281. const percentOfWidth =
  282. width >= 1151
  283. ? 15
  284. : width < 1151 && width >= 700
  285. ? 14
  286. : width < 700 && width >= 515
  287. ? 13
  288. : width < 515 && width >= 300
  289. ? 12
  290. : 8;
  291. const truncateWidth = (percentOfWidth / 100) * width;
  292. return (
  293. <ChartPanel>
  294. <StyledPanelBody withPadding>
  295. <ChartHeader>
  296. <HeaderTitleLegend>
  297. {AlertWizardAlertNames[getAlertTypeFromAggregateDataset(rule)]}
  298. </HeaderTitleLegend>
  299. </ChartHeader>
  300. <ChartFilters>
  301. <StyledCircleIndicator size={8} />
  302. <Filters>{rule.aggregate}</Filters>
  303. <Truncate value={queryFilter ?? ''} maxLength={truncateWidth} />
  304. </ChartFilters>
  305. {getDynamicText({
  306. value: (
  307. <ChartZoom
  308. router={router}
  309. start={start}
  310. end={end}
  311. onZoom={zoomArgs => this.handleZoom(zoomArgs.start, zoomArgs.end)}
  312. onFinished={() => {
  313. // We want to do this whenever the chart finishes re-rendering so that we can update the dimensions of
  314. // any graphics related to the triggers (e.g. the threshold areas + boundaries)
  315. this.updateDimensions();
  316. }}
  317. >
  318. {zoomRenderProps => (
  319. <AreaChart
  320. {...zoomRenderProps}
  321. {...chartOption}
  322. showTimeInTooltip
  323. minutesThresholdToDisplaySeconds={minutesThresholdToDisplaySeconds}
  324. forwardedRef={this.handleRef}
  325. additionalSeries={additionalSeries}
  326. tooltip={{
  327. formatter: seriesParams => {
  328. // seriesParams can be object instead of array
  329. const pointSeries = toArray(seriesParams);
  330. const {marker, data: pointData, seriesName} = pointSeries[0];
  331. const [pointX, pointY] = pointData as [number, number];
  332. const pointYFormatted = alertTooltipValueFormatter(
  333. pointY,
  334. seriesName ?? '',
  335. rule.aggregate
  336. );
  337. const isModified =
  338. dateModified && pointX <= new Date(dateModified).getTime();
  339. const startTime = formatTooltipDate(moment(pointX), 'MMM D LT');
  340. const {period, periodLength} = parseStatsPeriod(interval) ?? {
  341. periodLength: 'm',
  342. period: `${timeWindow}`,
  343. };
  344. const endTime = formatTooltipDate(
  345. moment(pointX).add(
  346. parseInt(period, 10),
  347. periodLength as StatsPeriodType
  348. ),
  349. 'MMM D LT'
  350. );
  351. const comparisonSeries =
  352. pointSeries.length > 1
  353. ? pointSeries.find(
  354. ({seriesName: _sn}) => _sn === comparisonSeriesName
  355. )
  356. : undefined;
  357. const comparisonPointY = comparisonSeries?.data[1] as
  358. | number
  359. | undefined;
  360. const comparisonPointYFormatted =
  361. comparisonPointY !== undefined
  362. ? alertTooltipValueFormatter(
  363. comparisonPointY,
  364. seriesName ?? '',
  365. rule.aggregate
  366. )
  367. : undefined;
  368. const changePercentage =
  369. comparisonPointY === undefined
  370. ? NaN
  371. : ((pointY - comparisonPointY) * 100) / comparisonPointY;
  372. const changeStatus = getChangeStatus(
  373. changePercentage,
  374. rule.thresholdType,
  375. rule.triggers
  376. );
  377. const changeStatusColor =
  378. changeStatus === AlertRuleTriggerType.CRITICAL
  379. ? theme.red300
  380. : changeStatus === AlertRuleTriggerType.WARNING
  381. ? theme.yellow300
  382. : theme.green300;
  383. return [
  384. `<div class="tooltip-series">`,
  385. isModified &&
  386. `<div><span class="tooltip-label"><strong>${t(
  387. 'Alert Rule Modified'
  388. )}</strong></span></div>`,
  389. `<div><span class="tooltip-label">${marker} <strong>${seriesName}</strong></span>${pointYFormatted}</div>`,
  390. comparisonSeries &&
  391. `<div><span class="tooltip-label">${comparisonSeries.marker} <strong>${comparisonSeriesName}</strong></span>${comparisonPointYFormatted}</div>`,
  392. `</div>`,
  393. `<div class="tooltip-footer">`,
  394. `<span>${startTime} &mdash; ${endTime}</span>`,
  395. comparisonPointY !== undefined &&
  396. Math.abs(changePercentage) !== Infinity &&
  397. !isNaN(changePercentage) &&
  398. `<span style="color:${changeStatusColor};margin-left:10px;">${
  399. Math.sign(changePercentage) === 1 ? '+' : '-'
  400. }${Math.abs(changePercentage).toFixed(2)}%</span>`,
  401. `</div>`,
  402. '<div class="tooltip-arrow"></div>',
  403. ]
  404. .filter(e => e)
  405. .join('');
  406. },
  407. }}
  408. />
  409. )}
  410. </ChartZoom>
  411. ),
  412. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  413. })}
  414. </StyledPanelBody>
  415. {this.renderChartActions(totalDuration, criticalDuration, warningDuration)}
  416. </ChartPanel>
  417. );
  418. }
  419. renderEmpty(placeholderText = '') {
  420. return (
  421. <ChartPanel>
  422. <PanelBody withPadding>
  423. <TriggerChartPlaceholder>{placeholderText}</TriggerChartPlaceholder>
  424. </PanelBody>
  425. </ChartPanel>
  426. );
  427. }
  428. render() {
  429. const {
  430. api,
  431. rule,
  432. organization,
  433. timePeriod,
  434. project,
  435. interval,
  436. query,
  437. location,
  438. isOnDemandMetricAlert,
  439. } = this.props;
  440. const {aggregate, timeWindow, environment, dataset} = rule;
  441. // Fix for 7 days * 1m interval being over the max number of results from events api
  442. // 10k events is the current max
  443. if (
  444. timePeriod.usingPeriod &&
  445. timePeriod.period === TimePeriod.SEVEN_DAYS &&
  446. interval === '1m'
  447. ) {
  448. timePeriod.start = getUtcDateString(
  449. // -5 minutes provides a small cushion for rounding up minutes. This might be able to be smaller
  450. moment(moment.utc(timePeriod.end).subtract(10000 - 5, 'minutes'))
  451. );
  452. }
  453. // If the chart duration isn't as long as the rollup duration the events-stats
  454. // endpoint will return an invalid timeseriesData dataset
  455. const viableStartDate = getUtcDateString(
  456. moment.min(
  457. moment.utc(timePeriod.start),
  458. moment.utc(timePeriod.end).subtract(timeWindow, 'minutes')
  459. )
  460. );
  461. const viableEndDate = getUtcDateString(
  462. moment.utc(timePeriod.end).add(timeWindow, 'minutes')
  463. );
  464. const queryExtras = getMetricDatasetQueryExtras({
  465. organization,
  466. location,
  467. dataset,
  468. newAlertOrQuery: false,
  469. });
  470. return isCrashFreeAlert(dataset) ? (
  471. <SessionsRequest
  472. api={api}
  473. organization={organization}
  474. project={project.id ? [Number(project.id)] : []}
  475. environment={environment ? [environment] : undefined}
  476. start={viableStartDate}
  477. end={viableEndDate}
  478. query={query}
  479. interval={interval}
  480. field={SESSION_AGGREGATE_TO_FIELD[aggregate]}
  481. groupBy={['session.status']}
  482. >
  483. {({loading, response}) =>
  484. this.renderChart(
  485. loading,
  486. transformSessionResponseToSeries(response, rule),
  487. MINUTES_THRESHOLD_TO_DISPLAY_SECONDS
  488. )
  489. }
  490. </SessionsRequest>
  491. ) : (
  492. <EventsRequest
  493. api={api}
  494. organization={organization}
  495. query={query}
  496. environment={environment ? [environment] : undefined}
  497. project={project.id ? [Number(project.id)] : []}
  498. interval={interval}
  499. comparisonDelta={rule.comparisonDelta ? rule.comparisonDelta * 60 : undefined}
  500. start={viableStartDate}
  501. end={viableEndDate}
  502. yAxis={aggregate}
  503. includePrevious={false}
  504. currentSeriesNames={[aggregate]}
  505. partial={false}
  506. queryExtras={queryExtras}
  507. referrer="api.alerts.alert-rule-chart"
  508. useOnDemandMetrics={isOnDemandMetricAlert}
  509. >
  510. {({loading, timeseriesData, comparisonTimeseriesData}) =>
  511. this.renderChart(loading, timeseriesData, undefined, comparisonTimeseriesData)
  512. }
  513. </EventsRequest>
  514. );
  515. }
  516. }
  517. export default withSentryRouter(MetricChart);
  518. const ChartPanel = styled(Panel)`
  519. margin-top: ${space(2)};
  520. `;
  521. const ChartHeader = styled('div')`
  522. margin-bottom: ${space(3)};
  523. `;
  524. const StyledChartControls = styled(ChartControls)`
  525. display: flex;
  526. justify-content: space-between;
  527. flex-wrap: wrap;
  528. `;
  529. const StyledInlineContainer = styled(InlineContainer)`
  530. grid-auto-flow: column;
  531. grid-column-gap: ${space(1)};
  532. `;
  533. const StyledCircleIndicator = styled(CircleIndicator)`
  534. background: ${p => p.theme.formText};
  535. height: ${space(1)};
  536. margin-right: ${space(0.5)};
  537. `;
  538. const ChartFilters = styled('div')`
  539. font-size: ${p => p.theme.fontSizeSmall};
  540. font-family: ${p => p.theme.text.family};
  541. color: ${p => p.theme.textColor};
  542. display: inline-grid;
  543. grid-template-columns: repeat(3, max-content);
  544. align-items: center;
  545. `;
  546. const Filters = styled('span')`
  547. margin-right: ${space(1)};
  548. `;
  549. const StyledSectionValue = styled(SectionValue)`
  550. display: grid;
  551. grid-template-columns: repeat(3, auto);
  552. gap: ${space(1.5)};
  553. margin: 0 0 0 ${space(1.5)};
  554. `;
  555. const ValueItem = styled('div')`
  556. display: grid;
  557. grid-template-columns: repeat(2, auto);
  558. gap: ${space(0.5)};
  559. align-items: center;
  560. font-variant-numeric: tabular-nums;
  561. `;
  562. /* Override padding to make chart appear centered */
  563. const StyledPanelBody = styled(PanelBody)`
  564. padding-right: 6px;
  565. `;
  566. const TriggerChartPlaceholder = styled(Placeholder)`
  567. height: 200px;
  568. text-align: center;
  569. padding: ${space(3)};
  570. `;