index.tsx 14 KB

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