queryBuilder.tsx 11 KB

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