index.tsx 14 KB

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