index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. import * as React from 'react';
  2. import styled from '@emotion/styled';
  3. import capitalize from 'lodash/capitalize';
  4. import chunk from 'lodash/chunk';
  5. import maxBy from 'lodash/maxBy';
  6. import minBy from 'lodash/minBy';
  7. import {fetchTotalCount} from 'app/actionCreators/events';
  8. import {Client} from 'app/api';
  9. import Feature from 'app/components/acl/feature';
  10. import EventsRequest from 'app/components/charts/eventsRequest';
  11. import {LineChartSeries} from 'app/components/charts/lineChart';
  12. import OptionSelector from 'app/components/charts/optionSelector';
  13. import SessionsRequest from 'app/components/charts/sessionsRequest';
  14. import {
  15. ChartControls,
  16. InlineContainer,
  17. SectionHeading,
  18. SectionValue,
  19. } from 'app/components/charts/styles';
  20. import LoadingMask from 'app/components/loadingMask';
  21. import Placeholder from 'app/components/placeholder';
  22. import {t} from 'app/locale';
  23. import space from 'app/styles/space';
  24. import {Organization, Project} from 'app/types';
  25. import {Series, SeriesDataUnit} from 'app/types/echarts';
  26. import {
  27. getCrashFreeRateSeries,
  28. MINUTES_THRESHOLD_TO_DISPLAY_SECONDS,
  29. } from 'app/utils/sessions';
  30. import withApi from 'app/utils/withApi';
  31. import {getComparisonMarkLines} from 'app/views/alerts/changeAlerts/comparisonMarklines';
  32. import {COMPARISON_DELTA_OPTIONS} from 'app/views/alerts/incidentRules/constants';
  33. import {isSessionAggregate, SESSION_AGGREGATE_TO_FIELD} from 'app/views/alerts/utils';
  34. import {AlertWizardAlertNames} from 'app/views/alerts/wizard/options';
  35. import {getAlertTypeFromAggregateDataset} from 'app/views/alerts/wizard/utils';
  36. import {
  37. AlertRuleComparisonType,
  38. Dataset,
  39. IncidentRule,
  40. SessionsAggregate,
  41. TimePeriod,
  42. TimeWindow,
  43. Trigger,
  44. } from '../../types';
  45. import ThresholdsChart from './thresholdsChart';
  46. type Props = {
  47. api: Client;
  48. organization: Organization;
  49. projects: Project[];
  50. query: IncidentRule['query'];
  51. timeWindow: IncidentRule['timeWindow'];
  52. environment: string | null;
  53. aggregate: IncidentRule['aggregate'];
  54. triggers: Trigger[];
  55. resolveThreshold: IncidentRule['resolveThreshold'];
  56. thresholdType: IncidentRule['thresholdType'];
  57. comparisonType: AlertRuleComparisonType;
  58. header?: React.ReactNode;
  59. comparisonDelta?: number;
  60. };
  61. const TIME_PERIOD_MAP: Record<TimePeriod, string> = {
  62. [TimePeriod.SIX_HOURS]: t('Last 6 hours'),
  63. [TimePeriod.ONE_DAY]: t('Last 24 hours'),
  64. [TimePeriod.THREE_DAYS]: t('Last 3 days'),
  65. [TimePeriod.SEVEN_DAYS]: t('Last 7 days'),
  66. [TimePeriod.FOURTEEN_DAYS]: t('Last 14 days'),
  67. [TimePeriod.THIRTY_DAYS]: t('Last 30 days'),
  68. };
  69. /**
  70. * If TimeWindow is small we want to limit the stats period
  71. * If the time window is one day we want to use a larger stats period
  72. */
  73. const AVAILABLE_TIME_PERIODS: Record<TimeWindow, TimePeriod[]> = {
  74. [TimeWindow.ONE_MINUTE]: [
  75. TimePeriod.SIX_HOURS,
  76. TimePeriod.ONE_DAY,
  77. TimePeriod.THREE_DAYS,
  78. TimePeriod.SEVEN_DAYS,
  79. ],
  80. [TimeWindow.FIVE_MINUTES]: [
  81. TimePeriod.ONE_DAY,
  82. TimePeriod.THREE_DAYS,
  83. TimePeriod.SEVEN_DAYS,
  84. TimePeriod.FOURTEEN_DAYS,
  85. TimePeriod.THIRTY_DAYS,
  86. ],
  87. [TimeWindow.TEN_MINUTES]: [
  88. TimePeriod.ONE_DAY,
  89. TimePeriod.THREE_DAYS,
  90. TimePeriod.SEVEN_DAYS,
  91. TimePeriod.FOURTEEN_DAYS,
  92. TimePeriod.THIRTY_DAYS,
  93. ],
  94. [TimeWindow.FIFTEEN_MINUTES]: [
  95. TimePeriod.THREE_DAYS,
  96. TimePeriod.SEVEN_DAYS,
  97. TimePeriod.FOURTEEN_DAYS,
  98. TimePeriod.THIRTY_DAYS,
  99. ],
  100. [TimeWindow.THIRTY_MINUTES]: [
  101. TimePeriod.SEVEN_DAYS,
  102. TimePeriod.FOURTEEN_DAYS,
  103. TimePeriod.THIRTY_DAYS,
  104. ],
  105. [TimeWindow.ONE_HOUR]: [TimePeriod.FOURTEEN_DAYS, TimePeriod.THIRTY_DAYS],
  106. [TimeWindow.TWO_HOURS]: [TimePeriod.THIRTY_DAYS],
  107. [TimeWindow.FOUR_HOURS]: [TimePeriod.THIRTY_DAYS],
  108. [TimeWindow.ONE_DAY]: [TimePeriod.THIRTY_DAYS],
  109. };
  110. const AGGREGATE_FUNCTIONS = {
  111. avg: (seriesChunk: SeriesDataUnit[]) =>
  112. AGGREGATE_FUNCTIONS.sum(seriesChunk) / seriesChunk.length,
  113. sum: (seriesChunk: SeriesDataUnit[]) =>
  114. seriesChunk.reduce((acc, series) => acc + series.value, 0),
  115. max: (seriesChunk: SeriesDataUnit[]) =>
  116. Math.max(...seriesChunk.map(series => series.value)),
  117. min: (seriesChunk: SeriesDataUnit[]) =>
  118. Math.min(...seriesChunk.map(series => series.value)),
  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. /**
  132. * Determines the number of datapoints to roll up
  133. */
  134. const getBucketSize = (timeWindow: TimeWindow, dataPoints: number): number => {
  135. const MAX_DPS = 720;
  136. for (const bucketSize of [5, 10, 15, 30, 60, 120, 240]) {
  137. const chunkSize = bucketSize / timeWindow;
  138. if (dataPoints / chunkSize <= MAX_DPS) {
  139. return bucketSize / timeWindow;
  140. }
  141. }
  142. return 2;
  143. };
  144. type State = {
  145. statsPeriod: TimePeriod;
  146. totalCount: number | null;
  147. };
  148. /**
  149. * This is a chart to be used in Metric Alert rules that fetches events based on
  150. * query, timewindow, and aggregations.
  151. */
  152. class TriggersChart extends React.PureComponent<Props, State> {
  153. state: State = {
  154. statsPeriod: TimePeriod.ONE_DAY,
  155. totalCount: null,
  156. };
  157. componentDidMount() {
  158. if (!isSessionAggregate(this.props.aggregate)) {
  159. this.fetchTotalCount();
  160. }
  161. }
  162. componentDidUpdate(prevProps: Props, prevState: State) {
  163. const {query, environment, timeWindow, aggregate, projects} = this.props;
  164. const {statsPeriod} = this.state;
  165. if (
  166. !isSessionAggregate(aggregate) &&
  167. (prevProps.projects !== projects ||
  168. prevProps.environment !== environment ||
  169. prevProps.query !== query ||
  170. prevProps.timeWindow !== timeWindow ||
  171. prevState.statsPeriod !== statsPeriod)
  172. ) {
  173. this.fetchTotalCount();
  174. }
  175. }
  176. get availableTimePeriods() {
  177. // We need to special case sessions, because sub-hour windows are available
  178. // only when time period is six hours or less (backend limitation)
  179. if (isSessionAggregate(this.props.aggregate)) {
  180. return {
  181. ...AVAILABLE_TIME_PERIODS,
  182. [TimeWindow.THIRTY_MINUTES]: [TimePeriod.SIX_HOURS],
  183. };
  184. }
  185. return AVAILABLE_TIME_PERIODS;
  186. }
  187. handleStatsPeriodChange = (timePeriod: string) => {
  188. this.setState({statsPeriod: timePeriod as TimePeriod});
  189. };
  190. getStatsPeriod = () => {
  191. const {statsPeriod} = this.state;
  192. const {timeWindow} = this.props;
  193. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  194. const period = statsPeriodOptions.includes(statsPeriod)
  195. ? statsPeriod
  196. : statsPeriodOptions[0];
  197. return period;
  198. };
  199. get comparisonSeriesName() {
  200. return capitalize(
  201. COMPARISON_DELTA_OPTIONS.find(({value}) => value === this.props.comparisonDelta)
  202. ?.label || ''
  203. );
  204. }
  205. async fetchTotalCount() {
  206. const {api, organization, environment, projects, query} = this.props;
  207. const statsPeriod = this.getStatsPeriod();
  208. try {
  209. const totalCount = await fetchTotalCount(api, organization.slug, {
  210. field: [],
  211. project: projects.map(({id}) => id),
  212. query,
  213. statsPeriod,
  214. environment: environment ? [environment] : [],
  215. });
  216. this.setState({totalCount});
  217. } catch (e) {
  218. this.setState({totalCount: null});
  219. }
  220. }
  221. renderChart(
  222. timeseriesData: Series[] = [],
  223. isLoading: boolean,
  224. isReloading: boolean,
  225. comparisonData?: Series[],
  226. comparisonMarkLines?: LineChartSeries[],
  227. minutesThresholdToDisplaySeconds?: number
  228. ) {
  229. const {
  230. triggers,
  231. resolveThreshold,
  232. thresholdType,
  233. header,
  234. timeWindow,
  235. aggregate,
  236. comparisonType,
  237. } = this.props;
  238. const {statsPeriod, totalCount} = this.state;
  239. const statsPeriodOptions = this.availableTimePeriods[timeWindow];
  240. const period = this.getStatsPeriod();
  241. return (
  242. <React.Fragment>
  243. {header}
  244. <TransparentLoadingMask visible={isReloading} />
  245. {isLoading ? (
  246. <ChartPlaceholder />
  247. ) : (
  248. <ThresholdsChart
  249. period={statsPeriod}
  250. minValue={minBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  251. maxValue={maxBy(timeseriesData[0]?.data, ({value}) => value)?.value}
  252. data={timeseriesData}
  253. comparisonData={comparisonData ?? []}
  254. comparisonSeriesName={this.comparisonSeriesName}
  255. comparisonMarkLines={comparisonMarkLines ?? []}
  256. hideThresholdLines={comparisonType === AlertRuleComparisonType.CHANGE}
  257. triggers={triggers}
  258. resolveThreshold={resolveThreshold}
  259. thresholdType={thresholdType}
  260. aggregate={aggregate}
  261. minutesThresholdToDisplaySeconds={minutesThresholdToDisplaySeconds}
  262. />
  263. )}
  264. <ChartControls>
  265. <InlineContainer>
  266. <SectionHeading>
  267. {isSessionAggregate(aggregate)
  268. ? SESSION_AGGREGATE_TO_HEADING[aggregate]
  269. : t('Total Events')}
  270. </SectionHeading>
  271. <SectionValue>
  272. {totalCount !== null ? totalCount.toLocaleString() : '\u2014'}
  273. </SectionValue>
  274. </InlineContainer>
  275. <InlineContainer>
  276. <OptionSelector
  277. options={statsPeriodOptions.map(timePeriod => ({
  278. label: TIME_PERIOD_MAP[timePeriod],
  279. value: timePeriod,
  280. disabled: isLoading || isReloading,
  281. }))}
  282. selected={period}
  283. onChange={this.handleStatsPeriodChange}
  284. title={t('Display')}
  285. />
  286. </InlineContainer>
  287. </ChartControls>
  288. </React.Fragment>
  289. );
  290. }
  291. render() {
  292. const {
  293. api,
  294. organization,
  295. projects,
  296. timeWindow,
  297. query,
  298. aggregate,
  299. environment,
  300. comparisonDelta,
  301. triggers,
  302. thresholdType,
  303. } = this.props;
  304. const period = this.getStatsPeriod();
  305. const renderComparisonStats = Boolean(
  306. organization.features.includes('change-alerts') && comparisonDelta
  307. );
  308. return isSessionAggregate(aggregate) ? (
  309. <SessionsRequest
  310. api={api}
  311. organization={organization}
  312. project={projects.map(({id}) => Number(id))}
  313. environment={environment ? [environment] : undefined}
  314. statsPeriod={period}
  315. query={query}
  316. interval={TIME_WINDOW_TO_SESSION_INTERVAL[timeWindow]}
  317. field={SESSION_AGGREGATE_TO_FIELD[aggregate]}
  318. groupBy={['session.status']}
  319. >
  320. {({loading, reloading, response}) => {
  321. const {groups, intervals} = response || {};
  322. const sessionTimeSeries = [
  323. {
  324. seriesName:
  325. AlertWizardAlertNames[
  326. getAlertTypeFromAggregateDataset({aggregate, dataset: Dataset.SESSIONS})
  327. ],
  328. data: getCrashFreeRateSeries(
  329. groups,
  330. intervals,
  331. SESSION_AGGREGATE_TO_FIELD[aggregate]
  332. ),
  333. },
  334. ];
  335. return this.renderChart(
  336. sessionTimeSeries,
  337. loading,
  338. reloading,
  339. undefined,
  340. undefined,
  341. MINUTES_THRESHOLD_TO_DISPLAY_SECONDS
  342. );
  343. }}
  344. </SessionsRequest>
  345. ) : (
  346. <Feature features={['metric-alert-builder-aggregate']} organization={organization}>
  347. {({hasFeature}) => {
  348. return (
  349. <EventsRequest
  350. api={api}
  351. organization={organization}
  352. query={query}
  353. environment={environment ? [environment] : undefined}
  354. project={projects.map(({id}) => Number(id))}
  355. interval={`${timeWindow}m`}
  356. comparisonDelta={comparisonDelta && comparisonDelta * 60}
  357. period={period}
  358. yAxis={aggregate}
  359. includePrevious={false}
  360. currentSeriesNames={[aggregate]}
  361. partial={false}
  362. >
  363. {({loading, reloading, timeseriesData, comparisonTimeseriesData}) => {
  364. let comparisonMarkLines: LineChartSeries[] = [];
  365. if (renderComparisonStats && comparisonTimeseriesData) {
  366. comparisonMarkLines = getComparisonMarkLines(
  367. timeseriesData,
  368. comparisonTimeseriesData,
  369. timeWindow,
  370. triggers,
  371. thresholdType
  372. );
  373. }
  374. let timeseriesLength: number | undefined;
  375. if (timeseriesData?.[0]?.data !== undefined) {
  376. timeseriesLength = timeseriesData[0].data.length;
  377. if (hasFeature && timeseriesLength > 600) {
  378. const avgData: SeriesDataUnit[] = [];
  379. const minData: SeriesDataUnit[] = [];
  380. const maxData: SeriesDataUnit[] = [];
  381. const chunkSize = getBucketSize(
  382. timeWindow,
  383. timeseriesData[0].data.length
  384. );
  385. chunk(timeseriesData[0].data, chunkSize).forEach(seriesChunk => {
  386. avgData.push({
  387. name: seriesChunk[0].name,
  388. value: AGGREGATE_FUNCTIONS.avg(seriesChunk),
  389. });
  390. minData.push({
  391. name: seriesChunk[0].name,
  392. value: AGGREGATE_FUNCTIONS.min(seriesChunk),
  393. });
  394. maxData.push({
  395. name: seriesChunk[0].name,
  396. value: AGGREGATE_FUNCTIONS.max(seriesChunk),
  397. });
  398. });
  399. timeseriesData = [
  400. timeseriesData[0],
  401. {seriesName: t('Minimum'), data: minData},
  402. {seriesName: t('Average'), data: avgData},
  403. {seriesName: t('Maximum'), data: maxData},
  404. ];
  405. }
  406. }
  407. return this.renderChart(
  408. timeseriesData,
  409. loading,
  410. reloading,
  411. comparisonTimeseriesData,
  412. comparisonMarkLines
  413. );
  414. }}
  415. </EventsRequest>
  416. );
  417. }}
  418. </Feature>
  419. );
  420. }
  421. }
  422. export default withApi(TriggersChart);
  423. const TransparentLoadingMask = styled(LoadingMask)<{visible: boolean}>`
  424. ${p => !p.visible && 'display: none;'};
  425. opacity: 0.4;
  426. z-index: 1;
  427. `;
  428. const ChartPlaceholder = styled(Placeholder)`
  429. /* Height and margin should add up to graph size (200px) */
  430. margin: 0 0 ${space(2)};
  431. height: 184px;
  432. `;