123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393 |
- import {memo, useCallback, useEffect, useMemo, useState} from 'react';
- import styled from '@emotion/styled';
- import uniqBy from 'lodash/uniqBy';
- import GuideAnchor from 'sentry/components/assistant/guideAnchor';
- import {ComboBox} from 'sentry/components/comboBox';
- import type {ComboBoxOption} from 'sentry/components/comboBox/types';
- import type {SelectOption} from 'sentry/components/compactSelect';
- import {CompactSelect} from 'sentry/components/compactSelect';
- import {Tooltip} from 'sentry/components/tooltip';
- import {IconWarning} from 'sentry/icons';
- import {t} from 'sentry/locale';
- import {space} from 'sentry/styles/space';
- import type {MetricMeta, MRI} from 'sentry/types/metrics';
- import {trackAnalytics} from 'sentry/utils/analytics';
- import {
- getDefaultAggregate,
- isAllowedOp,
- isCustomMetric,
- isSpanDuration,
- isSpanMeasurement,
- isTransactionDuration,
- isTransactionMeasurement,
- } from 'sentry/utils/metrics';
- import {getReadableMetricType} from 'sentry/utils/metrics/formatters';
- import {formatMRI, parseMRI} from 'sentry/utils/metrics/mri';
- import type {MetricsQuery} from 'sentry/utils/metrics/types';
- import {useIncrementQueryMetric} from 'sentry/utils/metrics/useIncrementQueryMetric';
- import {useMetricsMeta} from 'sentry/utils/metrics/useMetricsMeta';
- import {useMetricsTags} from 'sentry/utils/metrics/useMetricsTags';
- import {middleEllipsis} from 'sentry/utils/middleEllipsis';
- import useKeyPress from 'sentry/utils/useKeyPress';
- import useOrganization from 'sentry/utils/useOrganization';
- import usePageFilters from 'sentry/utils/usePageFilters';
- import useProjects from 'sentry/utils/useProjects';
- import {MetricListItemDetails} from 'sentry/views/metrics/metricListItemDetails';
- import {MetricSearchBar} from 'sentry/views/metrics/metricSearchBar';
- type QueryBuilderProps = {
- index: number;
- metricsQuery: MetricsQuery;
- onChange: (data: Partial<MetricsQuery>) => void;
- projects: number[];
- };
- const isVisibleTransactionMetric = (metric: MetricMeta) =>
- isTransactionDuration(metric) || isTransactionMeasurement(metric);
- const isVisibleSpanMetric = (metric: MetricMeta) =>
- isSpanDuration(metric) || isSpanMeasurement(metric);
- const isShownByDefault = (metric: MetricMeta) =>
- isCustomMetric(metric) ||
- isVisibleTransactionMetric(metric) ||
- isVisibleSpanMetric(metric);
- function useMriMode() {
- const [mriMode, setMriMode] = useState(false);
- const mriModeKeyPressed = useKeyPress('`', undefined, true);
- useEffect(() => {
- if (mriModeKeyPressed) {
- setMriMode(value => !value);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [mriModeKeyPressed]);
- return mriMode;
- }
- export const QueryBuilder = memo(function QueryBuilder({
- metricsQuery,
- projects: projectIds,
- onChange,
- index,
- }: QueryBuilderProps) {
- const organization = useOrganization();
- const pageFilters = usePageFilters();
- const {projects} = useProjects();
- const {
- data: meta,
- isLoading: isMetaLoading,
- isRefetching: isMetaRefetching,
- refetch: refetchMeta,
- } = useMetricsMeta(pageFilters.selection);
- const mriMode = useMriMode();
- const {data: tagsData = [], isLoading: tagsIsLoading} = useMetricsTags(
- metricsQuery.mri,
- {
- projects: projectIds,
- }
- );
- const selectedProjects = useMemo(
- () =>
- projects.filter(project =>
- projectIds[0] === -1
- ? true
- : projectIds.length === 0
- ? project.isMember
- : projectIds.includes(parseInt(project.id, 10))
- ),
- [projectIds, projects]
- );
- const groupByOptions = useMemo(() => {
- return uniqBy(tagsData, 'key').map(tag => ({
- key: tag.key,
- // So that we don't have to parse the query to determine if the tag is used
- trailingItems: metricsQuery.query?.includes(`${tag.key}:`) ? (
- <TagWarningIcon />
- ) : undefined,
- }));
- }, [tagsData, metricsQuery.query]);
- const displayedMetrics = useMemo(() => {
- const isSelected = (metric: MetricMeta) => metric.mri === metricsQuery.mri;
- const result = meta
- .filter(metric => isShownByDefault(metric) || isSelected(metric))
- .sort(metric => (isSelected(metric) ? -1 : 1));
- // Add the selected metric to the top of the list if it's not already there
- if (result[0]?.mri !== metricsQuery.mri) {
- const parsedMri = parseMRI(metricsQuery.mri)!;
- return [
- {
- mri: metricsQuery.mri,
- type: parsedMri.type,
- unit: parsedMri.unit,
- operations: [],
- projectIds: [],
- blockingStatus: [],
- } satisfies MetricMeta,
- ...result,
- ];
- }
- return result;
- }, [meta, metricsQuery.mri]);
- const selectedMeta = useMemo(() => {
- return meta.find(metric => metric.mri === metricsQuery.mri);
- }, [meta, metricsQuery.mri]);
- const incrementQueryMetric = useIncrementQueryMetric({
- ...metricsQuery,
- });
- const handleMRIChange = useCallback(
- ({value}) => {
- const currentMRI = parseMRI(metricsQuery.mri);
- const newMRI = parseMRI(value);
- if (!currentMRI || !newMRI) {
- return;
- }
- let queryChanges = {};
- // If the type is the same, we can keep the current aggregate
- if (currentMRI.type === newMRI.type) {
- queryChanges = {
- mri: value,
- groupBy: undefined,
- };
- } else {
- queryChanges = {
- mri: value,
- op: getDefaultAggregate(value),
- groupBy: undefined,
- };
- }
- trackAnalytics('ddm.widget.metric', {organization});
- incrementQueryMetric('ddm.widget.metric', queryChanges);
- onChange(queryChanges);
- },
- [incrementQueryMetric, metricsQuery.mri, onChange, organization]
- );
- const handleOpChange = useCallback(
- ({value}) => {
- trackAnalytics('ddm.widget.operation', {organization});
- incrementQueryMetric('ddm.widget.operation', {op: value});
- onChange({
- op: value,
- });
- },
- [incrementQueryMetric, onChange, organization]
- );
- const handleGroupByChange = useCallback(
- (options: SelectOption<string>[]) => {
- trackAnalytics('ddm.widget.group', {organization});
- incrementQueryMetric('ddm.widget.group', {
- groupBy: options.map(o => o.value),
- });
- onChange({
- groupBy: options.map(o => o.value),
- });
- },
- [incrementQueryMetric, onChange, organization]
- );
- const handleQueryChange = useCallback(
- (query: string) => {
- trackAnalytics('ddm.widget.filter', {organization});
- incrementQueryMetric('ddm.widget.filter', {query});
- onChange({
- query,
- });
- },
- [incrementQueryMetric, onChange, organization]
- );
- const handleOpenMetricsMenu = useCallback(
- (isOpen: boolean) => {
- if (isOpen && !isMetaLoading && !isMetaRefetching) {
- refetchMeta();
- }
- },
- [isMetaLoading, isMetaRefetching, refetchMeta]
- );
- const mriOptions = useMemo(
- () =>
- displayedMetrics.map<ComboBoxOption<MRI>>(metric => {
- const isDuplicateWithDifferentUnit = displayedMetrics.some(
- displayedMetric =>
- metric.mri !== displayedMetric.mri &&
- parseMRI(metric.mri)?.name === parseMRI(displayedMetric.mri)?.name
- );
- const trailingItems: React.ReactNode[] = [];
- if (isDuplicateWithDifferentUnit) {
- trailingItems.push(<IconWarning size="xs" color="yellow400" />);
- }
- if (parseMRI(metric.mri)?.useCase === 'custom' && !mriMode) {
- trailingItems.push(<CustomMetricInfoText>{t('Custom')}</CustomMetricInfoText>);
- }
- return {
- label: mriMode
- ? metric.mri
- : middleEllipsis(formatMRI(metric.mri) ?? '', 46, /\.|-|_/),
- textValue: mriMode
- ? // enable search by mri, name, unit (millisecond), type (c:), and readable type (counter)
- `${metric.mri}${getReadableMetricType(metric.type)}`
- : // enable search in the full formatted string
- formatMRI(metric.mri),
- value: metric.mri,
- details:
- metric.projectIds.length > 0 ? (
- <MetricListItemDetails
- metric={metric}
- selectedProjects={selectedProjects}
- onTagClick={(mri, tag) => {
- onChange({mri, groupBy: [tag]});
- }}
- isDuplicateWithDifferentUnit={isDuplicateWithDifferentUnit}
- />
- ) : null,
- showDetailsInOverlay: true,
- trailingItems,
- };
- }),
- [displayedMetrics, mriMode, onChange, selectedProjects]
- );
- const projectIdStrings = useMemo(() => projectIds.map(String), [projectIds]);
- return (
- <QueryBuilderWrapper>
- <FlexBlock>
- <GuideAnchor target="metrics_selector" position="bottom" disabled={index !== 0}>
- <MetricComboBox
- aria-label={t('Metric')}
- placeholder={t('Select a metric')}
- loadingMessage={t('Loading metrics...')}
- sizeLimit={100}
- size="md"
- menuSize="sm"
- isLoading={isMetaLoading}
- onOpenChange={handleOpenMetricsMenu}
- options={mriOptions}
- value={metricsQuery.mri}
- onChange={handleMRIChange}
- growingInput
- menuWidth="450px"
- />
- </GuideAnchor>
- <FlexBlock>
- <GuideAnchor
- target="metrics_aggregate"
- position="bottom"
- disabled={index !== 0}
- >
- <OpSelect
- size="md"
- triggerProps={{prefix: t('Agg')}}
- options={
- selectedMeta?.operations.filter(isAllowedOp).map(op => ({
- label: op,
- value: op,
- })) ?? []
- }
- triggerLabel={metricsQuery.op}
- disabled={!selectedMeta}
- value={metricsQuery.op}
- onChange={handleOpChange}
- />
- </GuideAnchor>
- <GuideAnchor target="metrics_groupby" position="bottom" disabled={index !== 0}>
- <CompactSelect
- multiple
- size="md"
- triggerProps={{prefix: t('Group by')}}
- options={groupByOptions.map(tag => ({
- label: tag.key,
- value: tag.key,
- }))}
- disabled={!metricsQuery.mri || tagsIsLoading}
- value={metricsQuery.groupBy}
- onChange={handleGroupByChange}
- />
- </GuideAnchor>
- </FlexBlock>
- </FlexBlock>
- <SearchBarWrapper>
- <MetricSearchBar
- mri={metricsQuery.mri}
- disabled={!metricsQuery.mri}
- onChange={handleQueryChange}
- query={metricsQuery.query}
- projectIds={projectIdStrings}
- blockedTags={selectedMeta?.blockingStatus?.flatMap(s => s.blockedTags) ?? []}
- />
- </SearchBarWrapper>
- </QueryBuilderWrapper>
- );
- });
- function TagWarningIcon() {
- return (
- <TooltipIconWrapper>
- <Tooltip
- title={t('This tag appears in filter conditions, some groups may be omitted.')}
- >
- <IconWarning size="xs" color="warning" />
- </Tooltip>
- </TooltipIconWrapper>
- );
- }
- const TooltipIconWrapper = styled('span')`
- margin-top: ${space(0.25)};
- `;
- const CustomMetricInfoText = styled('span')`
- color: ${p => p.theme.subText};
- `;
- const QueryBuilderWrapper = styled('div')`
- display: flex;
- flex-grow: 1;
- gap: ${space(1)};
- flex-wrap: wrap;
- `;
- const FlexBlock = styled('div')`
- display: flex;
- gap: ${space(1)};
- flex-wrap: wrap;
- `;
- const MetricComboBox = styled(ComboBox)`
- min-width: 200px;
- max-width: min(500px, 100%);
- `;
- const OpSelect = styled(CompactSelect)`
- /* makes selects from different have the same width which is enough to fit all agg options except "count_unique" */
- min-width: 128px;
- & > button {
- width: 100%;
- }
- `;
- const SearchBarWrapper = styled('div')`
- flex: 1;
- min-width: 200px;
- `;
|