widget.tsx 18 KB

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