From 24e930b2f334a98f07f14aa702416322b74c37db Mon Sep 17 00:00:00 2001 From: Jiawei Wu <74562234+JiaweiWu@users.noreply.github.com> Date: Mon, 2 Dec 2024 14:06:01 -0800 Subject: [PATCH] [Response Ops] Remove ephemeral tasks from action and alerting plugins (#197421) ## Summary Issue: https://github.com/elastic/kibana/issues/151461 Removes all reference to ephemeral tasks in the alerting and actions plugin. As well as unit and E2E tests while maintaining backwards compatibility for `xpack.alerting.maxEphemeralActionsPerAlert` flag. ### Checklist - [x] [Unit or functional tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html) were updated or added to match the most common scenarios --------- Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: Elastic Machine --- docs/settings/alert-action-settings.asciidoc | 6 - .../actions_client/actions_client.mock.ts | 1 - .../actions_client/actions_client.test.ts | 28 - .../server/actions_client/actions_client.ts | 18 - .../actions_client_hooks.test.ts | 2 - .../connector/methods/get_all/get_all.test.ts | 9 - .../methods/list_types/list_types.test.ts | 1 - .../actions/server/create_execute_function.ts | 61 +- .../actions/server/lib/action_executor.ts | 5 - .../server/lib/task_runner_factory.test.ts | 11 - .../actions/server/lib/task_runner_factory.ts | 92 +- x-pack/plugins/actions/server/plugin.ts | 21 +- x-pack/plugins/actions/server/types.ts | 20 +- x-pack/plugins/alerting/server/config.test.ts | 1 - x-pack/plugins/alerting/server/config.ts | 5 +- x-pack/plugins/alerting/server/index.ts | 5 +- x-pack/plugins/alerting/server/plugin.ts | 2 - .../action_scheduler/action_scheduler.test.ts | 2 - .../action_scheduler/action_scheduler.ts | 81 +- .../task_runner/ad_hoc_task_runner.test.ts | 2 - .../server/task_runner/task_runner.test.ts | 1767 ++++++++--------- .../task_runner_alerts_client.test.ts | 2 - .../task_runner/task_runner_cancel.test.ts | 2 - .../task_runner/task_runner_factory.test.ts | 2 - .../alerting/server/task_runner/types.ts | 2 - .../alerting/server/test_utils/index.ts | 1 - .../alerting_api_integration/common/config.ts | 1 - .../tests/alerting/group4/ephemeral.ts | 124 -- .../tests/alerting/group4/index.ts | 1 - 29 files changed, 890 insertions(+), 1385 deletions(-) delete mode 100644 x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/ephemeral.ts diff --git a/docs/settings/alert-action-settings.asciidoc b/docs/settings/alert-action-settings.asciidoc index 0f4987822dc32..6bd7eb1e76345 100644 --- a/docs/settings/alert-action-settings.asciidoc +++ b/docs/settings/alert-action-settings.asciidoc @@ -577,12 +577,6 @@ For a <>, <> - `xpack.alerting.cancelAlertsOnRuleTimeout` {ess-icon}:: Specifies whether to skip writing alerts and scheduling actions if rule processing was cancelled due to a timeout. Default: `true`. This setting can be diff --git a/x-pack/plugins/actions/server/actions_client/actions_client.mock.ts b/x-pack/plugins/actions/server/actions_client/actions_client.mock.ts index 433e3850cae2a..9834765487a80 100644 --- a/x-pack/plugins/actions/server/actions_client/actions_client.mock.ts +++ b/x-pack/plugins/actions/server/actions_client/actions_client.mock.ts @@ -22,7 +22,6 @@ const createActionsClientMock = () => { getBulk: jest.fn(), getOAuthAccessToken: jest.fn(), execute: jest.fn(), - ephemeralEnqueuedExecution: jest.fn(), bulkEnqueueExecution: jest.fn(), listTypes: jest.fn(), isActionTypeEnabled: jest.fn(), diff --git a/x-pack/plugins/actions/server/actions_client/actions_client.test.ts b/x-pack/plugins/actions/server/actions_client/actions_client.test.ts index 99bcbf15ecfb9..b977f8fb97cd3 100644 --- a/x-pack/plugins/actions/server/actions_client/actions_client.test.ts +++ b/x-pack/plugins/actions/server/actions_client/actions_client.test.ts @@ -79,7 +79,6 @@ const unsecuredSavedObjectsClient = savedObjectsClientMock.create(); const scopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); const actionExecutor = actionExecutorMock.create(); const authorization = actionsAuthorizationMock.create(); -const ephemeralExecutionEnqueuer = jest.fn(); const bulkExecutionEnqueuer = jest.fn(); const request = httpServerMock.createKibanaRequest(); const auditLogger = auditLoggerMock.create(); @@ -138,7 +137,6 @@ beforeEach(() => { kibanaIndices, inMemoryConnectors: [], actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -613,7 +611,6 @@ describe('create()', () => { kibanaIndices, inMemoryConnectors: [], actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -739,7 +736,6 @@ describe('create()', () => { ], actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -801,7 +797,6 @@ describe('create()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -862,7 +857,6 @@ describe('get()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -899,7 +893,6 @@ describe('get()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -956,7 +949,6 @@ describe('get()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -999,7 +991,6 @@ describe('get()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -1121,7 +1112,6 @@ describe('get()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -1165,7 +1155,6 @@ describe('get()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -1199,7 +1188,6 @@ describe('get()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -1270,7 +1258,6 @@ describe('getBulk()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -1408,7 +1395,6 @@ describe('getBulk()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -1503,7 +1489,6 @@ describe('getBulk()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -1577,7 +1562,6 @@ describe('getBulk()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -1662,7 +1646,6 @@ describe('getOAuthAccessToken()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -2097,7 +2080,6 @@ describe('delete()', () => { }, ], actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -2133,7 +2115,6 @@ describe('delete()', () => { }, ], actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -2653,7 +2634,6 @@ describe('update()', () => { }, ], actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -2696,7 +2676,6 @@ describe('update()', () => { }, ], actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -2782,7 +2761,6 @@ describe('execute()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -2845,7 +2823,6 @@ describe('execute()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -2907,7 +2884,6 @@ describe('execute()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -3180,7 +3156,6 @@ describe('isPreconfigured()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -3230,7 +3205,6 @@ describe('isPreconfigured()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -3282,7 +3256,6 @@ describe('isSystemAction()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -3332,7 +3305,6 @@ describe('isSystemAction()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, diff --git a/x-pack/plugins/actions/server/actions_client/actions_client.ts b/x-pack/plugins/actions/server/actions_client/actions_client.ts index 5c563fbd6aa82..e39cf8712894f 100644 --- a/x-pack/plugins/actions/server/actions_client/actions_client.ts +++ b/x-pack/plugins/actions/server/actions_client/actions_client.ts @@ -18,7 +18,6 @@ import { Logger, } from '@kbn/core/server'; import { AuditLogger } from '@kbn/security-plugin/server'; -import { RunNowResult } from '@kbn/task-manager-plugin/server'; import { IEventLogClient } from '@kbn/event-log-plugin/server'; import { KueryNode } from '@kbn/es-query'; import { Connector, ConnectorWithExtraFindData } from '../application/connector/types'; @@ -46,7 +45,6 @@ import { } from '../types'; import { PreconfiguredActionDisabledModificationError } from '../lib/errors/preconfigured_action_disabled_modification'; import { - ExecutionEnqueuer, ExecuteOptions as EnqueueExecutionOptions, BulkExecutionEnqueuer, ExecutionResponse, @@ -92,7 +90,6 @@ export interface ConstructorOptions { unsecuredSavedObjectsClient: SavedObjectsClientContract; inMemoryConnectors: InMemoryConnector[]; actionExecutor: ActionExecutorContract; - ephemeralExecutionEnqueuer: ExecutionEnqueuer; bulkExecutionEnqueuer: BulkExecutionEnqueuer; request: KibanaRequest; authorization: ActionsAuthorization; @@ -112,7 +109,6 @@ export interface ActionsClientContext { actionExecutor: ActionExecutorContract; request: KibanaRequest; authorization: ActionsAuthorization; - ephemeralExecutionEnqueuer: ExecutionEnqueuer; bulkExecutionEnqueuer: BulkExecutionEnqueuer; auditLogger?: AuditLogger; usageCounter?: UsageCounter; @@ -131,7 +127,6 @@ export class ActionsClient { unsecuredSavedObjectsClient, inMemoryConnectors, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization, @@ -148,7 +143,6 @@ export class ActionsClient { kibanaIndices, inMemoryConnectors, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization, @@ -504,18 +498,6 @@ export class ActionsClient { return this.context.bulkExecutionEnqueuer(this.context.unsecuredSavedObjectsClient, options); } - public async ephemeralEnqueuedExecution(options: EnqueueExecutionOptions): Promise { - await this.context.authorization.ensureAuthorized({ - operation: 'execute', - actionTypeId: options.actionTypeId, - }); - - return this.context.ephemeralExecutionEnqueuer( - this.context.unsecuredSavedObjectsClient, - options - ); - } - public async listTypes({ featureId, includeSystemActionTypes = false, diff --git a/x-pack/plugins/actions/server/actions_client/actions_client_hooks.test.ts b/x-pack/plugins/actions/server/actions_client/actions_client_hooks.test.ts index 7a1a0fb5e3d91..303254a66ea19 100644 --- a/x-pack/plugins/actions/server/actions_client/actions_client_hooks.test.ts +++ b/x-pack/plugins/actions/server/actions_client/actions_client_hooks.test.ts @@ -38,7 +38,6 @@ const unsecuredSavedObjectsClient = savedObjectsClientMock.create(); const scopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); const actionExecutor = actionExecutorMock.create(); const authorization = actionsAuthorizationMock.create(); -const ephemeralExecutionEnqueuer = jest.fn(); const bulkExecutionEnqueuer = jest.fn(); const request = httpServerMock.createKibanaRequest(); const auditLogger = auditLoggerMock.create(); @@ -131,7 +130,6 @@ beforeEach(() => { kibanaIndices, inMemoryConnectors: [], actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, diff --git a/x-pack/plugins/actions/server/application/connector/methods/get_all/get_all.test.ts b/x-pack/plugins/actions/server/application/connector/methods/get_all/get_all.test.ts index 0f86a8e582e34..5ff37776cf2dc 100644 --- a/x-pack/plugins/actions/server/application/connector/methods/get_all/get_all.test.ts +++ b/x-pack/plugins/actions/server/application/connector/methods/get_all/get_all.test.ts @@ -52,7 +52,6 @@ const unsecuredSavedObjectsClient = savedObjectsClientMock.create(); const scopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); const actionExecutor = actionExecutorMock.create(); const authorization = actionsAuthorizationMock.create(); -const ephemeralExecutionEnqueuer = jest.fn(); const bulkExecutionEnqueuer = jest.fn(); const request = httpServerMock.createKibanaRequest(); const auditLogger = auditLoggerMock.create(); @@ -78,7 +77,6 @@ describe('getAll()', () => { kibanaIndices, inMemoryConnectors: [], actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -134,7 +132,6 @@ describe('getAll()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -279,7 +276,6 @@ describe('getAll()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -382,7 +378,6 @@ describe('getAll()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -487,7 +482,6 @@ describe('getAll()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -579,7 +573,6 @@ describe('getAll()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -613,7 +606,6 @@ describe('getAll()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, @@ -690,7 +682,6 @@ describe('getAll()', () => { scopedClusterClient, kibanaIndices, actionExecutor, - ephemeralExecutionEnqueuer, bulkExecutionEnqueuer, request, authorization: authorization as unknown as ActionsAuthorization, diff --git a/x-pack/plugins/actions/server/application/connector/methods/list_types/list_types.test.ts b/x-pack/plugins/actions/server/application/connector/methods/list_types/list_types.test.ts index 9ff5e05d45506..056d535ce438b 100644 --- a/x-pack/plugins/actions/server/application/connector/methods/list_types/list_types.test.ts +++ b/x-pack/plugins/actions/server/application/connector/methods/list_types/list_types.test.ts @@ -60,7 +60,6 @@ describe('listTypes()', () => { unsecuredSavedObjectsClient: savedObjectsClientMock.create(), inMemoryConnectors: [], actionExecutor: actionExecutorMock.create(), - ephemeralExecutionEnqueuer: jest.fn(), bulkExecutionEnqueuer: jest.fn(), request: httpServerMock.createKibanaRequest(), authorization: actionsAuthorizationMock.create() as unknown as ActionsAuthorization, diff --git a/x-pack/plugins/actions/server/create_execute_function.ts b/x-pack/plugins/actions/server/create_execute_function.ts index a92bff9719559..539ada46a094a 100644 --- a/x-pack/plugins/actions/server/create_execute_function.ts +++ b/x-pack/plugins/actions/server/create_execute_function.ts @@ -6,13 +6,8 @@ */ import { SavedObjectsBulkResponse, SavedObjectsClientContract, Logger } from '@kbn/core/server'; -import { RunNowResult, TaskManagerStartContract } from '@kbn/task-manager-plugin/server'; -import { - RawAction, - ActionTypeRegistryContract, - InMemoryConnector, - ActionTaskExecutorParams, -} from './types'; +import { TaskManagerStartContract } from '@kbn/task-manager-plugin/server'; +import { RawAction, ActionTypeRegistryContract, InMemoryConnector } from './types'; import { ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE } from './constants/saved_objects'; import { ExecuteOptions as ActionExecutorOptions } from './lib/action_executor'; import { extractSavedObjectReferences, isSavedObjectExecutionSource } from './lib'; @@ -215,43 +210,6 @@ export function createBulkExecutionEnqueuerFunction({ }; } -export function createEphemeralExecutionEnqueuerFunction({ - taskManager, - actionTypeRegistry, - inMemoryConnectors, - logger, -}: CreateExecuteFunctionOptions): ExecutionEnqueuer { - return async function execute( - unsecuredSavedObjectsClient: SavedObjectsClientContract, - { id, params, spaceId, source, consumer, apiKey, executionId }: ExecuteOptions - ): Promise { - const { connector } = await getConnector(unsecuredSavedObjectsClient, inMemoryConnectors, id); - - validateConnector({ id, connector, actionTypeRegistry }); - - const taskParams: ActionTaskExecutorParams = { - spaceId, - taskParams: { - actionId: id, - consumer, - // Saved Objects won't allow us to enforce unknown rather than any - // eslint-disable-next-line @typescript-eslint/no-explicit-any - params: params as Record, - ...(apiKey ? { apiKey } : {}), - ...(executionId ? { executionId } : {}), - }, - ...executionSourceAsSavedObjectReferences(source), - }; - - return taskManager.ephemeralRunNow({ - taskType: `actions:${connector.actionTypeId}`, - params: taskParams, - state: {}, - scope: ['actions'], - }); - }; -} - function validateConnector({ id, connector, @@ -287,21 +245,6 @@ function executionSourceAsSavedObjectReferences(executionSource: ActionExecutorO : {}; } -async function getConnector( - unsecuredSavedObjectsClient: SavedObjectsClientContract, - inMemoryConnectors: InMemoryConnector[], - actionId: string -): Promise<{ connector: InMemoryConnector | RawAction; isInMemory: boolean }> { - const inMemoryAction = inMemoryConnectors.find((action) => action.id === actionId); - - if (inMemoryAction) { - return { connector: inMemoryAction, isInMemory: true }; - } - - const { attributes } = await unsecuredSavedObjectsClient.get('action', actionId); - return { connector: attributes, isInMemory: false }; -} - async function getConnectors( unsecuredSavedObjectsClient: SavedObjectsClientContract, inMemoryConnectors: InMemoryConnector[], diff --git a/x-pack/plugins/actions/server/lib/action_executor.ts b/x-pack/plugins/actions/server/lib/action_executor.ts index b0f9db0ef700c..799fdb80f39af 100644 --- a/x-pack/plugins/actions/server/lib/action_executor.ts +++ b/x-pack/plugins/actions/server/lib/action_executor.ts @@ -82,7 +82,6 @@ export interface ExecuteOptions { actionId: string; consumer?: string; executionId?: string; - isEphemeral?: boolean; params: Record; relatedSavedObjects?: RelatedSavedObjects; request: KibanaRequest; @@ -133,7 +132,6 @@ export class ActionExecutor { actionId, consumer, executionId, - isEphemeral, request, params, relatedSavedObjects, @@ -175,7 +173,6 @@ export class ActionExecutor { }, executeLabel: `execute_action`, executionId, - isEphemeral, namespace, params, relatedSavedObjects, @@ -367,7 +364,6 @@ export class ActionExecutor { checkCanExecuteFn, executeLabel, executionId, - isEphemeral, namespace, params, relatedSavedObjects, @@ -512,7 +508,6 @@ export class ActionExecutor { params: validatedParams, config: validatedConfig, secrets: validatedSecrets, - isEphemeral, taskInfo, configurationUtilities, logger, diff --git a/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts b/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts index 9733b56638d77..0dc2b2f3f5c9a 100644 --- a/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts +++ b/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts @@ -35,7 +35,6 @@ import { SavedObjectsErrorHelpers } from '@kbn/core-saved-objects-server'; const executeParamsFields = [ 'actionId', - 'isEphemeral', 'params', 'relatedSavedObjects', 'executionId', @@ -173,7 +172,6 @@ describe('Task Runner Factory', () => { const [executeParams] = mockedActionExecutor.execute.mock.calls[0]; expect(pick(executeParams, executeParamsFields)).toEqual({ actionId: '2', - isEphemeral: false, params: { baz: true }, relatedSavedObjects: [], executionId: '123abc', @@ -233,7 +231,6 @@ describe('Task Runner Factory', () => { const [executeParams] = mockedActionExecutor.execute.mock.calls[0]; expect(pick(executeParams, executeParamsFields)).toEqual({ actionId: '9', - isEphemeral: false, params: { baz: true }, executionId: '123abc', relatedSavedObjects: [], @@ -289,7 +286,6 @@ describe('Task Runner Factory', () => { expect(pick(executeParams, [...executeParamsFields, 'consumer'])).toEqual({ actionId: '2', consumer: 'test-consumer', - isEphemeral: false, params: { baz: true }, relatedSavedObjects: [], executionId: '123abc', @@ -346,7 +342,6 @@ describe('Task Runner Factory', () => { expect(pick(executeParams, [...executeParamsFields, 'consumer'])).toEqual({ actionId: '2', consumer: 'test-consumer', - isEphemeral: false, params: { baz: true }, relatedSavedObjects: [], executionId: '123abc', @@ -407,7 +402,6 @@ describe('Task Runner Factory', () => { expect(pick(executeParams, [...executeParamsFields, 'consumer'])).toEqual({ actionId: '2', consumer: 'test-consumer', - isEphemeral: false, params: { baz: true }, relatedSavedObjects: [], executionId: '123abc', @@ -569,7 +563,6 @@ describe('Task Runner Factory', () => { const [executeParams] = mockedActionExecutor.execute.mock.calls[0]; expect(pick(executeParams, executeParamsFields)).toEqual({ actionId: '2', - isEphemeral: false, params: { baz: true }, executionId: '123abc', relatedSavedObjects: [], @@ -627,7 +620,6 @@ describe('Task Runner Factory', () => { const [executeParams] = mockedActionExecutor.execute.mock.calls[0]; expect(pick(executeParams, executeParamsFields)).toEqual({ actionId: '2', - isEphemeral: false, params: { baz: true }, executionId: '123abc', relatedSavedObjects: [ @@ -680,7 +672,6 @@ describe('Task Runner Factory', () => { const [executeParams] = mockedActionExecutor.execute.mock.calls[0]; expect(pick(executeParams, executeParamsFields)).toEqual({ actionId: '2', - isEphemeral: false, params: { baz: true }, executionId: '123abc', relatedSavedObjects: [ @@ -739,7 +730,6 @@ describe('Task Runner Factory', () => { const [executeParams] = mockedActionExecutor.execute.mock.calls[0]; expect(pick(executeParams, executeParamsFields)).toEqual({ actionId: '2', - isEphemeral: false, params: { baz: true }, request: { headers: { @@ -785,7 +775,6 @@ describe('Task Runner Factory', () => { const [executeParams] = mockedActionExecutor.execute.mock.calls[0]; expect(pick(executeParams, executeParamsFields)).toEqual({ actionId: '2', - isEphemeral: false, params: { baz: true }, executionId: '123abc', relatedSavedObjects: [], diff --git a/x-pack/plugins/actions/server/lib/task_runner_factory.ts b/x-pack/plugins/actions/server/lib/task_runner_factory.ts index cf1f9eed87c32..b718a32a2e4ad 100644 --- a/x-pack/plugins/actions/server/lib/task_runner_factory.ts +++ b/x-pack/plugins/actions/server/lib/task_runner_factory.ts @@ -32,7 +32,6 @@ import { ActionTaskParams, ActionTypeExecutorResult, ActionTypeRegistryContract, - isPersistedActionTask, SpaceIdToNamespaceFunction, } from '../types'; import { ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE } from '../constants/saved_objects'; @@ -128,7 +127,6 @@ export class TaskRunnerFactory { executorResult = await actionExecutor.execute({ params, actionId: actionId as string, - isEphemeral: !isPersistedActionTask(actionTaskExecutorParams), request, taskInfo, executionId, @@ -209,19 +207,17 @@ export class TaskRunnerFactory { }, cleanup: async () => { // Cleanup action_task_params object now that we're done with it - if (isPersistedActionTask(actionTaskExecutorParams)) { - try { - await savedObjectsRepository.delete( - ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, - actionTaskExecutorParams.actionTaskParamsId, - { refresh: false, namespace: spaceIdToNamespace(actionTaskExecutorParams.spaceId) } - ); - } catch (e) { - // Log error only, we shouldn't fail the task because of an error here (if ever there's retry logic) - logger.error( - `Failed to cleanup ${ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE} object [id="${actionTaskExecutorParams.actionTaskParamsId}"]: ${e.message}` - ); - } + try { + await savedObjectsRepository.delete( + ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, + actionTaskExecutorParams.actionTaskParamsId, + { refresh: false, namespace: spaceIdToNamespace(actionTaskExecutorParams.spaceId) } + ); + } catch (e) { + // Log error only, we shouldn't fail the task because of an error here (if ever there's retry logic) + logger.error( + `Failed to cleanup ${ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE} object [id="${actionTaskExecutorParams.actionTaskParamsId}"]: ${e.message}` + ); } }, }; @@ -252,45 +248,41 @@ async function getActionTaskParams( ): Promise { const { spaceId } = executorParams; const namespace = spaceIdToNamespace(spaceId); - if (isPersistedActionTask(executorParams)) { - try { - const actionTask = - await encryptedSavedObjectsClient.getDecryptedAsInternalUser( - ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, - executorParams.actionTaskParamsId, - { namespace } - ); - const { - attributes: { relatedSavedObjects }, - references, - } = actionTask; + try { + const actionTask = + await encryptedSavedObjectsClient.getDecryptedAsInternalUser( + ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, + executorParams.actionTaskParamsId, + { namespace } + ); + const { + attributes: { relatedSavedObjects }, + references, + } = actionTask; - const { actionId, relatedSavedObjects: injectedRelatedSavedObjects } = - injectSavedObjectReferences(references, relatedSavedObjects as RelatedSavedObjects); + const { actionId, relatedSavedObjects: injectedRelatedSavedObjects } = + injectSavedObjectReferences(references, relatedSavedObjects as RelatedSavedObjects); - return { - ...actionTask, - attributes: { - ...actionTask.attributes, - ...(actionId ? { actionId } : {}), - ...(relatedSavedObjects ? { relatedSavedObjects: injectedRelatedSavedObjects } : {}), - }, - }; - } catch (e) { - const errorSource = SavedObjectsErrorHelpers.isNotFoundError(e) - ? TaskErrorSource.USER - : TaskErrorSource.FRAMEWORK; - logger.error( - `Failed to load action task params ${executorParams.actionTaskParamsId}: ${e.message}`, - { tags: ['connector-run-failed', `${errorSource}-error`] } - ); - if (SavedObjectsErrorHelpers.isNotFoundError(e)) { - throw createRetryableError(createTaskRunError(e, errorSource), true); - } + return { + ...actionTask, + attributes: { + ...actionTask.attributes, + ...(actionId ? { actionId } : {}), + ...(relatedSavedObjects ? { relatedSavedObjects: injectedRelatedSavedObjects } : {}), + }, + }; + } catch (e) { + const errorSource = SavedObjectsErrorHelpers.isNotFoundError(e) + ? TaskErrorSource.USER + : TaskErrorSource.FRAMEWORK; + logger.error( + `Failed to load action task params ${executorParams.actionTaskParamsId}: ${e.message}`, + { tags: ['connector-run-failed', `${errorSource}-error`] } + ); + if (SavedObjectsErrorHelpers.isNotFoundError(e)) { throw createRetryableError(createTaskRunError(e, errorSource), true); } - } else { - return { attributes: executorParams.taskParams, references: executorParams.references ?? [] }; + throw createRetryableError(createTaskRunError(e, errorSource), true); } } diff --git a/x-pack/plugins/actions/server/plugin.ts b/x-pack/plugins/actions/server/plugin.ts index edfd7606950c1..012f602398e64 100644 --- a/x-pack/plugins/actions/server/plugin.ts +++ b/x-pack/plugins/actions/server/plugin.ts @@ -48,10 +48,7 @@ import { resolveCustomHosts } from './lib/custom_host_settings'; import { events } from './lib/event_based_telemetry'; import { ActionsClient } from './actions_client/actions_client'; import { ActionTypeRegistry } from './action_type_registry'; -import { - createEphemeralExecutionEnqueuerFunction, - createBulkExecutionEnqueuerFunction, -} from './create_execute_function'; +import { createBulkExecutionEnqueuerFunction } from './create_execute_function'; import { registerActionsUsageCollector } from './usage'; import { ActionExecutor, @@ -480,14 +477,6 @@ export class ActionsPlugin implements Plugin; @@ -238,27 +236,11 @@ export interface ActionTaskParams extends SavedObjectAttributes { source?: string; } -interface PersistedActionTaskExecutorParams { +export interface ActionTaskExecutorParams { spaceId: string; actionTaskParamsId: string; } -interface EphemeralActionTaskExecutorParams { - spaceId: string; - taskParams: ActionTaskParams; - references?: SavedObjectReference[]; -} - -export type ActionTaskExecutorParams = - | PersistedActionTaskExecutorParams - | EphemeralActionTaskExecutorParams; - -export function isPersistedActionTask( - actionTask: ActionTaskExecutorParams -): actionTask is PersistedActionTaskExecutorParams { - return typeof (actionTask as PersistedActionTaskExecutorParams).actionTaskParamsId === 'string'; -} - export interface ProxySettings { proxyUrl: string; proxyBypassHosts: Set | undefined; diff --git a/x-pack/plugins/alerting/server/config.test.ts b/x-pack/plugins/alerting/server/config.test.ts index 4b84905a12a6e..0cb75cb6162ce 100644 --- a/x-pack/plugins/alerting/server/config.test.ts +++ b/x-pack/plugins/alerting/server/config.test.ts @@ -21,7 +21,6 @@ describe('config validation', () => { "interval": "5m", "removalDelay": "1h", }, - "maxEphemeralActionsPerAlert": 10, "rules": Object { "maxScheduledPerMinute": 32000, "minimumScheduleInterval": Object { diff --git a/x-pack/plugins/alerting/server/config.ts b/x-pack/plugins/alerting/server/config.ts index be7790cd81888..776576cce2993 100644 --- a/x-pack/plugins/alerting/server/config.ts +++ b/x-pack/plugins/alerting/server/config.ts @@ -60,7 +60,6 @@ const rulesSchema = schema.object({ }), }); -export const DEFAULT_MAX_EPHEMERAL_ACTIONS_PER_ALERT = 10; export const configSchema = schema.object({ healthCheck: schema.object({ interval: schema.string({ validate: validateDurationSchema, defaultValue: '60m' }), @@ -69,9 +68,7 @@ export const configSchema = schema.object({ interval: schema.string({ validate: validateDurationSchema, defaultValue: '5m' }), removalDelay: schema.string({ validate: validateDurationSchema, defaultValue: '1h' }), }), - maxEphemeralActionsPerAlert: schema.number({ - defaultValue: DEFAULT_MAX_EPHEMERAL_ACTIONS_PER_ALERT, - }), + maxEphemeralActionsPerAlert: schema.maybe(schema.number()), enableFrameworkAlerts: schema.boolean({ defaultValue: true }), cancelAlertsOnRuleTimeout: schema.boolean({ defaultValue: true }), rules: rulesSchema, diff --git a/x-pack/plugins/alerting/server/index.ts b/x-pack/plugins/alerting/server/index.ts index 2cb2c212a91ba..5beafbff1c093 100644 --- a/x-pack/plugins/alerting/server/index.ts +++ b/x-pack/plugins/alerting/server/index.ts @@ -36,7 +36,6 @@ export type { export { DEFAULT_AAD_CONFIG } from './types'; export { RULE_SAVED_OBJECT_TYPE, API_KEY_PENDING_INVALIDATION_TYPE } from './saved_objects'; export { RuleNotifyWhen } from '../common'; -export { DEFAULT_MAX_EPHEMERAL_ACTIONS_PER_ALERT } from './config'; export type { PluginSetupContract, PluginStartContract } from './plugin'; export type { FindResult, BulkEditOperation, BulkOperationError } from './rules_client'; export type { Rule } from './application/rule/types'; @@ -84,9 +83,9 @@ export const config: PluginConfigDescriptor = { rules: { run: { alerts: { max: true } } }, }, deprecations: ({ renameFromRoot, deprecate }) => [ - deprecate('maxEphemeralActionsPerAlert', 'a future version', { + deprecate('maxEphemeralActionsPerAlert', '9.0.0', { level: 'warning', - message: `Configuring "xpack.alerting.maxEphemeralActionsPerAlert" is deprecated and will be removed in a future version. Remove this setting to increase action execution resiliency.`, + message: `The setting "xpack.alerting.maxEphemeralActionsPerAlert" is deprecated and currently ignored by the system. Please remove this setting.`, }), ], }; diff --git a/x-pack/plugins/alerting/server/plugin.ts b/x-pack/plugins/alerting/server/plugin.ts index 9a12b13eb164c..a369541b27bf3 100644 --- a/x-pack/plugins/alerting/server/plugin.ts +++ b/x-pack/plugins/alerting/server/plugin.ts @@ -615,7 +615,6 @@ export class AlertingPlugin { logger, }), maxAlerts: this.config.rules.run.alerts.max, - maxEphemeralActionsPerRule: this.config.maxEphemeralActionsPerAlert, ruleTypeRegistry: this.ruleTypeRegistry!, rulesSettingsService: new RulesSettingsService({ cacheInterval: this.config.rulesSettings.cacheInterval, @@ -626,7 +625,6 @@ export class AlertingPlugin { savedObjects: core.savedObjects, share: plugins.share, spaceIdToNamespace, - supportsEphemeralTasks: plugins.taskManager.supportsEphemeralTasks(), uiSettings: core.uiSettings, usageCounter: this.usageCounter, isServerless: this.isServerless, diff --git a/x-pack/plugins/alerting/server/task_runner/action_scheduler/action_scheduler.test.ts b/x-pack/plugins/alerting/server/task_runner/action_scheduler/action_scheduler.test.ts index 00f1a87aefd71..c0eb08e6d582f 100644 --- a/x-pack/plugins/alerting/server/task_runner/action_scheduler/action_scheduler.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/action_scheduler/action_scheduler.test.ts @@ -2617,7 +2617,6 @@ describe('Action Scheduler', () => { }); expect(buildActionParams).not.toHaveBeenCalledWith(); - expect(actionsClient.ephemeralEnqueuedExecution).not.toHaveBeenCalled(); expect(actionsClient.bulkEnqueueExecution).not.toHaveBeenCalled(); expect(alertingEventLogger.logAction).not.toHaveBeenCalled(); expect(executorParams.logger.warn).toHaveBeenCalledWith( @@ -2662,7 +2661,6 @@ describe('Action Scheduler', () => { expect(res).toEqual({ throttledSummaryActions: {} }); expect(buildActionParams).not.toHaveBeenCalled(); expect(alertsClient.getSummarizedAlerts).not.toHaveBeenCalled(); - expect(actionsClient.ephemeralEnqueuedExecution).not.toHaveBeenCalled(); expect(actionsClient.bulkEnqueueExecution).not.toHaveBeenCalled(); expect(alertingEventLogger.logAction).not.toHaveBeenCalled(); }); diff --git a/x-pack/plugins/alerting/server/task_runner/action_scheduler/action_scheduler.ts b/x-pack/plugins/alerting/server/task_runner/action_scheduler/action_scheduler.ts index fa16cfcabb094..9a174dd236cf1 100644 --- a/x-pack/plugins/alerting/server/task_runner/action_scheduler/action_scheduler.ts +++ b/x-pack/plugins/alerting/server/task_runner/action_scheduler/action_scheduler.ts @@ -5,13 +5,8 @@ * 2.0. */ +import { createTaskRunError, TaskErrorSource } from '@kbn/task-manager-plugin/server'; import { - createTaskRunError, - isEphemeralTaskRejectedDueToCapacityError, - TaskErrorSource, -} from '@kbn/task-manager-plugin/server'; -import { - ExecuteOptions as EnqueueExecutionOptions, ExecutionResponseItem, ExecutionResponseType, } from '@kbn/actions-plugin/server/create_execute_function'; @@ -51,8 +46,6 @@ export class ActionScheduler< IActionScheduler > = []; - private ephemeralActionsToSchedule: number; - constructor( private readonly context: ActionSchedulerOptions< Params, @@ -65,7 +58,6 @@ export class ActionScheduler< AlertData > ) { - this.ephemeralActionsToSchedule = context.taskRunnerContext.maxEphemeralActionsPerRule; for (const [_, scheduler] of Object.entries(schedulers)) { this.schedulers.push(new scheduler(context)); } @@ -101,37 +93,28 @@ export class ActionScheduler< return { throttledSummaryActions }; } - const bulkScheduleRequest: EnqueueExecutionOptions[] = []; - - for (const result of allActionsToScheduleResult) { - await this.runActionAsEphemeralOrAddToBulkScheduleRequest({ - enqueueOptions: result.actionToEnqueue, - bulkScheduleRequest, - }); - } - let bulkScheduleResponse: ExecutionResponseItem[] = []; - if (!!bulkScheduleRequest.length) { - for (const c of chunk(bulkScheduleRequest, BULK_SCHEDULE_CHUNK_SIZE)) { - let enqueueResponse; - try { - enqueueResponse = await withAlertingSpan('alerting:bulk-enqueue-actions', () => - this.context.actionsClient!.bulkEnqueueExecution(c) - ); - } catch (e) { - if (e.statusCode === 404) { - throw createTaskRunError(e, TaskErrorSource.USER); - } - throw createTaskRunError(e, TaskErrorSource.FRAMEWORK); - } - if (enqueueResponse.errors) { - bulkScheduleResponse = bulkScheduleResponse.concat( - enqueueResponse.items.filter( - (i) => i.response === ExecutionResponseType.QUEUED_ACTIONS_LIMIT_ERROR - ) - ); + for (const c of chunk(allActionsToScheduleResult, BULK_SCHEDULE_CHUNK_SIZE)) { + let enqueueResponse; + try { + enqueueResponse = await withAlertingSpan('alerting:bulk-enqueue-actions', () => + this.context.actionsClient!.bulkEnqueueExecution( + c.map((actions) => actions.actionToEnqueue) + ) + ); + } catch (e) { + if (e.statusCode === 404) { + throw createTaskRunError(e, TaskErrorSource.USER); } + throw createTaskRunError(e, TaskErrorSource.FRAMEWORK); + } + if (enqueueResponse.errors) { + bulkScheduleResponse = bulkScheduleResponse.concat( + enqueueResponse.items.filter( + (i) => i.response === ExecutionResponseType.QUEUED_ACTIONS_LIMIT_ERROR + ) + ); } } @@ -175,28 +158,4 @@ export class ActionScheduler< return { throttledSummaryActions }; } - - private async runActionAsEphemeralOrAddToBulkScheduleRequest({ - enqueueOptions, - bulkScheduleRequest, - }: { - enqueueOptions: EnqueueExecutionOptions; - bulkScheduleRequest: EnqueueExecutionOptions[]; - }) { - if ( - this.context.taskRunnerContext.supportsEphemeralTasks && - this.ephemeralActionsToSchedule > 0 - ) { - this.ephemeralActionsToSchedule--; - try { - await this.context.actionsClient!.ephemeralEnqueuedExecution(enqueueOptions); - } catch (err) { - if (isEphemeralTaskRejectedDueToCapacityError(err)) { - bulkScheduleRequest.push(enqueueOptions); - } - } - } else { - bulkScheduleRequest.push(enqueueOptions); - } - } } diff --git a/x-pack/plugins/alerting/server/task_runner/ad_hoc_task_runner.test.ts b/x-pack/plugins/alerting/server/task_runner/ad_hoc_task_runner.test.ts index cfc87f8497eae..ae6467d0dcbf8 100644 --- a/x-pack/plugins/alerting/server/task_runner/ad_hoc_task_runner.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/ad_hoc_task_runner.test.ts @@ -168,13 +168,11 @@ const taskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType kibanaBaseUrl: 'https://localhost:5601', logger, maxAlerts: 1000, - maxEphemeralActionsPerRule: 10, ruleTypeRegistry, rulesSettingsService, savedObjects: savedObjectsService, share: {} as SharePluginStart, spaceIdToNamespace: jest.fn().mockReturnValue(undefined), - supportsEphemeralTasks: false, uiSettings: uiSettingsService, usageCounter: mockUsageCounter, isServerless: false, diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts index da23b9bdce4ed..bbe927833afd0 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts @@ -53,7 +53,6 @@ import { generateActionOpts, mockDate, mockedRuleTypeSavedObject, - mockRunNowResponse, ruleType, RULE_NAME, generateRunnerResult, @@ -187,38 +186,16 @@ describe('Task Runner', () => { logger, maintenanceWindowsService, maxAlerts: 1000, - maxEphemeralActionsPerRule: 10, ruleTypeRegistry, rulesSettingsService, savedObjects: savedObjectsService, share: {} as SharePluginStart, spaceIdToNamespace: jest.fn().mockReturnValue(undefined), - supportsEphemeralTasks: false, uiSettings: uiSettingsService, usageCounter: mockUsageCounter, isServerless: false, }; - const ephemeralTestParams: Array< - [ - nameExtension: string, - customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, - enqueueFunction: unknown, - isBulk: boolean - ] - > = [ - ['', taskRunnerFactoryInitializerParams, actionsClient.bulkEnqueueExecution, true], - [ - ' (with ephemeral support)', - { - ...taskRunnerFactoryInitializerParams, - supportsEphemeralTasks: true, - }, - actionsClient.ephemeralEnqueuedExecution, - false, - ], - ]; - beforeEach(() => { jest.resetAllMocks(); jest.restoreAllMocks(); // clear spy mock implementations @@ -363,103 +340,95 @@ describe('Task Runner', () => { ).toHaveBeenCalled(); }); - test.each(ephemeralTestParams)( - 'actionsPlugin.execute is called per alert alert that is scheduled %s', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction, isBulk) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(mockRunNowResponse); - ruleType.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string, - RuleAlertData - >) => { - executorServices.alertFactory.create('1').scheduleActions('default'); - return { state: {} }; - } - ); - const taskRunner = new TaskRunner({ - ruleType, - taskInstance: mockedTaskInstance, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - internalSavedObjectsRepository, - }); - expect(AlertingEventLogger).toHaveBeenCalledTimes(1); + test('actionsPlugin.execute is called per alert alert that is scheduled', async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); + ruleType.executor.mockImplementation( + async ({ + services: executorServices, + }: RuleExecutorOptions< + RuleTypeParams, + RuleTypeState, + AlertInstanceState, + AlertInstanceContext, + string, + RuleAlertData + >) => { + executorServices.alertFactory.create('1').scheduleActions('default'); + return { state: {} }; + } + ); + const taskRunner = new TaskRunner({ + ruleType, + taskInstance: mockedTaskInstance, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + internalSavedObjectsRepository, + }); + expect(AlertingEventLogger).toHaveBeenCalledTimes(1); - mockGetAlertFromRaw.mockReturnValue(mockedRuleTypeSavedObject as Rule); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - await taskRunner.run(); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - expect(enqueueFunction).toHaveBeenCalledWith( - generateEnqueueFunctionInput({ isBulk, id: '1', foo: true }) - ); + mockGetAlertFromRaw.mockReturnValue(mockedRuleTypeSavedObject as Rule); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + await taskRunner.run(); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith( + generateEnqueueFunctionInput({ isBulk: true, id: '1', foo: true }) + ); - expect(logger.debug).toHaveBeenCalledTimes(6); - expect(logger.debug).nthCalledWith(1, 'executing rule test:1 at 1970-01-01T00:00:00.000Z', { - tags: ['1', 'test'], - }); - expect(logger.debug).nthCalledWith( - 2, - `rule test:1: '${RULE_NAME}' has 1 active alerts: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]`, - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 3, - 'deprecated ruleRunStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}', - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 4, - 'ruleRunStatus for test:1: {"outcome":"succeeded","outcomeOrder":0,"outcomeMsg":null,"warning":null,"alertsCount":{"active":1,"new":1,"recovered":0,"ignored":0}}', - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 5, - 'ruleRunMetrics for test:1: {"numSearches":3,"totalSearchDurationMs":23423,"esSearchDurationMs":33,"numberOfTriggeredActions":1,"numberOfGeneratedActions":1,"numberOfActiveAlerts":1,"numberOfRecoveredAlerts":0,"numberOfNewAlerts":1,"numberOfDelayedAlerts":0,"hasReachedAlertLimit":false,"hasReachedQueuedActionsLimit":false,"triggeredActionsStatus":"complete"}', - { tags: ['1', 'test'] } - ); + expect(logger.debug).toHaveBeenCalledTimes(6); + expect(logger.debug).nthCalledWith(1, 'executing rule test:1 at 1970-01-01T00:00:00.000Z', { + tags: ['1', 'test'], + }); + expect(logger.debug).nthCalledWith( + 2, + `rule test:1: '${RULE_NAME}' has 1 active alerts: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]`, + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 3, + 'deprecated ruleRunStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}', + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 4, + 'ruleRunStatus for test:1: {"outcome":"succeeded","outcomeOrder":0,"outcomeMsg":null,"warning":null,"alertsCount":{"active":1,"new":1,"recovered":0,"ignored":0}}', + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 5, + 'ruleRunMetrics for test:1: {"numSearches":3,"totalSearchDurationMs":23423,"esSearchDurationMs":33,"numberOfTriggeredActions":1,"numberOfGeneratedActions":1,"numberOfActiveAlerts":1,"numberOfRecoveredAlerts":0,"numberOfNewAlerts":1,"numberOfDelayedAlerts":0,"hasReachedAlertLimit":false,"hasReachedQueuedActionsLimit":false,"triggeredActionsStatus":"complete"}', + { tags: ['1', 'test'] } + ); - testAlertingEventLogCalls({ - activeAlerts: 1, - generatedActions: 1, - newAlerts: 1, - triggeredActions: 1, - status: 'active', - logAlert: 2, - logAction: 1, - }); - expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( - 1, - generateAlertOpts({ - action: EVENT_LOG_ACTIONS.newInstance, - group: 'default', - state: { start: DATE_1970, duration: '0' }, - }) - ); - expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( - 2, - generateAlertOpts({ - action: EVENT_LOG_ACTIONS.activeInstance, - group: 'default', - state: { start: DATE_1970, duration: '0' }, - }) - ); - expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith(1, generateActionOpts()); + testAlertingEventLogCalls({ + activeAlerts: 1, + generatedActions: 1, + newAlerts: 1, + triggeredActions: 1, + status: 'active', + logAlert: 2, + logAction: 1, + }); + expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( + 1, + generateAlertOpts({ + action: EVENT_LOG_ACTIONS.newInstance, + group: 'default', + state: { start: DATE_1970, duration: '0' }, + }) + ); + expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( + 2, + generateAlertOpts({ + action: EVENT_LOG_ACTIONS.activeInstance, + group: 'default', + state: { start: DATE_1970, duration: '0' }, + }) + ); + expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith(1, generateActionOpts()); - expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); - } - ); + expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); + }); test('actionsPlugin.execute is skipped if muteAll is true', async () => { taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); @@ -494,7 +463,6 @@ describe('Task Runner', () => { }); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); await taskRunner.run(); - expect(actionsClient.ephemeralEnqueuedExecution).toHaveBeenCalledTimes(0); expect(logger.debug).toHaveBeenCalledTimes(7); expect(logger.debug).nthCalledWith(1, 'executing rule test:1 at 1970-01-01T00:00:00.000Z', { @@ -633,7 +601,6 @@ describe('Task Runner', () => { const expectedExecutions = shouldBeSnoozed ? 0 : 1; expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(expectedExecutions); - expect(actionsClient.ephemeralEnqueuedExecution).toHaveBeenCalledTimes(0); const expectedMessage = `no scheduling of actions for rule test:1: '${RULE_NAME}': rule is snoozed.`; if (expectedExecutions) { @@ -689,7 +656,6 @@ describe('Task Runner', () => { encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); await taskRunner.run(); - expect(actionsClient.ephemeralEnqueuedExecution).toHaveBeenCalledTimes(0); testAlertingEventLogCalls({ activeAlerts: 1, @@ -761,7 +727,6 @@ describe('Task Runner', () => { encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); await taskRunner.run(); - expect(actionsClient.ephemeralEnqueuedExecution).toHaveBeenCalledTimes(0); testAlertingEventLogCalls({ activeAlerts: 1, @@ -824,7 +789,6 @@ describe('Task Runner', () => { encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); await taskRunner.run(); - expect(actionsClient.ephemeralEnqueuedExecution).toHaveBeenCalledTimes(0); testAlertingEventLogCalls({ activeAlerts: 1, @@ -855,202 +819,10 @@ describe('Task Runner', () => { expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); }); - test.each(ephemeralTestParams)( - 'skips firing actions for active alert if alert is muted %s', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction) => { - ( - customTaskRunnerFactoryInitializerParams as TaskRunnerFactoryInitializerParamsType - ).actionsPlugin.isActionTypeEnabled.mockReturnValue(true); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(mockRunNowResponse); - ruleType.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string, - RuleAlertData - >) => { - executorServices.alertFactory.create('1').scheduleActions('default'); - executorServices.alertFactory.create('2').scheduleActions('default'); - return { state: {} }; - } - ); - const taskRunner = new TaskRunner({ - ruleType, - taskInstance: mockedTaskInstance, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - internalSavedObjectsRepository, - }); - expect(AlertingEventLogger).toHaveBeenCalledTimes(1); - - mockGetAlertFromRaw.mockReturnValue({ - ...(mockedRuleTypeSavedObject as Rule), - mutedInstanceIds: ['2'], - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - await taskRunner.run(); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - - expect(logger.debug).toHaveBeenCalledTimes(7); - expect(logger.debug).nthCalledWith(1, 'executing rule test:1 at 1970-01-01T00:00:00.000Z', { - tags: ['1', 'test'], - }); - expect(logger.debug).nthCalledWith( - 2, - `rule test:1: '${RULE_NAME}' has 2 active alerts: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"},{\"instanceId\":\"2\",\"actionGroup\":\"default\"}]`, - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 3, - `skipping scheduling of actions for '2' in rule test:1: '${RULE_NAME}': rule is muted`, - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 4, - 'deprecated ruleRunStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}', - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 5, - 'ruleRunStatus for test:1: {"outcome":"succeeded","outcomeOrder":0,"outcomeMsg":null,"warning":null,"alertsCount":{"active":2,"new":2,"recovered":0,"ignored":0}}', - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 6, - 'ruleRunMetrics for test:1: {"numSearches":3,"totalSearchDurationMs":23423,"esSearchDurationMs":33,"numberOfTriggeredActions":1,"numberOfGeneratedActions":1,"numberOfActiveAlerts":2,"numberOfRecoveredAlerts":0,"numberOfNewAlerts":2,"numberOfDelayedAlerts":0,"hasReachedAlertLimit":false,"hasReachedQueuedActionsLimit":false,"triggeredActionsStatus":"complete"}', - { tags: ['1', 'test'] } - ); - expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); - } - ); - - test.each(ephemeralTestParams)( - 'skips firing actions for active alert if alert is throttled %s', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction) => { - ( - customTaskRunnerFactoryInitializerParams as TaskRunnerFactoryInitializerParamsType - ).actionsPlugin.isActionTypeEnabled.mockReturnValue(true); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(mockRunNowResponse); - ruleType.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string, - RuleAlertData - >) => { - executorServices.alertFactory.create('1').scheduleActions('default'); - executorServices.alertFactory.create('2').scheduleActions('default'); - return { state: {} }; - } - ); - const taskRunner = new TaskRunner({ - ruleType, - internalSavedObjectsRepository, - taskInstance: { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '2': { - meta: { - lastScheduledActions: { date: moment().toISOString(), group: 'default' }, - }, - state: { - bar: false, - start: DATE_1969, - duration: MOCK_DURATION, - }, - }, - }, - }, - }, - context: taskRunnerFactoryInitializerParams, - inMemoryMetrics, - }); - expect(AlertingEventLogger).toHaveBeenCalledTimes(1); - - mockGetAlertFromRaw.mockReturnValue({ - ...(mockedRuleTypeSavedObject as Rule), - notifyWhen: 'onThrottleInterval', - throttle: '1d', - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - await taskRunner.run(); - // expect(enqueueFunction).toHaveBeenCalledTimes(1); - - // expect(logger.debug).toHaveBeenCalledTimes(5); - expect(logger.debug).nthCalledWith( - 3, - `skipping scheduling of actions for '2' in rule test:1: '${RULE_NAME}': rule is throttled`, - { tags: ['1', 'test'] } - ); - } - ); - - test.each(ephemeralTestParams)( - 'skips firing actions for active alert when alert is muted even if notifyWhen === onActionGroupChange %s', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - ruleType.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string, - RuleAlertData - >) => { - executorServices.alertFactory.create('1').scheduleActions('default'); - executorServices.alertFactory.create('2').scheduleActions('default'); - return { state: {} }; - } - ); - const taskRunner = new TaskRunner({ - ruleType, - internalSavedObjectsRepository, - taskInstance: mockedTaskInstance, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - }); - expect(AlertingEventLogger).toHaveBeenCalledTimes(1); - - mockGetAlertFromRaw.mockReturnValue({ - ...(mockedRuleTypeSavedObject as Rule), - mutedInstanceIds: ['2'], - notifyWhen: 'onActionGroupChange', - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - await taskRunner.run(); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - expect(logger.debug).toHaveBeenCalledTimes(7); - expect(logger.debug).nthCalledWith( - 3, - `skipping scheduling of actions for '2' in rule test:1: '${RULE_NAME}': rule is muted`, - { tags: ['1', 'test'] } - ); - } - ); - - test('actionsPlugin.execute is not called when notifyWhen=onActionGroupChange and alert state does not change', async () => { - taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + test('skips firing actions for active alert if alert is muted', async () => { + ( + taskRunnerFactoryInitializerParams as TaskRunnerFactoryInitializerParamsType + ).actionsPlugin.isActionTypeEnabled.mockReturnValue(true); taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); ruleType.executor.mockImplementation( async ({ @@ -1064,13 +836,188 @@ describe('Task Runner', () => { RuleAlertData >) => { executorServices.alertFactory.create('1').scheduleActions('default'); + executorServices.alertFactory.create('2').scheduleActions('default'); return { state: {} }; } ); const taskRunner = new TaskRunner({ ruleType, - internalSavedObjectsRepository, - taskInstance: { + taskInstance: mockedTaskInstance, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + internalSavedObjectsRepository, + }); + expect(AlertingEventLogger).toHaveBeenCalledTimes(1); + + mockGetAlertFromRaw.mockReturnValue({ + ...(mockedRuleTypeSavedObject as Rule), + mutedInstanceIds: ['2'], + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + await taskRunner.run(); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + + expect(logger.debug).toHaveBeenCalledTimes(7); + expect(logger.debug).nthCalledWith(1, 'executing rule test:1 at 1970-01-01T00:00:00.000Z', { + tags: ['1', 'test'], + }); + expect(logger.debug).nthCalledWith( + 2, + `rule test:1: '${RULE_NAME}' has 2 active alerts: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"},{\"instanceId\":\"2\",\"actionGroup\":\"default\"}]`, + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 3, + `skipping scheduling of actions for '2' in rule test:1: '${RULE_NAME}': rule is muted`, + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 4, + 'deprecated ruleRunStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}', + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 5, + 'ruleRunStatus for test:1: {"outcome":"succeeded","outcomeOrder":0,"outcomeMsg":null,"warning":null,"alertsCount":{"active":2,"new":2,"recovered":0,"ignored":0}}', + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 6, + 'ruleRunMetrics for test:1: {"numSearches":3,"totalSearchDurationMs":23423,"esSearchDurationMs":33,"numberOfTriggeredActions":1,"numberOfGeneratedActions":1,"numberOfActiveAlerts":2,"numberOfRecoveredAlerts":0,"numberOfNewAlerts":2,"numberOfDelayedAlerts":0,"hasReachedAlertLimit":false,"hasReachedQueuedActionsLimit":false,"triggeredActionsStatus":"complete"}', + { tags: ['1', 'test'] } + ); + expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); + }); + + test('skips firing actions for active alert if alert is throttled', async () => { + ( + taskRunnerFactoryInitializerParams as TaskRunnerFactoryInitializerParamsType + ).actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); + ruleType.executor.mockImplementation( + async ({ + services: executorServices, + }: RuleExecutorOptions< + RuleTypeParams, + RuleTypeState, + AlertInstanceState, + AlertInstanceContext, + string, + RuleAlertData + >) => { + executorServices.alertFactory.create('1').scheduleActions('default'); + executorServices.alertFactory.create('2').scheduleActions('default'); + return { state: {} }; + } + ); + const taskRunner = new TaskRunner({ + ruleType, + internalSavedObjectsRepository, + taskInstance: { + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '2': { + meta: { + lastScheduledActions: { date: moment().toISOString(), group: 'default' }, + }, + state: { + bar: false, + start: DATE_1969, + duration: MOCK_DURATION, + }, + }, + }, + }, + }, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + }); + expect(AlertingEventLogger).toHaveBeenCalledTimes(1); + + mockGetAlertFromRaw.mockReturnValue({ + ...(mockedRuleTypeSavedObject as Rule), + notifyWhen: 'onThrottleInterval', + throttle: '1d', + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + await taskRunner.run(); + // expect(enqueueFunction).toHaveBeenCalledTimes(1); + + // expect(logger.debug).toHaveBeenCalledTimes(5); + expect(logger.debug).nthCalledWith( + 3, + `skipping scheduling of actions for '2' in rule test:1: '${RULE_NAME}': rule is throttled`, + { tags: ['1', 'test'] } + ); + }); + + test('skips firing actions for active alert when alert is muted even if notifyWhen === onActionGroupChange', async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); + ruleType.executor.mockImplementation( + async ({ + services: executorServices, + }: RuleExecutorOptions< + RuleTypeParams, + RuleTypeState, + AlertInstanceState, + AlertInstanceContext, + string, + RuleAlertData + >) => { + executorServices.alertFactory.create('1').scheduleActions('default'); + executorServices.alertFactory.create('2').scheduleActions('default'); + return { state: {} }; + } + ); + const taskRunner = new TaskRunner({ + ruleType, + internalSavedObjectsRepository, + taskInstance: mockedTaskInstance, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + }); + expect(AlertingEventLogger).toHaveBeenCalledTimes(1); + + mockGetAlertFromRaw.mockReturnValue({ + ...(mockedRuleTypeSavedObject as Rule), + mutedInstanceIds: ['2'], + notifyWhen: 'onActionGroupChange', + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + await taskRunner.run(); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + expect(logger.debug).toHaveBeenCalledTimes(7); + expect(logger.debug).nthCalledWith( + 3, + `skipping scheduling of actions for '2' in rule test:1: '${RULE_NAME}': rule is muted`, + { tags: ['1', 'test'] } + ); + }); + + test('actionsPlugin.execute is not called when notifyWhen=onActionGroupChange and alert state does not change', async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); + ruleType.executor.mockImplementation( + async ({ + services: executorServices, + }: RuleExecutorOptions< + RuleTypeParams, + RuleTypeState, + AlertInstanceState, + AlertInstanceContext, + string, + RuleAlertData + >) => { + executorServices.alertFactory.create('1').scheduleActions('default'); + return { state: {} }; + } + ); + const taskRunner = new TaskRunner({ + ruleType, + internalSavedObjectsRepository, + taskInstance: { ...mockedTaskInstance, state: { ...mockedTaskInstance.state, @@ -1099,7 +1046,6 @@ describe('Task Runner', () => { }); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); await taskRunner.run(); - expect(actionsClient.ephemeralEnqueuedExecution).toHaveBeenCalledTimes(0); testAlertingEventLogCalls({ activeAlerts: 1, @@ -1118,690 +1064,620 @@ describe('Task Runner', () => { expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); }); - test.each(ephemeralTestParams)( - 'actionsPlugin.execute is called when notifyWhen=onActionGroupChange and alert state has changed %s', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - ruleType.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string, - RuleAlertData - >) => { - executorServices.alertFactory.create('1').scheduleActions('default'); - return { state: {} }; - } - ); - const taskRunner = new TaskRunner({ - ruleType, - internalSavedObjectsRepository, - taskInstance: { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { - meta: { - lastScheduledActions: { group: 'newGroup', date: new Date().toISOString() }, - }, - state: { bar: false }, + test('actionsPlugin.execute is called when notifyWhen=onActionGroupChange and alert state has changed', async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); + ruleType.executor.mockImplementation( + async ({ + services: executorServices, + }: RuleExecutorOptions< + RuleTypeParams, + RuleTypeState, + AlertInstanceState, + AlertInstanceContext, + string, + RuleAlertData + >) => { + executorServices.alertFactory.create('1').scheduleActions('default'); + return { state: {} }; + } + ); + const taskRunner = new TaskRunner({ + ruleType, + internalSavedObjectsRepository, + taskInstance: { + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '1': { + meta: { + lastScheduledActions: { group: 'newGroup', date: new Date().toISOString() }, }, + state: { bar: false }, }, }, }, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - }); - expect(AlertingEventLogger).toHaveBeenCalledTimes(1); + }, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + }); + expect(AlertingEventLogger).toHaveBeenCalledTimes(1); - mockGetAlertFromRaw.mockReturnValue({ - ...(mockedRuleTypeSavedObject as Rule), - notifyWhen: 'onActionGroupChange', - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + mockGetAlertFromRaw.mockReturnValue({ + ...(mockedRuleTypeSavedObject as Rule), + notifyWhen: 'onActionGroupChange', + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - await taskRunner.run(); + await taskRunner.run(); - testAlertingEventLogCalls({ - activeAlerts: 1, - triggeredActions: 1, - generatedActions: 1, - status: 'active', - logAlert: 1, - logAction: 1, - }); - expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( - 1, - generateAlertOpts({ - action: EVENT_LOG_ACTIONS.activeInstance, - group: 'default', - state: { bar: false }, - }) - ); - expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith(1, generateActionOpts({})); + testAlertingEventLogCalls({ + activeAlerts: 1, + triggeredActions: 1, + generatedActions: 1, + status: 'active', + logAlert: 1, + logAction: 1, + }); + expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( + 1, + generateAlertOpts({ + action: EVENT_LOG_ACTIONS.activeInstance, + group: 'default', + state: { bar: false }, + }) + ); + expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith(1, generateActionOpts({})); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); - } - ); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); + }); - test.each(ephemeralTestParams)( - 'includes the apiKey in the request used to initialize the actionsClient %s', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction, isBulk) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(mockRunNowResponse); - ruleType.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string, - RuleAlertData - >) => { - executorServices.alertFactory.create('1').scheduleActions('default'); - return { state: {} }; - } - ); - const taskRunner = new TaskRunner({ - ruleType, - internalSavedObjectsRepository, - taskInstance: mockedTaskInstance, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - }); - expect(AlertingEventLogger).toHaveBeenCalled(); + test('includes the apiKey in the request used to initialize the actionsClient', async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); + ruleType.executor.mockImplementation( + async ({ + services: executorServices, + }: RuleExecutorOptions< + RuleTypeParams, + RuleTypeState, + AlertInstanceState, + AlertInstanceContext, + string, + RuleAlertData + >) => { + executorServices.alertFactory.create('1').scheduleActions('default'); + return { state: {} }; + } + ); + const taskRunner = new TaskRunner({ + ruleType, + internalSavedObjectsRepository, + taskInstance: mockedTaskInstance, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + }); + expect(AlertingEventLogger).toHaveBeenCalled(); - mockGetAlertFromRaw.mockReturnValue(mockedRuleTypeSavedObject as Rule); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - await taskRunner.run(); - expect( - customTaskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest - ).toHaveBeenCalledWith( - expect.objectContaining({ - headers: { - // base64 encoded "123:abc" - authorization: 'ApiKey MTIzOmFiYw==', - }, - }) - ); + mockGetAlertFromRaw.mockReturnValue(mockedRuleTypeSavedObject as Rule); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + await taskRunner.run(); + expect( + taskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest + ).toHaveBeenCalledWith( + expect.objectContaining({ + headers: { + // base64 encoded "123:abc" + authorization: 'ApiKey MTIzOmFiYw==', + }, + }) + ); - const [request] = - customTaskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest.mock - .calls[0]; + const [request] = + taskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest.mock.calls[0]; - expect(customTaskRunnerFactoryInitializerParams.basePathService.set).toHaveBeenCalledWith( - request, - '/' - ); + expect(taskRunnerFactoryInitializerParams.basePathService.set).toHaveBeenCalledWith( + request, + '/' + ); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - expect(enqueueFunction).toHaveBeenCalledWith( - generateEnqueueFunctionInput({ isBulk, id: '1', foo: true }) - ); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith( + generateEnqueueFunctionInput({ isBulk: true, id: '1', foo: true }) + ); - testAlertingEventLogCalls({ - activeAlerts: 1, - newAlerts: 1, - triggeredActions: 1, - generatedActions: 1, - status: 'active', - logAlert: 2, - logAction: 1, - }); - expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( - 1, - generateAlertOpts({ - action: EVENT_LOG_ACTIONS.newInstance, - group: 'default', - state: { start: DATE_1970, duration: '0' }, - }) - ); - expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( - 2, - generateAlertOpts({ - action: EVENT_LOG_ACTIONS.activeInstance, - group: 'default', - state: { start: DATE_1970, duration: '0' }, - }) - ); - expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith(1, generateActionOpts({})); + testAlertingEventLogCalls({ + activeAlerts: 1, + newAlerts: 1, + triggeredActions: 1, + generatedActions: 1, + status: 'active', + logAlert: 2, + logAction: 1, + }); + expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( + 1, + generateAlertOpts({ + action: EVENT_LOG_ACTIONS.newInstance, + group: 'default', + state: { start: DATE_1970, duration: '0' }, + }) + ); + expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( + 2, + generateAlertOpts({ + action: EVENT_LOG_ACTIONS.activeInstance, + group: 'default', + state: { start: DATE_1970, duration: '0' }, + }) + ); + expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith(1, generateActionOpts({})); - expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); - } - ); + expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); + }); - test.each(ephemeralTestParams)( - 'fire recovered actions for execution for the alertInstances which is in the recovered state %s', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction, isBulk) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(mockRunNowResponse); + test('fire recovered actions for execution for the alertInstances which is in the recovered state', async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); - ruleType.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string, - RuleAlertData - >) => { - executorServices.alertFactory.create('1').scheduleActions('default'); - return { state: {} }; - } - ); - const taskRunner = new TaskRunner({ - ruleType, - internalSavedObjectsRepository, - taskInstance: { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { - meta: {}, - state: { - bar: false, - start: DATE_1969, - duration: '80000000000', - }, + ruleType.executor.mockImplementation( + async ({ + services: executorServices, + }: RuleExecutorOptions< + RuleTypeParams, + RuleTypeState, + AlertInstanceState, + AlertInstanceContext, + string, + RuleAlertData + >) => { + executorServices.alertFactory.create('1').scheduleActions('default'); + return { state: {} }; + } + ); + const taskRunner = new TaskRunner({ + ruleType, + internalSavedObjectsRepository, + taskInstance: { + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '1': { + meta: {}, + state: { + bar: false, + start: DATE_1969, + duration: '80000000000', }, - '2': { - meta: {}, - state: { - bar: false, - start: '1969-12-31T06:00:00.000Z', - duration: '70000000000', - }, + }, + '2': { + meta: {}, + state: { + bar: false, + start: '1969-12-31T06:00:00.000Z', + duration: '70000000000', }, }, }, }, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - }); - expect(AlertingEventLogger).toHaveBeenCalled(); + }, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + }); + expect(AlertingEventLogger).toHaveBeenCalled(); - mockGetAlertFromRaw.mockReturnValue(mockedRuleTypeSavedObject as Rule); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - const runnerResult = await taskRunner.run(); - expect(runnerResult.state.alertInstances).toEqual( - generateAlertInstance({ - id: 1, - duration: MOCK_DURATION, - start: DATE_1969, - flappingHistory: [false], - }) - ); + mockGetAlertFromRaw.mockReturnValue(mockedRuleTypeSavedObject as Rule); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + const runnerResult = await taskRunner.run(); + expect(runnerResult.state.alertInstances).toEqual( + generateAlertInstance({ + id: 1, + duration: MOCK_DURATION, + start: DATE_1969, + flappingHistory: [false], + }) + ); - expect(logger.debug).toHaveBeenCalledTimes(7); - expect(logger.debug).nthCalledWith(1, 'executing rule test:1 at 1970-01-01T00:00:00.000Z', { - tags: ['1', 'test'], - }); - expect(logger.debug).nthCalledWith( - 2, - `rule test:1: '${RULE_NAME}' has 1 active alerts: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]`, - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 3, - `rule test:1: '${RULE_NAME}' has 1 recovered alerts: [\"2\"]`, - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 4, - 'deprecated ruleRunStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}', - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 5, - 'ruleRunStatus for test:1: {"outcome":"succeeded","outcomeOrder":0,"outcomeMsg":null,"warning":null,"alertsCount":{"active":1,"new":0,"recovered":1,"ignored":0}}', - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 6, - 'ruleRunMetrics for test:1: {"numSearches":3,"totalSearchDurationMs":23423,"esSearchDurationMs":33,"numberOfTriggeredActions":2,"numberOfGeneratedActions":2,"numberOfActiveAlerts":1,"numberOfRecoveredAlerts":1,"numberOfNewAlerts":0,"numberOfDelayedAlerts":0,"hasReachedAlertLimit":false,"hasReachedQueuedActionsLimit":false,"triggeredActionsStatus":"complete"}', - { tags: ['1', 'test'] } - ); + expect(logger.debug).toHaveBeenCalledTimes(7); + expect(logger.debug).nthCalledWith(1, 'executing rule test:1 at 1970-01-01T00:00:00.000Z', { + tags: ['1', 'test'], + }); + expect(logger.debug).nthCalledWith( + 2, + `rule test:1: '${RULE_NAME}' has 1 active alerts: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]`, + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 3, + `rule test:1: '${RULE_NAME}' has 1 recovered alerts: [\"2\"]`, + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 4, + 'deprecated ruleRunStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}', + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 5, + 'ruleRunStatus for test:1: {"outcome":"succeeded","outcomeOrder":0,"outcomeMsg":null,"warning":null,"alertsCount":{"active":1,"new":0,"recovered":1,"ignored":0}}', + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 6, + 'ruleRunMetrics for test:1: {"numSearches":3,"totalSearchDurationMs":23423,"esSearchDurationMs":33,"numberOfTriggeredActions":2,"numberOfGeneratedActions":2,"numberOfActiveAlerts":1,"numberOfRecoveredAlerts":1,"numberOfNewAlerts":0,"numberOfDelayedAlerts":0,"hasReachedAlertLimit":false,"hasReachedQueuedActionsLimit":false,"triggeredActionsStatus":"complete"}', + { tags: ['1', 'test'] } + ); - testAlertingEventLogCalls({ - activeAlerts: 1, - recoveredAlerts: 1, - triggeredActions: 2, - generatedActions: 2, - status: 'active', - logAlert: 2, - logAction: 2, - }); - expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( - 1, - generateAlertOpts({ - action: EVENT_LOG_ACTIONS.recoveredInstance, - id: '2', - state: { - bar: false, - start: '1969-12-31T06:00:00.000Z', - duration: '64800000000000', - end: DATE_1970, - }, - }) - ); - expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( - 2, - generateAlertOpts({ - action: EVENT_LOG_ACTIONS.activeInstance, - group: 'default', - state: { bar: false, start: DATE_1969, duration: MOCK_DURATION }, - }) - ); - expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith(1, generateActionOpts({})); - expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith( - 2, - generateActionOpts({ id: '2', alertId: '2', alertGroup: 'recovered', uuid: '222-222' }) - ); + testAlertingEventLogCalls({ + activeAlerts: 1, + recoveredAlerts: 1, + triggeredActions: 2, + generatedActions: 2, + status: 'active', + logAlert: 2, + logAction: 2, + }); + expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( + 1, + generateAlertOpts({ + action: EVENT_LOG_ACTIONS.recoveredInstance, + id: '2', + state: { + bar: false, + start: '1969-12-31T06:00:00.000Z', + duration: '64800000000000', + end: DATE_1970, + }, + }) + ); + expect(alertingEventLogger.logAlert).toHaveBeenNthCalledWith( + 2, + generateAlertOpts({ + action: EVENT_LOG_ACTIONS.activeInstance, + group: 'default', + state: { bar: false, start: DATE_1969, duration: MOCK_DURATION }, + }) + ); + expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith(1, generateActionOpts({})); + expect(alertingEventLogger.logAction).toHaveBeenNthCalledWith( + 2, + generateActionOpts({ id: '2', alertId: '2', alertGroup: 'recovered', uuid: '222-222' }) + ); - expect(enqueueFunction).toHaveBeenCalledTimes(isBulk ? 1 : 2); - expect(enqueueFunction).toHaveBeenCalledWith( - isBulk - ? [ - generateEnqueueFunctionInput({ isBulk: false, id: '1', foo: true }), - generateEnqueueFunctionInput({ - isBulk: false, - id: '2', - isResolved: true, - uuid: '222-222', - }), - ] - : generateEnqueueFunctionInput({ isBulk: false, id: '1', foo: true }) - ); - expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); - jest.resetAllMocks(); - } - ); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith([ + generateEnqueueFunctionInput({ isBulk: false, id: '1', foo: true }), + generateEnqueueFunctionInput({ + isBulk: false, + id: '2', + isResolved: true, + uuid: '222-222', + }), + ]); + expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); + jest.resetAllMocks(); + }); - test.each(ephemeralTestParams)( - "should skip alertInstances which weren't active on the previous execution %s", - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction, isBulk) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(mockRunNowResponse); + test("should skip alertInstances which weren't active on the previous execution", async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); - ruleType.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string, - RuleAlertData - >) => { - executorServices.alertFactory.create('1').scheduleActions('default'); + ruleType.executor.mockImplementation( + async ({ + services: executorServices, + }: RuleExecutorOptions< + RuleTypeParams, + RuleTypeState, + AlertInstanceState, + AlertInstanceContext, + string, + RuleAlertData + >) => { + executorServices.alertFactory.create('1').scheduleActions('default'); - // create an instance, but don't schedule any actions, so it doesn't go active - executorServices.alertFactory.create('3'); - return { state: {} }; - } - ); - const taskRunner = new TaskRunner({ - ruleType, - internalSavedObjectsRepository, - taskInstance: { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { meta: {}, state: { bar: false } }, - '2': { meta: {}, state: { bar: false } }, - }, + // create an instance, but don't schedule any actions, so it doesn't go active + executorServices.alertFactory.create('3'); + return { state: {} }; + } + ); + const taskRunner = new TaskRunner({ + ruleType, + internalSavedObjectsRepository, + taskInstance: { + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '1': { meta: {}, state: { bar: false } }, + '2': { meta: {}, state: { bar: false } }, }, }, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - }); - expect(AlertingEventLogger).toHaveBeenCalled(); - - mockGetAlertFromRaw.mockReturnValue(mockedRuleTypeSavedObject as Rule); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - const runnerResult = await taskRunner.run(); - expect(runnerResult.state.alertInstances).toEqual( - generateAlertInstance({ - id: 1, - flappingHistory: [false], - }) - ); + }, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + }); + expect(AlertingEventLogger).toHaveBeenCalled(); - expect(logger.debug).toHaveBeenCalledWith( - `rule test:1: '${RULE_NAME}' has 1 active alerts: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]`, - { tags: ['1', 'test'] } - ); + mockGetAlertFromRaw.mockReturnValue(mockedRuleTypeSavedObject as Rule); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + const runnerResult = await taskRunner.run(); + expect(runnerResult.state.alertInstances).toEqual( + generateAlertInstance({ + id: 1, + flappingHistory: [false], + }) + ); - expect(logger.debug).nthCalledWith( - 3, - `rule test:1: '${RULE_NAME}' has 1 recovered alerts: [\"2\"]`, - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 4, - `deprecated ruleRunStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}`, - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 5, - 'ruleRunStatus for test:1: {"outcome":"succeeded","outcomeOrder":0,"outcomeMsg":null,"warning":null,"alertsCount":{"active":1,"new":0,"recovered":1,"ignored":0}}', - { tags: ['1', 'test'] } - ); - expect(logger.debug).nthCalledWith( - 6, - `ruleRunMetrics for test:1: {"numSearches":3,"totalSearchDurationMs":23423,"esSearchDurationMs":33,"numberOfTriggeredActions":2,"numberOfGeneratedActions":2,"numberOfActiveAlerts":1,"numberOfRecoveredAlerts":1,"numberOfNewAlerts":0,"numberOfDelayedAlerts":0,"hasReachedAlertLimit":false,"hasReachedQueuedActionsLimit":false,"triggeredActionsStatus":"complete"}`, - { tags: ['1', 'test'] } - ); + expect(logger.debug).toHaveBeenCalledWith( + `rule test:1: '${RULE_NAME}' has 1 active alerts: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]`, + { tags: ['1', 'test'] } + ); - testAlertingEventLogCalls({ - activeAlerts: 1, - recoveredAlerts: 1, - triggeredActions: 2, - generatedActions: 2, - status: 'active', - logAlert: 2, - logAction: 2, - }); + expect(logger.debug).nthCalledWith( + 3, + `rule test:1: '${RULE_NAME}' has 1 recovered alerts: [\"2\"]`, + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 4, + `deprecated ruleRunStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}`, + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 5, + 'ruleRunStatus for test:1: {"outcome":"succeeded","outcomeOrder":0,"outcomeMsg":null,"warning":null,"alertsCount":{"active":1,"new":0,"recovered":1,"ignored":0}}', + { tags: ['1', 'test'] } + ); + expect(logger.debug).nthCalledWith( + 6, + `ruleRunMetrics for test:1: {"numSearches":3,"totalSearchDurationMs":23423,"esSearchDurationMs":33,"numberOfTriggeredActions":2,"numberOfGeneratedActions":2,"numberOfActiveAlerts":1,"numberOfRecoveredAlerts":1,"numberOfNewAlerts":0,"numberOfDelayedAlerts":0,"hasReachedAlertLimit":false,"hasReachedQueuedActionsLimit":false,"triggeredActionsStatus":"complete"}`, + { tags: ['1', 'test'] } + ); - expect(enqueueFunction).toHaveBeenCalledTimes(isBulk ? 1 : 2); - if (isBulk) { - expect((enqueueFunction as jest.Mock).mock.calls[0][0][0].id).toEqual('1'); - expect((enqueueFunction as jest.Mock).mock.calls[0][0][1].id).toEqual('2'); - } else { - expect((enqueueFunction as jest.Mock).mock.calls[0][0].id).toEqual('1'); - expect((enqueueFunction as jest.Mock).mock.calls[1][0].id).toEqual('2'); - } - expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); - } - ); + testAlertingEventLogCalls({ + activeAlerts: 1, + recoveredAlerts: 1, + triggeredActions: 2, + generatedActions: 2, + status: 'active', + logAlert: 2, + logAction: 2, + }); - test.each(ephemeralTestParams)( - 'fire actions under a custom recovery group when specified on an alert type for alertInstances which are in the recovered state %s', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction, isBulk) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + expect((actionsClient.bulkEnqueueExecution as jest.Mock).mock.calls[0][0][0].id).toEqual('1'); + expect((actionsClient.bulkEnqueueExecution as jest.Mock).mock.calls[0][0][1].id).toEqual('2'); + expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); + }); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(mockRunNowResponse); + test('fire actions under a custom recovery group when specified on an alert type for alertInstances which are in the recovered state', async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); - const recoveryActionGroup = { - id: 'customRecovered', - name: 'Custom Recovered', - }; - const ruleTypeWithCustomRecovery = { - ...ruleType, - recoveryActionGroup, - actionGroups: [{ id: 'default', name: 'Default' }, recoveryActionGroup], - }; + const recoveryActionGroup = { + id: 'customRecovered', + name: 'Custom Recovered', + }; + const ruleTypeWithCustomRecovery = { + ...ruleType, + recoveryActionGroup, + actionGroups: [{ id: 'default', name: 'Default' }, recoveryActionGroup], + }; - ruleTypeWithCustomRecovery.executor.mockImplementation( - async ({ - services: executorServices, - }: RuleExecutorOptions< - RuleTypeParams, - RuleTypeState, - AlertInstanceState, - AlertInstanceContext, - string, - RuleAlertData - >) => { - executorServices.alertFactory.create('1').scheduleActions('default'); - return { state: {} }; - } - ); - const taskRunner = new TaskRunner({ - ruleType: ruleTypeWithCustomRecovery, - internalSavedObjectsRepository, - taskInstance: { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { meta: {}, state: { bar: false } }, - '2': { meta: {}, state: { bar: false } }, - }, + ruleTypeWithCustomRecovery.executor.mockImplementation( + async ({ + services: executorServices, + }: RuleExecutorOptions< + RuleTypeParams, + RuleTypeState, + AlertInstanceState, + AlertInstanceContext, + string, + RuleAlertData + >) => { + executorServices.alertFactory.create('1').scheduleActions('default'); + return { state: {} }; + } + ); + const taskRunner = new TaskRunner({ + ruleType: ruleTypeWithCustomRecovery, + internalSavedObjectsRepository, + taskInstance: { + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '1': { meta: {}, state: { bar: false } }, + '2': { meta: {}, state: { bar: false } }, }, }, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - }); - expect(AlertingEventLogger).toHaveBeenCalled(); + }, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + }); + expect(AlertingEventLogger).toHaveBeenCalled(); - mockGetAlertFromRaw.mockReturnValue({ - ...(mockedRuleTypeSavedObject as Rule), - actions: [ - { - group: 'default', - id: '1', - actionTypeId: 'action', - params: { - foo: true, - }, - uuid: '111-111', + mockGetAlertFromRaw.mockReturnValue({ + ...(mockedRuleTypeSavedObject as Rule), + actions: [ + { + group: 'default', + id: '1', + actionTypeId: 'action', + params: { + foo: true, }, - { - group: recoveryActionGroup.id, - id: '2', - actionTypeId: 'action', - params: { - isResolved: true, - }, - uuid: '222-222', + uuid: '111-111', + }, + { + group: recoveryActionGroup.id, + id: '2', + actionTypeId: 'action', + params: { + isResolved: true, }, - ], - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - const runnerResult = await taskRunner.run(); - expect(runnerResult.state.alertInstances).toEqual( - generateAlertInstance({ - id: 1, - flappingHistory: [false], - }) - ); + uuid: '222-222', + }, + ], + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + const runnerResult = await taskRunner.run(); + expect(runnerResult.state.alertInstances).toEqual( + generateAlertInstance({ + id: 1, + flappingHistory: [false], + }) + ); - testAlertingEventLogCalls({ - ruleTypeDef: ruleTypeWithCustomRecovery, - activeAlerts: 1, - recoveredAlerts: 1, - triggeredActions: 2, - generatedActions: 2, - status: 'active', - logAlert: 2, - logAction: 2, - }); + testAlertingEventLogCalls({ + ruleTypeDef: ruleTypeWithCustomRecovery, + activeAlerts: 1, + recoveredAlerts: 1, + triggeredActions: 2, + generatedActions: 2, + status: 'active', + logAlert: 2, + logAction: 2, + }); - expect(enqueueFunction).toHaveBeenCalledTimes(isBulk ? 1 : 2); - expect(enqueueFunction).toHaveBeenCalledWith( - isBulk - ? [ - generateEnqueueFunctionInput({ isBulk: false, id: '1', foo: true }), - generateEnqueueFunctionInput({ - isBulk: false, - id: '2', - isResolved: true, - uuid: '222-222', - }), - ] - : generateEnqueueFunctionInput({ isBulk: false, id: '1', foo: true }) - ); - expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); - } - ); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith([ + generateEnqueueFunctionInput({ isBulk: false, id: '1', foo: true }), + generateEnqueueFunctionInput({ + isBulk: false, + id: '2', + isResolved: true, + uuid: '222-222', + }), + ]); + expect(mockUsageCounter.incrementCounter).not.toHaveBeenCalled(); + }); - test.each(ephemeralTestParams)( - 'triggers summary actions (Per rule run)', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction, isBulk) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(mockRunNowResponse); - ruleType.executor.mockImplementation(async () => { - return { state: {} }; - }); + test('triggers summary actions (Per rule run)', async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); + ruleType.executor.mockImplementation(async () => { + return { state: {} }; + }); - alertsClient.getProcessedAlerts.mockReturnValue({}); - alertsClient.getSummarizedAlerts.mockResolvedValue({ - new: { - count: 1, - data: [mockAAD], - }, - ongoing: { count: 0, data: [] }, - recovered: { count: 0, data: [] }, - }); - alertsService.createAlertsClient.mockImplementation(() => alertsClient); + alertsClient.getProcessedAlerts.mockReturnValue({}); + alertsClient.getSummarizedAlerts.mockResolvedValue({ + new: { + count: 1, + data: [mockAAD], + }, + ongoing: { count: 0, data: [] }, + recovered: { count: 0, data: [] }, + }); + alertsService.createAlertsClient.mockImplementation(() => alertsClient); - const taskRunner = new TaskRunner({ - ruleType, - internalSavedObjectsRepository, - taskInstance: mockedTaskInstance, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - }); - expect(AlertingEventLogger).toHaveBeenCalledTimes(1); + const taskRunner = new TaskRunner({ + ruleType, + internalSavedObjectsRepository, + taskInstance: mockedTaskInstance, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + }); + expect(AlertingEventLogger).toHaveBeenCalledTimes(1); - mockGetAlertFromRaw.mockReturnValue({ - ...(mockedRuleTypeSavedObject as Rule), - actions: [ - { - group: 'default', - id: '1', - actionTypeId: 'slack', - frequency: { - notifyWhen: 'onActiveAlert', - summary: true, - throttle: null, - }, - params: { - foo: true, - }, - uuid: '111-111', + mockGetAlertFromRaw.mockReturnValue({ + ...(mockedRuleTypeSavedObject as Rule), + actions: [ + { + group: 'default', + id: '1', + actionTypeId: 'slack', + frequency: { + notifyWhen: 'onActiveAlert', + summary: true, + throttle: null, }, - ], - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - await taskRunner.run(); + params: { + foo: true, + }, + uuid: '111-111', + }, + ], + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + await taskRunner.run(); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - expect(enqueueFunction).toHaveBeenCalledWith( - generateEnqueueFunctionInput({ isBulk, id: '1', foo: true, actionTypeId: 'slack' }) - ); - } - ); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith( + generateEnqueueFunctionInput({ isBulk: true, id: '1', foo: true, actionTypeId: 'slack' }) + ); + }); - test.each(ephemeralTestParams)( - 'triggers summary actions (Custom Frequency)', - async (nameExtension, customTaskRunnerFactoryInitializerParams, enqueueFunction, isBulk) => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(mockRunNowResponse); - ruleType.executor.mockImplementation(async () => { - return { state: {} }; - }); - alertsClient.getProcessedAlerts.mockReturnValue({}); - alertsClient.getSummarizedAlerts.mockResolvedValue({ - new: { - count: 1, - data: [mockAAD], - }, - ongoing: { count: 0, data: [] }, - recovered: { count: 0, data: [] }, - }); + test('triggers summary actions (Custom Frequency)', async () => { + taskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue(true); + taskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue(true); + ruleType.executor.mockImplementation(async () => { + return { state: {} }; + }); + alertsClient.getProcessedAlerts.mockReturnValue({}); + alertsClient.getSummarizedAlerts.mockResolvedValue({ + new: { + count: 1, + data: [mockAAD], + }, + ongoing: { count: 0, data: [] }, + recovered: { count: 0, data: [] }, + }); - alertsClient.getAlertsToSerialize.mockResolvedValueOnce({ state: {}, meta: {} }); - alertsService.createAlertsClient.mockImplementation(() => alertsClient); + alertsClient.getAlertsToSerialize.mockResolvedValueOnce({ state: {}, meta: {} }); + alertsService.createAlertsClient.mockImplementation(() => alertsClient); - const taskRunner = new TaskRunner({ - ruleType, - internalSavedObjectsRepository, - taskInstance: mockedTaskInstance, - context: customTaskRunnerFactoryInitializerParams, - inMemoryMetrics, - }); - expect(AlertingEventLogger).toHaveBeenCalledTimes(1); + const taskRunner = new TaskRunner({ + ruleType, + internalSavedObjectsRepository, + taskInstance: mockedTaskInstance, + context: taskRunnerFactoryInitializerParams, + inMemoryMetrics, + }); + expect(AlertingEventLogger).toHaveBeenCalledTimes(1); - mockGetAlertFromRaw.mockReturnValue({ - ...(mockedRuleTypeSavedObject as Rule), - actions: [ - { - group: 'default', - id: '1', - actionTypeId: 'slack', - frequency: { - notifyWhen: 'onThrottleInterval', - summary: true, - throttle: '1h', - }, - params: { - foo: true, - }, - uuid: '111-111', + mockGetAlertFromRaw.mockReturnValue({ + ...(mockedRuleTypeSavedObject as Rule), + actions: [ + { + group: 'default', + id: '1', + actionTypeId: 'slack', + frequency: { + notifyWhen: 'onThrottleInterval', + summary: true, + throttle: '1h', }, - ], - }); + params: { + foo: true, + }, + uuid: '111-111', + }, + ], + }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); - const result = await taskRunner.run(); - - expect(alertsClient.getSummarizedAlerts).toHaveBeenCalledWith({ - start: new Date('1969-12-31T23:00:00.000Z'), - end: new Date(DATE_1970), - ruleId: '1', - spaceId: 'default', - excludedAlertInstanceIds: [], - }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue(mockedRawRuleSO); + const result = await taskRunner.run(); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - expect(enqueueFunction).toHaveBeenCalledWith( - generateEnqueueFunctionInput({ isBulk, id: '1', foo: true, actionTypeId: 'slack' }) - ); - expect(result.state.summaryActions).toEqual({ - '111-111': { date: new Date(DATE_1970).toISOString() }, - }); - } - ); + expect(alertsClient.getSummarizedAlerts).toHaveBeenCalledWith({ + start: new Date('1969-12-31T23:00:00.000Z'), + end: new Date(DATE_1970), + ruleId: '1', + spaceId: 'default', + excludedAlertInstanceIds: [], + }); + + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); + expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith( + generateEnqueueFunctionInput({ isBulk: true, id: '1', foo: true, actionTypeId: 'slack' }) + ); + expect(result.state.summaryActions).toEqual({ + '111-111': { date: new Date(DATE_1970).toISOString() }, + }); + }); test('persists alertInstances passed in from state, only if they are scheduled for execution', async () => { ruleType.executor.mockImplementation( @@ -2629,7 +2505,6 @@ describe('Task Runner', () => { }, context: { ...taskRunnerFactoryInitializerParams, - supportsEphemeralTasks: true, }, inMemoryMetrics, }); diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner_alerts_client.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner_alerts_client.test.ts index ed8e4a1259e6c..3d0cd5ab05059 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner_alerts_client.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner_alerts_client.test.ts @@ -216,13 +216,11 @@ describe('Task Runner', () => { logger, maintenanceWindowsService, maxAlerts: 1000, - maxEphemeralActionsPerRule: 10, ruleTypeRegistry, rulesSettingsService, savedObjects: savedObjectsService, share: {} as SharePluginStart, spaceIdToNamespace: jest.fn().mockReturnValue(undefined), - supportsEphemeralTasks: false, uiSettings: uiSettingsService, usageCounter: mockUsageCounter, isServerless: false, diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner_cancel.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner_cancel.test.ts index 066cff2944f26..54faa13de8352 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner_cancel.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner_cancel.test.ts @@ -149,13 +149,11 @@ describe('Task Runner Cancel', () => { logger, maintenanceWindowsService, maxAlerts: 1000, - maxEphemeralActionsPerRule: 10, ruleTypeRegistry, rulesSettingsService, savedObjects: savedObjectsService, share: {} as SharePluginStart, spaceIdToNamespace: jest.fn().mockReturnValue(undefined), - supportsEphemeralTasks: false, uiSettings: uiSettingsService, usageCounter: mockUsageCounter, isServerless: false, diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner_factory.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner_factory.test.ts index 7aa0105f7c06e..94acd3a0b2db6 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner_factory.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner_factory.test.ts @@ -120,13 +120,11 @@ describe('Task Runner Factory', () => { logger: loggingSystemMock.create().get(), maintenanceWindowsService, maxAlerts: 1000, - maxEphemeralActionsPerRule: 10, ruleTypeRegistry: ruleTypeRegistryMock.create(), rulesSettingsService, savedObjects: savedObjectsService, share: {} as SharePluginStart, spaceIdToNamespace: jest.fn().mockReturnValue(undefined), - supportsEphemeralTasks: true, uiSettings: uiSettingsService, usageCounter: mockUsageCounter, isServerless: false, diff --git a/x-pack/plugins/alerting/server/task_runner/types.ts b/x-pack/plugins/alerting/server/task_runner/types.ts index b401155ab06d7..f3e08aff2c3b7 100644 --- a/x-pack/plugins/alerting/server/task_runner/types.ts +++ b/x-pack/plugins/alerting/server/task_runner/types.ts @@ -172,13 +172,11 @@ export interface TaskRunnerContext { logger: Logger; maintenanceWindowsService: MaintenanceWindowsService; maxAlerts: number; - maxEphemeralActionsPerRule: number; ruleTypeRegistry: RuleTypeRegistry; rulesSettingsService: RulesSettingsService; savedObjects: SavedObjectsServiceStart; share: SharePluginStart; spaceIdToNamespace: SpaceIdToNamespaceFunction; - supportsEphemeralTasks: boolean; uiSettings: UiSettingsServiceStart; usageCounter?: UsageCounter; isServerless: boolean; diff --git a/x-pack/plugins/alerting/server/test_utils/index.ts b/x-pack/plugins/alerting/server/test_utils/index.ts index 036454f2f80c6..401225f171f06 100644 --- a/x-pack/plugins/alerting/server/test_utils/index.ts +++ b/x-pack/plugins/alerting/server/test_utils/index.ts @@ -57,7 +57,6 @@ export function generateAlertingConfig(): AlertingConfig { interval: '5m', removalDelay: '1h', }, - maxEphemeralActionsPerAlert: 10, cancelAlertsOnRuleTimeout: true, rules: { maxScheduledPerMinute: 10000, diff --git a/x-pack/test/alerting_api_integration/common/config.ts b/x-pack/test/alerting_api_integration/common/config.ts index b8a576f99b8d0..04d6a1c48b98e 100644 --- a/x-pack/test/alerting_api_integration/common/config.ts +++ b/x-pack/test/alerting_api_integration/common/config.ts @@ -217,7 +217,6 @@ export function createTestConfig(name: string, options: CreateTestConfigOptions) ...emailSettings, ...maxScheduledPerMinuteSettings, '--xpack.eventLog.logEntries=true', - '--xpack.task_manager.ephemeral_tasks.enabled=false', `--xpack.task_manager.unsafe.exclude_task_types=${JSON.stringify([ 'actions:test.excluded', ])}`, diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/ephemeral.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/ephemeral.ts deleted file mode 100644 index 51149a3008ff0..0000000000000 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/ephemeral.ts +++ /dev/null @@ -1,124 +0,0 @@ -/* - * 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 expect from '@kbn/expect'; -import { flatten } from 'lodash'; -import { IValidatedEvent } from '@kbn/event-log-plugin/server'; -import { DEFAULT_MAX_EPHEMERAL_ACTIONS_PER_ALERT } from '@kbn/alerting-plugin/server/config'; -import { ESTestIndexTool, ES_TEST_INDEX_NAME } from '@kbn/alerting-api-integration-helpers'; -import { Spaces } from '../../../scenarios'; -import { getUrlPrefix, ObjectRemover, getTestRuleData, getEventLog } from '../../../../common/lib'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -// eslint-disable-next-line import/no-default-export -export default function createNotifyWhenTests({ getService }: FtrProviderContext) { - const supertest = getService('supertest'); - const retry = getService('retry'); - const es = getService('es'); - - const esTestIndexTool = new ESTestIndexTool(es, retry); - - describe('ephemeral', () => { - const objectRemover = new ObjectRemover(supertest); - - beforeEach(async () => { - await esTestIndexTool.destroy(); - await esTestIndexTool.setup(); - }); - afterEach(async () => await esTestIndexTool.destroy()); - after(async () => { - await objectRemover.removeAll(); - }); - - it('should execute all requests, when some will be ephemeral and some not', async () => { - const nonEphemeralTasks = 3; - const actionPromises = []; - for (let i = 0; i < DEFAULT_MAX_EPHEMERAL_ACTIONS_PER_ALERT + nonEphemeralTasks; i++) { - actionPromises.push( - supertest - .post(`${getUrlPrefix(Spaces.space1.id)}/api/actions/connector`) - .set('kbn-xsrf', 'foo') - .send({ - name: `My action${i}`, - connector_type_id: 'test.index-record', - config: { - unencrypted: `This value shouldn't get encrypted`, - }, - secrets: { - encrypted: 'This value should be encrypted', - }, - }) - .expect(200) - ); - } - const createdActions = await Promise.all(actionPromises); - createdActions.forEach((createdAction) => - objectRemover.add(Spaces.space1.id, createdAction.body.id, 'connector', 'actions') - ); - - const pattern = { - instance: [true, true, true, false, true, true], - }; - const alertData = getTestRuleData({ - rule_type_id: 'test.patternFiring', - params: { pattern }, - schedule: { interval: '1m' }, - throttle: null, - notify_when: 'onActiveAlert', - actions: createdActions.map((createdAction) => { - return { - id: createdAction.body.id, - group: 'default', - params: { - index: ES_TEST_INDEX_NAME, - reference: '', - message: 'test message', - }, - }; - }), - }); - const { body: createdAlert } = await supertest - .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerting/rule`) - .set('kbn-xsrf', 'foo') - .send(alertData) - .expect(200); - objectRemover.add(Spaces.space1.id, createdAlert.id, 'rule', 'alerting'); - - const events = flatten( - await Promise.all( - createdActions.map(async (createdAction) => { - return await retry.try(async () => { - return await getEventLog({ - getService, - spaceId: Spaces.space1.id, - type: 'action', - id: createdAction.body.id, - provider: 'actions', - actions: new Map([['execute', { gte: 1 }]]), - }); - }); - }) - ) - ); - - const executeActionsEvents = getEventsByAction(events, 'execute'); - expect(executeActionsEvents.length).equal( - nonEphemeralTasks + DEFAULT_MAX_EPHEMERAL_ACTIONS_PER_ALERT - ); - - const searchResult = await esTestIndexTool.search('action:test.index-record'); - // @ts-expect-error doesnt handle total: number - expect(searchResult.body.hits.total.value).equal( - nonEphemeralTasks + DEFAULT_MAX_EPHEMERAL_ACTIONS_PER_ALERT - ); - }); - }); -} - -function getEventsByAction(events: IValidatedEvent[], action: string) { - return events.filter((event) => event?.event?.action === action); -} diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/index.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/index.ts index 79dae86b6a8d5..1da03fbbcc54c 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/index.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/group4/index.ts @@ -18,7 +18,6 @@ export default function alertingTests({ loadTestFile, getService }: FtrProviderC loadTestFile(require.resolve('./builtin_alert_types')); loadTestFile(require.resolve('./mustache_templates.ts')); loadTestFile(require.resolve('./notify_when')); - loadTestFile(require.resolve('./ephemeral')); loadTestFile(require.resolve('./event_log_alerts')); loadTestFile(require.resolve('./snooze')); loadTestFile(require.resolve('./unsnooze'));