index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. import {useMemo} from 'react';
  2. import {type Theme, useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import Color from 'color';
  5. import type {
  6. BarSeriesOption,
  7. LegendComponentOption,
  8. SeriesOption,
  9. TooltipComponentOption,
  10. } from 'echarts';
  11. import BaseChart from 'sentry/components/charts/baseChart';
  12. import Legend from 'sentry/components/charts/components/legend';
  13. import xAxis from 'sentry/components/charts/components/xAxis';
  14. import barSeries from 'sentry/components/charts/series/barSeries';
  15. import {ChartContainer, HeaderTitleLegend} from 'sentry/components/charts/styles';
  16. import LoadingIndicator from 'sentry/components/loadingIndicator';
  17. import Panel from 'sentry/components/panels/panel';
  18. import Placeholder from 'sentry/components/placeholder';
  19. import {DATA_CATEGORY_INFO} from 'sentry/constants';
  20. import {IconWarning} from 'sentry/icons';
  21. import {t} from 'sentry/locale';
  22. import {space} from 'sentry/styles/space';
  23. import type {DataCategoryInfo, IntervalPeriod, SelectValue} from 'sentry/types/core';
  24. import {statsPeriodToDays} from 'sentry/utils/dates';
  25. import {parsePeriodToHours} from 'sentry/utils/duration/parsePeriodToHours';
  26. import {hasCustomMetrics} from 'sentry/utils/metrics/features';
  27. import commonTheme from 'sentry/utils/theme';
  28. import useOrganization from 'sentry/utils/useOrganization';
  29. import {formatUsageWithUnits} from '../utils';
  30. import {getTooltipFormatter, getXAxisDates, getXAxisLabelInterval} from './utils';
  31. const GIGABYTE = 10 ** 9;
  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. label: DATA_CATEGORY_INFO.metrics.titleName,
  86. value: DATA_CATEGORY_INFO.metrics.plural,
  87. disabled: false,
  88. yAxisMinInterval: 100,
  89. },
  90. {
  91. label: DATA_CATEGORY_INFO.span.titleName,
  92. value: DATA_CATEGORY_INFO.span.plural,
  93. disabled: false,
  94. yAxisMinInterval: 100,
  95. },
  96. ];
  97. export enum ChartDataTransform {
  98. CUMULATIVE = 'cumulative',
  99. PERIODIC = 'periodic',
  100. }
  101. export const CHART_OPTIONS_DATA_TRANSFORM: SelectValue<ChartDataTransform>[] = [
  102. {
  103. label: t('Cumulative'),
  104. value: ChartDataTransform.CUMULATIVE,
  105. disabled: false,
  106. },
  107. {
  108. label: t('Periodic'),
  109. value: ChartDataTransform.PERIODIC,
  110. disabled: false,
  111. },
  112. ];
  113. const enum SeriesTypes {
  114. ACCEPTED = 'Accepted',
  115. DROPPED = 'Dropped',
  116. PROJECTED = 'Projected',
  117. FILTERED = 'Filtered',
  118. }
  119. export type UsageChartProps = {
  120. dataCategory: DataCategoryInfo['plural'];
  121. dataTransform: ChartDataTransform;
  122. usageDateEnd: string;
  123. usageDateStart: string;
  124. /**
  125. * Usage data to draw on chart
  126. */
  127. usageStats: ChartStats;
  128. /**
  129. * Override chart colors for each outcome
  130. */
  131. categoryColors?: string[];
  132. /**
  133. * Config for category dropdown options
  134. */
  135. categoryOptions?: CategoryOption[];
  136. /**
  137. * Additional data to draw on the chart alongside usage
  138. */
  139. chartSeries?: SeriesOption[];
  140. /**
  141. * Replace default tooltip
  142. */
  143. chartTooltip?: TooltipComponentOption;
  144. errors?: Record<string, Error>;
  145. /**
  146. * Modify the usageStats using the transformation method selected.
  147. * If the parent component will handle the data transformation, you should
  148. * replace this prop with "(s) => {return s}"
  149. */
  150. handleDataTransformation?: (
  151. stats: Readonly<ChartStats>,
  152. transform: Readonly<ChartDataTransform>
  153. ) => ChartStats;
  154. isError?: boolean;
  155. isLoading?: boolean;
  156. /**
  157. * Intervals between the x-axis values
  158. */
  159. usageDateInterval?: IntervalPeriod;
  160. /**
  161. * Display datetime in UTC
  162. */
  163. usageDateShowUtc?: boolean;
  164. yAxisFormatter?: (val: number) => string;
  165. };
  166. /**
  167. * When the data transformation is set to cumulative, the chart will display
  168. * the total sum of the data points up to that point.
  169. */
  170. const cumulativeTotalDataTransformation: UsageChartProps['handleDataTransformation'] = (
  171. stats,
  172. transform
  173. ) => {
  174. const chartData: ChartStats = {
  175. accepted: [],
  176. dropped: [],
  177. projected: [],
  178. filtered: [],
  179. reserved: [],
  180. onDemand: [],
  181. };
  182. const isCumulative = transform === ChartDataTransform.CUMULATIVE;
  183. Object.keys(stats).forEach(k => {
  184. let count = 0;
  185. chartData[k] = stats[k].map((stat: any) => {
  186. const [x, y] = stat.value;
  187. count = isCumulative ? count + y : y;
  188. return {
  189. ...stat,
  190. value: [x, count],
  191. };
  192. });
  193. });
  194. return chartData;
  195. };
  196. const getUnitYaxisFormatter =
  197. (dataCategory: UsageChartProps['dataCategory']) => (val: number) =>
  198. formatUsageWithUnits(val, dataCategory, {
  199. isAbbreviated: true,
  200. useUnitScaling: true,
  201. });
  202. export type ChartStats = {
  203. accepted: NonNullable<BarSeriesOption['data']>;
  204. dropped: NonNullable<BarSeriesOption['data']>;
  205. projected: NonNullable<BarSeriesOption['data']>;
  206. filtered?: NonNullable<BarSeriesOption['data']>;
  207. onDemand?: 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 chartColors(theme: Theme, dataCategory: UsageChartProps['dataCategory']) {
  296. const COLOR_PROJECTED = theme.chartOther;
  297. if (dataCategory === DATA_CATEGORY_INFO.error.plural) {
  298. return [COLOR_ERRORS, COLOR_FILTERED, COLOR_DROPPED, COLOR_PROJECTED];
  299. }
  300. if (dataCategory === DATA_CATEGORY_INFO.attachment.plural) {
  301. return [COLOR_ATTACHMENTS, COLOR_FILTERED, COLOR_DROPPED, COLOR_PROJECTED];
  302. }
  303. return [COLOR_TRANSACTIONS, COLOR_FILTERED, COLOR_DROPPED, COLOR_PROJECTED];
  304. }
  305. function UsageChartBody({
  306. usageDateStart,
  307. usageDateEnd,
  308. usageStats,
  309. dataCategory,
  310. dataTransform,
  311. chartSeries,
  312. chartTooltip,
  313. categoryColors,
  314. isLoading,
  315. isError,
  316. errors,
  317. categoryOptions = CHART_OPTIONS_DATACATEGORY,
  318. usageDateInterval = '1d',
  319. usageDateShowUtc = true,
  320. yAxisFormatter,
  321. handleDataTransformation = cumulativeTotalDataTransformation,
  322. }: UsageChartProps) {
  323. const theme = useTheme();
  324. const organization = useOrganization();
  325. const filteredOptions = useMemo(() => {
  326. return categoryOptions.filter(option => {
  327. if (option.value !== DATA_CATEGORY_INFO.metrics.plural) {
  328. return true;
  329. }
  330. return hasCustomMetrics(organization);
  331. });
  332. }, [organization, categoryOptions]);
  333. if (isLoading) {
  334. return (
  335. <Placeholder height="200px">
  336. <LoadingIndicator mini />
  337. </Placeholder>
  338. );
  339. }
  340. if (isError) {
  341. return (
  342. <Placeholder height="200px">
  343. <IconWarning size="sm" />
  344. <ErrorMessages data-test-id="error-messages">
  345. {errors &&
  346. Object.keys(errors).map(k => <span key={k}>{errors[k]?.message}</span>)}
  347. </ErrorMessages>
  348. </Placeholder>
  349. );
  350. }
  351. const yAxisLabelFormatter = yAxisFormatter ?? getUnitYaxisFormatter(dataCategory);
  352. const {
  353. chartData,
  354. tooltipValueFormatter,
  355. xAxisData,
  356. xAxisTickInterval,
  357. xAxisLabelInterval,
  358. yAxisMinInterval,
  359. } = chartMetadata({
  360. categoryOptions: filteredOptions,
  361. dataCategory,
  362. handleDataTransformation: handleDataTransformation!,
  363. usageStats,
  364. dataTransform,
  365. usageDateStart,
  366. usageDateEnd,
  367. usageDateInterval,
  368. usageDateShowUtc,
  369. });
  370. function chartLegendData() {
  371. const legend: LegendComponentOption['data'] = [
  372. ...(chartData.reserved && chartData.reserved.length > 0
  373. ? []
  374. : [
  375. {
  376. name: SeriesTypes.ACCEPTED,
  377. },
  378. ]),
  379. ];
  380. if (chartData.filtered && chartData.filtered.length > 0) {
  381. legend.push({
  382. name: SeriesTypes.FILTERED,
  383. });
  384. }
  385. if (chartData.dropped.length > 0) {
  386. legend.push({
  387. name: SeriesTypes.DROPPED,
  388. });
  389. }
  390. if (chartData.projected.length > 0) {
  391. legend.push({
  392. name: SeriesTypes.PROJECTED,
  393. });
  394. }
  395. if (chartSeries) {
  396. chartSeries.forEach(chartOption => {
  397. if (chartOption.name) {
  398. legend.push({name: `${chartOption.name}`});
  399. }
  400. });
  401. }
  402. return legend;
  403. }
  404. const colors = categoryColors?.length
  405. ? categoryColors
  406. : chartColors(theme, dataCategory);
  407. const series: SeriesOption[] = [
  408. barSeries({
  409. name: SeriesTypes.ACCEPTED,
  410. data: chartData.accepted,
  411. barMinHeight: 1,
  412. stack: 'usage',
  413. legendHoverLink: false,
  414. }),
  415. barSeries({
  416. name: SeriesTypes.FILTERED,
  417. data: chartData.filtered,
  418. barMinHeight: 1,
  419. stack: 'usage',
  420. legendHoverLink: false,
  421. }),
  422. barSeries({
  423. name: SeriesTypes.DROPPED,
  424. data: chartData.dropped,
  425. stack: 'usage',
  426. legendHoverLink: false,
  427. }),
  428. barSeries({
  429. name: SeriesTypes.PROJECTED,
  430. data: chartData.projected,
  431. barMinHeight: 1,
  432. stack: 'usage',
  433. legendHoverLink: false,
  434. }),
  435. // Additional series passed by parent component
  436. ...(chartSeries || []),
  437. ];
  438. return (
  439. <BaseChart
  440. colors={colors}
  441. grid={{bottom: '3px', left: '3px', right: '10px', top: '40px'}}
  442. xAxis={xAxis({
  443. show: true,
  444. type: 'category',
  445. name: 'Date',
  446. data: xAxisData,
  447. axisTick: {
  448. interval: xAxisTickInterval,
  449. alignWithLabel: true,
  450. },
  451. axisLabel: {
  452. interval: xAxisLabelInterval,
  453. formatter: (label: string) => label.slice(0, 6), // Limit label to 6 chars
  454. },
  455. theme,
  456. })}
  457. yAxis={{
  458. min: 0,
  459. minInterval: yAxisMinInterval,
  460. axisLabel: {
  461. formatter: yAxisLabelFormatter,
  462. color: theme.chartLabel,
  463. },
  464. }}
  465. series={series}
  466. tooltip={
  467. chartTooltip
  468. ? chartTooltip
  469. : {
  470. // Trigger to axis prevents tooltip from redrawing when hovering
  471. // over individual bars
  472. trigger: 'axis',
  473. valueFormatter: tooltipValueFormatter,
  474. }
  475. }
  476. onLegendSelectChanged={() => {}}
  477. legend={Legend({
  478. right: 10,
  479. top: 5,
  480. data: chartLegendData(),
  481. theme,
  482. })}
  483. />
  484. );
  485. }
  486. interface UsageChartPanelProps extends UsageChartProps {
  487. footer?: React.ReactNode;
  488. title?: React.ReactNode;
  489. }
  490. function UsageChart({title, footer, ...props}: UsageChartPanelProps) {
  491. return (
  492. <Panel id="usage-chart" data-test-id="usage-chart">
  493. <ChartContainer>
  494. <HeaderTitleLegend>{title || t('Current Usage Period')}</HeaderTitleLegend>
  495. <UsageChartBody {...props} />
  496. </ChartContainer>
  497. {footer}
  498. </Panel>
  499. );
  500. }
  501. export default UsageChart;
  502. const ErrorMessages = styled('div')`
  503. display: flex;
  504. flex-direction: column;
  505. margin-top: ${space(1)};
  506. font-size: ${p => p.theme.fontSizeSmall};
  507. `;