index.tsx 14 KB

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