metricChart.tsx 21 KB

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