queryBuilder.tsx 11 KB

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