ruleConditionsForm.tsx 34 KB

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