index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. import {Fragment, PureComponent} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Location} from 'history';
  4. import capitalize from 'lodash/capitalize';
  5. import isEqual from 'lodash/isEqual';
  6. import maxBy from 'lodash/maxBy';
  7. import minBy from 'lodash/minBy';
  8. import {fetchTotalCount} from 'sentry/actionCreators/events';
  9. import type {Client} from 'sentry/api';
  10. import ErrorPanel from 'sentry/components/charts/errorPanel';
  11. import EventsRequest from 'sentry/components/charts/eventsRequest';
  12. import type {LineChartSeries} from 'sentry/components/charts/lineChart';
  13. import {OnDemandMetricRequest} from 'sentry/components/charts/onDemandMetricRequest';
  14. import SessionsRequest from 'sentry/components/charts/sessionsRequest';
  15. import {
  16. ChartControls,
  17. InlineContainer,
  18. SectionHeading,
  19. SectionValue,
  20. } from 'sentry/components/charts/styles';
  21. import {CompactSelect} from 'sentry/components/compactSelect';
  22. import LoadingMask from 'sentry/components/loadingMask';
  23. import PanelAlert from 'sentry/components/panels/panelAlert';
  24. import Placeholder from 'sentry/components/placeholder';
  25. import {IconWarning} from 'sentry/icons';
  26. import {t} from 'sentry/locale';
  27. import {space} from 'sentry/styles/space';
  28. import type {
  29. EventsStats,
  30. MultiSeriesEventsStats,
  31. Organization,
  32. Project,
  33. } from 'sentry/types';
  34. import type {Series} from 'sentry/types/echarts';
  35. import {parsePeriodToHours} from 'sentry/utils/dates';
  36. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  37. import {getForceMetricsLayerQueryExtras} from 'sentry/utils/metrics/features';
  38. import {formatMRIField} from 'sentry/utils/metrics/mri';
  39. import {shouldShowOnDemandMetricAlertUI} from 'sentry/utils/onDemandMetrics/features';
  40. import {
  41. getCrashFreeRateSeries,
  42. MINUTES_THRESHOLD_TO_DISPLAY_SECONDS,
  43. } from 'sentry/utils/sessions';
  44. import withApi from 'sentry/utils/withApi';
  45. import {COMPARISON_DELTA_OPTIONS} from 'sentry/views/alerts/rules/metric/constants';
  46. import {shouldUseErrorsDiscoverDataset} from 'sentry/views/alerts/rules/utils';
  47. import {isSessionAggregate, SESSION_AGGREGATE_TO_FIELD} from 'sentry/views/alerts/utils';
  48. import {getComparisonMarkLines} from 'sentry/views/alerts/utils/getComparisonMarkLines';
  49. import {AlertWizardAlertNames} from 'sentry/views/alerts/wizard/options';
  50. import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
  51. import {
  52. AlertRuleComparisonType,
  53. Dataset,
  54. MetricRule,
  55. SessionsAggregate,
  56. TimePeriod,
  57. TimeWindow,
  58. Trigger,
  59. } from '../../types';
  60. import {getMetricDatasetQueryExtras} from '../../utils/getMetricDatasetQueryExtras';
  61. import ThresholdsChart from './thresholdsChart';
  62. type Props = {
  63. aggregate: MetricRule['aggregate'];
  64. api: Client;
  65. comparisonType: AlertRuleComparisonType;
  66. dataset: MetricRule['dataset'];
  67. environment: string | null;
  68. isQueryValid: boolean;
  69. location: Location;
  70. newAlertOrQuery: boolean;
  71. organization: Organization;
  72. projects: Project[];
  73. query: MetricRule['query'];
  74. resolveThreshold: MetricRule['resolveThreshold'];
  75. thresholdType: MetricRule['thresholdType'];
  76. timeWindow: MetricRule['timeWindow'];
  77. triggers: Trigger[];
  78. comparisonDelta?: number;
  79. header?: React.ReactNode;
  80. isOnDemandMetricAlert?: boolean;
  81. onDataLoaded?: (data: EventsStats | MultiSeriesEventsStats | null) => void;
  82. showTotalCount?: boolean;
  83. };
  84. const TIME_PERIOD_MAP: Record<TimePeriod, string> = {
  85. [TimePeriod.SIX_HOURS]: t('Last 6 hours'),
  86. [TimePeriod.ONE_DAY]: t('Last 24 hours'),
  87. [TimePeriod.THREE_DAYS]: t('Last 3 days'),
  88. [TimePeriod.SEVEN_DAYS]: t('Last 7 days'),
  89. [TimePeriod.FOURTEEN_DAYS]: t('Last 14 days'),
  90. };
  91. /**
  92. * Just to avoid repeating it
  93. */
  94. const MOST_TIME_PERIODS: readonly TimePeriod[] = [
  95. TimePeriod.ONE_DAY,
  96. TimePeriod.THREE_DAYS,
  97. TimePeriod.SEVEN_DAYS,
  98. TimePeriod.FOURTEEN_DAYS,
  99. ];
  100. /**
  101. * TimeWindow determines data available in TimePeriod
  102. * If TimeWindow is small, lower TimePeriod to limit data points
  103. */
  104. export const AVAILABLE_TIME_PERIODS: Record<TimeWindow, readonly TimePeriod[]> = {
  105. [TimeWindow.ONE_MINUTE]: [
  106. TimePeriod.SIX_HOURS,
  107. TimePeriod.ONE_DAY,
  108. TimePeriod.THREE_DAYS,
  109. TimePeriod.SEVEN_DAYS,
  110. ],
  111. [TimeWindow.FIVE_MINUTES]: MOST_TIME_PERIODS,
  112. [TimeWindow.TEN_MINUTES]: MOST_TIME_PERIODS,
  113. [TimeWindow.FIFTEEN_MINUTES]: MOST_TIME_PERIODS,
  114. [TimeWindow.THIRTY_MINUTES]: MOST_TIME_PERIODS,
  115. [TimeWindow.ONE_HOUR]: MOST_TIME_PERIODS,
  116. [TimeWindow.TWO_HOURS]: MOST_TIME_PERIODS,
  117. [TimeWindow.FOUR_HOURS]: [
  118. TimePeriod.THREE_DAYS,
  119. TimePeriod.SEVEN_DAYS,
  120. TimePeriod.FOURTEEN_DAYS,
  121. ],
  122. [TimeWindow.ONE_DAY]: [TimePeriod.FOURTEEN_DAYS],
  123. };
  124. const TIME_WINDOW_TO_SESSION_INTERVAL = {
  125. [TimeWindow.THIRTY_MINUTES]: '30m',
  126. [TimeWindow.ONE_HOUR]: '1h',
  127. [TimeWindow.TWO_HOURS]: '2h',
  128. [TimeWindow.FOUR_HOURS]: '4h',
  129. [TimeWindow.ONE_DAY]: '1d',
  130. };
  131. const SESSION_AGGREGATE_TO_HEADING = {
  132. [SessionsAggregate.CRASH_FREE_SESSIONS]: t('Total Sessions'),
  133. [SessionsAggregate.CRASH_FREE_USERS]: t('Total Users'),
  134. };
  135. type State = {
  136. sampleRate: number;
  137. statsPeriod: TimePeriod;
  138. totalCount: number | null;
  139. };
  140. const getStatsPeriodFromQuery = (
  141. queryParam: string | string[] | null | undefined
  142. ): TimePeriod => {
  143. if (typeof queryParam !== 'string') {
  144. return TimePeriod.SEVEN_DAYS;
  145. }
  146. const inMinutes = parsePeriodToHours(queryParam || '') * 60;
  147. switch (inMinutes) {
  148. case 6 * 60:
  149. return TimePeriod.SIX_HOURS;
  150. case 24 * 60:
  151. return TimePeriod.ONE_DAY;
  152. case 3 * 24 * 60:
  153. return TimePeriod.THREE_DAYS;
  154. case 9999:
  155. return TimePeriod.SEVEN_DAYS;
  156. case 14 * 24 * 60:
  157. return TimePeriod.FOURTEEN_DAYS;
  158. default:
  159. return TimePeriod.SEVEN_DAYS;
  160. }
  161. };
  162. /**
  163. * This is a chart to be used in Metric Alert rules that fetches events based on
  164. * query, timewindow, and aggregations.
  165. */
  166. class TriggersChart extends PureComponent<Props, State> {
  167. state: State = {
  168. statsPeriod: getStatsPeriodFromQuery(this.props.location.query.statsPeriod),
  169. totalCount: null,
  170. sampleRate: 1,
  171. };
  172. componentDidMount() {
  173. const {aggregate, showTotalCount} = this.props;
  174. if (showTotalCount && !isSessionAggregate(aggregate)) {
  175. this.fetchTotalCount();
  176. }
  177. }
  178. componentDidUpdate(prevProps: Props, prevState: State) {
  179. const {query, environment, timeWindow, aggregate, projects, showTotalCount} =
  180. this.props;
  181. const {statsPeriod} = this.state;
  182. if (
  183. showTotalCount &&
  184. !isSessionAggregate(aggregate) &&
  185. (!isEqual(prevProps.projects, projects) ||
  186. prevProps.environment !== environment ||
  187. prevProps.query !== query ||
  188. !isEqual(prevProps.timeWindow, timeWindow) ||
  189. !isEqual(prevState.statsPeriod, statsPeriod))
  190. ) {
  191. this.fetchTotalCount();
  192. }
  193. }
  194. get availableTimePeriods() {
  195. // We need to special case sessions, because sub-hour windows are available
  196. // only when time period is six hours or less (backend limitation)
  197. if (isSessionAggregate(this.props.aggregate)) {
  198. return {
  199. ...AVAILABLE_TIME_PERIODS,
  200. [TimeWindow.THIRTY_MINUTES]: [TimePeriod.SIX_HOURS],
  201. };
  202. }
  203. return AVAILABLE_TIME_PERIODS;
  204. }
  205. handleStatsPeriodChange = (timePeriod: TimePeriod) => {
  206. this.setState({statsPeriod: timePeriod});
  207. };
  208. getStatsPeriod = () => {
  209. const {statsPeriod} = this.state;
  210. const {timeWindow} = this.props;
  211. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  212. const period = statsPeriodOptions.includes(statsPeriod)
  213. ? statsPeriod
  214. : statsPeriodOptions[statsPeriodOptions.length - 1];
  215. return period;
  216. };
  217. get comparisonSeriesName() {
  218. return capitalize(
  219. COMPARISON_DELTA_OPTIONS.find(({value}) => value === this.props.comparisonDelta)
  220. ?.label || ''
  221. );
  222. }
  223. async fetchTotalCount() {
  224. const {
  225. api,
  226. organization,
  227. location,
  228. newAlertOrQuery,
  229. environment,
  230. projects,
  231. query,
  232. dataset,
  233. } = this.props;
  234. const statsPeriod = this.getStatsPeriod();
  235. const queryExtras = getMetricDatasetQueryExtras({
  236. organization,
  237. location,
  238. dataset,
  239. newAlertOrQuery,
  240. });
  241. let queryDataset = queryExtras.dataset as undefined | DiscoverDatasets;
  242. if (shouldUseErrorsDiscoverDataset(query, dataset)) {
  243. queryDataset = DiscoverDatasets.ERRORS;
  244. }
  245. try {
  246. const totalCount = await fetchTotalCount(api, organization.slug, {
  247. field: [],
  248. project: projects.map(({id}) => id),
  249. query,
  250. statsPeriod,
  251. environment: environment ? [environment] : [],
  252. dataset: queryDataset,
  253. ...getForceMetricsLayerQueryExtras(organization, dataset),
  254. });
  255. this.setState({totalCount});
  256. } catch (e) {
  257. this.setState({totalCount: null});
  258. }
  259. }
  260. renderChart({
  261. isLoading,
  262. isReloading,
  263. timeseriesData = [],
  264. comparisonData,
  265. comparisonMarkLines,
  266. errorMessage,
  267. minutesThresholdToDisplaySeconds,
  268. isQueryValid,
  269. errored,
  270. orgFeatures,
  271. seriesAdditionalInfo,
  272. }: {
  273. isLoading: boolean;
  274. isQueryValid: boolean;
  275. isReloading: boolean;
  276. orgFeatures: string[];
  277. timeseriesData: Series[];
  278. comparisonData?: Series[];
  279. comparisonMarkLines?: LineChartSeries[];
  280. errorMessage?: string;
  281. errored?: boolean;
  282. minutesThresholdToDisplaySeconds?: number;
  283. seriesAdditionalInfo?: Record<string, any>;
  284. }) {
  285. const {
  286. triggers,
  287. resolveThreshold,
  288. thresholdType,
  289. header,
  290. timeWindow,
  291. aggregate,
  292. comparisonType,
  293. organization,
  294. showTotalCount,
  295. } = this.props;
  296. const {statsPeriod, totalCount} = this.state;
  297. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  298. const period = this.getStatsPeriod();
  299. const error = orgFeatures.includes('alert-allow-indexed')
  300. ? errored || errorMessage
  301. : errored || errorMessage || !isQueryValid;
  302. const showExtrapolatedChartData =
  303. shouldShowOnDemandMetricAlertUI(organization) &&
  304. seriesAdditionalInfo?.[timeseriesData[0]?.seriesName]?.isExtrapolatedData;
  305. const totalCountLabel = isSessionAggregate(aggregate)
  306. ? SESSION_AGGREGATE_TO_HEADING[aggregate]
  307. : showExtrapolatedChartData
  308. ? t('Estimated Transactions')
  309. : t('Total');
  310. return (
  311. <Fragment>
  312. {header}
  313. <TransparentLoadingMask visible={isReloading} />
  314. {isLoading && !error ? (
  315. <ChartPlaceholder />
  316. ) : error ? (
  317. <ErrorChart
  318. isAllowIndexed={orgFeatures.includes('alert-allow-indexed')}
  319. errorMessage={errorMessage}
  320. isQueryValid={isQueryValid}
  321. />
  322. ) : (
  323. <ThresholdsChart
  324. period={statsPeriod}
  325. minValue={minBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  326. maxValue={maxBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  327. data={timeseriesData}
  328. comparisonData={comparisonData ?? []}
  329. comparisonSeriesName={this.comparisonSeriesName}
  330. comparisonMarkLines={comparisonMarkLines ?? []}
  331. hideThresholdLines={comparisonType === AlertRuleComparisonType.CHANGE}
  332. triggers={triggers}
  333. resolveThreshold={resolveThreshold}
  334. thresholdType={thresholdType}
  335. aggregate={aggregate}
  336. minutesThresholdToDisplaySeconds={minutesThresholdToDisplaySeconds}
  337. isExtrapolatedData={showExtrapolatedChartData}
  338. />
  339. )}
  340. <ChartControls>
  341. {showTotalCount ? (
  342. <InlineContainer data-test-id="alert-total-events">
  343. <SectionHeading>{totalCountLabel}</SectionHeading>
  344. <SectionValue>
  345. {totalCount !== null ? totalCount.toLocaleString() : '\u2014'}
  346. </SectionValue>
  347. </InlineContainer>
  348. ) : (
  349. <InlineContainer />
  350. )}
  351. <InlineContainer>
  352. <CompactSelect
  353. size="sm"
  354. options={statsPeriodOptions.map(timePeriod => ({
  355. value: timePeriod,
  356. label: TIME_PERIOD_MAP[timePeriod],
  357. }))}
  358. value={period}
  359. onChange={opt => this.handleStatsPeriodChange(opt.value)}
  360. position="bottom-end"
  361. triggerProps={{
  362. borderless: true,
  363. prefix: t('Display'),
  364. }}
  365. disabled={isLoading || isReloading}
  366. />
  367. </InlineContainer>
  368. </ChartControls>
  369. </Fragment>
  370. );
  371. }
  372. render() {
  373. const {
  374. api,
  375. organization,
  376. projects,
  377. timeWindow,
  378. query,
  379. location,
  380. aggregate,
  381. dataset,
  382. newAlertOrQuery,
  383. onDataLoaded,
  384. environment,
  385. comparisonDelta,
  386. triggers,
  387. thresholdType,
  388. isQueryValid,
  389. isOnDemandMetricAlert,
  390. } = this.props;
  391. const period = this.getStatsPeriod();
  392. const renderComparisonStats = Boolean(
  393. organization.features.includes('change-alerts') && comparisonDelta
  394. );
  395. const queryExtras = {
  396. ...getMetricDatasetQueryExtras({
  397. organization,
  398. location,
  399. dataset,
  400. newAlertOrQuery,
  401. }),
  402. ...getForceMetricsLayerQueryExtras(organization, dataset),
  403. ...(shouldUseErrorsDiscoverDataset(query, dataset)
  404. ? {dataset: DiscoverDatasets.ERRORS}
  405. : {}),
  406. };
  407. if (isOnDemandMetricAlert) {
  408. return (
  409. <OnDemandMetricRequest
  410. api={api}
  411. organization={organization}
  412. query={query}
  413. environment={environment ? [environment] : undefined}
  414. project={projects.map(({id}) => Number(id))}
  415. interval={`${timeWindow}m`}
  416. comparisonDelta={comparisonDelta && comparisonDelta * 60}
  417. period={period}
  418. yAxis={aggregate}
  419. includePrevious={false}
  420. currentSeriesNames={[aggregate]}
  421. partial={false}
  422. queryExtras={queryExtras}
  423. sampleRate={this.state.sampleRate}
  424. dataLoadedCallback={onDataLoaded}
  425. >
  426. {({
  427. loading,
  428. errored,
  429. errorMessage,
  430. reloading,
  431. timeseriesData,
  432. comparisonTimeseriesData,
  433. seriesAdditionalInfo,
  434. }) => {
  435. let comparisonMarkLines: LineChartSeries[] = [];
  436. if (renderComparisonStats && comparisonTimeseriesData) {
  437. comparisonMarkLines = getComparisonMarkLines(
  438. timeseriesData,
  439. comparisonTimeseriesData,
  440. timeWindow,
  441. triggers,
  442. thresholdType
  443. );
  444. }
  445. return this.renderChart({
  446. timeseriesData: timeseriesData as Series[],
  447. isLoading: loading,
  448. isReloading: reloading,
  449. comparisonData: comparisonTimeseriesData,
  450. comparisonMarkLines,
  451. errorMessage,
  452. isQueryValid,
  453. errored,
  454. orgFeatures: organization.features,
  455. seriesAdditionalInfo,
  456. });
  457. }}
  458. </OnDemandMetricRequest>
  459. );
  460. }
  461. return isSessionAggregate(aggregate) ? (
  462. <SessionsRequest
  463. api={api}
  464. organization={organization}
  465. project={projects.map(({id}) => Number(id))}
  466. environment={environment ? [environment] : undefined}
  467. statsPeriod={period}
  468. query={query}
  469. interval={TIME_WINDOW_TO_SESSION_INTERVAL[timeWindow]}
  470. field={SESSION_AGGREGATE_TO_FIELD[aggregate]}
  471. groupBy={['session.status']}
  472. >
  473. {({loading, errored, reloading, response}) => {
  474. const {groups, intervals} = response || {};
  475. const sessionTimeSeries = [
  476. {
  477. seriesName:
  478. AlertWizardAlertNames[
  479. getAlertTypeFromAggregateDataset({aggregate, dataset: Dataset.SESSIONS})
  480. ],
  481. data: getCrashFreeRateSeries(
  482. groups,
  483. intervals,
  484. SESSION_AGGREGATE_TO_FIELD[aggregate]
  485. ),
  486. },
  487. ];
  488. return this.renderChart({
  489. timeseriesData: sessionTimeSeries,
  490. isLoading: loading,
  491. isReloading: reloading,
  492. comparisonData: undefined,
  493. comparisonMarkLines: undefined,
  494. minutesThresholdToDisplaySeconds: MINUTES_THRESHOLD_TO_DISPLAY_SECONDS,
  495. isQueryValid,
  496. errored,
  497. orgFeatures: organization.features,
  498. });
  499. }}
  500. </SessionsRequest>
  501. ) : (
  502. <EventsRequest
  503. api={api}
  504. organization={organization}
  505. query={query}
  506. environment={environment ? [environment] : undefined}
  507. project={projects.map(({id}) => Number(id))}
  508. interval={`${timeWindow}m`}
  509. comparisonDelta={comparisonDelta && comparisonDelta * 60}
  510. period={period}
  511. yAxis={aggregate}
  512. includePrevious={false}
  513. currentSeriesNames={[formatMRIField(aggregate)]}
  514. partial={false}
  515. queryExtras={queryExtras}
  516. useOnDemandMetrics
  517. dataLoadedCallback={onDataLoaded}
  518. >
  519. {({
  520. loading,
  521. errored,
  522. errorMessage,
  523. reloading,
  524. timeseriesData,
  525. comparisonTimeseriesData,
  526. }) => {
  527. let comparisonMarkLines: LineChartSeries[] = [];
  528. if (renderComparisonStats && comparisonTimeseriesData) {
  529. comparisonMarkLines = getComparisonMarkLines(
  530. timeseriesData,
  531. comparisonTimeseriesData,
  532. timeWindow,
  533. triggers,
  534. thresholdType
  535. );
  536. }
  537. return this.renderChart({
  538. timeseriesData: timeseriesData as Series[],
  539. isLoading: loading,
  540. isReloading: reloading,
  541. comparisonData: comparisonTimeseriesData,
  542. comparisonMarkLines,
  543. errorMessage,
  544. isQueryValid,
  545. errored,
  546. orgFeatures: organization.features,
  547. });
  548. }}
  549. </EventsRequest>
  550. );
  551. }
  552. }
  553. export default withApi(TriggersChart);
  554. const TransparentLoadingMask = styled(LoadingMask)<{visible: boolean}>`
  555. ${p => !p.visible && 'display: none;'};
  556. opacity: 0.4;
  557. z-index: 1;
  558. `;
  559. const ChartPlaceholder = styled(Placeholder)`
  560. /* Height and margin should add up to graph size (200px) */
  561. margin: 0 0 ${space(2)};
  562. height: 184px;
  563. `;
  564. const StyledErrorPanel = styled(ErrorPanel)`
  565. /* Height and margin should with the alert should match up placeholder height of (184px) */
  566. padding: ${space(2)};
  567. height: 119px;
  568. `;
  569. const ChartErrorWrapper = styled('div')`
  570. margin-top: ${space(2)};
  571. `;
  572. function ErrorChart({isAllowIndexed, isQueryValid, errorMessage}) {
  573. return (
  574. <ChartErrorWrapper>
  575. <PanelAlert type="error">
  576. {!isAllowIndexed && !isQueryValid
  577. ? t('Your filter conditions contain an unsupported field - please review.')
  578. : typeof errorMessage === 'string'
  579. ? errorMessage
  580. : t('An error occurred while fetching data')}
  581. </PanelAlert>
  582. <StyledErrorPanel>
  583. <IconWarning color="gray500" size="lg" />
  584. </StyledErrorPanel>
  585. </ChartErrorWrapper>
  586. );
  587. }