ruleForm.tsx 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. import {Fragment, ReactNode} from 'react';
  2. import {PlainRoute, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {
  5. addErrorMessage,
  6. addSuccessMessage,
  7. clearIndicators,
  8. Indicator,
  9. } from 'sentry/actionCreators/indicator';
  10. import {fetchOrganizationTags} from 'sentry/actionCreators/tags';
  11. import {hasEveryAccess} from 'sentry/components/acl/access';
  12. import 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 Form, {FormProps} from 'sentry/components/forms/form';
  19. import FormModel from 'sentry/components/forms/model';
  20. import * as Layout from 'sentry/components/layouts/thirds';
  21. import ExternalLink from 'sentry/components/links/externalLink';
  22. import List from 'sentry/components/list';
  23. import ListItem from 'sentry/components/list/listItem';
  24. import {Tooltip} from 'sentry/components/tooltip';
  25. import {t, tct} from 'sentry/locale';
  26. import IndicatorStore from 'sentry/stores/indicatorStore';
  27. import {space} from 'sentry/styles/space';
  28. import {EventsStats, MultiSeriesEventsStats, Organization, Project} from 'sentry/types';
  29. import {defined} from 'sentry/utils';
  30. import {metric, trackAnalytics} from 'sentry/utils/analytics';
  31. import type EventView from 'sentry/utils/discover/eventView';
  32. import {
  33. getForceMetricsLayerQueryExtras,
  34. hasDDMFeature,
  35. } from 'sentry/utils/metrics/features';
  36. import {DEFAULT_METRIC_ALERT_FIELD, formatMRIField} from 'sentry/utils/metrics/mri';
  37. import {isOnDemandQueryString} from 'sentry/utils/onDemandMetrics';
  38. import {
  39. hasOnDemandMetricAlertFeature,
  40. shouldShowOnDemandMetricAlertUI,
  41. } from 'sentry/utils/onDemandMetrics/features';
  42. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  43. import withProjects from 'sentry/utils/withProjects';
  44. import {IncompatibleAlertQuery} from 'sentry/views/alerts/rules/metric/incompatibleAlertQuery';
  45. import RuleNameOwnerForm from 'sentry/views/alerts/rules/metric/ruleNameOwnerForm';
  46. import ThresholdTypeForm from 'sentry/views/alerts/rules/metric/thresholdTypeForm';
  47. import Triggers from 'sentry/views/alerts/rules/metric/triggers';
  48. import TriggersChart from 'sentry/views/alerts/rules/metric/triggers/chart';
  49. import {getEventTypeFilter} from 'sentry/views/alerts/rules/metric/utils/getEventTypeFilter';
  50. import hasThresholdValue from 'sentry/views/alerts/rules/metric/utils/hasThresholdValue';
  51. import {
  52. isOnDemandMetricAlert,
  53. isValidOnDemandMetricAlert,
  54. } from 'sentry/views/alerts/rules/metric/utils/onDemandMetricAlert';
  55. import {AlertRuleType} from 'sentry/views/alerts/types';
  56. import {
  57. hasIgnoreArchivedFeatureFlag,
  58. hasMigrationFeatureFlag,
  59. ruleNeedsErrorMigration,
  60. ruleNeedsMigration,
  61. } from 'sentry/views/alerts/utils/migrationUi';
  62. import {
  63. AlertWizardAlertNames,
  64. DatasetMEPAlertQueryTypes,
  65. MetricAlertType,
  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 {
  79. AlertRuleComparisonType,
  80. AlertRuleThresholdType,
  81. AlertRuleTriggerType,
  82. Dataset,
  83. EventTypes,
  84. MetricActionTemplate,
  85. MetricRule,
  86. Trigger,
  87. UnsavedMetricRule,
  88. } from './types';
  89. const POLLING_MAX_TIME_LIMIT = 3 * 60000;
  90. type RuleTaskResponse = {
  91. status: 'pending' | 'failed' | 'success';
  92. alertRule?: MetricRule;
  93. error?: string;
  94. };
  95. type Props = {
  96. organization: Organization;
  97. project: Project;
  98. projects: Project[];
  99. routes: PlainRoute[];
  100. rule: MetricRule;
  101. userTeamIds: string[];
  102. disableProjectSelector?: boolean;
  103. eventView?: EventView;
  104. isCustomMetric?: boolean;
  105. isDuplicateRule?: boolean;
  106. ruleId?: string;
  107. sessionId?: string;
  108. } & RouteComponentProps<{projectId?: string; ruleId?: string}, {}> & {
  109. onSubmitSuccess?: FormProps['onSubmitSuccess'];
  110. } & DeprecatedAsyncComponent['props'];
  111. type State = {
  112. aggregate: string;
  113. alertType: MetricAlertType;
  114. // `null` means loading
  115. availableActions: MetricActionTemplate[] | null;
  116. comparisonType: AlertRuleComparisonType;
  117. // Rule conditions form inputs
  118. // Needed for TriggersChart
  119. dataset: Dataset;
  120. environment: string | null;
  121. eventTypes: EventTypes[];
  122. isQueryValid: boolean;
  123. project: Project;
  124. query: string;
  125. resolveThreshold: UnsavedMetricRule['resolveThreshold'];
  126. thresholdPeriod: UnsavedMetricRule['thresholdPeriod'];
  127. thresholdType: UnsavedMetricRule['thresholdType'];
  128. timeWindow: number;
  129. triggerErrors: Map<number, {[fieldName: string]: string}>;
  130. triggers: Trigger[];
  131. comparisonDelta?: number;
  132. isExtrapolatedChartData?: boolean;
  133. // TODO(telemetry-experiment): remove this state once the migration is complete
  134. triggersHaveChanged?: 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. return isValidOnDemandMetricAlert(
  497. this.state.dataset,
  498. this.state.aggregate,
  499. this.state.query
  500. );
  501. }
  502. handleSubmit = async (
  503. _data: Partial<MetricRule>,
  504. _onSubmitSuccess,
  505. _onSubmitError,
  506. _e,
  507. model: FormModel
  508. ) => {
  509. if (!this.validateMri()) {
  510. addErrorMessage(t('You need to select a metric before you can save the alert'));
  511. return;
  512. }
  513. // This validates all fields *except* for Triggers
  514. const validRule = model.validateForm();
  515. // Validate Triggers
  516. const triggerErrors = this.validateTriggers();
  517. const validTriggers = Array.from(triggerErrors).length === 0;
  518. const validOnDemandAlert = this.validateOnDemandMetricAlert();
  519. if (!validTriggers) {
  520. this.setState(state => ({
  521. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  522. }));
  523. }
  524. if (!validRule || !validTriggers) {
  525. const missingFields = [
  526. !validRule && t('name'),
  527. !validRule && !validTriggers && t('and'),
  528. !validTriggers && t('critical threshold'),
  529. ].filter(x => x);
  530. addErrorMessage(t('Alert not valid: missing %s', missingFields.join(' ')));
  531. return;
  532. }
  533. if (!validOnDemandAlert) {
  534. addErrorMessage(
  535. t('%s is not supported for on-demand metric alerts', this.state.aggregate)
  536. );
  537. return;
  538. }
  539. const {
  540. organization,
  541. rule,
  542. onSubmitSuccess,
  543. location,
  544. sessionId,
  545. params: {ruleId},
  546. } = this.props;
  547. const {
  548. project,
  549. aggregate,
  550. resolveThreshold,
  551. triggers,
  552. thresholdType,
  553. thresholdPeriod,
  554. comparisonDelta,
  555. uuid,
  556. timeWindow,
  557. eventTypes,
  558. } = this.state;
  559. // Remove empty warning trigger
  560. const sanitizedTriggers = triggers.filter(
  561. trigger =>
  562. trigger.label !== AlertRuleTriggerType.WARNING || !isEmpty(trigger.alertThreshold)
  563. );
  564. // form model has all form state data, however we use local state to keep
  565. // track of the list of triggers (and actions within triggers)
  566. const loadingIndicator = IndicatorStore.addMessage(
  567. t('Saving your alert rule, hold on...'),
  568. 'loading'
  569. );
  570. try {
  571. const transaction = metric.startTransaction({name: 'saveAlertRule'});
  572. transaction.setTag('type', AlertRuleType.METRIC);
  573. transaction.setTag('operation', !rule.id ? 'create' : 'edit');
  574. for (const trigger of sanitizedTriggers) {
  575. for (const action of trigger.actions) {
  576. if (action.type === 'slack' || action.type === 'discord') {
  577. transaction.setTag(action.type, true);
  578. }
  579. }
  580. }
  581. transaction.setData('actions', sanitizedTriggers);
  582. const dataset = this.determinePerformanceDataset();
  583. this.setState({loading: true});
  584. const [data, , resp] = await addOrUpdateRule(
  585. this.api,
  586. organization.slug,
  587. {
  588. ...rule,
  589. ...model.getTransformedData(),
  590. projects: [project.slug],
  591. triggers: sanitizedTriggers,
  592. resolveThreshold: isEmpty(resolveThreshold) ? null : resolveThreshold,
  593. thresholdType,
  594. thresholdPeriod,
  595. comparisonDelta: comparisonDelta ?? null,
  596. timeWindow,
  597. aggregate,
  598. // Remove eventTypes as it is no longer required for crash free
  599. eventTypes: isCrashFreeAlert(rule.dataset) ? undefined : eventTypes,
  600. dataset,
  601. queryType: DatasetMEPAlertQueryTypes[dataset],
  602. },
  603. {
  604. duplicateRule: this.isDuplicateRule ? 'true' : 'false',
  605. wizardV3: 'true',
  606. referrer: location?.query?.referrer,
  607. sessionId,
  608. ...getForceMetricsLayerQueryExtras(organization, dataset),
  609. }
  610. );
  611. // if we get a 202 back it means that we have an async task
  612. // running to lookup and verify the channel id for Slack.
  613. if (resp?.status === 202) {
  614. // if we have a uuid in state, no need to start a new polling cycle
  615. if (!uuid) {
  616. this.setState({loading: true, uuid: data.uuid});
  617. this.fetchStatus(model);
  618. }
  619. } else {
  620. IndicatorStore.remove(loadingIndicator);
  621. this.setState({loading: false});
  622. addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
  623. if (onSubmitSuccess) {
  624. onSubmitSuccess(data, model);
  625. }
  626. }
  627. } catch (err) {
  628. IndicatorStore.remove(loadingIndicator);
  629. this.setState({loading: false});
  630. const errors = err?.responseJSON
  631. ? Array.isArray(err?.responseJSON)
  632. ? err?.responseJSON
  633. : Object.values(err?.responseJSON)
  634. : [];
  635. const apiErrors = errors.length > 0 ? `: ${errors.join(', ')}` : '';
  636. this.handleRuleSaveFailure(t('Unable to save alert%s', apiErrors));
  637. }
  638. };
  639. /**
  640. * Callback for when triggers change
  641. *
  642. * Re-validate triggers on every change and reset indicators when no errors
  643. */
  644. handleChangeTriggers = (triggers: Trigger[], triggerIndex?: number) => {
  645. this.setState(state => {
  646. let triggerErrors = state.triggerErrors;
  647. const newTriggerErrors = this.validateTriggers(
  648. triggers,
  649. state.thresholdType,
  650. state.resolveThreshold,
  651. triggerIndex
  652. );
  653. triggerErrors = newTriggerErrors;
  654. if (Array.from(newTriggerErrors).length === 0) {
  655. clearIndicators();
  656. }
  657. return {triggers, triggerErrors, triggersHaveChanged: true};
  658. });
  659. };
  660. handleThresholdTypeChange = (thresholdType: AlertRuleThresholdType) => {
  661. const {triggers} = this.state;
  662. const triggerErrors = this.validateTriggers(triggers, thresholdType);
  663. this.setState(state => ({
  664. thresholdType,
  665. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  666. }));
  667. };
  668. handleThresholdPeriodChange = (value: number) => {
  669. this.setState({thresholdPeriod: value});
  670. };
  671. handleResolveThresholdChange = (
  672. resolveThreshold: UnsavedMetricRule['resolveThreshold']
  673. ) => {
  674. this.setState(state => {
  675. const triggerErrors = this.validateTriggers(
  676. state.triggers,
  677. state.thresholdType,
  678. resolveThreshold
  679. );
  680. if (Array.from(triggerErrors).length === 0) {
  681. clearIndicators();
  682. }
  683. return {resolveThreshold, triggerErrors};
  684. });
  685. };
  686. handleComparisonTypeChange = (value: AlertRuleComparisonType) => {
  687. const comparisonDelta =
  688. value === AlertRuleComparisonType.COUNT
  689. ? undefined
  690. : this.state.comparisonDelta ?? DEFAULT_CHANGE_COMP_DELTA;
  691. const timeWindow = this.state.comparisonDelta
  692. ? DEFAULT_COUNT_TIME_WINDOW
  693. : DEFAULT_CHANGE_TIME_WINDOW;
  694. this.setState({comparisonType: value, comparisonDelta, timeWindow});
  695. };
  696. handleDeleteRule = async () => {
  697. const {organization, params} = this.props;
  698. const {ruleId} = params;
  699. try {
  700. await this.api.requestPromise(
  701. `/organizations/${organization.slug}/alert-rules/${ruleId}/`,
  702. {
  703. method: 'DELETE',
  704. }
  705. );
  706. this.goBack();
  707. } catch (_err) {
  708. addErrorMessage(t('Error deleting rule'));
  709. }
  710. };
  711. handleRuleSaveFailure = (msg: ReactNode) => {
  712. addErrorMessage(msg);
  713. metric.endTransaction({name: 'saveAlertRule'});
  714. };
  715. handleCancel = () => {
  716. this.goBack();
  717. };
  718. handleMEPAlertDataset = (data: EventsStats | MultiSeriesEventsStats | null) => {
  719. const {isMetricsData} = data ?? {};
  720. const {organization} = this.props;
  721. if (
  722. isMetricsData === undefined ||
  723. !organization.features.includes('mep-rollout-flag')
  724. ) {
  725. return;
  726. }
  727. const {dataset} = this.state;
  728. if (isMetricsData && dataset === Dataset.TRANSACTIONS) {
  729. this.setState({dataset: Dataset.GENERIC_METRICS});
  730. }
  731. if (!isMetricsData && dataset === Dataset.GENERIC_METRICS) {
  732. this.setState({dataset: Dataset.TRANSACTIONS});
  733. }
  734. };
  735. handleTimeSeriesDataFetched = (data: EventsStats | MultiSeriesEventsStats | null) => {
  736. const {isExtrapolatedData} = data ?? {};
  737. if (shouldShowOnDemandMetricAlertUI(this.props.organization)) {
  738. this.setState({isExtrapolatedChartData: Boolean(isExtrapolatedData)});
  739. }
  740. const {dataset, aggregate, query} = this.state;
  741. if (!isOnDemandMetricAlert(dataset, aggregate, query)) {
  742. this.handleMEPAlertDataset(data);
  743. }
  744. };
  745. // If the user is creating an on-demand metric alert, we want to override the dataset
  746. // to be generic metrics instead of transactions
  747. checkOnDemandMetricsDataset = (dataset: Dataset, query: string) => {
  748. if (!hasOnDemandMetricAlertFeature(this.props.organization)) {
  749. return dataset;
  750. }
  751. if (dataset !== Dataset.TRANSACTIONS || !isOnDemandQueryString(query)) {
  752. return dataset;
  753. }
  754. return Dataset.GENERIC_METRICS;
  755. };
  756. // We are not allowing the creation of new transaction alerts
  757. determinePerformanceDataset = () => {
  758. // TODO: once all alerts are migrated to MEP, we can set the default to GENERIC_METRICS and remove this as well as
  759. // logic in handleMEPDataset, handleTimeSeriesDataFetched and checkOnDemandMetricsDataset
  760. const {dataset} = this.state;
  761. const {organization} = this.props;
  762. const hasMetricsFeatureFlags =
  763. organization.features.includes('mep-rollout-flag') ||
  764. hasOnDemandMetricAlertFeature(organization);
  765. if (hasMetricsFeatureFlags && dataset === Dataset.TRANSACTIONS) {
  766. return Dataset.GENERIC_METRICS;
  767. }
  768. return dataset;
  769. };
  770. renderLoading() {
  771. return this.renderBody();
  772. }
  773. renderTriggerChart() {
  774. const {organization, ruleId, rule, location} = this.props;
  775. const {
  776. query,
  777. project,
  778. timeWindow,
  779. triggers,
  780. aggregate,
  781. environment,
  782. thresholdType,
  783. comparisonDelta,
  784. comparisonType,
  785. resolveThreshold,
  786. eventTypes,
  787. dataset,
  788. alertType,
  789. isQueryValid,
  790. } = this.state;
  791. const isMigration = location?.query?.migration === '1';
  792. // TODO(telemetry-experience): Remove this and all connected logic once the migration is complete
  793. const isTransactionMigration = isMigration && ruleNeedsMigration(rule);
  794. const isOnDemand = isOnDemandMetricAlert(dataset, aggregate, query);
  795. const chartProps = {
  796. organization,
  797. projects: [project],
  798. triggers,
  799. location,
  800. query: this.chartQuery,
  801. aggregate,
  802. // If the alert is being migrated, we want to use the generic metrics dataset to allow users to edit their thresholds
  803. dataset: isTransactionMigration ? Dataset.GENERIC_METRICS : dataset,
  804. newAlertOrQuery: !ruleId || query !== rule.query,
  805. timeWindow,
  806. environment,
  807. resolveThreshold,
  808. thresholdType,
  809. comparisonDelta,
  810. comparisonType,
  811. isQueryValid,
  812. isOnDemandMetricAlert: isOnDemand,
  813. showTotalCount: alertType !== 'custom_metrics' && !isOnDemand,
  814. onDataLoaded: this.handleTimeSeriesDataFetched,
  815. };
  816. const wizardBuilderChart = (
  817. <TriggersChart
  818. {...chartProps}
  819. header={
  820. <ChartHeader>
  821. <AlertName>{AlertWizardAlertNames[alertType]}</AlertName>
  822. {!isCrashFreeAlert(dataset) && (
  823. <AlertInfo>
  824. <StyledCircleIndicator size={8} />
  825. <Aggregate>{formatMRIField(aggregate)}</Aggregate>
  826. {alertType !== 'custom_metrics'
  827. ? `event.type:${eventTypes?.join(',')}`
  828. : ''}
  829. </AlertInfo>
  830. )}
  831. </ChartHeader>
  832. }
  833. />
  834. );
  835. return wizardBuilderChart;
  836. }
  837. renderBody() {
  838. const {
  839. organization,
  840. ruleId,
  841. rule,
  842. onSubmitSuccess,
  843. router,
  844. disableProjectSelector,
  845. eventView,
  846. location,
  847. } = this.props;
  848. const {
  849. name,
  850. query,
  851. project,
  852. timeWindow,
  853. triggers,
  854. aggregate,
  855. thresholdType,
  856. thresholdPeriod,
  857. comparisonDelta,
  858. comparisonType,
  859. resolveThreshold,
  860. loading,
  861. eventTypes,
  862. dataset,
  863. alertType,
  864. isExtrapolatedChartData,
  865. triggersHaveChanged,
  866. } = this.state;
  867. const wizardBuilderChart = this.renderTriggerChart();
  868. // TODO(telemetry-experience): Remove this and all connected logic once the migration is complete
  869. const isMigration = location?.query?.migration === '1';
  870. const triggerForm = (disabled: boolean) => (
  871. <Triggers
  872. disabled={disabled}
  873. projects={[project]}
  874. errors={this.state.triggerErrors}
  875. triggers={triggers}
  876. aggregate={aggregate}
  877. isMigration={isMigration}
  878. resolveThreshold={resolveThreshold}
  879. thresholdPeriod={thresholdPeriod}
  880. thresholdType={thresholdType}
  881. comparisonType={comparisonType}
  882. currentProject={project.slug}
  883. organization={organization}
  884. availableActions={this.state.availableActions}
  885. onChange={this.handleChangeTriggers}
  886. onThresholdTypeChange={this.handleThresholdTypeChange}
  887. onThresholdPeriodChange={this.handleThresholdPeriodChange}
  888. onResolveThresholdChange={this.handleResolveThresholdChange}
  889. />
  890. );
  891. const ruleNameOwnerForm = (disabled: boolean) => (
  892. <RuleNameOwnerForm disabled={disabled} project={project} />
  893. );
  894. const thresholdTypeForm = (disabled: boolean) => (
  895. <ThresholdTypeForm
  896. comparisonType={comparisonType}
  897. dataset={dataset}
  898. disabled={disabled}
  899. onComparisonDeltaChange={value =>
  900. this.handleFieldChange('comparisonDelta', value)
  901. }
  902. onComparisonTypeChange={this.handleComparisonTypeChange}
  903. organization={organization}
  904. comparisonDelta={comparisonDelta}
  905. />
  906. );
  907. const hasAlertWrite = hasEveryAccess(['alerts:write'], {organization, project});
  908. const formDisabled = loading || !hasAlertWrite;
  909. const submitDisabled = formDisabled || !this.state.isQueryValid;
  910. const showTransactionMigrationWarning =
  911. !!ruleId && hasMigrationFeatureFlag(organization) && ruleNeedsMigration(rule);
  912. const showErrorMigrationWarning =
  913. !!ruleId &&
  914. isMigration &&
  915. hasIgnoreArchivedFeatureFlag(organization) &&
  916. ruleNeedsErrorMigration(rule);
  917. return (
  918. <Main fullWidth>
  919. <PermissionAlert access={['alerts:write']} project={project} />
  920. {eventView && (
  921. <IncompatibleAlertQuery orgSlug={organization.slug} eventView={eventView} />
  922. )}
  923. <Form
  924. model={this.form}
  925. apiMethod={ruleId ? 'PUT' : 'POST'}
  926. apiEndpoint={`/organizations/${organization.slug}/alert-rules/${
  927. ruleId ? `${ruleId}/` : ''
  928. }`}
  929. submitDisabled={submitDisabled}
  930. initialData={{
  931. name,
  932. dataset,
  933. eventTypes,
  934. aggregate,
  935. query,
  936. timeWindow: rule.timeWindow,
  937. environment: rule.environment || null,
  938. owner: rule.owner,
  939. projectId: project.id,
  940. alertType,
  941. }}
  942. saveOnBlur={false}
  943. onSubmit={this.handleSubmit}
  944. onSubmitSuccess={onSubmitSuccess}
  945. onCancel={this.handleCancel}
  946. onFieldChange={this.handleFieldChange}
  947. extraButton={
  948. rule.id ? (
  949. <Confirm
  950. disabled={formDisabled}
  951. message={t(
  952. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  953. rule.name
  954. )}
  955. header={<h5>{t('Delete Alert Rule?')}</h5>}
  956. priority="danger"
  957. confirmText={t('Delete Rule')}
  958. onConfirm={this.handleDeleteRule}
  959. >
  960. <Button priority="danger">{t('Delete Rule')}</Button>
  961. </Confirm>
  962. ) : null
  963. }
  964. submitLabel={
  965. isMigration && !triggersHaveChanged ? t('Looks good to me!') : t('Save Rule')
  966. }
  967. >
  968. <List symbol="colored-numeric">
  969. <RuleConditionsForm
  970. project={project}
  971. aggregate={aggregate}
  972. organization={organization}
  973. isTransactionMigration={isMigration && !showErrorMigrationWarning}
  974. isErrorMigration={showErrorMigrationWarning}
  975. router={router}
  976. disabled={formDisabled}
  977. thresholdChart={wizardBuilderChart}
  978. onFilterSearch={this.handleFilterUpdate}
  979. allowChangeEventTypes={
  980. hasDDMFeature(organization)
  981. ? dataset === Dataset.ERRORS
  982. : dataset === Dataset.ERRORS || alertType === 'custom_transactions'
  983. }
  984. alertType={alertType}
  985. dataset={dataset}
  986. timeWindow={timeWindow}
  987. comparisonType={comparisonType}
  988. comparisonDelta={comparisonDelta}
  989. onComparisonDeltaChange={value =>
  990. this.handleFieldChange('comparisonDelta', value)
  991. }
  992. onTimeWindowChange={value => this.handleFieldChange('timeWindow', value)}
  993. disableProjectSelector={disableProjectSelector}
  994. isExtrapolatedChartData={isExtrapolatedChartData}
  995. />
  996. <AlertListItem>{t('Set thresholds')}</AlertListItem>
  997. {thresholdTypeForm(formDisabled)}
  998. {showTransactionMigrationWarning && (
  999. <Alert type="warning" showIcon>
  1000. {tct(
  1001. 'Check the chart above and make sure the current thresholds are still valid, given that this alert is now based on [tooltip:total events].',
  1002. {
  1003. tooltip: (
  1004. <Tooltip
  1005. showUnderline
  1006. isHoverable
  1007. title={
  1008. <Fragment>
  1009. {t(
  1010. 'Performance alerts are based on all the events you send to Sentry, not just the ones that are stored'
  1011. )}
  1012. <br />
  1013. <ExternalLink href="https://docs.sentry.io/product/performance/retention-priorities/">
  1014. {t('Learn more')}
  1015. </ExternalLink>
  1016. </Fragment>
  1017. }
  1018. />
  1019. ),
  1020. }
  1021. )}
  1022. </Alert>
  1023. )}
  1024. {showErrorMigrationWarning && (
  1025. <Alert type="warning" showIcon>
  1026. {tct(
  1027. "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.",
  1028. {
  1029. code: <code />,
  1030. }
  1031. )}
  1032. </Alert>
  1033. )}
  1034. {triggerForm(formDisabled)}
  1035. {isMigration ? <Fragment /> : ruleNameOwnerForm(formDisabled)}
  1036. </List>
  1037. </Form>
  1038. </Main>
  1039. );
  1040. }
  1041. }
  1042. const Main = styled(Layout.Main)`
  1043. max-width: 1000px;
  1044. `;
  1045. const StyledListItem = styled(ListItem)`
  1046. margin: ${space(2)} 0 ${space(1)} 0;
  1047. font-size: ${p => p.theme.fontSizeExtraLarge};
  1048. `;
  1049. const AlertListItem = styled(StyledListItem)`
  1050. margin-top: 0;
  1051. `;
  1052. const ChartHeader = styled('div')`
  1053. padding: ${space(2)} ${space(3)} 0 ${space(3)};
  1054. margin-bottom: -${space(1.5)};
  1055. `;
  1056. const AlertName = styled(HeaderTitleLegend)`
  1057. position: relative;
  1058. `;
  1059. const AlertInfo = styled('div')`
  1060. font-size: ${p => p.theme.fontSizeSmall};
  1061. font-family: ${p => p.theme.text.family};
  1062. font-weight: normal;
  1063. color: ${p => p.theme.textColor};
  1064. `;
  1065. const StyledCircleIndicator = styled(CircleIndicator)`
  1066. background: ${p => p.theme.formText};
  1067. height: ${space(1)};
  1068. margin-right: ${space(0.5)};
  1069. `;
  1070. const Aggregate = styled('span')`
  1071. margin-right: ${space(1)};
  1072. `;
  1073. export default withProjects(RuleFormContainer);