metricsExplorer.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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, 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. />
  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 [dataToBeRendered, setDataToBeRendered] = useState<MetricsData | undefined>(
  274. undefined
  275. );
  276. const focusedSeries = router.location.query.focusedSeries;
  277. const [hoveredLegend, setHoveredLegend] = useState('');
  278. useEffect(() => {
  279. if (data) {
  280. setDataToBeRendered(data);
  281. }
  282. }, [data]);
  283. const toggleSeriesVisibility = (seriesName: string) => {
  284. setHoveredLegend('');
  285. router.push({
  286. ...router.location,
  287. query: {
  288. ...router.location.query,
  289. focusedSeries: focusedSeries === seriesName ? undefined : seriesName,
  290. },
  291. });
  292. };
  293. if (!dataToBeRendered || isError) {
  294. return (
  295. <DisplayWrapper>
  296. {isLoading && <LoadingIndicator />}
  297. {isError && <Alert type="error">{t('Error while fetching metrics data')}</Alert>}
  298. </DisplayWrapper>
  299. );
  300. }
  301. // TODO(ddm): we should move this into the useMetricsData hook
  302. const sorted = sortData(dataToBeRendered);
  303. const unit = getUnitFromMRI(Object.keys(dataToBeRendered.groups[0]?.series ?? {})[0]); // this assumes that all series have the same unit
  304. const series = sorted.groups.map(g => {
  305. return {
  306. values: Object.values(g.series)[0],
  307. name: getSeriesName(
  308. g,
  309. dataToBeRendered.groups.length === 1,
  310. metricsDataProps.groupBy
  311. ),
  312. transaction: g.by.transaction,
  313. release: g.by.release,
  314. };
  315. });
  316. const colors = theme.charts.getColorPalette(series.length);
  317. const chartSeries = series.map((item, i) => ({
  318. seriesName: item.name,
  319. unit,
  320. color: colorFn(colors[i])
  321. .alpha(hoveredLegend && hoveredLegend !== item.name ? 0.1 : 1)
  322. .string(),
  323. hidden: focusedSeries && focusedSeries !== item.name,
  324. data: item.values.map((value, index) => ({
  325. name: sorted.intervals[index],
  326. value,
  327. })),
  328. transaction: item.transaction as string | undefined,
  329. release: item.release as string | undefined,
  330. emphasis: {
  331. focus: 'series',
  332. } as LineSeriesOption['emphasis'],
  333. }));
  334. return (
  335. <DisplayWrapper>
  336. <TransparentLoadingMask visible={isLoading} />
  337. <Chart
  338. series={chartSeries}
  339. displayType={displayType}
  340. operation={metricsDataProps.op}
  341. projects={metricsDataProps.projects}
  342. environments={metricsDataProps.environments}
  343. {...normalizeChartTimeParams(sorted)}
  344. />
  345. <SummaryTable
  346. series={chartSeries}
  347. operation={metricsDataProps.op}
  348. onClick={toggleSeriesVisibility}
  349. setHoveredLegend={focusedSeries ? undefined : setHoveredLegend}
  350. />
  351. </DisplayWrapper>
  352. );
  353. }
  354. function getSeriesName(
  355. group: Group,
  356. isOnlyGroup = false,
  357. groupBy: MetricsDataProps['groupBy']
  358. ) {
  359. if (isOnlyGroup && !groupBy?.length) {
  360. return Object.keys(group.series)?.[0] ?? '(none)';
  361. }
  362. return Object.entries(group.by)
  363. .map(([key, value]) => `${key}:${String(value).length ? value : t('none')}`)
  364. .join(', ');
  365. }
  366. function sortData(data: MetricsData): MetricsData {
  367. if (!data.groups.length) {
  368. return data;
  369. }
  370. const key = Object.keys(data.groups[0].totals)[0];
  371. const sortedGroups = data.groups.sort((a, b) =>
  372. a.totals[key] < b.totals[key] ? 1 : -1
  373. );
  374. return {
  375. ...data,
  376. groups: sortedGroups,
  377. };
  378. }
  379. function normalizeChartTimeParams(data: MetricsData) {
  380. const {
  381. start,
  382. end,
  383. utc: utcString,
  384. statsPeriod,
  385. } = normalizeDateTimeParams(data, {
  386. allowEmptyPeriod: true,
  387. allowAbsoluteDatetime: true,
  388. allowAbsolutePageDatetime: true,
  389. });
  390. const utc = utcString === 'true';
  391. if (start && end) {
  392. return utc
  393. ? {
  394. start: moment.utc(start).format(),
  395. end: moment.utc(end).format(),
  396. utc,
  397. }
  398. : {
  399. start: moment(start).utc().format(),
  400. end: moment(end).utc().format(),
  401. utc,
  402. };
  403. }
  404. return {
  405. period: statsPeriod ?? '90d',
  406. };
  407. }
  408. export type Series = {
  409. color: string;
  410. data: {name: string; value: number}[];
  411. seriesName: string;
  412. unit: string;
  413. hidden?: boolean;
  414. release?: string;
  415. transaction?: string;
  416. };
  417. type ChartProps = {
  418. displayType: MetricDisplayType;
  419. environments: PageFilters['environments'];
  420. projects: PageFilters['projects'];
  421. series: Series[];
  422. end?: string;
  423. operation?: string;
  424. period?: string;
  425. start?: string;
  426. utc?: boolean;
  427. };
  428. function Chart({
  429. series,
  430. displayType,
  431. start,
  432. end,
  433. period,
  434. utc,
  435. operation,
  436. projects,
  437. environments,
  438. }: ChartProps) {
  439. const unit = series[0]?.unit;
  440. const seriesToShow = series.filter(s => !s.hidden);
  441. const chartProps = {
  442. isGroupedByDate: true,
  443. height: 300,
  444. colors: seriesToShow.map(s => s.color),
  445. grid: {top: 20, bottom: 20, left: 20, right: 20},
  446. tooltip: {
  447. valueFormatter: (value: number) => {
  448. return formatMetricsUsingUnitAndOp(value, unit, operation);
  449. },
  450. nameFormatter: mri => getNameFromMRI(mri),
  451. },
  452. yAxis: {
  453. axisLabel: {
  454. formatter: (value: number) => {
  455. return formatMetricsUsingUnitAndOp(value, unit, operation);
  456. },
  457. },
  458. },
  459. };
  460. return (
  461. <Fragment>
  462. <ChartZoom period={period} start={start} end={end} utc={utc}>
  463. {zoomRenderProps => (
  464. <ReleaseSeries
  465. utc={utc}
  466. period={period}
  467. start={zoomRenderProps.start!}
  468. end={zoomRenderProps.end!}
  469. projects={projects}
  470. environments={environments}
  471. preserveQueryParams
  472. >
  473. {({releaseSeries}) => {
  474. const legend = releaseSeries[0]?.markLine?.data?.length
  475. ? Legend({
  476. itemGap: 20,
  477. top: 0,
  478. right: 20,
  479. data: releaseSeries.map(s => s.seriesName),
  480. theme: theme as Theme,
  481. })
  482. : undefined;
  483. return displayType === MetricDisplayType.LINE ? (
  484. <LineChart
  485. series={[...seriesToShow, ...releaseSeries]}
  486. legend={legend}
  487. {...chartProps}
  488. {...zoomRenderProps}
  489. />
  490. ) : displayType === MetricDisplayType.AREA ? (
  491. <AreaChart
  492. series={[...seriesToShow, ...releaseSeries]}
  493. legend={legend}
  494. {...chartProps}
  495. {...zoomRenderProps}
  496. />
  497. ) : (
  498. <BarChart
  499. stacked
  500. series={[...seriesToShow, ...releaseSeries]}
  501. legend={legend}
  502. {...chartProps}
  503. {...zoomRenderProps}
  504. />
  505. );
  506. }}
  507. </ReleaseSeries>
  508. )}
  509. </ChartZoom>
  510. </Fragment>
  511. );
  512. }
  513. const MetricsExplorerPanel = styled(Panel)`
  514. padding-bottom: 0;
  515. `;
  516. const DisplayWrapper = styled('div')`
  517. padding: ${space(1)};
  518. display: flex;
  519. flex-direction: column;
  520. justify-content: center;
  521. `;
  522. export default MetricsExplorer;