ruleForm.tsx 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. import type {ReactNode} from 'react';
  2. import type {PlainRoute, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import type {Indicator} from 'sentry/actionCreators/indicator';
  6. import {
  7. addErrorMessage,
  8. addSuccessMessage,
  9. clearIndicators,
  10. } from 'sentry/actionCreators/indicator';
  11. import {fetchOrganizationTags} from 'sentry/actionCreators/tags';
  12. import {hasEveryAccess} from 'sentry/components/acl/access';
  13. import Alert from 'sentry/components/alert';
  14. import {Button} from 'sentry/components/button';
  15. import {HeaderTitleLegend} from 'sentry/components/charts/styles';
  16. import CircleIndicator from 'sentry/components/circleIndicator';
  17. import Confirm from 'sentry/components/confirm';
  18. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  19. import type {FormProps} from 'sentry/components/forms/form';
  20. import Form from 'sentry/components/forms/form';
  21. import FormModel from 'sentry/components/forms/model';
  22. import * as Layout from 'sentry/components/layouts/thirds';
  23. import List from 'sentry/components/list';
  24. import ListItem from 'sentry/components/list/listItem';
  25. import {t, tct} from 'sentry/locale';
  26. import IndicatorStore from 'sentry/stores/indicatorStore';
  27. import {space} from 'sentry/styles/space';
  28. import {ActivationConditionType, MonitorType} from 'sentry/types/alerts';
  29. import type {MetricsExtractionRule} from 'sentry/types/metrics';
  30. import type {
  31. EventsStats,
  32. MultiSeriesEventsStats,
  33. Organization,
  34. } from 'sentry/types/organization';
  35. import type {Project} from 'sentry/types/project';
  36. import {defined} from 'sentry/utils';
  37. import {metric, trackAnalytics} from 'sentry/utils/analytics';
  38. import type EventView from 'sentry/utils/discover/eventView';
  39. import {AggregationKey} from 'sentry/utils/fields';
  40. import {findExtractionRuleCondition} from 'sentry/utils/metrics/extractionRules';
  41. import {
  42. getForceMetricsLayerQueryExtras,
  43. hasCustomMetrics,
  44. hasCustomMetricsExtractionRules,
  45. } from 'sentry/utils/metrics/features';
  46. import {
  47. DEFAULT_METRIC_ALERT_FIELD,
  48. DEFAULT_SPAN_METRIC_ALERT_FIELD,
  49. formatMRIField,
  50. parseField,
  51. } from 'sentry/utils/metrics/mri';
  52. import {isOnDemandQueryString} from 'sentry/utils/onDemandMetrics';
  53. import {
  54. hasOnDemandMetricAlertFeature,
  55. shouldShowOnDemandMetricAlertUI,
  56. } from 'sentry/utils/onDemandMetrics/features';
  57. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  58. import withProjects from 'sentry/utils/withProjects';
  59. import {IncompatibleAlertQuery} from 'sentry/views/alerts/rules/metric/incompatibleAlertQuery';
  60. import RuleNameOwnerForm from 'sentry/views/alerts/rules/metric/ruleNameOwnerForm';
  61. import ThresholdTypeForm from 'sentry/views/alerts/rules/metric/thresholdTypeForm';
  62. import Triggers from 'sentry/views/alerts/rules/metric/triggers';
  63. import TriggersChart from 'sentry/views/alerts/rules/metric/triggers/chart';
  64. import {getEventTypeFilter} from 'sentry/views/alerts/rules/metric/utils/getEventTypeFilter';
  65. import {getFormattedSpanMetricField} from 'sentry/views/alerts/rules/metric/utils/getFormattedSpanMetric';
  66. import hasThresholdValue from 'sentry/views/alerts/rules/metric/utils/hasThresholdValue';
  67. import {isOnDemandMetricAlert} from 'sentry/views/alerts/rules/metric/utils/onDemandMetricAlert';
  68. import {AlertRuleType} from 'sentry/views/alerts/types';
  69. import {ruleNeedsErrorMigration} from 'sentry/views/alerts/utils/migrationUi';
  70. import type {MetricAlertType} from 'sentry/views/alerts/wizard/options';
  71. import {
  72. AlertWizardAlertNames,
  73. DatasetMEPAlertQueryTypes,
  74. } from 'sentry/views/alerts/wizard/options';
  75. import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
  76. import PermissionAlert from 'sentry/views/settings/project/permissionAlert';
  77. import {isCrashFreeAlert} from './utils/isCrashFreeAlert';
  78. import {addOrUpdateRule} from './actions';
  79. import {
  80. createDefaultTrigger,
  81. DEFAULT_CHANGE_COMP_DELTA,
  82. DEFAULT_CHANGE_TIME_WINDOW,
  83. DEFAULT_COUNT_TIME_WINDOW,
  84. } from './constants';
  85. import RuleConditionsForm from './ruleConditionsForm';
  86. import {
  87. AlertRuleSeasonality,
  88. AlertRuleSensitivity,
  89. type EventTypes,
  90. type MetricActionTemplate,
  91. type MetricRule,
  92. type Trigger,
  93. type UnsavedMetricRule,
  94. } from './types';
  95. import {
  96. AlertRuleComparisonType,
  97. AlertRuleThresholdType,
  98. AlertRuleTriggerType,
  99. Dataset,
  100. TimeWindow,
  101. } from './types';
  102. const POLLING_MAX_TIME_LIMIT = 3 * 60000;
  103. type RuleTaskResponse = {
  104. status: 'pending' | 'failed' | 'success';
  105. alertRule?: MetricRule;
  106. error?: string;
  107. };
  108. type Props = {
  109. organization: Organization;
  110. project: Project;
  111. projects: Project[];
  112. routes: PlainRoute[];
  113. rule: MetricRule;
  114. userTeamIds: string[];
  115. disableProjectSelector?: boolean;
  116. eventView?: EventView;
  117. isCustomMetric?: boolean;
  118. isDuplicateRule?: boolean;
  119. ruleId?: string;
  120. sessionId?: string;
  121. } & RouteComponentProps<{projectId?: string; ruleId?: string}, {}> & {
  122. onSubmitSuccess?: FormProps['onSubmitSuccess'];
  123. } & DeprecatedAsyncComponent['props'];
  124. type State = {
  125. aggregate: string;
  126. alertType: MetricAlertType;
  127. // `null` means loading
  128. availableActions: MetricActionTemplate[] | null;
  129. comparisonType: AlertRuleComparisonType;
  130. // Rule conditions form inputs
  131. // Needed for TriggersChart
  132. dataset: Dataset;
  133. environment: string | null;
  134. eventTypes: EventTypes[];
  135. isQueryValid: boolean;
  136. // `null` means loading
  137. metricExtractionRules: MetricsExtractionRule[] | null;
  138. project: Project;
  139. query: string;
  140. resolveThreshold: UnsavedMetricRule['resolveThreshold'];
  141. sensitivity: UnsavedMetricRule['sensitivity'];
  142. thresholdPeriod: UnsavedMetricRule['thresholdPeriod'];
  143. thresholdType: UnsavedMetricRule['thresholdType'];
  144. timeWindow: number;
  145. triggerErrors: Map<number, {[fieldName: string]: string}>;
  146. triggers: Trigger[];
  147. activationCondition?: ActivationConditionType;
  148. comparisonDelta?: number;
  149. isExtrapolatedChartData?: boolean;
  150. monitorType?: MonitorType;
  151. seasonality?: AlertRuleSeasonality;
  152. } & DeprecatedAsyncComponent['state'];
  153. const isEmpty = (str: unknown): boolean => str === '' || !defined(str);
  154. class RuleFormContainer extends DeprecatedAsyncComponent<Props, State> {
  155. form = new FormModel();
  156. pollingTimeout: number | undefined = undefined;
  157. uuid: string | null = null;
  158. get isDuplicateRule(): boolean {
  159. return Boolean(this.props.isDuplicateRule);
  160. }
  161. get chartQuery(): string {
  162. const {alertType, query, eventTypes, dataset} = this.state;
  163. const eventTypeFilter = getEventTypeFilter(this.state.dataset, eventTypes);
  164. const queryWithTypeFilter = (
  165. !['custom_metrics', 'span_metrics'].includes(alertType)
  166. ? query
  167. ? `(${query}) AND (${eventTypeFilter})`
  168. : eventTypeFilter
  169. : query
  170. ).trim();
  171. return isCrashFreeAlert(dataset) ? query : queryWithTypeFilter;
  172. }
  173. componentDidMount() {
  174. super.componentDidMount();
  175. const {organization} = this.props;
  176. const {project} = this.state;
  177. // SearchBar gets its tags from Reflux.
  178. fetchOrganizationTags(this.api, organization.slug, [project.id]);
  179. }
  180. componentWillUnmount() {
  181. window.clearTimeout(this.pollingTimeout);
  182. }
  183. getDefaultState(): State {
  184. const {rule, location, organization} = this.props;
  185. const triggersClone = [...rule.triggers];
  186. const {
  187. aggregate: _aggregate,
  188. eventTypes: _eventTypes,
  189. dataset: _dataset,
  190. name,
  191. } = location?.query ?? {};
  192. const eventTypes = typeof _eventTypes === 'string' ? [_eventTypes] : _eventTypes;
  193. // Warning trigger is removed if it is blank when saving
  194. if (triggersClone.length !== 2) {
  195. triggersClone.push(createDefaultTrigger(AlertRuleTriggerType.WARNING));
  196. }
  197. const aggregate = _aggregate ?? rule.aggregate;
  198. const dataset = _dataset ?? rule.dataset;
  199. const isErrorMigration =
  200. this.props.location?.query?.migration === '1' && ruleNeedsErrorMigration(rule);
  201. // TODO(issues): Does this need to be smarter about where its inserting the new filter?
  202. const query = isErrorMigration
  203. ? `is:unresolved ${rule.query ?? ''}`
  204. : rule.query ?? '';
  205. const hasActivatedAlerts = organization.features.includes('activated-alert-rules');
  206. return {
  207. ...super.getDefaultState(),
  208. name: name ?? rule.name ?? '',
  209. aggregate,
  210. dataset,
  211. eventTypes: eventTypes ?? rule.eventTypes ?? [],
  212. query,
  213. isQueryValid: true, // Assume valid until input is changed
  214. timeWindow: rule.timeWindow,
  215. environment: rule.environment || null,
  216. triggerErrors: new Map(),
  217. availableActions: null,
  218. metricExtractionRules: null,
  219. triggers: triggersClone,
  220. resolveThreshold: rule.resolveThreshold,
  221. sensitivity: null,
  222. thresholdType: rule.thresholdType,
  223. thresholdPeriod: rule.thresholdPeriod ?? 1,
  224. comparisonDelta: rule.comparisonDelta ?? undefined,
  225. comparisonType: rule.comparisonDelta
  226. ? AlertRuleComparisonType.CHANGE
  227. : AlertRuleComparisonType.COUNT,
  228. project: this.props.project,
  229. owner: rule.owner,
  230. alertType: getAlertTypeFromAggregateDataset({aggregate, dataset}),
  231. monitorType: hasActivatedAlerts
  232. ? rule.monitorType || MonitorType.CONTINUOUS
  233. : undefined,
  234. activationCondition:
  235. rule.activationCondition || ActivationConditionType.RELEASE_CREATION,
  236. };
  237. }
  238. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  239. const {organization} = this.props;
  240. const project = this.state?.project ?? this.props.project;
  241. // TODO(incidents): This is temporary until new API endpoints
  242. // We should be able to just fetch the rule if rule.id exists
  243. return [
  244. [
  245. 'availableActions',
  246. `/organizations/${organization.slug}/alert-rules/available-actions/`,
  247. ],
  248. ...(hasCustomMetricsExtractionRules(organization)
  249. ? [
  250. [
  251. 'metricExtractionRules',
  252. `/projects/${organization.slug}/${project.slug}/metrics/extraction-rules/`,
  253. ] as [string, string],
  254. ]
  255. : []),
  256. ];
  257. }
  258. goBack() {
  259. const {router} = this.props;
  260. const {organization} = this.props;
  261. router.push(normalizeUrl(`/organizations/${organization.slug}/alerts/rules/`));
  262. }
  263. resetPollingState = (loadingSlackIndicator: Indicator) => {
  264. IndicatorStore.remove(loadingSlackIndicator);
  265. this.uuid = null;
  266. this.setState({loading: false});
  267. };
  268. fetchStatus(model: FormModel) {
  269. const loadingSlackIndicator = IndicatorStore.addMessage(
  270. t('Looking for your slack channel (this can take a while)'),
  271. 'loading'
  272. );
  273. // pollHandler calls itself until it gets either a success
  274. // or failed status but we don't want to poll forever so we pass
  275. // in a hard stop time of 3 minutes before we bail.
  276. const quitTime = Date.now() + POLLING_MAX_TIME_LIMIT;
  277. window.clearTimeout(this.pollingTimeout);
  278. this.pollingTimeout = window.setTimeout(() => {
  279. this.pollHandler(model, quitTime, loadingSlackIndicator);
  280. }, 1000);
  281. }
  282. pollHandler = async (
  283. model: FormModel,
  284. quitTime: number,
  285. loadingSlackIndicator: Indicator
  286. ) => {
  287. if (Date.now() > quitTime) {
  288. addErrorMessage(t('Looking for that channel took too long :('));
  289. this.resetPollingState(loadingSlackIndicator);
  290. return;
  291. }
  292. const {
  293. organization,
  294. onSubmitSuccess,
  295. params: {ruleId},
  296. } = this.props;
  297. const {project} = this.state;
  298. try {
  299. const response: RuleTaskResponse = await this.api.requestPromise(
  300. `/projects/${organization.slug}/${project.slug}/alert-rule-task/${this.uuid}/`
  301. );
  302. const {status, alertRule, error} = response;
  303. if (status === 'pending') {
  304. window.clearTimeout(this.pollingTimeout);
  305. this.pollingTimeout = window.setTimeout(() => {
  306. this.pollHandler(model, quitTime, loadingSlackIndicator);
  307. }, 1000);
  308. return;
  309. }
  310. this.resetPollingState(loadingSlackIndicator);
  311. if (status === 'failed') {
  312. this.handleRuleSaveFailure(error);
  313. }
  314. if (alertRule) {
  315. addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
  316. if (onSubmitSuccess) {
  317. onSubmitSuccess(alertRule, model);
  318. }
  319. }
  320. } catch {
  321. this.handleRuleSaveFailure(t('An error occurred'));
  322. this.resetPollingState(loadingSlackIndicator);
  323. }
  324. };
  325. /**
  326. * Checks to see if threshold is valid given target value, and state of
  327. * inverted threshold as well as the *other* threshold
  328. *
  329. * @param type The threshold type to be updated
  330. * @param value The new threshold value
  331. */
  332. isValidTrigger = (
  333. triggerIndex: number,
  334. trigger: Trigger,
  335. errors,
  336. resolveThreshold: number | '' | null
  337. ): boolean => {
  338. const {alertThreshold} = trigger;
  339. const {thresholdType} = this.state;
  340. // If value and/or other value is empty
  341. // then there are no checks to perform against
  342. if (!hasThresholdValue(alertThreshold) || !hasThresholdValue(resolveThreshold)) {
  343. return true;
  344. }
  345. // If this is alert threshold and not inverted, it can't be below resolve
  346. // If this is alert threshold and inverted, it can't be above resolve
  347. // If this is resolve threshold and not inverted, it can't be above resolve
  348. // If this is resolve threshold and inverted, it can't be below resolve
  349. // Since we're comparing non-inclusive thresholds here (>, <), we need
  350. // to modify the values when we compare. An example of why:
  351. // Alert > 0, resolve < 1. This means that we want to alert on values
  352. // of 1 or more, and resolve on values of 0 or less. This is valid, but
  353. // without modifying the values, this boundary case will fail.
  354. const isValid =
  355. thresholdType === AlertRuleThresholdType.BELOW
  356. ? alertThreshold - 1 < resolveThreshold + 1
  357. : alertThreshold + 1 > resolveThreshold - 1;
  358. const otherErrors = errors.get(triggerIndex) || {};
  359. if (isValid) {
  360. return true;
  361. }
  362. // Not valid... let's figure out an error message
  363. const isBelow = thresholdType === AlertRuleThresholdType.BELOW;
  364. let errorMessage = '';
  365. if (typeof resolveThreshold !== 'number') {
  366. errorMessage = isBelow
  367. ? t('Resolution threshold must be greater than alert')
  368. : t('Resolution threshold must be less than alert');
  369. } else {
  370. errorMessage = isBelow
  371. ? t('Alert threshold must be less than resolution')
  372. : t('Alert threshold must be greater than resolution');
  373. }
  374. errors.set(triggerIndex, {
  375. ...otherErrors,
  376. alertThreshold: errorMessage,
  377. });
  378. return false;
  379. };
  380. validateFieldInTrigger({errors, triggerIndex, field, message, isValid}) {
  381. // If valid, reset error for fieldName
  382. if (isValid()) {
  383. const {[field]: _validatedField, ...otherErrors} = errors.get(triggerIndex) || {};
  384. if (Object.keys(otherErrors).length > 0) {
  385. errors.set(triggerIndex, otherErrors);
  386. } else {
  387. errors.delete(triggerIndex);
  388. }
  389. return errors;
  390. }
  391. if (!errors.has(triggerIndex)) {
  392. errors.set(triggerIndex, {});
  393. }
  394. const currentErrors = errors.get(triggerIndex);
  395. errors.set(triggerIndex, {
  396. ...currentErrors,
  397. [field]: message,
  398. });
  399. return errors;
  400. }
  401. /**
  402. * Validate triggers
  403. *
  404. * @return Returns true if triggers are valid
  405. */
  406. validateTriggers(
  407. triggers = this.state.triggers,
  408. thresholdType = this.state.thresholdType,
  409. resolveThreshold = this.state.resolveThreshold,
  410. changedTriggerIndex?: number
  411. ) {
  412. const {comparisonType} = this.state;
  413. const triggerErrors = new Map();
  414. // If we have an anomaly detection alert, then we don't need to validate the thresholds, but we do need to set them to 0
  415. if (comparisonType === AlertRuleComparisonType.DYNAMIC) {
  416. // NOTE: we don't support warning triggers for anomaly detection alerts yet
  417. // once we do, uncomment this code and delete 475-478:
  418. // triggers.forEach(trigger => {
  419. // trigger.alertThreshold = 0;
  420. // });
  421. const criticalTriggerIndex = triggers.findIndex(
  422. ({label}) => label === AlertRuleTriggerType.CRITICAL
  423. );
  424. const warningTriggerIndex = criticalTriggerIndex ^ 1;
  425. const triggersCopy = [...triggers];
  426. const criticalTrigger = triggersCopy[criticalTriggerIndex];
  427. const warningTrigger = triggersCopy[warningTriggerIndex];
  428. criticalTrigger.alertThreshold = 0;
  429. warningTrigger.alertThreshold = ''; // we need to set this to empty
  430. this.setState({triggers: triggersCopy});
  431. return triggerErrors; // return an empty map
  432. }
  433. const requiredFields = ['label', 'alertThreshold'];
  434. triggers.forEach((trigger, triggerIndex) => {
  435. requiredFields.forEach(field => {
  436. // check required fields
  437. this.validateFieldInTrigger({
  438. errors: triggerErrors,
  439. triggerIndex,
  440. isValid: (): boolean => {
  441. if (trigger.label === AlertRuleTriggerType.CRITICAL) {
  442. return !isEmpty(trigger[field]);
  443. }
  444. // If warning trigger has actions, it must have a value
  445. return trigger.actions.length === 0 || !isEmpty(trigger[field]);
  446. },
  447. field,
  448. message: t('Field is required'),
  449. });
  450. });
  451. // Check thresholds
  452. this.isValidTrigger(
  453. changedTriggerIndex ?? triggerIndex,
  454. trigger,
  455. triggerErrors,
  456. resolveThreshold
  457. );
  458. });
  459. // If we have 2 triggers, we need to make sure that the critical and warning
  460. // alert thresholds are valid (e.g. if critical is above x, warning must be less than x)
  461. const criticalTriggerIndex = triggers.findIndex(
  462. ({label}) => label === AlertRuleTriggerType.CRITICAL
  463. );
  464. const warningTriggerIndex = criticalTriggerIndex ^ 1;
  465. const criticalTrigger = triggers[criticalTriggerIndex];
  466. const warningTrigger = triggers[warningTriggerIndex];
  467. const isEmptyWarningThreshold = isEmpty(warningTrigger.alertThreshold);
  468. const warningThreshold = warningTrigger.alertThreshold ?? 0;
  469. const criticalThreshold = criticalTrigger.alertThreshold ?? 0;
  470. const hasError =
  471. thresholdType === AlertRuleThresholdType.ABOVE ||
  472. comparisonType === AlertRuleComparisonType.CHANGE
  473. ? warningThreshold > criticalThreshold
  474. : warningThreshold < criticalThreshold;
  475. if (hasError && !isEmptyWarningThreshold) {
  476. [criticalTriggerIndex, warningTriggerIndex].forEach(index => {
  477. const otherErrors = triggerErrors.get(index) ?? {};
  478. triggerErrors.set(index, {
  479. ...otherErrors,
  480. alertThreshold:
  481. thresholdType === AlertRuleThresholdType.ABOVE ||
  482. comparisonType === AlertRuleComparisonType.CHANGE
  483. ? t('Warning threshold must be less than critical threshold')
  484. : t('Warning threshold must be greater than critical threshold'),
  485. });
  486. });
  487. }
  488. return triggerErrors;
  489. }
  490. validateMri = () => {
  491. const {aggregate} = this.state;
  492. return aggregate !== DEFAULT_METRIC_ALERT_FIELD;
  493. };
  494. handleFieldChange = (name: string, value: unknown) => {
  495. const {projects} = this.props;
  496. const {timeWindow} = this.state;
  497. if (name === 'alertType') {
  498. this.setState(({dataset}) => ({
  499. alertType: value as MetricAlertType,
  500. dataset: this.checkOnDemandMetricsDataset(dataset, this.state.query),
  501. timeWindow:
  502. ['custom_metrics', 'span_metrics'].includes(value as string) &&
  503. timeWindow === TimeWindow.ONE_MINUTE
  504. ? TimeWindow.FIVE_MINUTES
  505. : timeWindow,
  506. }));
  507. return;
  508. }
  509. if (name === 'projectId') {
  510. this.setState(
  511. ({project, alertType, aggregate}) => {
  512. return {
  513. projectId: value,
  514. project: projects.find(({id}) => id === value) ?? project,
  515. aggregate:
  516. alertType === 'span_metrics' ? DEFAULT_SPAN_METRIC_ALERT_FIELD : aggregate,
  517. };
  518. },
  519. () => {
  520. this.reloadData();
  521. }
  522. );
  523. }
  524. if (
  525. [
  526. 'aggregate',
  527. 'dataset',
  528. 'eventTypes',
  529. 'timeWindow',
  530. 'environment',
  531. 'comparisonDelta',
  532. 'alertType',
  533. ].includes(name)
  534. ) {
  535. this.setState(({dataset: _dataset, aggregate, alertType}) => {
  536. const dataset = this.checkOnDemandMetricsDataset(
  537. name === 'dataset' ? (value as Dataset) : _dataset,
  538. this.state.query
  539. );
  540. const newAlertType = getAlertTypeFromAggregateDataset({
  541. aggregate,
  542. dataset,
  543. });
  544. return {
  545. [name]: value,
  546. alertType: alertType !== newAlertType ? 'custom_transactions' : alertType,
  547. dataset,
  548. };
  549. });
  550. }
  551. };
  552. // We handle the filter update outside of the fieldChange handler since we
  553. // don't want to update the filter on every input change, just on blurs and
  554. // searches.
  555. handleFilterUpdate = (query: string, isQueryValid: boolean) => {
  556. const {organization, sessionId} = this.props;
  557. trackAnalytics('alert_builder.filter', {
  558. organization,
  559. session_id: sessionId,
  560. query,
  561. });
  562. const dataset = this.checkOnDemandMetricsDataset(this.state.dataset, query);
  563. this.setState({query, dataset, isQueryValid});
  564. };
  565. handleMonitorTypeSelect = (activatedAlertFields: {
  566. activationCondition?: ActivationConditionType | undefined;
  567. monitorType?: MonitorType;
  568. monitorWindowSuffix?: string | undefined;
  569. monitorWindowValue?: number | undefined;
  570. }) => {
  571. const {monitorType} = activatedAlertFields;
  572. let updatedFields = activatedAlertFields;
  573. if (monitorType === MonitorType.CONTINUOUS) {
  574. updatedFields = {
  575. ...updatedFields,
  576. activationCondition: undefined,
  577. monitorWindowValue: undefined,
  578. };
  579. }
  580. this.setState(updatedFields as State);
  581. };
  582. validateOnDemandMetricAlert() {
  583. if (
  584. !isOnDemandMetricAlert(this.state.dataset, this.state.aggregate, this.state.query)
  585. ) {
  586. return true;
  587. }
  588. return !this.state.aggregate.includes(AggregationKey.PERCENTILE);
  589. }
  590. validateActivatedAlerts() {
  591. const {organization} = this.props;
  592. const {monitorType, activationCondition, timeWindow} = this.state;
  593. const hasActivatedAlerts = organization.features.includes('activated-alert-rules');
  594. return (
  595. !hasActivatedAlerts ||
  596. monitorType !== MonitorType.ACTIVATED ||
  597. (activationCondition !== undefined && timeWindow)
  598. );
  599. }
  600. validateSubmit = model => {
  601. if (!this.validateMri()) {
  602. addErrorMessage(t('You need to select a metric before you can save the alert'));
  603. return false;
  604. }
  605. // This validates all fields *except* for Triggers
  606. const validRule = model.validateForm();
  607. // Validate Triggers
  608. const triggerErrors = this.validateTriggers();
  609. const validTriggers = Array.from(triggerErrors).length === 0;
  610. const validOnDemandAlert = this.validateOnDemandMetricAlert();
  611. const validActivatedAlerts = this.validateActivatedAlerts();
  612. if (!validTriggers) {
  613. this.setState(state => ({
  614. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  615. }));
  616. }
  617. if (!validRule || !validTriggers) {
  618. const missingFields = [
  619. !validRule && t('name'),
  620. !validRule && !validTriggers && t('and'),
  621. !validTriggers && t('critical threshold'),
  622. ].filter(x => x);
  623. addErrorMessage(t('Alert not valid: missing %s', missingFields.join(' ')));
  624. return false;
  625. }
  626. if (!validOnDemandAlert) {
  627. addErrorMessage(
  628. t('%s is not supported for on-demand metric alerts', this.state.aggregate)
  629. );
  630. return false;
  631. }
  632. if (!validActivatedAlerts) {
  633. addErrorMessage(
  634. t('Activation condition and monitor window must be set for activated alerts')
  635. );
  636. return false;
  637. }
  638. return true;
  639. };
  640. handleSubmit = async (
  641. _data: Partial<MetricRule>,
  642. _onSubmitSuccess,
  643. _onSubmitError,
  644. _e,
  645. model: FormModel
  646. ) => {
  647. if (!this.validateSubmit(model)) {
  648. return;
  649. }
  650. const {
  651. organization,
  652. rule,
  653. onSubmitSuccess,
  654. location,
  655. sessionId,
  656. params: {ruleId},
  657. } = this.props;
  658. const {
  659. project,
  660. aggregate,
  661. resolveThreshold,
  662. triggers,
  663. thresholdType,
  664. thresholdPeriod,
  665. comparisonDelta,
  666. timeWindow,
  667. eventTypes,
  668. monitorType,
  669. activationCondition,
  670. sensitivity,
  671. seasonality,
  672. comparisonType,
  673. } = this.state;
  674. // Remove empty warning trigger
  675. const sanitizedTriggers = triggers.filter(
  676. trigger =>
  677. trigger.label !== AlertRuleTriggerType.WARNING || !isEmpty(trigger.alertThreshold)
  678. );
  679. const hasActivatedAlerts = organization.features.includes('activated-alert-rules');
  680. // form model has all form state data, however we use local state to keep
  681. // track of the list of triggers (and actions within triggers)
  682. const loadingIndicator = IndicatorStore.addMessage(
  683. t('Saving your alert rule, hold on...'),
  684. 'loading'
  685. );
  686. await Sentry.withScope(async scope => {
  687. try {
  688. scope.setTag('type', AlertRuleType.METRIC);
  689. scope.setTag('operation', !rule.id ? 'create' : 'edit');
  690. for (const trigger of sanitizedTriggers) {
  691. for (const action of trigger.actions) {
  692. if (action.type === 'slack' || action.type === 'discord') {
  693. scope.setTag(action.type, true);
  694. }
  695. }
  696. }
  697. scope.setExtra('actions', sanitizedTriggers);
  698. metric.startSpan({name: 'saveAlertRule'});
  699. let activatedAlertFields = {};
  700. if (hasActivatedAlerts) {
  701. activatedAlertFields = {
  702. monitorType,
  703. activationCondition,
  704. };
  705. }
  706. const detectionTypes = new Map([
  707. [AlertRuleComparisonType.COUNT, 'static'],
  708. [AlertRuleComparisonType.CHANGE, 'percent'],
  709. [AlertRuleComparisonType.DYNAMIC, 'dynamic'],
  710. ]);
  711. const detectionType = detectionTypes.get(comparisonType) ?? '';
  712. const dataset = this.determinePerformanceDataset();
  713. this.setState({loading: true});
  714. // Add or update is just the PUT/POST to the org alert-rules api
  715. // we're splatting the full rule in, then overwriting all the data?
  716. const [data, , resp] = await addOrUpdateRule(
  717. this.api,
  718. organization.slug,
  719. {
  720. ...rule, // existing rule
  721. ...model.getTransformedData(), // form data
  722. ...activatedAlertFields,
  723. projects: [project.slug],
  724. triggers: sanitizedTriggers,
  725. resolveThreshold: isEmpty(resolveThreshold) ? null : resolveThreshold,
  726. thresholdType,
  727. thresholdPeriod,
  728. comparisonDelta: comparisonDelta ?? null,
  729. timeWindow,
  730. aggregate,
  731. // Remove eventTypes as it is no longer required for crash free
  732. eventTypes: isCrashFreeAlert(rule.dataset) ? undefined : eventTypes,
  733. dataset,
  734. queryType: DatasetMEPAlertQueryTypes[dataset],
  735. sensitivity: sensitivity ?? null,
  736. seasonality: seasonality ?? null,
  737. detectionType: detectionType,
  738. },
  739. {
  740. duplicateRule: this.isDuplicateRule ? 'true' : 'false',
  741. wizardV3: 'true',
  742. referrer: location?.query?.referrer,
  743. sessionId,
  744. ...getForceMetricsLayerQueryExtras(organization, dataset),
  745. }
  746. );
  747. // if we get a 202 back it means that we have an async task
  748. // running to lookup and verify the channel id for Slack.
  749. if (resp?.status === 202) {
  750. // if we have a uuid in state, no need to start a new polling cycle
  751. if (!this.uuid) {
  752. this.uuid = data.uuid;
  753. this.setState({loading: true});
  754. this.fetchStatus(model);
  755. }
  756. } else {
  757. IndicatorStore.remove(loadingIndicator);
  758. this.setState({loading: false});
  759. addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
  760. if (onSubmitSuccess) {
  761. onSubmitSuccess(data, model);
  762. }
  763. }
  764. } catch (err) {
  765. IndicatorStore.remove(loadingIndicator);
  766. this.setState({loading: false});
  767. const errors = err?.responseJSON
  768. ? Array.isArray(err?.responseJSON)
  769. ? err?.responseJSON
  770. : Object.values(err?.responseJSON)
  771. : [];
  772. let apiErrors = '';
  773. if (typeof errors[0] === 'object') {
  774. // NOTE: this occurs if we get a TimeoutError when attempting to hit the Seer API
  775. apiErrors = ': ' + errors[0].message;
  776. } else {
  777. apiErrors = errors.length > 0 ? `: ${errors.join(', ')}` : '';
  778. }
  779. this.handleRuleSaveFailure(t('Unable to save alert%s', apiErrors));
  780. }
  781. });
  782. };
  783. /**
  784. * Callback for when triggers change
  785. *
  786. * Re-validate triggers on every change and reset indicators when no errors
  787. */
  788. handleChangeTriggers = (triggers: Trigger[], triggerIndex?: number) => {
  789. this.setState(state => {
  790. let triggerErrors = state.triggerErrors;
  791. const newTriggerErrors = this.validateTriggers(
  792. triggers,
  793. state.thresholdType,
  794. state.resolveThreshold,
  795. triggerIndex
  796. );
  797. triggerErrors = newTriggerErrors;
  798. if (Array.from(newTriggerErrors).length === 0) {
  799. clearIndicators();
  800. }
  801. return {triggers, triggerErrors, triggersHaveChanged: true};
  802. });
  803. };
  804. handleSensitivityChange = (sensitivity: AlertRuleSensitivity) => {
  805. this.setState({sensitivity});
  806. };
  807. handleThresholdTypeChange = (thresholdType: AlertRuleThresholdType) => {
  808. const {triggers} = this.state;
  809. const triggerErrors = this.validateTriggers(triggers, thresholdType);
  810. this.setState(state => ({
  811. thresholdType,
  812. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  813. }));
  814. };
  815. handleThresholdPeriodChange = (value: number) => {
  816. this.setState({thresholdPeriod: value});
  817. };
  818. handleResolveThresholdChange = (
  819. resolveThreshold: UnsavedMetricRule['resolveThreshold']
  820. ) => {
  821. this.setState(state => {
  822. const triggerErrors = this.validateTriggers(
  823. state.triggers,
  824. state.thresholdType,
  825. resolveThreshold
  826. );
  827. if (Array.from(triggerErrors).length === 0) {
  828. clearIndicators();
  829. }
  830. return {resolveThreshold, triggerErrors};
  831. });
  832. };
  833. handleComparisonTypeChange = (value: AlertRuleComparisonType) => {
  834. const comparisonDelta =
  835. value === AlertRuleComparisonType.CHANGE
  836. ? this.state.comparisonDelta ?? DEFAULT_CHANGE_COMP_DELTA
  837. : undefined;
  838. const timeWindow = this.state.comparisonDelta
  839. ? DEFAULT_COUNT_TIME_WINDOW
  840. : DEFAULT_CHANGE_TIME_WINDOW;
  841. const sensitivity =
  842. value === AlertRuleComparisonType.DYNAMIC
  843. ? this.state.sensitivity || AlertRuleSensitivity.MEDIUM
  844. : undefined;
  845. const seasonality =
  846. value === AlertRuleComparisonType.DYNAMIC ? AlertRuleSeasonality.AUTO : undefined; // TODO: replace "auto" with the correct constant
  847. this.setState({
  848. comparisonType: value,
  849. comparisonDelta,
  850. timeWindow,
  851. sensitivity,
  852. seasonality,
  853. });
  854. };
  855. handleDeleteRule = async () => {
  856. const {organization, params} = this.props;
  857. const {ruleId} = params;
  858. try {
  859. await this.api.requestPromise(
  860. `/organizations/${organization.slug}/alert-rules/${ruleId}/`,
  861. {
  862. method: 'DELETE',
  863. }
  864. );
  865. this.goBack();
  866. } catch (_err) {
  867. addErrorMessage(t('Error deleting rule'));
  868. }
  869. };
  870. handleRuleSaveFailure = (msg: ReactNode) => {
  871. addErrorMessage(msg);
  872. metric.endSpan({name: 'saveAlertRule'});
  873. };
  874. handleCancel = () => {
  875. this.goBack();
  876. };
  877. handleMEPAlertDataset = (data: EventsStats | MultiSeriesEventsStats | null) => {
  878. const {isMetricsData} = data ?? {};
  879. const {organization} = this.props;
  880. if (
  881. isMetricsData === undefined ||
  882. !organization.features.includes('mep-rollout-flag')
  883. ) {
  884. return;
  885. }
  886. const {dataset} = this.state;
  887. if (isMetricsData && dataset === Dataset.TRANSACTIONS) {
  888. this.setState({dataset: Dataset.GENERIC_METRICS});
  889. }
  890. if (!isMetricsData && dataset === Dataset.GENERIC_METRICS) {
  891. this.setState({dataset: Dataset.TRANSACTIONS});
  892. }
  893. };
  894. handleTimeSeriesDataFetched = (data: EventsStats | MultiSeriesEventsStats | null) => {
  895. const {isExtrapolatedData} = data ?? {};
  896. if (shouldShowOnDemandMetricAlertUI(this.props.organization)) {
  897. this.setState({isExtrapolatedChartData: Boolean(isExtrapolatedData)});
  898. }
  899. const {dataset, aggregate, query} = this.state;
  900. if (!isOnDemandMetricAlert(dataset, aggregate, query)) {
  901. this.handleMEPAlertDataset(data);
  902. }
  903. };
  904. // If the user is creating an on-demand metric alert, we want to override the dataset
  905. // to be generic metrics instead of transactions
  906. checkOnDemandMetricsDataset = (dataset: Dataset, query: string) => {
  907. if (!hasOnDemandMetricAlertFeature(this.props.organization)) {
  908. return dataset;
  909. }
  910. if (dataset !== Dataset.TRANSACTIONS || !isOnDemandQueryString(query)) {
  911. return dataset;
  912. }
  913. return Dataset.GENERIC_METRICS;
  914. };
  915. // We are not allowing the creation of new transaction alerts
  916. determinePerformanceDataset = () => {
  917. // TODO: once all alerts are migrated to MEP, we can set the default to GENERIC_METRICS and remove this as well as
  918. // logic in handleMEPDataset, handleTimeSeriesDataFetched and checkOnDemandMetricsDataset
  919. const {dataset} = this.state;
  920. const {organization} = this.props;
  921. const hasMetricsFeatureFlags =
  922. organization.features.includes('mep-rollout-flag') ||
  923. hasOnDemandMetricAlertFeature(organization);
  924. if (hasMetricsFeatureFlags && dataset === Dataset.TRANSACTIONS) {
  925. return Dataset.GENERIC_METRICS;
  926. }
  927. return dataset;
  928. };
  929. renderLoading() {
  930. return this.renderBody();
  931. }
  932. renderTriggerChart() {
  933. const {organization, ruleId, rule, location} = this.props;
  934. const {
  935. query,
  936. project,
  937. timeWindow,
  938. triggers,
  939. aggregate,
  940. environment,
  941. thresholdType,
  942. comparisonDelta,
  943. comparisonType,
  944. resolveThreshold,
  945. eventTypes,
  946. dataset,
  947. alertType,
  948. isQueryValid,
  949. } = this.state;
  950. const isOnDemand = isOnDemandMetricAlert(dataset, aggregate, query);
  951. let formattedAggregate = aggregate;
  952. if (alertType === 'custom_metrics') {
  953. formattedAggregate = formatMRIField(aggregate);
  954. } else if (alertType === 'span_metrics') {
  955. formattedAggregate = getFormattedSpanMetricField(
  956. aggregate,
  957. this.state.metricExtractionRules
  958. );
  959. }
  960. const chartProps = {
  961. organization,
  962. projects: [project],
  963. triggers,
  964. location,
  965. query: this.chartQuery,
  966. aggregate,
  967. formattedAggregate: formattedAggregate,
  968. dataset,
  969. newAlertOrQuery: !ruleId || query !== rule.query,
  970. timeWindow,
  971. environment,
  972. resolveThreshold,
  973. thresholdType,
  974. comparisonDelta,
  975. comparisonType,
  976. isQueryValid,
  977. isOnDemandMetricAlert: isOnDemand,
  978. showTotalCount:
  979. !['custom_metrics', 'span_metrics'].includes(alertType) && !isOnDemand,
  980. onDataLoaded: this.handleTimeSeriesDataFetched,
  981. };
  982. let formattedQuery = `event.type:${eventTypes?.join(',')}`;
  983. if (alertType === 'custom_metrics') {
  984. formattedQuery = '';
  985. }
  986. if (alertType === 'span_metrics') {
  987. const mri = parseField(aggregate)!.mri;
  988. const condition = findExtractionRuleCondition(
  989. mri,
  990. this.state.metricExtractionRules || []
  991. );
  992. formattedQuery = condition?.value || '';
  993. }
  994. const wizardBuilderChart = (
  995. <TriggersChart
  996. {...chartProps}
  997. header={
  998. <ChartHeader>
  999. <AlertName>{AlertWizardAlertNames[alertType]}</AlertName>
  1000. {!isCrashFreeAlert(dataset) && (
  1001. <AlertInfo>
  1002. <StyledCircleIndicator size={8} />
  1003. <Aggregate>{formattedAggregate}</Aggregate>
  1004. {formattedQuery}
  1005. </AlertInfo>
  1006. )}
  1007. </ChartHeader>
  1008. }
  1009. />
  1010. );
  1011. return wizardBuilderChart;
  1012. }
  1013. renderBody() {
  1014. const {
  1015. organization,
  1016. ruleId,
  1017. rule,
  1018. onSubmitSuccess,
  1019. router,
  1020. disableProjectSelector,
  1021. eventView,
  1022. location,
  1023. } = this.props;
  1024. const {
  1025. name,
  1026. query,
  1027. project,
  1028. timeWindow,
  1029. triggers,
  1030. aggregate,
  1031. thresholdType,
  1032. thresholdPeriod,
  1033. comparisonDelta,
  1034. comparisonType,
  1035. resolveThreshold,
  1036. sensitivity,
  1037. loading,
  1038. eventTypes,
  1039. dataset,
  1040. alertType,
  1041. isExtrapolatedChartData,
  1042. triggersHaveChanged,
  1043. activationCondition,
  1044. monitorType,
  1045. } = this.state;
  1046. const wizardBuilderChart = this.renderTriggerChart();
  1047. // Used to hide specific fields like actions while migrating metric alert rules.
  1048. // Currently used to help people add `is:unresolved` to their metric alert query.
  1049. const isMigration = location?.query?.migration === '1';
  1050. const triggerForm = (disabled: boolean) => (
  1051. <Triggers
  1052. disabled={disabled}
  1053. projects={[project]}
  1054. errors={this.state.triggerErrors}
  1055. triggers={triggers}
  1056. aggregate={aggregate}
  1057. isMigration={isMigration}
  1058. resolveThreshold={resolveThreshold}
  1059. sensitivity={sensitivity}
  1060. thresholdPeriod={thresholdPeriod}
  1061. thresholdType={thresholdType}
  1062. comparisonType={comparisonType}
  1063. currentProject={project.slug}
  1064. organization={organization}
  1065. availableActions={this.state.availableActions}
  1066. onChange={this.handleChangeTriggers}
  1067. onThresholdTypeChange={this.handleThresholdTypeChange}
  1068. onThresholdPeriodChange={this.handleThresholdPeriodChange}
  1069. onResolveThresholdChange={this.handleResolveThresholdChange}
  1070. onSensitivityChange={this.handleSensitivityChange}
  1071. />
  1072. );
  1073. const ruleNameOwnerForm = (disabled: boolean) => (
  1074. <RuleNameOwnerForm disabled={disabled} project={project} />
  1075. );
  1076. const thresholdTypeForm = (disabled: boolean) => (
  1077. <ThresholdTypeForm
  1078. comparisonType={comparisonType}
  1079. dataset={dataset}
  1080. disabled={disabled}
  1081. onComparisonDeltaChange={value =>
  1082. this.handleFieldChange('comparisonDelta', value)
  1083. }
  1084. onComparisonTypeChange={this.handleComparisonTypeChange}
  1085. organization={organization}
  1086. comparisonDelta={comparisonDelta}
  1087. />
  1088. );
  1089. const hasAlertWrite = hasEveryAccess(['alerts:write'], {organization, project});
  1090. const formDisabled = loading || !hasAlertWrite;
  1091. const submitDisabled = formDisabled || !this.state.isQueryValid;
  1092. const showErrorMigrationWarning =
  1093. !!ruleId && isMigration && ruleNeedsErrorMigration(rule);
  1094. // Rendering the main form body
  1095. return (
  1096. <Main fullWidth>
  1097. <PermissionAlert access={['alerts:write']} project={project} />
  1098. {eventView && <IncompatibleAlertQuery eventView={eventView} />}
  1099. <Form
  1100. model={this.form}
  1101. apiMethod={ruleId ? 'PUT' : 'POST'}
  1102. apiEndpoint={`/organizations/${organization.slug}/alert-rules/${
  1103. ruleId ? `${ruleId}/` : ''
  1104. }`}
  1105. submitDisabled={submitDisabled}
  1106. initialData={{
  1107. name,
  1108. dataset,
  1109. eventTypes,
  1110. aggregate,
  1111. query,
  1112. timeWindow: rule.timeWindow,
  1113. environment: rule.environment || null,
  1114. owner: rule.owner,
  1115. projectId: project.id,
  1116. alertType,
  1117. }}
  1118. saveOnBlur={false}
  1119. onSubmit={this.handleSubmit}
  1120. onSubmitSuccess={onSubmitSuccess}
  1121. onCancel={this.handleCancel}
  1122. onFieldChange={this.handleFieldChange}
  1123. extraButton={
  1124. rule.id ? (
  1125. <Confirm
  1126. disabled={formDisabled}
  1127. message={t(
  1128. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  1129. rule.name
  1130. )}
  1131. header={<h5>{t('Delete Alert Rule?')}</h5>}
  1132. priority="danger"
  1133. confirmText={t('Delete Rule')}
  1134. onConfirm={this.handleDeleteRule}
  1135. >
  1136. <Button priority="danger">{t('Delete Rule')}</Button>
  1137. </Confirm>
  1138. ) : null
  1139. }
  1140. submitLabel={
  1141. isMigration && !triggersHaveChanged ? t('Looks good to me!') : t('Save Rule')
  1142. }
  1143. >
  1144. <List symbol="colored-numeric">
  1145. <RuleConditionsForm
  1146. activationCondition={activationCondition}
  1147. aggregate={aggregate}
  1148. alertType={alertType}
  1149. allowChangeEventTypes={
  1150. hasCustomMetrics(organization)
  1151. ? dataset === Dataset.ERRORS
  1152. : dataset === Dataset.ERRORS || alertType === 'custom_transactions'
  1153. }
  1154. comparisonDelta={comparisonDelta}
  1155. comparisonType={comparisonType}
  1156. dataset={dataset}
  1157. disableProjectSelector={disableProjectSelector}
  1158. disabled={formDisabled}
  1159. isEditing={Boolean(ruleId)}
  1160. isErrorMigration={showErrorMigrationWarning}
  1161. isExtrapolatedChartData={isExtrapolatedChartData}
  1162. isForSpanMetric={aggregate.includes(':spans/')}
  1163. isTransactionMigration={isMigration && !showErrorMigrationWarning}
  1164. monitorType={monitorType}
  1165. onComparisonDeltaChange={value =>
  1166. this.handleFieldChange('comparisonDelta', value)
  1167. }
  1168. onFilterSearch={this.handleFilterUpdate}
  1169. onMonitorTypeSelect={this.handleMonitorTypeSelect}
  1170. onTimeWindowChange={value => this.handleFieldChange('timeWindow', value)}
  1171. organization={organization}
  1172. project={project}
  1173. router={router}
  1174. thresholdChart={wizardBuilderChart}
  1175. timeWindow={timeWindow}
  1176. />
  1177. <AlertListItem>{t('Set thresholds')}</AlertListItem>
  1178. {thresholdTypeForm(formDisabled)}
  1179. {showErrorMigrationWarning && (
  1180. <Alert type="warning" showIcon>
  1181. {tct(
  1182. "We've added [code:is:unresolved] to your events filter; please make sure the current thresholds are still valid as this alert is now filtering out resolved and archived errors.",
  1183. {
  1184. code: <code />,
  1185. }
  1186. )}
  1187. </Alert>
  1188. )}
  1189. {triggerForm(formDisabled)}
  1190. {ruleNameOwnerForm(formDisabled)}
  1191. </List>
  1192. </Form>
  1193. </Main>
  1194. );
  1195. }
  1196. }
  1197. const Main = styled(Layout.Main)`
  1198. max-width: 1000px;
  1199. `;
  1200. const AlertListItem = styled(ListItem)`
  1201. margin: ${space(2)} 0 ${space(1)} 0;
  1202. font-size: ${p => p.theme.fontSizeExtraLarge};
  1203. margin-top: 0;
  1204. `;
  1205. const ChartHeader = styled('div')`
  1206. padding: ${space(2)} ${space(3)} 0 ${space(3)};
  1207. margin-bottom: -${space(1.5)};
  1208. `;
  1209. const AlertName = styled(HeaderTitleLegend)`
  1210. position: relative;
  1211. `;
  1212. const AlertInfo = styled('div')`
  1213. font-size: ${p => p.theme.fontSizeSmall};
  1214. font-family: ${p => p.theme.text.family};
  1215. font-weight: ${p => p.theme.fontWeightNormal};
  1216. color: ${p => p.theme.textColor};
  1217. `;
  1218. const StyledCircleIndicator = styled(CircleIndicator)`
  1219. background: ${p => p.theme.formText};
  1220. height: ${space(1)};
  1221. margin-right: ${space(0.5)};
  1222. `;
  1223. const Aggregate = styled('span')`
  1224. margin-right: ${space(1)};
  1225. `;
  1226. export default withProjects(RuleFormContainer);