widget.tsx 13 KB

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