ruleForm.tsx 36 KB

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