insightsMetricField.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import {Fragment, useCallback, useEffect, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import Tag from 'sentry/components/badge/tag';
  4. import SelectControl from 'sentry/components/forms/controls/selectControl';
  5. import {t} from 'sentry/locale';
  6. import {space} from 'sentry/styles/space';
  7. import type {MetricAggregation, MetricMeta, ParsedMRI} from 'sentry/types/metrics';
  8. import type {Project} from 'sentry/types/project';
  9. import {parseFunction} from 'sentry/utils/discover/fields';
  10. import {getDefaultAggregation} from 'sentry/utils/metrics';
  11. import {getReadableMetricType} from 'sentry/utils/metrics/formatters';
  12. import {
  13. DEFAULT_INSIGHTS_METRICS_ALERT_FIELD,
  14. DEFAULT_INSIGHTS_MRI,
  15. formatMRI,
  16. isMRI,
  17. MRIToField,
  18. parseMRI,
  19. } from 'sentry/utils/metrics/mri';
  20. import {useVirtualizedMetricsMeta} from 'sentry/utils/metrics/useMetricsMeta';
  21. import {middleEllipsis} from 'sentry/utils/string/middleEllipsis';
  22. import {
  23. INSIGHTS_METRICS,
  24. INSIGHTS_METRICS_OPERATIONS,
  25. INSIGHTS_METRICS_OPERATIONS_WITH_CUSTOM_ARGS,
  26. INSIGHTS_METRICS_OPERATIONS_WITHOUT_ARGS,
  27. } from 'sentry/views/alerts/rules/metric/utils/isInsightsMetricAlert';
  28. interface Props {
  29. aggregate: string;
  30. onChange: (value: string, meta: Record<string, any>) => void;
  31. project: Project;
  32. }
  33. // We actually only store a few aggregations for Insights metrics.
  34. // The `metrics/meta/` endpoint doesn't know this, so hardcode supported aggregations for now.
  35. const OPERATIONS = [
  36. {
  37. label: 'avg',
  38. value: 'avg',
  39. },
  40. {
  41. label: 'sum',
  42. value: 'sum',
  43. },
  44. {
  45. label: 'min',
  46. value: 'min',
  47. },
  48. {
  49. label: 'max',
  50. value: 'max',
  51. },
  52. ...INSIGHTS_METRICS_OPERATIONS.map(({label, value}) => ({label, value})),
  53. ];
  54. function aggregateRequiresArgs(aggregation?: string) {
  55. return !INSIGHTS_METRICS_OPERATIONS_WITHOUT_ARGS.some(
  56. ({value}) => value === aggregation
  57. );
  58. }
  59. function aggregateHasCustomArgs(aggregation?: string) {
  60. return INSIGHTS_METRICS_OPERATIONS_WITH_CUSTOM_ARGS.some(
  61. ({value}) => value === aggregation
  62. );
  63. }
  64. function InsightsMetricField({aggregate, project, onChange}: Props) {
  65. const {data: meta, isLoading} = useVirtualizedMetricsMeta(
  66. {projects: [parseInt(project.id, 10)]},
  67. ['spans']
  68. );
  69. const metaArr = useMemo(() => {
  70. return meta
  71. .map(
  72. metric =>
  73. ({
  74. ...metric,
  75. ...parseMRI(metric.mri),
  76. }) as ParsedMRI & MetricMeta
  77. )
  78. .filter(metric => INSIGHTS_METRICS.includes(metric.mri));
  79. }, [meta]);
  80. // We parse out the aggregation and field from the aggregate string.
  81. // This only works for aggregates with <= 1 argument.
  82. const {
  83. name: aggregation,
  84. arguments: [field],
  85. } = parseFunction(aggregate) ?? {arguments: [undefined]};
  86. const selectedMriMeta = useMemo(() => {
  87. return meta.find(metric => metric.mri === field);
  88. }, [meta, field]);
  89. useEffect(() => {
  90. if (!aggregateRequiresArgs(aggregation)) {
  91. return;
  92. }
  93. if (aggregation && aggregateHasCustomArgs(aggregation)) {
  94. const options = INSIGHTS_METRICS_OPERATIONS_WITH_CUSTOM_ARGS.find(
  95. ({value}) => value === aggregation
  96. )?.options;
  97. if (options && !options.some(({value}) => value === field)) {
  98. onChange(`${aggregation}(${options?.[0].value})`, {});
  99. }
  100. return;
  101. }
  102. if (field && !selectedMriMeta && !isLoading) {
  103. const newSelection = metaArr[0];
  104. if (newSelection) {
  105. onChange(MRIToField(newSelection.mri, 'avg'), {});
  106. } else if (aggregate !== DEFAULT_INSIGHTS_METRICS_ALERT_FIELD) {
  107. onChange(DEFAULT_INSIGHTS_METRICS_ALERT_FIELD, {});
  108. }
  109. }
  110. }, [metaArr, onChange, isLoading, aggregate, selectedMriMeta, aggregation, field]);
  111. const handleMriChange = useCallback(
  112. option => {
  113. const selectedMeta = meta.find(metric => metric.mri === option.value);
  114. if (!selectedMeta) {
  115. return;
  116. }
  117. const newType = parseMRI(option.value)?.type;
  118. // If the type is the same, we can keep the current aggregate
  119. if (newType === selectedMeta.type && aggregation) {
  120. onChange(MRIToField(option.value, aggregation as MetricAggregation), {});
  121. } else {
  122. onChange(MRIToField(option.value, getDefaultAggregation(option.value)), {});
  123. }
  124. },
  125. [meta, onChange, aggregation]
  126. );
  127. const handleOptionChange = useCallback(
  128. option => {
  129. if (!option || !aggregation) {
  130. return;
  131. }
  132. onChange(`${aggregation}(${option.value})`, {});
  133. },
  134. [onChange, aggregation]
  135. );
  136. // As SelectControl does not support an options size limit out of the box
  137. // we work around it by using the async variant of the control
  138. const getMriOptions = useCallback(
  139. (searchText: string) => {
  140. const filteredMeta = metaArr.filter(
  141. ({name}) =>
  142. searchText === '' || name.toLowerCase().includes(searchText.toLowerCase())
  143. );
  144. const options = filteredMeta.splice(0, 100).map<{
  145. label: React.ReactNode;
  146. value: string;
  147. disabled?: boolean;
  148. trailingItems?: React.ReactNode;
  149. }>(metric => ({
  150. label: middleEllipsis(metric.name, 50, /\.|-|_/),
  151. value: metric.mri,
  152. trailingItems: (
  153. <Fragment>
  154. <Tag tooltipText={t('Type')}>{getReadableMetricType(metric.type)}</Tag>
  155. <Tag tooltipText={t('Unit')}>{metric.unit}</Tag>
  156. </Fragment>
  157. ),
  158. }));
  159. if (filteredMeta.length > options.length) {
  160. options.push({
  161. label: (
  162. <SizeLimitMessage>{t('Use search to find more options…')}</SizeLimitMessage>
  163. ),
  164. value: '',
  165. disabled: true,
  166. });
  167. }
  168. return options;
  169. },
  170. [metaArr]
  171. );
  172. // When using the async variant of SelectControl, we need to pass in an option object instead of just the value
  173. const selectedOption = field && {
  174. label: isMRI(field) ? formatMRI(field) : field,
  175. value: field,
  176. };
  177. return (
  178. <Wrapper>
  179. <StyledSelectControl
  180. searchable
  181. isDisabled={isLoading}
  182. placeholder={t('Select an operation')}
  183. options={OPERATIONS}
  184. value={aggregation}
  185. onChange={option => {
  186. if (!aggregateRequiresArgs(option.value)) {
  187. onChange(`${option.value}()`, {});
  188. } else if (aggregateHasCustomArgs(option.value)) {
  189. const options = INSIGHTS_METRICS_OPERATIONS_WITH_CUSTOM_ARGS.find(
  190. ({value}) => value === option.value
  191. )?.options;
  192. onChange(`${option.value}(${options?.[0].value})`, {});
  193. } else if (field && isMRI(field)) {
  194. onChange(MRIToField(field, option.value), {});
  195. } else {
  196. onChange(MRIToField(DEFAULT_INSIGHTS_MRI, option.value), {});
  197. }
  198. }}
  199. />
  200. {aggregateRequiresArgs(aggregation) &&
  201. (aggregateHasCustomArgs(aggregation) ? (
  202. <StyledSelectControl
  203. searchable
  204. placeholder={t('Select an option')}
  205. options={
  206. INSIGHTS_METRICS_OPERATIONS_WITH_CUSTOM_ARGS.find(
  207. ({value}) => value === aggregation
  208. )?.options
  209. }
  210. value={selectedOption}
  211. onChange={handleOptionChange}
  212. />
  213. ) : (
  214. <StyledSelectControl
  215. searchable
  216. isDisabled={isLoading}
  217. placeholder={t('Select a metric')}
  218. noOptionsMessage={() =>
  219. metaArr.length === 0 ? t('No metrics in this project') : t('No options')
  220. }
  221. async
  222. defaultOptions={getMriOptions('')}
  223. loadOptions={searchText => Promise.resolve(getMriOptions(searchText))}
  224. filterOption={() => true}
  225. value={selectedOption}
  226. onChange={handleMriChange}
  227. />
  228. ))}
  229. </Wrapper>
  230. );
  231. }
  232. export default InsightsMetricField;
  233. const Wrapper = styled('div')`
  234. display: flex;
  235. gap: ${space(1)};
  236. `;
  237. const StyledSelectControl = styled(SelectControl)`
  238. width: 200px;
  239. `;
  240. const SizeLimitMessage = styled('span')`
  241. font-size: ${p => p.theme.fontSizeSmall};
  242. display: block;
  243. width: 100%;
  244. text-align: center;
  245. `;