widget.tsx 13 KB

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