widget.tsx 19 KB

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