chart.tsx 14 KB

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