ruleConditionsForm.tsx 18 KB

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