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. MetricsQueryWidget,
  39. MetricsWidget,
  40. SortState,
  41. } from 'sentry/utils/metrics/types';
  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/metrics/chart/chart';
  51. import type {Series} from 'sentry/views/metrics/chart/types';
  52. import {useFocusArea} from 'sentry/views/metrics/chart/useFocusArea';
  53. import {useMetricChartSamples} from 'sentry/views/metrics/chart/useMetricChartSamples';
  54. import type {FocusAreaProps} from 'sentry/views/metrics/context';
  55. import {EquationSymbol} from 'sentry/views/metrics/equationSymbol copy';
  56. import {FormularFormatter} from 'sentry/views/metrics/formulaParser/formatter';
  57. import {QuerySymbol} from 'sentry/views/metrics/querySymbol';
  58. import {SummaryTable} from 'sentry/views/metrics/summaryTable';
  59. import {useSeriesHover} from 'sentry/views/metrics/useSeriesHover';
  60. import {extendQueryWithGroupBys} from 'sentry/views/metrics/utils';
  61. import {createChartPalette} from 'sentry/views/metrics/utils/metricsChartPalette';
  62. import {useMetricsIntervalParam} from 'sentry/views/metrics/utils/useMetricsIntervalParam';
  63. import {DDM_CHART_GROUP, MIN_WIDGET_WIDTH} from './constants';
  64. type MetricWidgetProps = {
  65. displayType: MetricDisplayType;
  66. filters: PageFilters;
  67. focusAreaProps: FocusAreaProps;
  68. onChange: (index: number, data: Partial<MetricsWidget>) => void;
  69. queries: MetricsQueryApiQueryParams[];
  70. chartHeight?: number;
  71. context?: 'ddm' | 'dashboard';
  72. focusedSeries?: FocusedMetricsSeries[];
  73. getChartPalette?: (seriesNames: string[]) => Record<string, string>;
  74. hasSiblings?: boolean;
  75. highlightedSampleId?: string;
  76. index?: number;
  77. isSelected?: boolean;
  78. metricsSamples?: MetricsSamplesResults<Field>['data'];
  79. onSampleClick?: (sample: MetricsSamplesResults<Field>['data'][number]) => void;
  80. onSelect?: (index: number) => void;
  81. queryId?: number;
  82. showQuerySymbols?: boolean;
  83. tableSort?: SortState;
  84. };
  85. export type Sample = {
  86. projectId: number;
  87. spanId: string;
  88. transactionId: string;
  89. transactionSpanId: string;
  90. };
  91. function isNotQueryOnly(query: MetricsQueryApiQueryParams) {
  92. return !('isQueryOnly' in query) || !query.isQueryOnly;
  93. }
  94. export function getWidgetTitle(queries: MetricsQueryApiQueryParams[]) {
  95. const filteredQueries = queries.filter(isNotQueryOnly);
  96. if (filteredQueries.length === 1) {
  97. const firstQuery = filteredQueries[0];
  98. if (isMetricFormula(firstQuery)) {
  99. return (
  100. <Fragment>
  101. <FormularFormatter formula={unescapeMetricsFormula(firstQuery.formula)} />
  102. </Fragment>
  103. );
  104. }
  105. return getFormattedMQL(firstQuery);
  106. }
  107. return filteredQueries
  108. .map(q =>
  109. isMetricFormula(q)
  110. ? unescapeMetricsFormula(q.formula)
  111. : formatMRIField(MRIToField(q.mri, q.op))
  112. )
  113. .join(', ');
  114. }
  115. export const MetricWidget = memo(
  116. ({
  117. queryId,
  118. queries,
  119. filters,
  120. displayType,
  121. tableSort,
  122. index = 0,
  123. isSelected = false,
  124. getChartPalette,
  125. onSelect,
  126. onChange,
  127. hasSiblings = false,
  128. showQuerySymbols,
  129. focusAreaProps,
  130. onSampleClick,
  131. chartHeight = 300,
  132. focusedSeries,
  133. metricsSamples,
  134. }: MetricWidgetProps) => {
  135. const firstQuery = queries
  136. .filter(isNotQueryOnly)
  137. .find((query): query is MetricsQueryApiRequestQuery => !isMetricFormula(query));
  138. const handleChange = useCallback(
  139. (data: Partial<MetricsWidget>) => {
  140. onChange(index, data);
  141. },
  142. [index, onChange]
  143. );
  144. const handleQueryChange = useCallback(
  145. (queryIndex, data: Partial<MetricsWidget>) => {
  146. onChange(queryIndex, data);
  147. },
  148. [onChange]
  149. );
  150. const handleDisplayTypeChange = ({value}: SelectOption<MetricDisplayType>) => {
  151. Sentry.metrics.increment('ddm.widget.display');
  152. onChange(index, {displayType: value});
  153. };
  154. const samples = useMemo(() => {
  155. if (!defined(metricsSamples)) {
  156. return undefined;
  157. }
  158. return {
  159. data: metricsSamples,
  160. onSampleClick,
  161. unit: parseMRI(firstQuery?.mri)?.unit ?? '',
  162. operation: firstQuery?.op ?? '',
  163. };
  164. }, [metricsSamples, firstQuery?.mri, firstQuery?.op, onSampleClick]);
  165. const widgetTitle = getWidgetTitle(queries);
  166. const queriesAreComplete = queries.every(q =>
  167. isMetricFormula(q) ? !!q.formula : !!q.mri
  168. );
  169. return (
  170. <MetricWidgetPanel
  171. // show the selection border only if we have more widgets than one
  172. isHighlighted={isSelected && hasSiblings}
  173. isHighlightable={hasSiblings}
  174. onClick={() => onSelect?.(index)}
  175. >
  176. <PanelBody>
  177. <MetricWidgetHeader>
  178. {showQuerySymbols &&
  179. queryId !== undefined &&
  180. (queries[0] && isMetricFormula(queries[0]) ? (
  181. <EquationSymbol
  182. equationId={queryId}
  183. isSelected={isSelected && hasSiblings}
  184. />
  185. ) : (
  186. <QuerySymbol queryId={queryId} isSelected={isSelected && hasSiblings} />
  187. ))}
  188. <WidgetTitle>
  189. <StyledTooltip
  190. title={widgetTitle}
  191. showOnlyOnOverflow
  192. delay={500}
  193. overlayStyle={{maxWidth: '90vw'}}
  194. >
  195. {widgetTitle}
  196. </StyledTooltip>
  197. </WidgetTitle>
  198. <CompactSelect
  199. size="xs"
  200. triggerProps={{prefix: t('Display')}}
  201. value={
  202. displayType ??
  203. getDefaultMetricDisplayType(firstQuery?.mri, firstQuery?.op)
  204. }
  205. options={metricDisplayTypeOptions}
  206. onChange={handleDisplayTypeChange}
  207. />
  208. </MetricWidgetHeader>
  209. <MetricWidgetBodyWrapper>
  210. {queriesAreComplete ? (
  211. <ErrorBoundary mini>
  212. <MetricWidgetBody
  213. widgetIndex={index}
  214. getChartPalette={getChartPalette}
  215. onChange={handleChange}
  216. onQueryChange={handleQueryChange}
  217. focusAreaProps={focusAreaProps}
  218. samples={isSelected ? samples : undefined}
  219. chartHeight={chartHeight}
  220. chartGroup={DDM_CHART_GROUP}
  221. queries={queries}
  222. filters={filters}
  223. displayType={displayType}
  224. tableSort={tableSort}
  225. focusedSeries={focusedSeries}
  226. />
  227. </ErrorBoundary>
  228. ) : (
  229. <StyledMetricWidgetBody>
  230. <EmptyMessage
  231. icon={<IconSearch size="xxl" />}
  232. title={t('Nothing to show!')}
  233. description={t('Choose a metric and an operation to display data.')}
  234. />
  235. </StyledMetricWidgetBody>
  236. )}
  237. </MetricWidgetBodyWrapper>
  238. </PanelBody>
  239. </MetricWidgetPanel>
  240. );
  241. }
  242. );
  243. interface MetricWidgetBodyProps {
  244. displayType: MetricDisplayType;
  245. filters: PageFilters;
  246. focusAreaProps: FocusAreaProps;
  247. queries: MetricsQueryApiQueryParams[];
  248. widgetIndex: number;
  249. chartGroup?: string;
  250. chartHeight?: number;
  251. focusedSeries?: FocusedMetricsSeries[];
  252. getChartPalette?: (seriesNames: string[]) => Record<string, string>;
  253. onChange?: (data: Partial<MetricsWidget>) => void;
  254. onQueryChange?: (queryIndex: number, data: Partial<MetricsQueryWidget>) => void;
  255. samples?: SamplesProps;
  256. tableSort?: SortState;
  257. }
  258. export interface SamplesProps {
  259. operation: string;
  260. unit: string;
  261. data?: MetricsSamplesResults<Field>['data'];
  262. higlightedId?: string;
  263. onSampleClick?: (sample: MetricsSamplesResults<Field>['data'][number]) => void;
  264. }
  265. const MetricWidgetBody = memo(
  266. ({
  267. onChange,
  268. onQueryChange,
  269. displayType,
  270. focusedSeries,
  271. tableSort,
  272. widgetIndex,
  273. getChartPalette = createChartPalette,
  274. focusAreaProps,
  275. chartHeight,
  276. chartGroup,
  277. samples,
  278. filters,
  279. queries,
  280. }: MetricWidgetBodyProps) => {
  281. const router = useRouter();
  282. const {interval} = useMetricsIntervalParam();
  283. const orderedQueries = useMemo(() => {
  284. return queries.map(q => {
  285. if (isMetricFormula(q)) {
  286. return q;
  287. }
  288. return {
  289. ...q,
  290. orderBy: q.orderBy ? q.orderBy : q.groupBy?.length ? 'desc' : undefined,
  291. };
  292. });
  293. }, [queries]);
  294. const {
  295. data: timeseriesData,
  296. isLoading,
  297. isError,
  298. error,
  299. } = useMetricsQuery(orderedQueries, filters, {
  300. interval: interval,
  301. });
  302. const limitedResults = useMemo(() => {
  303. if (!timeseriesData) {
  304. return false;
  305. }
  306. return areResultsLimited(timeseriesData);
  307. }, [timeseriesData]);
  308. const {chartRef, setHoveredSeries} = useSeriesHover();
  309. const handleHoverSeries = useCallback(
  310. (seriesId: string) => {
  311. setHoveredSeries([seriesId, getIngestionSeriesId(seriesId)]);
  312. },
  313. [setHoveredSeries]
  314. );
  315. const chartSeries = useMemo(() => {
  316. return timeseriesData
  317. ? getChartTimeseries(timeseriesData, queries, {
  318. getChartPalette,
  319. focusedSeries: focusedSeries && new Set(focusedSeries?.map(s => s.id)),
  320. })
  321. : [];
  322. }, [timeseriesData, queries, getChartPalette, focusedSeries]);
  323. const samplesProp = useMetricChartSamples({
  324. samples: samples?.data,
  325. highlightedSampleId: samples?.higlightedId,
  326. operation: samples?.operation,
  327. onSampleClick: samples?.onSampleClick,
  328. timeseries: chartSeries,
  329. unit: samples?.unit,
  330. });
  331. const handleZoom = useCallback(
  332. (range: DateTimeObject) => {
  333. Sentry.metrics.increment('ddm.enhance.zoom');
  334. updateDateTime(range, router, {save: true});
  335. },
  336. [router]
  337. );
  338. const handleRowFilter = useCallback(
  339. (queryIndex, series) => {
  340. const queryToUpdate = queries[queryIndex];
  341. if (!queryToUpdate) {
  342. return;
  343. }
  344. if (isMetricFormula(queryToUpdate)) {
  345. // TODO(ddm): filtering on an equation series should extend all conditions of all queries in the equation
  346. return;
  347. }
  348. const newQuery = extendQueryWithGroupBys(queryToUpdate.query, [series.groupBy]);
  349. const indexToUpdate = queries.length > 1 ? queryIndex : widgetIndex;
  350. onQueryChange?.(indexToUpdate, {query: 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. 'Specified queries 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(1)};
  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. `;