ruleForm.tsx 32 KB

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