ruleConditionsForm.tsx 34 KB

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