ruleForm.tsx 41 KB

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