ruleForm.tsx 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  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. // Used to hide specific fields like actions while migrating metric alert rules.
  990. // Currently used to help people add `is:unresolved` to their metric alert query.
  991. const isMigration = location?.query?.migration === '1';
  992. const triggerForm = (disabled: boolean) => (
  993. <Triggers
  994. disabled={disabled}
  995. projects={[project]}
  996. errors={this.state.triggerErrors}
  997. triggers={triggers}
  998. aggregate={aggregate}
  999. isMigration={isMigration}
  1000. resolveThreshold={resolveThreshold}
  1001. thresholdPeriod={thresholdPeriod}
  1002. thresholdType={thresholdType}
  1003. comparisonType={comparisonType}
  1004. currentProject={project.slug}
  1005. organization={organization}
  1006. availableActions={this.state.availableActions}
  1007. onChange={this.handleChangeTriggers}
  1008. onThresholdTypeChange={this.handleThresholdTypeChange}
  1009. onThresholdPeriodChange={this.handleThresholdPeriodChange}
  1010. onResolveThresholdChange={this.handleResolveThresholdChange}
  1011. />
  1012. );
  1013. const ruleNameOwnerForm = (disabled: boolean) => (
  1014. <RuleNameOwnerForm disabled={disabled} project={project} />
  1015. );
  1016. const thresholdTypeForm = (disabled: boolean) => (
  1017. <ThresholdTypeForm
  1018. comparisonType={comparisonType}
  1019. dataset={dataset}
  1020. disabled={disabled}
  1021. onComparisonDeltaChange={value =>
  1022. this.handleFieldChange('comparisonDelta', value)
  1023. }
  1024. onComparisonTypeChange={this.handleComparisonTypeChange}
  1025. organization={organization}
  1026. comparisonDelta={comparisonDelta}
  1027. />
  1028. );
  1029. const hasAlertWrite = hasEveryAccess(['alerts:write'], {organization, project});
  1030. const formDisabled = loading || !hasAlertWrite;
  1031. const submitDisabled = formDisabled || !this.state.isQueryValid;
  1032. const showErrorMigrationWarning =
  1033. !!ruleId && isMigration && ruleNeedsErrorMigration(rule);
  1034. // Rendering the main form body
  1035. return (
  1036. <Main fullWidth>
  1037. <PermissionAlert access={['alerts:write']} project={project} />
  1038. {eventView && <IncompatibleAlertQuery eventView={eventView} />}
  1039. <Form
  1040. model={this.form}
  1041. apiMethod={ruleId ? 'PUT' : 'POST'}
  1042. apiEndpoint={`/organizations/${organization.slug}/alert-rules/${
  1043. ruleId ? `${ruleId}/` : ''
  1044. }`}
  1045. submitDisabled={submitDisabled}
  1046. initialData={{
  1047. name,
  1048. dataset,
  1049. eventTypes,
  1050. aggregate,
  1051. query,
  1052. timeWindow: rule.timeWindow,
  1053. environment: rule.environment || null,
  1054. owner: rule.owner,
  1055. projectId: project.id,
  1056. alertType,
  1057. }}
  1058. saveOnBlur={false}
  1059. onSubmit={this.handleSubmit}
  1060. onSubmitSuccess={onSubmitSuccess}
  1061. onCancel={this.handleCancel}
  1062. onFieldChange={this.handleFieldChange}
  1063. extraButton={
  1064. rule.id ? (
  1065. <Confirm
  1066. disabled={formDisabled}
  1067. message={t(
  1068. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  1069. rule.name
  1070. )}
  1071. header={<h5>{t('Delete Alert Rule?')}</h5>}
  1072. priority="danger"
  1073. confirmText={t('Delete Rule')}
  1074. onConfirm={this.handleDeleteRule}
  1075. >
  1076. <Button priority="danger">{t('Delete Rule')}</Button>
  1077. </Confirm>
  1078. ) : null
  1079. }
  1080. submitLabel={
  1081. isMigration && !triggersHaveChanged ? t('Looks good to me!') : t('Save Rule')
  1082. }
  1083. >
  1084. <List symbol="colored-numeric">
  1085. <RuleConditionsForm
  1086. activationCondition={activationCondition}
  1087. aggregate={aggregate}
  1088. alertType={alertType}
  1089. allowChangeEventTypes={
  1090. hasCustomMetrics(organization)
  1091. ? dataset === Dataset.ERRORS
  1092. : dataset === Dataset.ERRORS || alertType === 'custom_transactions'
  1093. }
  1094. comparisonDelta={comparisonDelta}
  1095. comparisonType={comparisonType}
  1096. dataset={dataset}
  1097. disableProjectSelector={disableProjectSelector}
  1098. disabled={formDisabled}
  1099. isEditing={Boolean(ruleId)}
  1100. isErrorMigration={showErrorMigrationWarning}
  1101. isExtrapolatedChartData={isExtrapolatedChartData}
  1102. isForSpanMetric={aggregate.includes(':spans/')}
  1103. isTransactionMigration={isMigration && !showErrorMigrationWarning}
  1104. monitorType={monitorType}
  1105. onComparisonDeltaChange={value =>
  1106. this.handleFieldChange('comparisonDelta', value)
  1107. }
  1108. onFilterSearch={this.handleFilterUpdate}
  1109. onMonitorTypeSelect={this.handleMonitorTypeSelect}
  1110. onTimeWindowChange={value => this.handleFieldChange('timeWindow', value)}
  1111. organization={organization}
  1112. project={project}
  1113. router={router}
  1114. thresholdChart={wizardBuilderChart}
  1115. timeWindow={timeWindow}
  1116. />
  1117. <AlertListItem>{t('Set thresholds')}</AlertListItem>
  1118. {thresholdTypeForm(formDisabled)}
  1119. {showErrorMigrationWarning && (
  1120. <Alert type="warning" showIcon>
  1121. {tct(
  1122. "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.",
  1123. {
  1124. code: <code />,
  1125. }
  1126. )}
  1127. </Alert>
  1128. )}
  1129. {triggerForm(formDisabled)}
  1130. {ruleNameOwnerForm(formDisabled)}
  1131. </List>
  1132. </Form>
  1133. </Main>
  1134. );
  1135. }
  1136. }
  1137. const Main = styled(Layout.Main)`
  1138. max-width: 1000px;
  1139. `;
  1140. const AlertListItem = styled(ListItem)`
  1141. margin: ${space(2)} 0 ${space(1)} 0;
  1142. font-size: ${p => p.theme.fontSizeExtraLarge};
  1143. margin-top: 0;
  1144. `;
  1145. const ChartHeader = styled('div')`
  1146. padding: ${space(2)} ${space(3)} 0 ${space(3)};
  1147. margin-bottom: -${space(1.5)};
  1148. `;
  1149. const AlertName = styled(HeaderTitleLegend)`
  1150. position: relative;
  1151. `;
  1152. const AlertInfo = styled('div')`
  1153. font-size: ${p => p.theme.fontSizeSmall};
  1154. font-family: ${p => p.theme.text.family};
  1155. font-weight: ${p => p.theme.fontWeightNormal};
  1156. color: ${p => p.theme.textColor};
  1157. `;
  1158. const StyledCircleIndicator = styled(CircleIndicator)`
  1159. background: ${p => p.theme.formText};
  1160. height: ${space(1)};
  1161. margin-right: ${space(0.5)};
  1162. `;
  1163. const Aggregate = styled('span')`
  1164. margin-right: ${space(1)};
  1165. `;
  1166. export default withProjects(RuleFormContainer);