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 {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:
  222. rule.activationCondition || ActivationConditionType.RELEASE_CREATION,
  223. };
  224. }
  225. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  226. const {organization} = this.props;
  227. // TODO(incidents): This is temporary until new API endpoints
  228. // We should be able to just fetch the rule if rule.id exists
  229. return [
  230. [
  231. 'availableActions',
  232. `/organizations/${organization.slug}/alert-rules/available-actions/`,
  233. ],
  234. ];
  235. }
  236. goBack() {
  237. const {router} = this.props;
  238. const {organization} = this.props;
  239. router.push(normalizeUrl(`/organizations/${organization.slug}/alerts/rules/`));
  240. }
  241. resetPollingState = (loadingSlackIndicator: Indicator) => {
  242. IndicatorStore.remove(loadingSlackIndicator);
  243. this.uuid = null;
  244. this.setState({loading: false});
  245. };
  246. fetchStatus(model: FormModel) {
  247. const loadingSlackIndicator = IndicatorStore.addMessage(
  248. t('Looking for your slack channel (this can take a while)'),
  249. 'loading'
  250. );
  251. // pollHandler calls itself until it gets either a success
  252. // or failed status but we don't want to poll forever so we pass
  253. // in a hard stop time of 3 minutes before we bail.
  254. const quitTime = Date.now() + POLLING_MAX_TIME_LIMIT;
  255. window.clearTimeout(this.pollingTimeout);
  256. this.pollingTimeout = window.setTimeout(() => {
  257. this.pollHandler(model, quitTime, loadingSlackIndicator);
  258. }, 1000);
  259. }
  260. pollHandler = async (
  261. model: FormModel,
  262. quitTime: number,
  263. loadingSlackIndicator: Indicator
  264. ) => {
  265. if (Date.now() > quitTime) {
  266. addErrorMessage(t('Looking for that channel took too long :('));
  267. this.resetPollingState(loadingSlackIndicator);
  268. return;
  269. }
  270. const {
  271. organization,
  272. onSubmitSuccess,
  273. params: {ruleId},
  274. } = this.props;
  275. const {project} = this.state;
  276. try {
  277. const response: RuleTaskResponse = await this.api.requestPromise(
  278. `/projects/${organization.slug}/${project.slug}/alert-rule-task/${this.uuid}/`
  279. );
  280. const {status, alertRule, error} = response;
  281. if (status === 'pending') {
  282. window.clearTimeout(this.pollingTimeout);
  283. this.pollingTimeout = window.setTimeout(() => {
  284. this.pollHandler(model, quitTime, loadingSlackIndicator);
  285. }, 1000);
  286. return;
  287. }
  288. this.resetPollingState(loadingSlackIndicator);
  289. if (status === 'failed') {
  290. this.handleRuleSaveFailure(error);
  291. }
  292. if (alertRule) {
  293. addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
  294. if (onSubmitSuccess) {
  295. onSubmitSuccess(alertRule, model);
  296. }
  297. }
  298. } catch {
  299. this.handleRuleSaveFailure(t('An error occurred'));
  300. this.resetPollingState(loadingSlackIndicator);
  301. }
  302. };
  303. /**
  304. * Checks to see if threshold is valid given target value, and state of
  305. * inverted threshold as well as the *other* threshold
  306. *
  307. * @param type The threshold type to be updated
  308. * @param value The new threshold value
  309. */
  310. isValidTrigger = (
  311. triggerIndex: number,
  312. trigger: Trigger,
  313. errors,
  314. resolveThreshold: number | '' | null
  315. ): boolean => {
  316. const {alertThreshold} = trigger;
  317. const {thresholdType} = this.state;
  318. // If value and/or other value is empty
  319. // then there are no checks to perform against
  320. if (!hasThresholdValue(alertThreshold) || !hasThresholdValue(resolveThreshold)) {
  321. return true;
  322. }
  323. // If this is alert threshold and not inverted, it can't be below resolve
  324. // If this is alert threshold and inverted, it can't be above resolve
  325. // If this is resolve threshold and not inverted, it can't be above resolve
  326. // If this is resolve threshold and inverted, it can't be below resolve
  327. // Since we're comparing non-inclusive thresholds here (>, <), we need
  328. // to modify the values when we compare. An example of why:
  329. // Alert > 0, resolve < 1. This means that we want to alert on values
  330. // of 1 or more, and resolve on values of 0 or less. This is valid, but
  331. // without modifying the values, this boundary case will fail.
  332. const isValid =
  333. thresholdType === AlertRuleThresholdType.BELOW
  334. ? alertThreshold - 1 < resolveThreshold + 1
  335. : alertThreshold + 1 > resolveThreshold - 1;
  336. const otherErrors = errors.get(triggerIndex) || {};
  337. if (isValid) {
  338. return true;
  339. }
  340. // Not valid... let's figure out an error message
  341. const isBelow = thresholdType === AlertRuleThresholdType.BELOW;
  342. let errorMessage = '';
  343. if (typeof resolveThreshold !== 'number') {
  344. errorMessage = isBelow
  345. ? t('Resolution threshold must be greater than alert')
  346. : t('Resolution threshold must be less than alert');
  347. } else {
  348. errorMessage = isBelow
  349. ? t('Alert threshold must be less than resolution')
  350. : t('Alert threshold must be greater than resolution');
  351. }
  352. errors.set(triggerIndex, {
  353. ...otherErrors,
  354. alertThreshold: errorMessage,
  355. });
  356. return false;
  357. };
  358. validateFieldInTrigger({errors, triggerIndex, field, message, isValid}) {
  359. // If valid, reset error for fieldName
  360. if (isValid()) {
  361. const {[field]: _validatedField, ...otherErrors} = errors.get(triggerIndex) || {};
  362. if (Object.keys(otherErrors).length > 0) {
  363. errors.set(triggerIndex, otherErrors);
  364. } else {
  365. errors.delete(triggerIndex);
  366. }
  367. return errors;
  368. }
  369. if (!errors.has(triggerIndex)) {
  370. errors.set(triggerIndex, {});
  371. }
  372. const currentErrors = errors.get(triggerIndex);
  373. errors.set(triggerIndex, {
  374. ...currentErrors,
  375. [field]: message,
  376. });
  377. return errors;
  378. }
  379. /**
  380. * Validate triggers
  381. *
  382. * @return Returns true if triggers are valid
  383. */
  384. validateTriggers(
  385. triggers = this.state.triggers,
  386. thresholdType = this.state.thresholdType,
  387. resolveThreshold = this.state.resolveThreshold,
  388. changedTriggerIndex?: number
  389. ) {
  390. const {comparisonType} = this.state;
  391. const triggerErrors = new Map();
  392. const requiredFields = ['label', 'alertThreshold'];
  393. triggers.forEach((trigger, triggerIndex) => {
  394. requiredFields.forEach(field => {
  395. // check required fields
  396. this.validateFieldInTrigger({
  397. errors: triggerErrors,
  398. triggerIndex,
  399. isValid: (): boolean => {
  400. if (trigger.label === AlertRuleTriggerType.CRITICAL) {
  401. return !isEmpty(trigger[field]);
  402. }
  403. // If warning trigger has actions, it must have a value
  404. return trigger.actions.length === 0 || !isEmpty(trigger[field]);
  405. },
  406. field,
  407. message: t('Field is required'),
  408. });
  409. });
  410. // Check thresholds
  411. this.isValidTrigger(
  412. changedTriggerIndex ?? triggerIndex,
  413. trigger,
  414. triggerErrors,
  415. resolveThreshold
  416. );
  417. });
  418. // If we have 2 triggers, we need to make sure that the critical and warning
  419. // alert thresholds are valid (e.g. if critical is above x, warning must be less than x)
  420. const criticalTriggerIndex = triggers.findIndex(
  421. ({label}) => label === AlertRuleTriggerType.CRITICAL
  422. );
  423. const warningTriggerIndex = criticalTriggerIndex ^ 1;
  424. const criticalTrigger = triggers[criticalTriggerIndex];
  425. const warningTrigger = triggers[warningTriggerIndex];
  426. const isEmptyWarningThreshold = isEmpty(warningTrigger.alertThreshold);
  427. const warningThreshold = warningTrigger.alertThreshold ?? 0;
  428. const criticalThreshold = criticalTrigger.alertThreshold ?? 0;
  429. const hasError =
  430. thresholdType === AlertRuleThresholdType.ABOVE ||
  431. comparisonType === AlertRuleComparisonType.CHANGE
  432. ? warningThreshold > criticalThreshold
  433. : warningThreshold < criticalThreshold;
  434. if (hasError && !isEmptyWarningThreshold) {
  435. [criticalTriggerIndex, warningTriggerIndex].forEach(index => {
  436. const otherErrors = triggerErrors.get(index) ?? {};
  437. triggerErrors.set(index, {
  438. ...otherErrors,
  439. alertThreshold:
  440. thresholdType === AlertRuleThresholdType.ABOVE ||
  441. comparisonType === AlertRuleComparisonType.CHANGE
  442. ? t('Warning threshold must be less than critical threshold')
  443. : t('Warning threshold must be greater than critical threshold'),
  444. });
  445. });
  446. }
  447. return triggerErrors;
  448. }
  449. validateMri = () => {
  450. const {aggregate} = this.state;
  451. return aggregate !== DEFAULT_METRIC_ALERT_FIELD;
  452. };
  453. handleFieldChange = (name: string, value: unknown) => {
  454. const {projects} = this.props;
  455. if (name === 'alertType') {
  456. this.setState(({dataset}) => ({
  457. alertType: value as MetricAlertType,
  458. dataset: this.checkOnDemandMetricsDataset(dataset, this.state.query),
  459. }));
  460. return;
  461. }
  462. if (
  463. [
  464. 'aggregate',
  465. 'dataset',
  466. 'eventTypes',
  467. 'timeWindow',
  468. 'environment',
  469. 'comparisonDelta',
  470. 'projectId',
  471. 'alertType',
  472. ].includes(name)
  473. ) {
  474. this.setState(({project: _project, dataset: _dataset, aggregate, alertType}) => {
  475. const dataset = this.checkOnDemandMetricsDataset(
  476. name === 'dataset' ? (value as Dataset) : _dataset,
  477. this.state.query
  478. );
  479. const newAlertType = getAlertTypeFromAggregateDataset({
  480. aggregate,
  481. dataset,
  482. });
  483. return {
  484. [name]: value,
  485. project:
  486. name === 'projectId' ? projects.find(({id}) => id === value) : _project,
  487. alertType: alertType !== newAlertType ? 'custom_transactions' : alertType,
  488. dataset,
  489. };
  490. });
  491. }
  492. };
  493. // We handle the filter update outside of the fieldChange handler since we
  494. // don't want to update the filter on every input change, just on blurs and
  495. // searches.
  496. handleFilterUpdate = (query: string, isQueryValid: boolean) => {
  497. const {organization, sessionId} = this.props;
  498. trackAnalytics('alert_builder.filter', {
  499. organization,
  500. session_id: sessionId,
  501. query,
  502. });
  503. const dataset = this.checkOnDemandMetricsDataset(this.state.dataset, query);
  504. this.setState({query, dataset, isQueryValid});
  505. };
  506. handleMonitorTypeSelect = (activatedAlertFields: {
  507. activationCondition?: ActivationConditionType | undefined;
  508. monitorType?: MonitorType;
  509. monitorWindowSuffix?: string | undefined;
  510. monitorWindowValue?: number | undefined;
  511. }) => {
  512. const {monitorType} = activatedAlertFields;
  513. let updatedFields = activatedAlertFields;
  514. if (monitorType === MonitorType.CONTINUOUS) {
  515. updatedFields = {
  516. ...updatedFields,
  517. activationCondition: undefined,
  518. monitorWindowValue: undefined,
  519. };
  520. }
  521. this.setState(updatedFields as State);
  522. };
  523. validateOnDemandMetricAlert() {
  524. if (
  525. !isOnDemandMetricAlert(this.state.dataset, this.state.aggregate, this.state.query)
  526. ) {
  527. return true;
  528. }
  529. return !this.state.aggregate.includes(AggregationKey.PERCENTILE);
  530. }
  531. validateActivatedAlerts() {
  532. const {organization} = this.props;
  533. const {monitorType, activationCondition, timeWindow} = this.state;
  534. const hasActivatedAlerts = organization.features.includes('activated-alert-rules');
  535. return (
  536. !hasActivatedAlerts ||
  537. monitorType !== MonitorType.ACTIVATED ||
  538. (activationCondition !== undefined && timeWindow)
  539. );
  540. }
  541. validateSubmit = model => {
  542. if (!this.validateMri()) {
  543. addErrorMessage(t('You need to select a metric before you can save the alert'));
  544. return false;
  545. }
  546. // This validates all fields *except* for Triggers
  547. const validRule = model.validateForm();
  548. // Validate Triggers
  549. const triggerErrors = this.validateTriggers();
  550. const validTriggers = Array.from(triggerErrors).length === 0;
  551. const validOnDemandAlert = this.validateOnDemandMetricAlert();
  552. const validActivatedAlerts = this.validateActivatedAlerts();
  553. if (!validTriggers) {
  554. this.setState(state => ({
  555. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  556. }));
  557. }
  558. if (!validRule || !validTriggers) {
  559. const missingFields = [
  560. !validRule && t('name'),
  561. !validRule && !validTriggers && t('and'),
  562. !validTriggers && t('critical threshold'),
  563. ].filter(x => x);
  564. addErrorMessage(t('Alert not valid: missing %s', missingFields.join(' ')));
  565. return false;
  566. }
  567. if (!validOnDemandAlert) {
  568. addErrorMessage(
  569. t('%s is not supported for on-demand metric alerts', this.state.aggregate)
  570. );
  571. return false;
  572. }
  573. if (!validActivatedAlerts) {
  574. addErrorMessage(
  575. t('Activation condition and monitor window must be set for activated alerts')
  576. );
  577. return false;
  578. }
  579. return true;
  580. };
  581. handleSubmit = async (
  582. _data: Partial<MetricRule>,
  583. _onSubmitSuccess,
  584. _onSubmitError,
  585. _e,
  586. model: FormModel
  587. ) => {
  588. if (!this.validateSubmit(model)) {
  589. return;
  590. }
  591. const {
  592. organization,
  593. rule,
  594. onSubmitSuccess,
  595. location,
  596. sessionId,
  597. params: {ruleId},
  598. } = this.props;
  599. const {
  600. project,
  601. aggregate,
  602. resolveThreshold,
  603. triggers,
  604. thresholdType,
  605. thresholdPeriod,
  606. comparisonDelta,
  607. timeWindow,
  608. eventTypes,
  609. monitorType,
  610. activationCondition,
  611. } = this.state;
  612. // Remove empty warning trigger
  613. const sanitizedTriggers = triggers.filter(
  614. trigger =>
  615. trigger.label !== AlertRuleTriggerType.WARNING || !isEmpty(trigger.alertThreshold)
  616. );
  617. const hasActivatedAlerts = organization.features.includes('activated-alert-rules');
  618. // form model has all form state data, however we use local state to keep
  619. // track of the list of triggers (and actions within triggers)
  620. const loadingIndicator = IndicatorStore.addMessage(
  621. t('Saving your alert rule, hold on...'),
  622. 'loading'
  623. );
  624. await Sentry.withScope(async scope => {
  625. try {
  626. scope.setTag('type', AlertRuleType.METRIC);
  627. scope.setTag('operation', !rule.id ? 'create' : 'edit');
  628. for (const trigger of sanitizedTriggers) {
  629. for (const action of trigger.actions) {
  630. if (action.type === 'slack' || action.type === 'discord') {
  631. scope.setTag(action.type, true);
  632. }
  633. }
  634. }
  635. scope.setExtra('actions', sanitizedTriggers);
  636. metric.startSpan({name: 'saveAlertRule'});
  637. let activatedAlertFields = {};
  638. if (hasActivatedAlerts) {
  639. activatedAlertFields = {
  640. monitorType,
  641. activationCondition,
  642. };
  643. }
  644. const dataset = this.determinePerformanceDataset();
  645. this.setState({loading: true});
  646. // Add or update is just the PUT/POST to the org alert-rules api
  647. // we're splatting the full rule in, then overwriting all the data?
  648. const [data, , resp] = await addOrUpdateRule(
  649. this.api,
  650. organization.slug,
  651. {
  652. ...rule, // existing rule
  653. ...model.getTransformedData(), // form data
  654. ...activatedAlertFields,
  655. projects: [project.slug],
  656. triggers: sanitizedTriggers,
  657. resolveThreshold: isEmpty(resolveThreshold) ? null : resolveThreshold,
  658. thresholdType,
  659. thresholdPeriod,
  660. comparisonDelta: comparisonDelta ?? null,
  661. timeWindow,
  662. aggregate,
  663. // Remove eventTypes as it is no longer required for crash free
  664. eventTypes: isCrashFreeAlert(rule.dataset) ? undefined : eventTypes,
  665. dataset,
  666. queryType: DatasetMEPAlertQueryTypes[dataset],
  667. },
  668. {
  669. duplicateRule: this.isDuplicateRule ? 'true' : 'false',
  670. wizardV3: 'true',
  671. referrer: location?.query?.referrer,
  672. sessionId,
  673. ...getForceMetricsLayerQueryExtras(organization, dataset),
  674. }
  675. );
  676. // if we get a 202 back it means that we have an async task
  677. // running to lookup and verify the channel id for Slack.
  678. if (resp?.status === 202) {
  679. // if we have a uuid in state, no need to start a new polling cycle
  680. if (!this.uuid) {
  681. this.uuid = data.uuid;
  682. this.setState({loading: true});
  683. this.fetchStatus(model);
  684. }
  685. } else {
  686. IndicatorStore.remove(loadingIndicator);
  687. this.setState({loading: false});
  688. addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
  689. if (onSubmitSuccess) {
  690. onSubmitSuccess(data, model);
  691. }
  692. }
  693. } catch (err) {
  694. IndicatorStore.remove(loadingIndicator);
  695. this.setState({loading: false});
  696. const errors = err?.responseJSON
  697. ? Array.isArray(err?.responseJSON)
  698. ? err?.responseJSON
  699. : Object.values(err?.responseJSON)
  700. : [];
  701. const apiErrors = errors.length > 0 ? `: ${errors.join(', ')}` : '';
  702. this.handleRuleSaveFailure(t('Unable to save alert%s', apiErrors));
  703. }
  704. });
  705. };
  706. /**
  707. * Callback for when triggers change
  708. *
  709. * Re-validate triggers on every change and reset indicators when no errors
  710. */
  711. handleChangeTriggers = (triggers: Trigger[], triggerIndex?: number) => {
  712. this.setState(state => {
  713. let triggerErrors = state.triggerErrors;
  714. const newTriggerErrors = this.validateTriggers(
  715. triggers,
  716. state.thresholdType,
  717. state.resolveThreshold,
  718. triggerIndex
  719. );
  720. triggerErrors = newTriggerErrors;
  721. if (Array.from(newTriggerErrors).length === 0) {
  722. clearIndicators();
  723. }
  724. return {triggers, triggerErrors, triggersHaveChanged: true};
  725. });
  726. };
  727. handleThresholdTypeChange = (thresholdType: AlertRuleThresholdType) => {
  728. const {triggers} = this.state;
  729. const triggerErrors = this.validateTriggers(triggers, thresholdType);
  730. this.setState(state => ({
  731. thresholdType,
  732. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  733. }));
  734. };
  735. handleThresholdPeriodChange = (value: number) => {
  736. this.setState({thresholdPeriod: value});
  737. };
  738. handleResolveThresholdChange = (
  739. resolveThreshold: UnsavedMetricRule['resolveThreshold']
  740. ) => {
  741. this.setState(state => {
  742. const triggerErrors = this.validateTriggers(
  743. state.triggers,
  744. state.thresholdType,
  745. resolveThreshold
  746. );
  747. if (Array.from(triggerErrors).length === 0) {
  748. clearIndicators();
  749. }
  750. return {resolveThreshold, triggerErrors};
  751. });
  752. };
  753. handleComparisonTypeChange = (value: AlertRuleComparisonType) => {
  754. const comparisonDelta =
  755. value === AlertRuleComparisonType.COUNT
  756. ? undefined
  757. : this.state.comparisonDelta ?? DEFAULT_CHANGE_COMP_DELTA;
  758. const timeWindow = this.state.comparisonDelta
  759. ? DEFAULT_COUNT_TIME_WINDOW
  760. : DEFAULT_CHANGE_TIME_WINDOW;
  761. this.setState({comparisonType: value, comparisonDelta, timeWindow});
  762. };
  763. handleDeleteRule = async () => {
  764. const {organization, params} = this.props;
  765. const {ruleId} = params;
  766. try {
  767. await this.api.requestPromise(
  768. `/organizations/${organization.slug}/alert-rules/${ruleId}/`,
  769. {
  770. method: 'DELETE',
  771. }
  772. );
  773. this.goBack();
  774. } catch (_err) {
  775. addErrorMessage(t('Error deleting rule'));
  776. }
  777. };
  778. handleRuleSaveFailure = (msg: ReactNode) => {
  779. addErrorMessage(msg);
  780. metric.endSpan({name: 'saveAlertRule'});
  781. };
  782. handleCancel = () => {
  783. this.goBack();
  784. };
  785. handleMEPAlertDataset = (data: EventsStats | MultiSeriesEventsStats | null) => {
  786. const {isMetricsData} = data ?? {};
  787. const {organization} = this.props;
  788. if (
  789. isMetricsData === undefined ||
  790. !organization.features.includes('mep-rollout-flag')
  791. ) {
  792. return;
  793. }
  794. const {dataset} = this.state;
  795. if (isMetricsData && dataset === Dataset.TRANSACTIONS) {
  796. this.setState({dataset: Dataset.GENERIC_METRICS});
  797. }
  798. if (!isMetricsData && dataset === Dataset.GENERIC_METRICS) {
  799. this.setState({dataset: Dataset.TRANSACTIONS});
  800. }
  801. };
  802. handleTimeSeriesDataFetched = (data: EventsStats | MultiSeriesEventsStats | null) => {
  803. const {isExtrapolatedData} = data ?? {};
  804. if (shouldShowOnDemandMetricAlertUI(this.props.organization)) {
  805. this.setState({isExtrapolatedChartData: Boolean(isExtrapolatedData)});
  806. }
  807. const {dataset, aggregate, query} = this.state;
  808. if (!isOnDemandMetricAlert(dataset, aggregate, query)) {
  809. this.handleMEPAlertDataset(data);
  810. }
  811. };
  812. // If the user is creating an on-demand metric alert, we want to override the dataset
  813. // to be generic metrics instead of transactions
  814. checkOnDemandMetricsDataset = (dataset: Dataset, query: string) => {
  815. if (!hasOnDemandMetricAlertFeature(this.props.organization)) {
  816. return dataset;
  817. }
  818. if (dataset !== Dataset.TRANSACTIONS || !isOnDemandQueryString(query)) {
  819. return dataset;
  820. }
  821. return Dataset.GENERIC_METRICS;
  822. };
  823. // We are not allowing the creation of new transaction alerts
  824. determinePerformanceDataset = () => {
  825. // TODO: once all alerts are migrated to MEP, we can set the default to GENERIC_METRICS and remove this as well as
  826. // logic in handleMEPDataset, handleTimeSeriesDataFetched and checkOnDemandMetricsDataset
  827. const {dataset} = this.state;
  828. const {organization} = this.props;
  829. const hasMetricsFeatureFlags =
  830. organization.features.includes('mep-rollout-flag') ||
  831. hasOnDemandMetricAlertFeature(organization);
  832. if (hasMetricsFeatureFlags && dataset === Dataset.TRANSACTIONS) {
  833. return Dataset.GENERIC_METRICS;
  834. }
  835. return dataset;
  836. };
  837. renderLoading() {
  838. return this.renderBody();
  839. }
  840. renderTriggerChart() {
  841. const {organization, ruleId, rule, location} = this.props;
  842. const {
  843. query,
  844. project,
  845. timeWindow,
  846. triggers,
  847. aggregate,
  848. environment,
  849. thresholdType,
  850. comparisonDelta,
  851. comparisonType,
  852. resolveThreshold,
  853. eventTypes,
  854. dataset,
  855. alertType,
  856. isQueryValid,
  857. } = this.state;
  858. const isOnDemand = isOnDemandMetricAlert(dataset, aggregate, query);
  859. const chartProps = {
  860. organization,
  861. projects: [project],
  862. triggers,
  863. location,
  864. query: this.chartQuery,
  865. aggregate,
  866. dataset,
  867. newAlertOrQuery: !ruleId || query !== rule.query,
  868. timeWindow,
  869. environment,
  870. resolveThreshold,
  871. thresholdType,
  872. comparisonDelta,
  873. comparisonType,
  874. isQueryValid,
  875. isOnDemandMetricAlert: isOnDemand,
  876. showTotalCount: alertType !== 'custom_metrics' && !isOnDemand,
  877. onDataLoaded: this.handleTimeSeriesDataFetched,
  878. };
  879. const wizardBuilderChart = (
  880. <TriggersChart
  881. {...chartProps}
  882. header={
  883. <ChartHeader>
  884. <AlertName>{AlertWizardAlertNames[alertType]}</AlertName>
  885. {!isCrashFreeAlert(dataset) && (
  886. <AlertInfo>
  887. <StyledCircleIndicator size={8} />
  888. <Aggregate>{formatMRIField(aggregate)}</Aggregate>
  889. {alertType !== 'custom_metrics'
  890. ? `event.type:${eventTypes?.join(',')}`
  891. : ''}
  892. </AlertInfo>
  893. )}
  894. </ChartHeader>
  895. }
  896. />
  897. );
  898. return wizardBuilderChart;
  899. }
  900. renderBody() {
  901. const {
  902. organization,
  903. ruleId,
  904. rule,
  905. onSubmitSuccess,
  906. router,
  907. disableProjectSelector,
  908. eventView,
  909. location,
  910. } = this.props;
  911. const {
  912. name,
  913. query,
  914. project,
  915. timeWindow,
  916. triggers,
  917. aggregate,
  918. thresholdType,
  919. thresholdPeriod,
  920. comparisonDelta,
  921. comparisonType,
  922. resolveThreshold,
  923. loading,
  924. eventTypes,
  925. dataset,
  926. alertType,
  927. isExtrapolatedChartData,
  928. triggersHaveChanged,
  929. activationCondition,
  930. monitorType,
  931. } = this.state;
  932. const wizardBuilderChart = this.renderTriggerChart();
  933. // TODO(issues): Remove this and all connected logic once the migration is complete
  934. const isMigration = location?.query?.migration === '1';
  935. const triggerForm = (disabled: boolean) => (
  936. <Triggers
  937. disabled={disabled}
  938. projects={[project]}
  939. errors={this.state.triggerErrors}
  940. triggers={triggers}
  941. aggregate={aggregate}
  942. isMigration={isMigration}
  943. resolveThreshold={resolveThreshold}
  944. thresholdPeriod={thresholdPeriod}
  945. thresholdType={thresholdType}
  946. comparisonType={comparisonType}
  947. currentProject={project.slug}
  948. organization={organization}
  949. availableActions={this.state.availableActions}
  950. onChange={this.handleChangeTriggers}
  951. onThresholdTypeChange={this.handleThresholdTypeChange}
  952. onThresholdPeriodChange={this.handleThresholdPeriodChange}
  953. onResolveThresholdChange={this.handleResolveThresholdChange}
  954. />
  955. );
  956. const ruleNameOwnerForm = (disabled: boolean) => (
  957. <RuleNameOwnerForm disabled={disabled} project={project} />
  958. );
  959. const thresholdTypeForm = (disabled: boolean) => (
  960. <ThresholdTypeForm
  961. comparisonType={comparisonType}
  962. dataset={dataset}
  963. disabled={disabled}
  964. onComparisonDeltaChange={value =>
  965. this.handleFieldChange('comparisonDelta', value)
  966. }
  967. onComparisonTypeChange={this.handleComparisonTypeChange}
  968. organization={organization}
  969. comparisonDelta={comparisonDelta}
  970. />
  971. );
  972. const hasAlertWrite = hasEveryAccess(['alerts:write'], {organization, project});
  973. const formDisabled = loading || !hasAlertWrite;
  974. const submitDisabled = formDisabled || !this.state.isQueryValid;
  975. const showErrorMigrationWarning =
  976. !!ruleId &&
  977. isMigration &&
  978. hasIgnoreArchivedFeatureFlag(organization) &&
  979. ruleNeedsErrorMigration(rule);
  980. // Rendering the main form body
  981. return (
  982. <Main fullWidth>
  983. <PermissionAlert access={['alerts:write']} project={project} />
  984. {eventView && (
  985. <IncompatibleAlertQuery orgSlug={organization.slug} eventView={eventView} />
  986. )}
  987. <Form
  988. model={this.form}
  989. apiMethod={ruleId ? 'PUT' : 'POST'}
  990. apiEndpoint={`/organizations/${organization.slug}/alert-rules/${
  991. ruleId ? `${ruleId}/` : ''
  992. }`}
  993. submitDisabled={submitDisabled}
  994. initialData={{
  995. name,
  996. dataset,
  997. eventTypes,
  998. aggregate,
  999. query,
  1000. timeWindow: rule.timeWindow,
  1001. environment: rule.environment || null,
  1002. owner: rule.owner,
  1003. projectId: project.id,
  1004. alertType,
  1005. }}
  1006. saveOnBlur={false}
  1007. onSubmit={this.handleSubmit}
  1008. onSubmitSuccess={onSubmitSuccess}
  1009. onCancel={this.handleCancel}
  1010. onFieldChange={this.handleFieldChange}
  1011. extraButton={
  1012. rule.id ? (
  1013. <Confirm
  1014. disabled={formDisabled}
  1015. message={t(
  1016. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  1017. rule.name
  1018. )}
  1019. header={<h5>{t('Delete Alert Rule?')}</h5>}
  1020. priority="danger"
  1021. confirmText={t('Delete Rule')}
  1022. onConfirm={this.handleDeleteRule}
  1023. >
  1024. <Button priority="danger">{t('Delete Rule')}</Button>
  1025. </Confirm>
  1026. ) : null
  1027. }
  1028. submitLabel={
  1029. isMigration && !triggersHaveChanged ? t('Looks good to me!') : t('Save Rule')
  1030. }
  1031. >
  1032. <List symbol="colored-numeric">
  1033. <RuleConditionsForm
  1034. project={project}
  1035. aggregate={aggregate}
  1036. organization={organization}
  1037. isTransactionMigration={isMigration && !showErrorMigrationWarning}
  1038. isErrorMigration={showErrorMigrationWarning}
  1039. router={router}
  1040. disabled={formDisabled}
  1041. thresholdChart={wizardBuilderChart}
  1042. onFilterSearch={this.handleFilterUpdate}
  1043. allowChangeEventTypes={
  1044. hasCustomMetrics(organization)
  1045. ? dataset === Dataset.ERRORS
  1046. : dataset === Dataset.ERRORS || alertType === 'custom_transactions'
  1047. }
  1048. alertType={alertType}
  1049. dataset={dataset}
  1050. timeWindow={timeWindow}
  1051. comparisonType={comparisonType}
  1052. comparisonDelta={comparisonDelta}
  1053. onComparisonDeltaChange={value =>
  1054. this.handleFieldChange('comparisonDelta', value)
  1055. }
  1056. onTimeWindowChange={value => this.handleFieldChange('timeWindow', value)}
  1057. disableProjectSelector={disableProjectSelector}
  1058. isExtrapolatedChartData={isExtrapolatedChartData}
  1059. monitorType={monitorType}
  1060. activationCondition={activationCondition}
  1061. onMonitorTypeSelect={this.handleMonitorTypeSelect}
  1062. isEditing={Boolean(ruleId)}
  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);