chart.tsx 16 KB

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