ruleForm.tsx 36 KB

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