ruleForm.tsx 47 KB

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