widget.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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 && hasSiblings} />
  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={isSelected ? samples : undefined}
  233. samplesV2={isSelected ? samplesV2 : undefined}
  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 orderedQueries = useMemo(() => {
  308. return queries.map(q => {
  309. if (isMetricFormula(q)) {
  310. return q;
  311. }
  312. return {
  313. ...q,
  314. orderBy: q.orderBy ? q.orderBy : q.groupBy?.length ? 'desc' : undefined,
  315. };
  316. });
  317. }, [queries]);
  318. const {
  319. data: timeseriesData,
  320. isLoading,
  321. isError,
  322. error,
  323. } = useMetricsQuery(orderedQueries, filters, {
  324. intervalLadder: displayType === MetricDisplayType.BAR ? 'bar' : context,
  325. });
  326. const {chartRef, setHoveredSeries} = useSeriesHover();
  327. const handleHoverSeries = useCallback(
  328. (seriesId: string) => {
  329. setHoveredSeries([seriesId, getIngestionSeriesId(seriesId)]);
  330. },
  331. [setHoveredSeries]
  332. );
  333. const chartSeries = useMemo(() => {
  334. return timeseriesData
  335. ? getChartTimeseries(timeseriesData, queries, {
  336. getChartPalette,
  337. focusedSeries: focusedSeries && new Set(focusedSeries?.map(s => s.id)),
  338. })
  339. : [];
  340. }, [timeseriesData, queries, getChartPalette, focusedSeries]);
  341. const samplesProp = useMetricChartSamples({
  342. chartRef,
  343. correlations: samples?.data,
  344. unit: samples?.unit,
  345. onClick: samples?.onClick,
  346. highlightedSampleId: samples?.higlightedId,
  347. operation: samples?.operation,
  348. timeseries: chartSeries,
  349. });
  350. const samplesV2Prop = useMetricChartSamplesV2({
  351. samples: samplesV2?.data,
  352. highlightedSampleId: samples?.higlightedId,
  353. operation: samplesV2?.operation,
  354. onSampleClick: samplesV2?.onSampleClick,
  355. timeseries: chartSeries,
  356. unit: samplesV2?.unit,
  357. });
  358. const handleZoom = useCallback(
  359. (range: DateTimeObject) => {
  360. Sentry.metrics.increment('ddm.enhance.zoom');
  361. updateDateTime(range, router, {save: true});
  362. },
  363. [router]
  364. );
  365. const isCumulativeSamplesOp =
  366. queries[0] && !isMetricFormula(queries[0]) && isCumulativeOp(queries[0].op);
  367. const firstScalingFactor = chartSeries.find(s => !s.hidden)?.scalingFactor || 1;
  368. const focusArea = useFocusArea({
  369. ...focusAreaProps,
  370. scalingFactor: firstScalingFactor,
  371. chartRef,
  372. opts: {
  373. widgetIndex,
  374. isDisabled: !focusAreaProps.onAdd,
  375. useFullYAxis: isCumulativeSamplesOp,
  376. },
  377. onZoom: handleZoom,
  378. });
  379. const toggleSeriesVisibility = useCallback(
  380. (series: FocusedMetricsSeries) => {
  381. setHoveredSeries('');
  382. // The focused series array is not populated yet, so we can add all series except the one that was de-selected
  383. if (!focusedSeries || focusedSeries.length === 0) {
  384. onChange?.({
  385. focusedSeries: chartSeries
  386. .filter(s => s.id !== series.id)
  387. .map(s => ({
  388. id: s.id,
  389. groupBy: s.groupBy,
  390. })),
  391. });
  392. return;
  393. }
  394. const filteredSeries = focusedSeries.filter(s => s.id !== series.id);
  395. if (filteredSeries.length === focusedSeries.length) {
  396. // The series was not focused before so we can add it
  397. filteredSeries.push(series);
  398. }
  399. onChange?.({
  400. focusedSeries: filteredSeries,
  401. });
  402. },
  403. [chartSeries, focusedSeries, onChange, setHoveredSeries]
  404. );
  405. const setSeriesVisibility = useCallback(
  406. (series: FocusedMetricsSeries) => {
  407. setHoveredSeries('');
  408. if (focusedSeries?.length === 1 && focusedSeries[0].id === series.id) {
  409. onChange?.({
  410. focusedSeries: [],
  411. });
  412. return;
  413. }
  414. onChange?.({
  415. focusedSeries: [series],
  416. });
  417. },
  418. [focusedSeries, onChange, setHoveredSeries]
  419. );
  420. const handleSortChange = useCallback(
  421. newSort => {
  422. onChange?.({sort: newSort});
  423. },
  424. [onChange]
  425. );
  426. if (!chartSeries || !timeseriesData || isError) {
  427. return (
  428. <StyledMetricWidgetBody>
  429. {isLoading && <LoadingIndicator />}
  430. {isError && (
  431. <Alert type="error">
  432. {(error?.responseJSON?.detail as string) ||
  433. t('Error while fetching metrics data')}
  434. </Alert>
  435. )}
  436. </StyledMetricWidgetBody>
  437. );
  438. }
  439. if (timeseriesData.data.length === 0) {
  440. return (
  441. <StyledMetricWidgetBody>
  442. <EmptyMessage
  443. icon={<IconSearch size="xxl" />}
  444. title={t('No results')}
  445. description={t('No results found for the given query')}
  446. />
  447. </StyledMetricWidgetBody>
  448. );
  449. }
  450. return (
  451. <StyledMetricWidgetBody>
  452. <TransparentLoadingMask visible={isLoading} />
  453. <MetricChart
  454. ref={chartRef}
  455. series={chartSeries}
  456. displayType={displayType}
  457. height={chartHeight}
  458. samples={samplesV2Prop ?? samplesProp}
  459. focusArea={focusArea}
  460. group={chartGroup}
  461. />
  462. <SummaryTable
  463. series={chartSeries}
  464. onSortChange={handleSortChange}
  465. sort={tableSort}
  466. onRowClick={setSeriesVisibility}
  467. onColorDotClick={toggleSeriesVisibility}
  468. onRowHover={handleHoverSeries}
  469. />
  470. </StyledMetricWidgetBody>
  471. );
  472. }
  473. );
  474. export function getChartTimeseries(
  475. data: MetricsQueryApiResponse,
  476. queries: MetricsQueryApiQueryParams[],
  477. {
  478. getChartPalette,
  479. focusedSeries,
  480. }: {
  481. getChartPalette: (seriesNames: string[]) => Record<string, string>;
  482. focusedSeries?: Set<string>;
  483. showQuerySymbol?: boolean;
  484. }
  485. ) {
  486. const filteredQueries = queries.filter(isNotQueryOnly);
  487. const series = data.data.flatMap((group, index) => {
  488. const query = filteredQueries[index];
  489. const meta = data.meta[index];
  490. const lastMetaEntry = meta[meta.length - 1];
  491. const unit =
  492. (lastMetaEntry && 'unit' in lastMetaEntry && lastMetaEntry.unit) || 'none';
  493. const scalingFactor =
  494. (lastMetaEntry &&
  495. 'scaling_factor' in lastMetaEntry &&
  496. lastMetaEntry.scaling_factor) ||
  497. 1;
  498. const operation = isMetricFormula(query) ? 'count' : query.op;
  499. const isMultiQuery = filteredQueries.length > 1;
  500. return group.map(entry => ({
  501. unit: unit,
  502. operation: operation,
  503. values: entry.series,
  504. scalingFactor: scalingFactor,
  505. name: getMetricsSeriesName(query, entry.by, isMultiQuery),
  506. id: getMetricsSeriesId(query, entry.by),
  507. groupBy: entry.by,
  508. transaction: entry.by.transaction,
  509. release: entry.by.release,
  510. }));
  511. });
  512. const chartPalette = getChartPalette(series.map(s => s.id));
  513. return series.map(item => ({
  514. id: item.id,
  515. seriesName: item.name,
  516. groupBy: item.groupBy,
  517. unit: item.unit,
  518. scalingFactor: item.scalingFactor,
  519. operation: item.operation,
  520. color: chartPalette[item.id],
  521. hidden: focusedSeries && focusedSeries.size > 0 && !focusedSeries.has(item.id),
  522. data: item.values.map((value, index) => ({
  523. name: moment(data.intervals[index]).valueOf(),
  524. value,
  525. })),
  526. transaction: item.transaction as string | undefined,
  527. release: item.release as string | undefined,
  528. emphasis: {
  529. focus: 'series',
  530. } as SeriesOption['emphasis'],
  531. })) as Series[];
  532. }
  533. const MetricWidgetPanel = styled(Panel)<{
  534. isHighlightable: boolean;
  535. isHighlighted: boolean;
  536. }>`
  537. padding-bottom: 0;
  538. margin-bottom: 0;
  539. min-width: ${MIN_WIDGET_WIDTH}px;
  540. position: relative;
  541. transition: box-shadow 0.2s ease;
  542. ${p =>
  543. p.isHighlightable &&
  544. `
  545. &:focus,
  546. &:hover {
  547. box-shadow: 0px 0px 0px 3px
  548. ${p.isHighlighted ? p.theme.purple200 : 'rgba(209, 202, 216, 0.2)'};
  549. }
  550. `}
  551. ${p =>
  552. p.isHighlighted &&
  553. `
  554. box-shadow: 0px 0px 0px 3px ${p.theme.purple200};
  555. border-color: transparent;
  556. `}
  557. `;
  558. const StyledMetricWidgetBody = styled('div')`
  559. padding: ${space(1)};
  560. gap: ${space(3)};
  561. display: flex;
  562. flex-direction: column;
  563. justify-content: center;
  564. height: 100%;
  565. `;
  566. const MetricWidgetBodyWrapper = styled('div')`
  567. padding: ${space(1)};
  568. `;
  569. const MetricWidgetHeader = styled('div')`
  570. display: flex;
  571. justify-content: space-between;
  572. align-items: center;
  573. gap: ${space(1)};
  574. padding-left: ${space(2)};
  575. padding-top: ${space(1.5)};
  576. padding-right: ${space(2)};
  577. `;
  578. const WidgetTitle = styled('div')`
  579. flex-grow: 1;
  580. font-size: ${p => p.theme.fontSizeMedium};
  581. display: inline-grid;
  582. grid-auto-flow: column;
  583. `;
  584. const StyledTooltip = styled(Tooltip)`
  585. ${p => p.theme.overflowEllipsis};
  586. `;