queryBuilder.tsx 11 KB

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