ruleForm.tsx 44 KB

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