ruleForm.tsx 30 KB

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