,
+ });
+ return;
+ }
+ setFormValue({
+ ...formValue,
+ [property]: value,
+ });
+ },
+ [formValue]
+ );
+
+ const onRuleTypeChange = useCallback((newRuleTypeId: string) => {
+ setRuleTypeId(newRuleTypeId);
+ setFormValue(DEFAULT_FORM_VALUES(newRuleTypeId));
+ }, []);
+
+ const { docLinks, http, toasts } = useKibana<{
+ docLinks: DocLinksStart;
+ http: HttpStart;
+ toasts: ToastsStart;
+ }>().services;
+
+ const {
+ ruleTypesState: { data: ruleTypeIndex, isLoading },
+ } = useLoadRuleTypesQuery({
+ http,
+ toasts,
+ });
+
+ const ruleTypes = useMemo(() => [...ruleTypeIndex.values()], [ruleTypeIndex]);
+ const selectedRuleType = ruleTypes.find((ruleType) => ruleType.id === ruleTypeId);
+ const selectedRuleTypeModel = triggersActionsUi.ruleTypeRegistry.get(ruleTypeId);
+
+ const errors = useMemo(() => {
+ if (!selectedRuleType || !selectedRuleTypeModel) {
+ return {};
+ }
+
+ return getRuleErrors({
+ rule: formValue,
+ minimumScheduleInterval: {
+ value: '1m',
+ enforce: true,
+ },
+ ruleTypeModel: selectedRuleTypeModel,
+ }).ruleErrors;
+ }, [formValue, selectedRuleType, selectedRuleTypeModel]);
+
+ if (isLoading || !selectedRuleType) {
+ return ;
+ }
+
+ return (
+ <>
+
+
+ Form State
+
+ {JSON.stringify(formValue, null, 2)}
+
+
+
+ Switch Rule Types:
+
+ onRuleTypeChange('.es-query')}>Es Query
+ onRuleTypeChange('metrics.alert.threshold')}>
+ Metric Threshold
+
+ onRuleTypeChange('observability.rules.custom_threshold')}>
+ Custom Threshold
+
+
+
+ >
+ );
+};
diff --git a/x-pack/examples/triggers_actions_ui_example/public/components/sidebar.tsx b/x-pack/examples/triggers_actions_ui_example/public/components/sidebar.tsx
index 90a44353c646e..caaad858b4cc4 100644
--- a/x-pack/examples/triggers_actions_ui_example/public/components/sidebar.tsx
+++ b/x-pack/examples/triggers_actions_ui_example/public/components/sidebar.tsx
@@ -76,6 +76,17 @@ export const Sidebar = () => {
},
],
},
+ {
+ name: 'Rule Form Components',
+ id: 'rule-form-components',
+ items: [
+ {
+ id: 'rule-definition',
+ name: 'Rule Definition',
+ onClick: () => history.push('/rule_definition'),
+ },
+ ],
+ },
]}
/>
diff --git a/x-pack/examples/triggers_actions_ui_example/public/plugin.tsx b/x-pack/examples/triggers_actions_ui_example/public/plugin.tsx
index 5077795b620f7..ca932cb81bd6c 100644
--- a/x-pack/examples/triggers_actions_ui_example/public/plugin.tsx
+++ b/x-pack/examples/triggers_actions_ui_example/public/plugin.tsx
@@ -8,7 +8,11 @@
import React from 'react';
import { Plugin, CoreSetup, AppMountParameters, CoreStart } from '@kbn/core/public';
import { PluginSetupContract as AlertingSetup } from '@kbn/alerting-plugin/public';
-import { DataPublicPluginStart } from '@kbn/data-plugin/public';
+import type { ChartsPluginSetup } from '@kbn/charts-plugin/public';
+import type { DataPublicPluginStart } from '@kbn/data-plugin/public';
+import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public';
+import type { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public';
+import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public';
import { DeveloperExamplesSetup } from '@kbn/developer-examples-plugin/public';
import { get } from 'lodash';
import {
@@ -35,6 +39,10 @@ export interface TriggersActionsUiExamplePublicStartDeps {
alerting: AlertingSetup;
triggersActionsUi: TriggersAndActionsUIPublicPluginStart;
data: DataPublicPluginStart;
+ charts: ChartsPluginSetup;
+ dataViews: DataViewsPublicPluginStart;
+ dataViewsEditor: DataViewEditorStart;
+ unifiedSearch: UnifiedSearchPublicPluginStart;
}
export class TriggersActionsUiExamplePlugin
diff --git a/x-pack/examples/triggers_actions_ui_example/tsconfig.json b/x-pack/examples/triggers_actions_ui_example/tsconfig.json
index 193feffd2d5ee..0bb226e46c8a9 100644
--- a/x-pack/examples/triggers_actions_ui_example/tsconfig.json
+++ b/x-pack/examples/triggers_actions_ui_example/tsconfig.json
@@ -26,6 +26,13 @@
"@kbn/i18n",
"@kbn/actions-plugin",
"@kbn/config-schema",
+ "@kbn/charts-plugin",
+ "@kbn/data-views-plugin",
+ "@kbn/unified-search-plugin",
+ "@kbn/alerts-ui-shared",
+ "@kbn/data-view-editor-plugin",
+ "@kbn/core-http-browser",
+ "@kbn/core-notifications-browser",
"@kbn/react-kibana-context-render",
]
}
diff --git a/x-pack/plugins/alerting/common/iso_weekdays.ts b/x-pack/plugins/alerting/common/iso_weekdays.ts
index 1277370b0e6fc..15b2b5cb3d492 100644
--- a/x-pack/plugins/alerting/common/iso_weekdays.ts
+++ b/x-pack/plugins/alerting/common/iso_weekdays.ts
@@ -5,5 +5,5 @@
* 2.0.
*/
-export type IsoWeekday = 1 | 2 | 3 | 4 | 5 | 6 | 7;
-export const ISO_WEEKDAYS: IsoWeekday[] = [1, 2, 3, 4, 5, 6, 7];
+export type { IsoWeekday } from '@kbn/alerting-types';
+export { ISO_WEEKDAYS } from '@kbn/alerting-types';
diff --git a/x-pack/plugins/alerting/common/rrule_type.ts b/x-pack/plugins/alerting/common/rrule_type.ts
index 7d250a0302317..8b65ec192d316 100644
--- a/x-pack/plugins/alerting/common/rrule_type.ts
+++ b/x-pack/plugins/alerting/common/rrule_type.ts
@@ -5,14 +5,4 @@
* 2.0.
*/
-import type { WeekdayStr, Options } from '@kbn/rrule';
-
-export type RRuleParams = Partial & Pick;
-
-// An iCal RRULE to define a recurrence schedule, see https://github.com/jakubroztocil/rrule for the spec
-export type RRuleRecord = Omit & {
- dtstart: string;
- byweekday?: Array;
- wkst?: WeekdayStr;
- until?: string;
-};
+export type { RRuleParams, RRuleRecord } from '@kbn/alerting-types';
diff --git a/x-pack/plugins/alerting/common/rule.ts b/x-pack/plugins/alerting/common/rule.ts
index bc6c60fd75a53..7d28c5fce8b54 100644
--- a/x-pack/plugins/alerting/common/rule.ts
+++ b/x-pack/plugins/alerting/common/rule.ts
@@ -10,206 +10,71 @@ import type {
SavedObjectAttributes,
SavedObjectsResolveResponse,
} from '@kbn/core/server';
-import type { Filter } from '@kbn/es-query';
-import { IsoWeekday } from './iso_weekdays';
-import { RuleNotifyWhenType } from './rule_notify_when_type';
-import { RuleSnooze } from './rule_snooze_type';
-export type { ActionVariable } from '@kbn/alerting-types';
+import type {
+ SanitizedRule,
+ RuleLastRunOutcomes,
+ AlertsFilterTimeframe,
+ RuleAction,
+ RuleSystemAction,
+ RuleTypeParams,
+} from '@kbn/alerting-types';
+
+export type {
+ ActionVariable,
+ Rule,
+ SanitizedRule,
+ RuleTypeParams,
+ RuleActionParams,
+ IntervalSchedule,
+ RuleActionFrequency,
+ AlertsFilterTimeframe,
+ AlertsFilter,
+ RuleAction,
+ RuleSystemAction,
+ MappedParamsProperties,
+ MappedParams,
+ RuleExecutionStatuses,
+ RuleLastRunOutcomes,
+ RuleExecutionStatus,
+ RuleMonitoringHistory,
+ RuleMonitoringCalculatedMetrics,
+ RuleMonitoringLastRun,
+ RuleMonitoring,
+ RuleLastRun,
+ AlertDelay,
+ SanitizedAlertsFilter,
+ SanitizedRuleAction,
+} from '@kbn/alerting-types';
+
+export {
+ RuleExecutionStatusValues,
+ RuleLastRunOutcomeValues,
+ RuleExecutionStatusErrorReasons,
+ RuleExecutionStatusWarningReasons,
+} from '@kbn/alerting-types';
export type RuleTypeState = Record;
-export type RuleTypeParams = Record;
export type RuleTypeMetaData = Record;
// rule type defined alert fields to persist in alerts index
export type RuleAlertData = Record;
-export interface IntervalSchedule extends SavedObjectAttributes {
- interval: string;
-}
-
-// for the `typeof ThingValues[number]` types below, become string types that
-// only accept the values in the associated string arrays
-export const RuleExecutionStatusValues = [
- 'ok',
- 'active',
- 'error',
- 'pending',
- 'unknown',
- 'warning',
-] as const;
-export type RuleExecutionStatuses = typeof RuleExecutionStatusValues[number];
-
-export const RuleLastRunOutcomeValues = ['succeeded', 'warning', 'failed'] as const;
-export type RuleLastRunOutcomes = typeof RuleLastRunOutcomeValues[number];
-
export const RuleLastRunOutcomeOrderMap: Record = {
succeeded: 0,
warning: 10,
failed: 20,
};
-export enum RuleExecutionStatusErrorReasons {
- Read = 'read',
- Decrypt = 'decrypt',
- Execute = 'execute',
- Unknown = 'unknown',
- License = 'license',
- Timeout = 'timeout',
- Disabled = 'disabled',
- Validate = 'validate',
-}
-
-export enum RuleExecutionStatusWarningReasons {
- MAX_EXECUTABLE_ACTIONS = 'maxExecutableActions',
- MAX_ALERTS = 'maxAlerts',
- MAX_QUEUED_ACTIONS = 'maxQueuedActions',
-}
-
export type RuleAlertingOutcome = 'failure' | 'success' | 'unknown' | 'warning';
-export interface RuleExecutionStatus {
- status: RuleExecutionStatuses;
- lastExecutionDate: Date;
- lastDuration?: number;
- error?: {
- reason: RuleExecutionStatusErrorReasons;
- message: string;
- };
- warning?: {
- reason: RuleExecutionStatusWarningReasons;
- message: string;
- };
-}
-
-export type RuleActionParams = SavedObjectAttributes;
export type RuleActionParam = SavedObjectAttribute;
-export interface RuleActionFrequency extends SavedObjectAttributes {
- summary: boolean;
- notifyWhen: RuleNotifyWhenType;
- throttle: string | null;
-}
-
-export interface AlertsFilterTimeframe extends SavedObjectAttributes {
- days: IsoWeekday[];
- timezone: string;
- hours: {
- start: string;
- end: string;
- };
-}
-
-export interface AlertsFilter extends SavedObjectAttributes {
- query?: {
- kql: string;
- filters: Filter[];
- dsl?: string; // This fields is generated in the code by using "kql", therefore it's not optional but defined as optional to avoid modifying a lot of files in different plugins
- };
- timeframe?: AlertsFilterTimeframe;
-}
-
export type RuleActionAlertsFilterProperty = AlertsFilterTimeframe | RuleActionParam;
-export interface RuleAction {
- uuid?: string;
- group: string;
- id: string;
- actionTypeId: string;
- params: RuleActionParams;
- frequency?: RuleActionFrequency;
- alertsFilter?: AlertsFilter;
- useAlertDataForTemplate?: boolean;
-}
-
-export interface RuleSystemAction {
- uuid?: string;
- id: string;
- actionTypeId: string;
- params: RuleActionParams;
-}
-
export type RuleActionKey = keyof RuleAction;
export type RuleSystemActionKey = keyof RuleSystemAction;
-export interface RuleLastRun {
- outcome: RuleLastRunOutcomes;
- outcomeOrder?: number;
- warning?: RuleExecutionStatusErrorReasons | RuleExecutionStatusWarningReasons | null;
- outcomeMsg?: string[] | null;
- alertsCount: {
- active?: number | null;
- new?: number | null;
- recovered?: number | null;
- ignored?: number | null;
- };
-}
-
-export interface MappedParamsProperties {
- risk_score?: number;
- severity?: string;
-}
-
-export type MappedParams = SavedObjectAttributes & MappedParamsProperties;
-
-export interface AlertDelay extends SavedObjectAttributes {
- active: number;
-}
-
-export interface Rule {
- id: string;
- enabled: boolean;
- name: string;
- tags: string[];
- alertTypeId: string; // this is persisted in the Rule saved object so we would need a migration to change this to ruleTypeId
- consumer: string;
- schedule: IntervalSchedule;
- actions: RuleAction[];
- systemActions?: RuleSystemAction[];
- params: Params;
- mapped_params?: MappedParams;
- scheduledTaskId?: string | null;
- createdBy: string | null;
- updatedBy: string | null;
- createdAt: Date;
- updatedAt: Date;
- apiKey: string | null;
- apiKeyOwner: string | null;
- apiKeyCreatedByUser?: boolean | null;
- throttle?: string | null;
- muteAll: boolean;
- notifyWhen?: RuleNotifyWhenType | null;
- mutedInstanceIds: string[];
- executionStatus: RuleExecutionStatus;
- monitoring?: RuleMonitoring;
- snoozeSchedule?: RuleSnooze; // Remove ? when this parameter is made available in the public API
- activeSnoozes?: string[];
- isSnoozedUntil?: Date | null;
- lastRun?: RuleLastRun | null;
- nextRun?: Date | null;
- revision: number;
- running?: boolean | null;
- viewInAppRelativeUrl?: string;
- alertDelay?: AlertDelay;
-}
-
-export interface SanitizedAlertsFilter extends AlertsFilter {
- query?: {
- kql: string;
- filters: Filter[];
- };
- timeframe?: AlertsFilterTimeframe;
-}
-
-export type SanitizedRuleAction = Omit & {
- alertsFilter?: SanitizedAlertsFilter;
-};
-
-export type SanitizedRule = Omit<
- Rule,
- 'apiKey' | 'actions'
-> & { actions: SanitizedRuleAction[] };
-
export type ResolvedSanitizedRule = SanitizedRule &
Omit & {
outcome: string;
@@ -262,20 +127,6 @@ export interface AlertsHealth {
};
}
-export interface RuleMonitoringHistory extends SavedObjectAttributes {
- success: boolean;
- timestamp: number;
- duration?: number;
- outcome?: RuleLastRunOutcomes;
-}
-
-export interface RuleMonitoringCalculatedMetrics extends SavedObjectAttributes {
- p50?: number;
- p95?: number;
- p99?: number;
- success_ratio: number;
-}
-
export interface RuleMonitoringLastRunMetrics extends SavedObjectAttributes {
duration?: number;
total_search_duration_ms?: number | null;
@@ -284,16 +135,3 @@ export interface RuleMonitoringLastRunMetrics extends SavedObjectAttributes {
total_alerts_created?: number | null;
gap_duration_s?: number | null;
}
-
-export interface RuleMonitoringLastRun extends SavedObjectAttributes {
- timestamp: string;
- metrics: RuleMonitoringLastRunMetrics;
-}
-
-export interface RuleMonitoring {
- run: {
- history: RuleMonitoringHistory[];
- calculated_metrics: RuleMonitoringCalculatedMetrics;
- last_run: RuleMonitoringLastRun;
- };
-}
diff --git a/x-pack/plugins/alerting/common/rule_notify_when_type.ts b/x-pack/plugins/alerting/common/rule_notify_when_type.ts
index 76182636e9f71..272e458ade9d9 100644
--- a/x-pack/plugins/alerting/common/rule_notify_when_type.ts
+++ b/x-pack/plugins/alerting/common/rule_notify_when_type.ts
@@ -5,18 +5,8 @@
* 2.0.
*/
-export const RuleNotifyWhenTypeValues = [
- 'onActionGroupChange',
- 'onActiveAlert',
- 'onThrottleInterval',
-] as const;
-export type RuleNotifyWhenType = typeof RuleNotifyWhenTypeValues[number];
-
-export enum RuleNotifyWhen {
- CHANGE = 'onActionGroupChange',
- ACTIVE = 'onActiveAlert',
- THROTTLE = 'onThrottleInterval',
-}
+import type { RuleNotifyWhenType } from '@kbn/alerting-types';
+import { RuleNotifyWhenTypeValues } from '@kbn/alerting-types';
export function validateNotifyWhenType(notifyWhen: string) {
if (RuleNotifyWhenTypeValues.includes(notifyWhen as RuleNotifyWhenType)) {
@@ -24,3 +14,6 @@ export function validateNotifyWhenType(notifyWhen: string) {
}
return `string is not a valid RuleNotifyWhenType: ${notifyWhen}`;
}
+
+export type { RuleNotifyWhenType } from '@kbn/alerting-types';
+export { RuleNotifyWhenTypeValues, RuleNotifyWhen } from '@kbn/alerting-types';
diff --git a/x-pack/plugins/alerting/common/rule_snooze_type.ts b/x-pack/plugins/alerting/common/rule_snooze_type.ts
index 17e4d0eabb02a..b3b8b8b030a61 100644
--- a/x-pack/plugins/alerting/common/rule_snooze_type.ts
+++ b/x-pack/plugins/alerting/common/rule_snooze_type.ts
@@ -5,21 +5,4 @@
* 2.0.
*/
-import { RRuleParams } from './rrule_type';
-
-export interface RuleSnoozeSchedule {
- duration: number;
- rRule: RRuleParams;
- // For scheduled/recurring snoozes, `id` uniquely identifies them so that they can be displayed, modified, and deleted individually
- id?: string;
- skipRecurrences?: string[];
-}
-
-// Type signature of has to be repeated here to avoid issues with SavedObject compatibility
-// RuleSnooze = RuleSnoozeSchedule[] throws typescript errors across the whole lib
-export type RuleSnooze = Array<{
- duration: number;
- rRule: RRuleParams;
- id?: string;
- skipRecurrences?: string[];
-}>;
+export type { RuleSnoozeSchedule, RuleSnooze } from '@kbn/alerting-types';