widget.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. MetricQueryWidgetParams,
  37. MetricWidgetQueryParams,
  38. SortState,
  39. } from 'sentry/utils/metrics/types';
  40. import {MetricDisplayType} 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/ddm/chart/chart';
  50. import type {Series} from 'sentry/views/ddm/chart/types';
  51. import {useFocusArea} from 'sentry/views/ddm/chart/useFocusArea';
  52. import {useMetricChartSamples} from 'sentry/views/ddm/chart/useMetricChartSamples';
  53. import type {FocusAreaProps} from 'sentry/views/ddm/context';
  54. import {EquationSymbol} from 'sentry/views/ddm/equationSymbol copy';
  55. import {FormularFormatter} from 'sentry/views/ddm/formulaParser/formatter';
  56. import {QuerySymbol} from 'sentry/views/ddm/querySymbol';
  57. import {SummaryTable} from 'sentry/views/ddm/summaryTable';
  58. import {useSeriesHover} from 'sentry/views/ddm/useSeriesHover';
  59. import {extendQueryWithGroupBys} from 'sentry/views/ddm/utils';
  60. import {createChartPalette} from 'sentry/views/ddm/utils/metricsChartPalette';
  61. import {DDM_CHART_GROUP, MIN_WIDGET_WIDTH} from './constants';
  62. type MetricWidgetProps = {
  63. displayType: MetricDisplayType;
  64. filters: PageFilters;
  65. focusAreaProps: FocusAreaProps;
  66. onChange: (index: number, data: Partial<MetricWidgetQueryParams>) => void;
  67. queries: MetricsQueryApiQueryParams[];
  68. chartHeight?: number;
  69. context?: 'ddm' | 'dashboard';
  70. focusedSeries?: FocusedMetricsSeries[];
  71. getChartPalette?: (seriesNames: string[]) => Record<string, string>;
  72. hasSiblings?: boolean;
  73. highlightedSampleId?: string;
  74. index?: number;
  75. isSelected?: boolean;
  76. metricsSamples?: MetricsSamplesResults<Field>['data'];
  77. onSampleClick?: (sample: MetricsSamplesResults<Field>['data'][number]) => void;
  78. onSelect?: (index: number) => void;
  79. queryId?: number;
  80. showQuerySymbols?: boolean;
  81. tableSort?: SortState;
  82. };
  83. export type Sample = {
  84. projectId: number;
  85. spanId: string;
  86. transactionId: string;
  87. transactionSpanId: string;
  88. };
  89. function isNotQueryOnly(query: MetricsQueryApiQueryParams) {
  90. return !('isQueryOnly' in query) || !query.isQueryOnly;
  91. }
  92. export function getWidgetTitle(queries: MetricsQueryApiQueryParams[]) {
  93. const filteredQueries = queries.filter(isNotQueryOnly);
  94. if (filteredQueries.length === 1) {
  95. const firstQuery = filteredQueries[0];
  96. if (isMetricFormula(firstQuery)) {
  97. return (
  98. <Fragment>
  99. <FormularFormatter formula={unescapeMetricsFormula(firstQuery.formula)} />
  100. </Fragment>
  101. );
  102. }
  103. return getFormattedMQL(firstQuery);
  104. }
  105. return filteredQueries
  106. .map(q =>
  107. isMetricFormula(q)
  108. ? unescapeMetricsFormula(q.formula)
  109. : formatMRIField(MRIToField(q.mri, q.op))
  110. )
  111. .join(', ');
  112. }
  113. export const MetricWidget = memo(
  114. ({
  115. queryId,
  116. queries,
  117. filters,
  118. displayType,
  119. tableSort,
  120. index = 0,
  121. isSelected = false,
  122. getChartPalette,
  123. onSelect,
  124. onChange,
  125. hasSiblings = false,
  126. showQuerySymbols,
  127. focusAreaProps,
  128. onSampleClick,
  129. chartHeight = 300,
  130. focusedSeries,
  131. metricsSamples,
  132. context = 'ddm',
  133. }: MetricWidgetProps) => {
  134. const firstQuery = queries
  135. .filter(isNotQueryOnly)
  136. .find((query): query is MetricsQueryApiRequestQuery => !isMetricFormula(query));
  137. const handleChange = useCallback(
  138. (data: Partial<MetricWidgetQueryParams>) => {
  139. onChange(index, data);
  140. },
  141. [index, onChange]
  142. );
  143. const handleQueryChange = useCallback(
  144. (queryIndex, data: Partial<MetricWidgetQueryParams>) => {
  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. context={context}
  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. context: 'ddm' | 'dashboard';
  245. displayType: MetricDisplayType;
  246. filters: PageFilters;
  247. focusAreaProps: FocusAreaProps;
  248. queries: MetricsQueryApiQueryParams[];
  249. widgetIndex: number;
  250. chartGroup?: string;
  251. chartHeight?: number;
  252. focusedSeries?: FocusedMetricsSeries[];
  253. getChartPalette?: (seriesNames: string[]) => Record<string, string>;
  254. onChange?: (data: Partial<MetricWidgetQueryParams>) => void;
  255. onQueryChange?: (queryIndex: number, data: Partial<MetricQueryWidgetParams>) => void;
  256. samples?: SamplesProps;
  257. tableSort?: SortState;
  258. }
  259. export interface SamplesProps {
  260. operation: string;
  261. unit: string;
  262. data?: MetricsSamplesResults<Field>['data'];
  263. higlightedId?: string;
  264. onSampleClick?: (sample: MetricsSamplesResults<Field>['data'][number]) => void;
  265. }
  266. const MetricWidgetBody = memo(
  267. ({
  268. onChange,
  269. onQueryChange,
  270. displayType,
  271. focusedSeries,
  272. tableSort,
  273. widgetIndex,
  274. getChartPalette = createChartPalette,
  275. focusAreaProps,
  276. chartHeight,
  277. chartGroup,
  278. samples,
  279. filters,
  280. queries,
  281. context,
  282. }: MetricWidgetBodyProps) => {
  283. const router = useRouter();
  284. const orderedQueries = useMemo(() => {
  285. return queries.map(q => {
  286. if (isMetricFormula(q)) {
  287. return q;
  288. }
  289. return {
  290. ...q,
  291. orderBy: q.orderBy ? q.orderBy : q.groupBy?.length ? 'desc' : undefined,
  292. };
  293. });
  294. }, [queries]);
  295. const {
  296. data: timeseriesData,
  297. isLoading,
  298. isError,
  299. error,
  300. } = useMetricsQuery(orderedQueries, filters, {
  301. intervalLadder: displayType === MetricDisplayType.BAR ? 'bar' : context,
  302. });
  303. const {chartRef, setHoveredSeries} = useSeriesHover();
  304. const handleHoverSeries = useCallback(
  305. (seriesId: string) => {
  306. setHoveredSeries([seriesId, getIngestionSeriesId(seriesId)]);
  307. },
  308. [setHoveredSeries]
  309. );
  310. const chartSeries = useMemo(() => {
  311. return timeseriesData
  312. ? getChartTimeseries(timeseriesData, queries, {
  313. getChartPalette,
  314. focusedSeries: focusedSeries && new Set(focusedSeries?.map(s => s.id)),
  315. })
  316. : [];
  317. }, [timeseriesData, queries, getChartPalette, focusedSeries]);
  318. const samplesProp = useMetricChartSamples({
  319. samples: samples?.data,
  320. highlightedSampleId: samples?.higlightedId,
  321. operation: samples?.operation,
  322. onSampleClick: samples?.onSampleClick,
  323. timeseries: chartSeries,
  324. unit: samples?.unit,
  325. });
  326. const handleZoom = useCallback(
  327. (range: DateTimeObject) => {
  328. Sentry.metrics.increment('ddm.enhance.zoom');
  329. updateDateTime(range, router, {save: true});
  330. },
  331. [router]
  332. );
  333. const handleRowFilter = useCallback(
  334. (queryIndex, series) => {
  335. const queryToUpdate = queries[queryIndex];
  336. if (!queryToUpdate) {
  337. return;
  338. }
  339. if (isMetricFormula(queryToUpdate)) {
  340. // TODO(ddm): filtering on an equation series should extend all conditions of all queries in the equation
  341. return;
  342. }
  343. const newQuery = extendQueryWithGroupBys(queryToUpdate.query, [series.groupBy]);
  344. const indexToUpdate = queries.length > 1 ? queryIndex : widgetIndex;
  345. onQueryChange?.(indexToUpdate, {query: newQuery});
  346. },
  347. [queries, onQueryChange, widgetIndex]
  348. );
  349. const isCumulativeSamplesOp =
  350. queries[0] && !isMetricFormula(queries[0]) && isCumulativeOp(queries[0].op);
  351. const firstScalingFactor = chartSeries.find(s => !s.hidden)?.scalingFactor || 1;
  352. const focusArea = useFocusArea({
  353. ...focusAreaProps,
  354. scalingFactor: firstScalingFactor,
  355. chartRef,
  356. opts: {
  357. widgetIndex,
  358. isDisabled: !focusAreaProps.onAdd,
  359. useFullYAxis: isCumulativeSamplesOp,
  360. },
  361. onZoom: handleZoom,
  362. });
  363. const toggleSeriesVisibility = useCallback(
  364. (series: FocusedMetricsSeries) => {
  365. setHoveredSeries('');
  366. // The focused series array is not populated yet, so we can add all series except the one that was de-selected
  367. if (!focusedSeries || focusedSeries.length === 0) {
  368. onChange?.({
  369. focusedSeries: chartSeries
  370. .filter(s => s.id !== series.id)
  371. .map(s => ({
  372. id: s.id,
  373. groupBy: s.groupBy,
  374. })),
  375. });
  376. return;
  377. }
  378. const filteredSeries = focusedSeries.filter(s => s.id !== series.id);
  379. if (filteredSeries.length === focusedSeries.length) {
  380. // The series was not focused before so we can add it
  381. filteredSeries.push(series);
  382. }
  383. onChange?.({
  384. focusedSeries: filteredSeries,
  385. });
  386. },
  387. [chartSeries, focusedSeries, onChange, setHoveredSeries]
  388. );
  389. const setSeriesVisibility = useCallback(
  390. (series: FocusedMetricsSeries) => {
  391. setHoveredSeries('');
  392. if (focusedSeries?.length === 1 && focusedSeries[0].id === series.id) {
  393. onChange?.({
  394. focusedSeries: [],
  395. });
  396. return;
  397. }
  398. onChange?.({
  399. focusedSeries: [series],
  400. });
  401. },
  402. [focusedSeries, onChange, setHoveredSeries]
  403. );
  404. const handleSortChange = useCallback(
  405. newSort => {
  406. onChange?.({sort: newSort});
  407. },
  408. [onChange]
  409. );
  410. if (!chartSeries || !timeseriesData || isError) {
  411. return (
  412. <StyledMetricWidgetBody>
  413. {isLoading && <LoadingIndicator />}
  414. {isError && (
  415. <Alert type="error">
  416. {(error?.responseJSON?.detail as string) ||
  417. t('Error while fetching metrics data')}
  418. </Alert>
  419. )}
  420. </StyledMetricWidgetBody>
  421. );
  422. }
  423. if (timeseriesData.data.length === 0) {
  424. return (
  425. <StyledMetricWidgetBody>
  426. <EmptyMessage
  427. icon={<IconSearch size="xxl" />}
  428. title={t('No results')}
  429. description={t('No results found for the given query')}
  430. />
  431. </StyledMetricWidgetBody>
  432. );
  433. }
  434. return (
  435. <StyledMetricWidgetBody>
  436. <TransparentLoadingMask visible={isLoading} />
  437. <MetricChart
  438. ref={chartRef}
  439. series={chartSeries}
  440. displayType={displayType}
  441. height={chartHeight}
  442. samples={samplesProp}
  443. focusArea={focusArea}
  444. group={chartGroup}
  445. />
  446. <SummaryTable
  447. series={chartSeries}
  448. onSortChange={handleSortChange}
  449. sort={tableSort}
  450. onRowClick={setSeriesVisibility}
  451. onColorDotClick={toggleSeriesVisibility}
  452. onRowHover={handleHoverSeries}
  453. onRowFilter={handleRowFilter}
  454. />
  455. </StyledMetricWidgetBody>
  456. );
  457. }
  458. );
  459. export function getChartTimeseries(
  460. data: MetricsQueryApiResponse,
  461. queries: MetricsQueryApiQueryParams[],
  462. {
  463. getChartPalette,
  464. focusedSeries,
  465. }: {
  466. getChartPalette: (seriesNames: string[]) => Record<string, string>;
  467. focusedSeries?: Set<string>;
  468. showQuerySymbol?: boolean;
  469. }
  470. ) {
  471. const filteredQueries = queries.filter(isNotQueryOnly);
  472. const series = data.data.flatMap((group, index) => {
  473. const query = filteredQueries[index];
  474. const meta = data.meta[index];
  475. const lastMetaEntry = meta[meta.length - 1];
  476. const unit =
  477. (lastMetaEntry && 'unit' in lastMetaEntry && lastMetaEntry.unit) || 'none';
  478. const scalingFactor =
  479. (lastMetaEntry &&
  480. 'scaling_factor' in lastMetaEntry &&
  481. lastMetaEntry.scaling_factor) ||
  482. 1;
  483. const isEquationSeries = isMetricFormula(query);
  484. const operation = isEquationSeries ? 'count' : query.op;
  485. const isMultiQuery = filteredQueries.length > 1;
  486. return group.map(entry => ({
  487. unit: unit,
  488. operation: operation,
  489. values: entry.series,
  490. scalingFactor: scalingFactor,
  491. name: getMetricsSeriesName(query, entry.by, isMultiQuery),
  492. id: getMetricsSeriesId(query, entry.by),
  493. queryIndex: index,
  494. isEquationSeries,
  495. groupBy: entry.by,
  496. transaction: entry.by.transaction,
  497. release: entry.by.release,
  498. total: entry.totals,
  499. }));
  500. });
  501. const chartPalette = getChartPalette(series.map(s => s.id));
  502. return series.map(item => ({
  503. id: item.id,
  504. seriesName: item.name,
  505. groupBy: item.groupBy,
  506. unit: item.unit,
  507. scalingFactor: item.scalingFactor,
  508. operation: item.operation,
  509. color: chartPalette[item.id],
  510. hidden: focusedSeries && focusedSeries.size > 0 && !focusedSeries.has(item.id),
  511. data: item.values.map((value, index) => ({
  512. name: moment(data.intervals[index]).valueOf(),
  513. value,
  514. })),
  515. transaction: item.transaction as string | undefined,
  516. release: item.release as string | undefined,
  517. isEquationSeries: item.isEquationSeries,
  518. queryIndex: item.queryIndex,
  519. total: item.total,
  520. emphasis: {
  521. focus: 'series',
  522. } as SeriesOption['emphasis'],
  523. })) as Series[];
  524. }
  525. const MetricWidgetPanel = styled(Panel)<{
  526. isHighlightable: boolean;
  527. isHighlighted: boolean;
  528. }>`
  529. padding-bottom: 0;
  530. margin-bottom: 0;
  531. min-width: ${MIN_WIDGET_WIDTH}px;
  532. position: relative;
  533. transition: box-shadow 0.2s ease;
  534. ${p =>
  535. p.isHighlightable &&
  536. `
  537. &:focus,
  538. &:hover {
  539. box-shadow: 0px 0px 0px 3px
  540. ${p.isHighlighted ? p.theme.purple200 : 'rgba(209, 202, 216, 0.2)'};
  541. }
  542. `}
  543. ${p =>
  544. p.isHighlighted &&
  545. `
  546. box-shadow: 0px 0px 0px 3px ${p.theme.purple200};
  547. border-color: transparent;
  548. `}
  549. `;
  550. const StyledMetricWidgetBody = styled('div')`
  551. padding: ${space(1)};
  552. gap: ${space(3)};
  553. display: flex;
  554. flex-direction: column;
  555. justify-content: center;
  556. height: 100%;
  557. `;
  558. const MetricWidgetBodyWrapper = styled('div')`
  559. padding: ${space(1)};
  560. `;
  561. const MetricWidgetHeader = styled('div')`
  562. display: flex;
  563. justify-content: space-between;
  564. align-items: center;
  565. gap: ${space(1)};
  566. padding-left: ${space(2)};
  567. padding-top: ${space(1.5)};
  568. padding-right: ${space(2)};
  569. `;
  570. const WidgetTitle = styled('div')`
  571. flex-grow: 1;
  572. font-size: ${p => p.theme.fontSizeMedium};
  573. display: inline-grid;
  574. grid-auto-flow: column;
  575. `;
  576. const StyledTooltip = styled(Tooltip)`
  577. ${p => p.theme.overflowEllipsis};
  578. `;