ruleConditionsForm.tsx 33 KB

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