index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. label: DATA_CATEGORY_INFO.span.titleName,
  91. value: DATA_CATEGORY_INFO.span.plural,
  92. disabled: false,
  93. yAxisMinInterval: 100,
  94. },
  95. ];
  96. export enum ChartDataTransform {
  97. CUMULATIVE = 'cumulative',
  98. PERIODIC = 'periodic',
  99. }
  100. export const CHART_OPTIONS_DATA_TRANSFORM: SelectValue<ChartDataTransform>[] = [
  101. {
  102. label: t('Cumulative'),
  103. value: ChartDataTransform.CUMULATIVE,
  104. disabled: false,
  105. },
  106. {
  107. label: t('Periodic'),
  108. value: ChartDataTransform.PERIODIC,
  109. disabled: false,
  110. },
  111. ];
  112. const enum SeriesTypes {
  113. ACCEPTED = 'Accepted',
  114. DROPPED = 'Dropped',
  115. PROJECTED = 'Projected',
  116. FILTERED = 'Filtered',
  117. }
  118. export type UsageChartProps = {
  119. dataCategory: DataCategoryInfo['plural'];
  120. dataTransform: ChartDataTransform;
  121. usageDateEnd: string;
  122. usageDateStart: string;
  123. /**
  124. * Usage data to draw on chart
  125. */
  126. usageStats: ChartStats;
  127. /**
  128. * Override chart colors for each outcome
  129. */
  130. categoryColors?: string[];
  131. /**
  132. * Config for category dropdown options
  133. */
  134. categoryOptions?: CategoryOption[];
  135. /**
  136. * Additional data to draw on the chart alongside usage
  137. */
  138. chartSeries?: SeriesOption[];
  139. /**
  140. * Replace default tooltip
  141. */
  142. chartTooltip?: TooltipComponentOption;
  143. errors?: Record<string, Error>;
  144. /**
  145. * Modify the usageStats using the transformation method selected.
  146. * If the parent component will handle the data transformation, you should
  147. * replace this prop with "(s) => {return s}"
  148. */
  149. handleDataTransformation?: (
  150. stats: Readonly<ChartStats>,
  151. transform: Readonly<ChartDataTransform>
  152. ) => ChartStats;
  153. isError?: boolean;
  154. isLoading?: boolean;
  155. /**
  156. * Intervals between the x-axis values
  157. */
  158. usageDateInterval?: IntervalPeriod;
  159. /**
  160. * Display datetime in UTC
  161. */
  162. usageDateShowUtc?: boolean;
  163. yAxisFormatter?: (val: number) => string;
  164. };
  165. /**
  166. * When the data transformation is set to cumulative, the chart will display
  167. * the total sum of the data points up to that point.
  168. */
  169. const cumulativeTotalDataTransformation: UsageChartProps['handleDataTransformation'] = (
  170. stats,
  171. transform
  172. ) => {
  173. const chartData: ChartStats = {
  174. accepted: [],
  175. dropped: [],
  176. projected: [],
  177. filtered: [],
  178. reserved: [],
  179. onDemand: [],
  180. };
  181. const isCumulative = transform === ChartDataTransform.CUMULATIVE;
  182. Object.keys(stats).forEach(k => {
  183. let count = 0;
  184. chartData[k] = stats[k].map((stat: any) => {
  185. const [x, y] = stat.value;
  186. count = isCumulative ? count + y : y;
  187. return {
  188. ...stat,
  189. value: [x, count],
  190. };
  191. });
  192. });
  193. return chartData;
  194. };
  195. const getUnitYaxisFormatter =
  196. (dataCategory: UsageChartProps['dataCategory']) => (val: number) =>
  197. formatUsageWithUnits(val, dataCategory, {
  198. isAbbreviated: true,
  199. useUnitScaling: true,
  200. });
  201. export type ChartStats = {
  202. accepted: NonNullable<BarSeriesOption['data']>;
  203. dropped: NonNullable<BarSeriesOption['data']>;
  204. projected: NonNullable<BarSeriesOption['data']>;
  205. filtered?: NonNullable<BarSeriesOption['data']>;
  206. onDemand?: NonNullable<BarSeriesOption['data']>;
  207. reserved?: NonNullable<BarSeriesOption['data']>;
  208. };
  209. function chartMetadata({
  210. categoryOptions,
  211. dataCategory,
  212. usageStats,
  213. dataTransform,
  214. usageDateStart,
  215. usageDateEnd,
  216. usageDateInterval,
  217. usageDateShowUtc,
  218. handleDataTransformation,
  219. }: Required<
  220. Pick<
  221. UsageChartProps,
  222. | 'categoryOptions'
  223. | 'dataCategory'
  224. | 'handleDataTransformation'
  225. | 'usageStats'
  226. | 'dataTransform'
  227. | 'usageDateStart'
  228. | 'usageDateEnd'
  229. | 'usageDateInterval'
  230. | 'usageDateShowUtc'
  231. >
  232. >): {
  233. chartData: ChartStats;
  234. chartLabel: React.ReactNode;
  235. tooltipValueFormatter: (val?: number) => string;
  236. xAxisData: string[];
  237. xAxisLabelInterval: number;
  238. xAxisTickInterval: number;
  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 {xAxisTickInterval, xAxisLabelInterval} = getXAxisLabelInterval(
  267. dataPeriod,
  268. dataPeriod / barPeriod
  269. );
  270. const {label, yAxisMinInterval} = selectDataCategory;
  271. /**
  272. * UsageChart needs to generate the X-Axis dates as props.usageStats may
  273. * not pass the complete range of X-Axis data points
  274. *
  275. * E.g. usageStats.accepted covers day 1-15 of a month, usageStats.projected
  276. * either covers day 16-30 or may not be available at all.
  277. */
  278. const xAxisDates = getXAxisDates(
  279. usageDateStart,
  280. usageDateEnd,
  281. usageDateShowUtc,
  282. usageDateInterval
  283. );
  284. return {
  285. chartLabel: label,
  286. chartData,
  287. xAxisData: xAxisDates,
  288. xAxisTickInterval,
  289. xAxisLabelInterval,
  290. yAxisMinInterval,
  291. tooltipValueFormatter: getTooltipFormatter(dataCategory),
  292. };
  293. }
  294. function chartColors(theme: Theme, dataCategory: UsageChartProps['dataCategory']) {
  295. const COLOR_PROJECTED = theme.chartOther;
  296. if (dataCategory === DATA_CATEGORY_INFO.error.plural) {
  297. return [COLOR_ERRORS, COLOR_FILTERED, COLOR_DROPPED, COLOR_PROJECTED];
  298. }
  299. if (dataCategory === DATA_CATEGORY_INFO.attachment.plural) {
  300. return [COLOR_ATTACHMENTS, COLOR_FILTERED, COLOR_DROPPED, COLOR_PROJECTED];
  301. }
  302. return [COLOR_TRANSACTIONS, COLOR_FILTERED, COLOR_DROPPED, COLOR_PROJECTED];
  303. }
  304. function UsageChartBody({
  305. usageDateStart,
  306. usageDateEnd,
  307. usageStats,
  308. dataCategory,
  309. dataTransform,
  310. chartSeries,
  311. chartTooltip,
  312. categoryColors,
  313. isLoading,
  314. isError,
  315. errors,
  316. categoryOptions = CHART_OPTIONS_DATACATEGORY,
  317. usageDateInterval = '1d',
  318. usageDateShowUtc = true,
  319. yAxisFormatter,
  320. handleDataTransformation = cumulativeTotalDataTransformation,
  321. }: UsageChartProps) {
  322. const theme = useTheme();
  323. const organization = useOrganization();
  324. const filteredOptions = useMemo(() => {
  325. return categoryOptions.filter(option => {
  326. if (option.value !== DATA_CATEGORY_INFO.metrics.plural) {
  327. return true;
  328. }
  329. return hasCustomMetrics(organization);
  330. });
  331. }, [organization, categoryOptions]);
  332. if (isLoading) {
  333. return (
  334. <Placeholder height="200px">
  335. <LoadingIndicator mini />
  336. </Placeholder>
  337. );
  338. }
  339. if (isError) {
  340. return (
  341. <Placeholder height="200px">
  342. <IconWarning size="sm" />
  343. <ErrorMessages data-test-id="error-messages">
  344. {errors &&
  345. Object.keys(errors).map(k => <span key={k}>{errors[k]?.message}</span>)}
  346. </ErrorMessages>
  347. </Placeholder>
  348. );
  349. }
  350. const yAxisLabelFormatter = yAxisFormatter ?? getUnitYaxisFormatter(dataCategory);
  351. const {
  352. chartData,
  353. tooltipValueFormatter,
  354. xAxisData,
  355. xAxisTickInterval,
  356. xAxisLabelInterval,
  357. yAxisMinInterval,
  358. } = chartMetadata({
  359. categoryOptions: filteredOptions,
  360. dataCategory,
  361. handleDataTransformation: handleDataTransformation!,
  362. usageStats,
  363. dataTransform,
  364. usageDateStart,
  365. usageDateEnd,
  366. usageDateInterval,
  367. usageDateShowUtc,
  368. });
  369. function chartLegendData() {
  370. const legend: LegendComponentOption['data'] = [
  371. ...(chartData.reserved && chartData.reserved.length > 0
  372. ? []
  373. : [
  374. {
  375. name: SeriesTypes.ACCEPTED,
  376. },
  377. ]),
  378. ];
  379. if (chartData.filtered && chartData.filtered.length > 0) {
  380. legend.push({
  381. name: SeriesTypes.FILTERED,
  382. });
  383. }
  384. if (chartData.dropped.length > 0) {
  385. legend.push({
  386. name: SeriesTypes.DROPPED,
  387. });
  388. }
  389. if (chartData.projected.length > 0) {
  390. legend.push({
  391. name: SeriesTypes.PROJECTED,
  392. });
  393. }
  394. if (chartSeries) {
  395. chartSeries.forEach(chartOption => {
  396. if (chartOption.name) {
  397. legend.push({name: `${chartOption.name}`});
  398. }
  399. });
  400. }
  401. return legend;
  402. }
  403. const colors = categoryColors?.length
  404. ? categoryColors
  405. : chartColors(theme, dataCategory);
  406. const series: SeriesOption[] = [
  407. barSeries({
  408. name: SeriesTypes.ACCEPTED,
  409. data: chartData.accepted,
  410. barMinHeight: 1,
  411. stack: 'usage',
  412. legendHoverLink: false,
  413. }),
  414. barSeries({
  415. name: SeriesTypes.FILTERED,
  416. data: chartData.filtered,
  417. barMinHeight: 1,
  418. stack: 'usage',
  419. legendHoverLink: false,
  420. }),
  421. barSeries({
  422. name: SeriesTypes.DROPPED,
  423. data: chartData.dropped,
  424. stack: 'usage',
  425. legendHoverLink: false,
  426. }),
  427. barSeries({
  428. name: SeriesTypes.PROJECTED,
  429. data: chartData.projected,
  430. barMinHeight: 1,
  431. stack: 'usage',
  432. legendHoverLink: false,
  433. }),
  434. // Additional series passed by parent component
  435. ...(chartSeries || []),
  436. ];
  437. return (
  438. <BaseChart
  439. colors={colors}
  440. grid={{bottom: '3px', left: '3px', right: '10px', top: '40px'}}
  441. xAxis={xAxis({
  442. show: true,
  443. type: 'category',
  444. name: 'Date',
  445. data: xAxisData,
  446. axisTick: {
  447. interval: xAxisTickInterval,
  448. alignWithLabel: true,
  449. },
  450. axisLabel: {
  451. interval: xAxisLabelInterval,
  452. formatter: (label: string) => label.slice(0, 6), // Limit label to 6 chars
  453. },
  454. theme,
  455. })}
  456. yAxis={{
  457. min: 0,
  458. minInterval: yAxisMinInterval,
  459. axisLabel: {
  460. formatter: yAxisLabelFormatter,
  461. color: theme.chartLabel,
  462. },
  463. }}
  464. series={series}
  465. tooltip={
  466. chartTooltip
  467. ? chartTooltip
  468. : {
  469. // Trigger to axis prevents tooltip from redrawing when hovering
  470. // over individual bars
  471. trigger: 'axis',
  472. valueFormatter: tooltipValueFormatter,
  473. }
  474. }
  475. onLegendSelectChanged={() => {}}
  476. legend={Legend({
  477. right: 10,
  478. top: 5,
  479. data: chartLegendData(),
  480. theme,
  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. `;