Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Alert Summaries] [BE] Move “Notify When” and throttle from rule to action #144130

Merged
merged 33 commits into from
Nov 16, 2022
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
52d3433
Add frequency props to actions and validate them on edit/create
Zacqary Oct 27, 2022
d077ea1
Nullify undefined throttle
Zacqary Oct 27, 2022
378d4e8
Update schema to allow for frequency param on actions
Zacqary Oct 27, 2022
11cd1d3
[CI] Auto-commit changed files from 'node scripts/precommit_hook.js -…
kibanamachine Oct 27, 2022
4889023
Commit missing file
Zacqary Oct 28, 2022
1a84f27
Merge remote-tracking branch 'upstream/main' into 143368-notify-migra…
Zacqary Oct 28, 2022
4349c73
Fix types
Zacqary Oct 28, 2022
1c869ab
Merge branch '143368-notify-migration' of https://github.com/Zacqary/…
Zacqary Oct 28, 2022
ef43549
[CI] Auto-commit changed files from 'node scripts/eslint --no-cache -…
kibanamachine Oct 28, 2022
cb3f976
Fix types
Zacqary Oct 31, 2022
77711c2
Fix jest
Zacqary Oct 31, 2022
3d23b1c
Merge branch '143368-notify-migration' of https://github.com/Zacqary/…
Zacqary Oct 31, 2022
2abc7ae
Fix validating global freq params
Zacqary Oct 31, 2022
66810ae
Add tests for create and edit
Zacqary Oct 31, 2022
adf815f
Merge remote-tracking branch 'upstream/main' into 143368-notify-migra…
Zacqary Nov 1, 2022
20d4983
Reset legacy api
Zacqary Nov 2, 2022
24fe88c
Make notify and throttle optional in route schemas
Zacqary Nov 2, 2022
b35150b
Merge remote-tracking branch 'upstream/main' into 143368-notify-migra…
Zacqary Nov 3, 2022
bed44bc
Fix tests
Zacqary Nov 3, 2022
3b12f0f
Split missing frequency test cases
Zacqary Nov 4, 2022
b2bebdf
Handle xor undefined global frequency params
Zacqary Nov 7, 2022
e6b1843
Merge remote-tracking branch 'upstream/main' into 143368-notify-migra…
Zacqary Nov 7, 2022
11e16a5
Fix typecheck
Zacqary Nov 7, 2022
dec2b1a
Merge remote-tracking branch 'upstream/main' into 143368-notify-migra…
Zacqary Nov 8, 2022
bed5753
Refactor global freq param validation and clarify error messages
Zacqary Nov 9, 2022
26df5b5
Update jest snapshots
Zacqary Nov 9, 2022
cda3467
Merge remote-tracking branch 'upstream/main' into 143368-notify-migra…
Zacqary Nov 15, 2022
023cb65
Fix bad merge
Zacqary Nov 15, 2022
7a517e0
Merge remote-tracking branch 'upstream/main' into 143368-notify-migra…
Zacqary Nov 15, 2022
36d0843
Remove extraneous file
Zacqary Nov 15, 2022
da42cd2
Merge remote-tracking branch 'upstream/main' into 143368-notify-migra…
Zacqary Nov 16, 2022
4287aeb
Merge branch 'main' into 143368-notify-migration
kibanamachine Nov 16, 2022
4cf5498
Merge branch 'main' into 143368-notify-migration
kibanamachine Nov 16, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion x-pack/plugins/alerting/common/alert_summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface AlertSummary {
ruleTypeId: string;
consumer: string;
muteAll: boolean;
throttle: string | null;
throttle?: string | null;
enabled: boolean;
statusStartDate: string;
statusEndDate: string;
Expand Down
9 changes: 7 additions & 2 deletions x-pack/plugins/alerting/common/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ export interface RuleAction {
id: string;
actionTypeId: string;
params: RuleActionParams;
frequency?: {
summary: boolean;
notifyWhen: RuleNotifyWhenType;
throttle: string | null;
};
}

export interface RuleAggregations {
Expand Down Expand Up @@ -107,9 +112,9 @@ export interface Rule<Params extends RuleTypeParams = never> {
updatedAt: Date;
apiKey: string | null;
apiKeyOwner: string | null;
throttle: string | null;
throttle?: string | null;
muteAll: boolean;
notifyWhen: RuleNotifyWhenType | null;
notifyWhen?: RuleNotifyWhenType | null;
mutedInstanceIds: string[];
executionStatus: RuleExecutionStatus;
monitoring?: RuleMonitoring;
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/alerting/common/rule_notify_when_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

const RuleNotifyWhenTypeValues = [
export const RuleNotifyWhenTypeValues = [
'onActionGroupChange',
'onActiveAlert',
'onThrottleInterval',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function alertSummaryFromEventLog(params: AlertSummaryFromEventLogParams)
statusEndDate: dateEnd,
status: 'OK',
muteAll: rule.muteAll,
throttle: rule.throttle,
throttle: rule.throttle ?? null,
enabled: rule.enabled,
lastRun: undefined,
errorMessages: [],
Expand Down
24 changes: 24 additions & 0 deletions x-pack/plugins/alerting/server/lib/validate_rule_frequency.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like total copy of x-pack/plugins/alerting/server/lib/validate_rule_type_params.ts. With the same variables, types.
Maybe better to reuse it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah looks like I committed this file by mistake

* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import Boom from '@hapi/boom';
import { RuleTypeParams, RuleTypeParamsValidator } from '../types';

export function validateRuleTypeParams<Params extends RuleTypeParams>(
params: Record<string, unknown>,
validator?: RuleTypeParamsValidator<Params>
): Params {
if (!validator) {
return params as Params;
}

try {
return validator.validate(params);
} catch (err) {
throw Boom.badRequest(`params invalid: ${err.message}`);
}
}
13 changes: 5 additions & 8 deletions x-pack/plugins/alerting/server/routes/create_rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ import { CreateOptions } from '../rules_client';
import {
RewriteRequestCase,
RewriteResponseCase,
rewriteActions,
handleDisabledApiKeysError,
verifyAccessAndContext,
countUsageOfPredefinedIds,
actionsSchema,
} from './lib';
import {
SanitizedRule,
Expand All @@ -35,14 +37,7 @@ export const bodySchema = schema.object({
schedule: schema.object({
interval: schema.string({ validate: validateDurationSchema }),
}),
actions: schema.arrayOf(
schema.object({
group: schema.string(),
id: schema.string(),
params: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }),
}),
{ defaultValue: [] }
),
actions: actionsSchema,
notify_when: schema.string({ validate: validateNotifyWhenType }),
Zacqary marked this conversation as resolved.
Show resolved Hide resolved
});

Expand All @@ -55,6 +50,7 @@ const rewriteBodyReq: RewriteRequestCase<CreateOptions<RuleTypeParams>['data']>
alertTypeId,
notifyWhen,
});

const rewriteBodyRes: RewriteResponseCase<SanitizedRule<RuleTypeParams>> = ({
actions,
alertTypeId,
Expand Down Expand Up @@ -127,6 +123,7 @@ export const createRuleRoute = ({ router, licenseState, usageCounter }: RouteOpt
await rulesClient.create<RuleTypeParams>({
data: rewriteBodyReq({
...rule,
actions: rewriteActions(rule.actions),
notify_when: rule.notify_when as RuleNotifyWhenType,
}),
options: { id: params?.id },
Expand Down
14 changes: 3 additions & 11 deletions x-pack/plugins/alerting/server/routes/legacy/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
} from '../../types';
import { RuleTypeDisabledError } from '../../lib/errors/rule_type_disabled';
import { RouteOptions } from '..';
import { countUsageOfPredefinedIds } from '../lib';
import { countUsageOfPredefinedIds, actionsSchema, rewriteActions } from '../lib';
import { trackLegacyRouteUsage } from '../../lib/track_legacy_route_usage';

export const bodySchema = schema.object({
Expand All @@ -32,15 +32,7 @@ export const bodySchema = schema.object({
schedule: schema.object({
interval: schema.string({ validate: validateDurationSchema }),
}),
actions: schema.arrayOf(
schema.object({
group: schema.string(),
id: schema.string(),
actionTypeId: schema.maybe(schema.string()),
params: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }),
}),
{ defaultValue: [] }
),
actions: actionsSchema,
Zacqary marked this conversation as resolved.
Show resolved Hide resolved
notifyWhen: schema.nullable(schema.string({ validate: validateNotifyWhenType })),
});

Expand Down Expand Up @@ -79,7 +71,7 @@ export const createAlertRoute = ({ router, licenseState, usageCounter }: RouteOp

try {
const alertRes: SanitizedRule<RuleTypeParams> = await rulesClient.create<RuleTypeParams>({
data: { ...alert, notifyWhen },
data: { ...alert, notifyWhen, actions: rewriteActions(alert?.actions) },
options: { id: params?.id },
});
return res.ok({
Expand Down
13 changes: 3 additions & 10 deletions x-pack/plugins/alerting/server/routes/legacy/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { validateDurationSchema } from '../../lib';
import { handleDisabledApiKeysError } from '../lib/error_handler';
import { RuleTypeDisabledError } from '../../lib/errors/rule_type_disabled';
import { trackLegacyRouteUsage } from '../../lib/track_legacy_route_usage';
import { actionsSchema, rewriteActions } from '../lib';
import {
RuleNotifyWhenType,
LEGACY_BASE_ALERT_API_PATH,
Expand All @@ -32,15 +33,7 @@ const bodySchema = schema.object({
}),
throttle: schema.nullable(schema.string({ validate: validateDurationSchema })),
params: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }),
actions: schema.arrayOf(
schema.object({
group: schema.string(),
id: schema.string(),
params: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }),
actionTypeId: schema.maybe(schema.string()),
}),
{ defaultValue: [] }
),
actions: actionsSchema,
Zacqary marked this conversation as resolved.
Show resolved Hide resolved
notifyWhen: schema.nullable(schema.string({ validate: validateNotifyWhenType })),
});

Expand Down Expand Up @@ -72,7 +65,7 @@ export const updateAlertRoute = (
id,
data: {
name,
actions,
actions: rewriteActions(actions),
params,
schedule,
tags,
Expand Down
29 changes: 29 additions & 0 deletions x-pack/plugins/alerting/server/routes/lib/actions_schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { schema } from '@kbn/config-schema';
import { validateDurationSchema } from '../../lib';

export const actionsSchema = schema.arrayOf(
schema.object({
group: schema.string(),
id: schema.string(),
params: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }),
frequency: schema.maybe(
schema.object({
summary: schema.boolean(),
notify_when: schema.oneOf([
schema.literal('onActionGroupChange'),
schema.literal('onActiveAlert'),
schema.literal('onThrottleInterval'),
]),
throttle: schema.nullable(schema.string({ validate: validateDurationSchema })),
})
),
}),
{ defaultValue: [] }
);
2 changes: 2 additions & 0 deletions x-pack/plugins/alerting/server/routes/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ export type {
export { verifyAccessAndContext } from './verify_access_and_context';
export { countUsageOfPredefinedIds } from './count_usage_of_predefined_ids';
export { rewriteRule } from './rewrite_rule';
export { rewriteActions } from './rewrite_actions';
export { actionsSchema } from './actions_schema';
export { rewriteNamespaces } from './rewrite_namespaces';
32 changes: 32 additions & 0 deletions x-pack/plugins/alerting/server/routes/lib/rewrite_actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { CamelToSnake, RewriteRequestCase } from './rewrite_request_case';
import { RuleAction } from '../../types';

type ReqRuleAction = Omit<RuleAction, 'actionTypeId' | 'frequency'> & {
frequency?: {
[K in keyof NonNullable<RuleAction['frequency']> as CamelToSnake<K>]: NonNullable<
RuleAction['frequency']
>[K];
};
};
export const rewriteActions: (
actions?: ReqRuleAction[]
) => Array<Omit<RuleAction, 'actionTypeId'>> = (actions) => {
const rewriteFrequency: RewriteRequestCase<NonNullable<RuleAction['frequency']>> = ({
notify_when: notifyWhen,
...rest
}) => ({ ...rest, notifyWhen });
if (!actions) return [];
return actions.map(
(action) =>
({
...action,
...(action.frequency ? { frequency: rewriteFrequency(action.frequency) } : {}),
} as RuleAction)
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export type RewriteResponseCase<T> = (
*
* For more details see this PR comment: https://github.com/microsoft/TypeScript/pull/40336#issuecomment-686723087
*/
type CamelToSnake<T extends string> = string extends T
export type CamelToSnake<T extends string> = string extends T
? string
: T extends `${infer C0}${infer C1}${infer R}`
? `${C0 extends Uppercase<C0> ? '_' : ''}${Lowercase<C0>}${C1 extends Uppercase<C1>
Expand Down
10 changes: 9 additions & 1 deletion x-pack/plugins/alerting/server/routes/lib/rewrite_rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,18 @@ export const rewriteRule = ({
last_execution_date: executionStatus.lastExecutionDate,
last_duration: executionStatus.lastDuration,
},
actions: actions.map(({ group, id, actionTypeId, params }) => ({
actions: actions.map(({ group, id, actionTypeId, params, frequency }) => ({
group,
id,
params,
connector_type_id: actionTypeId,
...(frequency
? {
frequency: {
...frequency,
notify_when: frequency.notifyWhen,
},
}
: {}),
})),
});
12 changes: 4 additions & 8 deletions x-pack/plugins/alerting/server/routes/update_rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
RewriteResponseCase,
RewriteRequestCase,
handleDisabledApiKeysError,
rewriteActions,
actionsSchema,
} from './lib';
import {
RuleTypeParams,
Expand All @@ -36,14 +38,7 @@ const bodySchema = schema.object({
}),
throttle: schema.nullable(schema.string({ validate: validateDurationSchema })),
params: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }),
actions: schema.arrayOf(
schema.object({
group: schema.string(),
id: schema.string(),
params: schema.recordOf(schema.string(), schema.any(), { defaultValue: {} }),
}),
{ defaultValue: [] }
),
actions: actionsSchema,
notify_when: schema.string({ validate: validateNotifyWhenType }),
});

Expand Down Expand Up @@ -132,6 +127,7 @@ export const updateRuleRoute = (
id,
data: {
...rule,
actions: rewriteActions(rule.actions),
notify_when: rule.notify_when as RuleNotifyWhenType,
},
})
Expand Down
Loading