ruleForm.tsx 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  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. Confidence,
  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 {
  58. determineMultiSeriesConfidence,
  59. determineSeriesConfidence,
  60. } from 'sentry/views/alerts/rules/metric/utils/determineSeriesConfidence';
  61. import {getEventTypeFilter} from 'sentry/views/alerts/rules/metric/utils/getEventTypeFilter';
  62. import hasThresholdValue from 'sentry/views/alerts/rules/metric/utils/hasThresholdValue';
  63. import {isCustomMetricAlert} from 'sentry/views/alerts/rules/metric/utils/isCustomMetricAlert';
  64. import {isOnDemandMetricAlert} from 'sentry/views/alerts/rules/metric/utils/onDemandMetricAlert';
  65. import {AlertRuleType, type Anomaly} from 'sentry/views/alerts/types';
  66. import {ruleNeedsErrorMigration} from 'sentry/views/alerts/utils/migrationUi';
  67. import type {MetricAlertType} from 'sentry/views/alerts/wizard/options';
  68. import {
  69. AlertWizardAlertNames,
  70. DatasetMEPAlertQueryTypes,
  71. } from 'sentry/views/alerts/wizard/options';
  72. import {getAlertTypeFromAggregateDataset} from 'sentry/views/alerts/wizard/utils';
  73. import {isEventsStats} from 'sentry/views/dashboards/utils/isEventsStats';
  74. import {MetricsBetaEndAlert} from 'sentry/views/metrics/metricsBetaEndAlert';
  75. import PermissionAlert from 'sentry/views/settings/project/permissionAlert';
  76. import {isCrashFreeAlert} from './utils/isCrashFreeAlert';
  77. import {addOrUpdateRule} from './actions';
  78. import {
  79. createDefaultTrigger,
  80. DEFAULT_CHANGE_COMP_DELTA,
  81. DEFAULT_CHANGE_TIME_WINDOW,
  82. DEFAULT_COUNT_TIME_WINDOW,
  83. DEFAULT_DYNAMIC_TIME_WINDOW,
  84. } from './constants';
  85. import RuleConditionsForm from './ruleConditionsForm';
  86. import {
  87. AlertRuleSeasonality,
  88. AlertRuleSensitivity,
  89. type EventTypes,
  90. type MetricActionTemplate,
  91. type MetricRule,
  92. type Trigger,
  93. type UnsavedMetricRule,
  94. } from './types';
  95. import {
  96. AlertRuleComparisonType,
  97. AlertRuleThresholdType,
  98. AlertRuleTriggerType,
  99. Dataset,
  100. TimeWindow,
  101. } from './types';
  102. const POLLING_MAX_TIME_LIMIT = 3 * 60000;
  103. type RuleTaskResponse = {
  104. status: 'pending' | 'failed' | 'success';
  105. alertRule?: MetricRule;
  106. error?: string;
  107. };
  108. type HistoricalDataset = ReturnType<typeof formatStatsToHistoricalDataset>;
  109. type Props = {
  110. organization: Organization;
  111. project: Project;
  112. projects: Project[];
  113. routes: PlainRoute[];
  114. rule: MetricRule;
  115. userTeamIds: string[];
  116. disableProjectSelector?: boolean;
  117. eventView?: EventView;
  118. isCustomMetric?: boolean;
  119. isDuplicateRule?: boolean;
  120. ruleId?: string;
  121. sessionId?: string;
  122. } & RouteComponentProps<{projectId?: string; ruleId?: string}, {}> & {
  123. onSubmitSuccess?: FormProps['onSubmitSuccess'];
  124. } & DeprecatedAsyncComponent['props'];
  125. type State = {
  126. aggregate: string;
  127. alertType: MetricAlertType;
  128. anomalies: Anomaly[];
  129. // `null` means loading
  130. availableActions: MetricActionTemplate[] | null;
  131. comparisonType: AlertRuleComparisonType;
  132. currentData: HistoricalDataset;
  133. // Rule conditions form inputs
  134. // Needed for TriggersChart
  135. dataset: Dataset;
  136. environment: string | null;
  137. eventTypes: EventTypes[];
  138. historicalData: HistoricalDataset;
  139. isQueryValid: boolean;
  140. project: Project;
  141. query: string;
  142. resolveThreshold: UnsavedMetricRule['resolveThreshold'];
  143. sensitivity: UnsavedMetricRule['sensitivity'];
  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. confidence?: Confidence;
  152. isExtrapolatedChartData?: 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: any, context: any) {
  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: any,
  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}: any) {
  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. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  443. return !isEmpty(trigger[field]);
  444. }
  445. // If warning trigger has actions, it must have a value
  446. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  447. return trigger.actions.length === 0 || !isEmpty(trigger[field]);
  448. },
  449. field,
  450. message: t('Field is required'),
  451. });
  452. });
  453. // Check thresholds
  454. this.isValidTrigger(
  455. changedTriggerIndex ?? triggerIndex,
  456. trigger,
  457. triggerErrors,
  458. resolveThreshold
  459. );
  460. });
  461. // If we have 2 triggers, we need to make sure that the critical and warning
  462. // alert thresholds are valid (e.g. if critical is above x, warning must be less than x)
  463. const criticalTriggerIndex = triggers.findIndex(
  464. ({label}) => label === AlertRuleTriggerType.CRITICAL
  465. );
  466. const warningTriggerIndex = criticalTriggerIndex ^ 1;
  467. const criticalTrigger = triggers[criticalTriggerIndex]!;
  468. const warningTrigger = triggers[warningTriggerIndex]!;
  469. const isEmptyWarningThreshold = isEmpty(warningTrigger.alertThreshold);
  470. const warningThreshold = warningTrigger.alertThreshold ?? 0;
  471. const criticalThreshold = criticalTrigger.alertThreshold ?? 0;
  472. const hasError =
  473. thresholdType === AlertRuleThresholdType.ABOVE ||
  474. comparisonType === AlertRuleComparisonType.CHANGE
  475. ? warningThreshold > criticalThreshold
  476. : warningThreshold < criticalThreshold;
  477. if (hasError && !isEmptyWarningThreshold) {
  478. [criticalTriggerIndex, warningTriggerIndex].forEach(index => {
  479. const otherErrors = triggerErrors.get(index) ?? {};
  480. triggerErrors.set(index, {
  481. ...otherErrors,
  482. alertThreshold:
  483. thresholdType === AlertRuleThresholdType.ABOVE ||
  484. comparisonType === AlertRuleComparisonType.CHANGE
  485. ? t('Warning threshold must be less than critical threshold')
  486. : t('Warning threshold must be greater than critical threshold'),
  487. });
  488. });
  489. }
  490. return triggerErrors;
  491. }
  492. validateMri = () => {
  493. const {aggregate} = this.state;
  494. return aggregate !== DEFAULT_METRIC_ALERT_FIELD;
  495. };
  496. handleFieldChange = (name: string, value: unknown) => {
  497. const {projects} = this.props;
  498. const {timeWindow, chartError} = this.state;
  499. if (chartError) {
  500. this.setState({chartError: false, chartErrorMessage: undefined});
  501. }
  502. if (name === 'alertType') {
  503. if (value === 'crash_free_sessions' || value === 'crash_free_users') {
  504. this.setState({comparisonType: AlertRuleComparisonType.COUNT});
  505. }
  506. this.setState(({dataset}) => ({
  507. alertType: value as MetricAlertType,
  508. dataset: this.checkOnDemandMetricsDataset(dataset, this.state.query),
  509. timeWindow:
  510. ['custom_metrics', 'span_metrics'].includes(value as string) &&
  511. timeWindow === TimeWindow.ONE_MINUTE
  512. ? TimeWindow.FIVE_MINUTES
  513. : timeWindow,
  514. }));
  515. return;
  516. }
  517. if (name === 'projectId') {
  518. this.setState(
  519. ({project}) => {
  520. return {
  521. projectId: value,
  522. project: projects.find(({id}) => id === value) ?? project,
  523. };
  524. },
  525. () => {
  526. this.reloadData();
  527. }
  528. );
  529. }
  530. if (
  531. [
  532. 'aggregate',
  533. 'dataset',
  534. 'eventTypes',
  535. 'timeWindow',
  536. 'environment',
  537. 'comparisonDelta',
  538. 'alertType',
  539. ].includes(name)
  540. ) {
  541. this.setState(({dataset: _dataset, aggregate, alertType}) => {
  542. const dataset = this.checkOnDemandMetricsDataset(
  543. name === 'dataset' ? (value as Dataset) : _dataset,
  544. this.state.query
  545. );
  546. const newAlertType = getAlertTypeFromAggregateDataset({
  547. aggregate,
  548. dataset,
  549. });
  550. return {
  551. [name]: value,
  552. alertType: alertType !== newAlertType ? 'custom_transactions' : alertType,
  553. dataset,
  554. };
  555. });
  556. }
  557. };
  558. // We handle the filter update outside of the fieldChange handler since we
  559. // don't want to update the filter on every input change, just on blurs and
  560. // searches.
  561. handleFilterUpdate = (query: string, isQueryValid: boolean) => {
  562. const {organization, sessionId} = this.props;
  563. trackAnalytics('alert_builder.filter', {
  564. organization,
  565. session_id: sessionId,
  566. query,
  567. });
  568. const dataset = this.checkOnDemandMetricsDataset(this.state.dataset, query);
  569. this.setState({query, dataset, isQueryValid});
  570. };
  571. validateOnDemandMetricAlert() {
  572. if (
  573. !isOnDemandMetricAlert(this.state.dataset, this.state.aggregate, this.state.query)
  574. ) {
  575. return true;
  576. }
  577. return !this.state.aggregate.includes(AggregationKey.PERCENTILE);
  578. }
  579. validateSubmit = (model: any) => {
  580. if (!this.validateMri()) {
  581. addErrorMessage(t('You need to select a metric before you can save the alert'));
  582. return false;
  583. }
  584. // This validates all fields *except* for Triggers
  585. const validRule = model.validateForm();
  586. // Validate Triggers
  587. const triggerErrors = this.validateTriggers();
  588. const validTriggers = Array.from(triggerErrors).length === 0;
  589. const validOnDemandAlert = this.validateOnDemandMetricAlert();
  590. if (!validTriggers) {
  591. this.setState(state => ({
  592. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  593. }));
  594. }
  595. if (!validRule || !validTriggers) {
  596. const missingFields = [
  597. !validRule && t('name'),
  598. !validRule && !validTriggers && t('and'),
  599. !validTriggers && t('critical threshold'),
  600. ].filter(x => x);
  601. addErrorMessage(t('Alert not valid: missing %s', missingFields.join(' ')));
  602. return false;
  603. }
  604. if (!validOnDemandAlert) {
  605. addErrorMessage(
  606. t('%s is not supported for on-demand metric alerts', this.state.aggregate)
  607. );
  608. return false;
  609. }
  610. return true;
  611. };
  612. handleSubmit = async (
  613. _data: Partial<MetricRule>,
  614. _onSubmitSuccess: any,
  615. _onSubmitError: any,
  616. _e: any,
  617. model: FormModel
  618. ) => {
  619. if (!this.validateSubmit(model)) {
  620. return;
  621. }
  622. const {
  623. organization,
  624. rule,
  625. onSubmitSuccess,
  626. location,
  627. sessionId,
  628. params: {ruleId},
  629. } = this.props;
  630. const {
  631. project,
  632. aggregate,
  633. resolveThreshold,
  634. triggers,
  635. thresholdType,
  636. thresholdPeriod,
  637. comparisonDelta,
  638. timeWindow,
  639. eventTypes,
  640. sensitivity,
  641. seasonality,
  642. comparisonType,
  643. } = this.state;
  644. // Remove empty warning trigger
  645. const sanitizedTriggers = triggers.filter(
  646. trigger =>
  647. trigger.label !== AlertRuleTriggerType.WARNING || !isEmpty(trigger.alertThreshold)
  648. );
  649. // form model has all form state data, however we use local state to keep
  650. // track of the list of triggers (and actions within triggers)
  651. const loadingIndicator = IndicatorStore.addMessage(
  652. t('Saving your alert rule, hold on...'),
  653. 'loading'
  654. );
  655. await Sentry.withScope(async scope => {
  656. try {
  657. scope.setTag('type', AlertRuleType.METRIC);
  658. scope.setTag('operation', !rule.id ? 'create' : 'edit');
  659. for (const trigger of sanitizedTriggers) {
  660. for (const action of trigger.actions) {
  661. if (action.type === 'slack' || action.type === 'discord') {
  662. scope.setTag(action.type, true);
  663. }
  664. }
  665. }
  666. scope.setExtra('actions', sanitizedTriggers);
  667. metric.startSpan({name: 'saveAlertRule'});
  668. const detectionTypes = new Map([
  669. [AlertRuleComparisonType.COUNT, 'static'],
  670. [AlertRuleComparisonType.CHANGE, 'percent'],
  671. [AlertRuleComparisonType.DYNAMIC, 'dynamic'],
  672. ]);
  673. const detectionType = detectionTypes.get(comparisonType) ?? '';
  674. const dataset = this.determinePerformanceDataset();
  675. this.setState({loading: true});
  676. // Add or update is just the PUT/POST to the org alert-rules api
  677. // we're splatting the full rule in, then overwriting all the data?
  678. const [data, , resp] = await addOrUpdateRule(
  679. this.api,
  680. organization.slug,
  681. {
  682. ...rule, // existing rule
  683. ...model.getTransformedData(), // form data
  684. projects: [project.slug],
  685. triggers: sanitizedTriggers,
  686. resolveThreshold:
  687. isEmpty(resolveThreshold) ||
  688. detectionType === AlertRuleComparisonType.DYNAMIC
  689. ? null
  690. : resolveThreshold,
  691. thresholdType,
  692. thresholdPeriod,
  693. comparisonDelta: comparisonDelta ?? null,
  694. timeWindow,
  695. aggregate,
  696. // Remove eventTypes as it is no longer required for crash free
  697. eventTypes: isCrashFreeAlert(rule.dataset) ? undefined : eventTypes,
  698. dataset,
  699. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  700. queryType: DatasetMEPAlertQueryTypes[dataset],
  701. sensitivity: sensitivity ?? null,
  702. seasonality: seasonality ?? null,
  703. detectionType,
  704. },
  705. {
  706. duplicateRule: this.isDuplicateRule ? 'true' : 'false',
  707. wizardV3: 'true',
  708. referrer: location?.query?.referrer,
  709. sessionId,
  710. ...getForceMetricsLayerQueryExtras(organization, dataset),
  711. }
  712. );
  713. // if we get a 202 back it means that we have an async task
  714. // running to lookup and verify the channel id for Slack.
  715. if (resp?.status === 202) {
  716. // if we have a uuid in state, no need to start a new polling cycle
  717. if (!this.uuid) {
  718. this.uuid = data.uuid;
  719. this.setState({loading: true});
  720. this.fetchStatus(model);
  721. }
  722. } else {
  723. IndicatorStore.remove(loadingIndicator);
  724. this.setState({loading: false});
  725. addSuccessMessage(ruleId ? t('Updated alert rule') : t('Created alert rule'));
  726. if (onSubmitSuccess) {
  727. onSubmitSuccess(data, model);
  728. }
  729. }
  730. } catch (err) {
  731. IndicatorStore.remove(loadingIndicator);
  732. this.setState({loading: false});
  733. const errors = err?.responseJSON
  734. ? Array.isArray(err?.responseJSON)
  735. ? err?.responseJSON
  736. : Object.values(err?.responseJSON)
  737. : [];
  738. let apiErrors = '';
  739. if (typeof errors[0] === 'object' && !Array.isArray(errors[0])) {
  740. // NOTE: this occurs if we get a TimeoutError when attempting to hit the Seer API
  741. apiErrors = ': ' + errors[0].message;
  742. } else {
  743. apiErrors = errors.length > 0 ? `: ${errors.join(', ')}` : '';
  744. }
  745. this.handleRuleSaveFailure(t('Unable to save alert%s', apiErrors));
  746. }
  747. });
  748. };
  749. /**
  750. * Callback for when triggers change
  751. *
  752. * Re-validate triggers on every change and reset indicators when no errors
  753. */
  754. handleChangeTriggers = (triggers: Trigger[], triggerIndex?: number) => {
  755. this.setState(state => {
  756. let triggerErrors = state.triggerErrors;
  757. const newTriggerErrors = this.validateTriggers(
  758. triggers,
  759. state.thresholdType,
  760. state.resolveThreshold,
  761. triggerIndex
  762. );
  763. triggerErrors = newTriggerErrors;
  764. if (Array.from(newTriggerErrors).length === 0) {
  765. clearIndicators();
  766. }
  767. return {
  768. triggers,
  769. triggerErrors,
  770. triggersHaveChanged: true,
  771. chartError: false,
  772. chartErrorMessage: undefined,
  773. };
  774. });
  775. };
  776. handleSensitivityChange = (sensitivity: AlertRuleSensitivity) => {
  777. this.setState({sensitivity}, () => this.fetchAnomalies());
  778. };
  779. handleThresholdTypeChange = (thresholdType: AlertRuleThresholdType) => {
  780. const {triggers} = this.state;
  781. const triggerErrors = this.validateTriggers(triggers, thresholdType);
  782. this.setState(
  783. state => ({
  784. thresholdType,
  785. triggerErrors: new Map([...triggerErrors, ...state.triggerErrors]),
  786. }),
  787. () => this.fetchAnomalies()
  788. );
  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({confidence});
  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. confidence,
  1027. } = this.state;
  1028. if (chartError) {
  1029. return (
  1030. <ErrorChart
  1031. style={{marginTop: 0}}
  1032. errorMessage={`${chartErrorMessage}`}
  1033. isAllowIndexed
  1034. isQueryValid
  1035. />
  1036. );
  1037. }
  1038. const isOnDemand = isOnDemandMetricAlert(dataset, aggregate, query);
  1039. let formattedAggregate = aggregate;
  1040. if (alertType === 'custom_metrics') {
  1041. formattedAggregate = formatMRIField(aggregate);
  1042. }
  1043. const func = parseFunction(aggregate);
  1044. if (func && alertType === 'eap_metrics') {
  1045. formattedAggregate = prettifyParsedFunction(func);
  1046. }
  1047. const chartProps: ComponentProps<typeof TriggersChart> = {
  1048. organization,
  1049. projects: [project],
  1050. triggers,
  1051. anomalies: comparisonType === AlertRuleComparisonType.DYNAMIC ? anomalies : [],
  1052. location,
  1053. query: this.chartQuery,
  1054. aggregate,
  1055. formattedAggregate,
  1056. dataset,
  1057. newAlertOrQuery: !ruleId || query !== rule.query,
  1058. timeWindow,
  1059. environment,
  1060. resolveThreshold,
  1061. thresholdType,
  1062. comparisonDelta,
  1063. comparisonType,
  1064. isQueryValid,
  1065. isOnDemandMetricAlert: isOnDemand,
  1066. showTotalCount:
  1067. !['custom_metrics', 'span_metrics'].includes(alertType) && !isOnDemand,
  1068. onDataLoaded: this.handleTimeSeriesDataFetched,
  1069. onConfidenceDataLoaded: this.handleConfidenceTimeSeriesDataFetched,
  1070. includeHistorical: comparisonType === AlertRuleComparisonType.DYNAMIC,
  1071. onHistoricalDataLoaded: this.handleHistoricalTimeSeriesDataFetched,
  1072. includeConfidence: alertType === 'eap_metrics',
  1073. confidence,
  1074. };
  1075. let formattedQuery = `event.type:${eventTypes?.join(',')}`;
  1076. if (alertType === 'custom_metrics' || alertType === 'eap_metrics') {
  1077. formattedQuery = '';
  1078. }
  1079. const wizardBuilderChart = (
  1080. <TriggersChart
  1081. {...chartProps}
  1082. header={
  1083. <ChartHeader>
  1084. <AlertName>{AlertWizardAlertNames[alertType]}</AlertName>
  1085. {!isCrashFreeAlert(dataset) && (
  1086. <AlertInfo>
  1087. <StyledCircleIndicator size={8} />
  1088. <Aggregate>{formattedAggregate}</Aggregate>
  1089. {formattedQuery}
  1090. </AlertInfo>
  1091. )}
  1092. </ChartHeader>
  1093. }
  1094. />
  1095. );
  1096. return wizardBuilderChart;
  1097. }
  1098. renderBody() {
  1099. const {
  1100. organization,
  1101. ruleId,
  1102. rule,
  1103. onSubmitSuccess,
  1104. router,
  1105. disableProjectSelector,
  1106. eventView,
  1107. location,
  1108. } = this.props;
  1109. const {
  1110. name,
  1111. query,
  1112. project,
  1113. timeWindow,
  1114. triggers,
  1115. aggregate,
  1116. thresholdType,
  1117. comparisonDelta,
  1118. comparisonType,
  1119. resolveThreshold,
  1120. sensitivity,
  1121. loading,
  1122. eventTypes,
  1123. dataset,
  1124. alertType,
  1125. isExtrapolatedChartData,
  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. thresholdType={thresholdType}
  1143. comparisonType={comparisonType}
  1144. currentProject={project.slug}
  1145. organization={organization}
  1146. availableActions={this.state.availableActions}
  1147. onChange={this.handleChangeTriggers}
  1148. onThresholdTypeChange={this.handleThresholdTypeChange}
  1149. onResolveThresholdChange={this.handleResolveThresholdChange}
  1150. onSensitivityChange={this.handleSensitivityChange}
  1151. />
  1152. );
  1153. const ruleNameOwnerForm = (disabled: boolean) => (
  1154. <RuleNameOwnerForm disabled={disabled} project={project} />
  1155. );
  1156. const thresholdTypeForm = (disabled: boolean) => (
  1157. <ThresholdTypeForm
  1158. alertType={alertType}
  1159. comparisonType={comparisonType}
  1160. dataset={dataset}
  1161. disabled={disabled}
  1162. onComparisonDeltaChange={value =>
  1163. this.handleFieldChange('comparisonDelta', value)
  1164. }
  1165. onComparisonTypeChange={this.handleComparisonTypeChange}
  1166. organization={organization}
  1167. comparisonDelta={comparisonDelta}
  1168. />
  1169. );
  1170. const hasAlertWrite = hasEveryAccess(['alerts:write'], {organization, project});
  1171. const formDisabled = loading || !hasAlertWrite;
  1172. const submitDisabled = formDisabled || !this.state.isQueryValid;
  1173. const showErrorMigrationWarning =
  1174. !!ruleId && isMigration && ruleNeedsErrorMigration(rule);
  1175. // Rendering the main form body
  1176. return (
  1177. <Main fullWidth>
  1178. <PermissionAlert access={['alerts:write']} project={project} />
  1179. {isCustomMetricAlert(rule.aggregate) && (
  1180. <MetricsBetaEndAlert organization={organization} />
  1181. )}
  1182. {eventView && <IncompatibleAlertQuery eventView={eventView} />}
  1183. <Form
  1184. model={this.form}
  1185. apiMethod={ruleId ? 'PUT' : 'POST'}
  1186. apiEndpoint={`/organizations/${organization.slug}/alert-rules/${
  1187. ruleId ? `${ruleId}/` : ''
  1188. }`}
  1189. submitDisabled={submitDisabled}
  1190. initialData={{
  1191. name,
  1192. dataset,
  1193. eventTypes,
  1194. aggregate,
  1195. query,
  1196. timeWindow: rule.timeWindow,
  1197. environment: rule.environment || null,
  1198. owner: rule.owner,
  1199. projectId: project.id,
  1200. alertType,
  1201. }}
  1202. saveOnBlur={false}
  1203. onSubmit={this.handleSubmit}
  1204. onSubmitSuccess={onSubmitSuccess}
  1205. onCancel={this.handleCancel}
  1206. onFieldChange={this.handleFieldChange}
  1207. extraButton={
  1208. rule.id ? (
  1209. <Confirm
  1210. disabled={formDisabled}
  1211. message={t(
  1212. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  1213. rule.name
  1214. )}
  1215. header={<h5>{t('Delete Alert Rule?')}</h5>}
  1216. priority="danger"
  1217. confirmText={t('Delete Rule')}
  1218. onConfirm={this.handleDeleteRule}
  1219. >
  1220. <Button priority="danger">{t('Delete Rule')}</Button>
  1221. </Confirm>
  1222. ) : null
  1223. }
  1224. submitLabel={
  1225. isMigration && !triggersHaveChanged ? t('Looks good to me!') : t('Save Rule')
  1226. }
  1227. >
  1228. <List symbol="colored-numeric">
  1229. <RuleConditionsForm
  1230. aggregate={aggregate}
  1231. alertType={alertType}
  1232. allowChangeEventTypes={
  1233. hasCustomMetrics(organization)
  1234. ? dataset === Dataset.ERRORS
  1235. : dataset === Dataset.ERRORS || alertType === 'custom_transactions'
  1236. }
  1237. comparisonDelta={comparisonDelta}
  1238. comparisonType={comparisonType}
  1239. dataset={dataset}
  1240. disableProjectSelector={disableProjectSelector}
  1241. disabled={formDisabled}
  1242. isEditing={Boolean(ruleId)}
  1243. isErrorMigration={showErrorMigrationWarning}
  1244. isExtrapolatedChartData={isExtrapolatedChartData}
  1245. isForLlmMetric={[
  1246. 'sum(ai.total_tokens.used)',
  1247. 'sum(ai.total_cost)',
  1248. ].includes(aggregate)}
  1249. isTransactionMigration={isMigration && !showErrorMigrationWarning}
  1250. onComparisonDeltaChange={value =>
  1251. this.handleFieldChange('comparisonDelta', value)
  1252. }
  1253. onFilterSearch={this.handleFilterUpdate}
  1254. onTimeWindowChange={value => this.handleFieldChange('timeWindow', value)}
  1255. organization={organization}
  1256. project={project}
  1257. router={router}
  1258. thresholdChart={wizardBuilderChart}
  1259. timeWindow={timeWindow}
  1260. />
  1261. <AlertListItem>{t('Set thresholds')}</AlertListItem>
  1262. {thresholdTypeForm(formDisabled)}
  1263. {showErrorMigrationWarning && (
  1264. <Alert type="warning" showIcon>
  1265. {tct(
  1266. "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.",
  1267. {
  1268. code: <code />,
  1269. }
  1270. )}
  1271. </Alert>
  1272. )}
  1273. {triggerForm(formDisabled)}
  1274. {ruleNameOwnerForm(formDisabled)}
  1275. </List>
  1276. </Form>
  1277. </Main>
  1278. );
  1279. }
  1280. }
  1281. function formatStatsToHistoricalDataset(
  1282. data: EventsStats | MultiSeriesEventsStats | null
  1283. ): Array<[number, {count: number}]> {
  1284. return Array.isArray(data?.data)
  1285. ? data.data.flatMap(([timestamp, entries]) =>
  1286. entries.map(entry => [timestamp, entry] as [number, {count: number}])
  1287. ) ?? []
  1288. : [];
  1289. }
  1290. const Main = styled(Layout.Main)`
  1291. max-width: 1000px;
  1292. `;
  1293. const AlertListItem = styled(ListItem)`
  1294. margin: ${space(2)} 0 ${space(1)} 0;
  1295. font-size: ${p => p.theme.fontSizeExtraLarge};
  1296. margin-top: 0;
  1297. `;
  1298. const ChartHeader = styled('div')`
  1299. padding: ${space(2)} ${space(3)} 0 ${space(3)};
  1300. margin-bottom: -${space(1.5)};
  1301. `;
  1302. const AlertName = styled(HeaderTitleLegend)`
  1303. position: relative;
  1304. `;
  1305. const AlertInfo = styled('div')`
  1306. font-size: ${p => p.theme.fontSizeSmall};
  1307. font-family: ${p => p.theme.text.family};
  1308. font-weight: ${p => p.theme.fontWeightNormal};
  1309. color: ${p => p.theme.textColor};
  1310. `;
  1311. const StyledCircleIndicator = styled(CircleIndicator)`
  1312. background: ${p => p.theme.formText};
  1313. height: ${space(1)};
  1314. margin-right: ${space(0.5)};
  1315. `;
  1316. const Aggregate = styled('span')`
  1317. margin-right: ${space(1)};
  1318. `;
  1319. export default withProjects(RuleFormContainer);