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