chart.tsx 16 KB

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