ruleForm.tsx 36 KB

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