metricsExtractionRuleForm.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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(
  262. 'Select the tags that can be used to group and filter the metric. Tag values have to be non-numeric.'
  263. )}
  264. creatable
  265. formatCreateLabel={value => `Custom: "${value}"`}
  266. onCreateOption={value => {
  267. setCustomeAttributes(curr => [...curr, value]);
  268. const currentTags = model.getValue('tags') as string[];
  269. model.setValue('tags', [...currentTags, value]);
  270. }}
  271. />
  272. <FormField
  273. label={t('Filters')}
  274. help={t(
  275. 'Define filters to narrow down the metric to a specific set of spans.'
  276. )}
  277. name="conditions"
  278. inline={false}
  279. hasControlState={false}
  280. flexibleControlStateSize
  281. >
  282. {({onChange, initialData, value}) => {
  283. const conditions = (value ||
  284. initialData ||
  285. []) as MetricsExtractionCondition[];
  286. const handleChange = (queryString: string, index: number) => {
  287. onChange(
  288. conditions.toSpliced(index, 1, {
  289. ...conditions[index],
  290. value: queryString,
  291. }),
  292. {}
  293. );
  294. };
  295. const getMaxCardinality = (condition: MetricsExtractionCondition) => {
  296. if (!cardinality) {
  297. return 0;
  298. }
  299. return condition.mris.reduce(
  300. (acc, mri) => Math.max(acc, cardinality[mri] || 0),
  301. 0
  302. );
  303. };
  304. return (
  305. <Fragment>
  306. <ConditionsWrapper hasDelete={value.length > 1}>
  307. {conditions.map((condition, index) => {
  308. const maxCardinality = getMaxCardinality(condition);
  309. const isExeedingCardinalityLimit =
  310. // TODO: Retrieve limit from BE
  311. maxCardinality >= DEFAULT_METRICS_CARDINALITY_LIMIT;
  312. const hasSiblings = conditions.length > 1;
  313. return (
  314. <Fragment key={condition.id}>
  315. <SearchWrapper
  316. hasPrefix={hasSiblings || isExeedingCardinalityLimit}
  317. >
  318. {hasSiblings || isExeedingCardinalityLimit ? (
  319. isExeedingCardinalityLimit ? (
  320. <Tooltip
  321. title={t(
  322. 'This filter is exeeding the cardinality limit. Remove tags or add more conditions to receive accurate data.'
  323. )}
  324. >
  325. <StyledIconWarning size="xs" color="yellow300" />
  326. </Tooltip>
  327. ) : (
  328. <ConditionSymbol>{index + 1}</ConditionSymbol>
  329. )
  330. ) : null}
  331. <SearchBarWithId
  332. {...SPAN_SEARCH_CONFIG}
  333. searchSource="metrics-extraction"
  334. query={condition.value}
  335. onSearch={(queryString: string) =>
  336. handleChange(queryString, index)
  337. }
  338. onClose={(queryString: string, {validSearch}) => {
  339. if (validSearch) {
  340. handleChange(queryString, index);
  341. }
  342. }}
  343. placeholder={t('Search for span attributes')}
  344. organization={organization}
  345. supportedTags={supportedTags}
  346. dataset={DiscoverDatasets.SPANS_INDEXED}
  347. projectIds={[Number(projectId)]}
  348. hasRecentSearches={false}
  349. savedSearchType={undefined}
  350. useFormWrapper={false}
  351. />
  352. </SearchWrapper>
  353. {value.length > 1 && (
  354. <Button
  355. aria-label={t('Remove Filter')}
  356. onClick={() => onChange(conditions.toSpliced(index, 1), {})}
  357. icon={<IconClose />}
  358. />
  359. )}
  360. </Fragment>
  361. );
  362. })}
  363. </ConditionsWrapper>
  364. <ConditionsButtonBar>
  365. <Button
  366. size="sm"
  367. onClick={() => onChange([...conditions, createCondition()], {})}
  368. icon={<IconAdd />}
  369. >
  370. {t('Add Filter')}
  371. </Button>
  372. </ConditionsButtonBar>
  373. </Fragment>
  374. );
  375. }}
  376. </FormField>
  377. </Fragment>
  378. )}
  379. </Form>
  380. );
  381. }
  382. function SearchBarWithId(props: React.ComponentProps<typeof SearchBar>) {
  383. const id = useId();
  384. return <SearchBar id={id} {...props} />;
  385. }
  386. const ConditionsWrapper = styled('div')<{hasDelete: boolean}>`
  387. padding: ${space(1)} 0;
  388. display: grid;
  389. align-items: center;
  390. gap: ${space(1)};
  391. ${p =>
  392. p.hasDelete
  393. ? `
  394. grid-template-columns: 1fr min-content;
  395. `
  396. : `
  397. grid-template-columns: 1fr;
  398. `}
  399. `;
  400. const SearchWrapper = styled('div')<{hasPrefix?: boolean}>`
  401. display: grid;
  402. gap: ${space(1)};
  403. align-items: center;
  404. grid-template-columns: ${p => (p.hasPrefix ? 'max-content' : '')} 1fr;
  405. `;
  406. const ConditionSymbol = styled('div')`
  407. background-color: ${p => p.theme.purple100};
  408. color: ${p => p.theme.purple400};
  409. text-align: center;
  410. align-content: center;
  411. height: ${space(3)};
  412. width: ${space(3)};
  413. border-radius: 50%;
  414. `;
  415. const StyledIconWarning = styled(IconWarning)`
  416. margin: 0 ${space(0.5)};
  417. `;
  418. const ConditionsButtonBar = styled('div')`
  419. margin-top: ${space(1)};
  420. `;