ruleForm.tsx 39 KB

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