index.tsx 15 KB

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