widget.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. import {memo, useCallback, useMemo, useRef} from 'react';
  2. import styled from '@emotion/styled';
  3. import colorFn from 'color';
  4. import type {LineSeriesOption} from 'echarts';
  5. import moment from 'moment';
  6. import Alert from 'sentry/components/alert';
  7. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  8. import type {SelectOption} from 'sentry/components/compactSelect';
  9. import {CompactSelect} from 'sentry/components/compactSelect';
  10. import EmptyMessage from 'sentry/components/emptyMessage';
  11. import LoadingIndicator from 'sentry/components/loadingIndicator';
  12. import Panel from 'sentry/components/panels/panel';
  13. import PanelBody from 'sentry/components/panels/panelBody';
  14. import {Tooltip} from 'sentry/components/tooltip';
  15. import {IconSearch} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import type {MetricsApiResponse, MRI, PageFilters} from 'sentry/types';
  19. import type {ReactEchartsRef} from 'sentry/types/echarts';
  20. import {
  21. getDefaultMetricDisplayType,
  22. getSeriesName,
  23. stringifyMetricWidget,
  24. } from 'sentry/utils/metrics';
  25. import {metricDisplayTypeOptions} from 'sentry/utils/metrics/constants';
  26. import {parseMRI} from 'sentry/utils/metrics/mri';
  27. import type {
  28. MetricCorrelation,
  29. MetricWidgetQueryParams,
  30. } from 'sentry/utils/metrics/types';
  31. import {MetricDisplayType} from 'sentry/utils/metrics/types';
  32. import {useIncrementQueryMetric} from 'sentry/utils/metrics/useIncrementQueryMetric';
  33. import {useCorrelatedSamples} from 'sentry/utils/metrics/useMetricsCodeLocations';
  34. import {useMetricsDataZoom} from 'sentry/utils/metrics/useMetricsData';
  35. import theme from 'sentry/utils/theme';
  36. import {MetricChart} from 'sentry/views/ddm/chart';
  37. import type {FocusAreaProps} from 'sentry/views/ddm/context';
  38. import {QuerySymbol} from 'sentry/views/ddm/querySymbol';
  39. import {SummaryTable} from 'sentry/views/ddm/summaryTable';
  40. import {MIN_WIDGET_WIDTH} from './constants';
  41. type MetricWidgetProps = {
  42. datetime: PageFilters['datetime'];
  43. environments: PageFilters['environments'];
  44. onChange: (index: number, data: Partial<MetricWidgetQueryParams>) => void;
  45. projects: PageFilters['projects'];
  46. widget: MetricWidgetQueryParams;
  47. focusArea?: FocusAreaProps;
  48. hasSiblings?: boolean;
  49. highlightedSampleId?: string;
  50. index?: number;
  51. isSelected?: boolean;
  52. onSampleClick?: (sample: Sample) => void;
  53. onSelect?: (index: number) => void;
  54. showQuerySymbols?: boolean;
  55. };
  56. export type Sample = {
  57. projectId: number;
  58. spanId: string;
  59. transactionId: string;
  60. };
  61. export const MetricWidget = memo(
  62. ({
  63. widget,
  64. datetime,
  65. projects,
  66. environments,
  67. index = 0,
  68. isSelected = false,
  69. onSelect,
  70. onChange,
  71. hasSiblings = false,
  72. showQuerySymbols,
  73. focusArea,
  74. onSampleClick,
  75. highlightedSampleId,
  76. }: MetricWidgetProps) => {
  77. const handleChange = useCallback(
  78. (data: Partial<MetricWidgetQueryParams>) => {
  79. onChange(index, data);
  80. },
  81. [index, onChange]
  82. );
  83. const metricsQuery = useMemo(
  84. () => ({
  85. mri: widget.mri,
  86. query: widget.query,
  87. op: widget.op,
  88. groupBy: widget.groupBy,
  89. projects,
  90. datetime,
  91. environments,
  92. title: widget.title,
  93. }),
  94. [
  95. widget.mri,
  96. widget.query,
  97. widget.op,
  98. widget.groupBy,
  99. widget.title,
  100. projects,
  101. datetime,
  102. environments,
  103. ]
  104. );
  105. const incrementQueryMetric = useIncrementQueryMetric({
  106. displayType: widget.displayType,
  107. op: metricsQuery.op,
  108. groupBy: metricsQuery.groupBy,
  109. query: metricsQuery.query,
  110. mri: metricsQuery.mri,
  111. });
  112. const handleDisplayTypeChange = ({value}: SelectOption<MetricDisplayType>) => {
  113. incrementQueryMetric('ddm.widget.display', {displayType: value});
  114. onChange(index, {displayType: value});
  115. };
  116. const widgetTitle = metricsQuery.title ?? stringifyMetricWidget(metricsQuery);
  117. return (
  118. <MetricWidgetPanel
  119. // show the selection border only if we have more widgets than one
  120. isHighlighted={isSelected && !!hasSiblings}
  121. isHighlightable={!!hasSiblings}
  122. onClick={() => onSelect?.(index)}
  123. >
  124. <PanelBody>
  125. <MetricWidgetHeader>
  126. {showQuerySymbols && <QuerySymbol index={index} isSelected={isSelected} />}
  127. <WidgetTitle>
  128. <StyledTooltip
  129. title={widgetTitle}
  130. showOnlyOnOverflow
  131. delay={500}
  132. overlayStyle={{maxWidth: '90vw'}}
  133. >
  134. {widgetTitle}
  135. </StyledTooltip>
  136. </WidgetTitle>
  137. <CompactSelect
  138. size="xs"
  139. triggerProps={{prefix: t('Display')}}
  140. value={
  141. widget.displayType ??
  142. getDefaultMetricDisplayType(metricsQuery.mri, metricsQuery.op)
  143. }
  144. options={metricDisplayTypeOptions}
  145. onChange={handleDisplayTypeChange}
  146. />
  147. </MetricWidgetHeader>
  148. <MetricWidgetBodyWrapper>
  149. {widget.mri ? (
  150. <MetricWidgetBody
  151. widgetIndex={index}
  152. datetime={datetime}
  153. projects={projects}
  154. environments={environments}
  155. onChange={handleChange}
  156. focusArea={focusArea}
  157. onSampleClick={onSampleClick}
  158. chartHeight={300}
  159. highlightedSampleId={highlightedSampleId}
  160. {...widget}
  161. />
  162. ) : (
  163. <StyledMetricWidgetBody>
  164. <EmptyMessage
  165. icon={<IconSearch size="xxl" />}
  166. title={t('Nothing to show!')}
  167. description={t('Choose a metric to display data.')}
  168. />
  169. </StyledMetricWidgetBody>
  170. )}
  171. </MetricWidgetBodyWrapper>
  172. </PanelBody>
  173. </MetricWidgetPanel>
  174. );
  175. }
  176. );
  177. interface MetricWidgetBodyProps extends MetricWidgetQueryParams {
  178. widgetIndex: number;
  179. chartHeight?: number;
  180. focusArea?: FocusAreaProps;
  181. highlightedSampleId?: string;
  182. onChange?: (data: Partial<MetricWidgetQueryParams>) => void;
  183. onSampleClick?: (sample: Sample) => void;
  184. }
  185. export const MetricWidgetBody = memo(
  186. ({
  187. onChange,
  188. displayType,
  189. focusedSeries,
  190. highlightedSampleId,
  191. sort,
  192. widgetIndex,
  193. focusArea,
  194. chartHeight,
  195. onSampleClick,
  196. ...metricsQuery
  197. }: MetricWidgetBodyProps & PageFilters) => {
  198. const {mri, op, query, groupBy, projects, environments, datetime} = metricsQuery;
  199. const {
  200. data: timeseriesData,
  201. isLoading,
  202. isError,
  203. error,
  204. } = useMetricsDataZoom(
  205. {
  206. mri,
  207. op,
  208. query,
  209. groupBy,
  210. projects,
  211. environments,
  212. datetime,
  213. },
  214. {fidelity: displayType === MetricDisplayType.BAR ? 'low' : 'high'}
  215. );
  216. const {data: samplesData} = useCorrelatedSamples(mri, {
  217. ...focusArea?.selection?.range,
  218. });
  219. const chartRef = useRef<ReactEchartsRef>(null);
  220. const setHoveredSeries = useCallback((legend: string) => {
  221. if (!chartRef.current) {
  222. return;
  223. }
  224. const echartsInstance = chartRef.current.getEchartsInstance();
  225. echartsInstance.dispatchAction({
  226. type: 'highlight',
  227. seriesName: legend,
  228. });
  229. }, []);
  230. const toggleSeriesVisibility = useCallback(
  231. (series: MetricWidgetQueryParams['focusedSeries']) => {
  232. setHoveredSeries('');
  233. onChange?.({
  234. focusedSeries:
  235. focusedSeries?.seriesName === series?.seriesName ? undefined : series,
  236. });
  237. },
  238. [focusedSeries, onChange, setHoveredSeries]
  239. );
  240. const chartSeries = useMemo(() => {
  241. return timeseriesData
  242. ? getChartTimeseries(timeseriesData, {
  243. mri,
  244. focusedSeries: focusedSeries?.seriesName,
  245. groupBy: metricsQuery.groupBy,
  246. displayType,
  247. })
  248. : [];
  249. }, [timeseriesData, displayType, focusedSeries, metricsQuery.groupBy, mri]);
  250. const correlations = useMemo(() => {
  251. return (
  252. samplesData
  253. ? samplesData.metrics
  254. .map(m => m.metricSpans)
  255. .flat()
  256. .filter(correlation => !!correlation)
  257. : []
  258. ) as MetricCorrelation[];
  259. }, [samplesData]);
  260. const handleSortChange = useCallback(
  261. newSort => {
  262. onChange?.({sort: newSort});
  263. },
  264. [onChange]
  265. );
  266. if (!chartSeries || !timeseriesData || isError) {
  267. return (
  268. <StyledMetricWidgetBody>
  269. {isLoading && <LoadingIndicator />}
  270. {isError && (
  271. <Alert type="error">
  272. {error?.responseJSON?.detail || t('Error while fetching metrics data')}
  273. </Alert>
  274. )}
  275. </StyledMetricWidgetBody>
  276. );
  277. }
  278. if (timeseriesData.groups.length === 0) {
  279. return (
  280. <StyledMetricWidgetBody>
  281. <EmptyMessage
  282. icon={<IconSearch size="xxl" />}
  283. title={t('No results')}
  284. description={t('No results found for the given query')}
  285. />
  286. </StyledMetricWidgetBody>
  287. );
  288. }
  289. return (
  290. <StyledMetricWidgetBody>
  291. <TransparentLoadingMask visible={isLoading} />
  292. <MetricChart
  293. ref={chartRef}
  294. series={chartSeries}
  295. displayType={displayType}
  296. operation={metricsQuery.op}
  297. widgetIndex={widgetIndex}
  298. height={chartHeight}
  299. highlightedSampleId={highlightedSampleId}
  300. correlations={correlations}
  301. onSampleClick={onSampleClick}
  302. focusArea={focusArea}
  303. />
  304. {metricsQuery.showSummaryTable && (
  305. <SummaryTable
  306. series={chartSeries}
  307. onSortChange={handleSortChange}
  308. sort={sort}
  309. operation={metricsQuery.op}
  310. onRowClick={toggleSeriesVisibility}
  311. setHoveredSeries={focusedSeries ? undefined : setHoveredSeries}
  312. />
  313. )}
  314. </StyledMetricWidgetBody>
  315. );
  316. }
  317. );
  318. export function getChartTimeseries(
  319. data: MetricsApiResponse,
  320. {
  321. mri,
  322. focusedSeries,
  323. groupBy,
  324. hoveredLegend,
  325. displayType,
  326. }: {
  327. displayType: MetricDisplayType;
  328. mri: MRI;
  329. focusedSeries?: string;
  330. groupBy?: string[];
  331. hoveredLegend?: string;
  332. }
  333. ) {
  334. // this assumes that all series have the same unit
  335. const parsed = parseMRI(mri);
  336. const unit = parsed?.unit ?? '';
  337. const series = data.groups.map(g => {
  338. return {
  339. values: Object.values(g.series)[0],
  340. name: getSeriesName(g, data.groups.length === 1, groupBy),
  341. groupBy: g.by,
  342. transaction: g.by.transaction,
  343. release: g.by.release,
  344. };
  345. });
  346. const colors = getChartColorPalette(displayType, series.length);
  347. return sortSeries(series, displayType).map((item, i) => ({
  348. seriesName: item.name,
  349. groupBy: item.groupBy,
  350. unit,
  351. color: colorFn(colors[i % colors.length])
  352. .alpha(hoveredLegend && hoveredLegend !== item.name ? 0.1 : 1)
  353. .string(),
  354. hidden: focusedSeries && focusedSeries !== item.name,
  355. data: item.values.map((value, index) => ({
  356. name: moment(data.intervals[index]).valueOf(),
  357. value,
  358. })),
  359. transaction: item.transaction as string | undefined,
  360. release: item.release as string | undefined,
  361. emphasis: {
  362. focus: 'series',
  363. } as LineSeriesOption['emphasis'],
  364. })) as Series[];
  365. }
  366. function sortSeries(
  367. series: {
  368. groupBy: Record<string, string>;
  369. name: string;
  370. release: string;
  371. transaction: string;
  372. values: (number | null)[];
  373. }[],
  374. displayType: MetricDisplayType
  375. ) {
  376. const sorted = series
  377. // we need to sort the series by their values so that the colors in area chart do not overlap
  378. // for now we are only sorting by the first value, but we might need to sort by the sum of all values
  379. .sort((a, b) => {
  380. return Number(a.values?.[0]) > Number(b.values?.[0]) ? -1 : 1;
  381. });
  382. if (displayType === MetricDisplayType.BAR) {
  383. return sorted.toReversed();
  384. }
  385. return sorted;
  386. }
  387. function getChartColorPalette(displayType: MetricDisplayType, length: number) {
  388. // We do length - 2 to be aligned with the colors in other parts of the app (copy-pasta)
  389. // We use Math.max to avoid numbers < -1 as then `getColorPalette` returns undefined (not typesafe because of array access)
  390. const palette = theme.charts.getColorPalette(Math.max(length - 2, -1));
  391. if (displayType === MetricDisplayType.BAR) {
  392. return palette;
  393. }
  394. return palette.toReversed();
  395. }
  396. export type Series = {
  397. color: string;
  398. data: {name: number; value: number}[];
  399. seriesName: string;
  400. unit: string;
  401. groupBy?: Record<string, string>;
  402. hidden?: boolean;
  403. release?: string;
  404. transaction?: string;
  405. };
  406. export interface ScatterSeries extends Series {
  407. itemStyle: {
  408. color: string;
  409. opacity: number;
  410. };
  411. projectId: number;
  412. spanId: string;
  413. symbol: string;
  414. symbolSize: number;
  415. transactionId: string;
  416. z: number;
  417. }
  418. const MetricWidgetPanel = styled(Panel)<{
  419. isHighlightable: boolean;
  420. isHighlighted: boolean;
  421. }>`
  422. padding-bottom: 0;
  423. margin-bottom: 0;
  424. min-width: ${MIN_WIDGET_WIDTH}px;
  425. position: relative;
  426. transition: box-shadow 0.2s ease;
  427. ${p =>
  428. p.isHighlightable &&
  429. `
  430. &:focus,
  431. &:hover {
  432. box-shadow: 0px 0px 0px 3px
  433. ${p.isHighlighted ? p.theme.purple200 : 'rgba(209, 202, 216, 0.2)'};
  434. }
  435. `}
  436. ${p =>
  437. p.isHighlighted &&
  438. `
  439. box-shadow: 0px 0px 0px 3px ${p.theme.purple200};
  440. border-color: transparent;
  441. `}
  442. `;
  443. const StyledMetricWidgetBody = styled('div')`
  444. padding: ${space(1)};
  445. gap: ${space(3)};
  446. display: flex;
  447. flex-direction: column;
  448. justify-content: center;
  449. height: 100%;
  450. `;
  451. const MetricWidgetBodyWrapper = styled('div')`
  452. padding: ${space(1)};
  453. padding-bottom: 0;
  454. `;
  455. const MetricWidgetHeader = styled('div')`
  456. display: flex;
  457. justify-content: space-between;
  458. align-items: center;
  459. gap: ${space(1)};
  460. padding-left: ${space(2)};
  461. padding-top: ${space(1.5)};
  462. padding-right: ${space(2)};
  463. `;
  464. const WidgetTitle = styled('div')`
  465. flex-grow: 1;
  466. font-size: ${p => p.theme.fontSizeMedium};
  467. display: inline-grid;
  468. grid-auto-flow: column;
  469. `;
  470. const StyledTooltip = styled(Tooltip)`
  471. ${p => p.theme.overflowEllipsis};
  472. `;