index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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, getXAxisLabelInterval} 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. xAxisLabelInterval: number;
  239. xAxisTickInterval: number;
  240. yAxisMinInterval: number;
  241. } {
  242. const selectDataCategory = categoryOptions.find(o => o.value === dataCategory);
  243. if (!selectDataCategory) {
  244. throw new Error('Selected item is not supported');
  245. }
  246. // Do not assume that handleDataTransformation is a pure function
  247. const chartData: ChartStats = {
  248. ...handleDataTransformation(usageStats, dataTransform),
  249. };
  250. Object.keys(chartData).forEach(k => {
  251. const isProjected = k === SeriesTypes.PROJECTED;
  252. // Map the array and destructure elements to avoid side-effects
  253. chartData[k] = chartData[k]?.map((stat: any) => {
  254. return {
  255. ...stat,
  256. tooltip: {show: false},
  257. itemStyle: {opacity: isProjected ? 0.6 : 1},
  258. };
  259. });
  260. });
  261. // Use hours as common units
  262. const dataPeriod = statsPeriodToDays(undefined, usageDateStart, usageDateEnd) * 24;
  263. const barPeriod = parsePeriodToHours(usageDateInterval);
  264. if (dataPeriod < 0 || barPeriod < 0) {
  265. throw new Error('UsageChart: Unable to parse data time period');
  266. }
  267. const {xAxisTickInterval, xAxisLabelInterval} = getXAxisLabelInterval(
  268. dataPeriod,
  269. dataPeriod / barPeriod
  270. );
  271. const {label, yAxisMinInterval} = selectDataCategory;
  272. /**
  273. * UsageChart needs to generate the X-Axis dates as props.usageStats may
  274. * not pass the complete range of X-Axis data points
  275. *
  276. * E.g. usageStats.accepted covers day 1-15 of a month, usageStats.projected
  277. * either covers day 16-30 or may not be available at all.
  278. */
  279. const xAxisDates = getXAxisDates(
  280. usageDateStart,
  281. usageDateEnd,
  282. usageDateShowUtc,
  283. usageDateInterval
  284. );
  285. return {
  286. chartLabel: label,
  287. chartData,
  288. xAxisData: xAxisDates,
  289. xAxisTickInterval,
  290. xAxisLabelInterval,
  291. yAxisMinInterval,
  292. tooltipValueFormatter: getTooltipFormatter(dataCategory),
  293. };
  294. }
  295. function UsageChartBody({
  296. usageDateStart,
  297. usageDateEnd,
  298. usageStats,
  299. dataCategory,
  300. dataTransform,
  301. chartSeries,
  302. chartTooltip,
  303. categoryColors,
  304. isLoading,
  305. isError,
  306. errors,
  307. categoryOptions = CHART_OPTIONS_DATACATEGORY,
  308. usageDateInterval = '1d',
  309. usageDateShowUtc = true,
  310. yAxisFormatter,
  311. handleDataTransformation = cumulativeTotalDataTransformation,
  312. legendSelected,
  313. onLegendSelectChanged,
  314. }: UsageChartProps) {
  315. const theme = useTheme();
  316. if (isLoading) {
  317. return (
  318. <Placeholder height="200px">
  319. <LoadingIndicator mini />
  320. </Placeholder>
  321. );
  322. }
  323. if (isError) {
  324. return (
  325. <Placeholder height="200px">
  326. <IconWarning size="sm" />
  327. <ErrorMessages data-test-id="error-messages">
  328. {errors &&
  329. Object.keys(errors).map(k => <span key={k}>{errors[k]?.message}</span>)}
  330. </ErrorMessages>
  331. </Placeholder>
  332. );
  333. }
  334. const yAxisLabelFormatter = yAxisFormatter ?? getUnitYaxisFormatter(dataCategory);
  335. const {
  336. chartData,
  337. tooltipValueFormatter,
  338. xAxisData,
  339. xAxisTickInterval,
  340. xAxisLabelInterval,
  341. yAxisMinInterval,
  342. } = chartMetadata({
  343. categoryOptions,
  344. dataCategory,
  345. handleDataTransformation: handleDataTransformation!,
  346. usageStats,
  347. dataTransform,
  348. usageDateStart,
  349. usageDateEnd,
  350. usageDateInterval,
  351. usageDateShowUtc,
  352. });
  353. function chartLegendData(): LegendComponentOption['data'] {
  354. const legend: LegendComponentOption['data'] = [];
  355. if (!chartData.reserved || chartData.reserved.length === 0) {
  356. legend.push({name: SeriesTypes.ACCEPTED});
  357. }
  358. if ((chartData.filtered ?? []).length > 0) {
  359. legend.push({name: SeriesTypes.FILTERED});
  360. }
  361. if ((chartData.rateLimited ?? []).length > 0) {
  362. legend.push({name: SeriesTypes.RATE_LIMITED});
  363. }
  364. if ((chartData.invalid ?? []).length > 0) {
  365. legend.push({name: SeriesTypes.INVALID});
  366. }
  367. if ((chartData.clientDiscard ?? []).length > 0) {
  368. legend.push({name: SeriesTypes.CLIENT_DISCARD});
  369. }
  370. if (chartData.projected.length > 0) {
  371. legend.push({name: SeriesTypes.PROJECTED});
  372. }
  373. if (chartSeries) {
  374. chartSeries.forEach(chartOption => {
  375. if (chartOption.name) {
  376. legend.push({name: `${chartOption.name}`});
  377. }
  378. });
  379. }
  380. return legend;
  381. }
  382. const colors = categoryColors?.length
  383. ? categoryColors
  384. : [
  385. theme.outcome[Outcome.ACCEPTED],
  386. theme.outcome[Outcome.FILTERED],
  387. theme.outcome[Outcome.RATE_LIMITED],
  388. theme.outcome[Outcome.INVALID],
  389. theme.outcome[Outcome.CLIENT_DISCARD],
  390. theme.chartOther, // Projected
  391. ];
  392. const series: SeriesOption[] = [
  393. barSeries({
  394. name: SeriesTypes.ACCEPTED,
  395. data: chartData.accepted,
  396. barMinHeight: 1,
  397. stack: 'usage',
  398. legendHoverLink: false,
  399. }),
  400. barSeries({
  401. name: SeriesTypes.FILTERED,
  402. data: chartData.filtered,
  403. barMinHeight: 1,
  404. stack: 'usage',
  405. legendHoverLink: false,
  406. }),
  407. barSeries({
  408. name: SeriesTypes.RATE_LIMITED,
  409. data: chartData.rateLimited,
  410. barMinHeight: 1,
  411. stack: 'usage',
  412. legendHoverLink: false,
  413. }),
  414. barSeries({
  415. name: SeriesTypes.INVALID,
  416. data: chartData.invalid,
  417. stack: 'usage',
  418. legendHoverLink: false,
  419. }),
  420. barSeries({
  421. name: SeriesTypes.CLIENT_DISCARD,
  422. data: chartData.clientDiscard,
  423. stack: 'usage',
  424. legendHoverLink: false,
  425. }),
  426. barSeries({
  427. name: SeriesTypes.PROJECTED,
  428. data: chartData.projected,
  429. barMinHeight: 1,
  430. stack: 'usage',
  431. legendHoverLink: false,
  432. }),
  433. // Additional series passed by parent component
  434. ...(chartSeries || []),
  435. ];
  436. return (
  437. <BaseChart
  438. colors={colors}
  439. grid={{bottom: '3px', left: '3px', right: '10px', top: '40px'}}
  440. xAxis={xAxis({
  441. show: true,
  442. type: 'category',
  443. name: 'Date',
  444. data: xAxisData,
  445. axisTick: {
  446. interval: xAxisTickInterval,
  447. alignWithLabel: true,
  448. },
  449. axisLabel: {
  450. interval: xAxisLabelInterval,
  451. formatter: (label: string) => label.slice(0, 6), // Limit label to 6 chars
  452. },
  453. theme,
  454. })}
  455. yAxis={{
  456. min: 0,
  457. minInterval: yAxisMinInterval,
  458. axisLabel: {
  459. formatter: yAxisLabelFormatter,
  460. color: theme.chartLabel,
  461. },
  462. }}
  463. series={series}
  464. tooltip={
  465. chartTooltip
  466. ? chartTooltip
  467. : {
  468. // Trigger to axis prevents tooltip from redrawing when hovering
  469. // over individual bars
  470. trigger: 'axis',
  471. valueFormatter: tooltipValueFormatter,
  472. }
  473. }
  474. onLegendSelectChanged={onLegendSelectChanged}
  475. legend={Legend({
  476. right: 10,
  477. top: 5,
  478. data: chartLegendData(),
  479. theme,
  480. selected: legendSelected,
  481. })}
  482. />
  483. );
  484. }
  485. interface UsageChartPanelProps extends UsageChartProps {
  486. footer?: React.ReactNode;
  487. title?: React.ReactNode;
  488. }
  489. function UsageChart({title, footer, ...props}: UsageChartPanelProps) {
  490. return (
  491. <Panel id="usage-chart" data-test-id="usage-chart">
  492. <ChartContainer>
  493. <HeaderTitleLegend>{title || t('Current Usage Period')}</HeaderTitleLegend>
  494. <UsageChartBody {...props} />
  495. </ChartContainer>
  496. {footer}
  497. </Panel>
  498. );
  499. }
  500. export default UsageChart;
  501. const ErrorMessages = styled('div')`
  502. display: flex;
  503. flex-direction: column;
  504. margin-top: ${space(1)};
  505. font-size: ${p => p.theme.fontSizeSmall};
  506. `;