ruleForm.tsx 32 KB

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