index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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 OptionSelector from 'sentry/components/charts/optionSelector';
  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 LoadingMask from 'sentry/components/loadingMask';
  22. import PanelAlert from 'sentry/components/panels/panelAlert';
  23. import Placeholder from 'sentry/components/placeholder';
  24. import {IconSettings, 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 {DiscoverDatasets} from 'sentry/utils/discover/types';
  35. import {
  36. getCrashFreeRateSeries,
  37. MINUTES_THRESHOLD_TO_DISPLAY_SECONDS,
  38. } from 'sentry/utils/sessions';
  39. import withApi from 'sentry/utils/withApi';
  40. import {COMPARISON_DELTA_OPTIONS} from 'sentry/views/alerts/rules/metric/constants';
  41. import {isSessionAggregate, SESSION_AGGREGATE_TO_FIELD} from 'sentry/views/alerts/utils';
  42. import {getComparisonMarkLines} from 'sentry/views/alerts/utils/getComparisonMarkLines';
  43. import {AlertWizardAlertNames} from 'sentry/views/alerts/wizard/options';
  44. import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
  45. import {
  46. AlertRuleComparisonType,
  47. Dataset,
  48. MetricRule,
  49. SessionsAggregate,
  50. TimePeriod,
  51. TimeWindow,
  52. Trigger,
  53. } from '../../types';
  54. import {getMetricDatasetQueryExtras} from '../../utils/getMetricDatasetQueryExtras';
  55. import ThresholdsChart from './thresholdsChart';
  56. type Props = {
  57. aggregate: MetricRule['aggregate'];
  58. api: Client;
  59. comparisonType: AlertRuleComparisonType;
  60. dataset: MetricRule['dataset'];
  61. environment: string | null;
  62. handleMEPAlertDataset: (data: EventsStats | MultiSeriesEventsStats | null) => void;
  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. };
  77. const TIME_PERIOD_MAP: Record<TimePeriod, string> = {
  78. [TimePeriod.SIX_HOURS]: t('Last 6 hours'),
  79. [TimePeriod.ONE_DAY]: t('Last 24 hours'),
  80. [TimePeriod.THREE_DAYS]: t('Last 3 days'),
  81. [TimePeriod.SEVEN_DAYS]: t('Last 7 days'),
  82. [TimePeriod.FOURTEEN_DAYS]: t('Last 14 days'),
  83. [TimePeriod.THIRTY_DAYS]: t('Last 30 days'),
  84. };
  85. /**
  86. * Just to avoid repeating it
  87. */
  88. const MOST_TIME_PERIODS: readonly TimePeriod[] = [
  89. TimePeriod.ONE_DAY,
  90. TimePeriod.THREE_DAYS,
  91. TimePeriod.SEVEN_DAYS,
  92. TimePeriod.FOURTEEN_DAYS,
  93. TimePeriod.THIRTY_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. TimePeriod.THIRTY_DAYS,
  117. ],
  118. [TimeWindow.ONE_DAY]: [TimePeriod.THIRTY_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. 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. };
  144. componentDidMount() {
  145. if (!isSessionAggregate(this.props.aggregate)) {
  146. this.fetchTotalCount();
  147. }
  148. }
  149. componentDidUpdate(prevProps: Props, prevState: State) {
  150. const {query, environment, timeWindow, aggregate, projects} = this.props;
  151. const {statsPeriod} = this.state;
  152. if (
  153. !isSessionAggregate(aggregate) &&
  154. (!isEqual(prevProps.projects, projects) ||
  155. prevProps.environment !== environment ||
  156. prevProps.query !== query ||
  157. !isEqual(prevProps.timeWindow, timeWindow) ||
  158. !isEqual(prevState.statsPeriod, statsPeriod))
  159. ) {
  160. this.fetchTotalCount();
  161. }
  162. }
  163. get availableTimePeriods() {
  164. // We need to special case sessions, because sub-hour windows are available
  165. // only when time period is six hours or less (backend limitation)
  166. if (isSessionAggregate(this.props.aggregate)) {
  167. return {
  168. ...AVAILABLE_TIME_PERIODS,
  169. [TimeWindow.THIRTY_MINUTES]: [TimePeriod.SIX_HOURS],
  170. };
  171. }
  172. return AVAILABLE_TIME_PERIODS;
  173. }
  174. handleStatsPeriodChange = (timePeriod: string) => {
  175. this.setState({statsPeriod: timePeriod as TimePeriod});
  176. };
  177. getStatsPeriod = () => {
  178. const {statsPeriod} = this.state;
  179. const {timeWindow} = this.props;
  180. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  181. const period = statsPeriodOptions.includes(statsPeriod)
  182. ? statsPeriod
  183. : statsPeriodOptions[statsPeriodOptions.length - 1];
  184. return period;
  185. };
  186. get comparisonSeriesName() {
  187. return capitalize(
  188. COMPARISON_DELTA_OPTIONS.find(({value}) => value === this.props.comparisonDelta)
  189. ?.label || ''
  190. );
  191. }
  192. async fetchTotalCount() {
  193. const {
  194. api,
  195. organization,
  196. location,
  197. newAlertOrQuery,
  198. environment,
  199. projects,
  200. query,
  201. dataset,
  202. } = this.props;
  203. const statsPeriod = this.getStatsPeriod();
  204. const queryExtras = getMetricDatasetQueryExtras({
  205. organization,
  206. location,
  207. dataset,
  208. newAlertOrQuery,
  209. });
  210. const queryDataset = queryExtras.dataset as undefined | DiscoverDatasets;
  211. try {
  212. const totalCount = await fetchTotalCount(api, organization.slug, {
  213. field: [],
  214. project: projects.map(({id}) => id),
  215. query,
  216. statsPeriod,
  217. environment: environment ? [environment] : [],
  218. dataset: queryDataset,
  219. });
  220. this.setState({totalCount});
  221. } catch (e) {
  222. this.setState({totalCount: null});
  223. }
  224. }
  225. renderChart({
  226. isLoading,
  227. isReloading,
  228. timeseriesData = [],
  229. comparisonData,
  230. comparisonMarkLines,
  231. errorMessage,
  232. minutesThresholdToDisplaySeconds,
  233. isQueryValid,
  234. errored,
  235. orgFeatures,
  236. }: {
  237. isLoading: boolean;
  238. isQueryValid: boolean;
  239. isReloading: boolean;
  240. orgFeatures: string[];
  241. timeseriesData: Series[];
  242. comparisonData?: Series[];
  243. comparisonMarkLines?: LineChartSeries[];
  244. errorMessage?: string;
  245. errored?: boolean;
  246. minutesThresholdToDisplaySeconds?: number;
  247. }) {
  248. const {
  249. triggers,
  250. resolveThreshold,
  251. thresholdType,
  252. header,
  253. timeWindow,
  254. aggregate,
  255. comparisonType,
  256. isOnDemandMetricAlert,
  257. } = this.props;
  258. const {statsPeriod, totalCount} = this.state;
  259. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  260. const period = this.getStatsPeriod();
  261. const error = orgFeatures.includes('alert-allow-indexed')
  262. ? errored || errorMessage
  263. : errored || errorMessage || !isQueryValid;
  264. return (
  265. <Fragment>
  266. {header}
  267. <TransparentLoadingMask visible={isReloading} />
  268. {isLoading && !error ? (
  269. <ChartPlaceholder />
  270. ) : isOnDemandMetricAlert ? (
  271. <WarningChart />
  272. ) : error ? (
  273. <ErrorChart
  274. isAllowIndexed={orgFeatures.includes('alert-allow-indexed')}
  275. errorMessage={errorMessage}
  276. isQueryValid={isQueryValid}
  277. />
  278. ) : (
  279. <ThresholdsChart
  280. period={statsPeriod}
  281. minValue={minBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  282. maxValue={maxBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  283. data={timeseriesData}
  284. comparisonData={comparisonData ?? []}
  285. comparisonSeriesName={this.comparisonSeriesName}
  286. comparisonMarkLines={comparisonMarkLines ?? []}
  287. hideThresholdLines={comparisonType === AlertRuleComparisonType.CHANGE}
  288. triggers={triggers}
  289. resolveThreshold={resolveThreshold}
  290. thresholdType={thresholdType}
  291. aggregate={aggregate}
  292. minutesThresholdToDisplaySeconds={minutesThresholdToDisplaySeconds}
  293. />
  294. )}
  295. <ChartControls>
  296. <InlineContainer data-test-id="alert-total-events">
  297. <SectionHeading>
  298. {isSessionAggregate(aggregate)
  299. ? SESSION_AGGREGATE_TO_HEADING[aggregate]
  300. : t('Total Events')}
  301. </SectionHeading>
  302. <SectionValue>
  303. {totalCount !== null ? totalCount.toLocaleString() : '\u2014'}
  304. </SectionValue>
  305. </InlineContainer>
  306. <InlineContainer>
  307. <OptionSelector
  308. options={statsPeriodOptions.map(timePeriod => ({
  309. label: TIME_PERIOD_MAP[timePeriod],
  310. value: timePeriod,
  311. disabled: isLoading || isReloading,
  312. }))}
  313. selected={period}
  314. onChange={this.handleStatsPeriodChange}
  315. title={t('Display')}
  316. disabled={isOnDemandMetricAlert}
  317. />
  318. </InlineContainer>
  319. </ChartControls>
  320. </Fragment>
  321. );
  322. }
  323. render() {
  324. const {
  325. api,
  326. organization,
  327. projects,
  328. timeWindow,
  329. query,
  330. location,
  331. aggregate,
  332. dataset,
  333. newAlertOrQuery,
  334. handleMEPAlertDataset,
  335. environment,
  336. comparisonDelta,
  337. triggers,
  338. thresholdType,
  339. isQueryValid,
  340. isOnDemandMetricAlert,
  341. } = this.props;
  342. const period = this.getStatsPeriod();
  343. const renderComparisonStats = Boolean(
  344. organization.features.includes('change-alerts') && comparisonDelta
  345. );
  346. const queryExtras = getMetricDatasetQueryExtras({
  347. organization,
  348. location,
  349. dataset,
  350. newAlertOrQuery,
  351. });
  352. // Currently we don't have anything to show for on-demand metric alerts
  353. if (isOnDemandMetricAlert) {
  354. return this.renderChart({
  355. timeseriesData: [],
  356. isQueryValid: true,
  357. isLoading: false,
  358. isReloading: false,
  359. orgFeatures: organization.features,
  360. });
  361. }
  362. return isSessionAggregate(aggregate) ? (
  363. <SessionsRequest
  364. api={api}
  365. organization={organization}
  366. project={projects.map(({id}) => Number(id))}
  367. environment={environment ? [environment] : undefined}
  368. statsPeriod={period}
  369. query={query}
  370. interval={TIME_WINDOW_TO_SESSION_INTERVAL[timeWindow]}
  371. field={SESSION_AGGREGATE_TO_FIELD[aggregate]}
  372. groupBy={['session.status']}
  373. >
  374. {({loading, errored, reloading, response}) => {
  375. const {groups, intervals} = response || {};
  376. const sessionTimeSeries = [
  377. {
  378. seriesName:
  379. AlertWizardAlertNames[
  380. getAlertTypeFromAggregateDataset({aggregate, dataset: Dataset.SESSIONS})
  381. ],
  382. data: getCrashFreeRateSeries(
  383. groups,
  384. intervals,
  385. SESSION_AGGREGATE_TO_FIELD[aggregate]
  386. ),
  387. },
  388. ];
  389. return this.renderChart({
  390. timeseriesData: sessionTimeSeries,
  391. isLoading: loading,
  392. isReloading: reloading,
  393. comparisonData: undefined,
  394. comparisonMarkLines: undefined,
  395. minutesThresholdToDisplaySeconds: MINUTES_THRESHOLD_TO_DISPLAY_SECONDS,
  396. isQueryValid,
  397. errored,
  398. orgFeatures: organization.features,
  399. });
  400. }}
  401. </SessionsRequest>
  402. ) : (
  403. <EventsRequest
  404. api={api}
  405. organization={organization}
  406. query={query}
  407. environment={environment ? [environment] : undefined}
  408. project={projects.map(({id}) => Number(id))}
  409. interval={`${timeWindow}m`}
  410. comparisonDelta={comparisonDelta && comparisonDelta * 60}
  411. period={period}
  412. yAxis={aggregate}
  413. includePrevious={false}
  414. currentSeriesNames={[aggregate]}
  415. partial={false}
  416. queryExtras={queryExtras}
  417. dataLoadedCallback={handleMEPAlertDataset}
  418. useOnDemandMetrics={isOnDemandMetricAlert}
  419. >
  420. {({
  421. loading,
  422. errored,
  423. errorMessage,
  424. reloading,
  425. timeseriesData,
  426. comparisonTimeseriesData,
  427. }) => {
  428. let comparisonMarkLines: LineChartSeries[] = [];
  429. if (renderComparisonStats && comparisonTimeseriesData) {
  430. comparisonMarkLines = getComparisonMarkLines(
  431. timeseriesData,
  432. comparisonTimeseriesData,
  433. timeWindow,
  434. triggers,
  435. thresholdType
  436. );
  437. }
  438. return this.renderChart({
  439. timeseriesData: timeseriesData as Series[],
  440. isLoading: loading,
  441. isReloading: reloading,
  442. comparisonData: comparisonTimeseriesData,
  443. comparisonMarkLines,
  444. errorMessage,
  445. isQueryValid,
  446. errored,
  447. orgFeatures: organization.features,
  448. });
  449. }}
  450. </EventsRequest>
  451. );
  452. }
  453. }
  454. export default withApi(TriggersChart);
  455. const TransparentLoadingMask = styled(LoadingMask)<{visible: boolean}>`
  456. ${p => !p.visible && 'display: none;'};
  457. opacity: 0.4;
  458. z-index: 1;
  459. `;
  460. const ChartPlaceholder = styled(Placeholder)`
  461. /* Height and margin should add up to graph size (200px) */
  462. margin: 0 0 ${space(2)};
  463. height: 184px;
  464. `;
  465. const StyledErrorPanel = styled(ErrorPanel)`
  466. /* Height and margin should with the alert should match up placeholder height of (184px) */
  467. padding: ${space(2)};
  468. height: 119px;
  469. `;
  470. const ChartErrorWrapper = styled('div')`
  471. margin-top: ${space(2)};
  472. `;
  473. function ErrorChart({isAllowIndexed, isQueryValid, errorMessage}) {
  474. return (
  475. <ChartErrorWrapper>
  476. <PanelAlert type="error">
  477. {!isAllowIndexed && !isQueryValid
  478. ? t('Your filter conditions contain an unsupported field - please review.')
  479. : typeof errorMessage === 'string'
  480. ? errorMessage
  481. : t('An error occurred while fetching data')}
  482. </PanelAlert>
  483. <StyledErrorPanel>
  484. <IconWarning color="gray500" size="lg" />
  485. </StyledErrorPanel>
  486. </ChartErrorWrapper>
  487. );
  488. }
  489. function WarningChart() {
  490. return (
  491. <ChartErrorWrapper>
  492. <PanelAlert type="info">
  493. {t(
  494. 'Selected filters include advanced conditions, which is a feature that is currently in early access. We will start collecting data for the chart once this alert rule is saved.'
  495. )}
  496. </PanelAlert>
  497. <StyledErrorPanel>
  498. <IconSettings color="gray500" size="lg" />
  499. </StyledErrorPanel>
  500. </ChartErrorWrapper>
  501. );
  502. }