useChartSamples.tsx 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import type {RefObject} from 'react';
  2. import {useCallback, useEffect, useMemo, useState} from 'react';
  3. import {useTheme} from '@emotion/react';
  4. import type {XAXisOption} from 'echarts/types/dist/shared';
  5. import moment from 'moment';
  6. import type {ReactEchartsRef, Series} from 'sentry/types/echarts';
  7. import {getDuration} from 'sentry/utils/formatters';
  8. import {isCumulativeOp} from 'sentry/utils/metrics';
  9. import type {MetricCorrelation, MetricSummary} from 'sentry/utils/metrics/types';
  10. import {fitToValueRect, getValueRect} from 'sentry/views/ddm/chartUtils';
  11. import type {Sample} from 'sentry/views/ddm/widget';
  12. type UseChartSamplesProps = {
  13. timeseries: Series[];
  14. chartRef?: RefObject<ReactEchartsRef>;
  15. correlations?: MetricCorrelation[];
  16. highlightedSampleId?: string;
  17. onClick?: (sample: Sample) => void;
  18. onMouseOut?: (sample: Sample) => void;
  19. onMouseOver?: (sample: Sample) => void;
  20. operation?: string;
  21. };
  22. // TODO: remove this once we have a stabilized type for this
  23. type ChartSample = MetricCorrelation & MetricSummary;
  24. function getDateRange(timeseries: Series[]) {
  25. if (!timeseries?.length) {
  26. return {min: -Infinity, max: Infinity};
  27. }
  28. const min = timeseries[0].data[0].name as number;
  29. const max = timeseries[0].data[timeseries[0].data.length - 1].name as number;
  30. return {min, max};
  31. }
  32. export function useChartSamples({
  33. correlations,
  34. onClick,
  35. highlightedSampleId,
  36. chartRef,
  37. operation,
  38. timeseries,
  39. }: UseChartSamplesProps) {
  40. const theme = useTheme();
  41. const [valueRect, setValueRect] = useState(getValueRect(chartRef));
  42. const samples: Record<string, ChartSample> = useMemo(() => {
  43. return (correlations ?? [])
  44. ?.flatMap(correlation => [
  45. ...correlation.metricSummaries.map(summaries => ({...summaries, ...correlation})),
  46. ])
  47. .reduce((acc, sample) => {
  48. acc[sample.transactionId] = sample;
  49. return acc;
  50. }, {});
  51. }, [correlations]);
  52. useEffect(() => {
  53. // Changes in timeseries change the valueRect since the timeseries yAxis auto scales
  54. // and scatter yAxis needs to match the scale
  55. setValueRect(getValueRect(chartRef));
  56. }, [chartRef, timeseries]);
  57. const xAxis: XAXisOption = useMemo(() => {
  58. const {min, max} = getDateRange(timeseries);
  59. return {
  60. id: 'xAxisScatter',
  61. scale: false,
  62. show: false,
  63. axisLabel: {
  64. formatter: () => {
  65. return '';
  66. },
  67. },
  68. axisPointer: {
  69. type: 'none',
  70. },
  71. min: Math.max(valueRect.xMin, min),
  72. max: Math.min(valueRect.xMax, max),
  73. };
  74. }, [valueRect.xMin, valueRect.xMax, timeseries]);
  75. const yAxis = useMemo(() => {
  76. return {
  77. id: 'yAxisScatter',
  78. scale: false,
  79. show: false,
  80. axisLabel: {
  81. formatter: () => {
  82. return '';
  83. },
  84. },
  85. min: valueRect.yMin,
  86. max: valueRect.yMax,
  87. };
  88. }, [valueRect.yMin, valueRect.yMax]);
  89. const getSample = useCallback(
  90. event => {
  91. return samples?.[event.seriesName] as Sample;
  92. },
  93. [samples]
  94. );
  95. const handleClick = useCallback(
  96. event => {
  97. if (!onClick) {
  98. return;
  99. }
  100. const sample = getSample(event);
  101. if (!sample) {
  102. return;
  103. }
  104. onClick(sample);
  105. },
  106. [getSample, onClick]
  107. );
  108. const series = useMemo(() => {
  109. if (isCumulativeOp(operation)) {
  110. // TODO: for now we do not show samples for cumulative operations,
  111. // we will implement them as marklines
  112. return [];
  113. }
  114. return Object.values(samples).map(sample => {
  115. const isHighlighted = highlightedSampleId === sample.transactionId;
  116. const xValue = moment(sample.timestamp).valueOf();
  117. const yValue = ((sample.min ?? 0) + (sample.max ?? 0)) / 2;
  118. const [xPosition, yPosition] = fitToValueRect(xValue, yValue, valueRect);
  119. const symbol = yPosition === yValue ? 'circle' : 'arrow';
  120. const symbolRotate = yPosition > yValue ? 180 : 0;
  121. return {
  122. seriesName: sample.transactionId,
  123. unit: '',
  124. symbolSize: isHighlighted ? 20 : 10,
  125. animation: false,
  126. symbol,
  127. symbolRotate,
  128. color: theme.purple400,
  129. // TODO: for now we just pass these ids through, but we should probably index
  130. // samples by an id and then just pass that reference
  131. transactionId: sample.transactionId,
  132. transactionSpanId: sample.transactionSpanId,
  133. spanId: sample.spanId,
  134. projectId: sample.projectId,
  135. itemStyle: {
  136. color: theme.purple400,
  137. opacity: 1,
  138. },
  139. yAxisIndex: 1,
  140. xAxisIndex: 1,
  141. xValue,
  142. yValue,
  143. tooltip: {
  144. axisPointer: {
  145. type: 'none',
  146. },
  147. },
  148. data: [
  149. {
  150. name: xPosition,
  151. value: yPosition,
  152. },
  153. ],
  154. z: 10,
  155. };
  156. });
  157. }, [samples, highlightedSampleId, theme.purple400, valueRect, operation]);
  158. const formatters = useMemo(() => {
  159. return {
  160. isGroupedByDate: true,
  161. limit: 1,
  162. showTimeInTooltip: true,
  163. addSecondsToTimeFormat: true,
  164. nameFormatter: (name: string) => {
  165. return name.substring(0, 8);
  166. },
  167. valueFormatter: (_, label?: string) => {
  168. const sample = samples[label ?? ''];
  169. return getDuration(sample.duration / 1000, 2, true);
  170. },
  171. };
  172. }, [samples]);
  173. return {
  174. handleClick,
  175. series,
  176. xAxis,
  177. yAxis,
  178. formatters,
  179. };
  180. }