ruleForm.tsx 36 KB

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