ruleForm.tsx 30 KB

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