index.tsx 18 KB

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