ruleForm.tsx 33 KB

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