metricChart.tsx 20 KB

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