index.tsx 17 KB

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