queryBuilder.tsx 12 KB

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