index.tsx 17 KB

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