queryBuilder.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import {Fragment, memo, useCallback, useEffect, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import uniqBy from 'lodash/uniqBy';
  4. import {ComboBox} from 'sentry/components/comboBox';
  5. import type {ComboBoxOption} from 'sentry/components/comboBox/types';
  6. import type {SelectOption} from 'sentry/components/compactSelect';
  7. import {CompactSelect} from 'sentry/components/compactSelect';
  8. import {Tooltip} from 'sentry/components/tooltip';
  9. import {IconLightning, IconReleases, IconWarning} from 'sentry/icons';
  10. import {t} from 'sentry/locale';
  11. import {space} from 'sentry/styles/space';
  12. import type {MetricMeta, MetricsOperation, MRI} from 'sentry/types';
  13. import {trackAnalytics} from 'sentry/utils/analytics';
  14. import {
  15. isAllowedOp,
  16. isCustomMetric,
  17. isSpanMeasurement,
  18. isSpanSelfTime,
  19. isTransactionDuration,
  20. isTransactionMeasurement,
  21. } from 'sentry/utils/metrics';
  22. import {hasMetricsExperimentalFeature} from 'sentry/utils/metrics/features';
  23. import {getReadableMetricType} from 'sentry/utils/metrics/formatters';
  24. import {formatMRI, parseMRI} from 'sentry/utils/metrics/mri';
  25. import type {MetricsQuery} from 'sentry/utils/metrics/types';
  26. import {useBreakpoints} from 'sentry/utils/metrics/useBreakpoints';
  27. import {useIncrementQueryMetric} from 'sentry/utils/metrics/useIncrementQueryMetric';
  28. import {useMetricsMeta} from 'sentry/utils/metrics/useMetricsMeta';
  29. import {useMetricsTags} from 'sentry/utils/metrics/useMetricsTags';
  30. import {middleEllipsis} from 'sentry/utils/middleEllipsis';
  31. import useKeyPress from 'sentry/utils/useKeyPress';
  32. import useOrganization from 'sentry/utils/useOrganization';
  33. import usePageFilters from 'sentry/utils/usePageFilters';
  34. import useProjects from 'sentry/utils/useProjects';
  35. import {MetricListItemDetails} from 'sentry/views/metrics/metricListItemDetails';
  36. import {MetricSearchBar} from 'sentry/views/metrics/metricSearchBar';
  37. type QueryBuilderProps = {
  38. metricsQuery: MetricsQuery;
  39. onChange: (data: Partial<MetricsQuery>) => void;
  40. projects: number[];
  41. };
  42. const isVisibleTransactionMetric = (metric: MetricMeta) =>
  43. isTransactionDuration(metric) || isTransactionMeasurement(metric);
  44. const isVisibleSpanMetric = (metric: MetricMeta) =>
  45. isSpanSelfTime(metric) || isSpanMeasurement(metric);
  46. const isShownByDefault = (metric: MetricMeta) =>
  47. isCustomMetric(metric) ||
  48. isVisibleTransactionMetric(metric) ||
  49. isVisibleSpanMetric(metric);
  50. function getOpsForMRI(mri: MRI, meta: MetricMeta[]) {
  51. return meta.find(metric => metric.mri === mri)?.operations.filter(isAllowedOp) ?? [];
  52. }
  53. function useMriMode() {
  54. const [mriMode, setMriMode] = useState(false);
  55. const mriModeKeyPressed = useKeyPress('`', undefined, true);
  56. useEffect(() => {
  57. if (mriModeKeyPressed) {
  58. setMriMode(value => !value);
  59. }
  60. // eslint-disable-next-line react-hooks/exhaustive-deps
  61. }, [mriModeKeyPressed]);
  62. return mriMode;
  63. }
  64. export const QueryBuilder = memo(function QueryBuilder({
  65. metricsQuery,
  66. projects: projectIds,
  67. onChange,
  68. }: QueryBuilderProps) {
  69. const organization = useOrganization();
  70. const pageFilters = usePageFilters();
  71. const breakpoints = useBreakpoints();
  72. const {projects} = useProjects();
  73. const {
  74. data: meta,
  75. isLoading: isMetaLoading,
  76. isRefetching: isMetaRefetching,
  77. refetch: refetchMeta,
  78. } = useMetricsMeta(pageFilters.selection);
  79. const mriMode = useMriMode();
  80. const shouldUseComboBox = hasMetricsExperimentalFeature(organization);
  81. const {data: tagsData = [], isLoading: tagsIsLoading} = useMetricsTags(
  82. metricsQuery.mri,
  83. {
  84. projects: projectIds,
  85. }
  86. );
  87. const selectedProjects = useMemo(
  88. () =>
  89. projects.filter(project =>
  90. projectIds[0] === -1
  91. ? true
  92. : projectIds.length === 0
  93. ? project.isMember
  94. : projectIds.includes(parseInt(project.id, 10))
  95. ),
  96. [projectIds, projects]
  97. );
  98. const groupByOptions = useMemo(() => {
  99. return uniqBy(tagsData, 'key').map(tag => ({
  100. key: tag.key,
  101. // So that we don't have to parse the query to determine if the tag is used
  102. trailingItems: metricsQuery.query?.includes(`${tag.key}:`) ? (
  103. <TagWarningIcon />
  104. ) : undefined,
  105. }));
  106. }, [tagsData, metricsQuery.query]);
  107. const displayedMetrics = useMemo(() => {
  108. const isSelected = (metric: MetricMeta) => metric.mri === metricsQuery.mri;
  109. const result = meta
  110. .filter(metric => isShownByDefault(metric) || isSelected(metric))
  111. .sort(metric => (isSelected(metric) ? -1 : 1));
  112. // Add the selected metric to the top of the list if it's not already there
  113. if (shouldUseComboBox && result[0]?.mri !== metricsQuery.mri) {
  114. const parsedMri = parseMRI(metricsQuery.mri)!;
  115. return [
  116. {
  117. mri: metricsQuery.mri,
  118. type: parsedMri.type,
  119. unit: parsedMri.unit,
  120. operations: [],
  121. projectIds: [],
  122. blockingStatus: [],
  123. } satisfies MetricMeta,
  124. ...result,
  125. ];
  126. }
  127. return result;
  128. }, [meta, metricsQuery.mri, shouldUseComboBox]);
  129. const selectedMeta = useMemo(() => {
  130. return meta.find(metric => metric.mri === metricsQuery.mri);
  131. }, [meta, metricsQuery.mri]);
  132. const incrementQueryMetric = useIncrementQueryMetric({
  133. ...metricsQuery,
  134. });
  135. const handleMRIChange = useCallback(
  136. ({value}) => {
  137. const availableOps = getOpsForMRI(value, meta);
  138. const selectedOp = availableOps.includes(
  139. (metricsQuery.op ?? '') as MetricsOperation
  140. )
  141. ? metricsQuery.op
  142. : availableOps?.[0];
  143. const queryChanges = {
  144. mri: value,
  145. op: selectedOp,
  146. groupBy: undefined,
  147. };
  148. trackAnalytics('ddm.widget.metric', {organization});
  149. incrementQueryMetric('ddm.widget.metric', queryChanges);
  150. onChange(queryChanges);
  151. },
  152. [incrementQueryMetric, meta, metricsQuery.op, onChange, organization]
  153. );
  154. const handleOpChange = useCallback(
  155. ({value}) => {
  156. trackAnalytics('ddm.widget.operation', {organization});
  157. incrementQueryMetric('ddm.widget.operation', {op: value});
  158. onChange({
  159. op: value,
  160. });
  161. },
  162. [incrementQueryMetric, onChange, organization]
  163. );
  164. const handleGroupByChange = useCallback(
  165. (options: SelectOption<string>[]) => {
  166. trackAnalytics('ddm.widget.group', {organization});
  167. incrementQueryMetric('ddm.widget.group', {
  168. groupBy: options.map(o => o.value),
  169. });
  170. onChange({
  171. groupBy: options.map(o => o.value),
  172. });
  173. },
  174. [incrementQueryMetric, onChange, organization]
  175. );
  176. const handleQueryChange = useCallback(
  177. (query: string) => {
  178. trackAnalytics('ddm.widget.filter', {organization});
  179. incrementQueryMetric('ddm.widget.filter', {query});
  180. onChange({
  181. query,
  182. });
  183. },
  184. [incrementQueryMetric, onChange, organization]
  185. );
  186. const handleOpenMetricsMenu = useCallback(
  187. (isOpen: boolean) => {
  188. if (isOpen && !isMetaLoading && !isMetaRefetching) {
  189. refetchMeta();
  190. }
  191. },
  192. [isMetaLoading, isMetaRefetching, refetchMeta]
  193. );
  194. const mriOptions = useMemo(
  195. () =>
  196. displayedMetrics.map<ComboBoxOption<MRI>>(metric => ({
  197. label: mriMode
  198. ? metric.mri
  199. : middleEllipsis(formatMRI(metric.mri) ?? '', 55, /\.|-|_/),
  200. // enable search by mri, name, unit (millisecond), type (c:), and readable type (counter)
  201. textValue: `${metric.mri}${getReadableMetricType(metric.type)}`,
  202. value: metric.mri,
  203. details:
  204. metric.projectIds.length > 0 ? (
  205. <MetricListItemDetails metric={metric} selectedProjects={selectedProjects} />
  206. ) : null,
  207. showDetailsInOverlay: true,
  208. trailingItems:
  209. mriMode || parseMRI(metric.mri)?.useCase !== 'custom' ? undefined : (
  210. <CustomMetricInfoText>{t('Custom')}</CustomMetricInfoText>
  211. ),
  212. })),
  213. [displayedMetrics, mriMode, selectedProjects]
  214. );
  215. const projectIdStrings = useMemo(() => projectIds.map(String), [projectIds]);
  216. return (
  217. <QueryBuilderWrapper>
  218. <FlexBlock>
  219. {shouldUseComboBox ? (
  220. <MetricComboBox
  221. aria-label={t('Metric')}
  222. placeholder={t('Select a metric')}
  223. loadingMessage={t('Loading metrics...')}
  224. sizeLimit={100}
  225. size="md"
  226. menuSize="sm"
  227. isLoading={isMetaLoading}
  228. onOpenChange={handleOpenMetricsMenu}
  229. options={mriOptions}
  230. value={metricsQuery.mri}
  231. onChange={handleMRIChange}
  232. growingInput
  233. menuWidth="400px"
  234. />
  235. ) : (
  236. <MetricSelect
  237. searchable
  238. sizeLimit={100}
  239. size="md"
  240. triggerLabel={middleEllipsis(
  241. formatMRI(metricsQuery.mri) ?? '',
  242. breakpoints.large ? (breakpoints.xlarge ? 70 : 45) : 30,
  243. /\.|-|_/
  244. )}
  245. options={mriOptions}
  246. value={metricsQuery.mri}
  247. onChange={handleMRIChange}
  248. />
  249. )}
  250. <FlexBlock>
  251. <OpSelect
  252. size="md"
  253. triggerProps={{prefix: t('Agg')}}
  254. options={
  255. selectedMeta?.operations.filter(isAllowedOp).map(op => ({
  256. label: op,
  257. value: op,
  258. })) ?? []
  259. }
  260. triggerLabel={metricsQuery.op}
  261. disabled={!selectedMeta}
  262. value={metricsQuery.op}
  263. onChange={handleOpChange}
  264. />
  265. <CompactSelect
  266. multiple
  267. size="md"
  268. triggerProps={{prefix: t('Group by')}}
  269. options={groupByOptions.map(tag => ({
  270. label: tag.key,
  271. value: tag.key,
  272. trailingItems: tag.trailingItems ?? (
  273. <Fragment>
  274. {tag.key === 'release' && <IconReleases size="xs" />}
  275. {tag.key === 'transaction' && <IconLightning size="xs" />}
  276. </Fragment>
  277. ),
  278. }))}
  279. disabled={!metricsQuery.mri || tagsIsLoading}
  280. value={metricsQuery.groupBy}
  281. onChange={handleGroupByChange}
  282. />
  283. </FlexBlock>
  284. </FlexBlock>
  285. <SearchBarWrapper>
  286. <MetricSearchBar
  287. mri={metricsQuery.mri}
  288. disabled={!metricsQuery.mri}
  289. onChange={handleQueryChange}
  290. query={metricsQuery.query}
  291. projectIds={projectIdStrings}
  292. blockedTags={selectedMeta?.blockingStatus?.flatMap(s => s.blockedTags) ?? []}
  293. />
  294. </SearchBarWrapper>
  295. </QueryBuilderWrapper>
  296. );
  297. });
  298. function TagWarningIcon() {
  299. return (
  300. <TooltipIconWrapper>
  301. <Tooltip
  302. title={t('This tag appears in filter conditions, some groups may be omitted.')}
  303. >
  304. <IconWarning size="xs" color="warning" />
  305. </Tooltip>
  306. </TooltipIconWrapper>
  307. );
  308. }
  309. const TooltipIconWrapper = styled('span')`
  310. margin-top: ${space(0.25)};
  311. `;
  312. const CustomMetricInfoText = styled('span')`
  313. color: ${p => p.theme.subText};
  314. `;
  315. const QueryBuilderWrapper = styled('div')`
  316. display: flex;
  317. flex-grow: 1;
  318. gap: ${space(1)};
  319. flex-wrap: wrap;
  320. `;
  321. const FlexBlock = styled('div')`
  322. display: flex;
  323. gap: ${space(1)};
  324. flex-wrap: wrap;
  325. `;
  326. const MetricComboBox = styled(ComboBox)`
  327. min-width: 200px;
  328. max-width: min(500px, 100%);
  329. `;
  330. const MetricSelect = styled(CompactSelect)`
  331. min-width: 200px;
  332. & > button {
  333. width: 100%;
  334. }
  335. `;
  336. const OpSelect = styled(CompactSelect)`
  337. width: 128px;
  338. min-width: min-content;
  339. & > button {
  340. width: 100%;
  341. }
  342. `;
  343. const SearchBarWrapper = styled('div')`
  344. flex: 1;
  345. min-width: 200px;
  346. `;