ruleForm.tsx 48 KB

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