ruleForm.tsx 31 KB

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