useMetricChartSamples.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import type {RefObject} from 'react';
  2. import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
  3. import {useTheme} from '@emotion/react';
  4. import type {XAXisOption, YAXisOption} from 'echarts/types/dist/shared';
  5. import moment from 'moment';
  6. import {getFormatter} from 'sentry/components/charts/components/tooltip';
  7. import {isChartHovered} from 'sentry/components/charts/utils';
  8. import type {Field} from 'sentry/components/ddm/metricSamplesTable';
  9. import {t} from 'sentry/locale';
  10. import type {EChartClickHandler, ReactEchartsRef, Series} from 'sentry/types/echarts';
  11. import {defined} from 'sentry/utils';
  12. import mergeRefs from 'sentry/utils/mergeRefs';
  13. import {isCumulativeOp} from 'sentry/utils/metrics';
  14. import {formatMetricsUsingUnitAndOp} from 'sentry/utils/metrics/formatters';
  15. import {getMetricValueNormalizer} from 'sentry/utils/metrics/normalizeMetricValue';
  16. import type {MetricCorrelation, MetricSummary} from 'sentry/utils/metrics/types';
  17. import {
  18. getSummaryValueForOp,
  19. type MetricsSamplesResults,
  20. } from 'sentry/utils/metrics/useMetricsSamples';
  21. import {fitToValueRect, getValueRect} from 'sentry/views/ddm/chart/chartUtils';
  22. import type {CombinedMetricChartProps} from 'sentry/views/ddm/chart/types';
  23. import type {Sample} from 'sentry/views/ddm/widget';
  24. type UseChartSamplesProps = {
  25. timeseries: Series[];
  26. chartRef?: RefObject<ReactEchartsRef>;
  27. correlations?: MetricCorrelation[];
  28. highlightedSampleId?: string;
  29. onClick?: (sample: Sample) => void;
  30. onMouseOut?: (sample: Sample) => void;
  31. onMouseOver?: (sample: Sample) => void;
  32. operation?: string;
  33. unit?: string;
  34. };
  35. // TODO: remove this once we have a stabilized type for this
  36. type ChartSample = MetricCorrelation & MetricSummary;
  37. function getDateRange(timeseries: Series[]) {
  38. if (!timeseries?.length) {
  39. return {min: -Infinity, max: Infinity};
  40. }
  41. const min = timeseries[0].data[0].name as number;
  42. const max = timeseries[0].data[timeseries[0].data.length - 1].name as number;
  43. return {min, max};
  44. }
  45. type EChartMouseEventParam = Parameters<EChartClickHandler>[0];
  46. export function useMetricChartSamples({
  47. correlations,
  48. onClick,
  49. highlightedSampleId,
  50. unit = '',
  51. operation,
  52. timeseries,
  53. }: UseChartSamplesProps) {
  54. const theme = useTheme();
  55. const chartRef = useRef<ReactEchartsRef>(null);
  56. const [valueRect, setValueRect] = useState(getValueRect(chartRef));
  57. const samples: Record<string, ChartSample> = useMemo(() => {
  58. return (correlations ?? [])
  59. ?.flatMap(correlation => [
  60. ...correlation.metricSummaries.map(summaries => ({...summaries, ...correlation})),
  61. ])
  62. .reduce((acc, sample) => {
  63. acc[sample.transactionId] = sample;
  64. return acc;
  65. }, {});
  66. }, [correlations]);
  67. useEffect(() => {
  68. // Changes in timeseries change the valueRect since the timeseries yAxis auto scales
  69. // and scatter yAxis needs to match the scale
  70. setValueRect(getValueRect(chartRef));
  71. }, [chartRef, timeseries]);
  72. const xAxis: XAXisOption = useMemo(() => {
  73. const {min, max} = getDateRange(timeseries);
  74. return {
  75. id: 'xAxisScatter',
  76. scale: false,
  77. show: false,
  78. axisLabel: {
  79. formatter: () => {
  80. return '';
  81. },
  82. },
  83. axisPointer: {
  84. type: 'none',
  85. },
  86. min: Math.max(valueRect.xMin, min),
  87. max: Math.min(valueRect.xMax, max),
  88. };
  89. }, [valueRect.xMin, valueRect.xMax, timeseries]);
  90. const yAxis: YAXisOption = useMemo(() => {
  91. return {
  92. id: 'yAxisScatter',
  93. scale: false,
  94. show: false,
  95. axisLabel: {
  96. formatter: () => {
  97. return '';
  98. },
  99. },
  100. min: valueRect.yMin,
  101. max: valueRect.yMax,
  102. };
  103. }, [valueRect.yMin, valueRect.yMax]);
  104. const getSample = useCallback(
  105. (event: EChartMouseEventParam): ChartSample | undefined => {
  106. return samples[event.seriesId];
  107. },
  108. [samples]
  109. );
  110. const handleClick = useCallback<EChartClickHandler>(
  111. (event: EChartMouseEventParam) => {
  112. if (!onClick) {
  113. return;
  114. }
  115. const sample = getSample(event);
  116. if (!sample) {
  117. return;
  118. }
  119. onClick(sample);
  120. },
  121. [getSample, onClick]
  122. );
  123. const series = useMemo(() => {
  124. if (isCumulativeOp(operation)) {
  125. // TODO: for now we do not show samples for cumulative operations,
  126. // we will implement them as marklines
  127. return [];
  128. }
  129. const normalizeMetric = getMetricValueNormalizer(unit ?? '');
  130. return Object.values(samples).map(sample => {
  131. const isHighlighted = highlightedSampleId === sample.transactionId;
  132. const xValue = moment(sample.timestamp).valueOf();
  133. const yValue = normalizeMetric(((sample.min ?? 0) + (sample.max ?? 0)) / 2) ?? 0;
  134. const [xPosition, yPosition] = fitToValueRect(xValue, yValue, valueRect);
  135. const symbol = yPosition === yValue ? 'circle' : 'arrow';
  136. const symbolRotate = yPosition > yValue ? 180 : 0;
  137. return {
  138. seriesName: sample.transactionId,
  139. id: sample.transactionId,
  140. operation: '',
  141. unit: '',
  142. symbolSize: isHighlighted ? 20 : 10,
  143. animation: false,
  144. symbol,
  145. symbolRotate,
  146. color: theme.purple400,
  147. // TODO: for now we just pass these ids through, but we should probably index
  148. // samples by an id and then just pass that reference
  149. itemStyle: {
  150. color: theme.purple400,
  151. opacity: 1,
  152. },
  153. yAxisIndex: 1,
  154. xAxisIndex: 1,
  155. xValue,
  156. yValue,
  157. tooltip: {
  158. axisPointer: {
  159. type: 'none',
  160. },
  161. },
  162. data: [
  163. {
  164. name: xPosition,
  165. value: yPosition,
  166. },
  167. ],
  168. z: 10,
  169. };
  170. });
  171. }, [operation, unit, samples, highlightedSampleId, valueRect, theme.purple400]);
  172. const formatterOptions = useMemo(() => {
  173. return {
  174. isGroupedByDate: true,
  175. limit: 1,
  176. showTimeInTooltip: true,
  177. addSecondsToTimeFormat: true,
  178. nameFormatter: (name: string) => {
  179. return t('Event %s', name.substring(0, 8));
  180. },
  181. valueFormatter: (_, label?: string) => {
  182. // We need to access the sample as the charts datapoints are fit to the charts viewport
  183. const sample = samples[label ?? ''];
  184. const yValue = ((sample.min ?? 0) + (sample.max ?? 0)) / 2;
  185. return formatMetricsUsingUnitAndOp(yValue, unit, operation);
  186. },
  187. };
  188. }, [operation, samples, unit]);
  189. const applyChartProps = useCallback(
  190. (baseProps: CombinedMetricChartProps): CombinedMetricChartProps => {
  191. return {
  192. ...baseProps,
  193. forwardedRef: mergeRefs([baseProps.forwardedRef, chartRef]),
  194. scatterSeries: series,
  195. xAxes: [...(Array.isArray(baseProps.xAxes) ? baseProps.xAxes : []), xAxis],
  196. yAxes: [...(Array.isArray(baseProps.yAxes) ? baseProps.yAxes : []), yAxis],
  197. onClick: (...args) => {
  198. handleClick(...args);
  199. baseProps.onClick?.(...args);
  200. },
  201. tooltip: {
  202. formatter: (params: any, asyncTicket) => {
  203. // Only show the tooltip if the current chart is hovered
  204. // as chart groups trigger the tooltip for all charts in the group when one is hoverered
  205. if (!isChartHovered(chartRef?.current)) {
  206. return '';
  207. }
  208. // Hovering a single correlated sample datapoint
  209. if (params.seriesType === 'scatter') {
  210. return getFormatter(formatterOptions)(params, asyncTicket);
  211. }
  212. const baseFormatter = baseProps.tooltip?.formatter;
  213. if (typeof baseFormatter === 'string') {
  214. return baseFormatter;
  215. }
  216. if (!baseFormatter) {
  217. throw new Error(
  218. 'You need to define a tooltip formatter for the chart when using metric samples'
  219. );
  220. }
  221. return baseFormatter(params, asyncTicket);
  222. },
  223. },
  224. };
  225. },
  226. [formatterOptions, handleClick, series, xAxis, yAxis]
  227. );
  228. // eslint-disable-next-line react-hooks/exhaustive-deps
  229. return useMemo(
  230. () => ({
  231. applyChartProps,
  232. }),
  233. [applyChartProps]
  234. );
  235. }
  236. interface UseMetricChartSamplesV2Options {
  237. timeseries: Series[];
  238. highlightedSampleId?: string;
  239. onSampleClick?: (sample: MetricsSamplesResults<Field>['data'][number]) => void;
  240. operation?: string;
  241. samples?: MetricsSamplesResults<Field>['data'];
  242. unit?: string;
  243. }
  244. export function useMetricChartSamplesV2({
  245. timeseries,
  246. highlightedSampleId,
  247. onSampleClick,
  248. operation,
  249. samples,
  250. unit = '',
  251. }: UseMetricChartSamplesV2Options) {
  252. const theme = useTheme();
  253. const chartRef = useRef<ReactEchartsRef>(null);
  254. const [valueRect, setValueRect] = useState(getValueRect(chartRef));
  255. const samplesById = useMemo(() => {
  256. return (samples ?? []).reduce((acc, sample) => {
  257. acc[sample.id] = sample;
  258. return acc;
  259. }, {});
  260. }, [samples]);
  261. useEffect(() => {
  262. // Changes in timeseries change the valueRect since the timeseries yAxis auto scales
  263. // and scatter yAxis needs to match the scale
  264. setValueRect(getValueRect(chartRef));
  265. }, [chartRef, timeseries]);
  266. const xAxis: XAXisOption = useMemo(() => {
  267. const {min, max} = getDateRange(timeseries);
  268. return {
  269. id: 'xAxisScatter',
  270. scale: false,
  271. show: false,
  272. axisLabel: {
  273. formatter: () => {
  274. return '';
  275. },
  276. },
  277. axisPointer: {
  278. type: 'none',
  279. },
  280. min: Math.max(valueRect.xMin, min),
  281. max: Math.min(valueRect.xMax, max),
  282. };
  283. }, [valueRect.xMin, valueRect.xMax, timeseries]);
  284. const yAxis: YAXisOption = useMemo(() => {
  285. return {
  286. id: 'yAxisScatter',
  287. scale: false,
  288. show: false,
  289. axisLabel: {
  290. formatter: () => {
  291. return '';
  292. },
  293. },
  294. min: valueRect.yMin,
  295. max: valueRect.yMax,
  296. };
  297. }, [valueRect.yMin, valueRect.yMax]);
  298. const series = useMemo(() => {
  299. if (isCumulativeOp(operation)) {
  300. // TODO: for now we do not show samples for cumulative operations
  301. // figure out how should this be shown
  302. return [];
  303. }
  304. const normalizeMetric = getMetricValueNormalizer(unit);
  305. return (samples ?? []).map(sample => {
  306. const isHighlighted = highlightedSampleId === sample.id;
  307. const xValue = moment(sample.timestamp).valueOf();
  308. const value = getSummaryValueForOp(sample.summary, operation);
  309. const yValue = normalizeMetric(value) ?? 0;
  310. const [xPosition, yPosition] = fitToValueRect(xValue, yValue, valueRect);
  311. return {
  312. seriesName: sample.id,
  313. id: sample.id,
  314. operation: '',
  315. unit: '',
  316. symbolSize: isHighlighted ? 20 : 10,
  317. animation: false,
  318. symbol: yPosition === yValue ? 'circle' : 'arrow',
  319. symbolRotate: yPosition > yValue ? 180 : 0,
  320. color: theme.purple400,
  321. itemStyle: {
  322. color: theme.purple400,
  323. opacity: 1,
  324. },
  325. yAxisIndex: 1,
  326. xAxisIndex: 1,
  327. xValue,
  328. yValue,
  329. tooltip: {
  330. axisPointer: {
  331. type: 'none',
  332. },
  333. },
  334. data: [
  335. {
  336. name: xPosition,
  337. value: yPosition,
  338. },
  339. ],
  340. z: 10,
  341. };
  342. });
  343. }, [highlightedSampleId, operation, samples, theme, unit, valueRect]);
  344. const formatterOptions = useMemo(() => {
  345. return {
  346. isGroupedByDate: true,
  347. limit: 1,
  348. showTimeInTooltip: true,
  349. addSecondsToTimeFormat: true,
  350. nameFormatter: (name: string) => {
  351. return t('Span %s', name.substring(0, 8));
  352. },
  353. valueFormatter: (_, label?: string) => {
  354. // We need to access the sample as the charts datapoints are fit to the charts viewport
  355. const sample = samplesById[label ?? ''];
  356. const yValue = getSummaryValueForOp(sample.summary, operation);
  357. return formatMetricsUsingUnitAndOp(yValue, unit, operation);
  358. },
  359. };
  360. }, [operation, samplesById, unit]);
  361. const handleClick = useCallback<EChartClickHandler>(
  362. (event: EChartMouseEventParam) => {
  363. const sample = samplesById[event.seriesId];
  364. if (defined(onSampleClick) && defined(sample)) {
  365. onSampleClick(sample);
  366. }
  367. },
  368. [onSampleClick, samplesById]
  369. );
  370. const applyChartProps = useCallback(
  371. (baseProps: CombinedMetricChartProps): CombinedMetricChartProps => {
  372. return {
  373. ...baseProps,
  374. forwardedRef: mergeRefs([baseProps.forwardedRef, chartRef]),
  375. scatterSeries: series,
  376. xAxes: [...(Array.isArray(baseProps.xAxes) ? baseProps.xAxes : []), xAxis],
  377. yAxes: [...(Array.isArray(baseProps.yAxes) ? baseProps.yAxes : []), yAxis],
  378. onClick: (...args) => {
  379. handleClick(...args);
  380. baseProps.onClick?.(...args);
  381. },
  382. tooltip: {
  383. formatter: (params: any, asyncTicket) => {
  384. // Only show the tooltip if the current chart is hovered
  385. // as chart groups trigger the tooltip for all charts in the group when one is hoverered
  386. if (!isChartHovered(chartRef?.current)) {
  387. return '';
  388. }
  389. // Hovering a single correlated sample datapoint
  390. if (params.seriesType === 'scatter') {
  391. return getFormatter(formatterOptions)(params, asyncTicket);
  392. }
  393. const baseFormatter = baseProps.tooltip?.formatter;
  394. if (typeof baseFormatter === 'string') {
  395. return baseFormatter;
  396. }
  397. if (!baseFormatter) {
  398. throw new Error(
  399. 'You need to define a tooltip formatter for the chart when using metric samples'
  400. );
  401. }
  402. return baseFormatter(params, asyncTicket);
  403. },
  404. },
  405. };
  406. },
  407. [formatterOptions, handleClick, series, xAxis, yAxis]
  408. );
  409. return useMemo(() => {
  410. if (!defined(samples)) {
  411. return undefined;
  412. }
  413. return {applyChartProps};
  414. }, [applyChartProps, samples]);
  415. }
  416. export type UseMetricSamplesResult = ReturnType<typeof useMetricChartSamples>;