ruleConditionsForm.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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 {hasDDMExperimentalFeature} 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/queryBuilder';
  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. isExtrapolatedChartData?: boolean;
  76. isMigration?: boolean;
  77. loadingProjects?: boolean;
  78. };
  79. type State = {
  80. environments: Environment[] | null;
  81. };
  82. class RuleConditionsForm extends PureComponent<Props, State> {
  83. state: State = {
  84. environments: null,
  85. };
  86. componentDidMount() {
  87. this.fetchData();
  88. }
  89. componentDidUpdate(prevProps: Props) {
  90. if (prevProps.project.id === this.props.project.id) {
  91. return;
  92. }
  93. this.fetchData();
  94. }
  95. formElemBaseStyle = {
  96. padding: `${space(0.5)}`,
  97. border: 'none',
  98. };
  99. async fetchData() {
  100. const {api, organization, project} = this.props;
  101. try {
  102. const environments = await api.requestPromise(
  103. `/projects/${organization.slug}/${project.slug}/environments/`,
  104. {
  105. query: {
  106. visibility: 'visible',
  107. },
  108. }
  109. );
  110. this.setState({environments});
  111. } catch (_err) {
  112. addErrorMessage(t('Unable to fetch environments'));
  113. }
  114. }
  115. get timeWindowOptions() {
  116. let options: Record<string, string> = TIME_WINDOW_MAP;
  117. if (isCrashFreeAlert(this.props.dataset)) {
  118. options = pick(TIME_WINDOW_MAP, [
  119. // TimeWindow.THIRTY_MINUTES, leaving this option out until we figure out the sub-hour session resolution chart limitations
  120. TimeWindow.ONE_HOUR,
  121. TimeWindow.TWO_HOURS,
  122. TimeWindow.FOUR_HOURS,
  123. TimeWindow.ONE_DAY,
  124. ]);
  125. }
  126. return Object.entries(options).map(([value, label]) => ({
  127. value: parseInt(value, 10),
  128. label: tct('[timeWindow] interval', {
  129. timeWindow: label.slice(-1) === 's' ? label.slice(0, -1) : label,
  130. }),
  131. }));
  132. }
  133. get searchPlaceholder() {
  134. switch (this.props.dataset) {
  135. case Dataset.ERRORS:
  136. return t('Filter events by level, message, and other properties\u2026');
  137. case Dataset.METRICS:
  138. case Dataset.SESSIONS:
  139. return t('Filter sessions by release version\u2026');
  140. case Dataset.TRANSACTIONS:
  141. default:
  142. return t('Filter transactions by URL, tags, and other properties\u2026');
  143. }
  144. }
  145. renderEventTypeFilter() {
  146. const {organization, disabled, alertType} = 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}
  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. organization,
  354. disabled,
  355. onFilterSearch,
  356. allowChangeEventTypes,
  357. dataset,
  358. isExtrapolatedChartData,
  359. isMigration,
  360. aggregate,
  361. project,
  362. } = this.props;
  363. const {environments} = this.state;
  364. const environmentOptions: SelectValue<string | null>[] = [
  365. {
  366. value: null,
  367. label: t('All Environments'),
  368. },
  369. ...(environments?.map(env => ({value: env.name, label: getDisplayName(env)})) ??
  370. []),
  371. ];
  372. return (
  373. <Fragment>
  374. <ChartPanel>
  375. <StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody>
  376. </ChartPanel>
  377. {isMigration ? (
  378. <Fragment>
  379. <Spacer />
  380. <HiddenListItem />
  381. <HiddenListItem />
  382. </Fragment>
  383. ) : (
  384. <Fragment>
  385. {isExtrapolatedChartData && (
  386. <OnDemandMetricAlert
  387. message={t(
  388. 'The chart data above is an estimate based on the stored transactions that match the filters specified.'
  389. )}
  390. />
  391. )}
  392. {this.renderInterval()}
  393. <StyledListItem>{t('Filter events')}</StyledListItem>
  394. <FormRow noMargin columns={1 + (allowChangeEventTypes ? 1 : 0) + 1}>
  395. {this.renderProjectSelector()}
  396. <SelectField
  397. name="environment"
  398. placeholder={t('All Environments')}
  399. style={{
  400. ...this.formElemBaseStyle,
  401. minWidth: 230,
  402. flex: 1,
  403. }}
  404. styles={{
  405. singleValue: (base: any) => ({
  406. ...base,
  407. }),
  408. option: (base: any) => ({
  409. ...base,
  410. }),
  411. }}
  412. options={environmentOptions}
  413. isDisabled={disabled || this.state.environments === null}
  414. isClearable
  415. inline={false}
  416. flexibleControlStateSize
  417. />
  418. {allowChangeEventTypes && this.renderEventTypeFilter()}
  419. </FormRow>
  420. <FormRow>
  421. <FormField
  422. name="query"
  423. inline={false}
  424. style={{
  425. ...this.formElemBaseStyle,
  426. flex: '6 0 500px',
  427. }}
  428. flexibleControlStateSize
  429. >
  430. {({onChange, onBlur, onKeyDown, initialData, value}) => {
  431. return hasDDMExperimentalFeature(organization) ? (
  432. <MetricSearchBar
  433. mri={getMRI(aggregate)}
  434. projectIds={[project.id]}
  435. placeholder={this.searchPlaceholder}
  436. query={initialData.query}
  437. defaultQuery={initialData?.query ?? ''}
  438. useFormWrapper={false}
  439. searchSource="alert_builder"
  440. onChange={query => {
  441. onFilterSearch(query, true);
  442. onChange(query, {});
  443. }}
  444. />
  445. ) : (
  446. <SearchContainer>
  447. <StyledSearchBar
  448. disallowWildcard={dataset === Dataset.SESSIONS}
  449. invalidMessages={{
  450. [InvalidReason.WILDCARD_NOT_ALLOWED]: t(
  451. 'The wildcard operator is not supported here.'
  452. ),
  453. }}
  454. customInvalidTagMessage={item => {
  455. if (
  456. ![Dataset.GENERIC_METRICS, Dataset.TRANSACTIONS].includes(
  457. dataset
  458. )
  459. ) {
  460. return null;
  461. }
  462. return (
  463. <SearchInvalidTag
  464. message={tct(
  465. "The field [field] isn't supported for performance alerts.",
  466. {
  467. field: <code>{item.desc}</code>,
  468. }
  469. )}
  470. docLink="https://docs.sentry.io/product/alerts/create-alerts/metric-alert-config/#tags--properties"
  471. />
  472. );
  473. }}
  474. searchSource="alert_builder"
  475. defaultQuery={initialData?.query ?? ''}
  476. {...getSupportedAndOmittedTags(dataset, organization)}
  477. includeSessionTagsValues={dataset === Dataset.SESSIONS}
  478. disabled={disabled}
  479. useFormWrapper={false}
  480. organization={organization}
  481. placeholder={this.searchPlaceholder}
  482. onChange={onChange}
  483. query={initialData.query}
  484. // We only need strict validation for Transaction queries, everything else is fine
  485. highlightUnsupportedTags={
  486. organization.features.includes('alert-allow-indexed') ||
  487. (hasOnDemandMetricAlertFeature(organization) &&
  488. isOnDemandQueryString(initialData.query))
  489. ? false
  490. : [Dataset.GENERIC_METRICS, Dataset.TRANSACTIONS].includes(
  491. dataset
  492. )
  493. }
  494. onKeyDown={e => {
  495. /**
  496. * Do not allow enter key to submit the alerts form since it is unlikely
  497. * users will be ready to create the rule as this sits above required fields.
  498. */
  499. if (e.key === 'Enter') {
  500. e.preventDefault();
  501. e.stopPropagation();
  502. }
  503. onKeyDown?.(e);
  504. }}
  505. onClose={(query, {validSearch}) => {
  506. onFilterSearch(query, validSearch);
  507. onBlur(query);
  508. }}
  509. onSearch={query => {
  510. onFilterSearch(query, true);
  511. onChange(query, {});
  512. }}
  513. hasRecentSearches={dataset !== Dataset.SESSIONS}
  514. />
  515. {isExtrapolatedChartData && isOnDemandQueryString(value) && (
  516. <OnDemandWarningIcon
  517. color="gray500"
  518. msg={tct(
  519. `We don’t routinely collect metrics from [fields]. However, we’ll do so [strong:once this alert has been saved.]`,
  520. {
  521. fields: (
  522. <strong>
  523. {getOnDemandKeys(value)
  524. .map(key => `"${key}"`)
  525. .join(', ')}
  526. </strong>
  527. ),
  528. strong: <strong />,
  529. }
  530. )}
  531. />
  532. )}
  533. </SearchContainer>
  534. );
  535. }}
  536. </FormField>
  537. </FormRow>
  538. </Fragment>
  539. )}
  540. </Fragment>
  541. );
  542. }
  543. }
  544. const StyledListTitle = styled('div')`
  545. display: flex;
  546. span {
  547. margin-left: ${space(1)};
  548. }
  549. `;
  550. // This is a temporary hacky solution to hide list items without changing the numbering of the rest of the list
  551. // TODO(telemetry-experience): Remove this once the migration is complete
  552. const HiddenListItem = styled(ListItem)`
  553. position: absolute;
  554. width: 0px;
  555. height: 0px;
  556. opacity: 0;
  557. pointer-events: none;
  558. `;
  559. const Spacer = styled('div')`
  560. margin-bottom: ${space(2)};
  561. `;
  562. const ChartPanel = styled(Panel)`
  563. margin-bottom: ${space(1)};
  564. `;
  565. const StyledPanelBody = styled(PanelBody)`
  566. ol,
  567. h4 {
  568. margin-bottom: ${space(1)};
  569. }
  570. `;
  571. const SearchContainer = styled('div')`
  572. display: flex;
  573. align-items: center;
  574. gap: ${space(1)};
  575. `;
  576. const StyledSearchBar = styled(SearchBar)`
  577. flex-grow: 1;
  578. ${p =>
  579. p.disabled &&
  580. `
  581. background: ${p.theme.backgroundSecondary};
  582. color: ${p.theme.disabled};
  583. cursor: not-allowed;
  584. `}
  585. `;
  586. const StyledListItem = styled(ListItem)`
  587. margin-bottom: ${space(0.5)};
  588. font-size: ${p => p.theme.fontSizeExtraLarge};
  589. line-height: 1.3;
  590. `;
  591. const FormRow = styled('div')<{columns?: number; noMargin?: boolean}>`
  592. display: flex;
  593. flex-direction: row;
  594. align-items: center;
  595. flex-wrap: wrap;
  596. margin-bottom: ${p => (p.noMargin ? 0 : space(4))};
  597. ${p =>
  598. p.columns !== undefined &&
  599. css`
  600. display: grid;
  601. grid-template-columns: repeat(${p.columns}, auto);
  602. `}
  603. `;
  604. export default withApi(withProjects(RuleConditionsForm));