ruleForm.tsx 36 KB

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