index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. import {Component, Fragment} from 'react';
  2. import {Theme, withTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import Color from 'color';
  5. import type {
  6. BarSeriesOption,
  7. LegendComponentOption,
  8. SeriesOption,
  9. TooltipComponentOption,
  10. } from 'echarts';
  11. import BaseChart from 'sentry/components/charts/baseChart';
  12. import Legend from 'sentry/components/charts/components/legend';
  13. import xAxis from 'sentry/components/charts/components/xAxis';
  14. import barSeries from 'sentry/components/charts/series/barSeries';
  15. import {ChartContainer, HeaderTitleLegend} from 'sentry/components/charts/styles';
  16. import LoadingIndicator from 'sentry/components/loadingIndicator';
  17. import Panel from 'sentry/components/panels/panel';
  18. import Placeholder from 'sentry/components/placeholder';
  19. import {DATA_CATEGORY_INFO} from 'sentry/constants';
  20. import {IconWarning} from 'sentry/icons';
  21. import {t} from 'sentry/locale';
  22. import {space} from 'sentry/styles/space';
  23. import {DataCategoryInfo, IntervalPeriod, SelectValue} from 'sentry/types';
  24. import {parsePeriodToHours, statsPeriodToDays} from 'sentry/utils/dates';
  25. import getDynamicText from 'sentry/utils/getDynamicText';
  26. import commonTheme from 'sentry/utils/theme';
  27. import {formatUsageWithUnits} from '../utils';
  28. import {getTooltipFormatter, getXAxisDates, getXAxisLabelInterval} from './utils';
  29. const GIGABYTE = 10 ** 9;
  30. type ChartProps = React.ComponentProps<typeof BaseChart>;
  31. const COLOR_ERRORS = Color(commonTheme.dataCategory.errors).lighten(0.25).string();
  32. const COLOR_TRANSACTIONS = Color(commonTheme.dataCategory.transactions)
  33. .lighten(0.35)
  34. .string();
  35. const COLOR_ATTACHMENTS = Color(commonTheme.dataCategory.attachments)
  36. .lighten(0.65)
  37. .string();
  38. const COLOR_DROPPED = commonTheme.red300;
  39. const COLOR_FILTERED = commonTheme.pink100;
  40. export type CategoryOption = {
  41. /**
  42. * Scale of y-axis with no usage data.
  43. */
  44. yAxisMinInterval: number;
  45. } & SelectValue<DataCategoryInfo['plural']>;
  46. export const CHART_OPTIONS_DATACATEGORY: CategoryOption[] = [
  47. {
  48. label: DATA_CATEGORY_INFO.error.titleName,
  49. value: DATA_CATEGORY_INFO.error.plural,
  50. disabled: false,
  51. yAxisMinInterval: 100,
  52. },
  53. {
  54. label: DATA_CATEGORY_INFO.transaction.titleName,
  55. value: DATA_CATEGORY_INFO.transaction.plural,
  56. disabled: false,
  57. yAxisMinInterval: 100,
  58. },
  59. {
  60. label: DATA_CATEGORY_INFO.replay.titleName,
  61. value: DATA_CATEGORY_INFO.replay.plural,
  62. disabled: false,
  63. yAxisMinInterval: 100,
  64. },
  65. {
  66. label: DATA_CATEGORY_INFO.attachment.titleName,
  67. value: DATA_CATEGORY_INFO.attachment.plural,
  68. disabled: false,
  69. yAxisMinInterval: 0.5 * GIGABYTE,
  70. },
  71. {
  72. label: DATA_CATEGORY_INFO.profile.titleName,
  73. value: DATA_CATEGORY_INFO.profile.plural,
  74. disabled: false,
  75. yAxisMinInterval: 100,
  76. },
  77. {
  78. label: DATA_CATEGORY_INFO.monitor.titleName,
  79. value: DATA_CATEGORY_INFO.monitor.plural,
  80. disabled: false,
  81. yAxisMinInterval: 100,
  82. },
  83. ];
  84. export enum ChartDataTransform {
  85. CUMULATIVE = 'cumulative',
  86. PERIODIC = 'periodic',
  87. }
  88. export const CHART_OPTIONS_DATA_TRANSFORM: SelectValue<ChartDataTransform>[] = [
  89. {
  90. label: t('Cumulative'),
  91. value: ChartDataTransform.CUMULATIVE,
  92. disabled: false,
  93. },
  94. {
  95. label: t('Periodic'),
  96. value: ChartDataTransform.PERIODIC,
  97. disabled: false,
  98. },
  99. ];
  100. export enum SeriesTypes {
  101. ACCEPTED = 'Accepted',
  102. DROPPED = 'Dropped',
  103. PROJECTED = 'Projected',
  104. FILTERED = 'Filtered',
  105. }
  106. type DefaultProps = {
  107. /**
  108. * Config for category dropdown options
  109. */
  110. categoryOptions: CategoryOption[];
  111. /**
  112. * Modify the usageStats using the transformation method selected.
  113. * 1. This must be a pure function!
  114. * 2. If the parent component will handle the data transformation, you should
  115. * replace this prop with "(s) => {return s}"
  116. */
  117. handleDataTransformation: (
  118. stats: ChartStats,
  119. transform: ChartDataTransform
  120. ) => ChartStats;
  121. /**
  122. * Intervals between the x-axis values
  123. */
  124. usageDateInterval: IntervalPeriod;
  125. /**
  126. * Display datetime in UTC
  127. */
  128. usageDateShowUtc: boolean;
  129. };
  130. export type UsageChartProps = DefaultProps & {
  131. dataCategory: DataCategoryInfo['plural'];
  132. dataTransform: ChartDataTransform;
  133. theme: Theme;
  134. usageDateEnd: string;
  135. usageDateStart: string;
  136. /**
  137. * Usage data to draw on chart
  138. */
  139. usageStats: ChartStats;
  140. /**
  141. * Override chart colors for each outcome
  142. */
  143. categoryColors?: string[];
  144. /**
  145. * Additional data to draw on the chart alongside usage
  146. */
  147. chartSeries?: SeriesOption[];
  148. /**
  149. * Replace default tooltip
  150. */
  151. chartTooltip?: TooltipComponentOption;
  152. errors?: Record<string, Error>;
  153. footer?: React.ReactNode;
  154. isError?: boolean;
  155. isLoading?: boolean;
  156. title?: React.ReactNode;
  157. };
  158. type State = {
  159. xAxisDates: string[];
  160. };
  161. export type ChartStats = {
  162. accepted: NonNullable<BarSeriesOption['data']>;
  163. dropped: NonNullable<BarSeriesOption['data']>;
  164. projected: NonNullable<BarSeriesOption['data']>;
  165. filtered?: NonNullable<BarSeriesOption['data']>;
  166. };
  167. export class UsageChart extends Component<UsageChartProps, State> {
  168. static defaultProps: DefaultProps = {
  169. categoryOptions: CHART_OPTIONS_DATACATEGORY,
  170. usageDateShowUtc: true,
  171. usageDateInterval: '1d',
  172. handleDataTransformation: (stats, transform) => {
  173. const chartData: ChartStats = {
  174. accepted: [],
  175. dropped: [],
  176. projected: [],
  177. filtered: [],
  178. };
  179. const isCumulative = transform === ChartDataTransform.CUMULATIVE;
  180. Object.keys(stats).forEach(k => {
  181. let count = 0;
  182. chartData[k] = stats[k].map(stat => {
  183. const [x, y] = stat.value;
  184. count = isCumulative ? count + y : y;
  185. return {
  186. ...stat,
  187. value: [x, count],
  188. };
  189. });
  190. });
  191. return chartData;
  192. },
  193. };
  194. state: State = {
  195. xAxisDates: [],
  196. };
  197. /**
  198. * UsageChart needs to generate the X-Axis dates as props.usageStats may
  199. * not pass the complete range of X-Axis data points
  200. *
  201. * E.g. usageStats.accepted covers day 1-15 of a month, usageStats.projected
  202. * either covers day 16-30 or may not be available at all.
  203. */
  204. static getDerivedStateFromProps(
  205. nextProps: Readonly<UsageChartProps>,
  206. prevState: State
  207. ): State {
  208. const {usageDateStart, usageDateEnd, usageDateShowUtc, usageDateInterval} = nextProps;
  209. return {
  210. ...prevState,
  211. xAxisDates: getXAxisDates(
  212. usageDateStart,
  213. usageDateEnd,
  214. usageDateShowUtc,
  215. usageDateInterval
  216. ),
  217. };
  218. }
  219. get chartColors() {
  220. const {dataCategory, theme} = this.props;
  221. const COLOR_PROJECTED = theme.chartOther;
  222. if (dataCategory === DATA_CATEGORY_INFO.error.plural) {
  223. return [COLOR_ERRORS, COLOR_FILTERED, COLOR_DROPPED, COLOR_PROJECTED];
  224. }
  225. if (dataCategory === DATA_CATEGORY_INFO.attachment.plural) {
  226. return [COLOR_ATTACHMENTS, COLOR_FILTERED, COLOR_DROPPED, COLOR_PROJECTED];
  227. }
  228. return [COLOR_TRANSACTIONS, COLOR_FILTERED, COLOR_DROPPED, COLOR_PROJECTED];
  229. }
  230. get chartMetadata(): {
  231. chartData: ChartStats;
  232. chartLabel: React.ReactNode;
  233. tooltipValueFormatter: (val?: number) => string;
  234. xAxisData: string[];
  235. xAxisLabelInterval: number;
  236. xAxisTickInterval: number;
  237. yAxisFormatter: (val: number) => string;
  238. yAxisMinInterval: number;
  239. } {
  240. const {categoryOptions, usageDateStart, usageDateEnd} = this.props;
  241. const {
  242. usageDateInterval,
  243. usageStats,
  244. dataCategory,
  245. dataTransform,
  246. handleDataTransformation,
  247. } = this.props;
  248. const {xAxisDates} = this.state;
  249. const selectDataCategory = categoryOptions.find(o => o.value === dataCategory);
  250. if (!selectDataCategory) {
  251. throw new Error('Selected item is not supported');
  252. }
  253. // Do not assume that handleDataTransformation is a pure function
  254. const chartData: ChartStats = {
  255. ...handleDataTransformation(usageStats, dataTransform),
  256. };
  257. Object.keys(chartData).forEach(k => {
  258. const isProjected = k === SeriesTypes.PROJECTED;
  259. // Map the array and destructure elements to avoid side-effects
  260. chartData[k] = chartData[k].map(stat => {
  261. return {
  262. ...stat,
  263. tooltip: {show: false},
  264. itemStyle: {opacity: isProjected ? 0.6 : 1},
  265. };
  266. });
  267. });
  268. // Use hours as common units
  269. const dataPeriod = statsPeriodToDays(undefined, usageDateStart, usageDateEnd) * 24;
  270. const barPeriod = parsePeriodToHours(usageDateInterval);
  271. if (dataPeriod < 0 || barPeriod < 0) {
  272. throw new Error('UsageChart: Unable to parse data time period');
  273. }
  274. const {xAxisTickInterval, xAxisLabelInterval} = getXAxisLabelInterval(
  275. dataPeriod,
  276. dataPeriod / barPeriod
  277. );
  278. const {label, yAxisMinInterval} = selectDataCategory;
  279. return {
  280. chartLabel: label,
  281. chartData,
  282. xAxisData: xAxisDates,
  283. xAxisTickInterval,
  284. xAxisLabelInterval,
  285. yAxisMinInterval,
  286. yAxisFormatter: (val: number) =>
  287. formatUsageWithUnits(val, dataCategory, {
  288. isAbbreviated: true,
  289. useUnitScaling: true,
  290. }),
  291. tooltipValueFormatter: getTooltipFormatter(dataCategory),
  292. };
  293. }
  294. get chartSeries() {
  295. const {chartSeries} = this.props;
  296. const {chartData} = this.chartMetadata;
  297. let series: SeriesOption[] = [
  298. barSeries({
  299. name: SeriesTypes.ACCEPTED,
  300. data: chartData.accepted,
  301. barMinHeight: 1,
  302. stack: 'usage',
  303. legendHoverLink: false,
  304. }),
  305. barSeries({
  306. name: SeriesTypes.FILTERED,
  307. data: chartData.filtered,
  308. barMinHeight: 1,
  309. stack: 'usage',
  310. legendHoverLink: false,
  311. }),
  312. barSeries({
  313. name: SeriesTypes.DROPPED,
  314. data: chartData.dropped,
  315. stack: 'usage',
  316. legendHoverLink: false,
  317. }),
  318. barSeries({
  319. name: SeriesTypes.PROJECTED,
  320. data: chartData.projected,
  321. barMinHeight: 1,
  322. stack: 'usage',
  323. legendHoverLink: false,
  324. }),
  325. ];
  326. // Additional series passed by parent component
  327. if (chartSeries) {
  328. series = series.concat(chartSeries as SeriesOption[]);
  329. }
  330. return series;
  331. }
  332. get chartLegendData() {
  333. const {chartSeries} = this.props;
  334. const {chartData} = this.chartMetadata;
  335. const legend: LegendComponentOption['data'] = [
  336. {
  337. name: SeriesTypes.ACCEPTED,
  338. },
  339. ];
  340. if (chartData.filtered && chartData.filtered.length > 0) {
  341. legend.push({
  342. name: SeriesTypes.FILTERED,
  343. });
  344. }
  345. if (chartData.dropped.length > 0) {
  346. legend.push({
  347. name: SeriesTypes.DROPPED,
  348. });
  349. }
  350. if (chartData.projected.length > 0) {
  351. legend.push({
  352. name: SeriesTypes.PROJECTED,
  353. });
  354. }
  355. if (chartSeries) {
  356. chartSeries.forEach(chartOption => {
  357. legend.push({name: `${chartOption.name}`});
  358. });
  359. }
  360. return legend;
  361. }
  362. get chartTooltip(): ChartProps['tooltip'] {
  363. const {chartTooltip} = this.props;
  364. if (chartTooltip) {
  365. return chartTooltip;
  366. }
  367. const {tooltipValueFormatter} = this.chartMetadata;
  368. return {
  369. // Trigger to axis prevents tooltip from redrawing when hovering
  370. // over individual bars
  371. trigger: 'axis',
  372. valueFormatter: tooltipValueFormatter,
  373. };
  374. }
  375. renderChart() {
  376. const {categoryColors, theme, title, isLoading, isError, errors} = this.props;
  377. if (isLoading) {
  378. return (
  379. <Placeholder height="200px">
  380. <LoadingIndicator mini />
  381. </Placeholder>
  382. );
  383. }
  384. if (isError) {
  385. return (
  386. <Placeholder height="200px">
  387. <IconWarning size="sm" />
  388. <ErrorMessages data-test-id="error-messages">
  389. {errors &&
  390. Object.keys(errors).map(k => <span key={k}>{errors[k]?.message}</span>)}
  391. </ErrorMessages>
  392. </Placeholder>
  393. );
  394. }
  395. const {
  396. xAxisData,
  397. xAxisTickInterval,
  398. xAxisLabelInterval,
  399. yAxisMinInterval,
  400. yAxisFormatter,
  401. } = this.chartMetadata;
  402. const colors = categoryColors?.length ? categoryColors : this.chartColors;
  403. return (
  404. <Fragment>
  405. <HeaderTitleLegend>{title || t('Current Usage Period')}</HeaderTitleLegend>
  406. {getDynamicText({
  407. value: (
  408. <BaseChart
  409. colors={colors}
  410. grid={{bottom: '3px', left: '0px', right: '10px', top: '40px'}}
  411. xAxis={xAxis({
  412. show: true,
  413. type: 'category',
  414. name: 'Date',
  415. data: xAxisData,
  416. axisTick: {
  417. interval: xAxisTickInterval,
  418. alignWithLabel: true,
  419. },
  420. axisLabel: {
  421. interval: xAxisLabelInterval,
  422. formatter: (label: string) => label.slice(0, 6), // Limit label to 6 chars
  423. },
  424. theme,
  425. })}
  426. yAxis={{
  427. min: 0,
  428. minInterval: yAxisMinInterval,
  429. axisLabel: {
  430. formatter: yAxisFormatter,
  431. color: theme.chartLabel,
  432. },
  433. }}
  434. series={this.chartSeries}
  435. tooltip={this.chartTooltip}
  436. onLegendSelectChanged={() => {}}
  437. legend={Legend({
  438. right: 10,
  439. top: 5,
  440. data: this.chartLegendData,
  441. theme,
  442. })}
  443. />
  444. ),
  445. fixed: <Placeholder height="200px" />,
  446. })}
  447. </Fragment>
  448. );
  449. }
  450. render() {
  451. const {footer} = this.props;
  452. return (
  453. <Panel id="usage-chart" data-test-id="usage-chart">
  454. <ChartContainer>{this.renderChart()}</ChartContainer>
  455. {footer}
  456. </Panel>
  457. );
  458. }
  459. }
  460. export default withTheme(UsageChart);
  461. const ErrorMessages = styled('div')`
  462. display: flex;
  463. flex-direction: column;
  464. margin-top: ${space(1)};
  465. font-size: ${p => p.theme.fontSizeSmall};
  466. `;