ruleForm.tsx 32 KB

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