chart.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 addAreaChartSeriesPadding(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[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.AREA
  114. ? addAreaChartSeriesPadding(s.data)
  115. : {data: s.data}),
  116. connectNulls: displayType === MetricDisplayType.LINE,
  117. }))
  118. // Split series in two parts, one for the main chart and one for the fog of war
  119. // The order is important as the tooltip will show the first series first (for overlaps)
  120. .flatMap(s => [
  121. {
  122. ...s,
  123. silent: true,
  124. data: s.data.slice(0, -fogOfWarBuckets),
  125. },
  126. displayType === MetricDisplayType.BAR
  127. ? createFogOfWarBarSeries(s, fogOfWarBuckets)
  128. : displayType === MetricDisplayType.LINE
  129. ? createFogOfWarLineSeries(s, fogOfWarBuckets)
  130. : createFogOfWarAreaSeries(s, fogOfWarBuckets),
  131. ]),
  132. [series, fogOfWarBuckets, displayType]
  133. );
  134. const valueFormatter = useCallback(
  135. (value: number) => {
  136. return formatMetricsUsingUnitAndOp(value, unit, operation);
  137. },
  138. [unit, operation]
  139. );
  140. const samples = useChartSamples({
  141. chartRef,
  142. correlations: scatter?.data,
  143. onClick: scatter?.onClick,
  144. highlightedSampleId: scatter?.higlightedId,
  145. operation,
  146. timeseries: series,
  147. valueFormatter,
  148. });
  149. const chartProps = useMemo(() => {
  150. const timeseriesFormatters = {
  151. valueFormatter,
  152. isGroupedByDate: true,
  153. bucketSize,
  154. showTimeInTooltip: true,
  155. addSecondsToTimeFormat: isSubMinuteBucket,
  156. limit: 10,
  157. filter: (_, seriesParam) => {
  158. return seriesParam?.axisId === 'xAxis';
  159. },
  160. };
  161. const heightOptions = height ? {height} : {autoHeightResize: true};
  162. return {
  163. ...heightOptions,
  164. ...focusAreaBrush.options,
  165. forwardedRef: mergeRefs([forwardedRef, chartRef]),
  166. series: seriesToShow,
  167. devicePixelRatio: 2,
  168. renderer: 'canvas' as const,
  169. isGroupedByDate: true,
  170. colors: seriesToShow.map(s => s.color),
  171. grid: {top: 5, bottom: 0, left: 0, right: 0},
  172. onClick: samples.handleClick,
  173. tooltip: {
  174. formatter: (params, asyncTicket) => {
  175. if (focusAreaBrush.isDrawingRef.current) {
  176. return '';
  177. }
  178. if (!isChartHovered(chartRef?.current)) {
  179. return '';
  180. }
  181. // Hovering a single correlated sample datapoint
  182. if (params.seriesType === 'scatter') {
  183. return getFormatter(samples.formatters)(params, asyncTicket);
  184. }
  185. // The mechanism by which we add the fog of war series to the chart, duplicates the series in the chart data
  186. // so we need to deduplicate the series before showing the tooltip
  187. // this assumes that the first series is the main series and the second is the fog of war series
  188. if (Array.isArray(params)) {
  189. const uniqueSeries = new Set<string>();
  190. const deDupedParams = params.filter(param => {
  191. // Filter null values from tooltip
  192. if (param.value[1] === null) {
  193. return false;
  194. }
  195. // scatter series (samples) have their own tooltip
  196. if (param.seriesType === 'scatter') {
  197. return false;
  198. }
  199. // Filter padding datapoints from tooltip
  200. if (param.value[1] === 0) {
  201. const currentSeries = seriesToShow[param.seriesIndex];
  202. const paddingIndices =
  203. 'paddingIndices' in currentSeries
  204. ? currentSeries.paddingIndices
  205. : undefined;
  206. if (paddingIndices?.has(param.dataIndex)) {
  207. return false;
  208. }
  209. }
  210. if (uniqueSeries.has(param.seriesName)) {
  211. return false;
  212. }
  213. uniqueSeries.add(param.seriesName);
  214. return true;
  215. });
  216. const date = defaultFormatAxisLabel(
  217. params[0].value[0] as number,
  218. timeseriesFormatters.isGroupedByDate,
  219. false,
  220. timeseriesFormatters.showTimeInTooltip,
  221. timeseriesFormatters.addSecondsToTimeFormat,
  222. timeseriesFormatters.bucketSize
  223. );
  224. if (deDupedParams.length === 0) {
  225. return [
  226. '<div class="tooltip-series">',
  227. `<center>${t('No data available')}</center>`,
  228. '</div>',
  229. `<div class="tooltip-footer">${date}</div>`,
  230. ].join('');
  231. }
  232. return getFormatter(timeseriesFormatters)(deDupedParams, asyncTicket);
  233. }
  234. return getFormatter(timeseriesFormatters)(params, asyncTicket);
  235. },
  236. },
  237. yAxes: [
  238. {
  239. // used to find and convert datapoint to pixel position
  240. id: 'yAxis',
  241. axisLabel: {
  242. formatter: (value: number) => {
  243. return valueFormatter(value);
  244. },
  245. },
  246. },
  247. samples.yAxis,
  248. ],
  249. xAxes: [
  250. {
  251. // used to find and convert datapoint to pixel position
  252. id: 'xAxis',
  253. axisPointer: {
  254. snap: true,
  255. },
  256. },
  257. samples.xAxis,
  258. ],
  259. };
  260. }, [
  261. bucketSize,
  262. focusAreaBrush.options,
  263. focusAreaBrush.isDrawingRef,
  264. forwardedRef,
  265. isSubMinuteBucket,
  266. seriesToShow,
  267. height,
  268. samples.handleClick,
  269. samples.xAxis,
  270. samples.yAxis,
  271. samples.formatters,
  272. valueFormatter,
  273. ]);
  274. return (
  275. <ChartWrapper>
  276. {focusAreaBrush.overlay}
  277. <CombinedChart
  278. {...chartProps}
  279. displayType={displayType}
  280. scatterSeries={samples.series}
  281. />
  282. </ChartWrapper>
  283. );
  284. }
  285. );
  286. interface CombinedChartProps extends BaseChartProps {
  287. displayType: MetricDisplayType;
  288. series: Series[];
  289. scatterSeries?: ScatterSeriesType[];
  290. }
  291. function CombinedChart({
  292. displayType,
  293. series,
  294. scatterSeries = [],
  295. ...chartProps
  296. }: CombinedChartProps) {
  297. const combinedSeries = useMemo(() => {
  298. if (displayType === MetricDisplayType.LINE) {
  299. return [
  300. ...transformToLineSeries({series}),
  301. ...transformToScatterSeries({series: scatterSeries, displayType}),
  302. ];
  303. }
  304. if (displayType === MetricDisplayType.BAR) {
  305. return [
  306. ...transformToBarSeries({series, stacked: true, animation: false}),
  307. ...transformToScatterSeries({series: scatterSeries, displayType}),
  308. ];
  309. }
  310. if (displayType === MetricDisplayType.AREA) {
  311. return [
  312. ...transformToAreaSeries({series, stacked: true, colors: chartProps.colors}),
  313. ...transformToScatterSeries({series: scatterSeries, displayType}),
  314. ];
  315. }
  316. return [];
  317. }, [displayType, scatterSeries, series, chartProps.colors]);
  318. return <BaseChart {...chartProps} series={combinedSeries} />;
  319. }
  320. function transformToScatterSeries({
  321. series,
  322. displayType,
  323. }: {
  324. displayType: MetricDisplayType;
  325. series: Series[];
  326. }) {
  327. return series.map(({seriesName, data: seriesData, ...options}) => {
  328. if (displayType === MetricDisplayType.BAR) {
  329. return ScatterSeries({
  330. ...options,
  331. name: seriesName,
  332. data: seriesData?.map(({value, name}) => ({value: [name, value]})),
  333. });
  334. }
  335. return ScatterSeries({
  336. ...options,
  337. name: seriesName,
  338. data: seriesData?.map(({value, name}) => [name, value]),
  339. animation: false,
  340. });
  341. });
  342. }
  343. const EXTRAPOLATED_AREA_STRIPE_IMG =
  344. 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAABkCAYAAAC/zKGXAAAAMUlEQVR4Ae3KoREAIAwEsMKgrMeYj8BzyIpEZyTZda16mPVJFEVRFEVRFEVRFMWO8QB4uATKpuU51gAAAABJRU5ErkJggg==';
  345. const createFogOfWarBarSeries = (series: Series, fogBucketCnt = 0) => ({
  346. ...series,
  347. silent: true,
  348. data: series.data.map((data, index) => ({
  349. ...data,
  350. // W need to set a value for the non-fog of war buckets so that the stacking still works in echarts
  351. value: index < series.data.length - fogBucketCnt ? 0 : data.value,
  352. })),
  353. itemStyle: {
  354. opacity: 1,
  355. decal: {
  356. symbol: EXTRAPOLATED_AREA_STRIPE_IMG,
  357. dashArrayX: [6, 0],
  358. dashArrayY: [6, 0],
  359. rotation: Math.PI / 4,
  360. },
  361. },
  362. });
  363. const createFogOfWarLineSeries = (series: Series, fogBucketCnt = 0) => ({
  364. ...series,
  365. silent: true,
  366. // We include the last non-fog of war bucket so that the line is connected
  367. data: series.data.slice(-fogBucketCnt - 1),
  368. lineStyle: {
  369. type: 'dotted',
  370. },
  371. });
  372. const createFogOfWarAreaSeries = (series: Series, fogBucketCnt = 0) => ({
  373. ...series,
  374. silent: true,
  375. stack: 'fogOfWar',
  376. // We include the last non-fog of war bucket so that the line is connected
  377. data: series.data.slice(-fogBucketCnt - 1),
  378. lineStyle: {
  379. type: 'dotted',
  380. color: Color(series.color).lighten(0.3).string(),
  381. },
  382. });
  383. function getWidthFactor(bucketSize: number) {
  384. // If the bucket size is >= 5 minutes the fog of war should only cover the last bucket
  385. if (bucketSize >= 5 * 60_000) {
  386. return 1;
  387. }
  388. // for buckets <= 10s we want to show a fog of war that spans last 10 buckets
  389. // because on average, we are missing last 90 seconds of data
  390. if (bucketSize <= 10_000) {
  391. return 10;
  392. }
  393. // For smaller time frames we want to show a wider fog of war
  394. return 2;
  395. }
  396. const ChartWrapper = styled('div')`
  397. position: relative;
  398. height: 100%;
  399. `;