ruleConditionsForm.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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/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. alertType,
  354. organization,
  355. disabled,
  356. onFilterSearch,
  357. allowChangeEventTypes,
  358. dataset,
  359. isExtrapolatedChartData,
  360. isMigration,
  361. aggregate,
  362. project,
  363. } = this.props;
  364. const {environments} = this.state;
  365. const environmentOptions: SelectValue<string | null>[] = [
  366. {
  367. value: null,
  368. label: t('All Environments'),
  369. },
  370. ...(environments?.map(env => ({value: env.name, label: getDisplayName(env)})) ??
  371. []),
  372. ];
  373. return (
  374. <Fragment>
  375. <ChartPanel>
  376. <StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody>
  377. </ChartPanel>
  378. {isMigration ? (
  379. <Fragment>
  380. <Spacer />
  381. <HiddenListItem />
  382. <HiddenListItem />
  383. </Fragment>
  384. ) : (
  385. <Fragment>
  386. {isExtrapolatedChartData && (
  387. <OnDemandMetricAlert
  388. message={t(
  389. 'The chart data above is an estimate based on the stored transactions that match the filters specified.'
  390. )}
  391. />
  392. )}
  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, value}) => {
  432. return hasDDMFeature(organization) && alertType === 'custom_metrics' ? (
  433. <MetricSearchBar
  434. mri={getMRI(aggregate)}
  435. projectIds={[project.id]}
  436. placeholder={this.searchPlaceholder}
  437. query={initialData.query}
  438. defaultQuery={initialData?.query ?? ''}
  439. useFormWrapper={false}
  440. searchSource="alert_builder"
  441. onChange={query => {
  442. onFilterSearch(query, true);
  443. onChange(query, {});
  444. }}
  445. />
  446. ) : (
  447. <SearchContainer>
  448. <StyledSearchBar
  449. disallowWildcard={dataset === Dataset.SESSIONS}
  450. invalidMessages={{
  451. [InvalidReason.WILDCARD_NOT_ALLOWED]: t(
  452. 'The wildcard operator is not supported here.'
  453. ),
  454. }}
  455. customInvalidTagMessage={item => {
  456. if (
  457. ![Dataset.GENERIC_METRICS, Dataset.TRANSACTIONS].includes(
  458. dataset
  459. )
  460. ) {
  461. return null;
  462. }
  463. return (
  464. <SearchInvalidTag
  465. message={tct(
  466. "The field [field] isn't supported for performance alerts.",
  467. {
  468. field: <code>{item.desc}</code>,
  469. }
  470. )}
  471. docLink="https://docs.sentry.io/product/alerts/create-alerts/metric-alert-config/#tags--properties"
  472. />
  473. );
  474. }}
  475. searchSource="alert_builder"
  476. defaultQuery={initialData?.query ?? ''}
  477. {...getSupportedAndOmittedTags(dataset, organization)}
  478. includeSessionTagsValues={dataset === Dataset.SESSIONS}
  479. disabled={disabled}
  480. useFormWrapper={false}
  481. organization={organization}
  482. placeholder={this.searchPlaceholder}
  483. onChange={onChange}
  484. query={initialData.query}
  485. // We only need strict validation for Transaction queries, everything else is fine
  486. highlightUnsupportedTags={
  487. organization.features.includes('alert-allow-indexed') ||
  488. (hasOnDemandMetricAlertFeature(organization) &&
  489. isOnDemandQueryString(initialData.query))
  490. ? false
  491. : [Dataset.GENERIC_METRICS, Dataset.TRANSACTIONS].includes(
  492. dataset
  493. )
  494. }
  495. onKeyDown={e => {
  496. /**
  497. * Do not allow enter key to submit the alerts form since it is unlikely
  498. * users will be ready to create the rule as this sits above required fields.
  499. */
  500. if (e.key === 'Enter') {
  501. e.preventDefault();
  502. e.stopPropagation();
  503. }
  504. onKeyDown?.(e);
  505. }}
  506. onClose={(query, {validSearch}) => {
  507. onFilterSearch(query, validSearch);
  508. onBlur(query);
  509. }}
  510. onSearch={query => {
  511. onFilterSearch(query, true);
  512. onChange(query, {});
  513. }}
  514. hasRecentSearches={dataset !== Dataset.SESSIONS}
  515. />
  516. {isExtrapolatedChartData && isOnDemandQueryString(value) && (
  517. <OnDemandWarningIcon
  518. color="gray500"
  519. msg={tct(
  520. `We don’t routinely collect metrics from [fields]. However, we’ll do so [strong:once this alert has been saved.]`,
  521. {
  522. fields: (
  523. <strong>
  524. {getOnDemandKeys(value)
  525. .map(key => `"${key}"`)
  526. .join(', ')}
  527. </strong>
  528. ),
  529. strong: <strong />,
  530. }
  531. )}
  532. />
  533. )}
  534. </SearchContainer>
  535. );
  536. }}
  537. </FormField>
  538. </FormRow>
  539. </Fragment>
  540. )}
  541. </Fragment>
  542. );
  543. }
  544. }
  545. const StyledListTitle = styled('div')`
  546. display: flex;
  547. span {
  548. margin-left: ${space(1)};
  549. }
  550. `;
  551. // This is a temporary hacky solution to hide list items without changing the numbering of the rest of the list
  552. // TODO(telemetry-experience): Remove this once the migration is complete
  553. const HiddenListItem = styled(ListItem)`
  554. position: absolute;
  555. width: 0px;
  556. height: 0px;
  557. opacity: 0;
  558. pointer-events: none;
  559. `;
  560. const Spacer = styled('div')`
  561. margin-bottom: ${space(2)};
  562. `;
  563. const ChartPanel = styled(Panel)`
  564. margin-bottom: ${space(1)};
  565. `;
  566. const StyledPanelBody = styled(PanelBody)`
  567. ol,
  568. h4 {
  569. margin-bottom: ${space(1)};
  570. }
  571. `;
  572. const SearchContainer = styled('div')`
  573. display: flex;
  574. align-items: center;
  575. gap: ${space(1)};
  576. `;
  577. const StyledSearchBar = styled(SearchBar)`
  578. flex-grow: 1;
  579. ${p =>
  580. p.disabled &&
  581. `
  582. background: ${p.theme.backgroundSecondary};
  583. color: ${p.theme.disabled};
  584. cursor: not-allowed;
  585. `}
  586. `;
  587. const StyledListItem = styled(ListItem)`
  588. margin-bottom: ${space(0.5)};
  589. font-size: ${p => p.theme.fontSizeExtraLarge};
  590. line-height: 1.3;
  591. `;
  592. const FormRow = styled('div')<{columns?: number; noMargin?: boolean}>`
  593. display: flex;
  594. flex-direction: row;
  595. align-items: center;
  596. flex-wrap: wrap;
  597. margin-bottom: ${p => (p.noMargin ? 0 : space(4))};
  598. ${p =>
  599. p.columns !== undefined &&
  600. css`
  601. display: grid;
  602. grid-template-columns: repeat(${p.columns}, auto);
  603. `}
  604. `;
  605. export default withApi(withProjects(RuleConditionsForm));