ruleForm.tsx 32 KB

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