ruleForm.tsx 49 KB

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