ruleForm.tsx 48 KB

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