metricsExplorer.tsx 15 KB

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