ruleConditionsForm.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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 SearchBar from 'sentry/components/events/searchBar';
  10. import SelectControl from 'sentry/components/forms/controls/selectControl';
  11. import SelectField from 'sentry/components/forms/fields/selectField';
  12. import FormField from 'sentry/components/forms/formField';
  13. import IdBadge from 'sentry/components/idBadge';
  14. import ListItem from 'sentry/components/list/listItem';
  15. import Panel from 'sentry/components/panels/panel';
  16. import PanelBody from 'sentry/components/panels/panelBody';
  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 withApi from 'sentry/utils/withApi';
  23. import withProjects from 'sentry/utils/withProjects';
  24. import WizardField from 'sentry/views/alerts/rules/metric/wizardField';
  25. import {
  26. convertDatasetEventTypesToSource,
  27. DATA_SOURCE_LABELS,
  28. DATA_SOURCE_TO_SET_AND_EVENT_TYPES,
  29. } from 'sentry/views/alerts/utils';
  30. import {
  31. AlertType,
  32. datasetOmittedTags,
  33. datasetSupportedTags,
  34. } from 'sentry/views/alerts/wizard/options';
  35. import {getProjectOptions} from '../utils';
  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. renderProjectSelector() {
  219. const {
  220. project: _selectedProject,
  221. projects,
  222. disabled,
  223. organization,
  224. disableProjectSelector,
  225. } = this.props;
  226. const projectOptions = getProjectOptions({
  227. organization,
  228. projects,
  229. isFormDisabled: disabled,
  230. });
  231. return (
  232. <FormField
  233. name="projectId"
  234. inline={false}
  235. style={{
  236. ...this.formElemBaseStyle,
  237. minWidth: 300,
  238. flex: 2,
  239. }}
  240. flexibleControlStateSize
  241. >
  242. {({onChange, onBlur, model}) => {
  243. const selectedProject =
  244. projects.find(({id}) => id === model.getValue('projectId')) ||
  245. _selectedProject;
  246. return (
  247. <SelectControl
  248. isDisabled={disabled || disableProjectSelector}
  249. value={selectedProject.id}
  250. options={projectOptions}
  251. onChange={({value}: {value: Project['id']}) => {
  252. // if the current owner/team isn't part of project selected, update to the first available team
  253. const nextSelectedProject =
  254. projects.find(({id}) => id === value) ?? selectedProject;
  255. const ownerId: string | undefined = model
  256. .getValue('owner')
  257. ?.split(':')[1];
  258. if (
  259. ownerId &&
  260. nextSelectedProject.teams.find(({id}) => id === ownerId) ===
  261. undefined &&
  262. nextSelectedProject.teams.length
  263. ) {
  264. model.setValue('owner', `team:${nextSelectedProject.teams[0].id}`);
  265. }
  266. onChange(value, {});
  267. onBlur(value, {});
  268. }}
  269. components={{
  270. SingleValue: containerProps => (
  271. <components.ValueContainer {...containerProps}>
  272. <IdBadge
  273. project={selectedProject}
  274. avatarProps={{consistentWidth: true}}
  275. avatarSize={18}
  276. disableLink
  277. />
  278. </components.ValueContainer>
  279. ),
  280. }}
  281. />
  282. );
  283. }}
  284. </FormField>
  285. );
  286. }
  287. renderInterval() {
  288. const {organization, disabled, alertType, timeWindow, onTimeWindowChange} =
  289. this.props;
  290. return (
  291. <Fragment>
  292. <StyledListItem>
  293. <StyledListTitle>
  294. <div>{t('Define your metric')}</div>
  295. </StyledListTitle>
  296. </StyledListItem>
  297. <FormRow>
  298. <WizardField
  299. name="aggregate"
  300. help={null}
  301. organization={organization}
  302. disabled={disabled}
  303. style={{
  304. ...this.formElemBaseStyle,
  305. flex: 1,
  306. }}
  307. inline={false}
  308. flexibleControlStateSize
  309. columnWidth={200}
  310. alertType={alertType}
  311. required
  312. />
  313. <SelectControl
  314. name="timeWindow"
  315. styles={{
  316. control: (provided: {[x: string]: string | number | boolean}) => ({
  317. ...provided,
  318. minWidth: 200,
  319. maxWidth: 300,
  320. }),
  321. container: (provided: {[x: string]: string | number | boolean}) => ({
  322. ...provided,
  323. margin: `${space(0.5)}`,
  324. }),
  325. }}
  326. options={this.timeWindowOptions}
  327. required
  328. isDisabled={disabled}
  329. value={timeWindow}
  330. onChange={({value}) => onTimeWindowChange(value)}
  331. inline={false}
  332. flexibleControlStateSize
  333. />
  334. </FormRow>
  335. </Fragment>
  336. );
  337. }
  338. render() {
  339. const {organization, disabled, onFilterSearch, allowChangeEventTypes, dataset} =
  340. this.props;
  341. const {environments} = this.state;
  342. const environmentOptions: SelectValue<string | null>[] = [
  343. {
  344. value: null,
  345. label: t('All Environments'),
  346. },
  347. ...(environments?.map(env => ({value: env.name, label: getDisplayName(env)})) ??
  348. []),
  349. ];
  350. return (
  351. <Fragment>
  352. <ChartPanel>
  353. <StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody>
  354. </ChartPanel>
  355. {this.renderInterval()}
  356. <StyledListItem>{t('Filter events')}</StyledListItem>
  357. <FormRow noMargin columns={1 + (allowChangeEventTypes ? 1 : 0) + 1}>
  358. {this.renderProjectSelector()}
  359. <SelectField
  360. name="environment"
  361. placeholder={t('All Environments')}
  362. style={{
  363. ...this.formElemBaseStyle,
  364. minWidth: 230,
  365. flex: 1,
  366. }}
  367. styles={{
  368. singleValue: (base: any) => ({
  369. ...base,
  370. }),
  371. option: (base: any) => ({
  372. ...base,
  373. }),
  374. }}
  375. options={environmentOptions}
  376. isDisabled={disabled || this.state.environments === null}
  377. isClearable
  378. inline={false}
  379. flexibleControlStateSize
  380. />
  381. {allowChangeEventTypes && this.renderEventTypeFilter()}
  382. </FormRow>
  383. <FormRow>
  384. <FormField
  385. name="query"
  386. inline={false}
  387. style={{
  388. ...this.formElemBaseStyle,
  389. flex: '6 0 500px',
  390. }}
  391. flexibleControlStateSize
  392. >
  393. {({onChange, onBlur, onKeyDown, initialData}) => {
  394. return (
  395. <SearchContainer>
  396. <StyledSearchBar
  397. customInvalidTagMessage={item => {
  398. if (
  399. ![Dataset.GENERIC_METRICS, Dataset.TRANSACTIONS].includes(dataset)
  400. ) {
  401. return null;
  402. }
  403. return (
  404. <SearchInvalidTag
  405. message={tct(
  406. "The field [field] isn't supported for performance alerts.",
  407. {
  408. field: <code>{item.desc}</code>,
  409. }
  410. )}
  411. docLink="https://docs.sentry.io/product/alerts/create-alerts/metric-alert-config/#tags--properties"
  412. />
  413. );
  414. }}
  415. searchSource="alert_builder"
  416. defaultQuery={initialData?.query ?? ''}
  417. omitTags={datasetOmittedTags(dataset, organization)}
  418. {...(datasetSupportedTags(dataset, organization)
  419. ? {supportedTags: datasetSupportedTags(dataset, organization)}
  420. : {})}
  421. includeSessionTagsValues={dataset === Dataset.SESSIONS}
  422. disabled={disabled}
  423. useFormWrapper={false}
  424. organization={organization}
  425. placeholder={this.searchPlaceholder}
  426. onChange={onChange}
  427. query={initialData.query}
  428. // We only need strict validation for Transaction queries, everything else is fine
  429. highlightUnsupportedTags={
  430. organization.features.includes('alert-allow-indexed')
  431. ? false
  432. : [Dataset.GENERIC_METRICS, Dataset.TRANSACTIONS].includes(
  433. dataset
  434. )
  435. }
  436. onKeyDown={e => {
  437. /**
  438. * Do not allow enter key to submit the alerts form since it is unlikely
  439. * users will be ready to create the rule as this sits above required fields.
  440. */
  441. if (e.key === 'Enter') {
  442. e.preventDefault();
  443. e.stopPropagation();
  444. }
  445. onKeyDown?.(e);
  446. }}
  447. onClose={(query, {validSearch}) => {
  448. onFilterSearch(query, validSearch);
  449. onBlur(query);
  450. }}
  451. onSearch={query => {
  452. onFilterSearch(query, true);
  453. onChange(query, {});
  454. }}
  455. hasRecentSearches={dataset !== Dataset.SESSIONS}
  456. />
  457. </SearchContainer>
  458. );
  459. }}
  460. </FormField>
  461. </FormRow>
  462. </Fragment>
  463. );
  464. }
  465. }
  466. const StyledListTitle = styled('div')`
  467. display: flex;
  468. span {
  469. margin-left: ${space(1)};
  470. }
  471. `;
  472. const ChartPanel = styled(Panel)`
  473. margin-bottom: ${space(1)};
  474. `;
  475. const StyledPanelBody = styled(PanelBody)`
  476. ol,
  477. h4 {
  478. margin-bottom: ${space(1)};
  479. }
  480. `;
  481. const SearchContainer = styled('div')`
  482. display: flex;
  483. `;
  484. const StyledSearchBar = styled(SearchBar)`
  485. flex-grow: 1;
  486. ${p =>
  487. p.disabled &&
  488. `
  489. background: ${p.theme.backgroundSecondary};
  490. color: ${p.theme.disabled};
  491. cursor: not-allowed;
  492. `}
  493. `;
  494. const StyledListItem = styled(ListItem)`
  495. margin-bottom: ${space(1)};
  496. font-size: ${p => p.theme.fontSizeExtraLarge};
  497. line-height: 1.3;
  498. `;
  499. const FormRow = styled('div')<{columns?: number; noMargin?: boolean}>`
  500. display: flex;
  501. flex-direction: row;
  502. align-items: center;
  503. flex-wrap: wrap;
  504. margin-bottom: ${p => (p.noMargin ? 0 : space(4))};
  505. ${p =>
  506. p.columns !== undefined &&
  507. css`
  508. display: grid;
  509. grid-template-columns: repeat(${p.columns}, auto);
  510. `}
  511. `;
  512. export default withApi(withProjects(RuleConditionsForm));