ruleForm.tsx 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. import {Fragment, ReactNode} from 'react';
  2. import {PlainRoute, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {
  5. addErrorMessage,
  6. addSuccessMessage,
  7. clearIndicators,
  8. Indicator,
  9. } from 'sentry/actionCreators/indicator';
  10. import {fetchOrganizationTags} from 'sentry/actionCreators/tags';
  11. import {hasEveryAccess} from 'sentry/components/acl/access';
  12. import Alert from 'sentry/components/alert';
  13. import {Button} from 'sentry/components/button';
  14. import {HeaderTitleLegend} from 'sentry/components/charts/styles';
  15. import CircleIndicator from 'sentry/components/circleIndicator';
  16. import Confirm from 'sentry/components/confirm';
  17. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  18. import Form, {FormProps} from 'sentry/components/forms/form';
  19. import FormModel from 'sentry/components/forms/model';
  20. import * as Layout from 'sentry/components/layouts/thirds';
  21. import ExternalLink from 'sentry/components/links/externalLink';
  22. import List from 'sentry/components/list';
  23. import ListItem from 'sentry/components/list/listItem';
  24. import {Tooltip} from 'sentry/components/tooltip';
  25. import {t, tct} from 'sentry/locale';
  26. import IndicatorStore from 'sentry/stores/indicatorStore';
  27. import {space} from 'sentry/styles/space';
  28. import {EventsStats, MultiSeriesEventsStats, Organization, Project} from 'sentry/types';
  29. import {defined} from 'sentry/utils';
  30. import {metric, trackAnalytics} from 'sentry/utils/analytics';
  31. import type EventView from 'sentry/utils/discover/eventView';
  32. import {isOnDemandQueryString} from 'sentry/utils/onDemandMetrics';
  33. import {
  34. hasOnDemandMetricAlertFeature,
  35. shouldShowOnDemandMetricAlertUI,
  36. } from 'sentry/utils/onDemandMetrics/features';
  37. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  38. import withProjects from 'sentry/utils/withProjects';
  39. import {IncompatibleAlertQuery} from 'sentry/views/alerts/rules/metric/incompatibleAlertQuery';
  40. import RuleNameOwnerForm from 'sentry/views/alerts/rules/metric/ruleNameOwnerForm';
  41. import ThresholdTypeForm from 'sentry/views/alerts/rules/metric/thresholdTypeForm';
  42. import Triggers from 'sentry/views/alerts/rules/metric/triggers';
  43. import TriggersChart from 'sentry/views/alerts/rules/metric/triggers/chart';
  44. import {getEventTypeFilter} from 'sentry/views/alerts/rules/metric/utils/getEventTypeFilter';
  45. import hasThresholdValue from 'sentry/views/alerts/rules/metric/utils/hasThresholdValue';
  46. import {
  47. isOnDemandMetricAlert,
  48. isValidOnDemandMetricAlert,
  49. } from 'sentry/views/alerts/rules/metric/utils/onDemandMetricAlert';
  50. import {AlertRuleType} from 'sentry/views/alerts/types';
  51. import {
  52. hasMigrationFeatureFlag,
  53. ruleNeedsMigration,
  54. } from 'sentry/views/alerts/utils/migrationUi';
  55. import {
  56. AlertWizardAlertNames,
  57. DatasetMEPAlertQueryTypes,
  58. MetricAlertType,
  59. } from 'sentry/views/alerts/wizard/options';
  60. import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
  61. import PermissionAlert from 'sentry/views/settings/project/permissionAlert';
  62. import {isCrashFreeAlert} from './utils/isCrashFreeAlert';
  63. import {addOrUpdateRule} from './actions';
  64. import {
  65. createDefaultTrigger,
  66. DEFAULT_CHANGE_COMP_DELTA,
  67. DEFAULT_CHANGE_TIME_WINDOW,
  68. DEFAULT_COUNT_TIME_WINDOW,
  69. } from './constants';
  70. import RuleConditionsForm from './ruleConditionsForm';
  71. import {
  72. AlertRuleComparisonType,
  73. AlertRuleThresholdType,
  74. AlertRuleTriggerType,
  75. Dataset,
  76. EventTypes,
  77. MetricActionTemplate,
  78. MetricRule,
  79. Trigger,
  80. UnsavedMetricRule,
  81. } from './types';
  82. const POLLING_MAX_TIME_LIMIT = 3 * 60000;
  83. type RuleTaskResponse = {
  84. status: 'pending' | 'failed' | 'success';
  85. alertRule?: MetricRule;
  86. error?: string;
  87. };
  88. type Props = {
  89. organization: Organization;
  90. project: Project;
  91. projects: Project[];
  92. routes: PlainRoute[];
  93. rule: MetricRule;
  94. userTeamIds: string[];
  95. disableProjectSelector?: boolean;
  96. eventView?: EventView;
  97. isCustomMetric?: boolean;
  98. isDuplicateRule?: boolean;
  99. ruleId?: string;
  100. sessionId?: string;
  101. } & RouteComponentProps<{projectId?: string; ruleId?: string}, {}> & {
  102. onSubmitSuccess?: FormProps['onSubmitSuccess'];
  103. } & DeprecatedAsyncComponent['props'];
  104. type State = {
  105. aggregate: string;
  106. alertType: MetricAlertType;
  107. // `null` means loading
  108. availableActions: MetricActionTemplate[] | null;
  109. comparisonType: AlertRuleComparisonType;
  110. // Rule conditions form inputs
  111. // Needed for TriggersChart
  112. dataset: Dataset;
  113. environment: string | null;
  114. eventTypes: EventTypes[];
  115. isQueryValid: boolean;
  116. project: Project;
  117. query: string;
  118. resolveThreshold: UnsavedMetricRule['resolveThreshold'];
  119. thresholdPeriod: UnsavedMetricRule['thresholdPeriod'];
  120. thresholdType: UnsavedMetricRule['thresholdType'];
  121. timeWindow: number;
  122. triggerErrors: Map<number, {[fieldName: string]: string}>;
  123. triggers: Trigger[];
  124. comparisonDelta?: number;
  125. isExtrapolatedChartData?: boolean;
  126. uuid?: string;
  127. } & DeprecatedAsyncComponent['state'];
  128. const isEmpty = (str: unknown): boolean => str === '' || !defined(str);
  129. class RuleFormContainer extends DeprecatedAsyncComponent<Props, State> {
  130. form = new FormModel();
  131. pollingTimeout: number | undefined = undefined;
  132. get isDuplicateRule(): boolean {
  133. return Boolean(this.props.isDuplicateRule);
  134. }
  135. get chartQuery(): string {
  136. const {query, eventTypes, dataset} = this.state;
  137. const eventTypeFilter = getEventTypeFilter(this.state.dataset, eventTypes);
  138. const queryWithTypeFilter = (
  139. query ? `(${query}) AND (${eventTypeFilter})` : eventTypeFilter
  140. ).trim();
  141. return isCrashFreeAlert(dataset) ? query : queryWithTypeFilter;
  142. }
  143. componentDidMount() {
  144. super.componentDidMount();
  145. const {organization} = this.props;
  146. const {project} = this.state;
  147. // SearchBar gets its tags from Reflux.
  148. fetchOrganizationTags(this.api, organization.slug, [project.id]);
  149. }
  150. componentWillUnmount() {
  151. window.clearTimeout(this.pollingTimeout);
  152. }
  153. getDefaultState(): State {
  154. const {rule, location} = this.props;
  155. const triggersClone = [...rule.triggers];
  156. const {
  157. aggregate: _aggregate,
  158. eventTypes: _eventTypes,
  159. dataset: _dataset,
  160. name,
  161. } = location?.query ?? {};
  162. const eventTypes = typeof _eventTypes === 'string' ? [_eventTypes] : _eventTypes;
  163. // Warning trigger is removed if it is blank when saving
  164. if (triggersClone.length !== 2) {
  165. triggersClone.push(createDefaultTrigger(AlertRuleTriggerType.WARNING));
  166. }
  167. const aggregate = _aggregate ?? rule.aggregate;
  168. const dataset = _dataset ?? rule.dataset;
  169. return {
  170. ...super.getDefaultState(),
  171. name: name ?? rule.name ?? '',
  172. aggregate,
  173. dataset,
  174. eventTypes: eventTypes ?? rule.eventTypes ?? [],
  175. query: rule.query ?? '',
  176. isQueryValid: true, // Assume valid until input is changed
  177. timeWindow: rule.timeWindow,
  178. environment: rule.environment || null,
  179. triggerErrors: new Map(),
  180. availableActions: null,
  181. triggers: triggersClone,
  182. resolveThreshold: rule.resolveThreshold,
  183. thresholdType: rule.thresholdType,
  184. thresholdPeriod: rule.thresholdPeriod ?? 1,
  185. comparisonDelta: rule.comparisonDelta ?? undefined,
  186. comparisonType: rule.comparisonDelta
  187. ? AlertRuleComparisonType.CHANGE
  188. : AlertRuleComparisonType.COUNT,
  189. project: this.props.project,
  190. owner: rule.owner,
  191. alertType: getAlertTypeFromAggregateDataset({aggregate, dataset}),
  192. };
  193. }
  194. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  195. const {organization} = this.props;
  196. // TODO(incidents): This is temporary until new API endpoints
  197. // We should be able to just fetch the rule if rule.id exists
  198. return [
  199. [
  200. 'availableActions',
  201. `/organizations/${organization.slug}/alert-rules/available-actions/`,
  202. ],
  203. ];
  204. }
  205. goBack() {
  206. const {router} = this.props;
  207. const {organization} = this.props;
  208. router.push(normalizeUrl(`/organizations/${organization.slug}/alerts/rules/`));
  209. }
  210. resetPollingState = (loadingSlackIndicator: Indicator) => {
  211. IndicatorStore.remove(loadingSlackIndicator);
  212. this.setState({loading: false, uuid: undefined});
  213. };
  214. fetchStatus(model: FormModel) {
  215. const loadingSlackIndicator = IndicatorStore.addMessage(
  216. t('Looking for your slack channel (this can take a while)'),
  217. 'loading'
  218. );
  219. // pollHandler calls itself until it gets either a success
  220. // or failed status but we don't want to poll forever so we pass
  221. // in a hard stop time of 3 minutes before we bail.
  222. const quitTime = Date.now() + POLLING_MAX_TIME_LIMIT;
  223. window.clearTimeout(this.pollingTimeout);
  224. this.pollingTimeout = window.setTimeout(() => {
  225. this.pollHandler(model, quitTime, loadingSlackIndicator);
  226. }, 1000);
  227. }
  228. pollHandler = async (
  229. model: FormModel,
  230. quitTime: number,
  231. loadingSlackIndicator: Indicator
  232. ) => {
  233. if (Date.now() > quitTime) {
  234. addErrorMessage(t('Looking for that channel took too long :('));
  235. this.resetPollingState(loadingSlackIndicator);
  236. return;
  237. }
  238. const {
  239. organization,
  240. onSubmitSuccess,
  241. params: {ruleId},
  242. } = this.props;
  243. const {uuid, project} = this.state;
  244. try {
  245. const response: RuleTaskResponse = await this.api.requestPromise(
  246. `/projects/${organization.slug}/${project.slug}/alert-rule-task/${uuid}/`
  247. );
  248. const {status, alertRule, error} = response;
  249. if (status === 'pending') {
  250. window.clearTimeout(this.pollingTimeout);
  251. this.pollingTimeout = window.setTimeout(() => {
  252. this.pollHandler(model, quitTime, loadingSlackIndicator);
  253. }, 1000);
  254. return;
  255. }
  256. this.resetPollingState(loadingSlackIndicator);
  257. if (status === 'failed') {
  258. this.handleRuleSaveFailure(error);
  259. }
  260. if (alertRule) {
  261. addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
  262. if (onSubmitSuccess) {
  263. onSubmitSuccess(alertRule, model);
  264. }
  265. }
  266. } catch {
  267. this.handleRuleSaveFailure(t('An error occurred'));
  268. this.resetPollingState(loadingSlackIndicator);
  269. }
  270. };
  271. /**
  272. * Checks to see if threshold is valid given target value, and state of
  273. * inverted threshold as well as the *other* threshold
  274. *
  275. * @param type The threshold type to be updated
  276. * @param value The new threshold value
  277. */
  278. isValidTrigger = (
  279. triggerIndex: number,
  280. trigger: Trigger,
  281. errors,
  282. resolveThreshold: number | '' | null
  283. ): boolean => {
  284. const {alertThreshold} = trigger;
  285. const {thresholdType} = this.state;
  286. // If value and/or other value is empty
  287. // then there are no checks to perform against
  288. if (!hasThresholdValue(alertThreshold) || !hasThresholdValue(resolveThreshold)) {
  289. return true;
  290. }
  291. // If this is alert threshold and not inverted, it can't be below resolve
  292. // If this is alert threshold and inverted, it can't be above resolve
  293. // If this is resolve threshold and not inverted, it can't be above resolve
  294. // If this is resolve threshold and inverted, it can't be below resolve
  295. // Since we're comparing non-inclusive thresholds here (>, <), we need
  296. // to modify the values when we compare. An example of why:
  297. // Alert > 0, resolve < 1. This means that we want to alert on values
  298. // of 1 or more, and resolve on values of 0 or less. This is valid, but
  299. // without modifying the values, this boundary case will fail.
  300. const isValid =
  301. thresholdType === AlertRuleThresholdType.BELOW
  302. ? alertThreshold - 1 < resolveThreshold + 1
  303. : alertThreshold + 1 > resolveThreshold - 1;
  304. const otherErrors = errors.get(triggerIndex) || {};
  305. if (isValid) {
  306. return true;
  307. }
  308. // Not valid... let's figure out an error message
  309. const isBelow = thresholdType === AlertRuleThresholdType.BELOW;
  310. let errorMessage = '';
  311. if (typeof resolveThreshold !== 'number') {
  312. errorMessage = isBelow
  313. ? t('Resolution threshold must be greater than alert')
  314. : t('Resolution threshold must be less than alert');
  315. } else {
  316. errorMessage = isBelow
  317. ? t('Alert threshold must be less than resolution')
  318. : t('Alert threshold must be greater than resolution');
  319. }
  320. errors.set(triggerIndex, {
  321. ...otherErrors,
  322. alertThreshold: errorMessage,
  323. });
  324. return false;
  325. };
  326. validateFieldInTrigger({errors, triggerIndex, field, message, isValid}) {
  327. // If valid, reset error for fieldName
  328. if (isValid()) {
  329. const {[field]: _validatedField, ...otherErrors} = errors.get(triggerIndex) || {};
  330. if (Object.keys(otherErrors).length > 0) {
  331. errors.set(triggerIndex, otherErrors);
  332. } else {
  333. errors.delete(triggerIndex);
  334. }
  335. return errors;
  336. }
  337. if (!errors.has(triggerIndex)) {
  338. errors.set(triggerIndex, {});
  339. }
  340. const currentErrors = errors.get(triggerIndex);
  341. errors.set(triggerIndex, {
  342. ...currentErrors,
  343. [field]: message,
  344. });
  345. return errors;
  346. }
  347. /**
  348. * Validate triggers
  349. *
  350. * @return Returns true if triggers are valid
  351. */
  352. validateTriggers(
  353. triggers = this.state.triggers,
  354. thresholdType = this.state.thresholdType,
  355. resolveThreshold = this.state.resolveThreshold,
  356. changedTriggerIndex?: number
  357. ) {
  358. const {comparisonType} = this.state;
  359. const triggerErrors = new Map();
  360. const requiredFields = ['label', 'alertThreshold'];
  361. triggers.forEach((trigger, triggerIndex) => {
  362. requiredFields.forEach(field => {
  363. // check required fields
  364. this.validateFieldInTrigger({
  365. errors: triggerErrors,
  366. triggerIndex,
  367. isValid: (): boolean => {
  368. if (trigger.label === AlertRuleTriggerType.CRITICAL) {
  369. return !isEmpty(trigger[field]);
  370. }
  371. // If warning trigger has actions, it must have a value
  372. return trigger.actions.length === 0 || !isEmpty(trigger[field]);
  373. },
  374. field,
  375. message: t('Field is required'),
  376. });
  377. });
  378. // Check thresholds
  379. this.isValidTrigger(
  380. changedTriggerIndex ?? triggerIndex,
  381. trigger,
  382. triggerErrors,
  383. resolveThreshold
  384. );
  385. });
  386. // If we have 2 triggers, we need to make sure that the critical and warning
  387. // alert thresholds are valid (e.g. if critical is above x, warning must be less than x)
  388. const criticalTriggerIndex = triggers.findIndex(
  389. ({label}) => label === AlertRuleTriggerType.CRITICAL
  390. );
  391. const warningTriggerIndex = criticalTriggerIndex ^ 1;
  392. const criticalTrigger = triggers[criticalTriggerIndex];
  393. const warningTrigger = triggers[warningTriggerIndex];
  394. const isEmptyWarningThreshold = isEmpty(warningTrigger.alertThreshold);
  395. const warningThreshold = warningTrigger.alertThreshold ?? 0;
  396. const criticalThreshold = criticalTrigger.alertThreshold ?? 0;
  397. const hasError =
  398. thresholdType === AlertRuleThresholdType.ABOVE ||
  399. comparisonType === AlertRuleComparisonType.CHANGE
  400. ? warningThreshold > criticalThreshold
  401. : warningThreshold < criticalThreshold;
  402. if (hasError && !isEmptyWarningThreshold) {
  403. [criticalTriggerIndex, warningTriggerIndex].forEach(index => {
  404. const otherErrors = triggerErrors.get(index) ?? {};
  405. triggerErrors.set(index, {
  406. ...otherErrors,
  407. alertThreshold:
  408. thresholdType === AlertRuleThresholdType.ABOVE ||
  409. comparisonType === AlertRuleComparisonType.CHANGE
  410. ? t('Warning threshold must be less than critical threshold')
  411. : t('Warning threshold must be greater than critical threshold'),
  412. });
  413. });
  414. }
  415. return triggerErrors;
  416. }
  417. handleFieldChange = (name: string, value: unknown) => {
  418. const {projects} = this.props;
  419. const dataset = this.checkOnDemandMetricsDataset(
  420. this.state.dataset,
  421. this.state.query
  422. );
  423. if (name === 'alertType') {
  424. this.setState({
  425. alertType: value as MetricAlertType,
  426. dataset,
  427. });
  428. return;
  429. }
  430. if (
  431. [
  432. 'aggregate',
  433. 'dataset',
  434. 'eventTypes',
  435. 'timeWindow',
  436. 'environment',
  437. 'comparisonDelta',
  438. 'projectId',
  439. 'alertType',
  440. ].includes(name)
  441. ) {
  442. this.setState(({project: _project, aggregate, alertType}) => {
  443. const newAlertType = getAlertTypeFromAggregateDataset({
  444. aggregate,
  445. dataset,
  446. });
  447. return {
  448. [name]: value,
  449. project:
  450. name === 'projectId' ? projects.find(({id}) => id === value) : _project,
  451. alertType: alertType !== newAlertType ? 'custom' : alertType,
  452. dataset,
  453. };
  454. });
  455. }
  456. };
  457. // We handle the filter update outside of the fieldChange handler since we
  458. // don't want to update the filter on every input change, just on blurs and
  459. // searches.
  460. handleFilterUpdate = (query: string, isQueryValid: boolean) => {
  461. const {organization, sessionId} = this.props;
  462. trackAnalytics('alert_builder.filter', {
  463. organization,
  464. session_id: sessionId,
  465. query,
  466. });
  467. const dataset = this.checkOnDemandMetricsDataset(this.state.dataset, query);
  468. this.setState({query, dataset, isQueryValid});
  469. };
  470. validateOnDemandMetricAlert() {
  471. return isValidOnDemandMetricAlert(
  472. this.state.dataset,
  473. this.state.aggregate,
  474. this.state.query
  475. );
  476. }
  477. handleSubmit = async (
  478. _data: Partial<MetricRule>,
  479. _onSubmitSuccess,
  480. _onSubmitError,
  481. _e,
  482. model: FormModel
  483. ) => {
  484. // This validates all fields *except* for Triggers
  485. const validRule = model.validateForm();
  486. // Validate Triggers
  487. const triggerErrors = this.validateTriggers();
  488. const validTriggers = Array.from(triggerErrors).length === 0;
  489. const validOnDemandAlert = this.validateOnDemandMetricAlert();
  490. if (!validTriggers) {
  491. this.setState(state => ({
  492. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  493. }));
  494. }
  495. if (!validRule || !validTriggers) {
  496. const missingFields = [
  497. !validRule && t('name'),
  498. !validRule && !validTriggers && t('and'),
  499. !validTriggers && t('critical threshold'),
  500. ].filter(x => x);
  501. addErrorMessage(t('Alert not valid: missing %s', missingFields.join(' ')));
  502. return;
  503. }
  504. if (!validOnDemandAlert) {
  505. addErrorMessage(
  506. t('%s is not supported for on-demand metric alerts', this.state.aggregate)
  507. );
  508. return;
  509. }
  510. const {
  511. organization,
  512. rule,
  513. onSubmitSuccess,
  514. location,
  515. sessionId,
  516. params: {ruleId},
  517. } = this.props;
  518. const {
  519. project,
  520. aggregate,
  521. resolveThreshold,
  522. triggers,
  523. thresholdType,
  524. thresholdPeriod,
  525. comparisonDelta,
  526. uuid,
  527. timeWindow,
  528. eventTypes,
  529. } = this.state;
  530. // Remove empty warning trigger
  531. const sanitizedTriggers = triggers.filter(
  532. trigger =>
  533. trigger.label !== AlertRuleTriggerType.WARNING || !isEmpty(trigger.alertThreshold)
  534. );
  535. // form model has all form state data, however we use local state to keep
  536. // track of the list of triggers (and actions within triggers)
  537. const loadingIndicator = IndicatorStore.addMessage(
  538. t('Saving your alert rule, hold on...'),
  539. 'loading'
  540. );
  541. try {
  542. const transaction = metric.startTransaction({name: 'saveAlertRule'});
  543. transaction.setTag('type', AlertRuleType.METRIC);
  544. transaction.setTag('operation', !rule.id ? 'create' : 'edit');
  545. for (const trigger of sanitizedTriggers) {
  546. for (const action of trigger.actions) {
  547. if (action.type === 'slack' || action.type === 'discord') {
  548. transaction.setTag(action.type, true);
  549. }
  550. }
  551. }
  552. transaction.setData('actions', sanitizedTriggers);
  553. const hasMetricDataset = organization.features.includes('mep-rollout-flag');
  554. this.setState({loading: true});
  555. const [data, , resp] = await addOrUpdateRule(
  556. this.api,
  557. organization.slug,
  558. {
  559. ...rule,
  560. ...model.getTransformedData(),
  561. projects: [project.slug],
  562. triggers: sanitizedTriggers,
  563. resolveThreshold: isEmpty(resolveThreshold) ? null : resolveThreshold,
  564. thresholdType,
  565. thresholdPeriod,
  566. comparisonDelta: comparisonDelta ?? null,
  567. timeWindow,
  568. aggregate,
  569. ...(hasMetricDataset
  570. ? {queryType: DatasetMEPAlertQueryTypes[rule.dataset]}
  571. : {}),
  572. // Remove eventTypes as it is no longer required for crash free
  573. eventTypes: isCrashFreeAlert(rule.dataset) ? undefined : eventTypes,
  574. dataset: this.determinePerformanceDataset(),
  575. },
  576. {
  577. duplicateRule: this.isDuplicateRule ? 'true' : 'false',
  578. wizardV3: 'true',
  579. referrer: location?.query?.referrer,
  580. sessionId,
  581. }
  582. );
  583. // if we get a 202 back it means that we have an async task
  584. // running to lookup and verify the channel id for Slack.
  585. if (resp?.status === 202) {
  586. // if we have a uuid in state, no need to start a new polling cycle
  587. if (!uuid) {
  588. this.setState({loading: true, uuid: data.uuid});
  589. this.fetchStatus(model);
  590. }
  591. } else {
  592. IndicatorStore.remove(loadingIndicator);
  593. this.setState({loading: false});
  594. addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
  595. if (onSubmitSuccess) {
  596. onSubmitSuccess(data, model);
  597. }
  598. }
  599. } catch (err) {
  600. IndicatorStore.remove(loadingIndicator);
  601. this.setState({loading: false});
  602. const errors = err?.responseJSON
  603. ? Array.isArray(err?.responseJSON)
  604. ? err?.responseJSON
  605. : Object.values(err?.responseJSON)
  606. : [];
  607. const apiErrors = errors.length > 0 ? `: ${errors.join(', ')}` : '';
  608. this.handleRuleSaveFailure(t('Unable to save alert%s', apiErrors));
  609. }
  610. };
  611. /**
  612. * Callback for when triggers change
  613. *
  614. * Re-validate triggers on every change and reset indicators when no errors
  615. */
  616. handleChangeTriggers = (triggers: Trigger[], triggerIndex?: number) => {
  617. this.setState(state => {
  618. let triggerErrors = state.triggerErrors;
  619. const newTriggerErrors = this.validateTriggers(
  620. triggers,
  621. state.thresholdType,
  622. state.resolveThreshold,
  623. triggerIndex
  624. );
  625. triggerErrors = newTriggerErrors;
  626. if (Array.from(newTriggerErrors).length === 0) {
  627. clearIndicators();
  628. }
  629. return {triggers, triggerErrors};
  630. });
  631. };
  632. handleThresholdTypeChange = (thresholdType: AlertRuleThresholdType) => {
  633. const {triggers} = this.state;
  634. const triggerErrors = this.validateTriggers(triggers, thresholdType);
  635. this.setState(state => ({
  636. thresholdType,
  637. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  638. }));
  639. };
  640. handleThresholdPeriodChange = (value: number) => {
  641. this.setState({thresholdPeriod: value});
  642. };
  643. handleResolveThresholdChange = (
  644. resolveThreshold: UnsavedMetricRule['resolveThreshold']
  645. ) => {
  646. this.setState(state => {
  647. const triggerErrors = this.validateTriggers(
  648. state.triggers,
  649. state.thresholdType,
  650. resolveThreshold
  651. );
  652. if (Array.from(triggerErrors).length === 0) {
  653. clearIndicators();
  654. }
  655. return {resolveThreshold, triggerErrors};
  656. });
  657. };
  658. handleComparisonTypeChange = (value: AlertRuleComparisonType) => {
  659. const comparisonDelta =
  660. value === AlertRuleComparisonType.COUNT
  661. ? undefined
  662. : this.state.comparisonDelta ?? DEFAULT_CHANGE_COMP_DELTA;
  663. const timeWindow = this.state.comparisonDelta
  664. ? DEFAULT_COUNT_TIME_WINDOW
  665. : DEFAULT_CHANGE_TIME_WINDOW;
  666. this.setState({comparisonType: value, comparisonDelta, timeWindow});
  667. };
  668. handleDeleteRule = async () => {
  669. const {organization, params} = this.props;
  670. const {ruleId} = params;
  671. try {
  672. await this.api.requestPromise(
  673. `/organizations/${organization.slug}/alert-rules/${ruleId}/`,
  674. {
  675. method: 'DELETE',
  676. }
  677. );
  678. this.goBack();
  679. } catch (_err) {
  680. addErrorMessage(t('Error deleting rule'));
  681. }
  682. };
  683. handleRuleSaveFailure = (msg: ReactNode) => {
  684. addErrorMessage(msg);
  685. metric.endTransaction({name: 'saveAlertRule'});
  686. };
  687. handleCancel = () => {
  688. this.goBack();
  689. };
  690. handleMEPAlertDataset = (data: EventsStats | MultiSeriesEventsStats | null) => {
  691. const {isMetricsData} = data ?? {};
  692. const {organization} = this.props;
  693. if (
  694. isMetricsData === undefined ||
  695. !organization.features.includes('mep-rollout-flag')
  696. ) {
  697. return;
  698. }
  699. const {dataset} = this.state;
  700. if (isMetricsData && dataset === Dataset.TRANSACTIONS) {
  701. this.setState({dataset: Dataset.GENERIC_METRICS});
  702. }
  703. if (!isMetricsData && dataset === Dataset.GENERIC_METRICS) {
  704. this.setState({dataset: Dataset.TRANSACTIONS});
  705. }
  706. };
  707. handleTimeSeriesDataFetched = (data: EventsStats | MultiSeriesEventsStats | null) => {
  708. const {isExtrapolatedData} = data ?? {};
  709. if (shouldShowOnDemandMetricAlertUI(this.props.organization)) {
  710. this.setState({isExtrapolatedChartData: Boolean(isExtrapolatedData)});
  711. }
  712. const {dataset, aggregate, query} = this.state;
  713. if (!isOnDemandMetricAlert(dataset, aggregate, query)) {
  714. this.handleMEPAlertDataset(data);
  715. }
  716. };
  717. // If the user is creating an on-demand metric alert, we want to override the dataset
  718. // to be generic metrics instead of transactions
  719. checkOnDemandMetricsDataset = (dataset: Dataset, query: string) => {
  720. if (!hasOnDemandMetricAlertFeature(this.props.organization)) {
  721. return dataset;
  722. }
  723. if (dataset !== Dataset.TRANSACTIONS || !isOnDemandQueryString(query)) {
  724. return dataset;
  725. }
  726. return Dataset.GENERIC_METRICS;
  727. };
  728. // We are not allowing the creation of new transaction alerts
  729. determinePerformanceDataset = () => {
  730. // TODO: once all alerts are migrated to MEP, we can set the default to GENERIC_METRICS and remove this as well as
  731. // logic in handleMEPDataset, handleTimeSeriesDataFetched and checkOnDemandMetricsDataset
  732. const {dataset} = this.state;
  733. const {organization} = this.props;
  734. const hasMetricsFeatureFlags =
  735. organization.features.includes('mep-rollout-flag') ||
  736. hasOnDemandMetricAlertFeature(organization);
  737. if (hasMetricsFeatureFlags && dataset === Dataset.TRANSACTIONS) {
  738. return Dataset.GENERIC_METRICS;
  739. }
  740. return dataset;
  741. };
  742. renderLoading() {
  743. return this.renderBody();
  744. }
  745. renderTriggerChart() {
  746. const {organization, ruleId, rule} = this.props;
  747. const {
  748. query,
  749. project,
  750. timeWindow,
  751. triggers,
  752. aggregate,
  753. environment,
  754. thresholdType,
  755. comparisonDelta,
  756. comparisonType,
  757. resolveThreshold,
  758. eventTypes,
  759. dataset,
  760. alertType,
  761. isQueryValid,
  762. location,
  763. } = this.state;
  764. const chartProps = {
  765. organization,
  766. projects: [project],
  767. triggers,
  768. location,
  769. query: this.chartQuery,
  770. aggregate,
  771. dataset,
  772. newAlertOrQuery: !ruleId || query !== rule.query,
  773. timeWindow,
  774. environment,
  775. resolveThreshold,
  776. thresholdType,
  777. comparisonDelta,
  778. comparisonType,
  779. isQueryValid,
  780. isOnDemandMetricAlert: isOnDemandMetricAlert(dataset, aggregate, query),
  781. onDataLoaded: this.handleTimeSeriesDataFetched,
  782. };
  783. const wizardBuilderChart = (
  784. <TriggersChart
  785. {...chartProps}
  786. header={
  787. <ChartHeader>
  788. <AlertName>{AlertWizardAlertNames[alertType]}</AlertName>
  789. {!isCrashFreeAlert(dataset) && (
  790. <AlertInfo>
  791. <StyledCircleIndicator size={8} />
  792. <Aggregate>{aggregate}</Aggregate>
  793. event.type:{eventTypes?.join(',')}
  794. </AlertInfo>
  795. )}
  796. </ChartHeader>
  797. }
  798. />
  799. );
  800. return wizardBuilderChart;
  801. }
  802. renderBody() {
  803. const {
  804. organization,
  805. ruleId,
  806. rule,
  807. onSubmitSuccess,
  808. router,
  809. disableProjectSelector,
  810. eventView,
  811. } = this.props;
  812. const {
  813. name,
  814. query,
  815. project,
  816. timeWindow,
  817. triggers,
  818. aggregate,
  819. thresholdType,
  820. thresholdPeriod,
  821. comparisonDelta,
  822. comparisonType,
  823. resolveThreshold,
  824. loading,
  825. eventTypes,
  826. dataset,
  827. alertType,
  828. isExtrapolatedChartData,
  829. } = this.state;
  830. const wizardBuilderChart = this.renderTriggerChart();
  831. const triggerForm = (disabled: boolean) => (
  832. <Triggers
  833. disabled={disabled}
  834. projects={[project]}
  835. errors={this.state.triggerErrors}
  836. triggers={triggers}
  837. aggregate={aggregate}
  838. resolveThreshold={resolveThreshold}
  839. thresholdPeriod={thresholdPeriod}
  840. thresholdType={thresholdType}
  841. comparisonType={comparisonType}
  842. currentProject={project.slug}
  843. organization={organization}
  844. availableActions={this.state.availableActions}
  845. onChange={this.handleChangeTriggers}
  846. onThresholdTypeChange={this.handleThresholdTypeChange}
  847. onThresholdPeriodChange={this.handleThresholdPeriodChange}
  848. onResolveThresholdChange={this.handleResolveThresholdChange}
  849. />
  850. );
  851. const ruleNameOwnerForm = (disabled: boolean) => (
  852. <RuleNameOwnerForm disabled={disabled} project={project} />
  853. );
  854. const thresholdTypeForm = (disabled: boolean) => (
  855. <ThresholdTypeForm
  856. comparisonType={comparisonType}
  857. dataset={dataset}
  858. disabled={disabled}
  859. onComparisonDeltaChange={value =>
  860. this.handleFieldChange('comparisonDelta', value)
  861. }
  862. onComparisonTypeChange={this.handleComparisonTypeChange}
  863. organization={organization}
  864. comparisonDelta={comparisonDelta}
  865. />
  866. );
  867. const hasAlertWrite = hasEveryAccess(['alerts:write'], {organization, project});
  868. const formDisabled = loading || !hasAlertWrite;
  869. const submitDisabled = formDisabled || !this.state.isQueryValid;
  870. const showMigrationWarning =
  871. !!ruleId && hasMigrationFeatureFlag(organization) && ruleNeedsMigration(rule);
  872. return (
  873. <Main fullWidth>
  874. <PermissionAlert access={['alerts:write']} project={project} />
  875. {eventView && (
  876. <IncompatibleAlertQuery orgSlug={organization.slug} eventView={eventView} />
  877. )}
  878. <Form
  879. model={this.form}
  880. apiMethod={ruleId ? 'PUT' : 'POST'}
  881. apiEndpoint={`/organizations/${organization.slug}/alert-rules/${
  882. ruleId ? `${ruleId}/` : ''
  883. }`}
  884. submitDisabled={submitDisabled}
  885. initialData={{
  886. name,
  887. dataset,
  888. eventTypes,
  889. aggregate,
  890. query,
  891. timeWindow: rule.timeWindow,
  892. environment: rule.environment || null,
  893. owner: rule.owner,
  894. projectId: project.id,
  895. alertType,
  896. }}
  897. saveOnBlur={false}
  898. onSubmit={this.handleSubmit}
  899. onSubmitSuccess={onSubmitSuccess}
  900. onCancel={this.handleCancel}
  901. onFieldChange={this.handleFieldChange}
  902. extraButton={
  903. rule.id ? (
  904. <Confirm
  905. disabled={formDisabled}
  906. message={t(
  907. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  908. rule.name
  909. )}
  910. header={<h5>{t('Delete Alert Rule?')}</h5>}
  911. priority="danger"
  912. confirmText={t('Delete Rule')}
  913. onConfirm={this.handleDeleteRule}
  914. >
  915. <Button priority="danger">{t('Delete Rule')}</Button>
  916. </Confirm>
  917. ) : null
  918. }
  919. submitLabel={t('Save Rule')}
  920. >
  921. <List symbol="colored-numeric">
  922. <RuleConditionsForm
  923. project={project}
  924. organization={organization}
  925. router={router}
  926. disabled={formDisabled}
  927. thresholdChart={wizardBuilderChart}
  928. onFilterSearch={this.handleFilterUpdate}
  929. allowChangeEventTypes={alertType === 'custom' || dataset === Dataset.ERRORS}
  930. alertType={alertType}
  931. dataset={dataset}
  932. timeWindow={timeWindow}
  933. comparisonType={comparisonType}
  934. comparisonDelta={comparisonDelta}
  935. onComparisonDeltaChange={value =>
  936. this.handleFieldChange('comparisonDelta', value)
  937. }
  938. onTimeWindowChange={value => this.handleFieldChange('timeWindow', value)}
  939. disableProjectSelector={disableProjectSelector}
  940. isExtrapolatedChartData={isExtrapolatedChartData}
  941. />
  942. <AlertListItem>{t('Set thresholds')}</AlertListItem>
  943. {thresholdTypeForm(formDisabled)}
  944. {showMigrationWarning && (
  945. <Alert
  946. type="warning"
  947. showIcon
  948. trailingItems={
  949. <Button size="xs" type="submit">
  950. {t('Looks good to me!')}
  951. </Button>
  952. }
  953. >
  954. {tct(
  955. 'Check the chart above and make sure the current thresholds are still valid, given that this alert is now based on [tooltip:total events].',
  956. {
  957. tooltip: (
  958. <Tooltip
  959. showUnderline
  960. isHoverable
  961. title={
  962. <Fragment>
  963. {t(
  964. 'Performance alerts are based on all the events you send to Sentry, not just the ones that are stored'
  965. )}
  966. <br />
  967. <ExternalLink href="https://docs.sentry.io/product/performance/retention-priorities/">
  968. {t('Learn more')}
  969. </ExternalLink>
  970. </Fragment>
  971. }
  972. />
  973. ),
  974. }
  975. )}
  976. </Alert>
  977. )}
  978. {triggerForm(formDisabled)}
  979. {ruleNameOwnerForm(formDisabled)}
  980. </List>
  981. </Form>
  982. </Main>
  983. );
  984. }
  985. }
  986. const Main = styled(Layout.Main)`
  987. max-width: 1000px;
  988. `;
  989. const StyledListItem = styled(ListItem)`
  990. margin: ${space(2)} 0 ${space(1)} 0;
  991. font-size: ${p => p.theme.fontSizeExtraLarge};
  992. `;
  993. const AlertListItem = styled(StyledListItem)`
  994. margin-top: 0;
  995. `;
  996. const ChartHeader = styled('div')`
  997. padding: ${space(2)} ${space(3)} 0 ${space(3)};
  998. margin-bottom: -${space(1.5)};
  999. `;
  1000. const AlertName = styled(HeaderTitleLegend)`
  1001. position: relative;
  1002. `;
  1003. const AlertInfo = styled('div')`
  1004. font-size: ${p => p.theme.fontSizeSmall};
  1005. font-family: ${p => p.theme.text.family};
  1006. font-weight: normal;
  1007. color: ${p => p.theme.textColor};
  1008. `;
  1009. const StyledCircleIndicator = styled(CircleIndicator)`
  1010. background: ${p => p.theme.formText};
  1011. height: ${space(1)};
  1012. margin-right: ${space(0.5)};
  1013. `;
  1014. const Aggregate = styled('span')`
  1015. margin-right: ${space(1)};
  1016. `;
  1017. export default withProjects(RuleFormContainer);