widget.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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} 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. MetricDisplayType,
  37. MetricsQueryWidget,
  38. MetricsWidget,
  39. SortState,
  40. } from 'sentry/utils/metrics/types';
  41. import {
  42. isMetricFormula,
  43. type MetricsQueryApiQueryParams,
  44. type MetricsQueryApiRequestQuery,
  45. useMetricsQuery,
  46. } from 'sentry/utils/metrics/useMetricsQuery';
  47. import type {MetricsSamplesResults} from 'sentry/utils/metrics/useMetricsSamples';
  48. import useRouter from 'sentry/utils/useRouter';
  49. import {getIngestionSeriesId, MetricChart} from 'sentry/views/metrics/chart/chart';
  50. import type {Series} from 'sentry/views/metrics/chart/types';
  51. import {useFocusArea} from 'sentry/views/metrics/chart/useFocusArea';
  52. import {useMetricChartSamples} from 'sentry/views/metrics/chart/useMetricChartSamples';
  53. import type {FocusAreaProps} from 'sentry/views/metrics/context';
  54. import {EquationSymbol} from 'sentry/views/metrics/equationSymbol copy';
  55. import {FormularFormatter} from 'sentry/views/metrics/formulaParser/formatter';
  56. import {QuerySymbol} from 'sentry/views/metrics/querySymbol';
  57. import {SummaryTable} from 'sentry/views/metrics/summaryTable';
  58. import {useSeriesHover} from 'sentry/views/metrics/useSeriesHover';
  59. import {extendQueryWithGroupBys} 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 &&
  178. queryId !== undefined &&
  179. (queries[0] && isMetricFormula(queries[0]) ? (
  180. <EquationSymbol
  181. equationId={queryId}
  182. isSelected={isSelected && hasSiblings}
  183. />
  184. ) : (
  185. <QuerySymbol queryId={queryId} isSelected={isSelected && hasSiblings} />
  186. ))}
  187. <WidgetTitle>
  188. <StyledTooltip
  189. title={widgetTitle}
  190. showOnlyOnOverflow
  191. delay={500}
  192. overlayStyle={{maxWidth: '90vw'}}
  193. >
  194. {widgetTitle}
  195. </StyledTooltip>
  196. </WidgetTitle>
  197. <CompactSelect
  198. size="xs"
  199. triggerProps={{prefix: t('Display')}}
  200. value={
  201. displayType ??
  202. getDefaultMetricDisplayType(firstQuery?.mri, firstQuery?.op)
  203. }
  204. options={metricDisplayTypeOptions}
  205. onChange={handleDisplayTypeChange}
  206. />
  207. </MetricWidgetHeader>
  208. <MetricWidgetBodyWrapper>
  209. {queriesAreComplete ? (
  210. <ErrorBoundary mini>
  211. <MetricWidgetBody
  212. widgetIndex={index}
  213. getChartPalette={getChartPalette}
  214. onChange={handleChange}
  215. onQueryChange={handleQueryChange}
  216. focusAreaProps={focusAreaProps}
  217. samples={isSelected ? samples : undefined}
  218. chartHeight={chartHeight}
  219. chartGroup={DDM_CHART_GROUP}
  220. queries={queries}
  221. filters={filters}
  222. displayType={displayType}
  223. tableSort={tableSort}
  224. focusedSeries={focusedSeries}
  225. />
  226. </ErrorBoundary>
  227. ) : (
  228. <StyledMetricWidgetBody>
  229. <EmptyMessage
  230. icon={<IconSearch size="xxl" />}
  231. title={t('Nothing to show!')}
  232. description={t('Choose a metric and an operation to display data.')}
  233. />
  234. </StyledMetricWidgetBody>
  235. )}
  236. </MetricWidgetBodyWrapper>
  237. </PanelBody>
  238. </MetricWidgetPanel>
  239. );
  240. }
  241. );
  242. interface MetricWidgetBodyProps {
  243. displayType: MetricDisplayType;
  244. filters: PageFilters;
  245. focusAreaProps: FocusAreaProps;
  246. queries: MetricsQueryApiQueryParams[];
  247. widgetIndex: number;
  248. chartGroup?: string;
  249. chartHeight?: number;
  250. focusedSeries?: FocusedMetricsSeries[];
  251. getChartPalette?: (seriesNames: string[]) => Record<string, string>;
  252. onChange?: (data: Partial<MetricsWidget>) => void;
  253. onQueryChange?: (queryIndex: number, data: Partial<MetricsQueryWidget>) => void;
  254. samples?: SamplesProps;
  255. tableSort?: SortState;
  256. }
  257. export interface SamplesProps {
  258. operation: string;
  259. unit: string;
  260. data?: MetricsSamplesResults<Field>['data'];
  261. higlightedId?: string;
  262. onSampleClick?: (sample: MetricsSamplesResults<Field>['data'][number]) => void;
  263. }
  264. const MetricWidgetBody = memo(
  265. ({
  266. onChange,
  267. onQueryChange,
  268. displayType,
  269. focusedSeries,
  270. tableSort,
  271. widgetIndex,
  272. getChartPalette = createChartPalette,
  273. focusAreaProps,
  274. chartHeight,
  275. chartGroup,
  276. samples,
  277. filters,
  278. queries,
  279. }: MetricWidgetBodyProps) => {
  280. const router = useRouter();
  281. const {interval} = useMetricsIntervalParam();
  282. const orderedQueries = useMemo(() => {
  283. return queries.map(q => {
  284. if (isMetricFormula(q)) {
  285. return q;
  286. }
  287. return {
  288. ...q,
  289. orderBy: q.orderBy ? q.orderBy : q.groupBy?.length ? 'desc' : undefined,
  290. };
  291. });
  292. }, [queries]);
  293. const {
  294. data: timeseriesData,
  295. isLoading,
  296. isError,
  297. error,
  298. } = useMetricsQuery(orderedQueries, filters, {
  299. interval: interval,
  300. });
  301. const {chartRef, setHoveredSeries} = useSeriesHover();
  302. const handleHoverSeries = useCallback(
  303. (seriesId: string) => {
  304. setHoveredSeries([seriesId, getIngestionSeriesId(seriesId)]);
  305. },
  306. [setHoveredSeries]
  307. );
  308. const chartSeries = useMemo(() => {
  309. return timeseriesData
  310. ? getChartTimeseries(timeseriesData, queries, {
  311. getChartPalette,
  312. focusedSeries: focusedSeries && new Set(focusedSeries?.map(s => s.id)),
  313. })
  314. : [];
  315. }, [timeseriesData, queries, getChartPalette, focusedSeries]);
  316. const samplesProp = useMetricChartSamples({
  317. samples: samples?.data,
  318. highlightedSampleId: samples?.higlightedId,
  319. operation: samples?.operation,
  320. onSampleClick: samples?.onSampleClick,
  321. timeseries: chartSeries,
  322. unit: samples?.unit,
  323. });
  324. const handleZoom = useCallback(
  325. (range: DateTimeObject) => {
  326. Sentry.metrics.increment('ddm.enhance.zoom');
  327. updateDateTime(range, router, {save: true});
  328. },
  329. [router]
  330. );
  331. const handleRowFilter = useCallback(
  332. (queryIndex, series) => {
  333. const queryToUpdate = queries[queryIndex];
  334. if (!queryToUpdate) {
  335. return;
  336. }
  337. if (isMetricFormula(queryToUpdate)) {
  338. // TODO(ddm): filtering on an equation series should extend all conditions of all queries in the equation
  339. return;
  340. }
  341. const newQuery = extendQueryWithGroupBys(queryToUpdate.query, [series.groupBy]);
  342. const indexToUpdate = queries.length > 1 ? queryIndex : widgetIndex;
  343. onQueryChange?.(indexToUpdate, {query: newQuery});
  344. },
  345. [queries, onQueryChange, widgetIndex]
  346. );
  347. const isCumulativeSamplesOp =
  348. queries[0] && !isMetricFormula(queries[0]) && isCumulativeOp(queries[0].op);
  349. const firstScalingFactor = chartSeries.find(s => !s.hidden)?.scalingFactor || 1;
  350. const focusArea = useFocusArea({
  351. ...focusAreaProps,
  352. scalingFactor: firstScalingFactor,
  353. chartRef,
  354. opts: {
  355. widgetIndex,
  356. isDisabled: !focusAreaProps.onAdd,
  357. useFullYAxis: isCumulativeSamplesOp,
  358. },
  359. onZoom: handleZoom,
  360. });
  361. const toggleSeriesVisibility = useCallback(
  362. (series: FocusedMetricsSeries) => {
  363. setHoveredSeries('');
  364. // The focused series array is not populated yet, so we can add all series except the one that was de-selected
  365. if (!focusedSeries || focusedSeries.length === 0) {
  366. onChange?.({
  367. focusedSeries: chartSeries
  368. .filter(s => s.id !== series.id)
  369. .map(s => ({
  370. id: s.id,
  371. groupBy: s.groupBy,
  372. })),
  373. });
  374. return;
  375. }
  376. const filteredSeries = focusedSeries.filter(s => s.id !== series.id);
  377. if (filteredSeries.length === focusedSeries.length) {
  378. // The series was not focused before so we can add it
  379. filteredSeries.push(series);
  380. }
  381. onChange?.({
  382. focusedSeries: filteredSeries,
  383. });
  384. },
  385. [chartSeries, focusedSeries, onChange, setHoveredSeries]
  386. );
  387. const setSeriesVisibility = useCallback(
  388. (series: FocusedMetricsSeries) => {
  389. setHoveredSeries('');
  390. if (focusedSeries?.length === 1 && focusedSeries[0].id === series.id) {
  391. onChange?.({
  392. focusedSeries: [],
  393. });
  394. return;
  395. }
  396. onChange?.({
  397. focusedSeries: [series],
  398. });
  399. },
  400. [focusedSeries, onChange, setHoveredSeries]
  401. );
  402. const handleSortChange = useCallback(
  403. newSort => {
  404. onChange?.({sort: newSort});
  405. },
  406. [onChange]
  407. );
  408. if (!chartSeries || !timeseriesData || isError) {
  409. return (
  410. <StyledMetricWidgetBody>
  411. {isLoading && <LoadingIndicator />}
  412. {isError && (
  413. <Alert type="error">
  414. {(error?.responseJSON?.detail as string) ||
  415. t('Error while fetching metrics data')}
  416. </Alert>
  417. )}
  418. </StyledMetricWidgetBody>
  419. );
  420. }
  421. if (timeseriesData.data.length === 0) {
  422. return (
  423. <StyledMetricWidgetBody>
  424. <EmptyMessage
  425. icon={<IconSearch size="xxl" />}
  426. title={t('No results')}
  427. description={t('No results found for the given query')}
  428. />
  429. </StyledMetricWidgetBody>
  430. );
  431. }
  432. return (
  433. <StyledMetricWidgetBody>
  434. <TransparentLoadingMask visible={isLoading} />
  435. <MetricChart
  436. ref={chartRef}
  437. series={chartSeries}
  438. displayType={displayType}
  439. height={chartHeight}
  440. samples={samplesProp}
  441. focusArea={focusArea}
  442. group={chartGroup}
  443. />
  444. <SummaryTable
  445. series={chartSeries}
  446. onSortChange={handleSortChange}
  447. sort={tableSort}
  448. onRowClick={setSeriesVisibility}
  449. onColorDotClick={toggleSeriesVisibility}
  450. onRowHover={handleHoverSeries}
  451. onRowFilter={handleRowFilter}
  452. />
  453. </StyledMetricWidgetBody>
  454. );
  455. }
  456. );
  457. export function getChartTimeseries(
  458. data: MetricsQueryApiResponse,
  459. queries: MetricsQueryApiQueryParams[],
  460. {
  461. getChartPalette,
  462. focusedSeries,
  463. }: {
  464. getChartPalette: (seriesNames: string[]) => Record<string, string>;
  465. focusedSeries?: Set<string>;
  466. showQuerySymbol?: boolean;
  467. }
  468. ) {
  469. const filteredQueries = queries.filter(isNotQueryOnly);
  470. const series = data.data.flatMap((group, index) => {
  471. const query = filteredQueries[index];
  472. const meta = data.meta[index];
  473. const lastMetaEntry = meta[meta.length - 1];
  474. const unit =
  475. (lastMetaEntry && 'unit' in lastMetaEntry && lastMetaEntry.unit) || 'none';
  476. const scalingFactor =
  477. (lastMetaEntry &&
  478. 'scaling_factor' in lastMetaEntry &&
  479. lastMetaEntry.scaling_factor) ||
  480. 1;
  481. const isEquationSeries = isMetricFormula(query);
  482. const operation = isEquationSeries ? 'count' : query.op;
  483. const isMultiQuery = filteredQueries.length > 1;
  484. return group.map(entry => ({
  485. unit: unit,
  486. operation: operation,
  487. values: entry.series,
  488. scalingFactor: scalingFactor,
  489. name: getMetricsSeriesName(query, entry.by, isMultiQuery),
  490. id: getMetricsSeriesId(query, entry.by),
  491. queryIndex: index,
  492. isEquationSeries,
  493. groupBy: entry.by,
  494. transaction: entry.by.transaction,
  495. release: entry.by.release,
  496. total: entry.totals,
  497. }));
  498. });
  499. const chartPalette = getChartPalette(series.map(s => s.id));
  500. return series.map(item => ({
  501. id: item.id,
  502. seriesName: item.name,
  503. groupBy: item.groupBy,
  504. unit: item.unit,
  505. scalingFactor: item.scalingFactor,
  506. operation: item.operation,
  507. color: chartPalette[item.id],
  508. hidden: focusedSeries && focusedSeries.size > 0 && !focusedSeries.has(item.id),
  509. data: item.values.map((value, index) => ({
  510. name: moment(data.intervals[index]).valueOf(),
  511. value,
  512. })),
  513. transaction: item.transaction as string | undefined,
  514. release: item.release as string | undefined,
  515. isEquationSeries: item.isEquationSeries,
  516. queryIndex: item.queryIndex,
  517. total: item.total,
  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. `;