queryBuilder.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import {Fragment, 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 {IconLightning, IconReleases, 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. label: mriMode
  203. ? metric.mri
  204. : middleEllipsis(formatMRI(metric.mri) ?? '', 46, /\.|-|_/),
  205. textValue: mriMode
  206. ? // enable search by mri, name, unit (millisecond), type (c:), and readable type (counter)
  207. `${metric.mri}${getReadableMetricType(metric.type)}`
  208. : // enable search in the full formatted string
  209. formatMRI(metric.mri),
  210. value: metric.mri,
  211. details:
  212. metric.projectIds.length > 0 ? (
  213. <MetricListItemDetails
  214. metric={metric}
  215. selectedProjects={selectedProjects}
  216. onTagClick={(mri, tag) => {
  217. onChange({mri, groupBy: [tag]});
  218. }}
  219. />
  220. ) : null,
  221. showDetailsInOverlay: true,
  222. trailingItems:
  223. mriMode || parseMRI(metric.mri)?.useCase !== 'custom' ? undefined : (
  224. <CustomMetricInfoText>{t('Custom')}</CustomMetricInfoText>
  225. ),
  226. })),
  227. [displayedMetrics, mriMode, onChange, selectedProjects]
  228. );
  229. const projectIdStrings = useMemo(() => projectIds.map(String), [projectIds]);
  230. return (
  231. <QueryBuilderWrapper>
  232. <FlexBlock>
  233. <GuideAnchor target="metrics_selector" position="bottom" disabled={index !== 0}>
  234. <MetricComboBox
  235. aria-label={t('Metric')}
  236. placeholder={t('Select a metric')}
  237. loadingMessage={t('Loading metrics...')}
  238. sizeLimit={100}
  239. size="md"
  240. menuSize="sm"
  241. isLoading={isMetaLoading}
  242. onOpenChange={handleOpenMetricsMenu}
  243. options={mriOptions}
  244. value={metricsQuery.mri}
  245. onChange={handleMRIChange}
  246. growingInput
  247. menuWidth="450px"
  248. />
  249. </GuideAnchor>
  250. <FlexBlock>
  251. <GuideAnchor
  252. target="metrics_aggregate"
  253. position="bottom"
  254. disabled={index !== 0}
  255. >
  256. <OpSelect
  257. size="md"
  258. triggerProps={{prefix: t('Agg')}}
  259. options={
  260. selectedMeta?.operations.filter(isAllowedOp).map(op => ({
  261. label: op,
  262. value: op,
  263. })) ?? []
  264. }
  265. triggerLabel={metricsQuery.op}
  266. disabled={!selectedMeta}
  267. value={metricsQuery.op}
  268. onChange={handleOpChange}
  269. />
  270. </GuideAnchor>
  271. <GuideAnchor target="metrics_groupby" position="bottom" disabled={index !== 0}>
  272. <CompactSelect
  273. multiple
  274. size="md"
  275. triggerProps={{prefix: t('Group by')}}
  276. options={groupByOptions.map(tag => ({
  277. label: tag.key,
  278. value: tag.key,
  279. trailingItems: tag.trailingItems ?? (
  280. <Fragment>
  281. {tag.key === 'release' && <IconReleases size="xs" />}
  282. {tag.key === 'transaction' && <IconLightning size="xs" />}
  283. </Fragment>
  284. ),
  285. }))}
  286. disabled={!metricsQuery.mri || tagsIsLoading}
  287. value={metricsQuery.groupBy}
  288. onChange={handleGroupByChange}
  289. />
  290. </GuideAnchor>
  291. </FlexBlock>
  292. </FlexBlock>
  293. <SearchBarWrapper>
  294. <MetricSearchBar
  295. mri={metricsQuery.mri}
  296. disabled={!metricsQuery.mri}
  297. onChange={handleQueryChange}
  298. query={metricsQuery.query}
  299. projectIds={projectIdStrings}
  300. blockedTags={selectedMeta?.blockingStatus?.flatMap(s => s.blockedTags) ?? []}
  301. />
  302. </SearchBarWrapper>
  303. </QueryBuilderWrapper>
  304. );
  305. });
  306. function TagWarningIcon() {
  307. return (
  308. <TooltipIconWrapper>
  309. <Tooltip
  310. title={t('This tag appears in filter conditions, some groups may be omitted.')}
  311. >
  312. <IconWarning size="xs" color="warning" />
  313. </Tooltip>
  314. </TooltipIconWrapper>
  315. );
  316. }
  317. const TooltipIconWrapper = styled('span')`
  318. margin-top: ${space(0.25)};
  319. `;
  320. const CustomMetricInfoText = styled('span')`
  321. color: ${p => p.theme.subText};
  322. `;
  323. const QueryBuilderWrapper = styled('div')`
  324. display: flex;
  325. flex-grow: 1;
  326. gap: ${space(1)};
  327. flex-wrap: wrap;
  328. `;
  329. const FlexBlock = styled('div')`
  330. display: flex;
  331. gap: ${space(1)};
  332. flex-wrap: wrap;
  333. `;
  334. const MetricComboBox = styled(ComboBox)`
  335. min-width: 200px;
  336. max-width: min(500px, 100%);
  337. `;
  338. const OpSelect = styled(CompactSelect)`
  339. /* makes selects from different have the same width which is enough to fit all agg options except "count_unique" */
  340. min-width: 128px;
  341. & > button {
  342. width: 100%;
  343. }
  344. `;
  345. const SearchBarWrapper = styled('div')`
  346. flex: 1;
  347. min-width: 200px;
  348. `;