index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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';
  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 {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. };
  76. const TIME_PERIOD_MAP: Record<TimePeriod, string> = {
  77. [TimePeriod.SIX_HOURS]: t('Last 6 hours'),
  78. [TimePeriod.ONE_DAY]: t('Last 24 hours'),
  79. [TimePeriod.THREE_DAYS]: t('Last 3 days'),
  80. [TimePeriod.SEVEN_DAYS]: t('Last 7 days'),
  81. [TimePeriod.FOURTEEN_DAYS]: t('Last 14 days'),
  82. [TimePeriod.THIRTY_DAYS]: t('Last 30 days'),
  83. };
  84. /**
  85. * Just to avoid repeating it
  86. */
  87. const MOST_TIME_PERIODS: readonly TimePeriod[] = [
  88. TimePeriod.ONE_DAY,
  89. TimePeriod.THREE_DAYS,
  90. TimePeriod.SEVEN_DAYS,
  91. TimePeriod.FOURTEEN_DAYS,
  92. TimePeriod.THIRTY_DAYS,
  93. ];
  94. /**
  95. * TimeWindow determines data available in TimePeriod
  96. * If TimeWindow is small, lower TimePeriod to limit data points
  97. */
  98. const AVAILABLE_TIME_PERIODS: Record<TimeWindow, readonly TimePeriod[]> = {
  99. [TimeWindow.ONE_MINUTE]: [
  100. TimePeriod.SIX_HOURS,
  101. TimePeriod.ONE_DAY,
  102. TimePeriod.THREE_DAYS,
  103. TimePeriod.SEVEN_DAYS,
  104. ],
  105. [TimeWindow.FIVE_MINUTES]: MOST_TIME_PERIODS,
  106. [TimeWindow.TEN_MINUTES]: MOST_TIME_PERIODS,
  107. [TimeWindow.FIFTEEN_MINUTES]: MOST_TIME_PERIODS,
  108. [TimeWindow.THIRTY_MINUTES]: MOST_TIME_PERIODS,
  109. [TimeWindow.ONE_HOUR]: MOST_TIME_PERIODS,
  110. [TimeWindow.TWO_HOURS]: MOST_TIME_PERIODS,
  111. [TimeWindow.FOUR_HOURS]: [
  112. TimePeriod.THREE_DAYS,
  113. TimePeriod.SEVEN_DAYS,
  114. TimePeriod.FOURTEEN_DAYS,
  115. TimePeriod.THIRTY_DAYS,
  116. ],
  117. [TimeWindow.ONE_DAY]: [TimePeriod.THIRTY_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. statsPeriod: TimePeriod;
  132. totalCount: number | null;
  133. };
  134. /**
  135. * This is a chart to be used in Metric Alert rules that fetches events based on
  136. * query, timewindow, and aggregations.
  137. */
  138. class TriggersChart extends PureComponent<Props, State> {
  139. state: State = {
  140. statsPeriod: TimePeriod.SEVEN_DAYS,
  141. totalCount: null,
  142. };
  143. componentDidMount() {
  144. if (!isSessionAggregate(this.props.aggregate)) {
  145. this.fetchTotalCount();
  146. }
  147. }
  148. componentDidUpdate(prevProps: Props, prevState: State) {
  149. const {query, environment, timeWindow, aggregate, projects} = this.props;
  150. const {statsPeriod} = this.state;
  151. if (
  152. !isSessionAggregate(aggregate) &&
  153. (!isEqual(prevProps.projects, projects) ||
  154. prevProps.environment !== environment ||
  155. prevProps.query !== query ||
  156. !isEqual(prevProps.timeWindow, timeWindow) ||
  157. !isEqual(prevState.statsPeriod, statsPeriod))
  158. ) {
  159. this.fetchTotalCount();
  160. }
  161. }
  162. get availableTimePeriods() {
  163. // We need to special case sessions, because sub-hour windows are available
  164. // only when time period is six hours or less (backend limitation)
  165. if (isSessionAggregate(this.props.aggregate)) {
  166. return {
  167. ...AVAILABLE_TIME_PERIODS,
  168. [TimeWindow.THIRTY_MINUTES]: [TimePeriod.SIX_HOURS],
  169. };
  170. }
  171. return AVAILABLE_TIME_PERIODS;
  172. }
  173. handleStatsPeriodChange = (timePeriod: string) => {
  174. this.setState({statsPeriod: timePeriod as TimePeriod});
  175. };
  176. getStatsPeriod = () => {
  177. const {statsPeriod} = this.state;
  178. const {timeWindow} = this.props;
  179. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  180. const period = statsPeriodOptions.includes(statsPeriod)
  181. ? statsPeriod
  182. : statsPeriodOptions[statsPeriodOptions.length - 1];
  183. return period;
  184. };
  185. get comparisonSeriesName() {
  186. return capitalize(
  187. COMPARISON_DELTA_OPTIONS.find(({value}) => value === this.props.comparisonDelta)
  188. ?.label || ''
  189. );
  190. }
  191. async fetchTotalCount() {
  192. const {
  193. api,
  194. organization,
  195. location,
  196. newAlertOrQuery,
  197. environment,
  198. projects,
  199. query,
  200. dataset,
  201. } = this.props;
  202. const statsPeriod = this.getStatsPeriod();
  203. const queryExtras = getMetricDatasetQueryExtras({
  204. organization,
  205. location,
  206. dataset,
  207. newAlertOrQuery,
  208. });
  209. const queryDataset = queryExtras.dataset as undefined | DiscoverDatasets;
  210. try {
  211. const totalCount = await fetchTotalCount(api, organization.slug, {
  212. field: [],
  213. project: projects.map(({id}) => id),
  214. query,
  215. statsPeriod,
  216. environment: environment ? [environment] : [],
  217. dataset: queryDataset,
  218. });
  219. this.setState({totalCount});
  220. } catch (e) {
  221. this.setState({totalCount: null});
  222. }
  223. }
  224. renderChart({
  225. isLoading,
  226. isReloading,
  227. timeseriesData = [],
  228. comparisonData,
  229. comparisonMarkLines,
  230. errorMessage,
  231. minutesThresholdToDisplaySeconds,
  232. isQueryValid,
  233. errored,
  234. orgFeatures,
  235. }: {
  236. isLoading: boolean;
  237. isQueryValid: boolean;
  238. isReloading: boolean;
  239. orgFeatures: string[];
  240. timeseriesData: Series[];
  241. comparisonData?: Series[];
  242. comparisonMarkLines?: LineChartSeries[];
  243. errorMessage?: string;
  244. errored?: boolean;
  245. minutesThresholdToDisplaySeconds?: number;
  246. }) {
  247. const {
  248. triggers,
  249. resolveThreshold,
  250. thresholdType,
  251. header,
  252. timeWindow,
  253. aggregate,
  254. comparisonType,
  255. } = this.props;
  256. const {statsPeriod, totalCount} = this.state;
  257. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  258. const period = this.getStatsPeriod();
  259. const error = orgFeatures.includes('alert-allow-indexed')
  260. ? errored || errorMessage
  261. : errored || errorMessage || !isQueryValid;
  262. return (
  263. <Fragment>
  264. {header}
  265. <TransparentLoadingMask visible={isReloading} />
  266. {isLoading && !error ? (
  267. <ChartPlaceholder />
  268. ) : error ? (
  269. <ChartErrorWrapper>
  270. <PanelAlert type="error">
  271. {!orgFeatures.includes('alert-allow-indexed') && !isQueryValid
  272. ? t(
  273. 'Your filter conditions contain an unsupported field - please review.'
  274. )
  275. : typeof errorMessage === 'string'
  276. ? errorMessage
  277. : t('An error occurred while fetching data')}
  278. </PanelAlert>
  279. <StyledErrorPanel>
  280. <IconWarning color="gray500" size="lg" />
  281. </StyledErrorPanel>
  282. </ChartErrorWrapper>
  283. ) : (
  284. <ThresholdsChart
  285. period={statsPeriod}
  286. minValue={minBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  287. maxValue={maxBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  288. data={timeseriesData}
  289. comparisonData={comparisonData ?? []}
  290. comparisonSeriesName={this.comparisonSeriesName}
  291. comparisonMarkLines={comparisonMarkLines ?? []}
  292. hideThresholdLines={comparisonType === AlertRuleComparisonType.CHANGE}
  293. triggers={triggers}
  294. resolveThreshold={resolveThreshold}
  295. thresholdType={thresholdType}
  296. aggregate={aggregate}
  297. minutesThresholdToDisplaySeconds={minutesThresholdToDisplaySeconds}
  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. handleMEPAlertDataset,
  339. environment,
  340. comparisonDelta,
  341. triggers,
  342. thresholdType,
  343. isQueryValid,
  344. } = this.props;
  345. const period = this.getStatsPeriod();
  346. const renderComparisonStats = Boolean(
  347. organization.features.includes('change-alerts') && comparisonDelta
  348. );
  349. const queryExtras = getMetricDatasetQueryExtras({
  350. organization,
  351. location,
  352. dataset,
  353. newAlertOrQuery,
  354. });
  355. return isSessionAggregate(aggregate) ? (
  356. <SessionsRequest
  357. api={api}
  358. organization={organization}
  359. project={projects.map(({id}) => Number(id))}
  360. environment={environment ? [environment] : undefined}
  361. statsPeriod={period}
  362. query={query}
  363. interval={TIME_WINDOW_TO_SESSION_INTERVAL[timeWindow]}
  364. field={SESSION_AGGREGATE_TO_FIELD[aggregate]}
  365. groupBy={['session.status']}
  366. >
  367. {({loading, errored, reloading, response}) => {
  368. const {groups, intervals} = response || {};
  369. const sessionTimeSeries = [
  370. {
  371. seriesName:
  372. AlertWizardAlertNames[
  373. getAlertTypeFromAggregateDataset({aggregate, dataset: Dataset.SESSIONS})
  374. ],
  375. data: getCrashFreeRateSeries(
  376. groups,
  377. intervals,
  378. SESSION_AGGREGATE_TO_FIELD[aggregate]
  379. ),
  380. },
  381. ];
  382. return this.renderChart({
  383. timeseriesData: sessionTimeSeries,
  384. isLoading: loading,
  385. isReloading: reloading,
  386. comparisonData: undefined,
  387. comparisonMarkLines: undefined,
  388. minutesThresholdToDisplaySeconds: MINUTES_THRESHOLD_TO_DISPLAY_SECONDS,
  389. isQueryValid,
  390. errored,
  391. orgFeatures: organization.features,
  392. });
  393. }}
  394. </SessionsRequest>
  395. ) : (
  396. <EventsRequest
  397. api={api}
  398. organization={organization}
  399. query={query}
  400. environment={environment ? [environment] : undefined}
  401. project={projects.map(({id}) => Number(id))}
  402. interval={`${timeWindow}m`}
  403. comparisonDelta={comparisonDelta && comparisonDelta * 60}
  404. period={period}
  405. yAxis={aggregate}
  406. includePrevious={false}
  407. currentSeriesNames={[aggregate]}
  408. partial={false}
  409. queryExtras={queryExtras}
  410. dataLoadedCallback={handleMEPAlertDataset}
  411. >
  412. {({
  413. loading,
  414. errored,
  415. errorMessage,
  416. reloading,
  417. timeseriesData,
  418. comparisonTimeseriesData,
  419. }) => {
  420. let comparisonMarkLines: LineChartSeries[] = [];
  421. if (renderComparisonStats && comparisonTimeseriesData) {
  422. comparisonMarkLines = getComparisonMarkLines(
  423. timeseriesData,
  424. comparisonTimeseriesData,
  425. timeWindow,
  426. triggers,
  427. thresholdType
  428. );
  429. }
  430. return this.renderChart({
  431. timeseriesData: timeseriesData as Series[],
  432. isLoading: loading,
  433. isReloading: reloading,
  434. comparisonData: comparisonTimeseriesData,
  435. comparisonMarkLines,
  436. errorMessage,
  437. isQueryValid,
  438. errored,
  439. orgFeatures: organization.features,
  440. });
  441. }}
  442. </EventsRequest>
  443. );
  444. }
  445. }
  446. export default withApi(TriggersChart);
  447. const TransparentLoadingMask = styled(LoadingMask)<{visible: boolean}>`
  448. ${p => !p.visible && 'display: none;'};
  449. opacity: 0.4;
  450. z-index: 1;
  451. `;
  452. const ChartPlaceholder = styled(Placeholder)`
  453. /* Height and margin should add up to graph size (200px) */
  454. margin: 0 0 ${space(2)};
  455. height: 184px;
  456. `;
  457. const StyledErrorPanel = styled(ErrorPanel)`
  458. padding: ${space(2)};
  459. `;
  460. const ChartErrorWrapper = styled('div')`
  461. margin-top: ${space(2)};
  462. `;