ruleForm.tsx 39 KB

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