ruleForm.tsx 32 KB

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