ruleConditionsForm.tsx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. import {Fragment, PureComponent} from 'react';
  2. import {components} from 'react-select';
  3. import {css} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import omit from 'lodash/omit';
  6. import pick from 'lodash/pick';
  7. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  8. import {fetchTagValues} from 'sentry/actionCreators/tags';
  9. import type {Client} from 'sentry/api';
  10. import {
  11. OnDemandMetricAlert,
  12. OnDemandWarningIcon,
  13. } from 'sentry/components/alerts/onDemandMetricAlert';
  14. import {getHasTag} from 'sentry/components/events/searchBar';
  15. import {
  16. STATIC_FIELD_TAGS,
  17. STATIC_FIELD_TAGS_WITHOUT_ERROR_FIELDS,
  18. STATIC_FIELD_TAGS_WITHOUT_TRACING,
  19. STATIC_FIELD_TAGS_WITHOUT_TRANSACTION_FIELDS,
  20. STATIC_SEMVER_TAGS,
  21. STATIC_SPAN_TAGS,
  22. } from 'sentry/components/events/searchBarFieldConstants';
  23. import SelectControl from 'sentry/components/forms/controls/selectControl';
  24. import SelectField from 'sentry/components/forms/fields/selectField';
  25. import FormField from 'sentry/components/forms/formField';
  26. import IdBadge from 'sentry/components/idBadge';
  27. import ListItem from 'sentry/components/list/listItem';
  28. import {MetricSearchBar} from 'sentry/components/metrics/metricSearchBar';
  29. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  30. import Panel from 'sentry/components/panels/panel';
  31. import PanelBody from 'sentry/components/panels/panelBody';
  32. import {SearchQueryBuilder} from 'sentry/components/searchQueryBuilder';
  33. import {InvalidReason} from 'sentry/components/searchSyntax/parser';
  34. import {t, tct} from 'sentry/locale';
  35. import {space} from 'sentry/styles/space';
  36. import {ActivationConditionType, MonitorType} from 'sentry/types/alerts';
  37. import type {SelectValue} from 'sentry/types/core';
  38. import type {Tag, TagCollection} from 'sentry/types/group';
  39. import type {InjectedRouter} from 'sentry/types/legacyReactRouter';
  40. import type {Organization} from 'sentry/types/organization';
  41. import type {Environment, Project} from 'sentry/types/project';
  42. import {defined} from 'sentry/utils';
  43. import {isAggregateField, isMeasurement} from 'sentry/utils/discover/fields';
  44. import {getDisplayName} from 'sentry/utils/environment';
  45. import {DEVICE_CLASS_TAG_VALUES, FieldKind, isDeviceClass} from 'sentry/utils/fields';
  46. import {
  47. getMeasurements,
  48. type MeasurementCollection,
  49. } from 'sentry/utils/measurements/measurements';
  50. import {hasCustomMetrics} from 'sentry/utils/metrics/features';
  51. import {getMRI} from 'sentry/utils/metrics/mri';
  52. import {getOnDemandKeys, isOnDemandQueryString} from 'sentry/utils/onDemandMetrics';
  53. import {hasOnDemandMetricAlertFeature} from 'sentry/utils/onDemandMetrics/features';
  54. import withApi from 'sentry/utils/withApi';
  55. import withProjects from 'sentry/utils/withProjects';
  56. import withTags from 'sentry/utils/withTags';
  57. import WizardField from 'sentry/views/alerts/rules/metric/wizardField';
  58. import {
  59. convertDatasetEventTypesToSource,
  60. DATA_SOURCE_LABELS,
  61. DATA_SOURCE_TO_SET_AND_EVENT_TYPES,
  62. } from 'sentry/views/alerts/utils';
  63. import type {AlertType} from 'sentry/views/alerts/wizard/options';
  64. import {getSupportedAndOmittedTags} from 'sentry/views/alerts/wizard/options';
  65. import {getProjectOptions} from '../utils';
  66. import {isCrashFreeAlert} from './utils/isCrashFreeAlert';
  67. import {DEFAULT_AGGREGATE, DEFAULT_TRANSACTION_AGGREGATE} from './constants';
  68. import {AlertRuleComparisonType, 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. isForLlmMetric?: 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 === 'insights_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. if (this.props.comparisonType === AlertRuleComparisonType.DYNAMIC) {
  242. options = pick(TIME_WINDOW_MAP, [
  243. TimeWindow.FIVE_MINUTES,
  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. isForLlmMetric,
  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. {isForLlmMetric ? 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. comparisonType,
  598. } = this.props;
  599. const {environments, filterKeys} = this.state;
  600. const hasActivatedAlerts = organization.features.includes('activated-alert-rules');
  601. const environmentOptions: SelectValue<string | null>[] = [
  602. {
  603. value: null,
  604. label: t('All Environments'),
  605. },
  606. ...(environments?.map(env => ({value: env.name, label: getDisplayName(env)})) ??
  607. []),
  608. ];
  609. return (
  610. <Fragment>
  611. <ChartPanel>
  612. <StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody>
  613. </ChartPanel>
  614. {isTransactionMigration ? (
  615. <Fragment>
  616. <Spacer />
  617. <HiddenListItem />
  618. <HiddenListItem />
  619. </Fragment>
  620. ) : (
  621. <Fragment>
  622. {isExtrapolatedChartData && (
  623. <OnDemandMetricAlert
  624. message={t(
  625. 'The chart data above is an estimate based on the stored transactions that match the filters specified.'
  626. )}
  627. />
  628. )}
  629. {hasActivatedAlerts && this.renderMonitorTypeSelect()}
  630. {!isErrorMigration && this.renderInterval()}
  631. <StyledListItem>{t('Filter events')}</StyledListItem>
  632. <FormRow noMargin columns={1 + (allowChangeEventTypes ? 1 : 0) + 1}>
  633. {this.renderProjectSelector()}
  634. <SelectField
  635. name="environment"
  636. placeholder={t('All Environments')}
  637. style={{
  638. ...this.formElemBaseStyle,
  639. minWidth: 230,
  640. flex: 1,
  641. }}
  642. styles={{
  643. singleValue: (base: any) => ({
  644. ...base,
  645. }),
  646. option: (base: any) => ({
  647. ...base,
  648. }),
  649. }}
  650. options={environmentOptions}
  651. isDisabled={
  652. disabled || this.state.environments === null || isErrorMigration
  653. }
  654. isClearable
  655. inline={false}
  656. flexibleControlStateSize
  657. />
  658. {allowChangeEventTypes && this.renderEventTypeFilter()}
  659. </FormRow>
  660. <FormRow noMargin>
  661. <FormField
  662. name="query"
  663. inline={false}
  664. style={{
  665. ...this.formElemBaseStyle,
  666. flex: '6 0 500px',
  667. }}
  668. flexibleControlStateSize
  669. >
  670. {({onChange, onBlur, initialData, value}) => {
  671. return (hasCustomMetrics(organization) &&
  672. alertType === 'custom_metrics') ||
  673. alertType === 'insights_metrics' ? (
  674. <MetricSearchBar
  675. mri={getMRI(aggregate)}
  676. projectIds={[project.id]}
  677. placeholder={this.searchPlaceholder}
  678. query={initialData.query}
  679. defaultQuery={initialData?.query ?? ''}
  680. useFormWrapper={false}
  681. searchSource="alert_builder"
  682. onChange={query => {
  683. onFilterSearch(query, true);
  684. onChange(query, {});
  685. }}
  686. />
  687. ) : (
  688. <SearchContainer>
  689. <SearchQueryBuilder
  690. initialQuery={initialData?.query ?? ''}
  691. getTagValues={this.getEventFieldValues}
  692. placeholder={this.searchPlaceholder}
  693. searchSource="alert_builder"
  694. filterKeys={filterKeys}
  695. disabled={disabled || isErrorMigration}
  696. onChange={onChange}
  697. invalidMessages={{
  698. [InvalidReason.WILDCARD_NOT_ALLOWED]: t(
  699. 'The wildcard operator is not supported here.'
  700. ),
  701. [InvalidReason.FREE_TEXT_NOT_ALLOWED]: t(
  702. 'Free text search is not allowed. If you want to partially match transaction names, use glob patterns like "transaction:*transaction-name*"'
  703. ),
  704. }}
  705. onSearch={query => {
  706. onFilterSearch(query, true);
  707. onChange(query, {});
  708. }}
  709. onBlur={(query, {parsedQuery}) => {
  710. onFilterSearch(query, parsedQuery);
  711. onBlur(query);
  712. }}
  713. // We only need strict validation for Transaction queries, everything else is fine
  714. disallowUnsupportedFilters={
  715. organization.features.includes('alert-allow-indexed') ||
  716. (hasOnDemandMetricAlertFeature(organization) &&
  717. isOnDemandQueryString(value))
  718. ? false
  719. : dataset === Dataset.GENERIC_METRICS
  720. }
  721. />
  722. {isExtrapolatedChartData && isOnDemandQueryString(value) && (
  723. <OnDemandWarningIcon
  724. color="gray500"
  725. msg={tct(
  726. `We don’t routinely collect metrics from [fields]. However, we’ll do so [strong:once this alert has been saved.]`,
  727. {
  728. fields: (
  729. <strong>
  730. {getOnDemandKeys(value)
  731. .map(key => `"${key}"`)
  732. .join(', ')}
  733. </strong>
  734. ),
  735. strong: <strong />,
  736. }
  737. )}
  738. />
  739. )}
  740. </SearchContainer>
  741. );
  742. }}
  743. </FormField>
  744. </FormRow>
  745. <FormRow noMargin>
  746. <FormField
  747. name="query"
  748. inline={false}
  749. style={{
  750. ...this.formElemBaseStyle,
  751. flex: '6 0 500px',
  752. }}
  753. flexibleControlStateSize
  754. >
  755. {args => {
  756. if (
  757. args.value?.includes('is:unresolved') &&
  758. comparisonType === AlertRuleComparisonType.DYNAMIC
  759. ) {
  760. return (
  761. <OnDemandMetricAlert
  762. message={t(
  763. "'is:unresolved' queries are not supported by Anomaly Detection alerts."
  764. )}
  765. />
  766. );
  767. }
  768. return null;
  769. }}
  770. </FormField>
  771. </FormRow>
  772. </Fragment>
  773. )}
  774. </Fragment>
  775. );
  776. }
  777. }
  778. const StyledListTitle = styled('div')`
  779. display: flex;
  780. span {
  781. margin-left: ${space(1)};
  782. }
  783. `;
  784. // This is a temporary hacky solution to hide list items without changing the numbering of the rest of the list
  785. // TODO(issues): Remove this once the migration is complete
  786. const HiddenListItem = styled(ListItem)`
  787. position: absolute;
  788. width: 0px;
  789. height: 0px;
  790. opacity: 0;
  791. pointer-events: none;
  792. `;
  793. const Spacer = styled('div')`
  794. margin-bottom: ${space(2)};
  795. `;
  796. const ChartPanel = styled(Panel)`
  797. margin-bottom: ${space(1)};
  798. `;
  799. const StyledPanelBody = styled(PanelBody)`
  800. ol,
  801. h4 {
  802. margin-bottom: ${space(1)};
  803. }
  804. `;
  805. const SearchContainer = styled('div')`
  806. display: flex;
  807. align-items: center;
  808. gap: ${space(1)};
  809. `;
  810. const StyledListItem = styled(ListItem)`
  811. margin-bottom: ${space(0.5)};
  812. font-size: ${p => p.theme.fontSizeExtraLarge};
  813. line-height: 1.3;
  814. `;
  815. const FormRow = styled('div')<{columns?: number; noMargin?: boolean}>`
  816. display: flex;
  817. flex-direction: row;
  818. align-items: center;
  819. flex-wrap: wrap;
  820. margin-bottom: ${p => (p.noMargin ? 0 : space(4))};
  821. ${p =>
  822. p.columns !== undefined &&
  823. css`
  824. display: grid;
  825. grid-template-columns: repeat(${p.columns}, auto);
  826. `}
  827. `;
  828. const MonitorSelect = styled('div')`
  829. border-radius: ${p => p.theme.borderRadius};
  830. border: 1px solid ${p => p.theme.border};
  831. width: 100%;
  832. display: grid;
  833. grid-template-columns: 1fr 1fr;
  834. height: 5rem;
  835. `;
  836. type MonitorCardProps = {
  837. isSelected: boolean;
  838. /**
  839. * Adds hover and focus states to the card
  840. */
  841. position: 'left' | 'right';
  842. disabled?: boolean;
  843. };
  844. const MonitorCard = styled('div')<MonitorCardProps>`
  845. padding: ${space(1)} ${space(2)};
  846. display: flex;
  847. flex-grow: 1;
  848. flex-direction: column;
  849. cursor: ${p => (p.disabled || p.isSelected ? 'default' : 'pointer')};
  850. justify-content: center;
  851. background-color: ${p =>
  852. p.disabled && !p.isSelected ? p.theme.backgroundSecondary : p.theme.background};
  853. &:focus,
  854. &:hover {
  855. ${p =>
  856. p.disabled || p.isSelected
  857. ? ''
  858. : `
  859. outline: 1px solid ${p.theme.purple200};
  860. background-color: ${p.theme.backgroundSecondary};
  861. `}
  862. }
  863. border-top-left-radius: ${p => (p.position === 'left' ? p.theme.borderRadius : 0)};
  864. border-bottom-left-radius: ${p => (p.position === 'left' ? p.theme.borderRadius : 0)};
  865. border-top-right-radius: ${p => (p.position !== 'left' ? p.theme.borderRadius : 0)};
  866. border-bottom-right-radius: ${p => (p.position !== 'left' ? p.theme.borderRadius : 0)};
  867. margin: ${p =>
  868. p.isSelected ? (p.position === 'left' ? '1px 2px 1px 0' : '1px 0 1px 2px') : 0};
  869. outline: ${p => (p.isSelected ? `2px solid ${p.theme.purple400}` : 'none')};
  870. `;
  871. const ActivatedAlertFields = styled('div')`
  872. display: flex;
  873. align-items: center;
  874. justify-content: space-between;
  875. `;
  876. export default withApi(withProjects(withTags(RuleConditionsForm)));