ruleForm.tsx 39 KB

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