ruleConditionsForm.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. import {Fragment, PureComponent} from 'react';
  2. import {InjectedRouter} from 'react-router';
  3. import {components} from 'react-select';
  4. import {css} from '@emotion/react';
  5. import styled from '@emotion/styled';
  6. import pick from 'lodash/pick';
  7. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  8. import {Client} from 'sentry/api';
  9. import {
  10. OnDemandMetricAlert,
  11. OnDemandWarningIcon,
  12. } from 'sentry/components/alerts/onDemandMetricAlert';
  13. import SearchBar from 'sentry/components/events/searchBar';
  14. import SelectControl from 'sentry/components/forms/controls/selectControl';
  15. import SelectField from 'sentry/components/forms/fields/selectField';
  16. import FormField from 'sentry/components/forms/formField';
  17. import IdBadge from 'sentry/components/idBadge';
  18. import ListItem from 'sentry/components/list/listItem';
  19. import Panel from 'sentry/components/panels/panel';
  20. import PanelBody from 'sentry/components/panels/panelBody';
  21. import {InvalidReason} from 'sentry/components/searchSyntax/parser';
  22. import {SearchInvalidTag} from 'sentry/components/smartSearchBar/searchInvalidTag';
  23. import {t, tct} from 'sentry/locale';
  24. import {space} from 'sentry/styles/space';
  25. import {Environment, Organization, Project, SelectValue} from 'sentry/types';
  26. import {getDisplayName} from 'sentry/utils/environment';
  27. import {hasDDMFeature} from 'sentry/utils/metrics/features';
  28. import {getMRI} from 'sentry/utils/metrics/mri';
  29. import {getOnDemandKeys, isOnDemandQueryString} from 'sentry/utils/onDemandMetrics';
  30. import {hasOnDemandMetricAlertFeature} from 'sentry/utils/onDemandMetrics/features';
  31. import withApi from 'sentry/utils/withApi';
  32. import withProjects from 'sentry/utils/withProjects';
  33. import WizardField from 'sentry/views/alerts/rules/metric/wizardField';
  34. import {
  35. convertDatasetEventTypesToSource,
  36. DATA_SOURCE_LABELS,
  37. DATA_SOURCE_TO_SET_AND_EVENT_TYPES,
  38. } from 'sentry/views/alerts/utils';
  39. import {AlertType, getSupportedAndOmittedTags} from 'sentry/views/alerts/wizard/options';
  40. import {MetricSearchBar} from 'sentry/views/ddm/metricSearchBar';
  41. import {getProjectOptions} from '../utils';
  42. import {isCrashFreeAlert} from './utils/isCrashFreeAlert';
  43. import {DEFAULT_AGGREGATE, DEFAULT_TRANSACTION_AGGREGATE} from './constants';
  44. import {AlertRuleComparisonType, Dataset, Datasource, TimeWindow} from './types';
  45. const TIME_WINDOW_MAP: Record<TimeWindow, string> = {
  46. [TimeWindow.ONE_MINUTE]: t('1 minute'),
  47. [TimeWindow.FIVE_MINUTES]: t('5 minutes'),
  48. [TimeWindow.TEN_MINUTES]: t('10 minutes'),
  49. [TimeWindow.FIFTEEN_MINUTES]: t('15 minutes'),
  50. [TimeWindow.THIRTY_MINUTES]: t('30 minutes'),
  51. [TimeWindow.ONE_HOUR]: t('1 hour'),
  52. [TimeWindow.TWO_HOURS]: t('2 hours'),
  53. [TimeWindow.FOUR_HOURS]: t('4 hours'),
  54. [TimeWindow.ONE_DAY]: t('24 hours'),
  55. };
  56. type Props = {
  57. aggregate: string;
  58. alertType: AlertType;
  59. api: Client;
  60. comparisonType: AlertRuleComparisonType;
  61. dataset: Dataset;
  62. disabled: boolean;
  63. onComparisonDeltaChange: (value: number) => void;
  64. onFilterSearch: (query: string, isQueryValid) => void;
  65. onTimeWindowChange: (value: number) => void;
  66. organization: Organization;
  67. project: Project;
  68. projects: Project[];
  69. router: InjectedRouter;
  70. thresholdChart: React.ReactNode;
  71. timeWindow: number;
  72. allowChangeEventTypes?: boolean;
  73. comparisonDelta?: number;
  74. disableProjectSelector?: boolean;
  75. isErrorMigration?: boolean;
  76. isExtrapolatedChartData?: boolean;
  77. isTransactionMigration?: boolean;
  78. loadingProjects?: boolean;
  79. };
  80. type State = {
  81. environments: Environment[] | null;
  82. };
  83. class RuleConditionsForm extends PureComponent<Props, State> {
  84. state: State = {
  85. environments: null,
  86. };
  87. componentDidMount() {
  88. this.fetchData();
  89. }
  90. componentDidUpdate(prevProps: Props) {
  91. if (prevProps.project.id === this.props.project.id) {
  92. return;
  93. }
  94. this.fetchData();
  95. }
  96. formElemBaseStyle = {
  97. padding: `${space(0.5)}`,
  98. border: 'none',
  99. };
  100. async fetchData() {
  101. const {api, organization, project} = this.props;
  102. try {
  103. const environments = await api.requestPromise(
  104. `/projects/${organization.slug}/${project.slug}/environments/`,
  105. {
  106. query: {
  107. visibility: 'visible',
  108. },
  109. }
  110. );
  111. this.setState({environments});
  112. } catch (_err) {
  113. addErrorMessage(t('Unable to fetch environments'));
  114. }
  115. }
  116. get timeWindowOptions() {
  117. let options: Record<string, string> = TIME_WINDOW_MAP;
  118. if (isCrashFreeAlert(this.props.dataset)) {
  119. options = pick(TIME_WINDOW_MAP, [
  120. // TimeWindow.THIRTY_MINUTES, leaving this option out until we figure out the sub-hour session resolution chart limitations
  121. TimeWindow.ONE_HOUR,
  122. TimeWindow.TWO_HOURS,
  123. TimeWindow.FOUR_HOURS,
  124. TimeWindow.ONE_DAY,
  125. ]);
  126. }
  127. return Object.entries(options).map(([value, label]) => ({
  128. value: parseInt(value, 10),
  129. label: tct('[timeWindow] interval', {
  130. timeWindow: label.slice(-1) === 's' ? label.slice(0, -1) : label,
  131. }),
  132. }));
  133. }
  134. get searchPlaceholder() {
  135. switch (this.props.dataset) {
  136. case Dataset.ERRORS:
  137. return t('Filter events by level, message, and other properties\u2026');
  138. case Dataset.METRICS:
  139. case Dataset.SESSIONS:
  140. return t('Filter sessions by release version\u2026');
  141. default:
  142. return t('Filter transactions by URL, tags, and other properties\u2026');
  143. }
  144. }
  145. renderEventTypeFilter() {
  146. const {organization, disabled, alertType, isErrorMigration} = this.props;
  147. const dataSourceOptions = [
  148. {
  149. label: t('Errors'),
  150. options: [
  151. {
  152. value: Datasource.ERROR_DEFAULT,
  153. label: DATA_SOURCE_LABELS[Datasource.ERROR_DEFAULT],
  154. },
  155. {
  156. value: Datasource.DEFAULT,
  157. label: DATA_SOURCE_LABELS[Datasource.DEFAULT],
  158. },
  159. {
  160. value: Datasource.ERROR,
  161. label: DATA_SOURCE_LABELS[Datasource.ERROR],
  162. },
  163. ],
  164. },
  165. ];
  166. if (
  167. organization.features.includes('performance-view') &&
  168. (alertType === 'custom_transactions' || alertType === 'custom_metrics')
  169. ) {
  170. dataSourceOptions.push({
  171. label: t('Transactions'),
  172. options: [
  173. {
  174. value: Datasource.TRANSACTION,
  175. label: DATA_SOURCE_LABELS[Datasource.TRANSACTION],
  176. },
  177. ],
  178. });
  179. }
  180. return (
  181. <FormField
  182. name="datasource"
  183. inline={false}
  184. style={{
  185. ...this.formElemBaseStyle,
  186. minWidth: 300,
  187. flex: 2,
  188. }}
  189. flexibleControlStateSize
  190. >
  191. {({onChange, onBlur, model}) => {
  192. const formDataset = model.getValue('dataset');
  193. const formEventTypes = model.getValue('eventTypes');
  194. const aggregate = model.getValue('aggregate');
  195. const mappedValue = convertDatasetEventTypesToSource(
  196. formDataset,
  197. formEventTypes
  198. );
  199. return (
  200. <SelectControl
  201. value={mappedValue}
  202. inFieldLabel={t('Events: ')}
  203. onChange={({value}) => {
  204. onChange(value, {});
  205. onBlur(value, {});
  206. // Reset the aggregate to the default (which works across
  207. // datatypes), otherwise we may send snuba an invalid query
  208. // (transaction aggregate on events datasource = bad).
  209. const newAggregate =
  210. value === Datasource.TRANSACTION
  211. ? DEFAULT_TRANSACTION_AGGREGATE
  212. : DEFAULT_AGGREGATE;
  213. if (alertType === 'custom_transactions' && aggregate !== newAggregate) {
  214. model.setValue('aggregate', newAggregate);
  215. }
  216. // set the value of the dataset and event type from data source
  217. const {dataset: datasetFromDataSource, eventTypes} =
  218. DATA_SOURCE_TO_SET_AND_EVENT_TYPES[value] ?? {};
  219. model.setValue('dataset', datasetFromDataSource);
  220. model.setValue('eventTypes', eventTypes);
  221. }}
  222. options={dataSourceOptions}
  223. isDisabled={disabled || isErrorMigration}
  224. />
  225. );
  226. }}
  227. </FormField>
  228. );
  229. }
  230. renderProjectSelector() {
  231. const {
  232. project: _selectedProject,
  233. projects,
  234. disabled,
  235. organization,
  236. disableProjectSelector,
  237. } = this.props;
  238. const projectOptions = getProjectOptions({
  239. organization,
  240. projects,
  241. isFormDisabled: disabled,
  242. });
  243. return (
  244. <FormField
  245. name="projectId"
  246. inline={false}
  247. style={{
  248. ...this.formElemBaseStyle,
  249. minWidth: 300,
  250. flex: 2,
  251. }}
  252. flexibleControlStateSize
  253. >
  254. {({onChange, onBlur, model}) => {
  255. const selectedProject =
  256. projects.find(({id}) => id === model.getValue('projectId')) ||
  257. _selectedProject;
  258. return (
  259. <SelectControl
  260. isDisabled={disabled || disableProjectSelector}
  261. value={selectedProject.id}
  262. options={projectOptions}
  263. onChange={({value}: {value: Project['id']}) => {
  264. // if the current owner/team isn't part of project selected, update to the first available team
  265. const nextSelectedProject =
  266. projects.find(({id}) => id === value) ?? selectedProject;
  267. const ownerId: string | undefined = model
  268. .getValue('owner')
  269. ?.split(':')[1];
  270. if (
  271. ownerId &&
  272. nextSelectedProject.teams.find(({id}) => id === ownerId) ===
  273. undefined &&
  274. nextSelectedProject.teams.length
  275. ) {
  276. model.setValue('owner', `team:${nextSelectedProject.teams[0].id}`);
  277. }
  278. onChange(value, {});
  279. onBlur(value, {});
  280. }}
  281. components={{
  282. SingleValue: containerProps => (
  283. <components.ValueContainer {...containerProps}>
  284. <IdBadge
  285. project={selectedProject}
  286. avatarProps={{consistentWidth: true}}
  287. avatarSize={18}
  288. disableLink
  289. />
  290. </components.ValueContainer>
  291. ),
  292. }}
  293. />
  294. );
  295. }}
  296. </FormField>
  297. );
  298. }
  299. renderInterval() {
  300. const {organization, disabled, alertType, timeWindow, onTimeWindowChange, project} =
  301. this.props;
  302. return (
  303. <Fragment>
  304. <StyledListItem>
  305. <StyledListTitle>
  306. <div>{t('Define your metric')}</div>
  307. </StyledListTitle>
  308. </StyledListItem>
  309. <FormRow>
  310. <WizardField
  311. name="aggregate"
  312. help={null}
  313. organization={organization}
  314. disabled={disabled}
  315. project={project}
  316. style={{
  317. ...this.formElemBaseStyle,
  318. flex: 1,
  319. }}
  320. inline={false}
  321. flexibleControlStateSize
  322. columnWidth={200}
  323. alertType={alertType}
  324. required
  325. />
  326. <SelectControl
  327. name="timeWindow"
  328. styles={{
  329. control: (provided: {[x: string]: string | number | boolean}) => ({
  330. ...provided,
  331. minWidth: 200,
  332. maxWidth: 300,
  333. }),
  334. container: (provided: {[x: string]: string | number | boolean}) => ({
  335. ...provided,
  336. margin: `${space(0.5)}`,
  337. }),
  338. }}
  339. options={this.timeWindowOptions}
  340. required
  341. isDisabled={disabled}
  342. value={timeWindow}
  343. onChange={({value}) => onTimeWindowChange(value)}
  344. inline={false}
  345. flexibleControlStateSize
  346. />
  347. </FormRow>
  348. </Fragment>
  349. );
  350. }
  351. render() {
  352. const {
  353. alertType,
  354. organization,
  355. disabled,
  356. onFilterSearch,
  357. allowChangeEventTypes,
  358. dataset,
  359. isExtrapolatedChartData,
  360. isTransactionMigration,
  361. isErrorMigration,
  362. aggregate,
  363. project,
  364. } = this.props;
  365. const {environments} = this.state;
  366. const environmentOptions: SelectValue<string | null>[] = [
  367. {
  368. value: null,
  369. label: t('All Environments'),
  370. },
  371. ...(environments?.map(env => ({value: env.name, label: getDisplayName(env)})) ??
  372. []),
  373. ];
  374. return (
  375. <Fragment>
  376. <ChartPanel>
  377. <StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody>
  378. </ChartPanel>
  379. {isTransactionMigration ? (
  380. <Fragment>
  381. <Spacer />
  382. <HiddenListItem />
  383. <HiddenListItem />
  384. </Fragment>
  385. ) : (
  386. <Fragment>
  387. {isExtrapolatedChartData && (
  388. <OnDemandMetricAlert
  389. message={t(
  390. 'The chart data above is an estimate based on the stored transactions that match the filters specified.'
  391. )}
  392. />
  393. )}
  394. {!isErrorMigration && this.renderInterval()}
  395. <StyledListItem>{t('Filter events')}</StyledListItem>
  396. <FormRow noMargin columns={1 + (allowChangeEventTypes ? 1 : 0) + 1}>
  397. {this.renderProjectSelector()}
  398. <SelectField
  399. name="environment"
  400. placeholder={t('All Environments')}
  401. style={{
  402. ...this.formElemBaseStyle,
  403. minWidth: 230,
  404. flex: 1,
  405. }}
  406. styles={{
  407. singleValue: (base: any) => ({
  408. ...base,
  409. }),
  410. option: (base: any) => ({
  411. ...base,
  412. }),
  413. }}
  414. options={environmentOptions}
  415. isDisabled={
  416. disabled || this.state.environments === null || isErrorMigration
  417. }
  418. isClearable
  419. inline={false}
  420. flexibleControlStateSize
  421. />
  422. {allowChangeEventTypes && this.renderEventTypeFilter()}
  423. </FormRow>
  424. <FormRow>
  425. <FormField
  426. name="query"
  427. inline={false}
  428. style={{
  429. ...this.formElemBaseStyle,
  430. flex: '6 0 500px',
  431. }}
  432. flexibleControlStateSize
  433. >
  434. {({onChange, onBlur, onKeyDown, initialData, value}) => {
  435. return hasDDMFeature(organization) && alertType === 'custom_metrics' ? (
  436. <MetricSearchBar
  437. mri={getMRI(aggregate)}
  438. projectIds={[project.id]}
  439. placeholder={this.searchPlaceholder}
  440. query={initialData.query}
  441. defaultQuery={initialData?.query ?? ''}
  442. useFormWrapper={false}
  443. searchSource="alert_builder"
  444. onChange={query => {
  445. onFilterSearch(query, true);
  446. onChange(query, {});
  447. }}
  448. />
  449. ) : (
  450. <SearchContainer>
  451. <StyledSearchBar
  452. disallowWildcard={dataset === Dataset.SESSIONS}
  453. disallowFreeText={[
  454. Dataset.GENERIC_METRICS,
  455. Dataset.TRANSACTIONS,
  456. ].includes(dataset)}
  457. invalidMessages={{
  458. [InvalidReason.WILDCARD_NOT_ALLOWED]: t(
  459. 'The wildcard operator is not supported here.'
  460. ),
  461. [InvalidReason.FREE_TEXT_NOT_ALLOWED]: t(
  462. 'Free text search is not allowed. If you want to partially match transaction names, use glob patterns like "transaction:*transaction-name*"'
  463. ),
  464. }}
  465. customInvalidTagMessage={item => {
  466. if (dataset !== Dataset.GENERIC_METRICS) {
  467. return null;
  468. }
  469. return (
  470. <SearchInvalidTag
  471. message={tct(
  472. "The field [field] isn't supported for performance alerts.",
  473. {
  474. field: <code>{item.desc}</code>,
  475. }
  476. )}
  477. docLink="https://docs.sentry.io/product/alerts/create-alerts/metric-alert-config/#tags--properties"
  478. />
  479. );
  480. }}
  481. searchSource="alert_builder"
  482. defaultQuery={initialData?.query ?? ''}
  483. {...getSupportedAndOmittedTags(dataset, organization)}
  484. includeSessionTagsValues={dataset === Dataset.SESSIONS}
  485. disabled={disabled || isErrorMigration}
  486. useFormWrapper={false}
  487. organization={organization}
  488. placeholder={this.searchPlaceholder}
  489. onChange={onChange}
  490. query={initialData.query}
  491. // We only need strict validation for Transaction queries, everything else is fine
  492. highlightUnsupportedTags={
  493. organization.features.includes('alert-allow-indexed') ||
  494. (hasOnDemandMetricAlertFeature(organization) &&
  495. isOnDemandQueryString(initialData.query))
  496. ? false
  497. : dataset === Dataset.GENERIC_METRICS
  498. }
  499. onKeyDown={e => {
  500. /**
  501. * Do not allow enter key to submit the alerts form since it is unlikely
  502. * users will be ready to create the rule as this sits above required fields.
  503. */
  504. if (e.key === 'Enter') {
  505. e.preventDefault();
  506. e.stopPropagation();
  507. }
  508. onKeyDown?.(e);
  509. }}
  510. onClose={(query, {validSearch}) => {
  511. onFilterSearch(query, validSearch);
  512. onBlur(query);
  513. }}
  514. onSearch={query => {
  515. onFilterSearch(query, true);
  516. onChange(query, {});
  517. }}
  518. hasRecentSearches={dataset !== Dataset.SESSIONS}
  519. />
  520. {isExtrapolatedChartData && isOnDemandQueryString(value) && (
  521. <OnDemandWarningIcon
  522. color="gray500"
  523. msg={tct(
  524. `We don’t routinely collect metrics from [fields]. However, we’ll do so [strong:once this alert has been saved.]`,
  525. {
  526. fields: (
  527. <strong>
  528. {getOnDemandKeys(value)
  529. .map(key => `"${key}"`)
  530. .join(', ')}
  531. </strong>
  532. ),
  533. strong: <strong />,
  534. }
  535. )}
  536. />
  537. )}
  538. </SearchContainer>
  539. );
  540. }}
  541. </FormField>
  542. </FormRow>
  543. </Fragment>
  544. )}
  545. </Fragment>
  546. );
  547. }
  548. }
  549. const StyledListTitle = styled('div')`
  550. display: flex;
  551. span {
  552. margin-left: ${space(1)};
  553. }
  554. `;
  555. // This is a temporary hacky solution to hide list items without changing the numbering of the rest of the list
  556. // TODO(issues): Remove this once the migration is complete
  557. const HiddenListItem = styled(ListItem)`
  558. position: absolute;
  559. width: 0px;
  560. height: 0px;
  561. opacity: 0;
  562. pointer-events: none;
  563. `;
  564. const Spacer = styled('div')`
  565. margin-bottom: ${space(2)};
  566. `;
  567. const ChartPanel = styled(Panel)`
  568. margin-bottom: ${space(1)};
  569. `;
  570. const StyledPanelBody = styled(PanelBody)`
  571. ol,
  572. h4 {
  573. margin-bottom: ${space(1)};
  574. }
  575. `;
  576. const SearchContainer = styled('div')`
  577. display: flex;
  578. align-items: center;
  579. gap: ${space(1)};
  580. `;
  581. const StyledSearchBar = styled(SearchBar)`
  582. flex-grow: 1;
  583. ${p =>
  584. p.disabled &&
  585. `
  586. background: ${p.theme.backgroundSecondary};
  587. color: ${p.theme.disabled};
  588. cursor: not-allowed;
  589. `}
  590. `;
  591. const StyledListItem = styled(ListItem)`
  592. margin-bottom: ${space(0.5)};
  593. font-size: ${p => p.theme.fontSizeExtraLarge};
  594. line-height: 1.3;
  595. `;
  596. const FormRow = styled('div')<{columns?: number; noMargin?: boolean}>`
  597. display: flex;
  598. flex-direction: row;
  599. align-items: center;
  600. flex-wrap: wrap;
  601. margin-bottom: ${p => (p.noMargin ? 0 : space(4))};
  602. ${p =>
  603. p.columns !== undefined &&
  604. css`
  605. display: grid;
  606. grid-template-columns: repeat(${p.columns}, auto);
  607. `}
  608. `;
  609. export default withApi(withProjects(RuleConditionsForm));