ruleForm.tsx 28 KB

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