index.tsx 22 KB

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