index.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. import {type ComponentProps, Fragment, PureComponent} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Location} from 'history';
  4. import isEqual from 'lodash/isEqual';
  5. import maxBy from 'lodash/maxBy';
  6. import minBy from 'lodash/minBy';
  7. import {fetchTotalCount} from 'sentry/actionCreators/events';
  8. import {Client} from 'sentry/api';
  9. import ErrorPanel from 'sentry/components/charts/errorPanel';
  10. import EventsRequest, {
  11. type EventsRequestProps,
  12. } from 'sentry/components/charts/eventsRequest';
  13. import type {LineChartSeries} from 'sentry/components/charts/lineChart';
  14. import {OnDemandMetricRequest} from 'sentry/components/charts/onDemandMetricRequest';
  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 {CompactSelect} from 'sentry/components/compactSelect';
  23. import LoadingMask from 'sentry/components/loadingMask';
  24. import PanelAlert from 'sentry/components/panels/panelAlert';
  25. import Placeholder from 'sentry/components/placeholder';
  26. import {IconWarning} from 'sentry/icons';
  27. import {t} from 'sentry/locale';
  28. import {space} from 'sentry/styles/space';
  29. import type {Series} from 'sentry/types/echarts';
  30. import type {
  31. EventsStats,
  32. MultiSeriesEventsStats,
  33. Organization,
  34. } from 'sentry/types/organization';
  35. import type {Project} from 'sentry/types/project';
  36. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  37. import {parsePeriodToHours} from 'sentry/utils/duration/parsePeriodToHours';
  38. import {getForceMetricsLayerQueryExtras} from 'sentry/utils/metrics/features';
  39. import {shouldShowOnDemandMetricAlertUI} from 'sentry/utils/onDemandMetrics/features';
  40. import {
  41. getCrashFreeRateSeries,
  42. MINUTES_THRESHOLD_TO_DISPLAY_SECONDS,
  43. } from 'sentry/utils/sessions';
  44. import {capitalize} from 'sentry/utils/string/capitalize';
  45. import withApi from 'sentry/utils/withApi';
  46. import {COMPARISON_DELTA_OPTIONS} from 'sentry/views/alerts/rules/metric/constants';
  47. import {shouldUseErrorsDiscoverDataset} from 'sentry/views/alerts/rules/utils';
  48. import type {Anomaly} from 'sentry/views/alerts/types';
  49. import {isSessionAggregate, SESSION_AGGREGATE_TO_FIELD} from 'sentry/views/alerts/utils';
  50. import {getComparisonMarkLines} from 'sentry/views/alerts/utils/getComparisonMarkLines';
  51. import {AlertWizardAlertNames} from 'sentry/views/alerts/wizard/options';
  52. import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
  53. import type {MetricRule, Trigger} from '../../types';
  54. import {
  55. AlertRuleComparisonType,
  56. Dataset,
  57. SessionsAggregate,
  58. TimePeriod,
  59. TimeWindow,
  60. } from '../../types';
  61. import {getMetricDatasetQueryExtras} from '../../utils/getMetricDatasetQueryExtras';
  62. import ThresholdsChart from './thresholdsChart';
  63. type Props = {
  64. aggregate: MetricRule['aggregate'];
  65. api: Client;
  66. comparisonType: AlertRuleComparisonType;
  67. dataset: MetricRule['dataset'];
  68. environment: string | null;
  69. isQueryValid: boolean;
  70. location: Location;
  71. newAlertOrQuery: boolean;
  72. organization: Organization;
  73. projects: Project[];
  74. query: MetricRule['query'];
  75. resolveThreshold: MetricRule['resolveThreshold'];
  76. thresholdType: MetricRule['thresholdType'];
  77. timeWindow: MetricRule['timeWindow'];
  78. triggers: Trigger[];
  79. anomalies?: Anomaly[];
  80. comparisonDelta?: number;
  81. formattedAggregate?: string;
  82. header?: React.ReactNode;
  83. includeConfidence?: boolean;
  84. includeHistorical?: boolean;
  85. isOnDemandMetricAlert?: boolean;
  86. onConfidenceDataLoaded?: (data: EventsStats | MultiSeriesEventsStats | null) => void;
  87. onDataLoaded?: (data: EventsStats | MultiSeriesEventsStats | null) => void;
  88. onHistoricalDataLoaded?: (data: EventsStats | MultiSeriesEventsStats | null) => void;
  89. showTotalCount?: boolean;
  90. };
  91. type TimePeriodMap = Omit<Record<TimePeriod, string>, TimePeriod.TWENTY_EIGHT_DAYS>;
  92. const TIME_PERIOD_MAP: TimePeriodMap = {
  93. [TimePeriod.SIX_HOURS]: t('Last 6 hours'),
  94. [TimePeriod.ONE_DAY]: t('Last 24 hours'),
  95. [TimePeriod.THREE_DAYS]: t('Last 3 days'),
  96. [TimePeriod.SEVEN_DAYS]: t('Last 7 days'),
  97. [TimePeriod.FOURTEEN_DAYS]: t('Last 14 days'),
  98. };
  99. /**
  100. * Just to avoid repeating it
  101. */
  102. const MOST_TIME_PERIODS: readonly TimePeriod[] = [
  103. TimePeriod.ONE_DAY,
  104. TimePeriod.THREE_DAYS,
  105. TimePeriod.SEVEN_DAYS,
  106. TimePeriod.FOURTEEN_DAYS,
  107. ];
  108. /**
  109. * TimeWindow determines data available in TimePeriod
  110. * If TimeWindow is small, lower TimePeriod to limit data points
  111. */
  112. export const AVAILABLE_TIME_PERIODS: Record<TimeWindow, readonly TimePeriod[]> = {
  113. [TimeWindow.ONE_MINUTE]: [
  114. TimePeriod.SIX_HOURS,
  115. TimePeriod.ONE_DAY,
  116. TimePeriod.THREE_DAYS,
  117. TimePeriod.SEVEN_DAYS,
  118. ],
  119. [TimeWindow.FIVE_MINUTES]: MOST_TIME_PERIODS,
  120. [TimeWindow.TEN_MINUTES]: MOST_TIME_PERIODS,
  121. [TimeWindow.FIFTEEN_MINUTES]: MOST_TIME_PERIODS,
  122. [TimeWindow.THIRTY_MINUTES]: MOST_TIME_PERIODS,
  123. [TimeWindow.ONE_HOUR]: MOST_TIME_PERIODS,
  124. [TimeWindow.TWO_HOURS]: MOST_TIME_PERIODS,
  125. [TimeWindow.FOUR_HOURS]: [
  126. TimePeriod.THREE_DAYS,
  127. TimePeriod.SEVEN_DAYS,
  128. TimePeriod.FOURTEEN_DAYS,
  129. ],
  130. [TimeWindow.ONE_DAY]: [TimePeriod.FOURTEEN_DAYS],
  131. };
  132. const MOST_EAP_TIME_PERIOD = [
  133. TimePeriod.ONE_DAY,
  134. TimePeriod.THREE_DAYS,
  135. TimePeriod.SEVEN_DAYS,
  136. ];
  137. const EAP_AVAILABLE_TIME_PERIODS = {
  138. [TimeWindow.ONE_MINUTE]: [], // One minute intervals are not allowed on EAP Alerts
  139. [TimeWindow.FIVE_MINUTES]: MOST_EAP_TIME_PERIOD,
  140. [TimeWindow.TEN_MINUTES]: MOST_EAP_TIME_PERIOD,
  141. [TimeWindow.FIFTEEN_MINUTES]: MOST_EAP_TIME_PERIOD,
  142. [TimeWindow.THIRTY_MINUTES]: MOST_EAP_TIME_PERIOD,
  143. [TimeWindow.ONE_HOUR]: MOST_EAP_TIME_PERIOD,
  144. [TimeWindow.TWO_HOURS]: MOST_EAP_TIME_PERIOD,
  145. [TimeWindow.FOUR_HOURS]: [TimePeriod.SEVEN_DAYS],
  146. [TimeWindow.ONE_DAY]: [TimePeriod.SEVEN_DAYS],
  147. };
  148. export const TIME_WINDOW_TO_INTERVAL = {
  149. [TimeWindow.FIVE_MINUTES]: '5m',
  150. [TimeWindow.TEN_MINUTES]: '10m',
  151. [TimeWindow.FIFTEEN_MINUTES]: '15m',
  152. [TimeWindow.THIRTY_MINUTES]: '30m',
  153. [TimeWindow.ONE_HOUR]: '1h',
  154. [TimeWindow.TWO_HOURS]: '2h',
  155. [TimeWindow.FOUR_HOURS]: '4h',
  156. [TimeWindow.ONE_DAY]: '1d',
  157. };
  158. const SESSION_AGGREGATE_TO_HEADING = {
  159. [SessionsAggregate.CRASH_FREE_SESSIONS]: t('Total Sessions'),
  160. [SessionsAggregate.CRASH_FREE_USERS]: t('Total Users'),
  161. };
  162. const HISTORICAL_TIME_PERIOD_MAP: TimePeriodMap = {
  163. [TimePeriod.SIX_HOURS]: '678h',
  164. [TimePeriod.ONE_DAY]: '29d',
  165. [TimePeriod.THREE_DAYS]: '31d',
  166. [TimePeriod.SEVEN_DAYS]: '35d',
  167. [TimePeriod.FOURTEEN_DAYS]: '42d',
  168. };
  169. const HISTORICAL_TIME_PERIOD_MAP_FIVE_MINS: TimePeriodMap = {
  170. ...HISTORICAL_TIME_PERIOD_MAP,
  171. [TimePeriod.SEVEN_DAYS]: '28d', // fetching 28 + 7 days of historical data at 5 minute increments exceeds the max number of data points that snuba can return
  172. [TimePeriod.FOURTEEN_DAYS]: '28d', // fetching 28 + 14 days of historical data at 5 minute increments exceeds the max number of data points that snuba can return
  173. };
  174. const noop: any = () => {};
  175. type State = {
  176. sampleRate: number;
  177. statsPeriod: TimePeriod;
  178. totalCount: number | null;
  179. };
  180. const getStatsPeriodFromQuery = (
  181. queryParam: string | string[] | null | undefined
  182. ): TimePeriod => {
  183. if (typeof queryParam !== 'string') {
  184. return TimePeriod.SEVEN_DAYS;
  185. }
  186. const inMinutes = parsePeriodToHours(queryParam || '') * 60;
  187. switch (inMinutes) {
  188. case 6 * 60:
  189. return TimePeriod.SIX_HOURS;
  190. case 24 * 60:
  191. return TimePeriod.ONE_DAY;
  192. case 3 * 24 * 60:
  193. return TimePeriod.THREE_DAYS;
  194. case 9999:
  195. return TimePeriod.SEVEN_DAYS;
  196. case 14 * 24 * 60:
  197. return TimePeriod.FOURTEEN_DAYS;
  198. default:
  199. return TimePeriod.SEVEN_DAYS;
  200. }
  201. };
  202. /**
  203. * This is a chart to be used in Metric Alert rules that fetches events based on
  204. * query, timewindow, and aggregations.
  205. */
  206. class TriggersChart extends PureComponent<Props, State> {
  207. state: State = {
  208. statsPeriod: getStatsPeriodFromQuery(this.props.location.query.statsPeriod),
  209. totalCount: null,
  210. sampleRate: 1,
  211. };
  212. componentDidMount() {
  213. const {aggregate, showTotalCount} = this.props;
  214. if (showTotalCount && !isSessionAggregate(aggregate)) {
  215. this.fetchTotalCount();
  216. }
  217. }
  218. componentDidUpdate(prevProps: Props, prevState: State) {
  219. const {query, environment, timeWindow, aggregate, projects, showTotalCount} =
  220. this.props;
  221. const {statsPeriod} = this.state;
  222. if (
  223. showTotalCount &&
  224. !isSessionAggregate(aggregate) &&
  225. (!isEqual(prevProps.projects, projects) ||
  226. prevProps.environment !== environment ||
  227. prevProps.query !== query ||
  228. !isEqual(prevProps.timeWindow, timeWindow) ||
  229. !isEqual(prevState.statsPeriod, statsPeriod))
  230. ) {
  231. this.fetchTotalCount();
  232. }
  233. }
  234. // Create new API Client so that historical requests aren't automatically deduplicated
  235. historicalAPI = new Client();
  236. confidenceAPI = new Client();
  237. get availableTimePeriods() {
  238. // We need to special case sessions, because sub-hour windows are available
  239. // only when time period is six hours or less (backend limitation)
  240. if (isSessionAggregate(this.props.aggregate)) {
  241. return {
  242. ...AVAILABLE_TIME_PERIODS,
  243. [TimeWindow.THIRTY_MINUTES]: [TimePeriod.SIX_HOURS],
  244. };
  245. }
  246. if (this.props.dataset === Dataset.EVENTS_ANALYTICS_PLATFORM) {
  247. return EAP_AVAILABLE_TIME_PERIODS;
  248. }
  249. return AVAILABLE_TIME_PERIODS;
  250. }
  251. handleStatsPeriodChange = (timePeriod: TimePeriod) => {
  252. this.setState({statsPeriod: timePeriod});
  253. };
  254. getStatsPeriod = () => {
  255. const {statsPeriod} = this.state;
  256. const {timeWindow} = this.props;
  257. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  258. const period = statsPeriodOptions.includes(statsPeriod)
  259. ? statsPeriod
  260. : statsPeriodOptions[statsPeriodOptions.length - 1];
  261. return period;
  262. };
  263. get comparisonSeriesName() {
  264. return capitalize(
  265. COMPARISON_DELTA_OPTIONS.find(({value}) => value === this.props.comparisonDelta)
  266. ?.label || ''
  267. );
  268. }
  269. async fetchTotalCount() {
  270. const {
  271. api,
  272. organization,
  273. location,
  274. newAlertOrQuery,
  275. environment,
  276. projects,
  277. query,
  278. dataset,
  279. } = this.props;
  280. const statsPeriod = this.getStatsPeriod();
  281. const queryExtras = getMetricDatasetQueryExtras({
  282. organization,
  283. location,
  284. dataset,
  285. newAlertOrQuery,
  286. });
  287. let queryDataset = queryExtras.dataset as undefined | DiscoverDatasets;
  288. const queryOverride = (queryExtras.query as string | undefined) ?? query;
  289. if (shouldUseErrorsDiscoverDataset(query, dataset, organization)) {
  290. queryDataset = DiscoverDatasets.ERRORS;
  291. }
  292. try {
  293. const totalCount = await fetchTotalCount(api, organization.slug, {
  294. field: [],
  295. project: projects.map(({id}) => id),
  296. query: queryOverride,
  297. statsPeriod,
  298. environment: environment ? [environment] : [],
  299. dataset: queryDataset,
  300. ...getForceMetricsLayerQueryExtras(organization, dataset),
  301. });
  302. this.setState({totalCount});
  303. } catch (e) {
  304. this.setState({totalCount: null});
  305. }
  306. }
  307. renderChart({
  308. isLoading,
  309. isReloading,
  310. timeseriesData = [],
  311. comparisonData,
  312. comparisonMarkLines,
  313. errorMessage,
  314. minutesThresholdToDisplaySeconds,
  315. isQueryValid,
  316. errored,
  317. orgFeatures,
  318. seriesAdditionalInfo,
  319. }: {
  320. isLoading: boolean;
  321. isQueryValid: boolean;
  322. isReloading: boolean;
  323. orgFeatures: string[];
  324. timeseriesData: Series[];
  325. comparisonData?: Series[];
  326. comparisonMarkLines?: LineChartSeries[];
  327. errorMessage?: string;
  328. errored?: boolean;
  329. minutesThresholdToDisplaySeconds?: number;
  330. seriesAdditionalInfo?: Record<string, any>;
  331. }) {
  332. const {
  333. triggers,
  334. resolveThreshold,
  335. thresholdType,
  336. header,
  337. timeWindow,
  338. aggregate,
  339. comparisonType,
  340. organization,
  341. showTotalCount,
  342. anomalies = [],
  343. } = this.props;
  344. const {statsPeriod, totalCount} = this.state;
  345. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  346. const period = this.getStatsPeriod();
  347. const error = orgFeatures.includes('alert-allow-indexed')
  348. ? errored || errorMessage
  349. : errored || errorMessage || !isQueryValid;
  350. const showExtrapolatedChartData =
  351. shouldShowOnDemandMetricAlertUI(organization) &&
  352. seriesAdditionalInfo?.[timeseriesData[0]!?.seriesName]?.isExtrapolatedData;
  353. const totalCountLabel = isSessionAggregate(aggregate)
  354. ? SESSION_AGGREGATE_TO_HEADING[aggregate]
  355. : showExtrapolatedChartData
  356. ? t('Estimated Transactions')
  357. : t('Total');
  358. return (
  359. <Fragment>
  360. {header}
  361. <TransparentLoadingMask visible={isReloading} />
  362. {isLoading && !error ? (
  363. <ChartPlaceholder />
  364. ) : error ? (
  365. <ErrorChart
  366. isAllowIndexed={orgFeatures.includes('alert-allow-indexed')}
  367. errorMessage={errorMessage}
  368. isQueryValid={isQueryValid}
  369. />
  370. ) : (
  371. <ThresholdsChart
  372. period={statsPeriod}
  373. minValue={minBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  374. maxValue={maxBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  375. data={timeseriesData}
  376. comparisonData={comparisonData ?? []}
  377. comparisonSeriesName={this.comparisonSeriesName}
  378. comparisonMarkLines={comparisonMarkLines ?? []}
  379. hideThresholdLines={comparisonType !== AlertRuleComparisonType.COUNT}
  380. triggers={triggers}
  381. anomalies={anomalies}
  382. resolveThreshold={resolveThreshold}
  383. thresholdType={thresholdType}
  384. aggregate={aggregate}
  385. minutesThresholdToDisplaySeconds={minutesThresholdToDisplaySeconds}
  386. isExtrapolatedData={showExtrapolatedChartData}
  387. />
  388. )}
  389. <ChartControls>
  390. {showTotalCount ? (
  391. <InlineContainer data-test-id="alert-total-events">
  392. <SectionHeading>{totalCountLabel}</SectionHeading>
  393. <SectionValue>
  394. {totalCount !== null ? totalCount.toLocaleString() : '\u2014'}
  395. </SectionValue>
  396. </InlineContainer>
  397. ) : (
  398. <InlineContainer />
  399. )}
  400. <InlineContainer>
  401. <CompactSelect
  402. size="sm"
  403. options={statsPeriodOptions.map(timePeriod => ({
  404. value: timePeriod,
  405. label: TIME_PERIOD_MAP[timePeriod],
  406. }))}
  407. value={period}
  408. onChange={opt => this.handleStatsPeriodChange(opt.value)}
  409. position="bottom-end"
  410. triggerProps={{
  411. borderless: true,
  412. prefix: t('Display'),
  413. }}
  414. />
  415. </InlineContainer>
  416. </ChartControls>
  417. </Fragment>
  418. );
  419. }
  420. render() {
  421. const {
  422. api,
  423. organization,
  424. projects,
  425. timeWindow,
  426. query,
  427. location,
  428. aggregate,
  429. dataset,
  430. newAlertOrQuery,
  431. onDataLoaded,
  432. onHistoricalDataLoaded,
  433. environment,
  434. formattedAggregate,
  435. comparisonDelta,
  436. triggers,
  437. thresholdType,
  438. isQueryValid,
  439. isOnDemandMetricAlert,
  440. onConfidenceDataLoaded,
  441. } = this.props;
  442. const period = this.getStatsPeriod()!;
  443. const renderComparisonStats = Boolean(
  444. organization.features.includes('change-alerts') && comparisonDelta
  445. );
  446. const queryExtras = {
  447. ...getMetricDatasetQueryExtras({
  448. organization,
  449. location,
  450. dataset,
  451. newAlertOrQuery,
  452. }),
  453. ...getForceMetricsLayerQueryExtras(organization, dataset),
  454. ...(shouldUseErrorsDiscoverDataset(query, dataset, organization)
  455. ? {dataset: DiscoverDatasets.ERRORS}
  456. : {}),
  457. };
  458. if (isOnDemandMetricAlert) {
  459. const {sampleRate} = this.state;
  460. const baseProps: EventsRequestProps = {
  461. api,
  462. organization,
  463. query,
  464. queryExtras,
  465. sampleRate,
  466. period,
  467. environment: environment ? [environment] : undefined,
  468. project: projects.map(({id}) => Number(id)),
  469. interval: `${timeWindow}m`,
  470. comparisonDelta: comparisonDelta ? comparisonDelta * 60 : undefined,
  471. yAxis: aggregate,
  472. includePrevious: false,
  473. currentSeriesNames: [formattedAggregate || aggregate],
  474. partial: false,
  475. limit: 15,
  476. children: noop,
  477. };
  478. return (
  479. <Fragment>
  480. {this.props.includeHistorical ? (
  481. <OnDemandMetricRequest
  482. {...baseProps}
  483. api={this.historicalAPI}
  484. period={
  485. timeWindow === 5
  486. ? HISTORICAL_TIME_PERIOD_MAP_FIVE_MINS[period]!
  487. : HISTORICAL_TIME_PERIOD_MAP[period]!
  488. }
  489. dataLoadedCallback={onHistoricalDataLoaded}
  490. />
  491. ) : null}
  492. <OnDemandMetricRequest {...baseProps} dataLoadedCallback={onDataLoaded}>
  493. {({
  494. loading,
  495. errored,
  496. errorMessage,
  497. reloading,
  498. timeseriesData,
  499. comparisonTimeseriesData,
  500. seriesAdditionalInfo,
  501. }) => {
  502. let comparisonMarkLines: LineChartSeries[] = [];
  503. if (renderComparisonStats && comparisonTimeseriesData) {
  504. comparisonMarkLines = getComparisonMarkLines(
  505. timeseriesData,
  506. comparisonTimeseriesData,
  507. timeWindow,
  508. triggers,
  509. thresholdType
  510. );
  511. }
  512. return this.renderChart({
  513. timeseriesData: timeseriesData as Series[],
  514. isLoading: loading,
  515. isReloading: reloading,
  516. comparisonData: comparisonTimeseriesData,
  517. comparisonMarkLines,
  518. errorMessage,
  519. isQueryValid,
  520. errored,
  521. orgFeatures: organization.features,
  522. seriesAdditionalInfo,
  523. });
  524. }}
  525. </OnDemandMetricRequest>
  526. </Fragment>
  527. );
  528. }
  529. if (isSessionAggregate(aggregate)) {
  530. const baseProps: ComponentProps<typeof SessionsRequest> = {
  531. api,
  532. organization,
  533. project: projects.map(({id}) => Number(id)),
  534. environment: environment ? [environment] : undefined,
  535. statsPeriod: period,
  536. query,
  537. interval: TIME_WINDOW_TO_INTERVAL[timeWindow],
  538. field: SESSION_AGGREGATE_TO_FIELD[aggregate],
  539. groupBy: ['session.status'],
  540. children: noop,
  541. };
  542. return (
  543. <SessionsRequest {...baseProps}>
  544. {({loading, errored, reloading, response}) => {
  545. const {groups, intervals} = response || {};
  546. const sessionTimeSeries = [
  547. {
  548. seriesName:
  549. AlertWizardAlertNames[
  550. getAlertTypeFromAggregateDataset({
  551. aggregate,
  552. dataset: Dataset.SESSIONS,
  553. })
  554. ],
  555. data: getCrashFreeRateSeries(
  556. groups,
  557. intervals,
  558. SESSION_AGGREGATE_TO_FIELD[aggregate]
  559. ),
  560. },
  561. ];
  562. return this.renderChart({
  563. timeseriesData: sessionTimeSeries,
  564. isLoading: loading,
  565. isReloading: reloading,
  566. comparisonData: undefined,
  567. comparisonMarkLines: undefined,
  568. minutesThresholdToDisplaySeconds: MINUTES_THRESHOLD_TO_DISPLAY_SECONDS,
  569. isQueryValid,
  570. errored,
  571. orgFeatures: organization.features,
  572. });
  573. }}
  574. </SessionsRequest>
  575. );
  576. }
  577. const useRpc = dataset === Dataset.EVENTS_ANALYTICS_PLATFORM;
  578. const baseProps = {
  579. api,
  580. organization,
  581. query,
  582. period,
  583. queryExtras,
  584. environment: environment ? [environment] : undefined,
  585. project: projects.map(({id}) => Number(id)),
  586. interval: `${timeWindow}m`,
  587. comparisonDelta: comparisonDelta ? comparisonDelta * 60 : undefined,
  588. yAxis: aggregate,
  589. includePrevious: false,
  590. currentSeriesNames: [formattedAggregate || aggregate],
  591. partial: false,
  592. useRpc,
  593. };
  594. return (
  595. <Fragment>
  596. {this.props.includeHistorical ? (
  597. <EventsRequest
  598. {...baseProps}
  599. api={this.historicalAPI}
  600. period={
  601. timeWindow === 5
  602. ? HISTORICAL_TIME_PERIOD_MAP_FIVE_MINS[period]!
  603. : HISTORICAL_TIME_PERIOD_MAP[period]!
  604. }
  605. dataLoadedCallback={onHistoricalDataLoaded}
  606. >
  607. {noop}
  608. </EventsRequest>
  609. ) : null}
  610. {this.props.includeConfidence ? (
  611. <EventsRequest
  612. {...baseProps}
  613. api={this.confidenceAPI}
  614. period={TimePeriod.SEVEN_DAYS}
  615. dataLoadedCallback={onConfidenceDataLoaded}
  616. >
  617. {noop}
  618. </EventsRequest>
  619. ) : null}
  620. <EventsRequest {...baseProps} period={period} dataLoadedCallback={onDataLoaded}>
  621. {({
  622. loading,
  623. errored,
  624. errorMessage,
  625. reloading,
  626. timeseriesData,
  627. comparisonTimeseriesData,
  628. }) => {
  629. let comparisonMarkLines: LineChartSeries[] = [];
  630. if (renderComparisonStats && comparisonTimeseriesData) {
  631. comparisonMarkLines = getComparisonMarkLines(
  632. timeseriesData,
  633. comparisonTimeseriesData,
  634. timeWindow,
  635. triggers,
  636. thresholdType
  637. );
  638. }
  639. return this.renderChart({
  640. timeseriesData: timeseriesData as Series[],
  641. isLoading: loading,
  642. isReloading: reloading,
  643. comparisonData: comparisonTimeseriesData,
  644. comparisonMarkLines,
  645. errorMessage,
  646. isQueryValid,
  647. errored,
  648. orgFeatures: organization.features,
  649. });
  650. }}
  651. </EventsRequest>
  652. </Fragment>
  653. );
  654. }
  655. }
  656. export default withApi(TriggersChart);
  657. const TransparentLoadingMask = styled(LoadingMask)<{visible: boolean}>`
  658. ${p => !p.visible && 'display: none;'};
  659. opacity: 0.4;
  660. z-index: 1;
  661. `;
  662. const ChartPlaceholder = styled(Placeholder)`
  663. /* Height and margin should add up to graph size (200px) */
  664. margin: 0 0 ${space(2)};
  665. height: 184px;
  666. `;
  667. const StyledErrorPanel = styled(ErrorPanel)`
  668. /* Height and margin should with the alert should match up placeholder height of (184px) */
  669. padding: ${space(2)};
  670. height: 119px;
  671. `;
  672. const ChartErrorWrapper = styled('div')`
  673. margin-top: ${space(2)};
  674. `;
  675. export function ErrorChart({isAllowIndexed, isQueryValid, errorMessage, ...props}) {
  676. return (
  677. <ChartErrorWrapper {...props}>
  678. <PanelAlert type="error">
  679. {!isAllowIndexed && !isQueryValid
  680. ? t('Your filter conditions contain an unsupported field - please review.')
  681. : typeof errorMessage === 'string'
  682. ? errorMessage
  683. : t('An error occurred while fetching data')}
  684. </PanelAlert>
  685. <StyledErrorPanel>
  686. <IconWarning color="gray500" size="lg" />
  687. </StyledErrorPanel>
  688. </ChartErrorWrapper>
  689. );
  690. }