chart.tsx 14 KB

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