ruleForm.tsx 31 KB

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