ruleForm.tsx 48 KB

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