chart.tsx 14 KB

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