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