index.tsx 19 KB

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