ruleConditionsForm.tsx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. import {Fragment, PureComponent} from 'react';
  2. import type {InjectedRouter} from 'react-router';
  3. import {components} from 'react-select';
  4. import {css} from '@emotion/react';
  5. import styled from '@emotion/styled';
  6. import omit from 'lodash/omit';
  7. import pick from 'lodash/pick';
  8. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  9. import {fetchTagValues} from 'sentry/actionCreators/tags';
  10. import type {Client} from 'sentry/api';
  11. import {
  12. OnDemandMetricAlert,
  13. OnDemandWarningIcon,
  14. } from 'sentry/components/alerts/onDemandMetricAlert';
  15. import SearchBar, {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 {SearchQueryBuilder} from 'sentry/components/searchQueryBuilder';
  34. import {InvalidReason} from 'sentry/components/searchSyntax/parser';
  35. import {SearchInvalidTag} from 'sentry/components/smartSearchBar/searchInvalidTag';
  36. import {t, tct} from 'sentry/locale';
  37. import {space} from 'sentry/styles/space';
  38. import type {Environment, Organization, Project, SelectValue} from 'sentry/types';
  39. import {ActivationConditionType, MonitorType} from 'sentry/types/alerts';
  40. import type {Tag, TagCollection} from 'sentry/types/group';
  41. import {defined} from 'sentry/utils';
  42. import {isAggregateField, isMeasurement} from 'sentry/utils/discover/fields';
  43. import {getDisplayName} from 'sentry/utils/environment';
  44. import {DEVICE_CLASS_TAG_VALUES, FieldKind, isDeviceClass} from 'sentry/utils/fields';
  45. import {
  46. getMeasurements,
  47. type MeasurementCollection,
  48. } from 'sentry/utils/measurements/measurements';
  49. import {hasCustomMetrics} from 'sentry/utils/metrics/features';
  50. import {getMRI} from 'sentry/utils/metrics/mri';
  51. import {getOnDemandKeys, isOnDemandQueryString} from 'sentry/utils/onDemandMetrics';
  52. import {hasOnDemandMetricAlertFeature} from 'sentry/utils/onDemandMetrics/features';
  53. import withApi from 'sentry/utils/withApi';
  54. import withProjects from 'sentry/utils/withProjects';
  55. import withTags from 'sentry/utils/withTags';
  56. import WizardField from 'sentry/views/alerts/rules/metric/wizardField';
  57. import {
  58. convertDatasetEventTypesToSource,
  59. DATA_SOURCE_LABELS,
  60. DATA_SOURCE_TO_SET_AND_EVENT_TYPES,
  61. } from 'sentry/views/alerts/utils';
  62. import type {AlertType} from 'sentry/views/alerts/wizard/options';
  63. import {getSupportedAndOmittedTags} from 'sentry/views/alerts/wizard/options';
  64. import {getProjectOptions} from '../utils';
  65. import {isCrashFreeAlert} from './utils/isCrashFreeAlert';
  66. import {DEFAULT_AGGREGATE, DEFAULT_TRANSACTION_AGGREGATE} from './constants';
  67. import type {AlertRuleComparisonType} from './types';
  68. import {Dataset, Datasource, TimeWindow} from './types';
  69. const TIME_WINDOW_MAP: Record<TimeWindow, string> = {
  70. [TimeWindow.ONE_MINUTE]: t('1 minute'),
  71. [TimeWindow.FIVE_MINUTES]: t('5 minutes'),
  72. [TimeWindow.TEN_MINUTES]: t('10 minutes'),
  73. [TimeWindow.FIFTEEN_MINUTES]: t('15 minutes'),
  74. [TimeWindow.THIRTY_MINUTES]: t('30 minutes'),
  75. [TimeWindow.ONE_HOUR]: t('1 hour'),
  76. [TimeWindow.TWO_HOURS]: t('2 hours'),
  77. [TimeWindow.FOUR_HOURS]: t('4 hours'),
  78. [TimeWindow.ONE_DAY]: t('24 hours'),
  79. };
  80. type Props = {
  81. aggregate: string;
  82. alertType: AlertType;
  83. api: Client;
  84. comparisonType: AlertRuleComparisonType;
  85. dataset: Dataset;
  86. disabled: boolean;
  87. isEditing: boolean;
  88. onComparisonDeltaChange: (value: number) => void;
  89. onFilterSearch: (query: string, isQueryValid) => void;
  90. onMonitorTypeSelect: (activatedAlertFields: {
  91. activationCondition?: ActivationConditionType | undefined;
  92. monitorType?: MonitorType;
  93. monitorWindowSuffix?: string | undefined;
  94. monitorWindowValue?: number | undefined;
  95. }) => void;
  96. onTimeWindowChange: (value: number) => void;
  97. organization: Organization;
  98. project: Project;
  99. projects: Project[];
  100. router: InjectedRouter;
  101. tags: TagCollection;
  102. thresholdChart: React.ReactNode;
  103. timeWindow: number;
  104. // optional props
  105. activationCondition?: ActivationConditionType;
  106. allowChangeEventTypes?: boolean;
  107. comparisonDelta?: number;
  108. disableProjectSelector?: boolean;
  109. isErrorMigration?: boolean;
  110. isExtrapolatedChartData?: boolean;
  111. isForSpanMetric?: boolean;
  112. isTransactionMigration?: boolean;
  113. loadingProjects?: boolean;
  114. monitorType?: number;
  115. };
  116. type State = {
  117. environments: Environment[] | null;
  118. filterKeys: TagCollection;
  119. measurements: MeasurementCollection;
  120. };
  121. class RuleConditionsForm extends PureComponent<Props, State> {
  122. state: State = {
  123. environments: null,
  124. measurements: {},
  125. filterKeys: {},
  126. };
  127. componentDidMount() {
  128. this.fetchData();
  129. const measurements = getMeasurements();
  130. const filterKeys = this.getFilterKeys();
  131. this.setState({measurements, filterKeys});
  132. }
  133. componentDidUpdate(prevProps: Props) {
  134. if (prevProps.project.id === this.props.project.id) {
  135. return;
  136. }
  137. this.fetchData();
  138. }
  139. getFilterKeys = () => {
  140. const {organization, dataset, tags} = this.props;
  141. const {measurements} = this.state;
  142. const measurementsWithKind = Object.keys(measurements).reduce(
  143. (measurement_tags, key) => {
  144. measurement_tags[key] = {
  145. ...measurements[key],
  146. kind: FieldKind.MEASUREMENT,
  147. };
  148. return measurement_tags;
  149. },
  150. {}
  151. );
  152. const orgHasPerformanceView = organization.features.includes('performance-view');
  153. const combinedTags: TagCollection =
  154. dataset === Dataset.ERRORS
  155. ? Object.assign({}, STATIC_FIELD_TAGS_WITHOUT_TRANSACTION_FIELDS)
  156. : dataset === Dataset.TRANSACTIONS
  157. ? Object.assign(
  158. {},
  159. measurementsWithKind,
  160. STATIC_SPAN_TAGS,
  161. STATIC_FIELD_TAGS_WITHOUT_ERROR_FIELDS
  162. )
  163. : orgHasPerformanceView
  164. ? Object.assign({}, measurementsWithKind, STATIC_SPAN_TAGS, STATIC_FIELD_TAGS)
  165. : Object.assign({}, STATIC_FIELD_TAGS_WITHOUT_TRACING);
  166. const tagsWithKind = Object.keys(tags).reduce<Record<string, Tag>>((acc, key) => {
  167. acc[key] = {
  168. ...tags[key],
  169. kind: FieldKind.TAG,
  170. };
  171. return acc;
  172. }, {});
  173. const {omitTags} = getSupportedAndOmittedTags(dataset, organization);
  174. Object.assign(combinedTags, tagsWithKind, STATIC_SEMVER_TAGS);
  175. combinedTags.has = getHasTag(combinedTags);
  176. const list =
  177. omitTags && omitTags.length > 0 ? omit(combinedTags, omitTags) : combinedTags;
  178. return list;
  179. };
  180. formElemBaseStyle = {
  181. padding: `${space(0.5)}`,
  182. border: 'none',
  183. };
  184. async fetchData() {
  185. const {api, organization, project} = this.props;
  186. try {
  187. const environments = await api.requestPromise(
  188. `/projects/${organization.slug}/${project.slug}/environments/`,
  189. {
  190. query: {
  191. visibility: 'visible',
  192. },
  193. }
  194. );
  195. this.setState({environments});
  196. } catch (_err) {
  197. addErrorMessage(t('Unable to fetch environments'));
  198. }
  199. }
  200. getEventFieldValues = async (tag, query): Promise<string[]> => {
  201. const {api, organization, project, dataset, router} = this.props;
  202. if (isAggregateField(tag.key) || isMeasurement(tag.key)) {
  203. // We can't really auto suggest values for aggregate fields
  204. // or measurements, so we simply don't
  205. // NOTE: these in particular are for discover queries. We may not need/support these
  206. return Promise.resolve([]);
  207. }
  208. // device.class is stored as "numbers" in snuba, but we want to suggest high, medium,
  209. // and low search filter values because discover maps device.class to these values.
  210. if (isDeviceClass(tag.key)) {
  211. return Promise.resolve(DEVICE_CLASS_TAG_VALUES);
  212. }
  213. const values = await fetchTagValues({
  214. api,
  215. orgSlug: organization.slug,
  216. tagKey: tag.key,
  217. search: query,
  218. projectIds: [project.id],
  219. endpointParams: normalizeDateTimeParams(router.location.query), // allows searching for tags on transactions as well
  220. includeTransactions: true, // allows searching for tags on sessions as well
  221. includeSessions: dataset === Dataset.SESSIONS,
  222. });
  223. return values.filter(({name}) => defined(name)).map(({name}) => name);
  224. };
  225. get timeWindowOptions() {
  226. let options: Record<string, string> = TIME_WINDOW_MAP;
  227. const {alertType} = this.props;
  228. if (alertType === 'custom_metrics' || alertType === 'span_metrics') {
  229. // Do not show ONE MINUTE interval as an option for custom_metrics alert
  230. options = omit(options, TimeWindow.ONE_MINUTE.toString());
  231. }
  232. if (isCrashFreeAlert(this.props.dataset)) {
  233. options = pick(TIME_WINDOW_MAP, [
  234. // TimeWindow.THIRTY_MINUTES, leaving this option out until we figure out the sub-hour session resolution chart limitations
  235. TimeWindow.ONE_HOUR,
  236. TimeWindow.TWO_HOURS,
  237. TimeWindow.FOUR_HOURS,
  238. TimeWindow.ONE_DAY,
  239. ]);
  240. }
  241. return Object.entries(options).map(([value, label]) => ({
  242. value: parseInt(value, 10),
  243. label: tct('[timeWindow] interval', {
  244. timeWindow: label.slice(-1) === 's' ? label.slice(0, -1) : label,
  245. }),
  246. }));
  247. }
  248. get searchPlaceholder() {
  249. switch (this.props.dataset) {
  250. case Dataset.ERRORS:
  251. return t('Filter events by level, message, and other properties\u2026');
  252. case Dataset.METRICS:
  253. case Dataset.SESSIONS:
  254. return t('Filter sessions by release version\u2026');
  255. default:
  256. return t('Filter transactions by URL, tags, and other properties\u2026');
  257. }
  258. }
  259. get selectControlStyles() {
  260. return {
  261. control: (provided: {[x: string]: string | number | boolean}) => ({
  262. ...provided,
  263. minWidth: 200,
  264. maxWidth: 300,
  265. }),
  266. container: (provided: {[x: string]: string | number | boolean}) => ({
  267. ...provided,
  268. margin: `${space(0.5)}`,
  269. }),
  270. };
  271. }
  272. renderEventTypeFilter() {
  273. const {organization, disabled, alertType, isErrorMigration} = this.props;
  274. const dataSourceOptions = [
  275. {
  276. label: t('Errors'),
  277. options: [
  278. {
  279. value: Datasource.ERROR_DEFAULT,
  280. label: DATA_SOURCE_LABELS[Datasource.ERROR_DEFAULT],
  281. },
  282. {
  283. value: Datasource.DEFAULT,
  284. label: DATA_SOURCE_LABELS[Datasource.DEFAULT],
  285. },
  286. {
  287. value: Datasource.ERROR,
  288. label: DATA_SOURCE_LABELS[Datasource.ERROR],
  289. },
  290. ],
  291. },
  292. ];
  293. if (
  294. organization.features.includes('performance-view') &&
  295. (alertType === 'custom_transactions' || alertType === 'custom_metrics')
  296. ) {
  297. dataSourceOptions.push({
  298. label: t('Transactions'),
  299. options: [
  300. {
  301. value: Datasource.TRANSACTION,
  302. label: DATA_SOURCE_LABELS[Datasource.TRANSACTION],
  303. },
  304. ],
  305. });
  306. }
  307. return (
  308. <FormField
  309. name="datasource"
  310. inline={false}
  311. style={{
  312. ...this.formElemBaseStyle,
  313. minWidth: 300,
  314. flex: 2,
  315. }}
  316. flexibleControlStateSize
  317. >
  318. {({onChange, onBlur, model}) => {
  319. const formDataset = model.getValue('dataset');
  320. const formEventTypes = model.getValue('eventTypes');
  321. const aggregate = model.getValue('aggregate');
  322. const mappedValue = convertDatasetEventTypesToSource(
  323. formDataset,
  324. formEventTypes
  325. );
  326. return (
  327. <SelectControl
  328. value={mappedValue}
  329. inFieldLabel={t('Events: ')}
  330. onChange={({value}) => {
  331. onChange(value, {});
  332. onBlur(value, {});
  333. // Reset the aggregate to the default (which works across
  334. // datatypes), otherwise we may send snuba an invalid query
  335. // (transaction aggregate on events datasource = bad).
  336. const newAggregate =
  337. value === Datasource.TRANSACTION
  338. ? DEFAULT_TRANSACTION_AGGREGATE
  339. : DEFAULT_AGGREGATE;
  340. if (alertType === 'custom_transactions' && aggregate !== newAggregate) {
  341. model.setValue('aggregate', newAggregate);
  342. }
  343. // set the value of the dataset and event type from data source
  344. const {dataset: datasetFromDataSource, eventTypes} =
  345. DATA_SOURCE_TO_SET_AND_EVENT_TYPES[value] ?? {};
  346. model.setValue('dataset', datasetFromDataSource);
  347. model.setValue('eventTypes', eventTypes);
  348. }}
  349. options={dataSourceOptions}
  350. isDisabled={disabled || isErrorMigration}
  351. />
  352. );
  353. }}
  354. </FormField>
  355. );
  356. }
  357. renderProjectSelector() {
  358. const {
  359. project: _selectedProject,
  360. projects, // note: org projects
  361. disabled,
  362. organization,
  363. disableProjectSelector,
  364. } = this.props;
  365. const projectOptions = getProjectOptions({
  366. organization,
  367. projects,
  368. isFormDisabled: disabled,
  369. });
  370. return (
  371. <FormField
  372. name="projectId"
  373. inline={false}
  374. style={{
  375. ...this.formElemBaseStyle,
  376. minWidth: 300,
  377. flex: 2,
  378. }}
  379. flexibleControlStateSize
  380. >
  381. {({onChange, onBlur, model}) => {
  382. const selectedProject =
  383. projects.find(({id}) => id === model.getValue('projectId')) ||
  384. _selectedProject;
  385. return (
  386. <SelectControl
  387. isDisabled={disabled || disableProjectSelector}
  388. value={selectedProject.id}
  389. options={projectOptions}
  390. onChange={({value}: {value: Project['id']}) => {
  391. // if the current owner/team isn't part of project selected, update to the first available team
  392. const nextSelectedProject =
  393. projects.find(({id}) => id === value) ?? selectedProject;
  394. const ownerId: string | undefined = model
  395. .getValue('owner')
  396. ?.split(':')[1];
  397. if (
  398. ownerId &&
  399. nextSelectedProject.teams.find(({id}) => id === ownerId) ===
  400. undefined &&
  401. nextSelectedProject.teams.length
  402. ) {
  403. model.setValue('owner', `team:${nextSelectedProject.teams[0].id}`);
  404. }
  405. onChange(value, {});
  406. onBlur(value, {});
  407. }}
  408. components={{
  409. SingleValue: containerProps => (
  410. <components.ValueContainer {...containerProps}>
  411. <IdBadge
  412. project={selectedProject}
  413. avatarProps={{consistentWidth: true}}
  414. avatarSize={18}
  415. disableLink
  416. />
  417. </components.ValueContainer>
  418. ),
  419. }}
  420. />
  421. );
  422. }}
  423. </FormField>
  424. );
  425. }
  426. renderInterval() {
  427. const {
  428. organization,
  429. disabled,
  430. alertType,
  431. timeWindow,
  432. onTimeWindowChange,
  433. project,
  434. monitorType,
  435. isForSpanMetric,
  436. } = this.props;
  437. return (
  438. <Fragment>
  439. <StyledListItem>
  440. <StyledListTitle>
  441. <div>{t('Define your metric')}</div>
  442. </StyledListTitle>
  443. </StyledListItem>
  444. <FormRow>
  445. {isForSpanMetric ? null : (
  446. <WizardField
  447. name="aggregate"
  448. help={null}
  449. organization={organization}
  450. disabled={disabled}
  451. project={project}
  452. style={{
  453. ...this.formElemBaseStyle,
  454. flex: 1,
  455. }}
  456. inline={false}
  457. flexibleControlStateSize
  458. columnWidth={200}
  459. alertType={alertType}
  460. required
  461. />
  462. )}
  463. {monitorType !== MonitorType.ACTIVATED && (
  464. <SelectControl
  465. name="timeWindow"
  466. styles={this.selectControlStyles}
  467. options={this.timeWindowOptions}
  468. required={monitorType === MonitorType.CONTINUOUS}
  469. isDisabled={disabled}
  470. value={timeWindow}
  471. onChange={({value}) => onTimeWindowChange(value)}
  472. inline={false}
  473. flexibleControlStateSize
  474. />
  475. )}
  476. </FormRow>
  477. </Fragment>
  478. );
  479. }
  480. renderMonitorTypeSelect() {
  481. // TODO: disable select on edit
  482. const {
  483. activationCondition,
  484. isEditing,
  485. monitorType,
  486. onMonitorTypeSelect,
  487. onTimeWindowChange,
  488. timeWindow,
  489. } = this.props;
  490. return (
  491. <Fragment>
  492. <StyledListItem>
  493. <StyledListTitle>
  494. <div>{t('Select Monitor Type')}</div>
  495. </StyledListTitle>
  496. </StyledListItem>
  497. <FormRow>
  498. <MonitorSelect>
  499. <MonitorCard
  500. disabled={isEditing}
  501. position="left"
  502. isSelected={monitorType === MonitorType.CONTINUOUS}
  503. onClick={() =>
  504. isEditing
  505. ? null
  506. : onMonitorTypeSelect({
  507. monitorType: MonitorType.CONTINUOUS,
  508. })
  509. }
  510. >
  511. <strong>{t('Continuous')}</strong>
  512. <div>{t('Continuously monitor trends for the metrics outlined below')}</div>
  513. </MonitorCard>
  514. <MonitorCard
  515. disabled={isEditing}
  516. position="right"
  517. isSelected={monitorType === MonitorType.ACTIVATED}
  518. onClick={() =>
  519. isEditing
  520. ? null
  521. : onMonitorTypeSelect({
  522. monitorType: MonitorType.ACTIVATED,
  523. })
  524. }
  525. >
  526. <strong>Conditional</strong>
  527. {monitorType === MonitorType.ACTIVATED ? (
  528. <ActivatedAlertFields>
  529. {`${t('Monitor')} `}
  530. <SelectControl
  531. name="activationCondition"
  532. styles={this.selectControlStyles}
  533. disabled={isEditing}
  534. options={[
  535. {
  536. value: ActivationConditionType.RELEASE_CREATION,
  537. label: t('New Release'),
  538. },
  539. {
  540. value: ActivationConditionType.DEPLOY_CREATION,
  541. label: t('New Deploy'),
  542. },
  543. ]}
  544. required
  545. value={activationCondition}
  546. onChange={({value}) =>
  547. onMonitorTypeSelect({activationCondition: value})
  548. }
  549. inline={false}
  550. flexibleControlStateSize
  551. size="xs"
  552. />
  553. {` ${t('for')} `}
  554. <SelectControl
  555. name="timeWindow"
  556. styles={this.selectControlStyles}
  557. options={this.timeWindowOptions}
  558. value={timeWindow}
  559. onChange={({value}) => onTimeWindowChange(value)}
  560. inline={false}
  561. flexibleControlStateSize
  562. size="xs"
  563. />
  564. </ActivatedAlertFields>
  565. ) : (
  566. <div>
  567. {t('Temporarily monitor specified query given activation condition')}
  568. </div>
  569. )}
  570. </MonitorCard>
  571. </MonitorSelect>
  572. </FormRow>
  573. </Fragment>
  574. );
  575. }
  576. render() {
  577. const {
  578. alertType,
  579. organization,
  580. disabled,
  581. onFilterSearch,
  582. allowChangeEventTypes,
  583. dataset,
  584. isExtrapolatedChartData,
  585. isTransactionMigration,
  586. isErrorMigration,
  587. aggregate,
  588. project,
  589. } = this.props;
  590. const {environments, filterKeys} = this.state;
  591. const hasActivatedAlerts = organization.features.includes('activated-alert-rules');
  592. const environmentOptions: SelectValue<string | null>[] = [
  593. {
  594. value: null,
  595. label: t('All Environments'),
  596. },
  597. ...(environments?.map(env => ({value: env.name, label: getDisplayName(env)})) ??
  598. []),
  599. ];
  600. return (
  601. <Fragment>
  602. <ChartPanel>
  603. <StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody>
  604. </ChartPanel>
  605. {isTransactionMigration ? (
  606. <Fragment>
  607. <Spacer />
  608. <HiddenListItem />
  609. <HiddenListItem />
  610. </Fragment>
  611. ) : (
  612. <Fragment>
  613. {isExtrapolatedChartData && (
  614. <OnDemandMetricAlert
  615. message={t(
  616. 'The chart data above is an estimate based on the stored transactions that match the filters specified.'
  617. )}
  618. />
  619. )}
  620. {hasActivatedAlerts && this.renderMonitorTypeSelect()}
  621. {!isErrorMigration && this.renderInterval()}
  622. <StyledListItem>{t('Filter events')}</StyledListItem>
  623. <FormRow noMargin columns={1 + (allowChangeEventTypes ? 1 : 0) + 1}>
  624. {this.renderProjectSelector()}
  625. <SelectField
  626. name="environment"
  627. placeholder={t('All Environments')}
  628. style={{
  629. ...this.formElemBaseStyle,
  630. minWidth: 230,
  631. flex: 1,
  632. }}
  633. styles={{
  634. singleValue: (base: any) => ({
  635. ...base,
  636. }),
  637. option: (base: any) => ({
  638. ...base,
  639. }),
  640. }}
  641. options={environmentOptions}
  642. isDisabled={
  643. disabled || this.state.environments === null || isErrorMigration
  644. }
  645. isClearable
  646. inline={false}
  647. flexibleControlStateSize
  648. />
  649. {allowChangeEventTypes && this.renderEventTypeFilter()}
  650. </FormRow>
  651. <FormRow>
  652. <FormField
  653. name="query"
  654. inline={false}
  655. style={{
  656. ...this.formElemBaseStyle,
  657. flex: '6 0 500px',
  658. }}
  659. flexibleControlStateSize
  660. >
  661. {({onChange, onBlur, onKeyDown, initialData, value}) => {
  662. return hasCustomMetrics(organization) &&
  663. alertType === 'custom_metrics' ? (
  664. <MetricSearchBar
  665. mri={getMRI(aggregate)}
  666. projectIds={[project.id]}
  667. placeholder={this.searchPlaceholder}
  668. query={initialData.query}
  669. defaultQuery={initialData?.query ?? ''}
  670. useFormWrapper={false}
  671. searchSource="alert_builder"
  672. onChange={query => {
  673. onFilterSearch(query, true);
  674. onChange(query, {});
  675. }}
  676. />
  677. ) : (
  678. <SearchContainer>
  679. {organization.features.includes('search-query-builder-alerts') ? (
  680. <SearchQueryBuilder
  681. initialQuery={initialData?.query ?? ''}
  682. getTagValues={this.getEventFieldValues}
  683. placeholder={this.searchPlaceholder}
  684. searchSource="alert_builder"
  685. filterKeys={filterKeys}
  686. disabled={disabled || isErrorMigration}
  687. onChange={onChange}
  688. invalidMessages={{
  689. [InvalidReason.WILDCARD_NOT_ALLOWED]: t(
  690. 'The wildcard operator is not supported here.'
  691. ),
  692. [InvalidReason.FREE_TEXT_NOT_ALLOWED]: t(
  693. 'Free text search is not allowed. If you want to partially match transaction names, use glob patterns like "transaction:*transaction-name*"'
  694. ),
  695. }}
  696. onSearch={query => {
  697. onFilterSearch(query, true);
  698. onChange(query, {});
  699. }}
  700. onBlur={(query, {parsedQuery}) => {
  701. onFilterSearch(query, parsedQuery);
  702. onBlur(query);
  703. }}
  704. // We only need strict validation for Transaction queries, everything else is fine
  705. disallowUnsupportedFilters={
  706. organization.features.includes('alert-allow-indexed') ||
  707. (hasOnDemandMetricAlertFeature(organization) &&
  708. isOnDemandQueryString(value))
  709. ? false
  710. : dataset === Dataset.GENERIC_METRICS
  711. }
  712. />
  713. ) : (
  714. <StyledSearchBar
  715. disallowWildcard={dataset === Dataset.SESSIONS}
  716. disallowFreeText={[
  717. Dataset.GENERIC_METRICS,
  718. Dataset.TRANSACTIONS,
  719. ].includes(dataset)}
  720. invalidMessages={{
  721. [InvalidReason.WILDCARD_NOT_ALLOWED]: t(
  722. 'The wildcard operator is not supported here.'
  723. ),
  724. [InvalidReason.FREE_TEXT_NOT_ALLOWED]: t(
  725. 'Free text search is not allowed. If you want to partially match transaction names, use glob patterns like "transaction:*transaction-name*"'
  726. ),
  727. }}
  728. customInvalidTagMessage={item => {
  729. if (dataset !== Dataset.GENERIC_METRICS) {
  730. return null;
  731. }
  732. return (
  733. <SearchInvalidTag
  734. message={tct(
  735. "The field [field] isn't supported for performance alerts.",
  736. {
  737. field: <code>{item.desc}</code>,
  738. }
  739. )}
  740. docLink="https://docs.sentry.io/product/alerts/create-alerts/metric-alert-config/#tags--properties"
  741. />
  742. );
  743. }}
  744. searchSource="alert_builder"
  745. defaultQuery={initialData?.query ?? ''}
  746. {...getSupportedAndOmittedTags(dataset, organization)}
  747. includeSessionTagsValues={dataset === Dataset.SESSIONS}
  748. disabled={disabled || isErrorMigration}
  749. useFormWrapper={false}
  750. organization={organization}
  751. placeholder={this.searchPlaceholder}
  752. onChange={onChange}
  753. query={initialData.query}
  754. // We only need strict validation for Transaction queries, everything else is fine
  755. highlightUnsupportedTags={
  756. organization.features.includes('alert-allow-indexed') ||
  757. (hasOnDemandMetricAlertFeature(organization) &&
  758. isOnDemandQueryString(value))
  759. ? false
  760. : dataset === Dataset.GENERIC_METRICS
  761. }
  762. onKeyDown={e => {
  763. /**
  764. * Do not allow enter key to submit the alerts form since it is unlikely
  765. * users will be ready to create the rule as this sits above required fields.
  766. */
  767. if (e.key === 'Enter') {
  768. e.preventDefault();
  769. e.stopPropagation();
  770. }
  771. onKeyDown?.(e);
  772. }}
  773. onClose={(query, {validSearch}) => {
  774. onFilterSearch(query, validSearch);
  775. onBlur(query);
  776. }}
  777. onSearch={query => {
  778. onFilterSearch(query, true);
  779. onChange(query, {});
  780. }}
  781. hasRecentSearches={dataset !== Dataset.SESSIONS}
  782. />
  783. )}
  784. {isExtrapolatedChartData && isOnDemandQueryString(value) && (
  785. <OnDemandWarningIcon
  786. color="gray500"
  787. msg={tct(
  788. `We don’t routinely collect metrics from [fields]. However, we’ll do so [strong:once this alert has been saved.]`,
  789. {
  790. fields: (
  791. <strong>
  792. {getOnDemandKeys(value)
  793. .map(key => `"${key}"`)
  794. .join(', ')}
  795. </strong>
  796. ),
  797. strong: <strong />,
  798. }
  799. )}
  800. />
  801. )}
  802. </SearchContainer>
  803. );
  804. }}
  805. </FormField>
  806. </FormRow>
  807. </Fragment>
  808. )}
  809. </Fragment>
  810. );
  811. }
  812. }
  813. const StyledListTitle = styled('div')`
  814. display: flex;
  815. span {
  816. margin-left: ${space(1)};
  817. }
  818. `;
  819. // This is a temporary hacky solution to hide list items without changing the numbering of the rest of the list
  820. // TODO(issues): Remove this once the migration is complete
  821. const HiddenListItem = styled(ListItem)`
  822. position: absolute;
  823. width: 0px;
  824. height: 0px;
  825. opacity: 0;
  826. pointer-events: none;
  827. `;
  828. const Spacer = styled('div')`
  829. margin-bottom: ${space(2)};
  830. `;
  831. const ChartPanel = styled(Panel)`
  832. margin-bottom: ${space(1)};
  833. `;
  834. const StyledPanelBody = styled(PanelBody)`
  835. ol,
  836. h4 {
  837. margin-bottom: ${space(1)};
  838. }
  839. `;
  840. const SearchContainer = styled('div')`
  841. display: flex;
  842. align-items: center;
  843. gap: ${space(1)};
  844. `;
  845. const StyledSearchBar = styled(SearchBar)`
  846. flex-grow: 1;
  847. ${p =>
  848. p.disabled &&
  849. `
  850. background: ${p.theme.backgroundSecondary};
  851. color: ${p.theme.disabled};
  852. cursor: not-allowed;
  853. `}
  854. `;
  855. const StyledListItem = styled(ListItem)`
  856. margin-bottom: ${space(0.5)};
  857. font-size: ${p => p.theme.fontSizeExtraLarge};
  858. line-height: 1.3;
  859. `;
  860. const FormRow = styled('div')<{columns?: number; noMargin?: boolean}>`
  861. display: flex;
  862. flex-direction: row;
  863. align-items: center;
  864. flex-wrap: wrap;
  865. margin-bottom: ${p => (p.noMargin ? 0 : space(4))};
  866. ${p =>
  867. p.columns !== undefined &&
  868. css`
  869. display: grid;
  870. grid-template-columns: repeat(${p.columns}, auto);
  871. `}
  872. `;
  873. const MonitorSelect = styled('div')`
  874. border-radius: ${p => p.theme.borderRadius};
  875. border: 1px solid ${p => p.theme.border};
  876. width: 100%;
  877. display: grid;
  878. grid-template-columns: 1fr 1fr;
  879. height: 5rem;
  880. `;
  881. type MonitorCardProps = {
  882. isSelected: boolean;
  883. /**
  884. * Adds hover and focus states to the card
  885. */
  886. position: 'left' | 'right';
  887. disabled?: boolean;
  888. };
  889. const MonitorCard = styled('div')<MonitorCardProps>`
  890. padding: ${space(1)} ${space(2)};
  891. display: flex;
  892. flex-grow: 1;
  893. flex-direction: column;
  894. cursor: ${p => (p.disabled || p.isSelected ? 'default' : 'pointer')};
  895. justify-content: center;
  896. background-color: ${p =>
  897. p.disabled && !p.isSelected ? p.theme.backgroundSecondary : p.theme.background};
  898. &:focus,
  899. &:hover {
  900. ${p =>
  901. p.disabled || p.isSelected
  902. ? ''
  903. : `
  904. outline: 1px solid ${p.theme.purple200};
  905. background-color: ${p.theme.backgroundSecondary};
  906. `}
  907. }
  908. border-top-left-radius: ${p => (p.position === 'left' ? p.theme.borderRadius : 0)};
  909. border-bottom-left-radius: ${p => (p.position === 'left' ? p.theme.borderRadius : 0)};
  910. border-top-right-radius: ${p => (p.position !== 'left' ? p.theme.borderRadius : 0)};
  911. border-bottom-right-radius: ${p => (p.position !== 'left' ? p.theme.borderRadius : 0)};
  912. margin: ${p =>
  913. p.isSelected ? (p.position === 'left' ? '1px 2px 1px 0' : '1px 0 1px 2px') : 0};
  914. outline: ${p => (p.isSelected ? `2px solid ${p.theme.purple400}` : 'none')};
  915. `;
  916. const ActivatedAlertFields = styled('div')`
  917. display: flex;
  918. align-items: center;
  919. justify-content: space-between;
  920. `;
  921. export default withApi(withProjects(withTags(RuleConditionsForm)));