index.tsx 13 KB

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