ruleConditionsForm.tsx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. import {Fragment, PureComponent} from 'react';
  2. import {components} from 'react-select';
  3. import {css} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import omit from 'lodash/omit';
  6. import pick from 'lodash/pick';
  7. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  8. import {fetchTagValues} from 'sentry/actionCreators/tags';
  9. import type {Client} from 'sentry/api';
  10. import Alert from 'sentry/components/alert';
  11. import {
  12. OnDemandMetricAlert,
  13. OnDemandWarningIcon,
  14. } from 'sentry/components/alerts/onDemandMetricAlert';
  15. import {getHasTag} from 'sentry/components/events/searchBar';
  16. import {
  17. STATIC_FIELD_TAGS,
  18. STATIC_FIELD_TAGS_WITHOUT_ERROR_FIELDS,
  19. STATIC_FIELD_TAGS_WITHOUT_TRACING,
  20. STATIC_FIELD_TAGS_WITHOUT_TRANSACTION_FIELDS,
  21. STATIC_SEMVER_TAGS,
  22. STATIC_SPAN_TAGS,
  23. } from 'sentry/components/events/searchBarFieldConstants';
  24. import SelectControl from 'sentry/components/forms/controls/selectControl';
  25. import SelectField from 'sentry/components/forms/fields/selectField';
  26. import FormField from 'sentry/components/forms/formField';
  27. import IdBadge from 'sentry/components/idBadge';
  28. import ListItem from 'sentry/components/list/listItem';
  29. import {MetricSearchBar} from 'sentry/components/metrics/metricSearchBar';
  30. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  31. import Panel from 'sentry/components/panels/panel';
  32. import PanelBody from 'sentry/components/panels/panelBody';
  33. import {EAPSpanSearchQueryBuilder} from 'sentry/components/performance/spanSearchQueryBuilder';
  34. import {SearchQueryBuilder} from 'sentry/components/searchQueryBuilder';
  35. import {InvalidReason} from 'sentry/components/searchSyntax/parser';
  36. import {t, tct} from 'sentry/locale';
  37. import {space} from 'sentry/styles/space';
  38. import type {SelectValue} from 'sentry/types/core';
  39. import type {Tag, TagCollection} from 'sentry/types/group';
  40. import type {InjectedRouter} from 'sentry/types/legacyReactRouter';
  41. import type {Organization} from 'sentry/types/organization';
  42. import type {Environment, Project} from 'sentry/types/project';
  43. import {defined} from 'sentry/utils';
  44. import {isAggregateField, isMeasurement} from 'sentry/utils/discover/fields';
  45. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  46. import {getDisplayName} from 'sentry/utils/environment';
  47. import {
  48. ALLOWED_EXPLORE_VISUALIZE_AGGREGATES,
  49. DEVICE_CLASS_TAG_VALUES,
  50. FieldKind,
  51. isDeviceClass,
  52. } from 'sentry/utils/fields';
  53. import {
  54. getMeasurements,
  55. type MeasurementCollection,
  56. } from 'sentry/utils/measurements/measurements';
  57. import {hasCustomMetrics} from 'sentry/utils/metrics/features';
  58. import {getMRI} from 'sentry/utils/metrics/mri';
  59. import {getOnDemandKeys, isOnDemandQueryString} from 'sentry/utils/onDemandMetrics';
  60. import {hasOnDemandMetricAlertFeature} from 'sentry/utils/onDemandMetrics/features';
  61. import withApi from 'sentry/utils/withApi';
  62. import withProjects from 'sentry/utils/withProjects';
  63. import withTags from 'sentry/utils/withTags';
  64. import WizardField from 'sentry/views/alerts/rules/metric/wizardField';
  65. import {
  66. convertDatasetEventTypesToSource,
  67. DATA_SOURCE_LABELS,
  68. DATA_SOURCE_TO_SET_AND_EVENT_TYPES,
  69. } from 'sentry/views/alerts/utils';
  70. import type {AlertType} from 'sentry/views/alerts/wizard/options';
  71. import {getSupportedAndOmittedTags} from 'sentry/views/alerts/wizard/options';
  72. import {
  73. SpanTagsContext,
  74. SpanTagsProvider,
  75. } from 'sentry/views/explore/contexts/spanTagsContext';
  76. import {hasEAPAlerts} from 'sentry/views/insights/common/utils/hasEAPAlerts';
  77. import {getProjectOptions} from '../utils';
  78. import {isCrashFreeAlert} from './utils/isCrashFreeAlert';
  79. import {DEFAULT_AGGREGATE, DEFAULT_TRANSACTION_AGGREGATE} from './constants';
  80. import {AlertRuleComparisonType, Dataset, Datasource, TimeWindow} from './types';
  81. const TIME_WINDOW_MAP: Record<TimeWindow, string> = {
  82. [TimeWindow.ONE_MINUTE]: t('1 minute'),
  83. [TimeWindow.FIVE_MINUTES]: t('5 minutes'),
  84. [TimeWindow.TEN_MINUTES]: t('10 minutes'),
  85. [TimeWindow.FIFTEEN_MINUTES]: t('15 minutes'),
  86. [TimeWindow.THIRTY_MINUTES]: t('30 minutes'),
  87. [TimeWindow.ONE_HOUR]: t('1 hour'),
  88. [TimeWindow.TWO_HOURS]: t('2 hours'),
  89. [TimeWindow.FOUR_HOURS]: t('4 hours'),
  90. [TimeWindow.ONE_DAY]: t('24 hours'),
  91. };
  92. type Props = {
  93. aggregate: string;
  94. alertType: AlertType;
  95. api: Client;
  96. comparisonType: AlertRuleComparisonType;
  97. dataset: Dataset;
  98. disabled: boolean;
  99. isEditing: boolean;
  100. onComparisonDeltaChange: (value: number) => void;
  101. onFilterSearch: (query: string, isQueryValid) => void;
  102. onTimeWindowChange: (value: number) => void;
  103. organization: Organization;
  104. project: Project;
  105. projects: Project[];
  106. router: InjectedRouter;
  107. tags: TagCollection;
  108. thresholdChart: React.ReactNode;
  109. timeWindow: number;
  110. // optional props
  111. allowChangeEventTypes?: boolean;
  112. comparisonDelta?: number;
  113. disableProjectSelector?: boolean;
  114. isErrorMigration?: boolean;
  115. isExtrapolatedChartData?: boolean;
  116. isForLlmMetric?: boolean;
  117. isLowConfidenceChartData?: boolean;
  118. isTransactionMigration?: boolean;
  119. loadingProjects?: boolean;
  120. };
  121. type State = {
  122. environments: Environment[] | null;
  123. filterKeys: TagCollection;
  124. measurements: MeasurementCollection;
  125. };
  126. class RuleConditionsForm extends PureComponent<Props, State> {
  127. state: State = {
  128. environments: null,
  129. measurements: {},
  130. filterKeys: {},
  131. };
  132. componentDidMount() {
  133. this.fetchData();
  134. const measurements = getMeasurements();
  135. const filterKeys = this.getFilterKeys();
  136. this.setState({measurements, filterKeys});
  137. }
  138. componentDidUpdate(prevProps: Props) {
  139. if (prevProps.project.id === this.props.project.id) {
  140. return;
  141. }
  142. this.fetchData();
  143. }
  144. getFilterKeys = () => {
  145. const {organization, dataset, tags} = this.props;
  146. const {measurements} = this.state;
  147. const measurementsWithKind = Object.keys(measurements).reduce(
  148. (measurement_tags, key) => {
  149. measurement_tags[key] = {
  150. ...measurements[key],
  151. kind: FieldKind.MEASUREMENT,
  152. };
  153. return measurement_tags;
  154. },
  155. {}
  156. );
  157. const orgHasPerformanceView = organization.features.includes('performance-view');
  158. const combinedTags: TagCollection =
  159. dataset === Dataset.ERRORS
  160. ? Object.assign({}, STATIC_FIELD_TAGS_WITHOUT_TRANSACTION_FIELDS)
  161. : dataset === Dataset.TRANSACTIONS
  162. ? Object.assign(
  163. {},
  164. measurementsWithKind,
  165. STATIC_SPAN_TAGS,
  166. STATIC_FIELD_TAGS_WITHOUT_ERROR_FIELDS
  167. )
  168. : orgHasPerformanceView
  169. ? Object.assign({}, measurementsWithKind, STATIC_SPAN_TAGS, STATIC_FIELD_TAGS)
  170. : Object.assign({}, STATIC_FIELD_TAGS_WITHOUT_TRACING);
  171. const tagsWithKind = Object.keys(tags).reduce<Record<string, Tag>>((acc, key) => {
  172. acc[key] = {
  173. ...tags[key]!,
  174. kind: FieldKind.TAG,
  175. };
  176. return acc;
  177. }, {});
  178. const {omitTags} = getSupportedAndOmittedTags(dataset, organization);
  179. Object.assign(combinedTags, tagsWithKind, STATIC_SEMVER_TAGS);
  180. combinedTags.has = getHasTag(combinedTags);
  181. const list =
  182. omitTags && omitTags.length > 0 ? omit(combinedTags, omitTags) : combinedTags;
  183. return list;
  184. };
  185. formElemBaseStyle = {
  186. padding: `${space(0.5)}`,
  187. border: 'none',
  188. };
  189. async fetchData() {
  190. const {api, organization, project} = this.props;
  191. try {
  192. const environments = await api.requestPromise(
  193. `/projects/${organization.slug}/${project.slug}/environments/`,
  194. {
  195. query: {
  196. visibility: 'visible',
  197. },
  198. }
  199. );
  200. this.setState({environments});
  201. } catch (_err) {
  202. addErrorMessage(t('Unable to fetch environments'));
  203. }
  204. }
  205. getEventFieldValues = async (tag, query): Promise<string[]> => {
  206. const {api, organization, project, dataset, router} = this.props;
  207. if (isAggregateField(tag.key) || isMeasurement(tag.key)) {
  208. // We can't really auto suggest values for aggregate fields
  209. // or measurements, so we simply don't
  210. // NOTE: these in particular are for discover queries. We may not need/support these
  211. return Promise.resolve([]);
  212. }
  213. // device.class is stored as "numbers" in snuba, but we want to suggest high, medium,
  214. // and low search filter values because discover maps device.class to these values.
  215. if (isDeviceClass(tag.key)) {
  216. return Promise.resolve(DEVICE_CLASS_TAG_VALUES);
  217. }
  218. const values = await fetchTagValues({
  219. api,
  220. orgSlug: organization.slug,
  221. tagKey: tag.key,
  222. search: query,
  223. projectIds: [project.id],
  224. endpointParams: normalizeDateTimeParams(router.location.query), // allows searching for tags on transactions as well
  225. includeTransactions: true, // allows searching for tags on sessions as well
  226. includeSessions: dataset === Dataset.SESSIONS,
  227. });
  228. return values.filter(({name}) => defined(name)).map(({name}) => name);
  229. };
  230. get timeWindowOptions() {
  231. let options: Record<string, string> = TIME_WINDOW_MAP;
  232. const {alertType} = this.props;
  233. if (alertType === 'custom_metrics') {
  234. // Do not show ONE MINUTE interval as an option for custom_metrics alert
  235. options = omit(options, TimeWindow.ONE_MINUTE.toString());
  236. }
  237. if (isCrashFreeAlert(this.props.dataset)) {
  238. options = pick(TIME_WINDOW_MAP, [
  239. // TimeWindow.THIRTY_MINUTES, leaving this option out until we figure out the sub-hour session resolution chart limitations
  240. TimeWindow.ONE_HOUR,
  241. TimeWindow.TWO_HOURS,
  242. TimeWindow.FOUR_HOURS,
  243. TimeWindow.ONE_DAY,
  244. ]);
  245. }
  246. if (this.props.comparisonType === AlertRuleComparisonType.DYNAMIC) {
  247. options = pick(TIME_WINDOW_MAP, [
  248. TimeWindow.FIVE_MINUTES,
  249. TimeWindow.FIFTEEN_MINUTES,
  250. TimeWindow.THIRTY_MINUTES,
  251. TimeWindow.ONE_HOUR,
  252. ]);
  253. }
  254. if (this.props.dataset === Dataset.EVENTS_ANALYTICS_PLATFORM) {
  255. options = pick(TIME_WINDOW_MAP, [
  256. TimeWindow.FIVE_MINUTES,
  257. TimeWindow.TEN_MINUTES,
  258. TimeWindow.FIFTEEN_MINUTES,
  259. TimeWindow.THIRTY_MINUTES,
  260. TimeWindow.ONE_HOUR,
  261. TimeWindow.TWO_HOURS,
  262. TimeWindow.FOUR_HOURS,
  263. TimeWindow.ONE_DAY,
  264. ]);
  265. }
  266. return Object.entries(options).map(([value, label]) => ({
  267. value: parseInt(value, 10),
  268. label: tct('[timeWindow] interval', {
  269. timeWindow: label.slice(-1) === 's' ? label.slice(0, -1) : label,
  270. }),
  271. }));
  272. }
  273. get searchPlaceholder() {
  274. switch (this.props.dataset) {
  275. case Dataset.ERRORS:
  276. return t('Filter events by level, message, and other properties\u2026');
  277. case Dataset.METRICS:
  278. case Dataset.SESSIONS:
  279. return t('Filter sessions by release version\u2026');
  280. default:
  281. return t('Filter transactions by URL, tags, and other properties\u2026');
  282. }
  283. }
  284. get selectControlStyles() {
  285. return {
  286. control: (provided: {[x: string]: string | number | boolean}) => ({
  287. ...provided,
  288. minWidth: 200,
  289. maxWidth: 300,
  290. }),
  291. container: (provided: {[x: string]: string | number | boolean}) => ({
  292. ...provided,
  293. margin: `${space(0.5)}`,
  294. }),
  295. };
  296. }
  297. renderEventTypeFilter() {
  298. const {organization, disabled, alertType, isErrorMigration} = this.props;
  299. const dataSourceOptions = [
  300. {
  301. label: t('Errors'),
  302. options: [
  303. {
  304. value: Datasource.ERROR_DEFAULT,
  305. label: DATA_SOURCE_LABELS[Datasource.ERROR_DEFAULT],
  306. },
  307. {
  308. value: Datasource.DEFAULT,
  309. label: DATA_SOURCE_LABELS[Datasource.DEFAULT],
  310. },
  311. {
  312. value: Datasource.ERROR,
  313. label: DATA_SOURCE_LABELS[Datasource.ERROR],
  314. },
  315. ],
  316. },
  317. ];
  318. if (
  319. organization.features.includes('performance-view') &&
  320. (alertType === 'custom_transactions' || alertType === 'custom_metrics')
  321. ) {
  322. dataSourceOptions.push({
  323. label: t('Transactions'),
  324. options: [
  325. {
  326. value: Datasource.TRANSACTION,
  327. label: DATA_SOURCE_LABELS[Datasource.TRANSACTION],
  328. },
  329. ],
  330. });
  331. }
  332. return (
  333. <FormField
  334. name="datasource"
  335. inline={false}
  336. style={{
  337. ...this.formElemBaseStyle,
  338. minWidth: 300,
  339. flex: 2,
  340. }}
  341. flexibleControlStateSize
  342. >
  343. {({onChange, onBlur, model}) => {
  344. const formDataset = model.getValue('dataset');
  345. const formEventTypes = model.getValue('eventTypes');
  346. const aggregate = model.getValue('aggregate');
  347. const mappedValue = convertDatasetEventTypesToSource(
  348. formDataset,
  349. formEventTypes
  350. );
  351. return (
  352. <SelectControl
  353. value={mappedValue}
  354. inFieldLabel={t('Events: ')}
  355. onChange={({value}) => {
  356. onChange(value, {});
  357. onBlur(value, {});
  358. // Reset the aggregate to the default (which works across
  359. // datatypes), otherwise we may send snuba an invalid query
  360. // (transaction aggregate on events datasource = bad).
  361. const newAggregate =
  362. value === Datasource.TRANSACTION
  363. ? DEFAULT_TRANSACTION_AGGREGATE
  364. : DEFAULT_AGGREGATE;
  365. if (alertType === 'custom_transactions' && aggregate !== newAggregate) {
  366. model.setValue('aggregate', newAggregate);
  367. }
  368. // set the value of the dataset and event type from data source
  369. const {dataset: datasetFromDataSource, eventTypes} =
  370. DATA_SOURCE_TO_SET_AND_EVENT_TYPES[value] ?? {};
  371. model.setValue('dataset', datasetFromDataSource);
  372. model.setValue('eventTypes', eventTypes);
  373. }}
  374. options={dataSourceOptions}
  375. isDisabled={disabled || isErrorMigration}
  376. />
  377. );
  378. }}
  379. </FormField>
  380. );
  381. }
  382. renderProjectSelector() {
  383. const {
  384. project: _selectedProject,
  385. projects, // note: org projects
  386. disabled,
  387. organization,
  388. disableProjectSelector,
  389. } = this.props;
  390. const projectOptions = getProjectOptions({
  391. organization,
  392. projects,
  393. isFormDisabled: disabled,
  394. });
  395. return (
  396. <FormField
  397. name="projectId"
  398. inline={false}
  399. style={{
  400. ...this.formElemBaseStyle,
  401. minWidth: 300,
  402. flex: 2,
  403. }}
  404. flexibleControlStateSize
  405. >
  406. {({onChange, onBlur, model}) => {
  407. const selectedProject =
  408. projects.find(({id}) => id === model.getValue('projectId')) ||
  409. _selectedProject;
  410. return (
  411. <SelectControl
  412. isDisabled={disabled || disableProjectSelector}
  413. value={selectedProject.id}
  414. options={projectOptions}
  415. onChange={({value}: {value: Project['id']}) => {
  416. // if the current owner/team isn't part of project selected, update to the first available team
  417. const nextSelectedProject =
  418. projects.find(({id}) => id === value) ?? selectedProject;
  419. const ownerId: string | undefined = model
  420. .getValue('owner')
  421. ?.split(':')[1];
  422. if (
  423. ownerId &&
  424. nextSelectedProject.teams.find(({id}) => id === ownerId) ===
  425. undefined &&
  426. nextSelectedProject.teams.length
  427. ) {
  428. model.setValue('owner', `team:${nextSelectedProject.teams[0]!.id}`);
  429. }
  430. onChange(value, {});
  431. onBlur(value, {});
  432. }}
  433. components={{
  434. SingleValue: containerProps => (
  435. <components.ValueContainer {...containerProps}>
  436. <IdBadge
  437. project={selectedProject}
  438. avatarProps={{consistentWidth: true}}
  439. avatarSize={18}
  440. disableLink
  441. />
  442. </components.ValueContainer>
  443. ),
  444. }}
  445. />
  446. );
  447. }}
  448. </FormField>
  449. );
  450. }
  451. renderInterval() {
  452. const {
  453. organization,
  454. timeWindow,
  455. disabled,
  456. alertType,
  457. project,
  458. isForLlmMetric,
  459. onTimeWindowChange,
  460. } = this.props;
  461. return (
  462. <Fragment>
  463. <StyledListItem>
  464. <StyledListTitle>
  465. <div>{t('Define your metric')}</div>
  466. </StyledListTitle>
  467. </StyledListItem>
  468. <FormRow>
  469. {isForLlmMetric ? null : (
  470. <WizardField
  471. name="aggregate"
  472. help={null}
  473. organization={organization}
  474. disabled={disabled}
  475. project={project}
  476. style={{
  477. ...this.formElemBaseStyle,
  478. flex: 1,
  479. }}
  480. inline={false}
  481. flexibleControlStateSize
  482. columnWidth={200}
  483. alertType={alertType}
  484. required
  485. />
  486. )}
  487. <SelectControl
  488. name="timeWindow"
  489. styles={this.selectControlStyles}
  490. options={this.timeWindowOptions}
  491. isDisabled={disabled}
  492. value={timeWindow}
  493. onChange={({value}) => onTimeWindowChange(value)}
  494. inline={false}
  495. flexibleControlStateSize
  496. />
  497. </FormRow>
  498. </Fragment>
  499. );
  500. }
  501. render() {
  502. const {
  503. alertType,
  504. organization,
  505. disabled,
  506. onFilterSearch,
  507. allowChangeEventTypes,
  508. dataset,
  509. isExtrapolatedChartData,
  510. isTransactionMigration,
  511. isErrorMigration,
  512. aggregate,
  513. project,
  514. comparisonType,
  515. isLowConfidenceChartData,
  516. } = this.props;
  517. const {environments, filterKeys} = this.state;
  518. const environmentOptions: SelectValue<string | null>[] = [
  519. {
  520. value: null,
  521. label: t('All Environments'),
  522. },
  523. ...(environments?.map(env => ({value: env.name, label: getDisplayName(env)})) ??
  524. []),
  525. ];
  526. const confidenceEnabled = hasEAPAlerts(organization);
  527. return (
  528. <Fragment>
  529. <ChartPanel>
  530. <StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody>
  531. </ChartPanel>
  532. {isTransactionMigration ? (
  533. <Fragment>
  534. <Spacer />
  535. <HiddenListItem />
  536. <HiddenListItem />
  537. </Fragment>
  538. ) : (
  539. <Fragment>
  540. <SpanTagsProvider
  541. dataset={DiscoverDatasets.SPANS_EAP}
  542. enabled={
  543. organization.features.includes('alerts-eap') &&
  544. alertType === 'eap_metrics'
  545. }
  546. >
  547. {isExtrapolatedChartData && (
  548. <OnDemandMetricAlert
  549. message={t(
  550. 'The chart data above is an estimate based on the stored transactions that match the filters specified.'
  551. )}
  552. />
  553. )}
  554. {confidenceEnabled && isLowConfidenceChartData && (
  555. <Alert showIcon type="warning">
  556. {t(
  557. 'Your low sample count may impact the accuracy of this alert. Edit your query or increase your sampling rate.'
  558. )}
  559. </Alert>
  560. )}
  561. {!isErrorMigration && this.renderInterval()}
  562. <StyledListItem>{t('Filter events')}</StyledListItem>
  563. <FormRow noMargin columns={1 + (allowChangeEventTypes ? 1 : 0) + 1}>
  564. {this.renderProjectSelector()}
  565. <SelectField
  566. name="environment"
  567. placeholder={t('All Environments')}
  568. style={{
  569. ...this.formElemBaseStyle,
  570. minWidth: 230,
  571. flex: 1,
  572. }}
  573. styles={{
  574. singleValue: (base: any) => ({
  575. ...base,
  576. }),
  577. option: (base: any) => ({
  578. ...base,
  579. }),
  580. }}
  581. options={environmentOptions}
  582. isDisabled={
  583. disabled || this.state.environments === null || isErrorMigration
  584. }
  585. isClearable
  586. inline={false}
  587. flexibleControlStateSize
  588. />
  589. {allowChangeEventTypes && this.renderEventTypeFilter()}
  590. </FormRow>
  591. <FormRow noMargin>
  592. <FormField
  593. name="query"
  594. inline={false}
  595. style={{
  596. ...this.formElemBaseStyle,
  597. flex: '6 0 500px',
  598. }}
  599. flexibleControlStateSize
  600. >
  601. {({onChange, onBlur, initialData, value}) => {
  602. return hasCustomMetrics(organization) &&
  603. alertType === 'custom_metrics' ? (
  604. <MetricSearchBar
  605. mri={getMRI(aggregate)}
  606. projectIds={[project.id]}
  607. placeholder={this.searchPlaceholder}
  608. query={initialData.query}
  609. defaultQuery={initialData?.query ?? ''}
  610. useFormWrapper={false}
  611. searchSource="alert_builder"
  612. onChange={query => {
  613. onFilterSearch(query, true);
  614. onChange(query, {});
  615. }}
  616. />
  617. ) : alertType === 'eap_metrics' ? (
  618. <SpanTagsContext.Consumer>
  619. {tags => (
  620. <EAPSpanSearchQueryBuilder
  621. numberTags={tags?.number ?? {}}
  622. stringTags={tags?.string ?? {}}
  623. initialQuery={value ?? ''}
  624. searchSource="alerts"
  625. onSearch={(query, {parsedQuery}) => {
  626. onFilterSearch(query, parsedQuery);
  627. onChange(query, {});
  628. }}
  629. supportedAggregates={ALLOWED_EXPLORE_VISUALIZE_AGGREGATES}
  630. projects={[parseInt(project.id, 10)]}
  631. />
  632. )}
  633. </SpanTagsContext.Consumer>
  634. ) : (
  635. <SearchContainer>
  636. <SearchQueryBuilder
  637. initialQuery={initialData?.query ?? ''}
  638. getTagValues={this.getEventFieldValues}
  639. placeholder={this.searchPlaceholder}
  640. searchSource="alert_builder"
  641. filterKeys={filterKeys}
  642. disabled={disabled || isErrorMigration}
  643. onChange={onChange}
  644. invalidMessages={{
  645. [InvalidReason.WILDCARD_NOT_ALLOWED]: t(
  646. 'The wildcard operator is not supported here.'
  647. ),
  648. [InvalidReason.FREE_TEXT_NOT_ALLOWED]: t(
  649. 'Free text search is not allowed. If you want to partially match transaction names, use glob patterns like "transaction:*transaction-name*"'
  650. ),
  651. }}
  652. onSearch={query => {
  653. onFilterSearch(query, true);
  654. onChange(query, {});
  655. }}
  656. onBlur={(query, {parsedQuery}) => {
  657. onFilterSearch(query, parsedQuery);
  658. onBlur(query);
  659. }}
  660. // We only need strict validation for Transaction queries, everything else is fine
  661. disallowUnsupportedFilters={
  662. organization.features.includes('alert-allow-indexed') ||
  663. (hasOnDemandMetricAlertFeature(organization) &&
  664. isOnDemandQueryString(value))
  665. ? false
  666. : dataset === Dataset.GENERIC_METRICS
  667. }
  668. />
  669. {isExtrapolatedChartData && isOnDemandQueryString(value) && (
  670. <OnDemandWarningIcon
  671. color="gray500"
  672. msg={tct(
  673. `We don’t routinely collect metrics from [fields]. However, we’ll do so [strong:once this alert has been saved.]`,
  674. {
  675. fields: (
  676. <strong>
  677. {getOnDemandKeys(value)
  678. .map(key => `"${key}"`)
  679. .join(', ')}
  680. </strong>
  681. ),
  682. strong: <strong />,
  683. }
  684. )}
  685. />
  686. )}
  687. </SearchContainer>
  688. );
  689. }}
  690. </FormField>
  691. </FormRow>
  692. <FormRow noMargin>
  693. <FormField
  694. name="query"
  695. inline={false}
  696. style={{
  697. ...this.formElemBaseStyle,
  698. flex: '6 0 500px',
  699. }}
  700. flexibleControlStateSize
  701. >
  702. {args => {
  703. if (
  704. args.value?.includes('is:unresolved') &&
  705. comparisonType === AlertRuleComparisonType.DYNAMIC
  706. ) {
  707. return (
  708. <OnDemandMetricAlert
  709. message={t(
  710. "'is:unresolved' queries are not supported by Anomaly Detection alerts."
  711. )}
  712. />
  713. );
  714. }
  715. return null;
  716. }}
  717. </FormField>
  718. </FormRow>
  719. </SpanTagsProvider>
  720. </Fragment>
  721. )}
  722. </Fragment>
  723. );
  724. }
  725. }
  726. const StyledListTitle = styled('div')`
  727. display: flex;
  728. span {
  729. margin-left: ${space(1)};
  730. }
  731. `;
  732. // This is a temporary hacky solution to hide list items without changing the numbering of the rest of the list
  733. // TODO(issues): Remove this once the migration is complete
  734. const HiddenListItem = styled(ListItem)`
  735. position: absolute;
  736. width: 0px;
  737. height: 0px;
  738. opacity: 0;
  739. pointer-events: none;
  740. `;
  741. const Spacer = styled('div')`
  742. margin-bottom: ${space(2)};
  743. `;
  744. const ChartPanel = styled(Panel)`
  745. margin-bottom: ${space(1)};
  746. `;
  747. const StyledPanelBody = styled(PanelBody)`
  748. ol,
  749. h4 {
  750. margin-bottom: ${space(1)};
  751. }
  752. `;
  753. const SearchContainer = styled('div')`
  754. display: flex;
  755. align-items: center;
  756. gap: ${space(1)};
  757. `;
  758. const StyledListItem = styled(ListItem)`
  759. margin-bottom: ${space(0.5)};
  760. font-size: ${p => p.theme.fontSizeExtraLarge};
  761. line-height: 1.3;
  762. `;
  763. const FormRow = styled('div')<{columns?: number; noMargin?: boolean}>`
  764. display: flex;
  765. flex-direction: row;
  766. align-items: center;
  767. flex-wrap: wrap;
  768. margin-bottom: ${p => (p.noMargin ? 0 : space(4))};
  769. ${p =>
  770. p.columns !== undefined &&
  771. css`
  772. display: grid;
  773. grid-template-columns: repeat(${p.columns}, auto);
  774. `}
  775. `;
  776. export default withApi(withProjects(withTags(RuleConditionsForm)));