chart.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. import {forwardRef, memo, useEffect, useMemo, useRef} from 'react';
  2. import styled from '@emotion/styled';
  3. import Color from 'color';
  4. import type {SeriesOption} from 'echarts';
  5. import * as echarts from 'echarts/core';
  6. import {CanvasRenderer} from 'echarts/renderers';
  7. import isNil from 'lodash/isNil';
  8. import omitBy from 'lodash/omitBy';
  9. import {transformToAreaSeries} from 'sentry/components/charts/areaChart';
  10. import {transformToBarSeries} from 'sentry/components/charts/barChart';
  11. import BaseChart, {type BaseChartProps} from 'sentry/components/charts/baseChart';
  12. import {
  13. defaultFormatAxisLabel,
  14. getFormatter,
  15. } from 'sentry/components/charts/components/tooltip';
  16. import {transformToLineSeries} from 'sentry/components/charts/lineChart';
  17. import ScatterSeries from 'sentry/components/charts/series/scatterSeries';
  18. import ChartZoom from 'sentry/components/charts/useChartZoom';
  19. import {isChartHovered} from 'sentry/components/charts/utils';
  20. import {t} from 'sentry/locale';
  21. import type {ReactEchartsRef} from 'sentry/types/echarts';
  22. import mergeRefs from 'sentry/utils/mergeRefs';
  23. import {formatMetricUsingUnit} from 'sentry/utils/metrics/formatters';
  24. import {MetricDisplayType} from 'sentry/utils/metrics/types';
  25. import usePageFilters from 'sentry/utils/usePageFilters';
  26. import type {CombinedMetricChartProps, Series} from 'sentry/views/metrics/chart/types';
  27. import type {UseFocusAreaResult} from 'sentry/views/metrics/chart/useFocusArea';
  28. import type {UseMetricSamplesResult} from 'sentry/views/metrics/chart/useMetricChartSamples';
  29. import type {UseMetricReleasesResult} from 'sentry/views/metrics/chart/useMetricReleases';
  30. const MAIN_X_AXIS_ID = 'xAxis';
  31. type ChartProps = {
  32. displayType: MetricDisplayType;
  33. series: Series[];
  34. additionalSeries?: SeriesOption[];
  35. enableZoom?: boolean;
  36. focusArea?: UseFocusAreaResult;
  37. group?: string;
  38. height?: number;
  39. releases?: UseMetricReleasesResult;
  40. samples?: UseMetricSamplesResult;
  41. showLegend?: boolean;
  42. };
  43. function getLegendProps(showLegend?: boolean): Pick<BaseChartProps, 'legend' | 'grid'> {
  44. if (showLegend) {
  45. return {
  46. legend: {
  47. show: true,
  48. left: 0,
  49. top: 0,
  50. },
  51. grid: {
  52. top: 40,
  53. bottom: 0,
  54. left: 0,
  55. right: 0,
  56. },
  57. };
  58. }
  59. return {
  60. grid: {
  61. top: 5,
  62. bottom: 0,
  63. left: 0,
  64. right: 0,
  65. },
  66. };
  67. }
  68. // We need to enable canvas renderer for echarts before we use it here.
  69. // Once we use it in more places, this should probably move to a more global place
  70. // But for now we keep it here to not invluence the bundle size of the main chunks.
  71. echarts.use(CanvasRenderer);
  72. function isNonZeroValue(value: number | null) {
  73. return value !== null && value !== 0;
  74. }
  75. function addSeriesPadding(data: Series['data']) {
  76. const hasNonZeroSibling = (index: number) => {
  77. return (
  78. isNonZeroValue(data[index - 1]?.value) || isNonZeroValue(data[index + 1]?.value)
  79. );
  80. };
  81. const paddingIndices = new Set<number>();
  82. return {
  83. data: data.map(({name, value}, index) => {
  84. const shouldAddPadding = value === null && hasNonZeroSibling(index);
  85. if (shouldAddPadding) {
  86. paddingIndices.add(index);
  87. }
  88. return {
  89. name,
  90. value: shouldAddPadding ? 0 : value,
  91. };
  92. }),
  93. paddingIndices,
  94. };
  95. }
  96. export const MetricChart = memo(
  97. forwardRef<ReactEchartsRef, ChartProps>(
  98. (
  99. {
  100. series,
  101. displayType,
  102. height,
  103. group,
  104. samples,
  105. focusArea,
  106. enableZoom,
  107. releases,
  108. additionalSeries,
  109. showLegend,
  110. },
  111. forwardedRef
  112. ) => {
  113. const chartRef = useRef<ReactEchartsRef>(null);
  114. const filteredSeries = useMemo(() => series.filter(s => !s.hidden), [series]);
  115. const firstUnit = filteredSeries[0]?.unit || 'none';
  116. const uniqueUnits = useMemo(
  117. () => [...new Set(filteredSeries.map(s => s.unit || 'none'))],
  118. [filteredSeries]
  119. );
  120. useEffect(() => {
  121. if (!group) {
  122. return;
  123. }
  124. const echartsInstance = chartRef?.current?.getEchartsInstance();
  125. if (echartsInstance && !echartsInstance.group) {
  126. echartsInstance.group = group;
  127. }
  128. });
  129. const bucketSize = series[0]?.data[1]?.name - series[0]?.data[0]?.name;
  130. const isSubMinuteBucket = bucketSize < 60_000;
  131. const lastBucketTimestamp = series[0]?.data?.[series[0]?.data?.length - 1]?.name;
  132. const ingestionBuckets = useMemo(
  133. () => getIngestionDelayBucketCount(bucketSize, lastBucketTimestamp),
  134. [bucketSize, lastBucketTimestamp]
  135. );
  136. const seriesToShow = useMemo(
  137. () =>
  138. filteredSeries
  139. .map(s => {
  140. const mappedSeries = {
  141. ...s,
  142. silent: true,
  143. yAxisIndex: uniqueUnits.indexOf(s.unit),
  144. xAxisIndex: 0,
  145. ...(displayType !== MetricDisplayType.BAR
  146. ? addSeriesPadding(s.data)
  147. : {data: s.data}),
  148. };
  149. if (displayType === MetricDisplayType.BAR) {
  150. mappedSeries.stack = s.unit;
  151. }
  152. return mappedSeries;
  153. })
  154. // Split series in two parts, one for the main chart and one for the fog of war
  155. // The order is important as the tooltip will show the first series first (for overlaps)
  156. .flatMap(s => createIngestionSeries(s, ingestionBuckets, displayType)),
  157. [filteredSeries, uniqueUnits, displayType, ingestionBuckets]
  158. );
  159. const {selection} = usePageFilters();
  160. const dateTimeOptions = useMemo(() => {
  161. return omitBy(selection.datetime, isNil);
  162. }, [selection.datetime]);
  163. const chartProps = useMemo(() => {
  164. const seriesUnits = seriesToShow.reduce(
  165. (acc, s) => {
  166. acc[s.seriesName] = s.unit;
  167. return acc;
  168. },
  169. {} as Record<string, string>
  170. );
  171. const timeseriesFormatters = {
  172. valueFormatter: (value: number, seriesName?: string) => {
  173. const unit = (seriesName && seriesUnits[seriesName]) ?? 'none';
  174. return formatMetricUsingUnit(value, unit);
  175. },
  176. isGroupedByDate: true,
  177. bucketSize,
  178. showTimeInTooltip: true,
  179. addSecondsToTimeFormat: isSubMinuteBucket,
  180. limit: 10,
  181. utc: !!dateTimeOptions.utc,
  182. filter: (_, seriesParam) => {
  183. return seriesParam?.axisId === MAIN_X_AXIS_ID;
  184. },
  185. };
  186. const heightOptions = height ? {height} : {autoHeightResize: true};
  187. let baseChartProps: CombinedMetricChartProps = {
  188. ...heightOptions,
  189. ...dateTimeOptions,
  190. ...getLegendProps(showLegend),
  191. displayType,
  192. forwardedRef: mergeRefs([forwardedRef, chartRef]),
  193. series: seriesToShow,
  194. devicePixelRatio: 2,
  195. renderer: 'canvas' as const,
  196. isGroupedByDate: true,
  197. colors: seriesToShow.map(s => s.color),
  198. additionalSeries,
  199. tooltip: {
  200. formatter: (params, asyncTicket) => {
  201. // Only show the tooltip if the current chart is hovered
  202. // as chart groups trigger the tooltip for all charts in the group when one is hoverered
  203. if (!isChartHovered(chartRef?.current)) {
  204. return '';
  205. }
  206. // The mechanism by which we display ingestion delay the chart, duplicates the series in the chart data
  207. // so we need to de-duplicate the series before showing the tooltip
  208. // this assumes that the first series is the main series and the second is the ingestion delay series
  209. if (Array.isArray(params)) {
  210. const uniqueSeries = new Set<string>();
  211. const deDupedParams = params.filter(param => {
  212. // Filter null values from tooltip
  213. if (param.value[1] === null) {
  214. return false;
  215. }
  216. // scatter series (samples) have their own tooltip
  217. if (param.seriesType === 'scatter') {
  218. return false;
  219. }
  220. // Filter padding datapoints from tooltip
  221. if (param.value[1] === 0) {
  222. const currentSeries = seriesToShow[param.seriesIndex];
  223. const paddingIndices =
  224. 'paddingIndices' in currentSeries
  225. ? currentSeries.paddingIndices
  226. : undefined;
  227. if (paddingIndices?.has(param.dataIndex)) {
  228. return false;
  229. }
  230. }
  231. if (uniqueSeries.has(param.seriesName)) {
  232. return false;
  233. }
  234. uniqueSeries.add(param.seriesName);
  235. return true;
  236. });
  237. const formattedDate = defaultFormatAxisLabel(
  238. params[0].value[0] as number,
  239. timeseriesFormatters.isGroupedByDate,
  240. timeseriesFormatters.utc,
  241. timeseriesFormatters.showTimeInTooltip,
  242. timeseriesFormatters.addSecondsToTimeFormat,
  243. timeseriesFormatters.bucketSize
  244. );
  245. if (deDupedParams.length === 0) {
  246. return [
  247. '<div class="tooltip-series">',
  248. `<center>${t('No data available')}</center>`,
  249. '</div>',
  250. `<div class="tooltip-footer">${formattedDate}</div>`,
  251. ].join('');
  252. }
  253. return getFormatter(timeseriesFormatters)(deDupedParams, asyncTicket);
  254. }
  255. return getFormatter(timeseriesFormatters)(params, asyncTicket);
  256. },
  257. },
  258. yAxes:
  259. uniqueUnits.length === 0
  260. ? // fallback axis for when there are no series as echarts requires at least one axis
  261. [
  262. {
  263. id: 'none',
  264. axisLabel: {
  265. formatter: (value: number) => {
  266. return formatMetricUsingUnit(value, 'none');
  267. },
  268. },
  269. },
  270. ]
  271. : [
  272. ...uniqueUnits.map((unit, index) =>
  273. unit === firstUnit
  274. ? {
  275. id: unit,
  276. axisLabel: {
  277. formatter: (value: number) => {
  278. return formatMetricUsingUnit(value, unit);
  279. },
  280. },
  281. }
  282. : {
  283. id: unit,
  284. show: index === 1,
  285. axisLabel: {
  286. show: index === 1,
  287. formatter: (value: number) => {
  288. return formatMetricUsingUnit(value, unit);
  289. },
  290. },
  291. splitLine: {
  292. show: false,
  293. },
  294. position: 'right' as const,
  295. axisPointer: {
  296. type: 'none' as const,
  297. },
  298. }
  299. ),
  300. ],
  301. xAxes: [
  302. {
  303. id: MAIN_X_AXIS_ID,
  304. axisPointer: {
  305. snap: true,
  306. },
  307. },
  308. ],
  309. };
  310. if (samples?.applyChartProps) {
  311. baseChartProps = samples.applyChartProps(baseChartProps);
  312. }
  313. if (releases?.applyChartProps) {
  314. baseChartProps = releases.applyChartProps(baseChartProps);
  315. }
  316. // Apply focus area props as last so it can disable tooltips
  317. if (focusArea?.applyChartProps) {
  318. baseChartProps = focusArea.applyChartProps(baseChartProps);
  319. }
  320. return baseChartProps;
  321. }, [
  322. seriesToShow,
  323. dateTimeOptions,
  324. bucketSize,
  325. isSubMinuteBucket,
  326. height,
  327. displayType,
  328. forwardedRef,
  329. uniqueUnits,
  330. samples,
  331. focusArea,
  332. releases,
  333. firstUnit,
  334. additionalSeries,
  335. showLegend,
  336. ]);
  337. if (!enableZoom) {
  338. return (
  339. <ChartWrapper>
  340. {focusArea?.overlay}
  341. <CombinedChart {...chartProps} />
  342. </ChartWrapper>
  343. );
  344. }
  345. return (
  346. <ChartWrapper>
  347. <ChartZoom>
  348. {zoomRenderProps => <CombinedChart {...chartProps} {...zoomRenderProps} />}
  349. </ChartZoom>
  350. </ChartWrapper>
  351. );
  352. }
  353. )
  354. );
  355. function CombinedChart({
  356. displayType,
  357. series,
  358. scatterSeries = [],
  359. additionalSeries = [],
  360. ...chartProps
  361. }: CombinedMetricChartProps) {
  362. const combinedSeries = useMemo(() => {
  363. if (displayType === MetricDisplayType.LINE) {
  364. return [
  365. ...transformToLineSeries({series}),
  366. ...transformToScatterSeries({series: scatterSeries, displayType}),
  367. ...additionalSeries,
  368. ];
  369. }
  370. if (displayType === MetricDisplayType.BAR) {
  371. return [
  372. ...transformToBarSeries({series, stacked: true, animation: false}),
  373. ...transformToScatterSeries({series: scatterSeries, displayType}),
  374. ...additionalSeries,
  375. ];
  376. }
  377. if (displayType === MetricDisplayType.AREA) {
  378. return [
  379. ...transformToAreaSeries({series, stacked: true, colors: chartProps.colors}),
  380. ...transformToScatterSeries({series: scatterSeries, displayType}),
  381. ...additionalSeries,
  382. ];
  383. }
  384. return [];
  385. }, [displayType, series, scatterSeries, additionalSeries, chartProps.colors]);
  386. return <BaseChart {...chartProps} series={combinedSeries} />;
  387. }
  388. function transformToScatterSeries({
  389. series,
  390. displayType,
  391. }: {
  392. displayType: MetricDisplayType;
  393. series: Series[];
  394. }) {
  395. return series.map(({seriesName, data: seriesData, ...options}) => {
  396. if (displayType === MetricDisplayType.BAR) {
  397. return ScatterSeries({
  398. ...options,
  399. name: seriesName,
  400. data: seriesData?.map(({value, name}) => ({value: [name, value]})),
  401. });
  402. }
  403. return ScatterSeries({
  404. ...options,
  405. name: seriesName,
  406. data: seriesData?.map(({value, name}) => [name, value]),
  407. animation: false,
  408. });
  409. });
  410. }
  411. function createIngestionSeries(
  412. orignalSeries: Series,
  413. ingestionBuckets: number,
  414. displayType: MetricDisplayType
  415. ) {
  416. if (ingestionBuckets < 1) {
  417. return [orignalSeries];
  418. }
  419. const series = [
  420. {
  421. ...orignalSeries,
  422. data: orignalSeries.data.slice(0, -ingestionBuckets),
  423. },
  424. ];
  425. if (displayType === MetricDisplayType.BAR) {
  426. series.push(createIngestionBarSeries(orignalSeries, ingestionBuckets));
  427. } else if (displayType === MetricDisplayType.AREA) {
  428. series.push(createIngestionAreaSeries(orignalSeries, ingestionBuckets));
  429. } else {
  430. series.push(createIngestionLineSeries(orignalSeries, ingestionBuckets));
  431. }
  432. return series;
  433. }
  434. const EXTRAPOLATED_AREA_STRIPE_IMG =
  435. 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAABkCAYAAAC/zKGXAAAAMUlEQVR4Ae3KoREAIAwEsMKgrMeYj8BzyIpEZyTZda16mPVJFEVRFEVRFEVRFMWO8QB4uATKpuU51gAAAABJRU5ErkJggg==';
  436. export const getIngestionSeriesId = (seriesId: string) => `${seriesId}-ingestion`;
  437. function createIngestionBarSeries(series: Series, fogBucketCnt = 0) {
  438. return {
  439. ...series,
  440. id: getIngestionSeriesId(series.id),
  441. silent: true,
  442. data: series.data.map((data, index) => ({
  443. ...data,
  444. // W need to set a value for the non-fog of war buckets so that the stacking still works in echarts
  445. value: index < series.data.length - fogBucketCnt ? 0 : data.value,
  446. })),
  447. itemStyle: {
  448. opacity: 1,
  449. decal: {
  450. symbol: EXTRAPOLATED_AREA_STRIPE_IMG,
  451. dashArrayX: [6, 0],
  452. dashArrayY: [6, 0],
  453. rotation: Math.PI / 4,
  454. },
  455. },
  456. };
  457. }
  458. function createIngestionLineSeries(series: Series, fogBucketCnt = 0) {
  459. return {
  460. ...series,
  461. id: getIngestionSeriesId(series.id),
  462. silent: true,
  463. // We include the last non-fog of war bucket so that the line is connected
  464. data: series.data.slice(-fogBucketCnt - 1),
  465. lineStyle: {
  466. type: 'dotted',
  467. },
  468. };
  469. }
  470. function createIngestionAreaSeries(series: Series, fogBucketCnt = 0) {
  471. return {
  472. ...series,
  473. id: getIngestionSeriesId(series.id),
  474. silent: true,
  475. stack: 'fogOfWar',
  476. // We include the last non-fog of war bucket so that the line is connected
  477. data: series.data.slice(-fogBucketCnt - 1),
  478. lineStyle: {
  479. type: 'dotted',
  480. color: Color(series.color).lighten(0.3).string(),
  481. },
  482. };
  483. }
  484. const AVERAGE_INGESTION_DELAY_MS = 90_000;
  485. /**
  486. * Calculates the number of buckets, affected by ingestion delay.
  487. * Based on the AVERAGE_INGESTION_DELAY_MS
  488. * @param bucketSize in ms
  489. * @param lastBucketTimestamp starting time of the last bucket in ms
  490. */
  491. function getIngestionDelayBucketCount(bucketSize: number, lastBucketTimestamp: number) {
  492. const timeSinceLastBucket = Date.now() - (lastBucketTimestamp + bucketSize);
  493. const ingestionAffectedTime = Math.max(
  494. 0,
  495. AVERAGE_INGESTION_DELAY_MS - timeSinceLastBucket
  496. );
  497. return Math.ceil(ingestionAffectedTime / bucketSize);
  498. }
  499. const ChartWrapper = styled('div')`
  500. position: relative;
  501. height: 100%;
  502. `;