diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.es_field_types.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.es_field_types.md
index c5e01715534d1..ad762cae489c8 100644
--- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.es_field_types.md
+++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.es_field_types.md
@@ -43,4 +43,5 @@ export declare enum ES_FIELD_TYPES
| STRING | "string"
| |
| TEXT | "text"
| |
| TOKEN\_COUNT | "token_count"
| |
+| UNSIGNED\_LONG | "unsigned_long"
| |
diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.es_field_types.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.es_field_types.md
index d071955f4f522..545b7b9d27e10 100644
--- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.es_field_types.md
+++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.es_field_types.md
@@ -43,4 +43,5 @@ export declare enum ES_FIELD_TYPES
| STRING | "string"
| |
| TEXT | "text"
| |
| TOKEN\_COUNT | "token_count"
| |
+| UNSIGNED\_LONG | "unsigned_long"
| |
diff --git a/src/plugins/data/common/kbn_field_types/kbn_field_types.test.ts b/src/plugins/data/common/kbn_field_types/kbn_field_types.test.ts
index 6a2d6edd04692..dd1a9a7f689a9 100644
--- a/src/plugins/data/common/kbn_field_types/kbn_field_types.test.ts
+++ b/src/plugins/data/common/kbn_field_types/kbn_field_types.test.ts
@@ -66,6 +66,7 @@ describe('utils/kbn_field_types', () => {
test('returns the kbnFieldType name that matches the esType', () => {
expect(castEsToKbnFieldTypeName(ES_FIELD_TYPES.KEYWORD)).toBe('string');
expect(castEsToKbnFieldTypeName(ES_FIELD_TYPES.FLOAT)).toBe('number');
+ expect(castEsToKbnFieldTypeName(ES_FIELD_TYPES.UNSIGNED_LONG)).toBe('number');
});
test('returns unknown for unknown es types', () => {
diff --git a/src/plugins/data/common/kbn_field_types/kbn_field_types_factory.ts b/src/plugins/data/common/kbn_field_types/kbn_field_types_factory.ts
index b93ebcbbca9c8..373cdfda30607 100644
--- a/src/plugins/data/common/kbn_field_types/kbn_field_types_factory.ts
+++ b/src/plugins/data/common/kbn_field_types/kbn_field_types_factory.ts
@@ -48,6 +48,7 @@ export const createKbnFieldTypes = (): KbnFieldType[] => [
ES_FIELD_TYPES.DOUBLE,
ES_FIELD_TYPES.INTEGER,
ES_FIELD_TYPES.LONG,
+ ES_FIELD_TYPES.UNSIGNED_LONG,
ES_FIELD_TYPES.SHORT,
ES_FIELD_TYPES.BYTE,
ES_FIELD_TYPES.TOKEN_COUNT,
diff --git a/src/plugins/data/common/kbn_field_types/types.ts b/src/plugins/data/common/kbn_field_types/types.ts
index acd7a36b01fb3..ba9fd3e70b315 100644
--- a/src/plugins/data/common/kbn_field_types/types.ts
+++ b/src/plugins/data/common/kbn_field_types/types.ts
@@ -52,6 +52,7 @@ export enum ES_FIELD_TYPES {
INTEGER = 'integer',
LONG = 'long',
SHORT = 'short',
+ UNSIGNED_LONG = 'unsigned_long',
NESTED = 'nested',
BYTE = 'byte',
diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md
index 688509a0758c0..1390b28ec830d 100644
--- a/src/plugins/data/public/public.api.md
+++ b/src/plugins/data/public/public.api.md
@@ -514,7 +514,9 @@ export enum ES_FIELD_TYPES {
// (undocumented)
TOKEN_COUNT = "token_count",
// (undocumented)
- _TYPE = "_type"
+ _TYPE = "_type",
+ // (undocumented)
+ UNSIGNED_LONG = "unsigned_long"
}
// Warning: (ae-missing-release-tag) "ES_SEARCH_STRATEGY" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md
index add923ad2da47..65313adfc0e0f 100644
--- a/src/plugins/data/server/server.api.md
+++ b/src/plugins/data/server/server.api.md
@@ -211,7 +211,9 @@ export enum ES_FIELD_TYPES {
// (undocumented)
TOKEN_COUNT = "token_count",
// (undocumented)
- _TYPE = "_type"
+ _TYPE = "_type",
+ // (undocumented)
+ UNSIGNED_LONG = "unsigned_long"
}
// Warning: (ae-missing-release-tag) "ES_SEARCH_STRATEGY" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
diff --git a/x-pack/plugins/actions/server/action_type_registry.test.ts b/x-pack/plugins/actions/server/action_type_registry.test.ts
index e641b81189b93..95e7784e51acf 100644
--- a/x-pack/plugins/actions/server/action_type_registry.test.ts
+++ b/x-pack/plugins/actions/server/action_type_registry.test.ts
@@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/
-import { taskManagerMock } from '../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../task_manager/server/mocks';
import { ActionTypeRegistry, ActionTypeRegistryOpts } from './action_type_registry';
import { ActionType, ExecutorType } from './types';
import { ActionExecutor, ExecutorError, ILicenseState, TaskRunnerFactory } from './lib';
@@ -13,7 +13,7 @@ import { licenseStateMock } from './lib/license_state.mock';
import { ActionsConfigurationUtilities } from './actions_config';
import { licensingMock } from '../../licensing/server/mocks';
-const mockTaskManager = taskManagerMock.setup();
+const mockTaskManager = taskManagerMock.createSetup();
let mockedLicenseState: jest.Mocked;
let mockedActionsConfig: jest.Mocked;
let actionTypeRegistryParams: ActionTypeRegistryOpts;
@@ -66,7 +66,6 @@ describe('register()', () => {
"getRetry": [Function],
"maxAttempts": 1,
"title": "My action type",
- "type": "actions:my-action-type",
},
},
]
diff --git a/x-pack/plugins/actions/server/action_type_registry.ts b/x-pack/plugins/actions/server/action_type_registry.ts
index b93d4a6e78ac6..cacf7166b96ba 100644
--- a/x-pack/plugins/actions/server/action_type_registry.ts
+++ b/x-pack/plugins/actions/server/action_type_registry.ts
@@ -125,7 +125,6 @@ export class ActionTypeRegistry {
this.taskManager.registerTaskDefinitions({
[`actions:${actionType.id}`]: {
title: actionType.name,
- type: `actions:${actionType.id}`,
maxAttempts: actionType.maxAttempts || 1,
getRetry(attempts: number, error: unknown) {
if (error instanceof ExecutorError) {
diff --git a/x-pack/plugins/actions/server/actions_client.test.ts b/x-pack/plugins/actions/server/actions_client.test.ts
index 2b6aec42e0d21..171f8d4b0b1d4 100644
--- a/x-pack/plugins/actions/server/actions_client.test.ts
+++ b/x-pack/plugins/actions/server/actions_client.test.ts
@@ -10,7 +10,7 @@ import { ActionTypeRegistry, ActionTypeRegistryOpts } from './action_type_regist
import { ActionsClient } from './actions_client';
import { ExecutorType, ActionType } from './types';
import { ActionExecutor, TaskRunnerFactory, ILicenseState } from './lib';
-import { taskManagerMock } from '../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../task_manager/server/mocks';
import { actionsConfigMock } from './actions_config.mock';
import { getActionsConfigurationUtilities } from './actions_config';
import { licenseStateMock } from './lib/license_state.mock';
@@ -34,7 +34,7 @@ const authorization = actionsAuthorizationMock.create();
const executionEnqueuer = jest.fn();
const request = {} as KibanaRequest;
-const mockTaskManager = taskManagerMock.setup();
+const mockTaskManager = taskManagerMock.createSetup();
let actionsClient: ActionsClient;
let mockedLicenseState: jest.Mocked;
diff --git a/x-pack/plugins/actions/server/builtin_action_types/index.test.ts b/x-pack/plugins/actions/server/builtin_action_types/index.test.ts
index f7882849708e5..a9d1e28182b29 100644
--- a/x-pack/plugins/actions/server/builtin_action_types/index.test.ts
+++ b/x-pack/plugins/actions/server/builtin_action_types/index.test.ts
@@ -6,7 +6,7 @@
import { ActionExecutor, TaskRunnerFactory } from '../lib';
import { ActionTypeRegistry } from '../action_type_registry';
-import { taskManagerMock } from '../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../task_manager/server/mocks';
import { registerBuiltInActionTypes } from './index';
import { Logger } from '../../../../../src/core/server';
import { loggingSystemMock } from '../../../../../src/core/server/mocks';
@@ -22,8 +22,8 @@ export function createActionTypeRegistry(): {
} {
const logger = loggingSystemMock.create().get() as jest.Mocked;
const actionTypeRegistry = new ActionTypeRegistry({
+ taskManager: taskManagerMock.createSetup(),
licensing: licensingMock.createSetup(),
- taskManager: taskManagerMock.setup(),
taskRunnerFactory: new TaskRunnerFactory(
new ActionExecutor({ isESOUsingEphemeralEncryptionKey: false })
),
diff --git a/x-pack/plugins/actions/server/create_execute_function.test.ts b/x-pack/plugins/actions/server/create_execute_function.test.ts
index 33e78ee444cd0..ed06bd888f919 100644
--- a/x-pack/plugins/actions/server/create_execute_function.test.ts
+++ b/x-pack/plugins/actions/server/create_execute_function.test.ts
@@ -6,7 +6,7 @@
import { KibanaRequest } from 'src/core/server';
import uuid from 'uuid';
-import { taskManagerMock } from '../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../task_manager/server/mocks';
import { createExecutionEnqueuerFunction } from './create_execute_function';
import { savedObjectsClientMock } from '../../../../src/core/server/mocks';
import { actionTypeRegistryMock } from './action_type_registry.mock';
@@ -15,7 +15,7 @@ import {
asSavedObjectExecutionSource,
} from './lib/action_execution_source';
-const mockTaskManager = taskManagerMock.start();
+const mockTaskManager = taskManagerMock.createStart();
const savedObjectsClient = savedObjectsClientMock.create();
const request = {} as KibanaRequest;
diff --git a/x-pack/plugins/actions/server/usage/actions_usage_collector.test.ts b/x-pack/plugins/actions/server/usage/actions_usage_collector.test.ts
index 2e2944aab425c..0e6c2ff37eb02 100644
--- a/x-pack/plugins/actions/server/usage/actions_usage_collector.test.ts
+++ b/x-pack/plugins/actions/server/usage/actions_usage_collector.test.ts
@@ -6,9 +6,9 @@
import { UsageCollectionSetup } from 'src/plugins/usage_collection/server';
import { registerActionsUsageCollector } from './actions_usage_collector';
-import { taskManagerMock } from '../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../task_manager/server/mocks';
-const mockTaskManagerStart = taskManagerMock.start();
+const mockTaskManagerStart = taskManagerMock.createStart();
beforeEach(() => jest.resetAllMocks());
diff --git a/x-pack/plugins/actions/server/usage/task.ts b/x-pack/plugins/actions/server/usage/task.ts
index efa695cdc2667..f7af480aa9fb3 100644
--- a/x-pack/plugins/actions/server/usage/task.ts
+++ b/x-pack/plugins/actions/server/usage/task.ts
@@ -39,7 +39,6 @@ function registerActionsTelemetryTask(
taskManager.registerTaskDefinitions({
[TELEMETRY_TASK_TYPE]: {
title: 'Actions usage fetch task',
- type: TELEMETRY_TASK_TYPE,
timeout: '5m',
createTaskRunner: telemetryTaskRunner(logger, core, kibanaIndex),
},
diff --git a/x-pack/plugins/alerts/server/alert_type_registry.test.ts b/x-pack/plugins/alerts/server/alert_type_registry.test.ts
index 048cc3d5a4440..9e1545bae5384 100644
--- a/x-pack/plugins/alerts/server/alert_type_registry.test.ts
+++ b/x-pack/plugins/alerts/server/alert_type_registry.test.ts
@@ -7,9 +7,9 @@
import { TaskRunnerFactory } from './task_runner';
import { AlertTypeRegistry } from './alert_type_registry';
import { AlertType } from './types';
-import { taskManagerMock } from '../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../task_manager/server/mocks';
-const taskManager = taskManagerMock.setup();
+const taskManager = taskManagerMock.createSetup();
const alertTypeRegistryParams = {
taskManager,
taskRunnerFactory: new TaskRunnerFactory(),
@@ -118,7 +118,6 @@ describe('register()', () => {
"alerting:test": Object {
"createTaskRunner": [Function],
"title": "Test",
- "type": "alerting:test",
},
},
]
diff --git a/x-pack/plugins/alerts/server/alert_type_registry.ts b/x-pack/plugins/alerts/server/alert_type_registry.ts
index 7f34803b05a81..0cd218571035a 100644
--- a/x-pack/plugins/alerts/server/alert_type_registry.ts
+++ b/x-pack/plugins/alerts/server/alert_type_registry.ts
@@ -86,7 +86,6 @@ export class AlertTypeRegistry {
this.taskManager.registerTaskDefinitions({
[`alerting:${alertType.id}`]: {
title: alertType.name,
- type: `alerting:${alertType.id}`,
createTaskRunner: (context: RunContext) =>
this.taskRunnerFactory.create({ ...alertType } as AlertType, context),
},
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/create.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/create.test.ts
index 56e868732e3fb..bce1af203fb0e 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/create.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/create.test.ts
@@ -6,7 +6,7 @@
import { schema } from '@kbn/config-schema';
import { AlertsClient, ConstructorOptions, CreateOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -16,7 +16,7 @@ import { ActionsAuthorization, ActionsClient } from '../../../../actions/server'
import { TaskStatus } from '../../../../task_manager/server';
import { getBeforeSetup, setGlobalDate } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/delete.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/delete.test.ts
index 1ebd9fc296b13..d9b253c3a56e8 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/delete.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/delete.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -14,7 +14,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/disable.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/disable.test.ts
index 2dd3da07234ce..d0557df622028 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/disable.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/disable.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -14,7 +14,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/enable.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/enable.test.ts
index b214d8ba697b1..f098bbcad8d05 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/enable.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/enable.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -15,7 +15,7 @@ import { ActionsAuthorization } from '../../../../actions/server';
import { TaskStatus } from '../../../../task_manager/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/find.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/find.test.ts
index bf55a2070d8fe..c1adaddc80d9e 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/find.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/find.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { nodeTypes } from '../../../../../../src/plugins/data/common';
@@ -16,7 +16,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup, setGlobalDate } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/get.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/get.test.ts
index 327a1fa23ef05..004230403de2e 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/get.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/get.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -14,7 +14,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup, setGlobalDate } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_instance_summary.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_instance_summary.test.ts
index 09212732b76e7..a53e49337f385 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_instance_summary.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_instance_summary.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -19,7 +19,7 @@ import { EventsFactory } from '../../lib/alert_instance_summary_from_event_log.t
import { RawAlert } from '../../types';
import { getBeforeSetup, mockedDateString, setGlobalDate } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
const eventLogClient = eventLogClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_state.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_state.test.ts
index 42e573aea347f..8b32f05f6d5a1 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_state.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/get_alert_state.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { TaskStatus } from '../../../../task_manager/server';
@@ -15,7 +15,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/lib.ts b/x-pack/plugins/alerts/server/alerts_client/tests/lib.ts
index 96e49e21b9045..5ebb4e90d4b50 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/lib.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/lib.ts
@@ -3,8 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
-// eslint-disable-next-line @kbn/eslint/no-restricted-paths
-import { TaskManager } from '../../../../task_manager/server/task_manager';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { IEventLogClient } from '../../../../event_log/server';
import { actionsClientMock } from '../../../../actions/server/mocks';
import { ConstructorOptions } from '../alerts_client';
@@ -41,9 +40,7 @@ export function setGlobalDate() {
export function getBeforeSetup(
alertsClientParams: jest.Mocked,
- taskManager: jest.Mocked<
- Pick
- >,
+ taskManager: ReturnType,
alertTypeRegistry: jest.Mocked>,
eventLogClient?: jest.Mocked
) {
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/list_alert_types.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/list_alert_types.test.ts
index 4337ed6c491d4..b2f5c5498f848 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/list_alert_types.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/list_alert_types.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -14,7 +14,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/mute_all.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/mute_all.test.ts
index 44ee6713f2560..88199dfd1f7b9 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/mute_all.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/mute_all.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -14,7 +14,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/mute_instance.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/mute_instance.test.ts
index dc9a1600a5776..cd7112b3551b3 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/mute_instance.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/mute_instance.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -14,7 +14,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/unmute_all.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/unmute_all.test.ts
index 45920db105c2a..07666c1cc6261 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/unmute_all.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/unmute_all.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -14,7 +14,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/unmute_instance.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/unmute_instance.test.ts
index 5604011501130..97711b8c14579 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/unmute_instance.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/unmute_instance.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -14,7 +14,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/update.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/update.test.ts
index 60b5b62954f05..1dcde6addb9bf 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/update.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/update.test.ts
@@ -7,7 +7,7 @@ import uuid from 'uuid';
import { schema } from '@kbn/config-schema';
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { IntervalSchedule } from '../../types';
@@ -19,7 +19,7 @@ import { ActionsAuthorization, ActionsClient } from '../../../../actions/server'
import { TaskStatus } from '../../../../task_manager/server';
import { getBeforeSetup, setGlobalDate } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client/tests/update_api_key.test.ts b/x-pack/plugins/alerts/server/alerts_client/tests/update_api_key.test.ts
index 97ddfa5e4adb4..1f3b567b2c031 100644
--- a/x-pack/plugins/alerts/server/alerts_client/tests/update_api_key.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client/tests/update_api_key.test.ts
@@ -5,7 +5,7 @@
*/
import { AlertsClient, ConstructorOptions } from '../alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../../../task_manager/server/mocks';
import { alertTypeRegistryMock } from '../../alert_type_registry.mock';
import { alertsAuthorizationMock } from '../../authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../../../encrypted_saved_objects/server/mocks';
@@ -14,7 +14,7 @@ import { AlertsAuthorization } from '../../authorization/alerts_authorization';
import { ActionsAuthorization } from '../../../../actions/server';
import { getBeforeSetup } from './lib';
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
const encryptedSavedObjects = encryptedSavedObjectsMock.createClient();
diff --git a/x-pack/plugins/alerts/server/alerts_client_conflict_retries.test.ts b/x-pack/plugins/alerts/server/alerts_client_conflict_retries.test.ts
index 1c5edb45c80fe..b1ac5ac4c6783 100644
--- a/x-pack/plugins/alerts/server/alerts_client_conflict_retries.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client_conflict_retries.test.ts
@@ -8,7 +8,7 @@ import { cloneDeep } from 'lodash';
import { AlertsClient, ConstructorOptions } from './alerts_client';
import { savedObjectsClientMock, loggingSystemMock } from '../../../../src/core/server/mocks';
-import { taskManagerMock } from '../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../task_manager/server/mocks';
import { alertTypeRegistryMock } from './alert_type_registry.mock';
import { alertsAuthorizationMock } from './authorization/alerts_authorization.mock';
import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/mocks';
@@ -25,7 +25,7 @@ const MockAlertId = 'alert-id';
const ConflictAfterRetries = RetryForConflictsAttempts + 1;
-const taskManager = taskManagerMock.start();
+const taskManager = taskManagerMock.createStart();
const alertTypeRegistry = alertTypeRegistryMock.create();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
diff --git a/x-pack/plugins/alerts/server/alerts_client_factory.test.ts b/x-pack/plugins/alerts/server/alerts_client_factory.test.ts
index d747efbb959d8..55c2f3ddd18a4 100644
--- a/x-pack/plugins/alerts/server/alerts_client_factory.test.ts
+++ b/x-pack/plugins/alerts/server/alerts_client_factory.test.ts
@@ -7,7 +7,7 @@
import { Request } from 'hapi';
import { AlertsClientFactory, AlertsClientFactoryOpts } from './alerts_client_factory';
import { alertTypeRegistryMock } from './alert_type_registry.mock';
-import { taskManagerMock } from '../../task_manager/server/task_manager.mock';
+import { taskManagerMock } from '../../task_manager/server/mocks';
import { KibanaRequest } from '../../../../src/core/server';
import {
savedObjectsClientMock,
@@ -35,7 +35,7 @@ const features = featuresPluginMock.createStart();
const securityPluginSetup = securityMock.createSetup();
const alertsClientFactoryParams: jest.Mocked = {
logger: loggingSystemMock.create().get(),
- taskManager: taskManagerMock.start(),
+ taskManager: taskManagerMock.createStart(),
alertTypeRegistry: alertTypeRegistryMock.create(),
getSpaceId: jest.fn(),
getSpace: jest.fn(),
diff --git a/x-pack/plugins/alerts/server/usage/alerts_usage_collector.test.ts b/x-pack/plugins/alerts/server/usage/alerts_usage_collector.test.ts
index b48d173ba36d9..a5f83bc393d4e 100644
--- a/x-pack/plugins/alerts/server/usage/alerts_usage_collector.test.ts
+++ b/x-pack/plugins/alerts/server/usage/alerts_usage_collector.test.ts
@@ -6,8 +6,8 @@
import { UsageCollectionSetup } from 'src/plugins/usage_collection/server';
import { registerAlertsUsageCollector } from './alerts_usage_collector';
-import { taskManagerMock } from '../../../task_manager/server/task_manager.mock';
-const taskManagerStart = taskManagerMock.start();
+import { taskManagerMock } from '../../../task_manager/server/mocks';
+const taskManagerStart = taskManagerMock.createStart();
beforeEach(() => jest.resetAllMocks());
diff --git a/x-pack/plugins/alerts/server/usage/task.ts b/x-pack/plugins/alerts/server/usage/task.ts
index daf3ac246adad..24ac15bbea78c 100644
--- a/x-pack/plugins/alerts/server/usage/task.ts
+++ b/x-pack/plugins/alerts/server/usage/task.ts
@@ -42,7 +42,6 @@ function registerAlertingTelemetryTask(
taskManager.registerTaskDefinitions({
[TELEMETRY_TASK_TYPE]: {
title: 'Alerting usage fetch task',
- type: TELEMETRY_TASK_TYPE,
timeout: '5m',
createTaskRunner: telemetryTaskRunner(logger, core, kibanaIndex),
},
diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts
index c93fdfc15fe3c..62fc16fb25053 100644
--- a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts
+++ b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts
@@ -49,7 +49,6 @@ export async function createApmTelemetry({
taskManager.registerTaskDefinitions({
[APM_TELEMETRY_TASK_NAME]: {
title: 'Collect APM usage',
- type: APM_TELEMETRY_TASK_NAME,
createTaskRunner: () => {
return {
run: async () => {
diff --git a/x-pack/plugins/lens/server/usage/task.ts b/x-pack/plugins/lens/server/usage/task.ts
index 9fee72b59b44c..83cdbd62f3484 100644
--- a/x-pack/plugins/lens/server/usage/task.ts
+++ b/x-pack/plugins/lens/server/usage/task.ts
@@ -48,7 +48,6 @@ function registerLensTelemetryTask(
taskManager.registerTaskDefinitions({
[TELEMETRY_TASK_TYPE]: {
title: 'Lens usage fetch task',
- type: TELEMETRY_TASK_TYPE,
timeout: '1m',
createTaskRunner: telemetryTaskRunner(logger, core, config),
},
diff --git a/x-pack/plugins/security/server/session_management/session_management_service.test.ts b/x-pack/plugins/security/server/session_management/session_management_service.test.ts
index 0328455fc8379..155cc0bdd58ff 100644
--- a/x-pack/plugins/security/server/session_management/session_management_service.test.ts
+++ b/x-pack/plugins/security/server/session_management/session_management_service.test.ts
@@ -50,7 +50,6 @@ describe('SessionManagementService', () => {
expect(mockTaskManager.registerTaskDefinitions).toHaveBeenCalledWith({
[SESSION_INDEX_CLEANUP_TASK_NAME]: {
title: 'Cleanup expired or invalid user sessions',
- type: SESSION_INDEX_CLEANUP_TASK_NAME,
createTaskRunner: expect.any(Function),
},
});
diff --git a/x-pack/plugins/security/server/session_management/session_management_service.ts b/x-pack/plugins/security/server/session_management/session_management_service.ts
index 60c0f7c23e959..fc2e85d683d58 100644
--- a/x-pack/plugins/security/server/session_management/session_management_service.ts
+++ b/x-pack/plugins/security/server/session_management/session_management_service.ts
@@ -78,7 +78,6 @@ export class SessionManagementService {
taskManager.registerTaskDefinitions({
[SESSION_INDEX_CLEANUP_TASK_NAME]: {
title: 'Cleanup expired or invalid user sessions',
- type: SESSION_INDEX_CLEANUP_TASK_NAME,
createTaskRunner: () => ({ run: () => this.sessionIndex.cleanUp() }),
},
});
diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts
index 02e57a71dcd94..0d78c90735ab3 100644
--- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts
+++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts
@@ -39,7 +39,6 @@ export class ManifestTask {
setupContract.taskManager.registerTaskDefinitions({
[ManifestTaskConstants.TYPE]: {
title: 'Security Solution Endpoint Exceptions Handler',
- type: ManifestTaskConstants.TYPE,
timeout: ManifestTaskConstants.TIMEOUT,
createTaskRunner: ({ taskInstance }: { taskInstance: ConcreteTaskInstance }) => {
return {
diff --git a/x-pack/plugins/task_manager/server/integration_tests/managed_configuration.test.ts b/x-pack/plugins/task_manager/server/integration_tests/managed_configuration.test.ts
index 443c811469002..11f6ccc881850 100644
--- a/x-pack/plugins/task_manager/server/integration_tests/managed_configuration.test.ts
+++ b/x-pack/plugins/task_manager/server/integration_tests/managed_configuration.test.ts
@@ -5,53 +5,47 @@
*/
import sinon from 'sinon';
-import { mockLogger } from '../test_utils';
-import { TaskManager } from '../task_manager';
import { savedObjectsRepositoryMock } from '../../../../../src/core/server/mocks';
-import {
- SavedObjectsSerializer,
- SavedObjectTypeRegistry,
- SavedObjectsErrorHelpers,
-} from '../../../../../src/core/server';
+import { SavedObjectsErrorHelpers, Logger } from '../../../../../src/core/server';
import { ADJUST_THROUGHPUT_INTERVAL } from '../lib/create_managed_configuration';
+import { TaskManagerPlugin, TaskManagerStartContract } from '../plugin';
+import { coreMock } from '../../../../../src/core/server/mocks';
+import { TaskManagerConfig } from '../config';
describe('managed configuration', () => {
- let taskManager: TaskManager;
+ let taskManagerStart: TaskManagerStartContract;
+ let logger: Logger;
+
let clock: sinon.SinonFakeTimers;
- const callAsInternalUser = jest.fn();
- const logger = mockLogger();
- const serializer = new SavedObjectsSerializer(new SavedObjectTypeRegistry());
const savedObjectsClient = savedObjectsRepositoryMock.create();
- const config = {
- enabled: true,
- max_workers: 10,
- index: 'foo',
- max_attempts: 9,
- poll_interval: 3000,
- max_poll_inactivity_cycles: 10,
- request_capacity: 1000,
- };
- beforeEach(() => {
+ beforeEach(async () => {
jest.resetAllMocks();
- callAsInternalUser.mockResolvedValue({ total: 0, updated: 0, version_conflicts: 0 });
clock = sinon.useFakeTimers();
- taskManager = new TaskManager({
- config,
- logger,
- serializer,
- callAsInternalUser,
- taskManagerId: 'some-uuid',
- savedObjectsRepository: savedObjectsClient,
+
+ const context = coreMock.createPluginInitializerContext({
+ enabled: true,
+ max_workers: 10,
+ index: 'foo',
+ max_attempts: 9,
+ poll_interval: 3000,
+ max_poll_inactivity_cycles: 10,
+ request_capacity: 1000,
});
- taskManager.registerTaskDefinitions({
+ logger = context.logger.get('taskManager');
+
+ const taskManager = new TaskManagerPlugin(context);
+ (await taskManager.setup(coreMock.createSetup())).registerTaskDefinitions({
foo: {
- type: 'foo',
title: 'Foo',
createTaskRunner: jest.fn(),
},
});
- taskManager.start();
+
+ const coreStart = coreMock.createStart();
+ coreStart.savedObjects.createInternalRepository.mockReturnValue(savedObjectsClient);
+ taskManagerStart = await taskManager.start(coreStart);
+
// force rxjs timers to fire when they are scheduled for setTimeout(0) as the
// sinon fake timers cause them to stall
clock.tick(0);
@@ -63,15 +57,17 @@ describe('managed configuration', () => {
savedObjectsClient.create.mockRejectedValueOnce(
SavedObjectsErrorHelpers.createTooManyRequestsError('a', 'b')
);
+
// Cause "too many requests" error to be thrown
await expect(
- taskManager.schedule({
+ taskManagerStart.schedule({
taskType: 'foo',
state: {},
params: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(`"Too Many Requests"`);
clock.tick(ADJUST_THROUGHPUT_INTERVAL);
+
expect(logger.warn).toHaveBeenCalledWith(
'Max workers configuration is temporarily reduced after Elasticsearch returned 1 "too many request" error(s).'
);
@@ -85,15 +81,17 @@ describe('managed configuration', () => {
savedObjectsClient.create.mockRejectedValueOnce(
SavedObjectsErrorHelpers.createTooManyRequestsError('a', 'b')
);
+
// Cause "too many requests" error to be thrown
await expect(
- taskManager.schedule({
+ taskManagerStart.schedule({
taskType: 'foo',
state: {},
params: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(`"Too Many Requests"`);
clock.tick(ADJUST_THROUGHPUT_INTERVAL);
+
expect(logger.warn).toHaveBeenCalledWith(
'Poll interval configuration is temporarily increased after Elasticsearch returned 1 "too many request" error(s).'
);
diff --git a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts
index c007b32338496..d6d776f970a32 100644
--- a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts
+++ b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts
@@ -4,9 +4,10 @@
* you may not use this file except in compliance with the Elastic License.
*/
+import { mockLogger } from '../test_utils';
+
import { createBuffer, Entity, OperationError, BulkOperation } from './bulk_operation_buffer';
import { mapErr, asOk, asErr, Ok, Err } from './result_type';
-import { mockLogger } from '../test_utils';
interface TaskInstance extends Entity {
attempts: number;
diff --git a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.ts b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.ts
index 57a14c2f8a56b..6df5b064f2792 100644
--- a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.ts
+++ b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.ts
@@ -8,7 +8,7 @@ import { map } from 'lodash';
import { Subject, race, from } from 'rxjs';
import { bufferWhen, filter, bufferCount, flatMap, mapTo, first } from 'rxjs/operators';
import { either, Result, asOk, asErr, Ok, Err } from './result_type';
-import { Logger } from '../types';
+import { Logger } from '../../../../../src/core/server';
export interface BufferOptions {
bufferMaxDuration?: number;
diff --git a/x-pack/plugins/task_manager/server/lib/correct_deprecated_fields.test.ts b/x-pack/plugins/task_manager/server/lib/correct_deprecated_fields.test.ts
index 408e8d36d3491..8c81e9b9c5b0a 100644
--- a/x-pack/plugins/task_manager/server/lib/correct_deprecated_fields.test.ts
+++ b/x-pack/plugins/task_manager/server/lib/correct_deprecated_fields.test.ts
@@ -4,8 +4,8 @@
* you may not use this file except in compliance with the Elastic License.
*/
-import { ensureDeprecatedFieldsAreCorrected } from './correct_deprecated_fields';
import { mockLogger } from '../test_utils';
+import { ensureDeprecatedFieldsAreCorrected } from './correct_deprecated_fields';
describe('ensureDeprecatedFieldsAreCorrected', () => {
test('doesnt change tasks without any schedule fields', async () => {
diff --git a/x-pack/plugins/task_manager/server/lib/correct_deprecated_fields.ts b/x-pack/plugins/task_manager/server/lib/correct_deprecated_fields.ts
index 2de95cbb8c2fa..9e5f4b7c143a2 100644
--- a/x-pack/plugins/task_manager/server/lib/correct_deprecated_fields.ts
+++ b/x-pack/plugins/task_manager/server/lib/correct_deprecated_fields.ts
@@ -5,7 +5,7 @@
*/
import { TaskInstance, TaskInstanceWithDeprecatedFields } from '../task';
-import { Logger } from '../types';
+import { Logger } from '../../../../../src/core/server';
export function ensureDeprecatedFieldsAreCorrected(
{ id, taskType, interval, schedule, ...taskInstance }: TaskInstanceWithDeprecatedFields,
diff --git a/x-pack/plugins/task_manager/server/lib/create_managed_configuration.test.ts b/x-pack/plugins/task_manager/server/lib/create_managed_configuration.test.ts
index b6b5cd003c5d4..6e1fc71f144a2 100644
--- a/x-pack/plugins/task_manager/server/lib/create_managed_configuration.test.ts
+++ b/x-pack/plugins/task_manager/server/lib/create_managed_configuration.test.ts
@@ -6,12 +6,12 @@
import sinon from 'sinon';
import { Subject } from 'rxjs';
-import { mockLogger } from '../test_utils';
import { SavedObjectsErrorHelpers } from '../../../../../src/core/server';
import {
createManagedConfiguration,
ADJUST_THROUGHPUT_INTERVAL,
} from './create_managed_configuration';
+import { mockLogger } from '../test_utils';
describe('createManagedConfiguration()', () => {
let clock: sinon.SinonFakeTimers;
diff --git a/x-pack/plugins/task_manager/server/lib/create_managed_configuration.ts b/x-pack/plugins/task_manager/server/lib/create_managed_configuration.ts
index 3dc5fd50d3ca4..9d093ec0c671f 100644
--- a/x-pack/plugins/task_manager/server/lib/create_managed_configuration.ts
+++ b/x-pack/plugins/task_manager/server/lib/create_managed_configuration.ts
@@ -7,7 +7,7 @@
import { interval, merge, of, Observable } from 'rxjs';
import { filter, mergeScan, map, scan, distinctUntilChanged, startWith } from 'rxjs/operators';
import { SavedObjectsErrorHelpers } from '../../../../../src/core/server';
-import { Logger } from '../types';
+import { Logger } from '../../../../../src/core/server';
const FLUSH_MARKER = Symbol('flush');
export const ADJUST_THROUGHPUT_INTERVAL = 10 * 1000;
@@ -31,7 +31,7 @@ interface ManagedConfigurationOpts {
errors$: Observable;
}
-interface ManagedConfiguration {
+export interface ManagedConfiguration {
maxWorkersConfiguration$: Observable;
pollIntervalConfiguration$: Observable;
}
diff --git a/x-pack/plugins/task_manager/server/lib/middleware.ts b/x-pack/plugins/task_manager/server/lib/middleware.ts
index d367c8ca56c09..c255ddd4775fc 100644
--- a/x-pack/plugins/task_manager/server/lib/middleware.ts
+++ b/x-pack/plugins/task_manager/server/lib/middleware.ts
@@ -6,49 +6,37 @@
import { RunContext, TaskInstance } from '../task';
-/*
- * BeforeSaveMiddlewareParams is nearly identical to RunContext, but
- * taskInstance is before save (no _id property)
- *
- * taskInstance property is guaranteed to exist. The params can optionally
- * include fields from an "options" object passed as the 2nd parameter to
- * taskManager.schedule()
- */
-export interface BeforeSaveMiddlewareParams {
+type Mapper = (params: T) => Promise;
+interface BeforeSaveContext {
taskInstance: TaskInstance;
}
-export type BeforeSaveFunction = (
- params: BeforeSaveMiddlewareParams
-) => Promise;
-
-export type BeforeRunFunction = (params: RunContext) => Promise;
-export type BeforeMarkRunningFunction = (params: RunContext) => Promise;
+export type BeforeSaveContextFunction = Mapper;
+export type BeforeRunContextFunction = Mapper;
export interface Middleware {
- beforeSave: BeforeSaveFunction;
- beforeRun: BeforeRunFunction;
- beforeMarkRunning: BeforeMarkRunningFunction;
+ beforeSave: BeforeSaveContextFunction;
+ beforeRun: BeforeRunContextFunction;
+ beforeMarkRunning: BeforeRunContextFunction;
}
-export function addMiddlewareToChain(prevMiddleware: Middleware, middleware: Middleware) {
- const beforeSave = middleware.beforeSave
- ? (params: BeforeSaveMiddlewareParams) =>
- middleware.beforeSave(params).then(prevMiddleware.beforeSave)
- : prevMiddleware.beforeSave;
-
- const beforeRun = middleware.beforeRun
- ? (params: RunContext) => middleware.beforeRun(params).then(prevMiddleware.beforeRun)
- : prevMiddleware.beforeRun;
+export function addMiddlewareToChain(prev: Middleware, next: Partial) {
+ return {
+ beforeSave: next.beforeSave ? chain(prev.beforeSave, next.beforeSave) : prev.beforeSave,
+ beforeRun: next.beforeRun ? chain(prev.beforeRun, next.beforeRun) : prev.beforeRun,
+ beforeMarkRunning: next.beforeMarkRunning
+ ? chain(prev.beforeMarkRunning, next.beforeMarkRunning)
+ : prev.beforeMarkRunning,
+ };
+}
- const beforeMarkRunning = middleware.beforeMarkRunning
- ? (params: RunContext) =>
- middleware.beforeMarkRunning(params).then(prevMiddleware.beforeMarkRunning)
- : prevMiddleware.beforeMarkRunning;
+const chain = (prev: Mapper, next: Mapper): Mapper => (params) =>
+ next(params).then(prev);
+export function createInitialMiddleware(): Middleware {
return {
- beforeSave,
- beforeRun,
- beforeMarkRunning,
+ beforeSave: async (saveOpts: BeforeSaveContext) => saveOpts,
+ beforeRun: async (runOpts: RunContext) => runOpts,
+ beforeMarkRunning: async (runOpts: RunContext) => runOpts,
};
}
diff --git a/x-pack/plugins/task_manager/server/lib/sanitize_task_definitions.ts b/x-pack/plugins/task_manager/server/lib/sanitize_task_definitions.ts
deleted file mode 100644
index f5856aa6fac33..0000000000000
--- a/x-pack/plugins/task_manager/server/lib/sanitize_task_definitions.ts
+++ /dev/null
@@ -1,25 +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;
- * you may not use this file except in compliance with the Elastic License.
- */
-
-import Joi from 'joi';
-import { TaskDefinition, TaskDictionary, validateTaskDefinition } from '../task';
-
-/**
- * Sanitizes the system's task definitions. Task definitions have optional properties, and
- * this ensures they all are given a reasonable default.
- *
- * @param taskDefinitions - The Kibana task definitions dictionary
- */
-export function sanitizeTaskDefinitions(
- taskDefinitions: TaskDictionary = {}
-): TaskDictionary {
- return Object.keys(taskDefinitions).reduce((acc, type) => {
- const rawDefinition = taskDefinitions[type];
- rawDefinition.type = type;
- acc[type] = Joi.attempt(rawDefinition, validateTaskDefinition) as TaskDefinition;
- return acc;
- }, {} as TaskDictionary);
-}
diff --git a/x-pack/plugins/task_manager/server/plugin.test.ts b/x-pack/plugins/task_manager/server/plugin.test.ts
new file mode 100644
index 0000000000000..50e7e9a7aa197
--- /dev/null
+++ b/x-pack/plugins/task_manager/server/plugin.test.ts
@@ -0,0 +1,71 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+
+import { TaskManagerPlugin } from './plugin';
+import { coreMock } from '../../../../src/core/server/mocks';
+import { TaskManagerConfig } from './config';
+
+describe('TaskManagerPlugin', () => {
+ describe('setup', () => {
+ test('throws if no valid UUID is available', async () => {
+ const pluginInitializerContext = coreMock.createPluginInitializerContext({
+ enabled: true,
+ max_workers: 10,
+ index: 'foo',
+ max_attempts: 9,
+ poll_interval: 3000,
+ max_poll_inactivity_cycles: 10,
+ request_capacity: 1000,
+ });
+
+ pluginInitializerContext.env.instanceUuid = '';
+
+ const taskManagerPlugin = new TaskManagerPlugin(pluginInitializerContext);
+ expect(taskManagerPlugin.setup(coreMock.createSetup())).rejects.toEqual(
+ new Error(`TaskManager is unable to start as Kibana has no valid UUID assigned to it.`)
+ );
+ });
+
+ test('throws if setup methods are called after start', async () => {
+ const pluginInitializerContext = coreMock.createPluginInitializerContext({
+ enabled: true,
+ max_workers: 10,
+ index: 'foo',
+ max_attempts: 9,
+ poll_interval: 3000,
+ max_poll_inactivity_cycles: 10,
+ request_capacity: 1000,
+ });
+
+ const taskManagerPlugin = new TaskManagerPlugin(pluginInitializerContext);
+
+ const setupApi = await taskManagerPlugin.setup(coreMock.createSetup());
+
+ await taskManagerPlugin.start(coreMock.createStart());
+
+ expect(() =>
+ setupApi.addMiddleware({
+ beforeSave: async (saveOpts) => saveOpts,
+ beforeRun: async (runOpts) => runOpts,
+ beforeMarkRunning: async (runOpts) => runOpts,
+ })
+ ).toThrowErrorMatchingInlineSnapshot(
+ `"Cannot add Middleware after the task manager has started"`
+ );
+
+ expect(() =>
+ setupApi.registerTaskDefinitions({
+ lateRegisteredType: {
+ title: 'lateRegisteredType',
+ createTaskRunner: () => ({ async run() {} }),
+ },
+ })
+ ).toThrowErrorMatchingInlineSnapshot(
+ `"Cannot register task definitions after the task manager has started"`
+ );
+ });
+ });
+});
diff --git a/x-pack/plugins/task_manager/server/plugin.ts b/x-pack/plugins/task_manager/server/plugin.ts
index d7dcf779376bf..0381698e6fb77 100644
--- a/x-pack/plugins/task_manager/server/plugin.ts
+++ b/x-pack/plugins/task_manager/server/plugin.ts
@@ -3,92 +3,140 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
-import { PluginInitializerContext, Plugin, CoreSetup, CoreStart } from 'src/core/server';
-import { Subject } from 'rxjs';
+import { PluginInitializerContext, Plugin, CoreSetup, Logger, CoreStart } from 'src/core/server';
import { first } from 'rxjs/operators';
-import { TaskDictionary, TaskDefinition } from './task';
-import { TaskManager } from './task_manager';
+import { TaskDefinition } from './task';
+import { TaskPollingLifecycle } from './polling_lifecycle';
import { TaskManagerConfig } from './config';
-import { Middleware } from './lib/middleware';
+import { createInitialMiddleware, addMiddlewareToChain, Middleware } from './lib/middleware';
import { setupSavedObjects } from './saved_objects';
+import { TaskTypeDictionary } from './task_type_dictionary';
+import { FetchResult, SearchOpts, TaskStore } from './task_store';
+import { createManagedConfiguration } from './lib/create_managed_configuration';
+import { TaskScheduling } from './task_scheduling';
-export type TaskManagerSetupContract = Pick<
- TaskManager,
- 'addMiddleware' | 'registerTaskDefinitions'
+export type TaskManagerSetupContract = { addMiddleware: (middleware: Middleware) => void } & Pick<
+ TaskTypeDictionary,
+ 'registerTaskDefinitions'
>;
export type TaskManagerStartContract = Pick<
- TaskManager,
- 'fetch' | 'get' | 'remove' | 'schedule' | 'runNow' | 'ensureScheduled'
->;
+ TaskScheduling,
+ 'schedule' | 'runNow' | 'ensureScheduled'
+> &
+ Pick;
export class TaskManagerPlugin
implements Plugin {
- legacyTaskManager$: Subject = new Subject();
- taskManager: Promise = this.legacyTaskManager$.pipe(first()).toPromise();
- currentConfig: TaskManagerConfig;
- taskManagerId?: string;
- config?: TaskManagerConfig;
+ private taskPollingLifecycle?: TaskPollingLifecycle;
+ private taskManagerId?: string;
+ private config?: TaskManagerConfig;
+ private logger: Logger;
+ private definitions: TaskTypeDictionary;
+ private middleware: Middleware = createInitialMiddleware();
constructor(private readonly initContext: PluginInitializerContext) {
this.initContext = initContext;
- this.currentConfig = {} as TaskManagerConfig;
+ this.logger = initContext.logger.get();
+ this.definitions = new TaskTypeDictionary(this.logger);
}
- public async setup(core: CoreSetup): Promise {
+ public async setup({ savedObjects }: CoreSetup): Promise {
this.config = await this.initContext.config
.create()
.pipe(first())
.toPromise();
- setupSavedObjects(core.savedObjects, this.config);
+ setupSavedObjects(savedObjects, this.config);
this.taskManagerId = this.initContext.env.instanceUuid;
+ if (!this.taskManagerId) {
+ this.logger.error(
+ `TaskManager is unable to start as there the Kibana UUID is invalid (value of the "server.uuid" configuration is ${this.taskManagerId})`
+ );
+ throw new Error(`TaskManager is unable to start as Kibana has no valid UUID assigned to it.`);
+ } else {
+ this.logger.info(`TaskManager is identified by the Kibana UUID: ${this.taskManagerId}`);
+ }
+
return {
addMiddleware: (middleware: Middleware) => {
- this.taskManager.then((tm) => tm.addMiddleware(middleware));
+ this.assertStillInSetup('add Middleware');
+ this.middleware = addMiddlewareToChain(this.middleware, middleware);
},
- registerTaskDefinitions: (taskDefinition: TaskDictionary) => {
- this.taskManager.then((tm) => tm.registerTaskDefinitions(taskDefinition));
+ registerTaskDefinitions: (taskDefinition: Record) => {
+ this.assertStillInSetup('register task definitions');
+ this.definitions.registerTaskDefinitions(taskDefinition);
},
};
}
public start({ savedObjects, elasticsearch }: CoreStart): TaskManagerStartContract {
- const logger = this.initContext.logger.get('taskManager');
const savedObjectsRepository = savedObjects.createInternalRepository(['task']);
- this.legacyTaskManager$.next(
- new TaskManager({
- taskManagerId: this.taskManagerId!,
- config: this.config!,
- savedObjectsRepository,
- serializer: savedObjects.createSerializer(),
- callAsInternalUser: elasticsearch.legacy.client.callAsInternalUser,
- logger,
- })
- );
- this.legacyTaskManager$.complete();
-
- // we need to "drain" any calls made to the seup API
- // before `starting` TaskManager. This is a legacy relic
- // of the old API that should be resolved once we split
- // Task manager into two services, setup and start, instead
- // of the single instance of TaskManager
- this.taskManager.then((tm) => tm.start());
+ const taskStore = new TaskStore({
+ serializer: savedObjects.createSerializer(),
+ savedObjectsRepository,
+ esClient: elasticsearch.createClient('taskManager').asInternalUser,
+ index: this.config!.index,
+ maxAttempts: this.config!.max_attempts,
+ definitions: this.definitions,
+ taskManagerId: `kibana:${this.taskManagerId!}`,
+ });
+
+ const { maxWorkersConfiguration$, pollIntervalConfiguration$ } = createManagedConfiguration({
+ logger: this.logger,
+ errors$: taskStore.errors$,
+ startingMaxWorkers: this.config!.max_workers,
+ startingPollInterval: this.config!.poll_interval,
+ });
+
+ const taskPollingLifecycle = new TaskPollingLifecycle({
+ config: this.config!,
+ definitions: this.definitions,
+ logger: this.logger,
+ taskStore,
+ middleware: this.middleware,
+ maxWorkersConfiguration$,
+ pollIntervalConfiguration$,
+ });
+ this.taskPollingLifecycle = taskPollingLifecycle;
+
+ const taskScheduling = new TaskScheduling({
+ logger: this.logger,
+ taskStore,
+ middleware: this.middleware,
+ taskPollingLifecycle,
+ });
+
+ // start polling for work
+ taskPollingLifecycle.start();
return {
- fetch: (...args) => this.taskManager.then((tm) => tm.fetch(...args)),
- get: (...args) => this.taskManager.then((tm) => tm.get(...args)),
- remove: (...args) => this.taskManager.then((tm) => tm.remove(...args)),
- schedule: (...args) => this.taskManager.then((tm) => tm.schedule(...args)),
- runNow: (...args) => this.taskManager.then((tm) => tm.runNow(...args)),
- ensureScheduled: (...args) => this.taskManager.then((tm) => tm.ensureScheduled(...args)),
+ fetch: (opts: SearchOpts): Promise => taskStore.fetch(opts),
+ get: (id: string) => taskStore.get(id),
+ remove: (id: string) => taskStore.remove(id),
+ schedule: (...args) => taskScheduling.schedule(...args),
+ ensureScheduled: (...args) => taskScheduling.ensureScheduled(...args),
+ runNow: (...args) => taskScheduling.runNow(...args),
};
}
+
public stop() {
- this.taskManager.then((tm) => {
- tm.stop();
- });
+ if (this.taskPollingLifecycle) {
+ this.taskPollingLifecycle.stop();
+ }
+ }
+
+ /**
+ * Ensures task manager hasn't started
+ *
+ * @param {string} the name of the operation being executed
+ * @returns void
+ */
+ private assertStillInSetup(operation: string) {
+ if (this.taskPollingLifecycle?.isStarted) {
+ throw new Error(`Cannot ${operation} after the task manager has started`);
+ }
}
}
diff --git a/x-pack/plugins/task_manager/server/polling/task_poller.ts b/x-pack/plugins/task_manager/server/polling/task_poller.ts
index 7515668a19d40..3d48453aa5a9a 100644
--- a/x-pack/plugins/task_manager/server/polling/task_poller.ts
+++ b/x-pack/plugins/task_manager/server/polling/task_poller.ts
@@ -15,7 +15,7 @@ import { mapTo, filter, scan, concatMap, tap, catchError, switchMap } from 'rxjs
import { pipe } from 'fp-ts/lib/pipeable';
import { Option, none, map as mapOptional, getOrElse } from 'fp-ts/lib/Option';
-import { Logger } from '../types';
+import { Logger } from '../../../../../src/core/server';
import { pullFromSet } from '../lib/pull_from_set';
import {
Result,
diff --git a/x-pack/plugins/task_manager/server/polling_lifecycle.mock.ts b/x-pack/plugins/task_manager/server/polling_lifecycle.mock.ts
new file mode 100644
index 0000000000000..9df1e06165bc6
--- /dev/null
+++ b/x-pack/plugins/task_manager/server/polling_lifecycle.mock.ts
@@ -0,0 +1,24 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+
+import { TaskPollingLifecycle, TaskLifecycleEvent } from './polling_lifecycle';
+import { of, Observable } from 'rxjs';
+
+export const taskPollingLifecycleMock = {
+ create(opts: { isStarted?: boolean; events$?: Observable }) {
+ return ({
+ start: jest.fn(),
+ attemptToRun: jest.fn(),
+ get isStarted() {
+ return opts.isStarted ?? true;
+ },
+ get events() {
+ return opts.events$ ?? of();
+ },
+ stop: jest.fn(),
+ } as unknown) as jest.Mocked;
+ },
+};
diff --git a/x-pack/plugins/task_manager/server/polling_lifecycle.test.ts b/x-pack/plugins/task_manager/server/polling_lifecycle.test.ts
new file mode 100644
index 0000000000000..29c8e836303f8
--- /dev/null
+++ b/x-pack/plugins/task_manager/server/polling_lifecycle.test.ts
@@ -0,0 +1,105 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+
+import _ from 'lodash';
+import sinon from 'sinon';
+import { of } from 'rxjs';
+
+import { TaskPollingLifecycle, claimAvailableTasks } from './polling_lifecycle';
+import { createInitialMiddleware } from './lib/middleware';
+import { TaskTypeDictionary } from './task_type_dictionary';
+import { taskStoreMock } from './task_store.mock';
+import { mockLogger } from './test_utils';
+
+describe('TaskPollingLifecycle', () => {
+ let clock: sinon.SinonFakeTimers;
+
+ const taskManagerLogger = mockLogger();
+ const mockTaskStore = taskStoreMock.create({});
+ const taskManagerOpts = {
+ config: {
+ enabled: true,
+ max_workers: 10,
+ index: 'foo',
+ max_attempts: 9,
+ poll_interval: 6000000,
+ max_poll_inactivity_cycles: 10,
+ request_capacity: 1000,
+ },
+ taskStore: mockTaskStore,
+ logger: taskManagerLogger,
+ definitions: new TaskTypeDictionary(taskManagerLogger),
+ middleware: createInitialMiddleware(),
+ maxWorkersConfiguration$: of(100),
+ pollIntervalConfiguration$: of(100),
+ };
+
+ beforeEach(() => {
+ clock = sinon.useFakeTimers();
+ taskManagerOpts.definitions = new TaskTypeDictionary(taskManagerLogger);
+ });
+
+ afterEach(() => clock.restore());
+
+ describe('start', () => {
+ test('begins polling once start is called', () => {
+ const taskManager = new TaskPollingLifecycle(taskManagerOpts);
+
+ clock.tick(150);
+ expect(mockTaskStore.claimAvailableTasks).not.toHaveBeenCalled();
+
+ taskManager.start();
+
+ clock.tick(150);
+ expect(mockTaskStore.claimAvailableTasks).toHaveBeenCalled();
+ });
+ });
+
+ describe('claimAvailableTasks', () => {
+ test('should claim Available Tasks when there are available workers', () => {
+ const logger = mockLogger();
+ const claim = jest.fn(() => Promise.resolve({ docs: [], claimedTasks: 0 }));
+
+ const availableWorkers = 1;
+
+ claimAvailableTasks([], claim, availableWorkers, logger);
+
+ expect(claim).toHaveBeenCalledTimes(1);
+ });
+
+ test('should not claim Available Tasks when there are no available workers', () => {
+ const logger = mockLogger();
+ const claim = jest.fn(() => Promise.resolve({ docs: [], claimedTasks: 0 }));
+
+ const availableWorkers = 0;
+
+ claimAvailableTasks([], claim, availableWorkers, logger);
+
+ expect(claim).not.toHaveBeenCalled();
+ });
+
+ /**
+ * This handles the case in which Elasticsearch has had inline script disabled.
+ * This is achieved by setting the `script.allowed_types` flag on Elasticsearch to `none`
+ */
+ test('handles failure due to inline scripts being disabled', () => {
+ const logger = mockLogger();
+ const claim = jest.fn(() => {
+ throw Object.assign(new Error(), {
+ response:
+ '{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"cannot execute [inline] scripts"}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":".kibana_task_manager_1","node":"24A4QbjHSK6prvtopAKLKw","reason":{"type":"illegal_argument_exception","reason":"cannot execute [inline] scripts"}}],"caused_by":{"type":"illegal_argument_exception","reason":"cannot execute [inline] scripts","caused_by":{"type":"illegal_argument_exception","reason":"cannot execute [inline] scripts"}}},"status":400}',
+ });
+ });
+
+ claimAvailableTasks([], claim, 10, logger);
+
+ expect(logger.warn).toHaveBeenCalledTimes(1);
+ expect(logger.warn).toHaveBeenCalledWith(
+ `Task Manager cannot operate when inline scripts are disabled in Elasticsearch`
+ );
+ });
+ });
+});
diff --git a/x-pack/plugins/task_manager/server/polling_lifecycle.ts b/x-pack/plugins/task_manager/server/polling_lifecycle.ts
new file mode 100644
index 0000000000000..8a506cca699de
--- /dev/null
+++ b/x-pack/plugins/task_manager/server/polling_lifecycle.ts
@@ -0,0 +1,259 @@
+/*
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
+ * or more contributor license agreements. Licensed under the Elastic License;
+ * you may not use this file except in compliance with the Elastic License.
+ */
+import { Subject, Observable, Subscription } from 'rxjs';
+
+import { performance } from 'perf_hooks';
+
+import { pipe } from 'fp-ts/lib/pipeable';
+import { Option, some, map as mapOptional } from 'fp-ts/lib/Option';
+import { Logger } from '../../../../src/core/server';
+
+import { Result, asErr, mapErr } from './lib/result_type';
+import { ManagedConfiguration } from './lib/create_managed_configuration';
+import { TaskManagerConfig } from './config';
+
+import {
+ TaskMarkRunning,
+ TaskRun,
+ TaskClaim,
+ TaskRunRequest,
+ asTaskRunRequestEvent,
+} from './task_events';
+import { fillPool, FillPoolResult } from './lib/fill_pool';
+import { Middleware } from './lib/middleware';
+import { intervalFromNow } from './lib/intervals';
+import { ConcreteTaskInstance } from './task';
+import {
+ createTaskPoller,
+ PollingError,
+ PollingErrorType,
+ createObservableMonitor,
+} from './polling';
+import { TaskPool } from './task_pool';
+import { TaskManagerRunner, TaskRunner } from './task_runner';
+import { TaskStore, OwnershipClaimingOpts, ClaimOwnershipResult } from './task_store';
+import { identifyEsError } from './lib/identify_es_error';
+import { BufferedTaskStore } from './buffered_task_store';
+import { TaskTypeDictionary } from './task_type_dictionary';
+
+export type TaskPollingLifecycleOpts = {
+ logger: Logger;
+ definitions: TaskTypeDictionary;
+ taskStore: TaskStore;
+ config: TaskManagerConfig;
+ middleware: Middleware;
+} & ManagedConfiguration;
+
+export type TaskLifecycleEvent = TaskMarkRunning | TaskRun | TaskClaim | TaskRunRequest;
+
+/**
+ * The public interface into the task manager system.
+ */
+export class TaskPollingLifecycle {
+ private definitions: TaskTypeDictionary;
+
+ private store: TaskStore;
+ private bufferedStore: BufferedTaskStore;
+
+ private logger: Logger;
+ private pool: TaskPool;
+ // all task related events (task claimed, task marked as running, etc.) are emitted through events$
+ private events$ = new Subject();
+ // all on-demand requests we wish to pipe into the poller
+ private claimRequests$ = new Subject