ruleForm.tsx 31 KB

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