metricsExplorer.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. import {Fragment, useCallback, useEffect, useMemo, useState} from 'react';
  2. import {Theme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import colorFn from 'color';
  5. import type {LineSeriesOption} from 'echarts';
  6. import moment from 'moment';
  7. import Alert from 'sentry/components/alert';
  8. import {AreaChart} from 'sentry/components/charts/areaChart';
  9. import {BarChart} from 'sentry/components/charts/barChart';
  10. import ChartZoom from 'sentry/components/charts/chartZoom';
  11. import Legend from 'sentry/components/charts/components/legend';
  12. import {LineChart} from 'sentry/components/charts/lineChart';
  13. import ReleaseSeries from 'sentry/components/charts/releaseSeries';
  14. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  15. import {CompactSelect} from 'sentry/components/compactSelect';
  16. import EmptyMessage from 'sentry/components/emptyMessage';
  17. import SearchBar from 'sentry/components/events/searchBar';
  18. import LoadingIndicator from 'sentry/components/loadingIndicator';
  19. import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
  20. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  21. import Panel from 'sentry/components/panels/panel';
  22. import PanelBody from 'sentry/components/panels/panelBody';
  23. import Tag from 'sentry/components/tag';
  24. import {IconSearch} from 'sentry/icons';
  25. import {t} from 'sentry/locale';
  26. import {space} from 'sentry/styles/space';
  27. import {MetricsTag, PageFilters, SavedSearchType, TagCollection} from 'sentry/types';
  28. import {
  29. defaultMetricDisplayType,
  30. formatMetricsUsingUnitAndOp,
  31. getNameFromMRI,
  32. getReadableMetricType,
  33. getUnitFromMRI,
  34. getUseCaseFromMri,
  35. isAllowedOp,
  36. MetricDisplayType,
  37. MetricsData,
  38. MetricsDataProps,
  39. MetricsQuery,
  40. updateQuery,
  41. useMetricsData,
  42. useMetricsMeta,
  43. useMetricsTags,
  44. } from 'sentry/utils/metrics';
  45. import {decodeList} from 'sentry/utils/queryString';
  46. import theme from 'sentry/utils/theme';
  47. import useApi from 'sentry/utils/useApi';
  48. import useKeyPress from 'sentry/utils/useKeyPress';
  49. import useOrganization from 'sentry/utils/useOrganization';
  50. import usePageFilters from 'sentry/utils/usePageFilters';
  51. import useRouter from 'sentry/utils/useRouter';
  52. import {SummaryTable} from 'sentry/views/ddm/summaryTable';
  53. function MetricsExplorer() {
  54. const {selection} = usePageFilters();
  55. const router = useRouter();
  56. const metricsQuery: MetricsQuery = {
  57. mri: router.location.query.mri,
  58. op: router.location.query.op,
  59. query: router.location.query.query,
  60. groupBy: decodeList(router.location.query.groupBy),
  61. };
  62. return (
  63. <MetricsExplorerPanel>
  64. <PanelBody>
  65. <QueryBuilder metricsQuery={metricsQuery} />
  66. <MetricsExplorerDisplayOuter
  67. displayType={router.location.query.display ?? defaultMetricDisplayType}
  68. datetime={selection.datetime}
  69. projects={selection.projects}
  70. environments={selection.environments}
  71. {...metricsQuery}
  72. />
  73. </PanelBody>
  74. </MetricsExplorerPanel>
  75. );
  76. }
  77. type QueryBuilderProps = {
  78. metricsQuery: MetricsQuery;
  79. };
  80. function QueryBuilder({metricsQuery}: QueryBuilderProps) {
  81. const router = useRouter();
  82. const {selection} = usePageFilters();
  83. const meta = useMetricsMeta(selection.projects);
  84. const mriModeKeyPressed = useKeyPress('`', undefined, true);
  85. const [mriMode, setMriMode] = useState(false); // power user mode that shows raw MRI instead of metrics names
  86. useEffect(() => {
  87. if (mriModeKeyPressed) {
  88. setMriMode(!mriMode);
  89. }
  90. // eslint-disable-next-line react-hooks/exhaustive-deps
  91. }, [mriModeKeyPressed]);
  92. const {data: tags = []} = useMetricsTags(metricsQuery.mri, selection.projects);
  93. if (!meta) {
  94. return null;
  95. }
  96. return (
  97. <QueryBuilderWrapper>
  98. <QueryBuilderRow>
  99. <PageFilterBar condensed>
  100. <CompactSelect
  101. searchable
  102. triggerProps={{prefix: t('Metric'), size: 'sm'}}
  103. options={Object.values(meta)
  104. .filter(metric =>
  105. mriMode
  106. ? true
  107. : metric.mri.includes(':custom/') || metric.mri === metricsQuery.mri
  108. )
  109. .map(metric => ({
  110. label: mriMode ? metric.mri : metric.name,
  111. value: metric.mri,
  112. trailingItems: mriMode ? undefined : (
  113. <Fragment>
  114. <Tag tooltipText={t('Type')}>
  115. {getReadableMetricType(metric.type)}
  116. </Tag>
  117. <Tag tooltipText={t('Unit')}>{metric.unit}</Tag>
  118. </Fragment>
  119. ),
  120. }))}
  121. value={metricsQuery.mri}
  122. onChange={option => {
  123. const availableOps = meta[option.value]?.operations.filter(isAllowedOp);
  124. const selectedOp = availableOps.includes(metricsQuery.op ?? '')
  125. ? metricsQuery.op
  126. : availableOps[0];
  127. updateQuery(router, {
  128. mri: option.value,
  129. op: selectedOp,
  130. groupBy: undefined,
  131. focusedSeries: undefined,
  132. });
  133. }}
  134. />
  135. <CompactSelect
  136. triggerProps={{prefix: t('Operation'), size: 'sm'}}
  137. options={
  138. meta[metricsQuery.mri]?.operations.filter(isAllowedOp).map(op => ({
  139. label: op,
  140. value: op,
  141. })) ?? []
  142. }
  143. disabled={!metricsQuery.mri}
  144. value={metricsQuery.op}
  145. onChange={option =>
  146. updateQuery(router, {
  147. op: option.value,
  148. })
  149. }
  150. />
  151. <CompactSelect
  152. multiple
  153. triggerProps={{prefix: t('Group by'), size: 'sm'}}
  154. options={tags.map(tag => ({
  155. label: tag.key,
  156. value: tag.key,
  157. }))}
  158. disabled={!metricsQuery.mri}
  159. value={metricsQuery.groupBy}
  160. onChange={options =>
  161. updateQuery(router, {
  162. groupBy: options.map(o => o.value),
  163. focusedSeries: undefined,
  164. })
  165. }
  166. />
  167. </PageFilterBar>
  168. </QueryBuilderRow>
  169. <QueryBuilderRow>
  170. <MetricSearchBar
  171. tags={tags}
  172. mri={metricsQuery.mri}
  173. disabled={!metricsQuery.mri}
  174. onChange={query => updateQuery(router, {query})}
  175. query={metricsQuery.query}
  176. />
  177. </QueryBuilderRow>
  178. </QueryBuilderWrapper>
  179. );
  180. }
  181. type MetricSearchBarProps = {
  182. mri: string;
  183. onChange: (value: string) => void;
  184. tags: MetricsTag[];
  185. disabled?: boolean;
  186. query?: string;
  187. };
  188. function MetricSearchBar({tags, mri, disabled, onChange, query}: MetricSearchBarProps) {
  189. const org = useOrganization();
  190. const api = useApi();
  191. const {selection} = usePageFilters();
  192. const supportedTags: TagCollection = useMemo(
  193. () => tags.reduce((acc, tag) => ({...acc, [tag.key]: tag}), {}),
  194. [tags]
  195. );
  196. // TODO(ogi) try to use useApiQuery here
  197. const getTagValues = useCallback(
  198. async tag => {
  199. const tagsValues = await api.requestPromise(
  200. `/organizations/${org.slug}/metrics/tags/${tag.key}/`,
  201. {
  202. query: {
  203. metric: mri,
  204. useCase: getUseCaseFromMri(mri),
  205. project: selection.projects,
  206. },
  207. }
  208. );
  209. return tagsValues.filter(tv => tv.value !== '').map(tv => tv.value);
  210. },
  211. [api, mri, org.slug, selection.projects]
  212. );
  213. const handleChange = useCallback(
  214. (value: string, {validSearch} = {validSearch: true}) => {
  215. if (validSearch) {
  216. onChange(value);
  217. }
  218. },
  219. [onChange]
  220. );
  221. return (
  222. <WideSearchBar
  223. disabled={disabled}
  224. maxMenuHeight={220}
  225. organization={org}
  226. onGetTagValues={getTagValues}
  227. supportedTags={supportedTags}
  228. onClose={handleChange}
  229. onSearch={handleChange}
  230. placeholder={t('Filter by tags')}
  231. defaultQuery={query}
  232. savedSearchType={SavedSearchType.METRIC}
  233. />
  234. );
  235. }
  236. const QueryBuilderWrapper = styled('div')`
  237. display: flex;
  238. flex-direction: column;
  239. `;
  240. const QueryBuilderRow = styled('div')`
  241. padding: ${space(1)};
  242. padding-bottom: 0;
  243. `;
  244. const WideSearchBar = styled(SearchBar)`
  245. width: 100%;
  246. opacity: ${p => (p.disabled ? '0.6' : '1')};
  247. `;
  248. // TODO(ddm): reuse from types/metrics.tsx
  249. type Group = {
  250. by: Record<string, unknown>;
  251. series: Record<string, number[]>;
  252. totals: Record<string, number>;
  253. };
  254. type DisplayProps = MetricsDataProps & {
  255. displayType: MetricDisplayType;
  256. };
  257. function MetricsExplorerDisplayOuter(props?: DisplayProps) {
  258. if (!props?.mri) {
  259. return (
  260. <DisplayWrapper>
  261. <EmptyMessage
  262. icon={<IconSearch size="xxl" />}
  263. title={t('Nothing to show!')}
  264. description={t('Choose a metric to display data.')}
  265. />
  266. </DisplayWrapper>
  267. );
  268. }
  269. return <MetricsExplorerDisplay {...props} />;
  270. }
  271. function MetricsExplorerDisplay({displayType, ...metricsDataProps}: DisplayProps) {
  272. const router = useRouter();
  273. const {data, isLoading, isError, error} = useMetricsData(metricsDataProps);
  274. const [dataToBeRendered, setDataToBeRendered] = useState<MetricsData | undefined>(
  275. undefined
  276. );
  277. const focusedSeries = router.location.query.focusedSeries;
  278. const [hoveredLegend, setHoveredLegend] = useState('');
  279. useEffect(() => {
  280. if (data) {
  281. setDataToBeRendered(data);
  282. }
  283. }, [data]);
  284. const toggleSeriesVisibility = (seriesName: string) => {
  285. setHoveredLegend('');
  286. router.push({
  287. ...router.location,
  288. query: {
  289. ...router.location.query,
  290. focusedSeries: focusedSeries === seriesName ? undefined : seriesName,
  291. },
  292. });
  293. };
  294. if (!dataToBeRendered || isError) {
  295. return (
  296. <DisplayWrapper>
  297. {isLoading && <LoadingIndicator />}
  298. {isError && (
  299. <Alert type="error">
  300. {error?.responseJSON?.detail || t('Error while fetching metrics data')}
  301. </Alert>
  302. )}
  303. </DisplayWrapper>
  304. );
  305. }
  306. // TODO(ddm): we should move this into the useMetricsData hook
  307. const sorted = sortData(dataToBeRendered);
  308. const unit = getUnitFromMRI(Object.keys(dataToBeRendered.groups[0]?.series ?? {})[0]); // this assumes that all series have the same unit
  309. const series = sorted.groups.map(g => {
  310. return {
  311. values: Object.values(g.series)[0],
  312. name: getSeriesName(
  313. g,
  314. dataToBeRendered.groups.length === 1,
  315. metricsDataProps.groupBy
  316. ),
  317. transaction: g.by.transaction,
  318. release: g.by.release,
  319. };
  320. });
  321. const colors = theme.charts.getColorPalette(series.length);
  322. const chartSeries = series.map((item, i) => ({
  323. seriesName: item.name,
  324. unit,
  325. color: colorFn(colors[i])
  326. .alpha(hoveredLegend && hoveredLegend !== item.name ? 0.1 : 1)
  327. .string(),
  328. hidden: focusedSeries && focusedSeries !== item.name,
  329. data: item.values.map((value, index) => ({
  330. name: sorted.intervals[index],
  331. value,
  332. })),
  333. transaction: item.transaction as string | undefined,
  334. release: item.release as string | undefined,
  335. emphasis: {
  336. focus: 'series',
  337. } as LineSeriesOption['emphasis'],
  338. }));
  339. return (
  340. <DisplayWrapper>
  341. <TransparentLoadingMask visible={isLoading} />
  342. <Chart
  343. series={chartSeries}
  344. displayType={displayType}
  345. operation={metricsDataProps.op}
  346. projects={metricsDataProps.projects}
  347. environments={metricsDataProps.environments}
  348. {...normalizeChartTimeParams(sorted)}
  349. />
  350. <SummaryTable
  351. series={chartSeries}
  352. operation={metricsDataProps.op}
  353. onClick={toggleSeriesVisibility}
  354. setHoveredLegend={focusedSeries ? undefined : setHoveredLegend}
  355. />
  356. </DisplayWrapper>
  357. );
  358. }
  359. function getSeriesName(
  360. group: Group,
  361. isOnlyGroup = false,
  362. groupBy: MetricsDataProps['groupBy']
  363. ) {
  364. if (isOnlyGroup && !groupBy?.length) {
  365. return Object.keys(group.series)?.[0] ?? '(none)';
  366. }
  367. return Object.entries(group.by)
  368. .map(([key, value]) => `${key}:${String(value).length ? value : t('none')}`)
  369. .join(', ');
  370. }
  371. function sortData(data: MetricsData): MetricsData {
  372. if (!data.groups.length) {
  373. return data;
  374. }
  375. const key = Object.keys(data.groups[0].totals)[0];
  376. const sortedGroups = data.groups.sort((a, b) =>
  377. a.totals[key] < b.totals[key] ? 1 : -1
  378. );
  379. return {
  380. ...data,
  381. groups: sortedGroups,
  382. };
  383. }
  384. function normalizeChartTimeParams(data: MetricsData) {
  385. const {
  386. start,
  387. end,
  388. utc: utcString,
  389. statsPeriod,
  390. } = normalizeDateTimeParams(data, {
  391. allowEmptyPeriod: true,
  392. allowAbsoluteDatetime: true,
  393. allowAbsolutePageDatetime: true,
  394. });
  395. const utc = utcString === 'true';
  396. if (start && end) {
  397. return utc
  398. ? {
  399. start: moment.utc(start).format(),
  400. end: moment.utc(end).format(),
  401. utc,
  402. }
  403. : {
  404. start: moment(start).utc().format(),
  405. end: moment(end).utc().format(),
  406. utc,
  407. };
  408. }
  409. return {
  410. period: statsPeriod ?? '90d',
  411. };
  412. }
  413. export type Series = {
  414. color: string;
  415. data: {name: string; value: number}[];
  416. seriesName: string;
  417. unit: string;
  418. hidden?: boolean;
  419. release?: string;
  420. transaction?: string;
  421. };
  422. type ChartProps = {
  423. displayType: MetricDisplayType;
  424. environments: PageFilters['environments'];
  425. projects: PageFilters['projects'];
  426. series: Series[];
  427. end?: string;
  428. operation?: string;
  429. period?: string;
  430. start?: string;
  431. utc?: boolean;
  432. };
  433. function Chart({
  434. series,
  435. displayType,
  436. start,
  437. end,
  438. period,
  439. utc,
  440. operation,
  441. projects,
  442. environments,
  443. }: ChartProps) {
  444. const unit = series[0]?.unit;
  445. const seriesToShow = series.filter(s => !s.hidden);
  446. const chartProps = {
  447. isGroupedByDate: true,
  448. height: 300,
  449. colors: seriesToShow.map(s => s.color),
  450. grid: {top: 20, bottom: 20, left: 20, right: 20},
  451. tooltip: {
  452. valueFormatter: (value: number) => {
  453. return formatMetricsUsingUnitAndOp(value, unit, operation);
  454. },
  455. nameFormatter: mri => getNameFromMRI(mri),
  456. },
  457. yAxis: {
  458. axisLabel: {
  459. formatter: (value: number) => {
  460. return formatMetricsUsingUnitAndOp(value, unit, operation);
  461. },
  462. },
  463. },
  464. };
  465. return (
  466. <Fragment>
  467. <ChartZoom period={period} start={start} end={end} utc={utc}>
  468. {zoomRenderProps => (
  469. <ReleaseSeries
  470. utc={utc}
  471. period={period}
  472. start={zoomRenderProps.start!}
  473. end={zoomRenderProps.end!}
  474. projects={projects}
  475. environments={environments}
  476. preserveQueryParams
  477. >
  478. {({releaseSeries}) => {
  479. const legend = releaseSeries[0]?.markLine?.data?.length
  480. ? Legend({
  481. itemGap: 20,
  482. top: 0,
  483. right: 20,
  484. data: releaseSeries.map(s => s.seriesName),
  485. theme: theme as Theme,
  486. })
  487. : undefined;
  488. return displayType === MetricDisplayType.LINE ? (
  489. <LineChart
  490. series={[...seriesToShow, ...releaseSeries]}
  491. legend={legend}
  492. {...chartProps}
  493. {...zoomRenderProps}
  494. />
  495. ) : displayType === MetricDisplayType.AREA ? (
  496. <AreaChart
  497. series={[...seriesToShow, ...releaseSeries]}
  498. legend={legend}
  499. {...chartProps}
  500. {...zoomRenderProps}
  501. />
  502. ) : (
  503. <BarChart
  504. stacked
  505. series={[...seriesToShow, ...releaseSeries]}
  506. legend={legend}
  507. {...chartProps}
  508. {...zoomRenderProps}
  509. />
  510. );
  511. }}
  512. </ReleaseSeries>
  513. )}
  514. </ChartZoom>
  515. </Fragment>
  516. );
  517. }
  518. const MetricsExplorerPanel = styled(Panel)`
  519. padding-bottom: 0;
  520. `;
  521. const DisplayWrapper = styled('div')`
  522. padding: ${space(1)};
  523. display: flex;
  524. flex-direction: column;
  525. justify-content: center;
  526. `;
  527. export default MetricsExplorer;