index.tsx 14 KB

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