widget.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. import {memo, useCallback, useMemo, useRef} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import type {SeriesOption} 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 {MetricsQueryApiResponse, PageFilters} from 'sentry/types';
  19. import type {ReactEchartsRef} from 'sentry/types/echarts';
  20. import {
  21. formatMetricsFormula,
  22. getDefaultMetricDisplayType,
  23. getFormattedMQL,
  24. getMetricsSeriesId,
  25. getMetricsSeriesName,
  26. } from 'sentry/utils/metrics';
  27. import {metricDisplayTypeOptions} from 'sentry/utils/metrics/constants';
  28. import {formatMRIField, MRIToField, parseMRI} from 'sentry/utils/metrics/mri';
  29. import {
  30. getMetricValueNormalizer,
  31. getNormalizedMetricUnit,
  32. } from 'sentry/utils/metrics/normalizeMetricValue';
  33. import type {
  34. FocusedMetricsSeries,
  35. MetricCorrelation,
  36. MetricWidgetQueryParams,
  37. SortState,
  38. } from 'sentry/utils/metrics/types';
  39. import {MetricDisplayType} from 'sentry/utils/metrics/types';
  40. import {useMetricSamples} from 'sentry/utils/metrics/useMetricsCorrelations';
  41. import {
  42. isMetricFormula,
  43. type MetricsQueryApiQueryParams,
  44. type MetricsQueryApiRequestQuery,
  45. useMetricsQuery,
  46. } from 'sentry/utils/metrics/useMetricsQuery';
  47. import {getIngestionSeriesId, MetricChart} from 'sentry/views/ddm/chart';
  48. import type {FocusAreaProps} from 'sentry/views/ddm/context';
  49. import {QuerySymbol} from 'sentry/views/ddm/querySymbol';
  50. import {SummaryTable} from 'sentry/views/ddm/summaryTable';
  51. import {getQueryWithFocusedSeries} from 'sentry/views/ddm/utils';
  52. import {createChartPalette} from 'sentry/views/ddm/utils/metricsChartPalette';
  53. import {DDM_CHART_GROUP, MIN_WIDGET_WIDTH} from './constants';
  54. type MetricWidgetProps = {
  55. context: 'ddm' | 'dashboard';
  56. displayType: MetricDisplayType;
  57. filters: PageFilters;
  58. onChange: (index: number, data: Partial<MetricWidgetQueryParams>) => void;
  59. queries: MetricsQueryApiQueryParams[];
  60. chartHeight?: number;
  61. focusArea?: FocusAreaProps;
  62. focusedSeries?: FocusedMetricsSeries[];
  63. getChartPalette?: (seriesNames: string[]) => Record<string, string>;
  64. hasSiblings?: boolean;
  65. highlightedSampleId?: string;
  66. index?: number;
  67. isSelected?: boolean;
  68. onSampleClick?: (sample: Sample) => void;
  69. onSelect?: (index: number) => void;
  70. queryId?: number;
  71. showQuerySymbols?: boolean;
  72. tableSort?: SortState;
  73. };
  74. export type Sample = {
  75. projectId: number;
  76. spanId: string;
  77. transactionId: string;
  78. transactionSpanId: string;
  79. };
  80. function isNotQueryOnly(query: MetricsQueryApiQueryParams) {
  81. return !('isQueryOnly' in query) || !query.isQueryOnly;
  82. }
  83. export function getWidgetTitle(queries: MetricsQueryApiQueryParams[]) {
  84. const filteredQueries = queries.filter(isNotQueryOnly);
  85. if (filteredQueries.length === 1) {
  86. const firstQuery = filteredQueries[0];
  87. if (isMetricFormula(firstQuery)) {
  88. return formatMetricsFormula(firstQuery.formula);
  89. }
  90. return getFormattedMQL(firstQuery);
  91. }
  92. return filteredQueries
  93. .map(q =>
  94. isMetricFormula(q)
  95. ? formatMetricsFormula(q.formula)
  96. : formatMRIField(MRIToField(q.mri, q.op))
  97. )
  98. .join(', ');
  99. }
  100. export const MetricWidget = memo(
  101. ({
  102. queryId,
  103. queries,
  104. filters,
  105. displayType,
  106. tableSort,
  107. index = 0,
  108. isSelected = false,
  109. getChartPalette,
  110. onSelect,
  111. onChange,
  112. hasSiblings = false,
  113. showQuerySymbols,
  114. focusArea,
  115. onSampleClick,
  116. highlightedSampleId,
  117. chartHeight = 300,
  118. focusedSeries,
  119. context = 'ddm',
  120. }: MetricWidgetProps) => {
  121. const firstQuery = queries
  122. .filter(isNotQueryOnly)
  123. .find((query): query is MetricsQueryApiRequestQuery => !isMetricFormula(query));
  124. const handleChange = useCallback(
  125. (data: Partial<MetricWidgetQueryParams>) => {
  126. onChange(index, data);
  127. },
  128. [index, onChange]
  129. );
  130. const handleDisplayTypeChange = ({value}: SelectOption<MetricDisplayType>) => {
  131. Sentry.metrics.increment('ddm.widget.display');
  132. onChange(index, {displayType: value});
  133. };
  134. const queryWithFocusedSeries = useMemo(
  135. () => getQueryWithFocusedSeries(firstQuery?.query ?? '', focusedSeries),
  136. [firstQuery, focusedSeries]
  137. );
  138. const samplesQuery = useMetricSamples(firstQuery?.mri, {
  139. ...focusArea?.selection?.range,
  140. query: queryWithFocusedSeries,
  141. });
  142. const samples = useMemo(() => {
  143. return {
  144. data: samplesQuery.data,
  145. onClick: onSampleClick,
  146. unit: parseMRI(firstQuery?.mri)?.unit ?? '',
  147. operation: firstQuery?.op ?? '',
  148. higlightedId: highlightedSampleId,
  149. };
  150. }, [
  151. samplesQuery.data,
  152. onSampleClick,
  153. firstQuery?.mri,
  154. firstQuery?.op,
  155. highlightedSampleId,
  156. ]);
  157. const widgetTitle = getWidgetTitle(queries);
  158. const queriesAreComplete = queries.every(q =>
  159. isMetricFormula(q) ? !!q.formula : !!q.mri
  160. );
  161. return (
  162. <MetricWidgetPanel
  163. // show the selection border only if we have more widgets than one
  164. isHighlighted={isSelected && !!hasSiblings}
  165. isHighlightable={!!hasSiblings}
  166. onClick={() => onSelect?.(index)}
  167. >
  168. <PanelBody>
  169. <MetricWidgetHeader>
  170. {showQuerySymbols && queryId !== undefined && (
  171. <QuerySymbol queryId={queryId} isSelected={isSelected} />
  172. )}
  173. <WidgetTitle>
  174. <StyledTooltip
  175. title={widgetTitle}
  176. showOnlyOnOverflow
  177. delay={500}
  178. overlayStyle={{maxWidth: '90vw'}}
  179. >
  180. {widgetTitle}
  181. </StyledTooltip>
  182. </WidgetTitle>
  183. <CompactSelect
  184. size="xs"
  185. triggerProps={{prefix: t('Display')}}
  186. value={
  187. displayType ??
  188. getDefaultMetricDisplayType(firstQuery?.mri, firstQuery?.op)
  189. }
  190. options={metricDisplayTypeOptions}
  191. onChange={handleDisplayTypeChange}
  192. />
  193. </MetricWidgetHeader>
  194. <MetricWidgetBodyWrapper>
  195. {queriesAreComplete ? (
  196. <MetricWidgetBody
  197. widgetIndex={index}
  198. getChartPalette={getChartPalette}
  199. onChange={handleChange}
  200. focusArea={focusArea}
  201. samples={samples}
  202. chartHeight={chartHeight}
  203. chartGroup={DDM_CHART_GROUP}
  204. queries={queries}
  205. filters={filters}
  206. displayType={displayType}
  207. tableSort={tableSort}
  208. focusedSeries={focusedSeries}
  209. context={context}
  210. />
  211. ) : (
  212. <StyledMetricWidgetBody>
  213. <EmptyMessage
  214. icon={<IconSearch size="xxl" />}
  215. title={t('Nothing to show!')}
  216. description={t('Choose a metric and an operation to display data.')}
  217. />
  218. </StyledMetricWidgetBody>
  219. )}
  220. </MetricWidgetBodyWrapper>
  221. </PanelBody>
  222. </MetricWidgetPanel>
  223. );
  224. }
  225. );
  226. interface MetricWidgetBodyProps {
  227. context: 'ddm' | 'dashboard';
  228. displayType: MetricDisplayType;
  229. filters: PageFilters;
  230. queries: MetricsQueryApiQueryParams[];
  231. widgetIndex: number;
  232. chartGroup?: string;
  233. chartHeight?: number;
  234. focusArea?: FocusAreaProps;
  235. focusedSeries?: FocusedMetricsSeries[];
  236. getChartPalette?: (seriesNames: string[]) => Record<string, string>;
  237. onChange?: (data: Partial<MetricWidgetQueryParams>) => void;
  238. samples?: SamplesProps;
  239. tableSort?: SortState;
  240. }
  241. export interface SamplesProps {
  242. operation: string;
  243. unit: string;
  244. data?: MetricCorrelation[];
  245. higlightedId?: string;
  246. onClick?: (sample: Sample) => void;
  247. }
  248. const MetricWidgetBody = memo(
  249. ({
  250. onChange,
  251. displayType,
  252. focusedSeries,
  253. tableSort,
  254. widgetIndex,
  255. getChartPalette = createChartPalette,
  256. focusArea,
  257. chartHeight,
  258. chartGroup,
  259. samples,
  260. filters,
  261. queries,
  262. context,
  263. }: MetricWidgetBodyProps) => {
  264. const {
  265. data: timeseriesData,
  266. isLoading,
  267. isError,
  268. error,
  269. } = useMetricsQuery(queries, filters, {
  270. intervalLadder: displayType === MetricDisplayType.BAR ? 'bar' : context,
  271. });
  272. const chartRef = useRef<ReactEchartsRef>(null);
  273. const setHoveredSeries = useCallback((seriesId: string) => {
  274. if (!chartRef.current) {
  275. return;
  276. }
  277. const echartsInstance = chartRef.current.getEchartsInstance();
  278. echartsInstance.dispatchAction({
  279. type: 'highlight',
  280. seriesId: [seriesId, getIngestionSeriesId(seriesId)],
  281. });
  282. }, []);
  283. const chartSeries = useMemo(() => {
  284. return timeseriesData
  285. ? getChartTimeseries(timeseriesData, queries, {
  286. getChartPalette,
  287. focusedSeries: focusedSeries && new Set(focusedSeries?.map(s => s.id)),
  288. })
  289. : [];
  290. }, [timeseriesData, queries, getChartPalette, focusedSeries]);
  291. const toggleSeriesVisibility = useCallback(
  292. (series: FocusedMetricsSeries) => {
  293. setHoveredSeries('');
  294. // The focused series array is not populated yet, so we can add all series except the one that was de-selected
  295. if (!focusedSeries || focusedSeries.length === 0) {
  296. onChange?.({
  297. focusedSeries: chartSeries
  298. .filter(s => s.id !== series.id)
  299. .map(s => ({
  300. id: s.id,
  301. groupBy: s.groupBy,
  302. })),
  303. });
  304. return;
  305. }
  306. const filteredSeries = focusedSeries.filter(s => s.id !== series.id);
  307. if (filteredSeries.length === focusedSeries.length) {
  308. // The series was not focused before so we can add it
  309. filteredSeries.push(series);
  310. }
  311. onChange?.({
  312. focusedSeries: filteredSeries,
  313. });
  314. },
  315. [chartSeries, focusedSeries, onChange, setHoveredSeries]
  316. );
  317. const setSeriesVisibility = useCallback(
  318. (series: FocusedMetricsSeries) => {
  319. setHoveredSeries('');
  320. if (focusedSeries?.length === 1 && focusedSeries[0].id === series.id) {
  321. onChange?.({
  322. focusedSeries: [],
  323. });
  324. return;
  325. }
  326. onChange?.({
  327. focusedSeries: [series],
  328. });
  329. },
  330. [focusedSeries, onChange, setHoveredSeries]
  331. );
  332. const handleSortChange = useCallback(
  333. newSort => {
  334. onChange?.({sort: newSort});
  335. },
  336. [onChange]
  337. );
  338. if (!chartSeries || !timeseriesData || isError) {
  339. return (
  340. <StyledMetricWidgetBody>
  341. {isLoading && <LoadingIndicator />}
  342. {isError && (
  343. <Alert type="error">
  344. {error?.responseJSON?.detail || t('Error while fetching metrics data')}
  345. </Alert>
  346. )}
  347. </StyledMetricWidgetBody>
  348. );
  349. }
  350. if (timeseriesData.data.length === 0) {
  351. return (
  352. <StyledMetricWidgetBody>
  353. <EmptyMessage
  354. icon={<IconSearch size="xxl" />}
  355. title={t('No results')}
  356. description={t('No results found for the given query')}
  357. />
  358. </StyledMetricWidgetBody>
  359. );
  360. }
  361. return (
  362. <StyledMetricWidgetBody>
  363. <TransparentLoadingMask visible={isLoading} />
  364. <MetricChart
  365. ref={chartRef}
  366. series={chartSeries}
  367. displayType={displayType}
  368. widgetIndex={widgetIndex}
  369. height={chartHeight}
  370. scatter={samples}
  371. focusArea={focusArea}
  372. group={chartGroup}
  373. />
  374. <SummaryTable
  375. series={chartSeries}
  376. onSortChange={handleSortChange}
  377. sort={tableSort}
  378. onRowClick={setSeriesVisibility}
  379. onColorDotClick={toggleSeriesVisibility}
  380. setHoveredSeries={setHoveredSeries}
  381. />
  382. </StyledMetricWidgetBody>
  383. );
  384. }
  385. );
  386. export function getChartTimeseries(
  387. data: MetricsQueryApiResponse,
  388. queries: MetricsQueryApiQueryParams[],
  389. {
  390. getChartPalette,
  391. focusedSeries,
  392. }: {
  393. getChartPalette: (seriesNames: string[]) => Record<string, string>;
  394. focusedSeries?: Set<string>;
  395. showQuerySymbol?: boolean;
  396. }
  397. ) {
  398. const filteredQueries = queries.filter(isNotQueryOnly);
  399. const series = data.data.flatMap((group, index) => {
  400. const query = filteredQueries[index];
  401. const isMultiQuery = filteredQueries.length > 1;
  402. let unit = '';
  403. let operation = '';
  404. if (!isMetricFormula(query)) {
  405. const parsed = parseMRI(query.mri);
  406. unit = parsed?.unit ?? '';
  407. operation = query.op ?? '';
  408. } else {
  409. // Treat formulas as if they were a single query with none as the unit and count as the operation
  410. unit = 'none';
  411. operation = 'count';
  412. }
  413. // We normalize metric units to make related units
  414. // (e.g. seconds & milliseconds) render in the correct ratio
  415. const normalizedUnit = getNormalizedMetricUnit(unit, operation);
  416. const normalizeValue = getMetricValueNormalizer(unit, operation);
  417. return group.map(entry => ({
  418. unit: normalizedUnit,
  419. operation: operation,
  420. values: entry.series.map(normalizeValue),
  421. name: getMetricsSeriesName(query, entry.by, isMultiQuery),
  422. id: getMetricsSeriesId(query, entry.by),
  423. groupBy: entry.by,
  424. transaction: entry.by.transaction,
  425. release: entry.by.release,
  426. }));
  427. });
  428. const chartPalette = getChartPalette(series.map(s => s.id));
  429. return series.map(item => ({
  430. id: item.id,
  431. seriesName: item.name,
  432. groupBy: item.groupBy,
  433. unit: item.unit,
  434. operation: item.operation,
  435. color: chartPalette[item.id],
  436. hidden: focusedSeries && focusedSeries.size > 0 && !focusedSeries.has(item.id),
  437. data: item.values.map((value, index) => ({
  438. name: moment(data.intervals[index]).valueOf(),
  439. value,
  440. })),
  441. transaction: item.transaction as string | undefined,
  442. release: item.release as string | undefined,
  443. emphasis: {
  444. focus: 'series',
  445. } as SeriesOption['emphasis'],
  446. })) as Series[];
  447. }
  448. export type Series = {
  449. color: string;
  450. data: {name: number; value: number}[];
  451. id: string;
  452. operation: string;
  453. seriesName: string;
  454. unit: string;
  455. groupBy?: Record<string, string>;
  456. hidden?: boolean;
  457. paddingIndices?: Set<number>;
  458. release?: string;
  459. transaction?: string;
  460. };
  461. export interface ScatterSeries extends Series {
  462. itemStyle: {
  463. color: string;
  464. opacity: number;
  465. };
  466. projectId: number;
  467. spanId: string;
  468. symbol: string;
  469. symbolSize: number;
  470. transactionId: string;
  471. z: number;
  472. }
  473. const MetricWidgetPanel = styled(Panel)<{
  474. isHighlightable: boolean;
  475. isHighlighted: boolean;
  476. }>`
  477. padding-bottom: 0;
  478. margin-bottom: 0;
  479. min-width: ${MIN_WIDGET_WIDTH}px;
  480. position: relative;
  481. transition: box-shadow 0.2s ease;
  482. ${p =>
  483. p.isHighlightable &&
  484. `
  485. &:focus,
  486. &:hover {
  487. box-shadow: 0px 0px 0px 3px
  488. ${p.isHighlighted ? p.theme.purple200 : 'rgba(209, 202, 216, 0.2)'};
  489. }
  490. `}
  491. ${p =>
  492. p.isHighlighted &&
  493. `
  494. box-shadow: 0px 0px 0px 3px ${p.theme.purple200};
  495. border-color: transparent;
  496. `}
  497. `;
  498. const StyledMetricWidgetBody = styled('div')`
  499. padding: ${space(1)};
  500. gap: ${space(3)};
  501. display: flex;
  502. flex-direction: column;
  503. justify-content: center;
  504. height: 100%;
  505. `;
  506. const MetricWidgetBodyWrapper = styled('div')`
  507. padding: ${space(1)};
  508. padding-bottom: 0;
  509. `;
  510. const MetricWidgetHeader = styled('div')`
  511. display: flex;
  512. justify-content: space-between;
  513. align-items: center;
  514. gap: ${space(1)};
  515. padding-left: ${space(2)};
  516. padding-top: ${space(1.5)};
  517. padding-right: ${space(2)};
  518. `;
  519. const WidgetTitle = styled('div')`
  520. flex-grow: 1;
  521. font-size: ${p => p.theme.fontSizeMedium};
  522. display: inline-grid;
  523. grid-auto-flow: column;
  524. `;
  525. const StyledTooltip = styled(Tooltip)`
  526. ${p => p.theme.overflowEllipsis};
  527. `;