metricsExtractionRuleForm.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import {Fragment, useCallback, useId, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {Button} from 'sentry/components/button';
  4. import SearchBar from 'sentry/components/events/searchBar';
  5. import SelectField from 'sentry/components/forms/fields/selectField';
  6. import Form, {type FormProps} from 'sentry/components/forms/form';
  7. import FormField from 'sentry/components/forms/formField';
  8. import type FormModel from 'sentry/components/forms/model';
  9. import ExternalLink from 'sentry/components/links/externalLink';
  10. import {Tooltip} from 'sentry/components/tooltip';
  11. import {IconAdd, IconClose, IconWarning} from 'sentry/icons';
  12. import {t, tct} from 'sentry/locale';
  13. import {space} from 'sentry/styles/space';
  14. import type {MetricAggregation, MetricsExtractionCondition} from 'sentry/types/metrics';
  15. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  16. import {DEFAULT_METRICS_CARDINALITY_LIMIT} from 'sentry/utils/metrics/constants';
  17. import useOrganization from 'sentry/utils/useOrganization';
  18. import {SpanIndexedField} from 'sentry/views/insights/types';
  19. import {useSpanFieldSupportedTags} from 'sentry/views/performance/utils/useSpanFieldSupportedTags';
  20. import {useMetricsExtractionRules} from 'sentry/views/settings/projectMetrics/utils/useMetricsExtractionRules';
  21. export type AggregateGroup = 'count' | 'count_unique' | 'min_max' | 'percentiles';
  22. export interface FormData {
  23. aggregates: AggregateGroup[];
  24. conditions: MetricsExtractionCondition[];
  25. spanAttribute: string | null;
  26. tags: string[];
  27. }
  28. interface Props extends Omit<FormProps, 'onSubmit'> {
  29. initialData: FormData;
  30. projectId: string | number;
  31. cardinality?: Record<string, number>;
  32. isEdit?: boolean;
  33. onSubmit?: (
  34. data: FormData,
  35. onSubmitSuccess: (data: FormData) => void,
  36. onSubmitError: (error: any) => void,
  37. event: React.FormEvent,
  38. model: FormModel
  39. ) => void;
  40. }
  41. const HIGH_CARDINALITY_TAGS = new Set([
  42. SpanIndexedField.SPAN_DURATION,
  43. SpanIndexedField.SPAN_SELF_TIME,
  44. SpanIndexedField.PROJECT_ID,
  45. SpanIndexedField.INP,
  46. SpanIndexedField.INP_SCORE,
  47. SpanIndexedField.INP_SCORE_WEIGHT,
  48. SpanIndexedField.TOTAL_SCORE,
  49. SpanIndexedField.CACHE_ITEM_SIZE,
  50. SpanIndexedField.MESSAGING_MESSAGE_BODY_SIZE,
  51. SpanIndexedField.MESSAGING_MESSAGE_RECEIVE_LATENCY,
  52. SpanIndexedField.MESSAGING_MESSAGE_RETRY_COUNT,
  53. SpanIndexedField.TRANSACTION_ID,
  54. SpanIndexedField.ID,
  55. ]);
  56. const AGGREGATE_OPTIONS: {label: string; value: AggregateGroup}[] = [
  57. {
  58. label: t('count'),
  59. value: 'count',
  60. },
  61. {
  62. label: t('count_unique'),
  63. value: 'count_unique',
  64. },
  65. {
  66. label: t('min, max, sum, avg'),
  67. value: 'min_max',
  68. },
  69. {
  70. label: t('percentiles'),
  71. value: 'percentiles',
  72. },
  73. ];
  74. export function explodeAggregateGroup(group: AggregateGroup): MetricAggregation[] {
  75. switch (group) {
  76. case 'count':
  77. return ['count'];
  78. case 'count_unique':
  79. return ['count_unique'];
  80. case 'min_max':
  81. return ['min', 'max', 'sum', 'avg'];
  82. case 'percentiles':
  83. return ['p50', 'p75', 'p95', 'p99'];
  84. default:
  85. throw new Error(`Unknown aggregate group: ${group}`);
  86. }
  87. }
  88. export function aggregatesToGroups(aggregates: MetricAggregation[]): AggregateGroup[] {
  89. const groups: AggregateGroup[] = [];
  90. if (aggregates.includes('count')) {
  91. groups.push('count');
  92. }
  93. if (aggregates.includes('count_unique')) {
  94. groups.push('count_unique');
  95. }
  96. const minMaxAggregates = new Set<MetricAggregation>(['min', 'max', 'sum', 'avg']);
  97. if (aggregates.find(aggregate => minMaxAggregates.has(aggregate))) {
  98. groups.push('min_max');
  99. }
  100. const percentileAggregates = new Set<MetricAggregation>(['p50', 'p75', 'p95', 'p99']);
  101. if (aggregates.find(aggregate => percentileAggregates.has(aggregate))) {
  102. groups.push('percentiles');
  103. }
  104. return groups;
  105. }
  106. let currentTempId = 0;
  107. function createTempId(): number {
  108. currentTempId -= 1;
  109. return currentTempId;
  110. }
  111. export function createCondition(): MetricsExtractionCondition {
  112. return {
  113. value: '',
  114. // id and mris will be set by the backend after creation
  115. id: createTempId(),
  116. mris: [],
  117. };
  118. }
  119. const EMPTY_SET = new Set<never>();
  120. const SPAN_SEARCH_CONFIG = {
  121. booleanKeys: EMPTY_SET,
  122. dateKeys: EMPTY_SET,
  123. durationKeys: EMPTY_SET,
  124. numericKeys: EMPTY_SET,
  125. percentageKeys: EMPTY_SET,
  126. sizeKeys: EMPTY_SET,
  127. textOperatorKeys: EMPTY_SET,
  128. disallowFreeText: true,
  129. disallowWildcard: true,
  130. disallowNegation: true,
  131. };
  132. export function MetricsExtractionRuleForm({
  133. isEdit,
  134. projectId,
  135. onSubmit,
  136. cardinality,
  137. ...props
  138. }: Props) {
  139. const organization = useOrganization();
  140. const [customAttributes, setCustomeAttributes] = useState<string[]>(() => {
  141. const {spanAttribute, tags} = props.initialData;
  142. return [...new Set(spanAttribute ? [...tags, spanAttribute] : tags)];
  143. });
  144. const {data: extractionRules} = useMetricsExtractionRules(organization.slug, projectId);
  145. const tags = useSpanFieldSupportedTags({projects: [Number(projectId)]});
  146. // TODO(aknaus): Make this nicer
  147. const supportedTags = useMemo(() => {
  148. const copy = {...tags};
  149. delete copy.has;
  150. return copy;
  151. }, [tags]);
  152. const allAttributeOptions = useMemo(() => {
  153. let keys = Object.keys(supportedTags);
  154. if (customAttributes.length) {
  155. keys = [...new Set(keys.concat(customAttributes))];
  156. }
  157. return keys.sort((a, b) => a.localeCompare(b));
  158. }, [customAttributes, supportedTags]);
  159. const attributeOptions = useMemo(() => {
  160. const disabledKeys = new Set(extractionRules?.map(rule => rule.spanAttribute) || []);
  161. return (
  162. allAttributeOptions
  163. .map(key => ({
  164. label: key,
  165. value: key,
  166. disabled: disabledKeys.has(key),
  167. tooltip: disabledKeys.has(key)
  168. ? t(
  169. 'This attribute is already in use. Please select another one or edit the existing metric.'
  170. )
  171. : undefined,
  172. tooltipOptions: {position: 'left'},
  173. }))
  174. // Sort disabled attributes to bottom
  175. .sort((a, b) => Number(a.disabled) - Number(b.disabled))
  176. );
  177. }, [allAttributeOptions, extractionRules]);
  178. const tagOptions = useMemo(() => {
  179. return allAttributeOptions
  180. .filter(
  181. // We don't want to suggest numeric fields as tags as they would explode cardinality
  182. option => !HIGH_CARDINALITY_TAGS.has(option as SpanIndexedField)
  183. )
  184. .map(option => ({
  185. label: option,
  186. value: option,
  187. }));
  188. }, [allAttributeOptions]);
  189. const handleSubmit = useCallback(
  190. (
  191. data: Record<string, any>,
  192. onSubmitSuccess: (data: Record<string, any>) => void,
  193. onSubmitError: (error: any) => void,
  194. event: React.FormEvent,
  195. model: FormModel
  196. ) => {
  197. const errors: Record<string, [string]> = {};
  198. if (!data.spanAttribute) {
  199. errors.spanAttribute = [t('Span attribute is required.')];
  200. }
  201. if (!data.aggregates.length) {
  202. errors.aggregates = [t('At least one aggregate is required.')];
  203. }
  204. if (Object.keys(errors).length) {
  205. onSubmitError({responseJSON: errors});
  206. return;
  207. }
  208. onSubmit?.(data as FormData, onSubmitSuccess, onSubmitError, event, model);
  209. },
  210. [onSubmit]
  211. );
  212. return (
  213. <Form onSubmit={onSubmit && handleSubmit} {...props}>
  214. {({model}) => (
  215. <Fragment>
  216. <SelectField
  217. name="spanAttribute"
  218. options={attributeOptions}
  219. disabled={isEdit}
  220. label={t('Measure')}
  221. help={tct(
  222. 'Define the span attribute you want to track. Learn how to instrument custom attributes in [link:our docs].',
  223. {
  224. // TODO(telemetry-experience): add the correct link here once we have it!!!
  225. link: (
  226. <ExternalLink href="https://docs.sentry.io/product/explore/metrics/" />
  227. ),
  228. }
  229. )}
  230. placeholder={t('Select a span attribute')}
  231. creatable
  232. formatCreateLabel={value => `Custom: "${value}"`}
  233. onCreateOption={value => {
  234. setCustomeAttributes(curr => [...curr, value]);
  235. model.setValue('spanAttribute', value);
  236. }}
  237. required
  238. />
  239. <SelectField
  240. name="aggregates"
  241. required
  242. options={AGGREGATE_OPTIONS}
  243. label={t('Aggregate')}
  244. multiple
  245. help={tct(
  246. 'Select the aggregations you want to store. For more information, read [link:our docs]',
  247. {
  248. // TODO(telemetry-experience): add the correct link here once we have it!!!
  249. link: (
  250. <ExternalLink href="https://docs.sentry.io/product/explore/metrics/" />
  251. ),
  252. }
  253. )}
  254. />
  255. <SelectField
  256. name="tags"
  257. options={tagOptions}
  258. label={t('Group and filter by')}
  259. multiple
  260. placeholder={t('Select tags')}
  261. help={t('Select the tags that can be used to group and filter the metric.')}
  262. creatable
  263. formatCreateLabel={value => `Custom: "${value}"`}
  264. onCreateOption={value => {
  265. setCustomeAttributes(curr => [...curr, value]);
  266. const currentTags = model.getValue('tags') as string[];
  267. model.setValue('tags', [...currentTags, value]);
  268. }}
  269. />
  270. <FormField
  271. label={t('Queries')}
  272. help={t(
  273. 'Define queries to narrow down the metric extraction to a specific set of spans.'
  274. )}
  275. name="conditions"
  276. inline={false}
  277. hasControlState={false}
  278. flexibleControlStateSize
  279. >
  280. {({onChange, initialData, value}) => {
  281. const conditions = (value ||
  282. initialData ||
  283. []) as MetricsExtractionCondition[];
  284. const handleChange = (queryString: string, index: number) => {
  285. onChange(
  286. conditions.toSpliced(index, 1, {
  287. ...conditions[index],
  288. value: queryString,
  289. }),
  290. {}
  291. );
  292. };
  293. const getMaxCardinality = (condition: MetricsExtractionCondition) => {
  294. if (!cardinality) {
  295. return 0;
  296. }
  297. return condition.mris.reduce(
  298. (acc, mri) => Math.max(acc, cardinality[mri] || 0),
  299. 0
  300. );
  301. };
  302. return (
  303. <Fragment>
  304. <ConditionsWrapper hasDelete={value.length > 1}>
  305. {conditions.map((condition, index) => {
  306. const maxCardinality = getMaxCardinality(condition);
  307. const isExeedingCardinalityLimit =
  308. // TODO: Retrieve limit from BE
  309. maxCardinality >= DEFAULT_METRICS_CARDINALITY_LIMIT;
  310. const hasSiblings = conditions.length > 1;
  311. return (
  312. <Fragment key={condition.id}>
  313. <SearchWrapper
  314. hasPrefix={hasSiblings || isExeedingCardinalityLimit}
  315. >
  316. {hasSiblings || isExeedingCardinalityLimit ? (
  317. isExeedingCardinalityLimit ? (
  318. <Tooltip
  319. title={t(
  320. 'This query is exeeding the cardinality limit. Remove tags or add more filters to receive accurate data.'
  321. )}
  322. >
  323. <StyledIconWarning size="xs" color="yellow300" />
  324. </Tooltip>
  325. ) : (
  326. <ConditionSymbol>{index + 1}</ConditionSymbol>
  327. )
  328. ) : null}
  329. <SearchBarWithId
  330. {...SPAN_SEARCH_CONFIG}
  331. searchSource="metrics-extraction"
  332. query={condition.value}
  333. onSearch={(queryString: string) =>
  334. handleChange(queryString, index)
  335. }
  336. onClose={(queryString: string, {validSearch}) => {
  337. if (validSearch) {
  338. handleChange(queryString, index);
  339. }
  340. }}
  341. placeholder={t('Search for span attributes')}
  342. organization={organization}
  343. metricAlert={false}
  344. supportedTags={supportedTags}
  345. dataset={DiscoverDatasets.SPANS_INDEXED}
  346. projectIds={[Number(projectId)]}
  347. hasRecentSearches={false}
  348. savedSearchType={undefined}
  349. useFormWrapper={false}
  350. />
  351. </SearchWrapper>
  352. {value.length > 1 && (
  353. <Button
  354. aria-label={t('Remove Query')}
  355. onClick={() => onChange(conditions.toSpliced(index, 1), {})}
  356. icon={<IconClose />}
  357. />
  358. )}
  359. </Fragment>
  360. );
  361. })}
  362. </ConditionsWrapper>
  363. <ConditionsButtonBar>
  364. <Button
  365. size="sm"
  366. onClick={() => onChange([...conditions, createCondition()], {})}
  367. icon={<IconAdd />}
  368. >
  369. {t('Add Query')}
  370. </Button>
  371. </ConditionsButtonBar>
  372. </Fragment>
  373. );
  374. }}
  375. </FormField>
  376. </Fragment>
  377. )}
  378. </Form>
  379. );
  380. }
  381. function SearchBarWithId(props: React.ComponentProps<typeof SearchBar>) {
  382. const id = useId();
  383. return <SearchBar id={id} {...props} />;
  384. }
  385. const ConditionsWrapper = styled('div')<{hasDelete: boolean}>`
  386. padding: ${space(1)} 0;
  387. display: grid;
  388. align-items: center;
  389. gap: ${space(1)};
  390. ${p =>
  391. p.hasDelete
  392. ? `
  393. grid-template-columns: 1fr min-content;
  394. `
  395. : `
  396. grid-template-columns: 1fr;
  397. `}
  398. `;
  399. const SearchWrapper = styled('div')<{hasPrefix?: boolean}>`
  400. display: grid;
  401. gap: ${space(1)};
  402. align-items: center;
  403. grid-template-columns: ${p => (p.hasPrefix ? 'max-content' : '')} 1fr;
  404. `;
  405. const ConditionSymbol = styled('div')`
  406. background-color: ${p => p.theme.purple100};
  407. color: ${p => p.theme.purple400};
  408. text-align: center;
  409. align-content: center;
  410. height: ${space(3)};
  411. width: ${space(3)};
  412. border-radius: 50%;
  413. `;
  414. const StyledIconWarning = styled(IconWarning)`
  415. margin: 0 ${space(0.5)};
  416. `;
  417. const ConditionsButtonBar = styled('div')`
  418. margin-top: ${space(1)};
  419. `;