>;
// @public
export interface ICspConfig {
@@ -1840,26 +1870,14 @@ export interface RegisterDeprecationsConfig {
export type RequestHandler = (context: Context, request: KibanaRequest
, response: ResponseFactory) => IKibanaResponse | Promise>;
// @public
-export interface RequestHandlerContext {
+export interface RequestHandlerContext extends RequestHandlerContextBase {
// (undocumented)
- core: {
- savedObjects: {
- client: SavedObjectsClientContract;
- typeRegistry: ISavedObjectTypeRegistry;
- getClient: (options?: SavedObjectsClientProviderOptions) => SavedObjectsClientContract;
- getExporter: (client: SavedObjectsClientContract) => ISavedObjectsExporter;
- getImporter: (client: SavedObjectsClientContract) => ISavedObjectsImporter;
- };
- elasticsearch: {
- client: IScopedClusterClient;
- };
- uiSettings: {
- client: IUiSettingsClient;
- };
- deprecations: {
- client: DeprecationsClient;
- };
- };
+ core: Promise;
+}
+
+// @public (undocumented)
+export interface RequestHandlerContextBase {
+ resolve: >(parts: T[]) => Promise>>;
}
// @public
diff --git a/src/core/server/server.ts b/src/core/server/server.ts
index fc215d9055818..c73e98f4bb6c4 100644
--- a/src/core/server/server.ts
+++ b/src/core/server/server.ts
@@ -42,7 +42,6 @@ import { config as uiSettingsConfig } from './ui_settings';
import { config as statusConfig } from './status';
import { config as i18nConfig } from './i18n';
import { ContextService } from './context';
-import { RequestHandlerContext } from '.';
import {
InternalCorePreboot,
InternalCoreSetup,
@@ -372,13 +371,9 @@ export class Server {
}
private registerCoreContext(coreSetup: InternalCoreSetup) {
- coreSetup.http.registerRouteHandlerContext(
- coreId,
- 'core',
- (context, req, res): RequestHandlerContext['core'] => {
- return new CoreRouteHandlerContext(this.coreStart!, req);
- }
- );
+ coreSetup.http.registerRouteHandlerContext(coreId, 'core', async (context, req, res) => {
+ return new CoreRouteHandlerContext(this.coreStart!, req);
+ });
}
public setupCoreConfig() {
diff --git a/src/core/server/ui_settings/routes/delete.ts b/src/core/server/ui_settings/routes/delete.ts
index f8ab4d5d0c2c4..87c6edf386428 100644
--- a/src/core/server/ui_settings/routes/delete.ts
+++ b/src/core/server/ui_settings/routes/delete.ts
@@ -23,7 +23,7 @@ export function registerDeleteRoute(router: IRouter) {
{ path: '/api/kibana/settings/{key}', validate },
async (context, request, response) => {
try {
- const uiSettingsClient = context.core.uiSettings.client;
+ const uiSettingsClient = (await context.core).uiSettings.client;
await uiSettingsClient.remove(request.params.key);
diff --git a/src/core/server/ui_settings/routes/get.ts b/src/core/server/ui_settings/routes/get.ts
index 051d562c39804..0929330cf0238 100644
--- a/src/core/server/ui_settings/routes/get.ts
+++ b/src/core/server/ui_settings/routes/get.ts
@@ -14,7 +14,7 @@ export function registerGetRoute(router: IRouter) {
{ path: '/api/kibana/settings', validate: false },
async (context, request, response) => {
try {
- const uiSettingsClient = context.core.uiSettings.client;
+ const uiSettingsClient = (await context.core).uiSettings.client;
return response.ok({
body: {
settings: await uiSettingsClient.getUserProvided(),
diff --git a/src/core/server/ui_settings/routes/set.ts b/src/core/server/ui_settings/routes/set.ts
index 7de287f4ebe6a..91518fb6f3476 100644
--- a/src/core/server/ui_settings/routes/set.ts
+++ b/src/core/server/ui_settings/routes/set.ts
@@ -26,7 +26,7 @@ export function registerSetRoute(router: IRouter) {
{ path: '/api/kibana/settings/{key}', validate },
async (context, request, response) => {
try {
- const uiSettingsClient = context.core.uiSettings.client;
+ const uiSettingsClient = (await context.core).uiSettings.client;
const { key } = request.params;
const { value } = request.body;
diff --git a/src/core/server/ui_settings/routes/set_many.ts b/src/core/server/ui_settings/routes/set_many.ts
index c4053dd3e7eed..f4f3f509bf920 100644
--- a/src/core/server/ui_settings/routes/set_many.ts
+++ b/src/core/server/ui_settings/routes/set_many.ts
@@ -21,7 +21,7 @@ const validate = {
export function registerSetManyRoute(router: IRouter) {
router.post({ path: '/api/kibana/settings', validate }, async (context, request, response) => {
try {
- const uiSettingsClient = context.core.uiSettings.client;
+ const uiSettingsClient = (await context.core).uiSettings.client;
const { changes } = request.body;
diff --git a/src/plugins/controls/server/control_types/options_list/options_list_suggestions_route.ts b/src/plugins/controls/server/control_types/options_list/options_list_suggestions_route.ts
index 7ed1ace5dbde9..9af4800ca00fb 100644
--- a/src/plugins/controls/server/control_types/options_list/options_list_suggestions_route.ts
+++ b/src/plugins/controls/server/control_types/options_list/options_list_suggestions_route.ts
@@ -53,7 +53,7 @@ export const setupOptionsListSuggestionsRoute = (
try {
const suggestionRequest: OptionsListRequestBody = request.body;
const { index } = request.params;
- const esClient = context.core.elasticsearch.client.asCurrentUser;
+ const esClient = (await context.core).elasticsearch.client.asCurrentUser;
const suggestionsResponse = await getOptionsListSuggestions({
abortedEvent$: request.events.aborted$,
request: suggestionRequest,
diff --git a/src/plugins/data/server/mocks.ts b/src/plugins/data/server/mocks.ts
index 62e1798c714a1..8df65f7e5b90e 100644
--- a/src/plugins/data/server/mocks.ts
+++ b/src/plugins/data/server/mocks.ts
@@ -6,6 +6,7 @@
* Side Public License, v 1.
*/
+import { coreMock } from '@kbn/core/server/mocks';
import {
createFieldFormatsSetupMock,
createFieldFormatsStartMock,
@@ -17,7 +18,6 @@ import {
} from './search/mocks';
import { createIndexPatternsStartMock } from './data_views/mocks';
import { createDatatableUtilitiesMock } from './datatable_utilities/mock';
-import { DataRequestHandlerContext } from './search';
function createSetupContract() {
return {
@@ -43,8 +43,9 @@ function createStartContract() {
function createRequestHandlerContext() {
return {
+ core: coreMock.createRequestHandlerContext(),
search: createSearchRequestHandlerContext(),
- } as unknown as jest.Mocked;
+ };
}
export const dataPluginMock = {
diff --git a/src/plugins/data/server/query/route_handler_context.test.ts b/src/plugins/data/server/query/route_handler_context.test.ts
index 69908f9733f56..c0db432ce3fd9 100644
--- a/src/plugins/data/server/query/route_handler_context.test.ts
+++ b/src/plugins/data/server/query/route_handler_context.test.ts
@@ -20,7 +20,6 @@ const {
savedObjects: { client: mockSavedObjectsClient },
},
} = mockContext;
-const context = registerSavedQueryRouteHandlerContext(mockContext);
const savedQueryAttributes: SavedQueryAttributes = {
title: 'foo',
@@ -73,7 +72,15 @@ const savedQueryReferences = [
];
describe('saved query route handler context', () => {
- beforeEach(() => {
+ let context: Awaited>;
+
+ beforeEach(async () => {
+ context = await registerSavedQueryRouteHandlerContext(
+ coreMock.createCustomRequestHandlerContext({
+ core: mockContext.core,
+ })
+ );
+
mockSavedObjectsClient.create.mockClear();
mockSavedObjectsClient.resolve.mockClear();
mockSavedObjectsClient.find.mockClear();
diff --git a/src/plugins/data/server/query/route_handler_context.ts b/src/plugins/data/server/query/route_handler_context.ts
index e72257fe185d3..0af658d7692c5 100644
--- a/src/plugins/data/server/query/route_handler_context.ts
+++ b/src/plugins/data/server/query/route_handler_context.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { RequestHandlerContext, SavedObject } from '@kbn/core/server';
+import { CustomRequestHandlerContext, RequestHandlerContext, SavedObject } from '@kbn/core/server';
import { isFilters } from '@kbn/es-query';
import { isQuery, SavedQueryAttributes } from '../../common';
import { extract, inject } from '../../common/query/persistable_state';
@@ -66,18 +66,16 @@ function verifySavedQuery({ title, query, filters = [] }: SavedQueryAttributes)
}
}
-export function registerSavedQueryRouteHandlerContext(context: RequestHandlerContext) {
+export async function registerSavedQueryRouteHandlerContext(context: RequestHandlerContext) {
+ const soClient = (await context.core).savedObjects.client;
+
const createSavedQuery = async (attrs: SavedQueryAttributes) => {
verifySavedQuery(attrs);
const { attributes, references } = extractReferences(attrs);
- const savedObject = await context.core.savedObjects.client.create(
- 'query',
- attributes,
- {
- references,
- }
- );
+ const savedObject = await soClient.create('query', attributes, {
+ references,
+ });
// TODO: Handle properly
if (savedObject.error) throw new Error(savedObject.error.message);
@@ -89,14 +87,9 @@ export function registerSavedQueryRouteHandlerContext(context: RequestHandlerCon
verifySavedQuery(attrs);
const { attributes, references } = extractReferences(attrs);
- const savedObject = await context.core.savedObjects.client.update(
- 'query',
- id,
- attributes,
- {
- references,
- }
- );
+ const savedObject = await soClient.update('query', id, attributes, {
+ references,
+ });
// TODO: Handle properly
if (savedObject.error) throw new Error(savedObject.error.message);
@@ -105,8 +98,10 @@ export function registerSavedQueryRouteHandlerContext(context: RequestHandlerCon
};
const getSavedQuery = async (id: string) => {
- const { saved_object: savedObject, outcome } =
- await context.core.savedObjects.client.resolve('query', id);
+ const { saved_object: savedObject, outcome } = await soClient.resolve(
+ 'query',
+ id
+ );
if (outcome === 'conflict') {
throw new Error(`Multiple saved queries found with ID: ${id} (legacy URL alias conflict)`);
} else if (savedObject.error) {
@@ -116,20 +111,19 @@ export function registerSavedQueryRouteHandlerContext(context: RequestHandlerCon
};
const getSavedQueriesCount = async () => {
- const { total } = await context.core.savedObjects.client.find({
+ const { total } = await soClient.find({
type: 'query',
});
return total;
};
const findSavedQueries = async ({ page = 1, perPage = 50, search = '' } = {}) => {
- const { total, saved_objects: savedObjects } =
- await context.core.savedObjects.client.find({
- type: 'query',
- page,
- perPage,
- search,
- });
+ const { total, saved_objects: savedObjects } = await soClient.find({
+ type: 'query',
+ page,
+ perPage,
+ search,
+ });
const savedQueries = savedObjects.map(injectReferences);
@@ -137,7 +131,7 @@ export function registerSavedQueryRouteHandlerContext(context: RequestHandlerCon
};
const getAllSavedQueries = async () => {
- const finder = context.core.savedObjects.client.createPointInTimeFinder({
+ const finder = soClient.createPointInTimeFinder({
type: 'query',
perPage: 100,
});
@@ -152,8 +146,8 @@ export function registerSavedQueryRouteHandlerContext(context: RequestHandlerCon
return { total: savedQueries.length, savedQueries };
};
- const deleteSavedQuery = (id: string) => {
- return context.core.savedObjects.client.delete('query', id);
+ const deleteSavedQuery = async (id: string) => {
+ return await soClient.delete('query', id);
};
return {
@@ -167,6 +161,6 @@ export function registerSavedQueryRouteHandlerContext(context: RequestHandlerCon
};
}
-export interface SavedQueryRouteHandlerContext extends RequestHandlerContext {
- savedQuery: ReturnType;
-}
+export type SavedQueryRouteHandlerContext = CustomRequestHandlerContext<{
+ savedQuery: Promise>;
+}>;
diff --git a/src/plugins/data/server/query/routes.ts b/src/plugins/data/server/query/routes.ts
index d5997e93fa993..16f5d8f9955a7 100644
--- a/src/plugins/data/server/query/routes.ts
+++ b/src/plugins/data/server/query/routes.ts
@@ -37,7 +37,8 @@ export function registerSavedQueryRoutes({ http }: CoreSetup): void {
},
async (context, request, response) => {
try {
- const body = await context.savedQuery.create(request.body);
+ const savedQuery = await context.savedQuery;
+ const body = await savedQuery.create(request.body);
return response.ok({ body });
} catch (e) {
// TODO: Handle properly
@@ -57,7 +58,8 @@ export function registerSavedQueryRoutes({ http }: CoreSetup): void {
async (context, request, response) => {
const { id } = request.params;
try {
- const body = await context.savedQuery.update(id, request.body);
+ const savedQuery = await context.savedQuery;
+ const body = await savedQuery.update(id, request.body);
return response.ok({ body });
} catch (e) {
// TODO: Handle properly
@@ -76,7 +78,8 @@ export function registerSavedQueryRoutes({ http }: CoreSetup): void {
async (context, request, response) => {
const { id } = request.params;
try {
- const body = await context.savedQuery.get(id);
+ const savedQuery = await context.savedQuery;
+ const body = await savedQuery.get(id);
return response.ok({ body });
} catch (e) {
// TODO: Handle properly
@@ -92,7 +95,8 @@ export function registerSavedQueryRoutes({ http }: CoreSetup): void {
},
async (context, request, response) => {
try {
- const count = await context.savedQuery.count();
+ const savedQuery = await context.savedQuery;
+ const count = await savedQuery.count();
return response.ok({ body: `${count}` });
} catch (e) {
// TODO: Handle properly
@@ -114,7 +118,8 @@ export function registerSavedQueryRoutes({ http }: CoreSetup): void {
},
async (context, request, response) => {
try {
- const body = await context.savedQuery.find(request.body);
+ const savedQuery = await context.savedQuery;
+ const body = await savedQuery.find(request.body);
return response.ok({ body });
} catch (e) {
// TODO: Handle properly
@@ -130,7 +135,8 @@ export function registerSavedQueryRoutes({ http }: CoreSetup): void {
},
async (context, request, response) => {
try {
- const body = await context.savedQuery.getAll();
+ const savedQuery = await context.savedQuery;
+ const body = await savedQuery.getAll();
return response.ok({ body });
} catch (e) {
// TODO: Handle properly
@@ -149,7 +155,8 @@ export function registerSavedQueryRoutes({ http }: CoreSetup): void {
async (context, request, response) => {
const { id } = request.params;
try {
- const body = await context.savedQuery.delete(id);
+ const savedQuery = await context.savedQuery;
+ const body = await savedQuery.delete(id);
return response.ok({ body });
} catch (e) {
// TODO: Handle properly
diff --git a/src/plugins/data/server/search/routes/search.ts b/src/plugins/data/server/search/routes/search.ts
index 6f48ba747a715..aa0f69b55816c 100644
--- a/src/plugins/data/server/search/routes/search.ts
+++ b/src/plugins/data/server/search/routes/search.ts
@@ -47,8 +47,9 @@ export function registerSearchRoute(router: DataPluginRouter): void {
const abortSignal = getRequestAbortedSignal(request.events.aborted$);
try {
- const response = await context
- .search!.search(
+ const search = await context.search;
+ const response = await search
+ .search(
{ ...searchRequest, id },
{
abortSignal,
@@ -85,7 +86,8 @@ export function registerSearchRoute(router: DataPluginRouter): void {
const { strategy, id } = request.params;
try {
- await context.search!.cancel(id, { strategy });
+ const search = await context.search;
+ await search.cancel(id, { strategy });
return res.ok();
} catch (err) {
return reportServerError(res, err);
diff --git a/src/plugins/data/server/search/search_service.ts b/src/plugins/data/server/search/search_service.ts
index 8c264889ebf2a..c59893cdead96 100644
--- a/src/plugins/data/server/search/search_service.ts
+++ b/src/plugins/data/server/search/search_service.ts
@@ -143,7 +143,7 @@ export class SearchService implements Plugin {
core.http.registerRouteHandlerContext(
'search',
- async (context, request) => {
+ (context, request) => {
return this.asScoped(request);
}
);
diff --git a/src/plugins/data/server/search/types.ts b/src/plugins/data/server/search/types.ts
index ef6a2f5f88fe5..70e04e97ea169 100644
--- a/src/plugins/data/server/search/types.ts
+++ b/src/plugins/data/server/search/types.ts
@@ -13,7 +13,7 @@ import type {
IUiSettingsClient,
SavedObjectsClientContract,
KibanaRequest,
- RequestHandlerContext,
+ CustomRequestHandlerContext,
} from '@kbn/core/server';
import {
ISearchOptions,
@@ -126,8 +126,8 @@ export interface ISearchStart<
export type SearchRequestHandlerContext = IScopedSearchClient;
-export interface DataRequestHandlerContext extends RequestHandlerContext {
+export type DataRequestHandlerContext = CustomRequestHandlerContext<{
search: SearchRequestHandlerContext;
-}
+}>;
export type DataPluginRouter = IRouter;
diff --git a/src/plugins/data_view_field_editor/server/routes/field_preview.ts b/src/plugins/data_view_field_editor/server/routes/field_preview.ts
index 022cd92a4bb1e..5595eeeaeddfb 100644
--- a/src/plugins/data_view_field_editor/server/routes/field_preview.ts
+++ b/src/plugins/data_view_field_editor/server/routes/field_preview.ts
@@ -38,7 +38,7 @@ export const registerFieldPreviewRoute = ({ router }: RouteDependencies): void =
},
},
async (ctx, req, res) => {
- const { client } = ctx.core.elasticsearch;
+ const { client } = (await ctx.core).elasticsearch;
const type = req.body.context.split('_field')[0] as estypes.MappingRuntimeFieldType;
const body = {
diff --git a/src/plugins/data_view_management/server/routes/preview_scripted_field.ts b/src/plugins/data_view_management/server/routes/preview_scripted_field.ts
index aee953af1c298..3a19872150a8b 100644
--- a/src/plugins/data_view_management/server/routes/preview_scripted_field.ts
+++ b/src/plugins/data_view_management/server/routes/preview_scripted_field.ts
@@ -24,7 +24,7 @@ export function registerPreviewScriptedFieldRoute(router: IRouter): void {
},
},
async (context, request, res) => {
- const client = context.core.elasticsearch.client.asCurrentUser;
+ const client = (await context.core).elasticsearch.client.asCurrentUser;
const { index, name, script, query, additionalFields } = request.body;
try {
diff --git a/src/plugins/data_view_management/server/routes/resolve_index.ts b/src/plugins/data_view_management/server/routes/resolve_index.ts
index 85ad6ae8993a3..820e6de1c9d7d 100644
--- a/src/plugins/data_view_management/server/routes/resolve_index.ts
+++ b/src/plugins/data_view_management/server/routes/resolve_index.ts
@@ -31,7 +31,8 @@ export function registerResolveIndexRoute(router: IRouter): void {
},
},
async (context, req, res) => {
- const body = await context.core.elasticsearch.client.asCurrentUser.indices.resolveIndex({
+ const esClient = (await context.core).elasticsearch.client;
+ const body = await esClient.asCurrentUser.indices.resolveIndex({
name: req.params.query,
expand_wildcards: req.query.expand_wildcards || 'open',
});
diff --git a/src/plugins/data_views/server/rest_api_routes/create_data_view.ts b/src/plugins/data_views/server/rest_api_routes/create_data_view.ts
index 755ba5dcd86ef..c35344f54c4fa 100644
--- a/src/plugins/data_views/server/rest_api_routes/create_data_view.ts
+++ b/src/plugins/data_views/server/rest_api_routes/create_data_view.ts
@@ -94,8 +94,9 @@ const registerCreateDataViewRouteFactory =
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
diff --git a/src/plugins/data_views/server/rest_api_routes/default_data_view.ts b/src/plugins/data_views/server/rest_api_routes/default_data_view.ts
index da89bbe95b69d..7ce241176228e 100644
--- a/src/plugins/data_views/server/rest_api_routes/default_data_view.ts
+++ b/src/plugins/data_views/server/rest_api_routes/default_data_view.ts
@@ -64,8 +64,9 @@ const manageDefaultIndexPatternRoutesFactory =
validate: {},
},
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
@@ -103,8 +104,9 @@ const manageDefaultIndexPatternRoutesFactory =
},
},
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/delete_data_view.ts b/src/plugins/data_views/server/rest_api_routes/delete_data_view.ts
index 88370b5aea776..b3fd0b8a041c8 100644
--- a/src/plugins/data_views/server/rest_api_routes/delete_data_view.ts
+++ b/src/plugins/data_views/server/rest_api_routes/delete_data_view.ts
@@ -58,8 +58,9 @@ const deleteIndexPatternRouteFactory =
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/fields/update_fields.ts b/src/plugins/data_views/server/rest_api_routes/fields/update_fields.ts
index 49e3d3fc0f1ef..d99aa67c7f153 100644
--- a/src/plugins/data_views/server/rest_api_routes/fields/update_fields.ts
+++ b/src/plugins/data_views/server/rest_api_routes/fields/update_fields.ts
@@ -134,8 +134,9 @@ const updateFieldsActionRouteFactory = (path: string, serviceKey: string) => {
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/get_data_view.ts b/src/plugins/data_views/server/rest_api_routes/get_data_view.ts
index 63ef2701a3062..86185fb0b2777 100644
--- a/src/plugins/data_views/server/rest_api_routes/get_data_view.ts
+++ b/src/plugins/data_views/server/rest_api_routes/get_data_view.ts
@@ -63,8 +63,9 @@ const getDataViewRouteFactory =
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/has_user_data_view.ts b/src/plugins/data_views/server/rest_api_routes/has_user_data_view.ts
index 5bbe7966ae267..1031a04456b47 100644
--- a/src/plugins/data_views/server/rest_api_routes/has_user_data_view.ts
+++ b/src/plugins/data_views/server/rest_api_routes/has_user_data_view.ts
@@ -45,8 +45,9 @@ const hasUserDataViewRouteFactory =
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
diff --git a/src/plugins/data_views/server/rest_api_routes/runtime_fields/create_runtime_field.ts b/src/plugins/data_views/server/rest_api_routes/runtime_fields/create_runtime_field.ts
index 4ae100e1a79f5..5c9faaf2c8593 100644
--- a/src/plugins/data_views/server/rest_api_routes/runtime_fields/create_runtime_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/runtime_fields/create_runtime_field.ts
@@ -92,8 +92,9 @@ const runtimeCreateFieldRouteFactory =
},
},
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/runtime_fields/delete_runtime_field.ts b/src/plugins/data_views/server/rest_api_routes/runtime_fields/delete_runtime_field.ts
index 94dde735c0674..e7db34f43cf37 100644
--- a/src/plugins/data_views/server/rest_api_routes/runtime_fields/delete_runtime_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/runtime_fields/delete_runtime_field.ts
@@ -73,8 +73,9 @@ const deleteRuntimeFieldRouteFactory =
},
},
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/runtime_fields/get_runtime_field.ts b/src/plugins/data_views/server/rest_api_routes/runtime_fields/get_runtime_field.ts
index 4d9a5678392a2..867766eec3124 100644
--- a/src/plugins/data_views/server/rest_api_routes/runtime_fields/get_runtime_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/runtime_fields/get_runtime_field.ts
@@ -80,8 +80,9 @@ const getRuntimeFieldRouteFactory =
},
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/runtime_fields/put_runtime_field.ts b/src/plugins/data_views/server/rest_api_routes/runtime_fields/put_runtime_field.ts
index ed4f01d703f0c..0f5399606dfdc 100644
--- a/src/plugins/data_views/server/rest_api_routes/runtime_fields/put_runtime_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/runtime_fields/put_runtime_field.ts
@@ -92,8 +92,9 @@ const putRuntimeFieldRouteFactory =
},
},
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/runtime_fields/update_runtime_field.ts b/src/plugins/data_views/server/rest_api_routes/runtime_fields/update_runtime_field.ts
index fe632f5533dc7..1aaf1b112feed 100644
--- a/src/plugins/data_views/server/rest_api_routes/runtime_fields/update_runtime_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/runtime_fields/update_runtime_field.ts
@@ -93,8 +93,9 @@ const updateRuntimeFieldRouteFactory =
},
},
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/scripted_fields/create_scripted_field.ts b/src/plugins/data_views/server/rest_api_routes/scripted_fields/create_scripted_field.ts
index 4335fc6aea905..759627f926762 100644
--- a/src/plugins/data_views/server/rest_api_routes/scripted_fields/create_scripted_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/scripted_fields/create_scripted_field.ts
@@ -42,8 +42,9 @@ export const registerCreateScriptedFieldRoute = (
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { indexPatternsServiceFactory }] = await getStartServices();
const indexPatternsService = await indexPatternsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/scripted_fields/delete_scripted_field.ts b/src/plugins/data_views/server/rest_api_routes/scripted_fields/delete_scripted_field.ts
index 811c3e096ca18..7e3333820e4e9 100644
--- a/src/plugins/data_views/server/rest_api_routes/scripted_fields/delete_scripted_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/scripted_fields/delete_scripted_field.ts
@@ -43,8 +43,9 @@ export const registerDeleteScriptedFieldRoute = (
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { indexPatternsServiceFactory }] = await getStartServices();
const indexPatternsService = await indexPatternsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/scripted_fields/get_scripted_field.ts b/src/plugins/data_views/server/rest_api_routes/scripted_fields/get_scripted_field.ts
index 3b76d56070f1e..befe30f8437f2 100644
--- a/src/plugins/data_views/server/rest_api_routes/scripted_fields/get_scripted_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/scripted_fields/get_scripted_field.ts
@@ -43,8 +43,9 @@ export const registerGetScriptedFieldRoute = (
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { indexPatternsServiceFactory }] = await getStartServices();
const indexPatternsService = await indexPatternsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/scripted_fields/put_scripted_field.ts b/src/plugins/data_views/server/rest_api_routes/scripted_fields/put_scripted_field.ts
index 8989c1412769e..93312dd6d3cf6 100644
--- a/src/plugins/data_views/server/rest_api_routes/scripted_fields/put_scripted_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/scripted_fields/put_scripted_field.ts
@@ -42,8 +42,9 @@ export const registerPutScriptedFieldRoute = (
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { indexPatternsServiceFactory }] = await getStartServices();
const indexPatternsService = await indexPatternsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/scripted_fields/update_scripted_field.ts b/src/plugins/data_views/server/rest_api_routes/scripted_fields/update_scripted_field.ts
index 28f28064b2a1b..ddc9d7ae552e8 100644
--- a/src/plugins/data_views/server/rest_api_routes/scripted_fields/update_scripted_field.ts
+++ b/src/plugins/data_views/server/rest_api_routes/scripted_fields/update_scripted_field.ts
@@ -63,8 +63,9 @@ export const registerUpdateScriptedFieldRoute = (
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { indexPatternsServiceFactory }] = await getStartServices();
const indexPatternsService = await indexPatternsServiceFactory(
savedObjectsClient,
diff --git a/src/plugins/data_views/server/rest_api_routes/update_data_view.ts b/src/plugins/data_views/server/rest_api_routes/update_data_view.ts
index c0f890fda9d85..424680f85b498 100644
--- a/src/plugins/data_views/server/rest_api_routes/update_data_view.ts
+++ b/src/plugins/data_views/server/rest_api_routes/update_data_view.ts
@@ -161,8 +161,9 @@ const updateDataViewRouteFactory =
},
router.handleLegacyErrors(
handleErrors(async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const [, , { dataViewsServiceFactory }] = await getStartServices();
const dataViewsService = await dataViewsServiceFactory(
diff --git a/src/plugins/data_views/server/routes.ts b/src/plugins/data_views/server/routes.ts
index 1a35b75b2a104..8f6299a58870a 100644
--- a/src/plugins/data_views/server/routes.ts
+++ b/src/plugins/data_views/server/routes.ts
@@ -56,7 +56,7 @@ export function registerRoutes(
},
},
async (context, request, response) => {
- const { asCurrentUser } = context.core.elasticsearch.client;
+ const { asCurrentUser } = (await context.core).elasticsearch.client;
const indexPatterns = new IndexPatternsFetcher(asCurrentUser);
const { pattern, interval, look_back: lookBack, meta_fields: metaFields } = request.query;
diff --git a/src/plugins/data_views/server/routes/fields_for.ts b/src/plugins/data_views/server/routes/fields_for.ts
index cc71eb9258d4c..3ad854ab0d6ac 100644
--- a/src/plugins/data_views/server/routes/fields_for.ts
+++ b/src/plugins/data_views/server/routes/fields_for.ts
@@ -51,7 +51,7 @@ const validate: RouteValidatorFullConfig<{}, IQuery, IBody> = {
body: schema.maybe(schema.object({ index_filter: schema.any() })),
};
const handler: RequestHandler<{}, IQuery, IBody> = async (context, request, response) => {
- const { asCurrentUser } = context.core.elasticsearch.client;
+ const { asCurrentUser } = (await context.core).elasticsearch.client;
const indexPatterns = new IndexPatternsFetcher(asCurrentUser);
const {
pattern,
diff --git a/src/plugins/data_views/server/routes/has_data_views.ts b/src/plugins/data_views/server/routes/has_data_views.ts
index d74711e8c0d2b..c4982311ce156 100644
--- a/src/plugins/data_views/server/routes/has_data_views.ts
+++ b/src/plugins/data_views/server/routes/has_data_views.ts
@@ -16,8 +16,9 @@ export const registerHasDataViewsRoute = (router: IRouter): void => {
validate: {},
},
async (ctx, req, res) => {
- const savedObjectsClient = ctx.core.savedObjects.client;
- const elasticsearchClient = ctx.core.elasticsearch.client.asCurrentUser;
+ const core = await ctx.core;
+ const savedObjectsClient = core.savedObjects.client;
+ const elasticsearchClient = core.elasticsearch.client.asCurrentUser;
const dataViews = await getIndexPattern({
esClient: elasticsearchClient,
soClient: savedObjectsClient,
diff --git a/src/plugins/home/server/routes/fetch_es_hits_status.ts b/src/plugins/home/server/routes/fetch_es_hits_status.ts
index 557f93f0425e9..0ce090c6bfeed 100644
--- a/src/plugins/home/server/routes/fetch_es_hits_status.ts
+++ b/src/plugins/home/server/routes/fetch_es_hits_status.ts
@@ -22,7 +22,7 @@ export const registerHitsStatusRoute = (router: IRouter) => {
},
router.handleLegacyErrors(async (context, req, res) => {
const { index, query } = req.body;
- const client = context.core.elasticsearch.client;
+ const client = (await context.core).elasticsearch.client;
try {
const body = await client.asCurrentUser.search({
diff --git a/src/plugins/home/server/services/sample_data/routes/install.ts b/src/plugins/home/server/services/sample_data/routes/install.ts
index 58604ec30ce07..f057e6861518e 100644
--- a/src/plugins/home/server/services/sample_data/routes/install.ts
+++ b/src/plugins/home/server/services/sample_data/routes/install.ts
@@ -38,7 +38,7 @@ export function createInstallRoute(
// @ts-ignore Custom query validation used
const now = query.now ? new Date(query.now) : new Date();
- const sampleDataInstaller = getSampleDataInstaller({
+ const sampleDataInstaller = await getSampleDataInstaller({
datasetId: sampleDataset.id,
sampleDatasets,
logger,
diff --git a/src/plugins/home/server/services/sample_data/routes/list.ts b/src/plugins/home/server/services/sample_data/routes/list.ts
index 8f500b1c95501..39690b3944d0c 100644
--- a/src/plugins/home/server/services/sample_data/routes/list.ts
+++ b/src/plugins/home/server/services/sample_data/routes/list.ts
@@ -78,7 +78,7 @@ async function findExistingSampleObjects(
.map(({ savedObjects }) => savedObjects.map(({ type, id }) => ({ type, id })))
.flat();
const objectTypes = getUniqueObjectTypes(objects);
- const client = getSavedObjectsClient(context, objectTypes);
+ const client = await getSavedObjectsClient(context, objectTypes);
const findSampleObjectsResult = await findSampleObjects({ client, logger, objects });
let objectCounter = 0;
@@ -101,18 +101,20 @@ async function getSampleDatasetStatus(
return { status: NOT_INSTALLED };
}
+ const { elasticsearch } = await context.core;
+
for (let i = 0; i < sampleDataset.dataIndices.length; i++) {
const dataIndexConfig = sampleDataset.dataIndices[i];
const index = createIndexName(sampleDataset.id, dataIndexConfig.id);
try {
- const indexExists = await context.core.elasticsearch.client.asCurrentUser.indices.exists({
+ const indexExists = await elasticsearch.client.asCurrentUser.indices.exists({
index,
});
if (!indexExists) {
return { status: NOT_INSTALLED };
}
- const count = await context.core.elasticsearch.client.asCurrentUser.count({
+ const count = await elasticsearch.client.asCurrentUser.count({
index,
});
if (count.count === 0) {
diff --git a/src/plugins/home/server/services/sample_data/routes/uninstall.ts b/src/plugins/home/server/services/sample_data/routes/uninstall.ts
index e6f4b9a07514c..d2700b4985a79 100644
--- a/src/plugins/home/server/services/sample_data/routes/uninstall.ts
+++ b/src/plugins/home/server/services/sample_data/routes/uninstall.ts
@@ -32,7 +32,7 @@ export function createUninstallRoute(
return response.notFound();
}
- const sampleDataInstaller = getSampleDataInstaller({
+ const sampleDataInstaller = await getSampleDataInstaller({
datasetId: sampleDataset.id,
sampleDatasets,
logger,
diff --git a/src/plugins/home/server/services/sample_data/routes/utils.ts b/src/plugins/home/server/services/sample_data/routes/utils.ts
index b784c50ff1182..f4e99e4c04c93 100644
--- a/src/plugins/home/server/services/sample_data/routes/utils.ts
+++ b/src/plugins/home/server/services/sample_data/routes/utils.ts
@@ -11,7 +11,7 @@ import type { SampleDatasetSchema } from '../lib/sample_dataset_registry_types';
import { SampleDataInstaller } from '../sample_data_installer';
import { getUniqueObjectTypes } from '../lib/utils';
-export const getSampleDataInstaller = ({
+export const getSampleDataInstaller = async ({
datasetId,
context,
sampleDatasets,
@@ -22,14 +22,15 @@ export const getSampleDataInstaller = ({
sampleDatasets: SampleDatasetSchema[];
logger: Logger;
}) => {
+ const core = await context.core;
const sampleDataset = sampleDatasets.find(({ id }) => id === datasetId)!;
- const { getImporter, client: soClient } = context.core.savedObjects;
+ const { getImporter, client: soClient } = core.savedObjects;
const objectTypes = getUniqueObjectTypes(sampleDataset.savedObjects);
- const savedObjectsClient = getSavedObjectsClient(context, objectTypes);
+ const savedObjectsClient = await getSavedObjectsClient(context, objectTypes);
const soImporter = getImporter(savedObjectsClient);
return new SampleDataInstaller({
- esClient: context.core.elasticsearch.client,
+ esClient: core.elasticsearch.client,
soImporter,
soClient,
logger,
@@ -37,8 +38,11 @@ export const getSampleDataInstaller = ({
});
};
-export const getSavedObjectsClient = (context: RequestHandlerContext, objectTypes: string[]) => {
- const { getClient, typeRegistry } = context.core.savedObjects;
+export const getSavedObjectsClient = async (
+ context: RequestHandlerContext,
+ objectTypes: string[]
+) => {
+ const { getClient, typeRegistry } = (await context.core).savedObjects;
const includedHiddenTypes = objectTypes.filter((supportedType) =>
typeRegistry.isHidden(supportedType)
);
diff --git a/src/plugins/saved_objects_management/server/routes/bulk_get.ts b/src/plugins/saved_objects_management/server/routes/bulk_get.ts
index fab25b51d9224..9e31b1c24b0b8 100644
--- a/src/plugins/saved_objects_management/server/routes/bulk_get.ts
+++ b/src/plugins/saved_objects_management/server/routes/bulk_get.ts
@@ -29,7 +29,7 @@ export const registerBulkGetRoute = (
},
router.handleLegacyErrors(async (context, req, res) => {
const managementService = await managementServicePromise;
- const { getClient, typeRegistry } = context.core.savedObjects;
+ const { getClient, typeRegistry } = (await context.core).savedObjects;
const objects = req.body;
const uniqueTypes = objects.reduce((acc, { type }) => acc.add(type), new Set());
diff --git a/src/plugins/saved_objects_management/server/routes/find.ts b/src/plugins/saved_objects_management/server/routes/find.ts
index 662ab68031158..05e69da5d3204 100644
--- a/src/plugins/saved_objects_management/server/routes/find.ts
+++ b/src/plugins/saved_objects_management/server/routes/find.ts
@@ -47,7 +47,7 @@ export const registerFindRoute = (
router.handleLegacyErrors(async (context, req, res) => {
const { query } = req;
const managementService = await managementServicePromise;
- const { getClient, typeRegistry } = context.core.savedObjects;
+ const { getClient, typeRegistry } = (await context.core).savedObjects;
const searchTypes = Array.isArray(query.type) ? query.type : [query.type];
const includedFields = Array.isArray(query.fields) ? query.fields : [query.fields];
diff --git a/src/plugins/saved_objects_management/server/routes/get_allowed_types.ts b/src/plugins/saved_objects_management/server/routes/get_allowed_types.ts
index 3ad8130654a77..cdd6dc215d69b 100644
--- a/src/plugins/saved_objects_management/server/routes/get_allowed_types.ts
+++ b/src/plugins/saved_objects_management/server/routes/get_allowed_types.ts
@@ -25,7 +25,7 @@ export const registerGetAllowedTypesRoute = (router: IRouter) => {
validate: false,
},
async (context, req, res) => {
- const allowedTypes = context.core.savedObjects.typeRegistry
+ const allowedTypes = (await context.core).savedObjects.typeRegistry
.getImportableAndExportableTypes()
.filter((type) => type.management!.visibleInManagement ?? true)
.map(convertType);
diff --git a/src/plugins/saved_objects_management/server/routes/relationships.ts b/src/plugins/saved_objects_management/server/routes/relationships.ts
index 875cf82488abe..8900987a645fe 100644
--- a/src/plugins/saved_objects_management/server/routes/relationships.ts
+++ b/src/plugins/saved_objects_management/server/routes/relationships.ts
@@ -32,7 +32,7 @@ export const registerRelationshipsRoute = (
},
router.handleLegacyErrors(async (context, req, res) => {
const managementService = await managementServicePromise;
- const { getClient, typeRegistry } = context.core.savedObjects;
+ const { getClient, typeRegistry } = (await context.core).savedObjects;
const { type, id } = req.params;
const { size, savedObjectTypes: maybeArraySavedObjectTypes } = req.query;
const savedObjectTypes = Array.isArray(maybeArraySavedObjectTypes)
diff --git a/src/plugins/saved_objects_management/server/routes/scroll_count.ts b/src/plugins/saved_objects_management/server/routes/scroll_count.ts
index 217153bbb86e0..26dd1d57b4cf9 100644
--- a/src/plugins/saved_objects_management/server/routes/scroll_count.ts
+++ b/src/plugins/saved_objects_management/server/routes/scroll_count.ts
@@ -31,7 +31,7 @@ export const registerScrollForCountRoute = (router: IRouter) => {
},
},
router.handleLegacyErrors(async (context, req, res) => {
- const { getClient, typeRegistry } = context.core.savedObjects;
+ const { getClient, typeRegistry } = (await context.core).savedObjects;
const { typesToInclude, searchString, references } = req.body;
const includedHiddenTypes = chain(typesToInclude)
diff --git a/src/plugins/screenshot_mode/server/types.ts b/src/plugins/screenshot_mode/server/types.ts
index 514bcb759428d..08655d2f0118d 100644
--- a/src/plugins/screenshot_mode/server/types.ts
+++ b/src/plugins/screenshot_mode/server/types.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { RequestHandlerContext, KibanaRequest } from '@kbn/core/server';
+import type { CustomRequestHandlerContext, KibanaRequest } from '@kbn/core/server';
export interface ScreenshotModePluginStart {
/**
@@ -32,8 +32,8 @@ export interface ScreenshotModePluginSetup extends ScreenshotModePluginStart {
setScreenshotModeEnabled(): void;
}
-export interface ScreenshotModeRequestHandlerContext extends RequestHandlerContext {
+export type ScreenshotModeRequestHandlerContext = CustomRequestHandlerContext<{
screenshotMode: {
isScreenshot: boolean;
};
-}
+}>;
diff --git a/src/plugins/share/server/url_service/http/short_urls/register_create_route.ts b/src/plugins/share/server/url_service/http/short_urls/register_create_route.ts
index 972641d160e28..1208f6fda4d1e 100644
--- a/src/plugins/share/server/url_service/http/short_urls/register_create_route.ts
+++ b/src/plugins/share/server/url_service/http/short_urls/register_create_route.ts
@@ -34,7 +34,7 @@ export const registerCreateRoute = (router: IRouter, url: ServerUrlService) => {
},
},
router.handleLegacyErrors(async (ctx, req, res) => {
- const savedObjects = ctx.core.savedObjects.client;
+ const savedObjects = (await ctx.core).savedObjects.client;
const shortUrls = url.shortUrls.get({ savedObjects });
const { locatorId, params, slug, humanReadableSlug } = req.body;
const locator = url.locators.get(locatorId);
diff --git a/src/plugins/share/server/url_service/http/short_urls/register_delete_route.ts b/src/plugins/share/server/url_service/http/short_urls/register_delete_route.ts
index 6e2b133ac3cff..ddc29117a3acc 100644
--- a/src/plugins/share/server/url_service/http/short_urls/register_delete_route.ts
+++ b/src/plugins/share/server/url_service/http/short_urls/register_delete_route.ts
@@ -25,7 +25,7 @@ export const registerDeleteRoute = (router: IRouter, url: ServerUrlService) => {
},
router.handleLegacyErrors(async (ctx, req, res) => {
const id = req.params.id;
- const savedObjects = ctx.core.savedObjects.client;
+ const savedObjects = (await ctx.core).savedObjects.client;
const shortUrls = url.shortUrls.get({ savedObjects });
await shortUrls.delete(id);
diff --git a/src/plugins/share/server/url_service/http/short_urls/register_get_route.ts b/src/plugins/share/server/url_service/http/short_urls/register_get_route.ts
index 7ece9b1ef6c63..8e783b3fcfd3d 100644
--- a/src/plugins/share/server/url_service/http/short_urls/register_get_route.ts
+++ b/src/plugins/share/server/url_service/http/short_urls/register_get_route.ts
@@ -25,7 +25,7 @@ export const registerGetRoute = (router: IRouter, url: ServerUrlService) => {
},
router.handleLegacyErrors(async (ctx, req, res) => {
const id = req.params.id;
- const savedObjects = ctx.core.savedObjects.client;
+ const savedObjects = (await ctx.core).savedObjects.client;
const shortUrls = url.shortUrls.get({ savedObjects });
const shortUrl = await shortUrls.get(id);
diff --git a/src/plugins/share/server/url_service/http/short_urls/register_resolve_route.ts b/src/plugins/share/server/url_service/http/short_urls/register_resolve_route.ts
index b4c73780bdf7c..47290d5754545 100644
--- a/src/plugins/share/server/url_service/http/short_urls/register_resolve_route.ts
+++ b/src/plugins/share/server/url_service/http/short_urls/register_resolve_route.ts
@@ -26,7 +26,7 @@ export const registerResolveRoute = (router: IRouter, url: ServerUrlService) =>
},
router.handleLegacyErrors(async (ctx, req, res) => {
const slug = req.params.slug;
- const savedObjects = ctx.core.savedObjects.client;
+ const savedObjects = (await ctx.core).savedObjects.client;
try {
const shortUrls = url.shortUrls.get({ savedObjects });
diff --git a/src/plugins/telemetry/server/routes/telemetry_opt_in.ts b/src/plugins/telemetry/server/routes/telemetry_opt_in.ts
index fff5df2dff100..06e443670518d 100644
--- a/src/plugins/telemetry/server/routes/telemetry_opt_in.ts
+++ b/src/plugins/telemetry/server/routes/telemetry_opt_in.ts
@@ -48,12 +48,13 @@ export function registerTelemetryOptInRoutes({
},
async (context, req, res) => {
const newOptInStatus = req.body.enabled;
+ const soClient = (await context.core).savedObjects.client;
const attributes: TelemetrySavedObjectAttributes = {
enabled: newOptInStatus,
lastVersionChecked: currentKibanaVersion,
};
const config = await firstValueFrom(config$);
- const telemetrySavedObject = await getTelemetrySavedObject(context.core.savedObjects.client);
+ const telemetrySavedObject = await getTelemetrySavedObject(soClient);
if (telemetrySavedObject === false) {
// If we get false, we couldn't get the saved object due to lack of permissions
@@ -96,7 +97,7 @@ export function registerTelemetryOptInRoutes({
}
try {
- await updateTelemetrySavedObject(context.core.savedObjects.client, attributes);
+ await updateTelemetrySavedObject(soClient, attributes);
} catch (e) {
if (SavedObjectsErrorHelpers.isForbiddenError(e)) {
return res.forbidden();
diff --git a/src/plugins/telemetry/server/routes/telemetry_user_has_seen_notice.ts b/src/plugins/telemetry/server/routes/telemetry_user_has_seen_notice.ts
index 686274dc4f5d3..cb990b68fd9b5 100644
--- a/src/plugins/telemetry/server/routes/telemetry_user_has_seen_notice.ts
+++ b/src/plugins/telemetry/server/routes/telemetry_user_has_seen_notice.ts
@@ -21,7 +21,7 @@ export function registerTelemetryUserHasSeenNotice(router: IRouter) {
validate: false,
},
async (context, req, res) => {
- const internalRepository = context.core.savedObjects.client;
+ const internalRepository = (await context.core).savedObjects.client;
const telemetrySavedObject: TelemetrySavedObject = await getTelemetrySavedObject(
internalRepository
);
diff --git a/src/plugins/unified_search/server/autocomplete/value_suggestions_route.ts b/src/plugins/unified_search/server/autocomplete/value_suggestions_route.ts
index 013401ee6d0d7..74a7e5202a541 100644
--- a/src/plugins/unified_search/server/autocomplete/value_suggestions_route.ts
+++ b/src/plugins/unified_search/server/autocomplete/value_suggestions_route.ts
@@ -45,13 +45,14 @@ export function registerValueSuggestionsRoute(router: IRouter, config$: Observab
const { field: fieldName, query, filters, fieldMeta, method } = request.body;
const { index } = request.params;
const abortSignal = getRequestAbortedSignal(request.events.aborted$);
+ const { savedObjects, elasticsearch } = await context.core;
try {
const fn = method === 'terms_agg' ? termsAggSuggestions : termsEnumSuggestions;
const body = await fn(
config,
- context.core.savedObjects.client,
- context.core.elasticsearch.client.asCurrentUser,
+ savedObjects.client,
+ elasticsearch.client.asCurrentUser,
index,
fieldName,
query,
diff --git a/src/plugins/usage_collection/server/routes/stats/stats.ts b/src/plugins/usage_collection/server/routes/stats/stats.ts
index 2c6c8e77d8cdf..d9c27afb5fb2a 100644
--- a/src/plugins/usage_collection/server/routes/stats/stats.ts
+++ b/src/plugins/usage_collection/server/routes/stats/stats.ts
@@ -89,8 +89,9 @@ export function registerStatsRoute({
let extended;
if (isExtended) {
- const { asCurrentUser } = context.core.elasticsearch.client;
- const savedObjectsClient = context.core.savedObjects.client;
+ const core = await context.core;
+ const { asCurrentUser } = core.elasticsearch.client;
+ const savedObjectsClient = core.savedObjects.client;
const [usage, clusterUuid] = await Promise.all([
shouldGetUsage
diff --git a/src/plugins/vis_types/timelion/server/routes/run.ts b/src/plugins/vis_types/timelion/server/routes/run.ts
index 5fb6ef6c0a3d3..e136f1ab5a241 100644
--- a/src/plugins/vis_types/timelion/server/routes/run.ts
+++ b/src/plugins/vis_types/timelion/server/routes/run.ts
@@ -77,10 +77,11 @@ export function runRoute(
},
router.handleLegacyErrors(async (context, request, response) => {
const [, { dataViews }] = await core.getStartServices();
- const uiSettings = await context.core.uiSettings.client.getAll();
+ const coreCtx = await context.core;
+ const uiSettings = await coreCtx.uiSettings.client.getAll();
const indexPatternsService = await dataViews.dataViewsServiceFactory(
- context.core.savedObjects.client,
- context.core.elasticsearch.client.asCurrentUser
+ coreCtx.savedObjects.client,
+ coreCtx.elasticsearch.client.asCurrentUser
);
const tlConfig = getTlConfig({
diff --git a/src/plugins/vis_types/timelion/server/series_functions/es/index.js b/src/plugins/vis_types/timelion/server/series_functions/es/index.js
index a86ee64f00568..2001a39bf7901 100644
--- a/src/plugins/vis_types/timelion/server/series_functions/es/index.js
+++ b/src/plugins/vis_types/timelion/server/series_functions/es/index.js
@@ -117,7 +117,8 @@ export default new Datasource('es', {
// we need to handle this scenario by aborting underlying server requests
const abortSignal = getRequestAbortedSignal(tlConfig.request.events.aborted$);
- const resp = await tlConfig.context.search
+ const searchContext = await tlConfig.context.search;
+ const resp = await searchContext
.search(
body,
{
diff --git a/src/plugins/vis_types/timeseries/server/lib/get_vis_data.ts b/src/plugins/vis_types/timeseries/server/lib/get_vis_data.ts
index a76132e0fbd21..360256ccb628b 100644
--- a/src/plugins/vis_types/timeseries/server/lib/get_vis_data.ts
+++ b/src/plugins/vis_types/timeseries/server/lib/get_vis_data.ts
@@ -28,7 +28,7 @@ export async function getVisData(
request: VisTypeTimeseriesVisDataRequest,
framework: Framework
): Promise {
- const uiSettings = requestContext.core.uiSettings.client;
+ const uiSettings = (await requestContext.core).uiSettings.client;
const esShardTimeout = await framework.getEsShardTimeout();
const fieldFormatService = await framework.getFieldFormatsService(uiSettings);
const indexPatternsService = await framework.getIndexPatternsService(requestContext);
diff --git a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts
index ae5dade8c5592..9fb7fc2a32317 100644
--- a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts
+++ b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts
@@ -84,7 +84,7 @@ describe('AbstractSearchStrategy', () => {
);
expect(responses).toEqual([{}]);
- expect(requestContext.search.search).toHaveBeenCalledWith(
+ expect((await requestContext.search).search).toHaveBeenCalledWith(
{
params: {
body: {},
diff --git a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts
index e89e999e583f0..167bc9cec8e03 100644
--- a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts
+++ b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts
@@ -46,11 +46,12 @@ export abstract class AbstractSearchStrategy {
// User may abort the request without waiting for the results
// we need to handle this scenario by aborting underlying server requests
const abortSignal = getRequestAbortedSignal(req.events.aborted$);
+ const searchContext = await requestContext.search;
esRequests.forEach(({ body, index, trackingEsSearchMeta }) => {
const startTime = Date.now();
requests.push(
- requestContext.search
+ searchContext
.search(
{
indexType,
diff --git a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/default_search_strategy.ts b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/default_search_strategy.ts
index f2c52b59bf0d9..ca20f87641f88 100644
--- a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/default_search_strategy.ts
+++ b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/default_search_strategy.ts
@@ -22,7 +22,7 @@ export class DefaultSearchStrategy extends AbstractSearchStrategy {
requestContext: VisTypeTimeseriesRequestHandlerContext,
req: VisTypeTimeseriesRequest
) {
- const uiSettings = requestContext.core.uiSettings.client;
+ const uiSettings = (await requestContext.core).uiSettings.client;
return {
isViable: true,
diff --git a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts
index dbc98e624b27a..35223f5159a86 100644
--- a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts
+++ b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts
@@ -38,10 +38,10 @@ export class RollupSearchStrategy extends AbstractSearchStrategy {
indexPattern: string
) {
try {
- const body =
- await requestContext.core.elasticsearch.client.asCurrentUser.rollup.getRollupIndexCaps({
- index: indexPattern,
- });
+ const esClient = (await requestContext.core).elasticsearch.client;
+ const body = await esClient.asCurrentUser.rollup.getRollupIndexCaps({
+ index: indexPattern,
+ });
return body;
} catch (e) {
@@ -64,7 +64,7 @@ export class RollupSearchStrategy extends AbstractSearchStrategy {
) {
const rollupData = await this.getRollupData(requestContext, indexPatternString);
const rollupIndices = getRollupIndices(rollupData);
- const uiSettings = requestContext.core.uiSettings.client;
+ const uiSettings = (await requestContext.core).uiSettings.client;
isViable = rollupIndices.length === 1;
diff --git a/src/plugins/vis_types/timeseries/server/plugin.ts b/src/plugins/vis_types/timeseries/server/plugin.ts
index e30758745627b..31ca2667ed3a7 100644
--- a/src/plugins/vis_types/timeseries/server/plugin.ts
+++ b/src/plugins/vis_types/timeseries/server/plugin.ts
@@ -109,10 +109,10 @@ export class VisTypeTimeseriesPlugin implements Plugin {
),
getIndexPatternsService: async (requestContext) => {
const [, { dataViews }] = await core.getStartServices();
-
+ const { elasticsearch, savedObjects } = await requestContext.core;
return await dataViews.dataViewsServiceFactory(
- requestContext.core.savedObjects.client,
- requestContext.core.elasticsearch.client.asCurrentUser
+ savedObjects.client,
+ elasticsearch.client.asCurrentUser
);
},
getFieldFormatsService: async (uiSettings) => {
diff --git a/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts b/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts
index aa86662871c29..a0f1ce279d652 100644
--- a/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts
+++ b/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts
@@ -6,15 +6,15 @@
* Side Public License, v 1.
*/
-import type { Plugin, CoreSetup, RequestHandlerContext } from '@kbn/core/server';
+import type { Plugin, CoreSetup, CustomRequestHandlerContext } from '@kbn/core/server';
export interface PluginAApiRequestContext {
ping: () => Promise;
}
-interface PluginARequstHandlerContext extends RequestHandlerContext {
+type PluginARequstHandlerContext = CustomRequestHandlerContext<{
pluginA: PluginAApiRequestContext;
-}
+}>;
export class CorePluginAPlugin implements Plugin {
public setup(core: CoreSetup, deps: {}) {
@@ -23,7 +23,8 @@ export class CorePluginAPlugin implements Plugin {
(context) => {
return {
ping: async () => {
- const body = await context.core.elasticsearch.client.asInternalUser.ping();
+ const esClient = (await context.core).elasticsearch.client;
+ const body = await esClient.asInternalUser.ping();
return String(body);
},
};
diff --git a/test/plugin_functional/plugins/core_plugin_b/server/plugin.ts b/test/plugin_functional/plugins/core_plugin_b/server/plugin.ts
index c9617eb81e8fb..9a34e82b38131 100644
--- a/test/plugin_functional/plugins/core_plugin_b/server/plugin.ts
+++ b/test/plugin_functional/plugins/core_plugin_b/server/plugin.ts
@@ -6,20 +6,21 @@
* Side Public License, v 1.
*/
-import { Plugin, CoreSetup, RequestHandlerContext } from '@kbn/core/server';
+import { Plugin, CoreSetup, CustomRequestHandlerContext } from '@kbn/core/server';
import { schema } from '@kbn/config-schema';
import { PluginAApiRequestContext } from '@kbn/core-plugin-a-plugin/server';
-interface PluginBContext extends RequestHandlerContext {
+type PluginBContext = CustomRequestHandlerContext<{
pluginA: PluginAApiRequestContext;
-}
+}>;
export class CorePluginBPlugin implements Plugin {
public setup(core: CoreSetup, deps: {}) {
const router = core.http.createRouter();
router.get({ path: '/core_plugin_b', validate: false }, async (context, req, res) => {
- if (!context.pluginA) throw new Error('pluginA is disabled');
- const response = await context.pluginA.ping();
+ const pluginAContext = await context.pluginA;
+ if (!pluginAContext) throw new Error('pluginA is disabled');
+ const response = await pluginAContext.ping();
return res.ok({ body: `Pong via plugin A: ${response}` });
});
diff --git a/test/plugin_functional/plugins/core_plugin_deprecations/server/routes.ts b/test/plugin_functional/plugins/core_plugin_deprecations/server/routes.ts
index ca7c17d1c94d2..aba6cd5b38e4c 100644
--- a/test/plugin_functional/plugins/core_plugin_deprecations/server/routes.ts
+++ b/test/plugin_functional/plugins/core_plugin_deprecations/server/routes.ts
@@ -33,7 +33,7 @@ export function registerRoutes(http: HttpServiceSetup) {
}
if (keyId) {
- const client = context.core.savedObjects.getClient();
+ const client = (await context.core).savedObjects.getClient();
await client.delete('test-deprecations-plugin', keyId, {
refresh: true,
});
diff --git a/test/plugin_functional/plugins/core_plugin_execution_context/server/plugin.ts b/test/plugin_functional/plugins/core_plugin_execution_context/server/plugin.ts
index 69001eb58b6f1..d7dad3f7b3d29 100644
--- a/test/plugin_functional/plugins/core_plugin_execution_context/server/plugin.ts
+++ b/test/plugin_functional/plugins/core_plugin_execution_context/server/plugin.ts
@@ -20,10 +20,8 @@ export class CorePluginExecutionContext implements Plugin {
},
},
async (context, request, response) => {
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
- {},
- { meta: true }
- );
+ const esClient = (await context.core).elasticsearch.client;
+ const { headers } = await esClient.asCurrentUser.ping({}, { meta: true });
return response.ok({ body: headers || {} });
}
);
diff --git a/test/plugin_functional/plugins/elasticsearch_client_plugin/server/plugin.ts b/test/plugin_functional/plugins/elasticsearch_client_plugin/server/plugin.ts
index d66069aa3ab64..ba161e05aaac8 100644
--- a/test/plugin_functional/plugins/elasticsearch_client_plugin/server/plugin.ts
+++ b/test/plugin_functional/plugins/elasticsearch_client_plugin/server/plugin.ts
@@ -10,12 +10,14 @@ import { Plugin, CoreSetup, CoreStart, ICustomClusterClient } from '@kbn/core/se
export class ElasticsearchClientPlugin implements Plugin {
private client?: ICustomClusterClient;
+
public setup(core: CoreSetup) {
const router = core.http.createRouter();
router.get(
{ path: '/api/elasticsearch_client_plugin/context/ping', validate: false },
async (context, req, res) => {
- const body = await context.core.elasticsearch.client.asInternalUser.ping();
+ const esClient = (await context.core).elasticsearch.client;
+ const body = await esClient.asInternalUser.ping();
return res.ok({ body: JSON.stringify(body) });
}
);
@@ -39,5 +41,6 @@ export class ElasticsearchClientPlugin implements Plugin {
public start(core: CoreStart) {
this.client = core.elasticsearch.createClient('my-custom-client-test');
}
+
public stop() {}
}
diff --git a/test/plugin_functional/plugins/ui_settings_plugin/server/plugin.ts b/test/plugin_functional/plugins/ui_settings_plugin/server/plugin.ts
index fee0773a76141..daa02f90426fa 100644
--- a/test/plugin_functional/plugins/ui_settings_plugin/server/plugin.ts
+++ b/test/plugin_functional/plugins/ui_settings_plugin/server/plugin.ts
@@ -23,13 +23,13 @@ export class UiSettingsPlugin implements Plugin {
const router = core.http.createRouter();
router.get({ path: '/api/ui-settings-plugin', validate: false }, async (context, req, res) => {
- const uiSettingsValue = await context.core.uiSettings.client.get(
- 'ui_settings_plugin'
- );
+ const { uiSettings } = await context.core;
+ const uiSettingsValue = await uiSettings.client.get('ui_settings_plugin');
return res.ok({ body: { uiSettingsValue } });
});
}
public start() {}
+
public stop() {}
}
diff --git a/x-pack/plugins/actions/server/plugin.ts b/x-pack/plugins/actions/server/plugin.ts
index 9d4a720eeae6b..ba8757b70b522 100644
--- a/x-pack/plugins/actions/server/plugin.ts
+++ b/x-pack/plugins/actions/server/plugin.ts
@@ -554,6 +554,8 @@ export class ActionsPlugin implements Plugin {
if (isESOCanEncrypt !== true) {
@@ -569,7 +571,7 @@ export class ActionsPlugin implements Plugin = await actionsClient.execute({
diff --git a/x-pack/plugins/actions/server/routes/get.ts b/x-pack/plugins/actions/server/routes/get.ts
index 64463c49c57be..352670bd5b170 100644
--- a/x-pack/plugins/actions/server/routes/get.ts
+++ b/x-pack/plugins/actions/server/routes/get.ts
@@ -41,7 +41,7 @@ export const getActionRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
const { id } = req.params;
return res.ok({
body: rewriteBodyRes(await actionsClient.get({ id })),
diff --git a/x-pack/plugins/actions/server/routes/get_all.ts b/x-pack/plugins/actions/server/routes/get_all.ts
index ebb357280f85e..3710b60ce5101 100644
--- a/x-pack/plugins/actions/server/routes/get_all.ts
+++ b/x-pack/plugins/actions/server/routes/get_all.ts
@@ -34,7 +34,7 @@ export const getAllActionRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
const result = await actionsClient.getAll();
return res.ok({
body: rewriteBodyRes(result),
diff --git a/x-pack/plugins/actions/server/routes/legacy/create.ts b/x-pack/plugins/actions/server/routes/legacy/create.ts
index 89b9f19d82633..120a7e5336235 100644
--- a/x-pack/plugins/actions/server/routes/legacy/create.ts
+++ b/x-pack/plugins/actions/server/routes/legacy/create.ts
@@ -35,7 +35,7 @@ export const createActionRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
const action = req.body;
trackLegacyRouteUsage('create', usageCounter);
return res.ok({
diff --git a/x-pack/plugins/actions/server/routes/legacy/delete.ts b/x-pack/plugins/actions/server/routes/legacy/delete.ts
index 59392c6592631..dd5f99aebd974 100644
--- a/x-pack/plugins/actions/server/routes/legacy/delete.ts
+++ b/x-pack/plugins/actions/server/routes/legacy/delete.ts
@@ -34,7 +34,7 @@ export const deleteActionRoute = (
if (!context.actions) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' });
}
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
const { id } = req.params;
trackLegacyRouteUsage('delete', usageCounter);
try {
diff --git a/x-pack/plugins/actions/server/routes/legacy/execute.ts b/x-pack/plugins/actions/server/routes/legacy/execute.ts
index 0616235cd52cb..e54e5f6c50397 100644
--- a/x-pack/plugins/actions/server/routes/legacy/execute.ts
+++ b/x-pack/plugins/actions/server/routes/legacy/execute.ts
@@ -43,7 +43,7 @@ export const executeActionRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' });
}
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
const { params } = req.body;
const { id } = req.params;
trackLegacyRouteUsage('execute', usageCounter);
diff --git a/x-pack/plugins/actions/server/routes/legacy/get.ts b/x-pack/plugins/actions/server/routes/legacy/get.ts
index 7612858c9fc8b..f103720233507 100644
--- a/x-pack/plugins/actions/server/routes/legacy/get.ts
+++ b/x-pack/plugins/actions/server/routes/legacy/get.ts
@@ -34,7 +34,7 @@ export const getActionRoute = (
if (!context.actions) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' });
}
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
const { id } = req.params;
trackLegacyRouteUsage('get', usageCounter);
return res.ok({
diff --git a/x-pack/plugins/actions/server/routes/legacy/get_all.ts b/x-pack/plugins/actions/server/routes/legacy/get_all.ts
index f968f4de85946..6fc478b04d51f 100644
--- a/x-pack/plugins/actions/server/routes/legacy/get_all.ts
+++ b/x-pack/plugins/actions/server/routes/legacy/get_all.ts
@@ -27,7 +27,7 @@ export const getAllActionRoute = (
if (!context.actions) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' });
}
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
const result = await actionsClient.getAll();
trackLegacyRouteUsage('getAll', usageCounter);
return res.ok({
diff --git a/x-pack/plugins/actions/server/routes/legacy/list_action_types.ts b/x-pack/plugins/actions/server/routes/legacy/list_action_types.ts
index 1c600b68b4e0e..92213c0b9be61 100644
--- a/x-pack/plugins/actions/server/routes/legacy/list_action_types.ts
+++ b/x-pack/plugins/actions/server/routes/legacy/list_action_types.ts
@@ -27,7 +27,7 @@ export const listActionTypesRoute = (
if (!context.actions) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' });
}
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
trackLegacyRouteUsage('listActionTypes', usageCounter);
return res.ok({
body: await actionsClient.listTypes(),
diff --git a/x-pack/plugins/actions/server/routes/legacy/update.ts b/x-pack/plugins/actions/server/routes/legacy/update.ts
index 28edcfd336898..a4e441d5d9846 100644
--- a/x-pack/plugins/actions/server/routes/legacy/update.ts
+++ b/x-pack/plugins/actions/server/routes/legacy/update.ts
@@ -41,7 +41,7 @@ export const updateActionRoute = (
if (!context.actions) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' });
}
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
const { id } = req.params;
const { name, config, secrets } = req.body;
trackLegacyRouteUsage('update', usageCounter);
diff --git a/x-pack/plugins/actions/server/routes/update.ts b/x-pack/plugins/actions/server/routes/update.ts
index 3f1ceb0a0096f..a8892c814fc66 100644
--- a/x-pack/plugins/actions/server/routes/update.ts
+++ b/x-pack/plugins/actions/server/routes/update.ts
@@ -48,7 +48,7 @@ export const updateActionRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const actionsClient = context.actions.getActionsClient();
+ const actionsClient = (await context.actions).getActionsClient();
const { id } = req.params;
const { name, config, secrets } = req.body;
diff --git a/x-pack/plugins/actions/server/types.ts b/x-pack/plugins/actions/server/types.ts
index b13df8dfe2460..9cb4f1aec63e8 100644
--- a/x-pack/plugins/actions/server/types.ts
+++ b/x-pack/plugins/actions/server/types.ts
@@ -12,7 +12,7 @@ import {
SavedObjectsClientContract,
SavedObjectAttributes,
ElasticsearchClient,
- RequestHandlerContext,
+ CustomRequestHandlerContext,
SavedObjectReference,
} from '@kbn/core/server';
import { ActionTypeRegistry } from './action_type_registry';
@@ -21,6 +21,7 @@ import { ActionsClient } from './actions_client';
import { ActionTypeExecutorResult } from '../common';
import { TaskInfo } from './lib/action_executor';
import { ConnectorTokenClient } from './builtin_action_types/lib/connector_token_client';
+
export type { ActionTypeExecutorResult } from '../common';
export type { GetFieldsByIssueTypeResponse as JiraGetFieldsResponse } from './builtin_action_types/jira/types';
export type { GetCommonFieldsResponse as ServiceNowGetFieldsResponse } from './builtin_action_types/servicenow/types';
@@ -46,9 +47,9 @@ export interface ActionsApiRequestHandlerContext {
listTypes: ActionTypeRegistry['list'];
}
-export interface ActionsRequestHandlerContext extends RequestHandlerContext {
+export type ActionsRequestHandlerContext = CustomRequestHandlerContext<{
actions: ActionsApiRequestHandlerContext;
-}
+}>;
export interface ActionsPlugin {
setup: PluginSetupContract;
@@ -97,6 +98,7 @@ interface ValidatorType {
export interface ActionValidationService {
isHostnameAllowed(hostname: string): boolean;
+
isUriAllowed(uri: string): boolean;
}
@@ -116,11 +118,13 @@ export interface ActionType<
secrets?: ValidatorType;
connector?: (config: Config, secrets: Secrets) => string | null;
};
+
renderParameterTemplates?(
params: Params,
variables: Record,
actionId?: string
): Params;
+
executor: ExecutorType;
}
@@ -146,6 +150,7 @@ interface PersistedActionTaskExecutorParams {
spaceId: string;
actionTaskParamsId: string;
}
+
interface EphemeralActionTaskExecutorParams {
spaceId: string;
taskParams: ActionTaskParams;
diff --git a/x-pack/plugins/alerting/server/routes/aggregate_rules.ts b/x-pack/plugins/alerting/server/routes/aggregate_rules.ts
index 5bba2b714d4d0..312def72dd65e 100644
--- a/x-pack/plugins/alerting/server/routes/aggregate_rules.ts
+++ b/x-pack/plugins/alerting/server/routes/aggregate_rules.ts
@@ -73,7 +73,7 @@ export const aggregateRulesRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const options = rewriteQueryReq({
...req.query,
has_reference: req.query.has_reference || undefined,
diff --git a/x-pack/plugins/alerting/server/routes/create_rule.ts b/x-pack/plugins/alerting/server/routes/create_rule.ts
index 5278f748f0ce4..cf044c94f2529 100644
--- a/x-pack/plugins/alerting/server/routes/create_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/create_rule.ts
@@ -110,7 +110,7 @@ export const createRuleRoute = ({ router, licenseState, usageCounter }: RouteOpt
handleDisabledApiKeysError(
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const rule = req.body;
const params = req.params;
diff --git a/x-pack/plugins/alerting/server/routes/delete_rule.ts b/x-pack/plugins/alerting/server/routes/delete_rule.ts
index 278bd031a8d6f..e4ccd491046d1 100644
--- a/x-pack/plugins/alerting/server/routes/delete_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/delete_rule.ts
@@ -28,7 +28,7 @@ export const deleteRuleRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
await rulesClient.delete({ id });
return res.noContent();
diff --git a/x-pack/plugins/alerting/server/routes/disable_rule.ts b/x-pack/plugins/alerting/server/routes/disable_rule.ts
index 6e6700c3ece4d..99795e7ee2bf2 100644
--- a/x-pack/plugins/alerting/server/routes/disable_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/disable_rule.ts
@@ -28,7 +28,7 @@ export const disableRuleRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
try {
await rulesClient.disable({ id });
diff --git a/x-pack/plugins/alerting/server/routes/enable_rule.ts b/x-pack/plugins/alerting/server/routes/enable_rule.ts
index f3b3c5bfbefdc..84a4086cd245c 100644
--- a/x-pack/plugins/alerting/server/routes/enable_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/enable_rule.ts
@@ -28,7 +28,7 @@ export const enableRuleRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
try {
await rulesClient.enable({ id });
diff --git a/x-pack/plugins/alerting/server/routes/find_rules.ts b/x-pack/plugins/alerting/server/routes/find_rules.ts
index 2c5819f7b7115..ef8b8b29057c0 100644
--- a/x-pack/plugins/alerting/server/routes/find_rules.ts
+++ b/x-pack/plugins/alerting/server/routes/find_rules.ts
@@ -140,7 +140,7 @@ const buildFindRulesRoute = ({
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
trackLegacyTerminology(
[req.query.search, req.query.search_fields, req.query.sort_field].filter(
diff --git a/x-pack/plugins/alerting/server/routes/get_rule.ts b/x-pack/plugins/alerting/server/routes/get_rule.ts
index 189401f03815c..f4414b0364dcb 100644
--- a/x-pack/plugins/alerting/server/routes/get_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/get_rule.ts
@@ -85,7 +85,7 @@ const buildGetRuleRoute = ({
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const rule = await rulesClient.get({ id, excludeFromPublicApi });
return res.ok({
diff --git a/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.ts b/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.ts
index 033c0f178cef7..c0d31d1ccbfac 100644
--- a/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.ts
+++ b/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.ts
@@ -72,7 +72,7 @@ export const getRuleAlertSummaryRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const summary = await rulesClient.getAlertSummary(rewriteReq({ id, ...req.query }));
return res.ok({ body: rewriteBodyRes(summary) });
diff --git a/x-pack/plugins/alerting/server/routes/get_rule_execution_log.ts b/x-pack/plugins/alerting/server/routes/get_rule_execution_log.ts
index 6f07c8daa14e7..650bdd83a0a83 100644
--- a/x-pack/plugins/alerting/server/routes/get_rule_execution_log.ts
+++ b/x-pack/plugins/alerting/server/routes/get_rule_execution_log.ts
@@ -67,7 +67,7 @@ export const getRuleExecutionLogRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
return res.ok({
body: await rulesClient.getExecutionLogForRule(rewriteReq({ id, ...req.query })),
diff --git a/x-pack/plugins/alerting/server/routes/get_rule_state.ts b/x-pack/plugins/alerting/server/routes/get_rule_state.ts
index 5f9bee59c4e70..50ad1f776110e 100644
--- a/x-pack/plugins/alerting/server/routes/get_rule_state.ts
+++ b/x-pack/plugins/alerting/server/routes/get_rule_state.ts
@@ -44,7 +44,7 @@ export const getRuleStateRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const state = await rulesClient.getAlertState({ id });
return state ? res.ok({ body: rewriteBodyRes(state) }) : res.noContent();
diff --git a/x-pack/plugins/alerting/server/routes/health.ts b/x-pack/plugins/alerting/server/routes/health.ts
index 4d9fcde896281..4d3934911221e 100644
--- a/x-pack/plugins/alerting/server/routes/health.ts
+++ b/x-pack/plugins/alerting/server/routes/health.ts
@@ -52,15 +52,16 @@ export const healthRoute = (
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
try {
+ const alertingContext = await context.alerting;
// Verify that user has access to at least one rule type
- const ruleTypes = Array.from(await context.alerting.getRulesClient().listAlertTypes());
+ const ruleTypes = Array.from(await alertingContext.getRulesClient().listAlertTypes());
if (ruleTypes.length > 0) {
- const alertingFrameworkHealth = await context.alerting.getFrameworkHealth();
+ const alertingFrameworkHealth = await alertingContext.getFrameworkHealth();
const securityHealth = await getSecurityHealth(
async () => (licenseState ? licenseState.getIsSecurityEnabled() : null),
async () => encryptedSavedObjects.canEncrypt,
- context.alerting.areApiKeysEnabled
+ alertingContext.areApiKeysEnabled
);
const frameworkHealth: AlertingFrameworkHealth = {
diff --git a/x-pack/plugins/alerting/server/routes/legacy/aggregate.ts b/x-pack/plugins/alerting/server/routes/legacy/aggregate.ts
index 67bb1a416d1c0..ba520cc401262 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/aggregate.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/aggregate.ts
@@ -53,7 +53,7 @@ export const aggregateAlertRoute = (
if (!context.alerting) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
trackLegacyRouteUsage('aggregate', usageCounter);
trackLegacyTerminology(
diff --git a/x-pack/plugins/alerting/server/routes/legacy/create.ts b/x-pack/plugins/alerting/server/routes/legacy/create.ts
index fb56279eaabc7..e7583033ae4ba 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/create.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/create.ts
@@ -64,7 +64,7 @@ export const createAlertRoute = ({ router, licenseState, usageCounter }: RouteOp
if (!context.alerting) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const alert = req.body;
const params = req.params;
const notifyWhen = alert?.notifyWhen ? (alert.notifyWhen as RuleNotifyWhenType) : null;
diff --git a/x-pack/plugins/alerting/server/routes/legacy/delete.ts b/x-pack/plugins/alerting/server/routes/legacy/delete.ts
index 4e29ded695181..4fcf85678db53 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/delete.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/delete.ts
@@ -35,7 +35,7 @@ export const deleteAlertRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('delete', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
await rulesClient.delete({ id });
return res.noContent();
diff --git a/x-pack/plugins/alerting/server/routes/legacy/disable.ts b/x-pack/plugins/alerting/server/routes/legacy/disable.ts
index b9ad5765e977e..5572220eb2171 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/disable.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/disable.ts
@@ -36,7 +36,7 @@ export const disableAlertRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('disable', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
try {
await rulesClient.disable({ id });
diff --git a/x-pack/plugins/alerting/server/routes/legacy/enable.ts b/x-pack/plugins/alerting/server/routes/legacy/enable.ts
index 6835be0631cb2..eb86b5db65da1 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/enable.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/enable.ts
@@ -38,7 +38,7 @@ export const enableAlertRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('enable', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
try {
await rulesClient.enable({ id });
diff --git a/x-pack/plugins/alerting/server/routes/legacy/find.ts b/x-pack/plugins/alerting/server/routes/legacy/find.ts
index e6d57572a2238..9a33f5b2dc5fd 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/find.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/find.ts
@@ -66,7 +66,7 @@ export const findAlertRoute = (
) as string[],
usageCounter
);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const query = req.query;
const renameMap = {
diff --git a/x-pack/plugins/alerting/server/routes/legacy/get.ts b/x-pack/plugins/alerting/server/routes/legacy/get.ts
index 82b56030de4cd..62fdde5507148 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/get.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/get.ts
@@ -35,7 +35,7 @@ export const getAlertRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('get', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
return res.ok({
body: await rulesClient.get({ id, excludeFromPublicApi: true }),
diff --git a/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.ts b/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.ts
index 7d467aed1b3fd..c33aea8060d77 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/get_alert_instance_summary.ts
@@ -46,7 +46,7 @@ export const getAlertInstanceSummaryRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('instanceSummary', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const { dateStart } = req.query;
const summary = await rulesClient.getAlertSummary({ id, dateStart });
diff --git a/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.ts b/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.ts
index 49a0daf5ea180..86a56403b39ae 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/get_alert_state.ts
@@ -35,7 +35,7 @@ export const getAlertStateRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('state', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const state = await rulesClient.getAlertState({ id });
return state ? res.ok({ body: state }) : res.noContent();
diff --git a/x-pack/plugins/alerting/server/routes/legacy/health.ts b/x-pack/plugins/alerting/server/routes/legacy/health.ts
index e9f770b437caa..02b8c8279b815 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/health.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/health.ts
@@ -32,15 +32,16 @@ export function healthRoute(
}
trackLegacyRouteUsage('health', usageCounter);
try {
+ const alertingContext = await context.alerting;
// Verify that user has access to at least one rule type
- const ruleTypes = Array.from(await context.alerting.getRulesClient().listAlertTypes());
+ const ruleTypes = Array.from(await alertingContext.getRulesClient().listAlertTypes());
if (ruleTypes.length > 0) {
- const alertingFrameworkHealth = await context.alerting.getFrameworkHealth();
+ const alertingFrameworkHealth = await alertingContext.getFrameworkHealth();
const securityHealth = await getSecurityHealth(
async () => (licenseState ? licenseState.getIsSecurityEnabled() : null),
async () => encryptedSavedObjects.canEncrypt,
- context.alerting.areApiKeysEnabled
+ alertingContext.areApiKeysEnabled
);
const frameworkHealth: AlertingFrameworkHealth = {
diff --git a/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.ts b/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.ts
index 5c0ef90ccc5e2..8cfef8af46247 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.ts
@@ -27,8 +27,9 @@ export const listAlertTypesRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('listAlertTypes', usageCounter);
+ const alertingContext = await context.alerting;
return res.ok({
- body: Array.from(await context.alerting.getRulesClient().listAlertTypes()),
+ body: Array.from(await alertingContext.getRulesClient().listAlertTypes()),
});
})
);
diff --git a/x-pack/plugins/alerting/server/routes/legacy/mute_all.ts b/x-pack/plugins/alerting/server/routes/legacy/mute_all.ts
index 2b16b332c9cbb..dcbc0c19dbe35 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/mute_all.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/mute_all.ts
@@ -36,7 +36,7 @@ export const muteAllAlertRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('muteAll', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
try {
await rulesClient.muteAll({ id });
diff --git a/x-pack/plugins/alerting/server/routes/legacy/mute_instance.ts b/x-pack/plugins/alerting/server/routes/legacy/mute_instance.ts
index 50c4a3de95893..f6c6a28ecc865 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/mute_instance.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/mute_instance.ts
@@ -41,7 +41,7 @@ export const muteAlertInstanceRoute = (
trackLegacyRouteUsage('muteInstance', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const renameMap = {
alert_id: 'alertId',
diff --git a/x-pack/plugins/alerting/server/routes/legacy/unmute_all.ts b/x-pack/plugins/alerting/server/routes/legacy/unmute_all.ts
index 34297624b45d6..31f82849ea1da 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/unmute_all.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/unmute_all.ts
@@ -36,7 +36,7 @@ export const unmuteAllAlertRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('unmuteAll', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
try {
await rulesClient.unmuteAll({ id });
diff --git a/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.ts b/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.ts
index 8f3b1f2413953..4d5b9b02da5f1 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/unmute_instance.ts
@@ -37,7 +37,7 @@ export const unmuteAlertInstanceRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('unmuteInstance', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { alertId, alertInstanceId } = req.params;
try {
await rulesClient.unmuteInstance({ alertId, alertInstanceId });
diff --git a/x-pack/plugins/alerting/server/routes/legacy/update.ts b/x-pack/plugins/alerting/server/routes/legacy/update.ts
index 415d2f0af4a60..07bde524076c1 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/update.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/update.ts
@@ -64,7 +64,7 @@ export const updateAlertRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('update', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const { name, actions, params, schedule, tags, throttle, notifyWhen } = req.body;
try {
diff --git a/x-pack/plugins/alerting/server/routes/legacy/update_api_key.ts b/x-pack/plugins/alerting/server/routes/legacy/update_api_key.ts
index 3c288219812ca..f0f7716b00771 100644
--- a/x-pack/plugins/alerting/server/routes/legacy/update_api_key.ts
+++ b/x-pack/plugins/alerting/server/routes/legacy/update_api_key.ts
@@ -38,7 +38,7 @@ export const updateApiKeyRoute = (
return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' });
}
trackLegacyRouteUsage('updateApiKey', usageCounter);
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
try {
await rulesClient.updateApiKey({ id });
diff --git a/x-pack/plugins/alerting/server/routes/mute_alert.ts b/x-pack/plugins/alerting/server/routes/mute_alert.ts
index a90dc77e5fb6b..22d9a1670dde5 100644
--- a/x-pack/plugins/alerting/server/routes/mute_alert.ts
+++ b/x-pack/plugins/alerting/server/routes/mute_alert.ts
@@ -38,7 +38,7 @@ export const muteAlertRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const params = rewriteParamsReq(req.params);
try {
await rulesClient.muteInstance(params);
diff --git a/x-pack/plugins/alerting/server/routes/mute_all_rule.ts b/x-pack/plugins/alerting/server/routes/mute_all_rule.ts
index e9d64ce3e30f0..41b561db0b2fd 100644
--- a/x-pack/plugins/alerting/server/routes/mute_all_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/mute_all_rule.ts
@@ -31,7 +31,7 @@ export const muteAllRuleRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
trackDeprecatedRouteUsage('muteAll', usageCounter);
try {
diff --git a/x-pack/plugins/alerting/server/routes/resolve_rule.ts b/x-pack/plugins/alerting/server/routes/resolve_rule.ts
index 02c70c555fc0d..cde747f9272fe 100644
--- a/x-pack/plugins/alerting/server/routes/resolve_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/resolve_rule.ts
@@ -73,7 +73,7 @@ export const resolveRuleRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const rule = await rulesClient.resolve({ id });
return res.ok({
diff --git a/x-pack/plugins/alerting/server/routes/rule_types.ts b/x-pack/plugins/alerting/server/routes/rule_types.ts
index f78a0ef3ee89e..5d6c9e9a3f0f4 100644
--- a/x-pack/plugins/alerting/server/routes/rule_types.ts
+++ b/x-pack/plugins/alerting/server/routes/rule_types.ts
@@ -54,7 +54,8 @@ export const ruleTypesRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const ruleTypes = Array.from(await context.alerting.getRulesClient().listAlertTypes());
+ const rulesClient = (await context.alerting).getRulesClient();
+ const ruleTypes = Array.from(await rulesClient.listAlertTypes());
return res.ok({
body: rewriteBodyRes(ruleTypes),
});
diff --git a/x-pack/plugins/alerting/server/routes/snooze_rule.ts b/x-pack/plugins/alerting/server/routes/snooze_rule.ts
index ed717de973c9a..a408a4d3175df 100644
--- a/x-pack/plugins/alerting/server/routes/snooze_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/snooze_rule.ts
@@ -44,7 +44,7 @@ export const snoozeRuleRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const params = req.params;
const body = rewriteBodyReq(req.body);
try {
diff --git a/x-pack/plugins/alerting/server/routes/unmute_alert.ts b/x-pack/plugins/alerting/server/routes/unmute_alert.ts
index 6b02674de0267..1e4191745f621 100644
--- a/x-pack/plugins/alerting/server/routes/unmute_alert.ts
+++ b/x-pack/plugins/alerting/server/routes/unmute_alert.ts
@@ -38,7 +38,7 @@ export const unmuteAlertRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const params = rewriteParamsReq(req.params);
try {
await rulesClient.unmuteInstance(params);
diff --git a/x-pack/plugins/alerting/server/routes/unmute_all_rule.ts b/x-pack/plugins/alerting/server/routes/unmute_all_rule.ts
index bead959a6d7d8..4e102f96cf381 100644
--- a/x-pack/plugins/alerting/server/routes/unmute_all_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/unmute_all_rule.ts
@@ -28,7 +28,7 @@ export const unmuteAllRuleRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
try {
await rulesClient.unmuteAll({ id });
diff --git a/x-pack/plugins/alerting/server/routes/unsnooze_rule.ts b/x-pack/plugins/alerting/server/routes/unsnooze_rule.ts
index f0c1a9a12ac50..b91fb24bea56a 100644
--- a/x-pack/plugins/alerting/server/routes/unsnooze_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/unsnooze_rule.ts
@@ -28,7 +28,7 @@ export const unsnoozeRuleRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const params = req.params;
try {
await rulesClient.unsnooze({ ...params });
diff --git a/x-pack/plugins/alerting/server/routes/update_rule.ts b/x-pack/plugins/alerting/server/routes/update_rule.ts
index f58e61b5d1ac2..d2130e1f33541 100644
--- a/x-pack/plugins/alerting/server/routes/update_rule.ts
+++ b/x-pack/plugins/alerting/server/routes/update_rule.ts
@@ -119,7 +119,7 @@ export const updateRuleRoute = (
handleDisabledApiKeysError(
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
const rule = req.body;
try {
diff --git a/x-pack/plugins/alerting/server/routes/update_rule_api_key.ts b/x-pack/plugins/alerting/server/routes/update_rule_api_key.ts
index af10d97bc2a97..4e99b54e76af4 100644
--- a/x-pack/plugins/alerting/server/routes/update_rule_api_key.ts
+++ b/x-pack/plugins/alerting/server/routes/update_rule_api_key.ts
@@ -28,7 +28,7 @@ export const updateRuleApiKeyRoute = (
},
router.handleLegacyErrors(
verifyAccessAndContext(licenseState, async function (context, req, res) {
- const rulesClient = context.alerting.getRulesClient();
+ const rulesClient = (await context.alerting).getRulesClient();
const { id } = req.params;
try {
await rulesClient.updateApiKey({ id });
diff --git a/x-pack/plugins/alerting/server/types.ts b/x-pack/plugins/alerting/server/types.ts
index 7469bdfd98277..32c6e41c63268 100644
--- a/x-pack/plugins/alerting/server/types.ts
+++ b/x-pack/plugins/alerting/server/types.ts
@@ -7,18 +7,16 @@
import type {
IRouter,
- RequestHandlerContext,
+ CustomRequestHandlerContext,
SavedObjectReference,
IUiSettingsClient,
-} from '@kbn/core/server';
-import type { PublicMethodsOf } from '@kbn/utility-types';
-import { ISearchStartSearchSource } from '@kbn/data-plugin/common';
-import { LicenseType } from '@kbn/licensing-plugin/server';
-import {
IScopedClusterClient,
SavedObjectAttributes,
SavedObjectsClientContract,
} from '@kbn/core/server';
+import type { PublicMethodsOf } from '@kbn/utility-types';
+import { ISearchStartSearchSource } from '@kbn/data-plugin/common';
+import { LicenseType } from '@kbn/licensing-plugin/server';
import { AlertFactoryDoneUtils, PublicAlert } from './alert';
import { RuleTypeRegistry as OrigruleTypeRegistry } from './rule_type_registry';
import { PluginSetupContract, PluginStartContract } from './plugin';
@@ -60,9 +58,9 @@ export interface AlertingApiRequestHandlerContext {
/**
* @internal
*/
-export interface AlertingRequestHandlerContext extends RequestHandlerContext {
+export type AlertingRequestHandlerContext = CustomRequestHandlerContext<{
alerting: AlertingApiRequestHandlerContext;
-}
+}>;
/**
* @internal
diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts
index f494a39956f2b..522fd5c078af3 100644
--- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts
@@ -21,14 +21,16 @@ import { cancelEsRequestOnAbort } from '../cancel_es_request_on_abort';
export type APMIndexDocumentParams = estypes.IndexRequest;
-export type APMInternalClient = ReturnType;
+export type APMInternalClient = Awaited<
+ ReturnType
+>;
-export function createInternalESClient({
+export async function createInternalESClient({
context,
debug,
request,
}: Pick & { debug: boolean }) {
- const { asInternalUser } = context.core.elasticsearch.client;
+ const { asInternalUser } = (await context.core).elasticsearch.client;
function callEs(
operationName: string,
diff --git a/x-pack/plugins/apm/server/lib/helpers/setup_request.ts b/x-pack/plugins/apm/server/lib/helpers/setup_request.ts
index a3eb942111a48..2701d754350f5 100644
--- a/x-pack/plugins/apm/server/lib/helpers/setup_request.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/setup_request.ts
@@ -42,36 +42,38 @@ export async function setupRequest({
}: APMRouteHandlerResources) {
return withApmSpan('setup_request', async () => {
const { query } = params;
+ const coreContext = await context.core;
+ const licensingContext = await context.licensing;
const [indices, includeFrozen] = await Promise.all([
getApmIndices({
- savedObjectsClient: context.core.savedObjects.client,
+ savedObjectsClient: coreContext.savedObjects.client,
config,
}),
withApmSpan('get_ui_settings', () =>
- context.core.uiSettings.client.get(UI_SETTINGS.SEARCH_INCLUDE_FROZEN)
+ coreContext.uiSettings.client.get(UI_SETTINGS.SEARCH_INCLUDE_FROZEN)
),
]);
return {
indices,
apmEventClient: new APMEventClient({
- esClient: context.core.elasticsearch.client.asCurrentUser,
+ esClient: coreContext.elasticsearch.client.asCurrentUser,
debug: query._inspect,
request,
indices,
options: { includeFrozen },
}),
- internalClient: createInternalESClient({
+ internalClient: await createInternalESClient({
context,
request,
debug: query._inspect,
}),
ml:
- plugins.ml && isActivePlatinumLicense(context.licensing.license)
+ plugins.ml && isActivePlatinumLicense(licensingContext.license)
? getMlSetup(
plugins.ml.setup,
- context.core.savedObjects.client,
+ coreContext.savedObjects.client,
request
)
: undefined,
@@ -82,7 +84,9 @@ export async function setupRequest({
function getMlSetup(
ml: Required['ml']['setup'],
- savedObjectsClient: APMRouteHandlerResources['context']['core']['savedObjects']['client'],
+ savedObjectsClient: Awaited<
+ APMRouteHandlerResources['context']['core']
+ >['savedObjects']['client'],
request: KibanaRequest
) {
return {
diff --git a/x-pack/plugins/apm/server/plugin.ts b/x-pack/plugins/apm/server/plugin.ts
index bc4c0d30a9a81..ad058a535206e 100644
--- a/x-pack/plugins/apm/server/plugin.ts
+++ b/x-pack/plugins/apm/server/plugin.ts
@@ -218,12 +218,13 @@ export class APMPlugin
request: KibanaRequest;
context: ApmPluginRequestHandlerContext;
}) => {
+ const coreContext = await context.core;
const [indices, includeFrozen] = await Promise.all([
boundGetApmIndices(),
- context.core.uiSettings.client.get(UI_SETTINGS.SEARCH_INCLUDE_FROZEN),
+ coreContext.uiSettings.client.get(UI_SETTINGS.SEARCH_INCLUDE_FROZEN),
]);
- const esClient = context.core.elasticsearch.client.asCurrentUser;
+ const esClient = coreContext.elasticsearch.client.asCurrentUser;
return new APMEventClient({
debug: debug ?? false,
diff --git a/x-pack/plugins/apm/server/routes/agent_keys/create_agent_key.ts b/x-pack/plugins/apm/server/routes/agent_keys/create_agent_key.ts
index 3b47b81a86416..0bcd85a88ce8c 100644
--- a/x-pack/plugins/apm/server/routes/agent_keys/create_agent_key.ts
+++ b/x-pack/plugins/apm/server/routes/agent_keys/create_agent_key.ts
@@ -26,6 +26,7 @@ export async function createAgentKey({
privileges,
resources: [resource],
};
+ const coreContext = await context.core;
// Elasticsearch will allow a user without the right apm privileges to create API keys, but the keys won't validate
// check first whether the user has the right privileges, and bail out early if not
@@ -33,7 +34,7 @@ export async function createAgentKey({
application: userApplicationPrivileges,
username,
has_all_requested: hasRequiredPrivileges,
- } = await context.core.elasticsearch.client.asCurrentUser.security.hasPrivileges(
+ } = await coreContext.elasticsearch.client.asCurrentUser.security.hasPrivileges(
{
body: {
application: [application],
@@ -80,11 +81,9 @@ export async function createAgentKey({
};
const agentKey =
- await context.core.elasticsearch.client.asCurrentUser.security.createApiKey(
- {
- body,
- }
- );
+ await coreContext.elasticsearch.client.asCurrentUser.security.createApiKey({
+ body,
+ });
return {
agentKey,
diff --git a/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys.ts b/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys.ts
index ee01876d743d4..239cc6ca896c4 100644
--- a/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys.ts
+++ b/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys.ts
@@ -27,7 +27,7 @@ export async function getAgentKeys({
},
};
- const esClient = context.core.elasticsearch.client;
+ const esClient = (await context.core).elasticsearch.client;
const apiResponse = await esClient.asCurrentUser.transport.request<{
api_keys: ApiKey[];
}>({
diff --git a/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts b/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts
index 29514739f2225..c9fba5d6ec71e 100644
--- a/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts
+++ b/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts
@@ -15,8 +15,9 @@ export async function getAgentKeysPrivileges({
context: ApmPluginRequestHandlerContext;
securityPluginStart: NonNullable;
}) {
+ const esClient = (await context.core).elasticsearch.client;
const [securityHasPrivilegesResponse, areApiKeysEnabled] = await Promise.all([
- context.core.elasticsearch.client.asCurrentUser.security.hasPrivileges({
+ esClient.asCurrentUser.security.hasPrivileges({
body: {
cluster: ['manage_security', 'manage_api_key', 'manage_own_api_key'],
},
diff --git a/x-pack/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts b/x-pack/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts
index ec244f8e9bee3..95ee67f0dff37 100644
--- a/x-pack/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts
+++ b/x-pack/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts
@@ -15,12 +15,11 @@ export async function invalidateAgentKey({
id: string;
isAdmin: boolean;
}) {
+ const esClient = (await context.core).elasticsearch.client;
const { invalidated_api_keys: invalidatedAgentKeys } =
- await context.core.elasticsearch.client.asCurrentUser.security.invalidateApiKey(
- {
- body: { ids: [id], owner: !isAdmin },
- }
- );
+ await esClient.asCurrentUser.security.invalidateApiKey({
+ body: { ids: [id], owner: !isAdmin },
+ });
return {
invalidatedAgentKeys,
diff --git a/x-pack/plugins/apm/server/routes/correlations/route.ts b/x-pack/plugins/apm/server/routes/correlations/route.ts
index 897ca65c37ca1..b2bca48574f5d 100644
--- a/x-pack/plugins/apm/server/routes/correlations/route.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/route.ts
@@ -57,12 +57,14 @@ const fieldCandidatesRoute = createApmServerRoute({
options: { tags: ['access:apm'] },
handler: async (resources): Promise<{ fieldCandidates: string[] }> => {
const { context } = resources;
- if (!isActivePlatinumLicense(context.licensing.license)) {
+ const { license } = await context.licensing;
+ if (!isActivePlatinumLicense(license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const { indices } = await setupRequest(resources);
- const esClient = resources.context.core.elasticsearch.client.asCurrentUser;
+ const esClient = (await resources.context.core).elasticsearch.client
+ .asCurrentUser;
return withApmSpan(
'get_correlations_field_candidates',
@@ -102,12 +104,14 @@ const fieldStatsRoute = createApmServerRoute({
errors: any[];
}> => {
const { context } = resources;
- if (!isActivePlatinumLicense(context.licensing.license)) {
+ const { license } = await context.licensing;
+ if (!isActivePlatinumLicense(license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const { indices } = await setupRequest(resources);
- const esClient = resources.context.core.elasticsearch.client.asCurrentUser;
+ const esClient = (await resources.context.core).elasticsearch.client
+ .asCurrentUser;
const { fieldsToSample, ...params } = resources.params.body;
@@ -151,12 +155,14 @@ const fieldValueStatsRoute = createApmServerRoute({
import('./../../../common/correlations/field_stats_types').TopValuesStats
> => {
const { context } = resources;
- if (!isActivePlatinumLicense(context.licensing.license)) {
+ const { license } = await context.licensing;
+ if (!isActivePlatinumLicense(license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const { indices } = await setupRequest(resources);
- const esClient = resources.context.core.elasticsearch.client.asCurrentUser;
+ const esClient = (await resources.context.core).elasticsearch.client
+ .asCurrentUser;
const { fieldName, fieldValue, ...params } = resources.params.query;
@@ -202,12 +208,14 @@ const fieldValuePairsRoute = createApmServerRoute({
errors: any[];
}> => {
const { context } = resources;
- if (!isActivePlatinumLicense(context.licensing.license)) {
+ const { license } = await context.licensing;
+ if (!isActivePlatinumLicense(license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const { indices } = await setupRequest(resources);
- const esClient = resources.context.core.elasticsearch.client.asCurrentUser;
+ const esClient = (await resources.context.core).elasticsearch.client
+ .asCurrentUser;
const { fieldCandidates, ...params } = resources.params.body;
@@ -260,12 +268,14 @@ const significantCorrelationsRoute = createApmServerRoute({
fallbackResult?: import('./../../../common/correlations/latency_correlations/types').LatencyCorrelation;
}> => {
const { context } = resources;
- if (!isActivePlatinumLicense(context.licensing.license)) {
+ const { license } = await context.licensing;
+ if (!isActivePlatinumLicense(license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const { indices } = await setupRequest(resources);
- const esClient = resources.context.core.elasticsearch.client.asCurrentUser;
+ const esClient = (await resources.context.core).elasticsearch.client
+ .asCurrentUser;
const { fieldValuePairs, ...params } = resources.params.body;
@@ -318,12 +328,14 @@ const pValuesRoute = createApmServerRoute({
fallbackResult?: import('./../../../common/correlations/failed_transactions_correlations/types').FailedTransactionsCorrelation;
}> => {
const { context } = resources;
- if (!isActivePlatinumLicense(context.licensing.license)) {
+ const { license } = await context.licensing;
+ if (!isActivePlatinumLicense(license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const { indices } = await setupRequest(resources);
- const esClient = resources.context.core.elasticsearch.client.asCurrentUser;
+ const esClient = (await resources.context.core).elasticsearch.client
+ .asCurrentUser;
const { fieldCandidates, ...params } = resources.params.body;
diff --git a/x-pack/plugins/apm/server/routes/data_view/get_dynamic_data_view.ts b/x-pack/plugins/apm/server/routes/data_view/get_dynamic_data_view.ts
index 6a0d52eadd228..8d2c61cce4d81 100644
--- a/x-pack/plugins/apm/server/routes/data_view/get_dynamic_data_view.ts
+++ b/x-pack/plugins/apm/server/routes/data_view/get_dynamic_data_view.ts
@@ -23,14 +23,15 @@ export const getDynamicDataView = ({
logger,
}: Pick) => {
return withApmSpan('get_dynamic_data_view', async () => {
+ const coreContext = await context.core;
const apmIndicies = await getApmIndices({
- savedObjectsClient: context.core.savedObjects.client,
+ savedObjectsClient: coreContext.savedObjects.client,
config,
});
const dataViewTitle = getApmDataViewTitle(apmIndicies);
const DataViewsFetcher = new IndexPatternsFetcher(
- context.core.elasticsearch.client.asCurrentUser
+ coreContext.elasticsearch.client.asCurrentUser
);
// Since `getDynamicDataView` is called in setup_request (and thus by every endpoint)
diff --git a/x-pack/plugins/apm/server/routes/environments/route.ts b/x-pack/plugins/apm/server/routes/environments/route.ts
index f8be45ecf0d59..03fb07fd51cb8 100644
--- a/x-pack/plugins/apm/server/routes/environments/route.ts
+++ b/x-pack/plugins/apm/server/routes/environments/route.ts
@@ -46,7 +46,8 @@ const environmentsRoute = createApmServerRoute({
end,
kuery: '',
});
- const size = await context.core.uiSettings.client.get(
+ const coreContext = await context.core;
+ const size = await coreContext.uiSettings.client.get(
maxSuggestions
);
const environments = await getEnvironments({
diff --git a/x-pack/plugins/apm/server/routes/fleet/route.ts b/x-pack/plugins/apm/server/routes/fleet/route.ts
index 2b6412647641c..76f05d50fff41 100644
--- a/x-pack/plugins/apm/server/routes/fleet/route.ts
+++ b/x-pack/plugins/apm/server/routes/fleet/route.ts
@@ -157,7 +157,7 @@ const getUnsupportedApmServerSchemaRoute = createApmServerRoute({
resources
): Promise<{ unsupported: Array<{ key: string; value: any }> }> => {
const { context } = resources;
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
return {
unsupported: await getUnsupportedApmServerSchema({ savedObjectsClient }),
};
@@ -185,7 +185,7 @@ const getMigrationCheckRoute = createApmServerRoute({
if (!plugins.fleet || !plugins.security) {
throw Boom.internal(FLEET_SECURITY_REQUIRED_MESSAGE);
}
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const [fleetPluginStart, securityPluginStart] = await Promise.all([
plugins.fleet.start(),
plugins.security.start(),
@@ -231,7 +231,7 @@ const createCloudApmPackagePolicyRoute = createApmServerRoute({
if (!plugins.fleet || !plugins.security) {
throw Boom.internal(FLEET_SECURITY_REQUIRED_MESSAGE);
}
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const coreStart = await resources.core.start();
const esClient = coreStart.elasticsearch.client.asScoped(
resources.request
diff --git a/x-pack/plugins/apm/server/routes/service_groups/route.ts b/x-pack/plugins/apm/server/routes/service_groups/route.ts
index b9e6a238ba261..160aea5abfe70 100644
--- a/x-pack/plugins/apm/server/routes/service_groups/route.ts
+++ b/x-pack/plugins/apm/server/routes/service_groups/route.ts
@@ -28,7 +28,7 @@ const serviceGroupsRoute = createApmServerRoute({
resources
): Promise<{ serviceGroups: SavedServiceGroup[] }> => {
const { context } = resources;
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const serviceGroups = await getServiceGroups({ savedObjectsClient });
return { serviceGroups };
},
@@ -46,7 +46,7 @@ const serviceGroupRoute = createApmServerRoute({
},
handler: async (resources): Promise<{ serviceGroup: SavedServiceGroup }> => {
const { context, params } = resources;
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const serviceGroup = await getServiceGroup({
savedObjectsClient,
serviceGroupId: params.query.serviceGroup,
@@ -75,7 +75,7 @@ const serviceGroupSaveRoute = createApmServerRoute({
handler: async (resources): Promise => {
const { context, params } = resources;
const { start, end, serviceGroupId } = params.query;
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const setup = await setupRequest(resources);
const items = await lookupServices({
setup,
@@ -107,7 +107,7 @@ const serviceGroupDeleteRoute = createApmServerRoute({
handler: async (resources): Promise => {
const { context, params } = resources;
const { serviceGroupId } = params.query;
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
await deleteServiceGroup({
savedObjectsClient,
serviceGroupId,
diff --git a/x-pack/plugins/apm/server/routes/service_map/route.ts b/x-pack/plugins/apm/server/routes/service_map/route.ts
index b357958d219a9..0bad4c251fddb 100644
--- a/x-pack/plugins/apm/server/routes/service_map/route.ts
+++ b/x-pack/plugins/apm/server/routes/service_map/route.ts
@@ -88,12 +88,14 @@ const serviceMapRoute = createApmServerRoute({
if (!config.serviceMapEnabled) {
throw Boom.notFound();
}
- if (!isActivePlatinumLicense(context.licensing.license)) {
+
+ const licensingContext = await context.licensing;
+ if (!isActivePlatinumLicense(licensingContext.license)) {
throw Boom.forbidden(invalidLicenseMessage);
}
notifyFeatureUsage({
- licensingPlugin: context.licensing,
+ licensingPlugin: licensingContext,
featureName: 'serviceMaps',
});
@@ -107,7 +109,7 @@ const serviceMapRoute = createApmServerRoute({
},
} = params;
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const [setup, serviceGroup] = await Promise.all([
setupRequest(resources),
serviceGroupId
@@ -164,7 +166,9 @@ const serviceMapServiceNodeRoute = createApmServerRoute({
if (!config.serviceMapEnabled) {
throw Boom.notFound();
}
- if (!isActivePlatinumLicense(context.licensing.license)) {
+
+ const licensingContext = await context.licensing;
+ if (!isActivePlatinumLicense(licensingContext.license)) {
throw Boom.forbidden(invalidLicenseMessage);
}
const setup = await setupRequest(resources);
@@ -226,7 +230,8 @@ const serviceMapBackendNodeRoute = createApmServerRoute({
if (!config.serviceMapEnabled) {
throw Boom.notFound();
}
- if (!isActivePlatinumLicense(context.licensing.license)) {
+ const licensingContext = await context.licensing;
+ if (!isActivePlatinumLicense(licensingContext.license)) {
throw Boom.forbidden(invalidLicenseMessage);
}
const setup = await setupRequest(resources);
diff --git a/x-pack/plugins/apm/server/routes/services/route.ts b/x-pack/plugins/apm/server/routes/services/route.ts
index 0bcdca6e3cb89..63a52da218d1a 100644
--- a/x-pack/plugins/apm/server/routes/services/route.ts
+++ b/x-pack/plugins/apm/server/routes/services/route.ts
@@ -113,7 +113,7 @@ const servicesRoute = createApmServerRoute({
serviceGroup: serviceGroupId,
probability,
} = params.query;
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const [setup, serviceGroup] = await Promise.all([
setupRequest(resources),
@@ -403,6 +403,7 @@ const serviceAnnotationsRoute = createApmServerRoute({
const { params, plugins, context, request, logger } = resources;
const { serviceName } = params.path;
const { environment, start, end } = params.query;
+ const esClient = (await context.core).elasticsearch.client;
const { observability } = plugins;
@@ -431,7 +432,7 @@ const serviceAnnotationsRoute = createApmServerRoute({
searchAggregatedTransactions,
serviceName,
annotationsClient,
- client: context.core.elasticsearch.client.asCurrentUser,
+ client: esClient.asCurrentUser,
logger,
start,
end,
@@ -1238,7 +1239,8 @@ const sortedAndFilteredServicesRoute = createApmServerRoute({
};
}
- const savedObjectsClient = resources.context.core.savedObjects.client;
+ const savedObjectsClient = (await resources.context.core).savedObjects
+ .client;
const [setup, serviceGroup] = await Promise.all([
setupRequest(resources),
diff --git a/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts
index 3618647717e50..72869ef165fa2 100644
--- a/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts
+++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts
@@ -269,6 +269,7 @@ const listAgentConfigurationEnvironmentsRoute = createApmServerRoute({
}> => {
const setup = await setupRequest(resources);
const { context, params } = resources;
+ const coreContext = await context.core;
const { serviceName, start, end } = params.query;
const searchAggregatedTransactions = await getSearchAggregatedTransactions({
@@ -278,7 +279,7 @@ const listAgentConfigurationEnvironmentsRoute = createApmServerRoute({
start,
end,
});
- const size = await context.core.uiSettings.client.get(
+ const size = await coreContext.uiSettings.client.get(
maxSuggestions
);
const environments = await getEnvironments({
diff --git a/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts b/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts
index 52e60b0191230..fa15ef06ff16a 100644
--- a/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts
+++ b/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts
@@ -37,8 +37,9 @@ const anomalyDetectionJobsRoute = createApmServerRoute({
}> => {
const setup = await setupRequest(resources);
const { context } = resources;
+ const licensingContext = await context.licensing;
- if (!isActivePlatinumLicense(context.licensing.license)) {
+ if (!isActivePlatinumLicense(licensingContext.license)) {
throw Boom.forbidden(ML_ERRORS.INVALID_LICENSE);
}
@@ -69,17 +70,18 @@ const createAnomalyDetectionJobsRoute = createApmServerRoute({
handler: async (resources): Promise<{ jobCreated: true }> => {
const { params, context, logger } = resources;
const { environments } = params.body;
+ const licensingContext = await context.licensing;
const setup = await setupRequest(resources);
- if (!isActivePlatinumLicense(context.licensing.license)) {
+ if (!isActivePlatinumLicense(licensingContext.license)) {
throw Boom.forbidden(ML_ERRORS.INVALID_LICENSE);
}
await createAnomalyDetectionJobs(setup, environments, logger);
notifyFeatureUsage({
- licensingPlugin: context.licensing,
+ licensingPlugin: licensingContext,
featureName: 'ml',
});
@@ -93,13 +95,14 @@ const anomalyDetectionEnvironmentsRoute = createApmServerRoute({
options: { tags: ['access:apm'] },
handler: async (resources): Promise<{ environments: string[] }> => {
const setup = await setupRequest(resources);
+ const coreContext = await resources.context.core;
const searchAggregatedTransactions = await getSearchAggregatedTransactions({
apmEventClient: setup.apmEventClient,
config: setup.config,
kuery: '',
});
- const size = await resources.context.core.uiSettings.client.get(
+ const size = await coreContext.uiSettings.client.get(
maxSuggestions
);
const environments = await getAllEnvironments({
diff --git a/x-pack/plugins/apm/server/routes/settings/apm_indices/get_apm_indices.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/get_apm_indices.ts
index 840c15ac1bbcd..bebb92d6b6445 100644
--- a/x-pack/plugins/apm/server/routes/settings/apm_indices/get_apm_indices.ts
+++ b/x-pack/plugins/apm/server/routes/settings/apm_indices/get_apm_indices.ts
@@ -74,9 +74,8 @@ export async function getApmIndexSettings({
ReturnType
>;
try {
- apmIndicesSavedObject = await getApmIndicesSavedObject(
- context.core.savedObjects.client
- );
+ const soClient = (await context.core).savedObjects.client;
+ apmIndicesSavedObject = await getApmIndicesSavedObject(soClient);
} catch (error: any) {
if (error.output && error.output.statusCode === 404) {
apmIndicesSavedObject = {};
diff --git a/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts
index cc9f8ef76e4de..796c4312eb2ea 100644
--- a/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts
+++ b/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts
@@ -46,8 +46,9 @@ const apmIndicesRoute = createApmServerRoute({
import('./../../../../../observability/common/typings').ApmIndicesConfig
> => {
const { context, config } = resources;
+ const savedObjectsClient = (await context.core).savedObjects.client;
return await getApmIndices({
- savedObjectsClient: context.core.savedObjects.client,
+ savedObjectsClient,
config,
});
},
@@ -80,7 +81,7 @@ const saveApmIndicesRoute = createApmServerRoute({
> => {
const { params, context } = resources;
const { body } = params;
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
return await saveApmIndices(savedObjectsClient, body);
},
});
diff --git a/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts
index ca111a50ce924..1bd6328bdcee5 100644
--- a/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts
+++ b/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts
@@ -54,7 +54,9 @@ const listCustomLinksRoute = createApmServerRoute({
>;
}> => {
const { context, params } = resources;
- if (!isActiveGoldLicense(context.licensing.license)) {
+ const licensingContext = await context.licensing;
+
+ if (!isActiveGoldLicense(licensingContext.license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const setup = await setupRequest(resources);
@@ -76,14 +78,16 @@ const createCustomLinkRoute = createApmServerRoute({
options: { tags: ['access:apm', 'access:apm_write'] },
handler: async (resources): Promise => {
const { context, params } = resources;
- if (!isActiveGoldLicense(context.licensing.license)) {
+ const licensingContext = await context.licensing;
+
+ if (!isActiveGoldLicense(licensingContext.license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const setup = await setupRequest(resources);
const customLink = params.body;
notifyFeatureUsage({
- licensingPlugin: context.licensing,
+ licensingPlugin: licensingContext,
featureName: 'customLinks',
});
@@ -104,8 +108,9 @@ const updateCustomLinkRoute = createApmServerRoute({
},
handler: async (resources): Promise => {
const { params, context } = resources;
+ const licensingContext = await context.licensing;
- if (!isActiveGoldLicense(context.licensing.license)) {
+ if (!isActiveGoldLicense(licensingContext.license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const setup = await setupRequest(resources);
@@ -133,8 +138,9 @@ const deleteCustomLinkRoute = createApmServerRoute({
},
handler: async (resources): Promise<{ result: string }> => {
const { context, params } = resources;
+ const licensingContext = await context.licensing;
- if (!isActiveGoldLicense(context.licensing.license)) {
+ if (!isActiveGoldLicense(licensingContext.license)) {
throw Boom.forbidden(INVALID_LICENSE);
}
const setup = await setupRequest(resources);
diff --git a/x-pack/plugins/apm/server/routes/suggestions/route.ts b/x-pack/plugins/apm/server/routes/suggestions/route.ts
index 85e58a815f0d9..b49204cd86fc6 100644
--- a/x-pack/plugins/apm/server/routes/suggestions/route.ts
+++ b/x-pack/plugins/apm/server/routes/suggestions/route.ts
@@ -27,7 +27,8 @@ const suggestionsRoute = createApmServerRoute({
config: setup.config,
kuery: '',
});
- const size = await context.core.uiSettings.client.get(
+ const coreContext = await context.core;
+ const size = await coreContext.uiSettings.client.get(
maxSuggestions
);
const suggestions = await getSuggestions({
diff --git a/x-pack/plugins/apm/server/routes/typings.ts b/x-pack/plugins/apm/server/routes/typings.ts
index dac98c9fd4e14..9764b427ee7d7 100644
--- a/x-pack/plugins/apm/server/routes/typings.ts
+++ b/x-pack/plugins/apm/server/routes/typings.ts
@@ -7,7 +7,7 @@
import {
CoreSetup,
- RequestHandlerContext,
+ CustomRequestHandlerContext,
Logger,
KibanaRequest,
CoreStart,
@@ -24,11 +24,11 @@ import {
} from '../types';
import { UxUIFilters } from '../../common/ux_ui_filter';
-export interface ApmPluginRequestHandlerContext extends RequestHandlerContext {
+export type ApmPluginRequestHandlerContext = CustomRequestHandlerContext<{
licensing: LicensingApiRequestHandlerContext;
alerting: AlertingApiRequestHandlerContext;
rac: RacApiRequestHandlerContext;
-}
+}>;
export interface APMRouteCreateOptions {
options: {
diff --git a/x-pack/plugins/banners/server/routes/info.ts b/x-pack/plugins/banners/server/routes/info.ts
index 94574d538c286..17d60cdbc532f 100644
--- a/x-pack/plugins/banners/server/routes/info.ts
+++ b/x-pack/plugins/banners/server/routes/info.ts
@@ -21,11 +21,11 @@ export const registerInfoRoute = (router: BannersRouter, config: BannersConfigTy
},
},
async (ctx, req, res) => {
- const allowed = isValidLicense(ctx.licensing.license);
+ const allowed = isValidLicense((await ctx.licensing).license);
const bannerConfig =
req.auth.isAuthenticated && config.disableSpaceBanners === false
- ? await getBannerConfig(ctx.core.uiSettings.client)
+ ? await getBannerConfig((await ctx.core).uiSettings.client)
: config;
return res.ok({
diff --git a/x-pack/plugins/banners/server/types.ts b/x-pack/plugins/banners/server/types.ts
index e72a5ec99d243..992a182378d63 100644
--- a/x-pack/plugins/banners/server/types.ts
+++ b/x-pack/plugins/banners/server/types.ts
@@ -5,11 +5,11 @@
* 2.0.
*/
-import { RequestHandlerContext, IRouter } from '@kbn/core/server';
+import { CustomRequestHandlerContext, IRouter } from '@kbn/core/server';
import { LicensingApiRequestHandlerContext } from '@kbn/licensing-plugin/server';
-export interface BannersRequestHandlerContext extends RequestHandlerContext {
+export type BannersRequestHandlerContext = CustomRequestHandlerContext<{
licensing: LicensingApiRequestHandlerContext;
-}
+}>;
export type BannersRouter = IRouter;
diff --git a/x-pack/plugins/canvas/server/mocks/workpad_route_context.ts b/x-pack/plugins/canvas/server/mocks/workpad_route_context.ts
index 13e4e34b20b66..fb5ad3285e766 100644
--- a/x-pack/plugins/canvas/server/mocks/workpad_route_context.ts
+++ b/x-pack/plugins/canvas/server/mocks/workpad_route_context.ts
@@ -5,9 +5,10 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import { CanvasRouteHandlerContext } from '../workpad_route_context';
-export interface MockWorkpadRouteContext extends CanvasRouteHandlerContext {
+export interface MockWorkpadRouteContext extends AwaitedProperties {
canvas: {
workpad: {
create: jest.Mock;
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts
index e1175191a4c2c..69bb51de7d5c5 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts
@@ -6,7 +6,8 @@
*/
import sinon from 'sinon';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { AwaitedProperties } from '@kbn/utility-types';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { CUSTOM_ELEMENT_TYPE } from '../../../common/lib/constants';
import { initializeCreateCustomElementRoute } from './create';
import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server';
@@ -18,7 +19,7 @@ const mockRouteContext = {
client: savedObjectsClientMock.create(),
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
const mockedUUID = '123abc';
const now = new Date();
@@ -54,7 +55,11 @@ describe('POST custom element', () => {
body: mockCustomElement,
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toEqual({ ok: true });
@@ -82,7 +87,11 @@ describe('POST custom element', () => {
throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request');
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(400);
});
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/create.ts b/x-pack/plugins/canvas/server/routes/custom_elements/create.ts
index 72780ee35e972..8164c124e27dc 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/create.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/create.ts
@@ -34,7 +34,8 @@ export function initializeCreateCustomElementRoute(deps: RouteInitializerDeps) {
const now = new Date().toISOString();
const { id, ...payload } = customElement;
- await context.core.savedObjects.client.create(
+ const soClient = (await context.core).savedObjects.client;
+ await soClient.create(
CUSTOM_ELEMENT_TYPE,
{
...payload,
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts
index 95d300ca07eda..e989f1c7741f6 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts
@@ -5,10 +5,11 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import { CUSTOM_ELEMENT_TYPE } from '../../../common/lib/constants';
import { initializeDeleteCustomElementRoute } from './delete';
import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { getMockedRouterDeps } from '../test_helpers';
const mockRouteContext = {
@@ -17,7 +18,7 @@ const mockRouteContext = {
client: savedObjectsClientMock.create(),
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
describe('DELETE custom element', () => {
let routeHandler: RequestHandler;
@@ -39,7 +40,11 @@ describe('DELETE custom element', () => {
},
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toEqual({ ok: true });
@@ -62,7 +67,11 @@ describe('DELETE custom element', () => {
throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request');
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(400);
});
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/delete.ts b/x-pack/plugins/canvas/server/routes/custom_elements/delete.ts
index 8e1ae3335c27d..60092f2a721f9 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/delete.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/delete.ts
@@ -23,7 +23,8 @@ export function initializeDeleteCustomElementRoute(deps: RouteInitializerDeps) {
},
},
catchErrorHandler(async (context, request, response) => {
- await context.core.savedObjects.client.delete(CUSTOM_ELEMENT_TYPE, request.params.id);
+ const soClient = (await context.core).savedObjects.client;
+ await soClient.delete(CUSTOM_ELEMENT_TYPE, request.params.id);
return response.ok({ body: okResponse });
})
);
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/find.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/find.test.ts
index e84d7ec758978..65a9d528a849d 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/find.test.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/find.test.ts
@@ -5,9 +5,10 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import { initializeFindCustomElementsRoute } from './find';
import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { getMockedRouterDeps } from '../test_helpers';
const mockRouteContext = {
@@ -16,7 +17,7 @@ const mockRouteContext = {
client: savedObjectsClientMock.create(),
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
describe('Find custom element', () => {
let routeHandler: RequestHandler;
@@ -52,7 +53,11 @@ describe('Find custom element', () => {
},
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(findMock.mock.calls[0][0].search).toBe(`${name}* | ${name}`);
expect(findMock.mock.calls[0][0].perPage).toBe(perPage);
@@ -88,7 +93,11 @@ describe('Find custom element', () => {
},
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toMatchInlineSnapshot(`
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/find.ts b/x-pack/plugins/canvas/server/routes/custom_elements/find.ts
index edc72208d8075..0f7f492cef87c 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/find.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/find.ts
@@ -24,7 +24,7 @@ export function initializeFindCustomElementsRoute(deps: RouteInitializerDeps) {
},
},
async (context, request, response) => {
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const { name, page, perPage } = request.query;
try {
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts
index 5f70876bd5f6d..e12b1840d58c4 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts
@@ -5,10 +5,11 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import { CUSTOM_ELEMENT_TYPE } from '../../../common/lib/constants';
import { initializeGetCustomElementRoute } from './get';
import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { getMockedRouterDeps } from '../test_helpers';
const mockRouteContext = {
@@ -17,7 +18,7 @@ const mockRouteContext = {
client: savedObjectsClientMock.create(),
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
describe('GET custom element', () => {
let routeHandler: RequestHandler;
@@ -48,7 +49,11 @@ describe('GET custom element', () => {
mockRouteContext.core.savedObjects.client = savedObjectsClient;
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toMatchInlineSnapshot(`
@@ -84,7 +89,11 @@ describe('GET custom element', () => {
});
mockRouteContext.core.savedObjects.client = savedObjectsClient;
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.payload).toMatchInlineSnapshot(`
Object {
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/get.ts b/x-pack/plugins/canvas/server/routes/custom_elements/get.ts
index 0fd66da28fab4..06696ca017ca8 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/get.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/get.ts
@@ -23,7 +23,8 @@ export function initializeGetCustomElementRoute(deps: RouteInitializerDeps) {
},
},
catchErrorHandler(async (context, request, response) => {
- const customElement = await context.core.savedObjects.client.get(
+ const soClient = (await context.core).savedObjects.client;
+ const customElement = await soClient.get(
CUSTOM_ELEMENT_TYPE,
request.params.id
);
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts
index cb984931d548f..cc24f5ad708ab 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts
@@ -6,11 +6,12 @@
*/
import sinon from 'sinon';
+import { AwaitedProperties } from '@kbn/utility-types';
import { CustomElement } from '../../../types';
import { CUSTOM_ELEMENT_TYPE } from '../../../common/lib/constants';
import { initializeUpdateCustomElementRoute } from './update';
import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { okResponse } from '../ok_response';
import { getMockedRouterDeps } from '../test_helpers';
@@ -20,7 +21,7 @@ const mockRouteContext = {
client: savedObjectsClientMock.create(),
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
const now = new Date();
const nowIso = now.toISOString();
@@ -82,7 +83,11 @@ describe('PUT custom element', () => {
mockRouteContext.core.savedObjects.client = savedObjectsClient;
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toEqual(okResponse);
@@ -117,7 +122,11 @@ describe('PUT custom element', () => {
);
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(404);
});
@@ -144,7 +153,11 @@ describe('PUT custom element', () => {
throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request');
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(400);
});
diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/update.ts b/x-pack/plugins/canvas/server/routes/custom_elements/update.ts
index 1604c7b408309..d0c1b8072e1d0 100644
--- a/x-pack/plugins/canvas/server/routes/custom_elements/update.ts
+++ b/x-pack/plugins/canvas/server/routes/custom_elements/update.ts
@@ -37,14 +37,14 @@ export function initializeUpdateCustomElementRoute(deps: RouteInitializerDeps) {
const id = request.params.id;
const now = new Date().toISOString();
+ const soClient = (await context.core).savedObjects.client;
- const customElementObject =
- await context.core.savedObjects.client.get(
- CUSTOM_ELEMENT_TYPE,
- id
- );
+ const customElementObject = await soClient.get(
+ CUSTOM_ELEMENT_TYPE,
+ id
+ );
- await context.core.savedObjects.client.create(
+ await soClient.create(
CUSTOM_ELEMENT_TYPE,
{
...customElementObject.attributes,
diff --git a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts
index ec664df330d31..06a30af03c921 100644
--- a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts
+++ b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts
@@ -5,9 +5,10 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import { initializeESFieldsRoute } from './es_fields';
import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server';
-import { httpServerMock, elasticsearchServiceMock } from '@kbn/core/server/mocks';
+import { httpServerMock, elasticsearchServiceMock, coreMock } from '@kbn/core/server/mocks';
import { getMockedRouterDeps } from '../test_helpers';
const mockRouteContext = {
@@ -16,7 +17,7 @@ const mockRouteContext = {
client: elasticsearchServiceMock.createScopedClusterClient(),
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
const path = `api/canvas/workpad/find`;
@@ -71,7 +72,11 @@ describe('Retrieve ES Fields', () => {
fieldCapsMock.mockResolvedValueOnce(mockResults);
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toMatchInlineSnapshot(`
@@ -99,7 +104,11 @@ describe('Retrieve ES Fields', () => {
fieldCapsMock.mockResolvedValueOnce(mockResults);
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toMatchInlineSnapshot('Object {}');
@@ -127,7 +136,11 @@ describe('Retrieve ES Fields', () => {
fieldCapsMock.mockResolvedValueOnce(mockResults);
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toMatchInlineSnapshot(`Object {}`);
@@ -148,7 +161,11 @@ describe('Retrieve ES Fields', () => {
fieldCapsMock.mockRejectedValueOnce(new Error('Index not found'));
await expect(
- routeHandler(mockRouteContext, request, kibanaResponseFactory)
+ routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ )
).rejects.toThrowError('Index not found');
});
});
diff --git a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts
index f9523cee0ce4d..1923d4648a2a3 100644
--- a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts
+++ b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts
@@ -28,7 +28,7 @@ export function initializeESFieldsRoute(deps: RouteInitializerDeps) {
},
},
catchErrorHandler(async (context, request, response) => {
- const client = context.core.elasticsearch.client.asCurrentUser;
+ const client = (await context.core).elasticsearch.client.asCurrentUser;
const { index, fields } = request.query;
const config = {
diff --git a/x-pack/plugins/canvas/server/routes/templates/list.test.ts b/x-pack/plugins/canvas/server/routes/templates/list.test.ts
index eb9703a33a401..a1480eb0eaea1 100644
--- a/x-pack/plugins/canvas/server/routes/templates/list.test.ts
+++ b/x-pack/plugins/canvas/server/routes/templates/list.test.ts
@@ -6,9 +6,10 @@
*/
import { badRequest } from '@hapi/boom';
+import { AwaitedProperties } from '@kbn/utility-types';
import { initializeListTemplates } from './list';
import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { getMockedRouterDeps } from '../test_helpers';
const mockRouteContext = {
@@ -17,7 +18,7 @@ const mockRouteContext = {
client: savedObjectsClientMock.create(),
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
describe('Find workpad', () => {
let routeHandler: RequestHandler;
@@ -50,7 +51,11 @@ describe('Find workpad', () => {
path: `api/canvas/templates/list`,
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toMatchInlineSnapshot(`
@@ -77,7 +82,11 @@ describe('Find workpad', () => {
path: `api/canvas/templates/list`,
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(400);
expect(response.payload).toMatchInlineSnapshot(`
diff --git a/x-pack/plugins/canvas/server/routes/templates/list.ts b/x-pack/plugins/canvas/server/routes/templates/list.ts
index 2bff143f127bc..c0e32fb3722b1 100644
--- a/x-pack/plugins/canvas/server/routes/templates/list.ts
+++ b/x-pack/plugins/canvas/server/routes/templates/list.ts
@@ -21,7 +21,7 @@ export function initializeListTemplates(deps: RouteInitializerDeps) {
},
},
catchErrorHandler(async (context, request, response) => {
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const templates = await savedObjectsClient.find({
type: TEMPLATE_TYPE,
diff --git a/x-pack/plugins/canvas/server/routes/workpad/create.test.ts b/x-pack/plugins/canvas/server/routes/workpad/create.test.ts
index 175a1084ec1a4..304d7864950e4 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/create.test.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/create.test.ts
@@ -5,7 +5,8 @@
* 2.0.
*/
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { AwaitedProperties } from '@kbn/utility-types';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { workpadRouteContextMock, MockWorkpadRouteContext } from '../../mocks';
import { initializeCreateWorkpadRoute } from './create';
import { kibanaResponseFactory, RequestHandler } from '@kbn/core/server';
@@ -18,7 +19,7 @@ let mockRouteContext = {
},
},
canvas: workpadRouteContextMock.create(),
-} as unknown as MockWorkpadRouteContext;
+} as unknown as AwaitedProperties;
jest.mock('uuid/v4', () => jest.fn().mockReturnValue('123abc'));
@@ -33,7 +34,7 @@ describe('POST workpad', () => {
},
},
canvas: workpadRouteContextMock.create(),
- } as unknown as MockWorkpadRouteContext;
+ } as unknown as AwaitedProperties;
const routerDeps = getMockedRouterDeps();
initializeCreateWorkpadRoute(routerDeps);
@@ -57,7 +58,11 @@ describe('POST workpad', () => {
body: mockWorkpad,
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toEqual({ ok: true, id });
@@ -75,7 +80,11 @@ describe('POST workpad', () => {
throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request');
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(400);
});
@@ -109,7 +118,11 @@ describe('POST workpad', () => {
body: cloneFromTemplateBody,
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toEqual({ ok: true, id });
diff --git a/x-pack/plugins/canvas/server/routes/workpad/create.ts b/x-pack/plugins/canvas/server/routes/workpad/create.ts
index 8460939c730c8..dec03c8945ac6 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/create.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/create.ts
@@ -50,14 +50,16 @@ export function initializeCreateWorkpadRoute(deps: RouteInitializerDeps) {
let workpad = request.body as CanvasWorkpad;
if (isCreateFromTemplate(request.body)) {
- const templateSavedObject = await context.core.savedObjects.client.get(
+ const soClient = (await context.core).savedObjects.client;
+ const templateSavedObject = await soClient.get(
TEMPLATE_TYPE,
request.body.templateId
);
workpad = templateSavedObject.attributes.template;
}
- const createdObject = await context.canvas.workpad.create(workpad);
+ const canvasContext = await context.canvas;
+ const createdObject = await canvasContext.workpad.create(workpad);
return response.ok({
body: { ...okResponse, id: createdObject.id },
diff --git a/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts b/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts
index fdd390d2954a9..f29bad869a8a6 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts
@@ -5,10 +5,11 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import { CANVAS_TYPE } from '../../../common/lib/constants';
import { initializeDeleteWorkpadRoute } from './delete';
import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { getMockedRouterDeps } from '../test_helpers';
const mockRouteContext = {
@@ -17,7 +18,7 @@ const mockRouteContext = {
client: savedObjectsClientMock.create(),
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
describe('DELETE workpad', () => {
let routeHandler: RequestHandler;
@@ -39,7 +40,11 @@ describe('DELETE workpad', () => {
},
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toEqual({ ok: true });
@@ -59,7 +64,11 @@ describe('DELETE workpad', () => {
throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request');
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(400);
});
diff --git a/x-pack/plugins/canvas/server/routes/workpad/delete.ts b/x-pack/plugins/canvas/server/routes/workpad/delete.ts
index 9075f651abb5a..0a1f69e273d05 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/delete.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/delete.ts
@@ -23,7 +23,8 @@ export function initializeDeleteWorkpadRoute(deps: RouteInitializerDeps) {
},
},
catchErrorHandler(async (context, request, response) => {
- context.core.savedObjects.client.delete(CANVAS_TYPE, request.params.id);
+ const soClient = (await context.core).savedObjects.client;
+ await soClient.delete(CANVAS_TYPE, request.params.id);
return response.ok({ body: okResponse });
})
);
diff --git a/x-pack/plugins/canvas/server/routes/workpad/find.test.ts b/x-pack/plugins/canvas/server/routes/workpad/find.test.ts
index 8a54889413d80..39626e95c3f06 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/find.test.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/find.test.ts
@@ -5,9 +5,10 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import { initializeFindWorkpadsRoute } from './find';
import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { getMockedRouterDeps } from '../test_helpers';
const mockRouteContext = {
@@ -16,7 +17,7 @@ const mockRouteContext = {
client: savedObjectsClientMock.create(),
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
describe('Find workpad', () => {
let routeHandler: RequestHandler;
@@ -52,7 +53,11 @@ describe('Find workpad', () => {
},
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(findMock.mock.calls[0][0].search).toBe(`${name}* | ${name}`);
expect(findMock.mock.calls[0][0].perPage).toBe(perPage);
@@ -88,7 +93,11 @@ describe('Find workpad', () => {
},
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toMatchInlineSnapshot(`
diff --git a/x-pack/plugins/canvas/server/routes/workpad/find.ts b/x-pack/plugins/canvas/server/routes/workpad/find.ts
index c8953bfab8a72..43db20ee11db5 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/find.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/find.ts
@@ -24,7 +24,7 @@ export function initializeFindWorkpadsRoute(deps: RouteInitializerDeps) {
},
},
async (context, request, response) => {
- const savedObjectsClient = context.core.savedObjects.client;
+ const savedObjectsClient = (await context.core).savedObjects.client;
const { name, page, perPage } = request.query;
try {
diff --git a/x-pack/plugins/canvas/server/routes/workpad/get.test.ts b/x-pack/plugins/canvas/server/routes/workpad/get.test.ts
index 735bbfc7209af..217072d045321 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/get.test.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/get.test.ts
@@ -5,10 +5,11 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import { CANVAS_TYPE } from '../../../common/lib/constants';
import { initializeGetWorkpadRoute } from './get';
import { kibanaResponseFactory, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { workpadWithGroupAsElement } from '../../../__fixtures__/workpads';
import { CanvasWorkpad } from '../../../types';
import { getMockedRouterDeps } from '../test_helpers';
@@ -16,7 +17,7 @@ import { workpadRouteContextMock, MockWorkpadRouteContext } from '../../mocks';
const mockRouteContext = {
canvas: workpadRouteContextMock.create(),
-} as unknown as MockWorkpadRouteContext;
+} as unknown as AwaitedProperties;
describe('GET workpad', () => {
let routeHandler: RequestHandler;
@@ -48,7 +49,11 @@ describe('GET workpad', () => {
references: [],
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toMatchInlineSnapshot(`
@@ -83,7 +88,11 @@ describe('GET workpad', () => {
references: [],
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
const workpad = response.payload as CanvasWorkpad;
expect(response.status).toBe(200);
@@ -108,7 +117,11 @@ describe('GET workpad', () => {
throw savedObjectsClient.errors.createGenericNotFoundError(CANVAS_TYPE, id);
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.payload).toMatchInlineSnapshot(`
Object {
diff --git a/x-pack/plugins/canvas/server/routes/workpad/get.ts b/x-pack/plugins/canvas/server/routes/workpad/get.ts
index 8fc31e9850dbc..fe38b768f64a1 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/get.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/get.ts
@@ -23,7 +23,8 @@ export function initializeGetWorkpadRoute(deps: RouteInitializerDeps) {
},
},
catchErrorHandler(async (context, request, response) => {
- const workpad = await context.canvas.workpad.get(request.params.id);
+ const canvasContext = await context.canvas;
+ const workpad = await canvasContext.workpad.get(request.params.id);
shimWorkpad(workpad);
diff --git a/x-pack/plugins/canvas/server/routes/workpad/import.ts b/x-pack/plugins/canvas/server/routes/workpad/import.ts
index d8438920aeb5d..4734e1e554f64 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/import.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/import.ts
@@ -32,7 +32,8 @@ export function initializeImportWorkpadRoute(deps: RouteInitializerDeps) {
catchErrorHandler(async (context, request, response) => {
const workpad = request.body as ImportedCanvasWorkpad;
- const createdObject = await context.canvas.workpad.import(workpad);
+ const canvasContext = await context.canvas;
+ const createdObject = await canvasContext.workpad.import(workpad);
return response.ok({
body: { ...okResponse, id: createdObject.id },
diff --git a/x-pack/plugins/canvas/server/routes/workpad/resolve.test.ts b/x-pack/plugins/canvas/server/routes/workpad/resolve.test.ts
index 94e3f9dd03462..80fde2fadc18b 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/resolve.test.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/resolve.test.ts
@@ -5,10 +5,11 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import { CANVAS_TYPE } from '../../../common/lib/constants';
import { initializeResolveWorkpadRoute } from './resolve';
import { kibanaResponseFactory, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { workpadWithGroupAsElement } from '../../../__fixtures__/workpads';
import { CanvasWorkpad } from '../../../types';
import { getMockedRouterDeps } from '../test_helpers';
@@ -16,7 +17,7 @@ import { workpadRouteContextMock, MockWorkpadRouteContext } from '../../mocks';
const mockRouteContext = {
canvas: workpadRouteContextMock.create(),
-} as unknown as MockWorkpadRouteContext;
+} as unknown as AwaitedProperties;
describe('RESOLVE workpad', () => {
let routeHandler: RequestHandler;
@@ -55,7 +56,11 @@ describe('RESOLVE workpad', () => {
alias_target_id: aliasId,
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toMatchInlineSnapshot(`
@@ -97,7 +102,11 @@ describe('RESOLVE workpad', () => {
outcome: 'exactMatch',
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
const workpad = response.payload.workpad as CanvasWorkpad;
expect(response.status).toBe(200);
@@ -122,7 +131,11 @@ describe('RESOLVE workpad', () => {
throw savedObjectsClient.errors.createGenericNotFoundError(CANVAS_TYPE, id);
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.payload).toMatchInlineSnapshot(`
Object {
diff --git a/x-pack/plugins/canvas/server/routes/workpad/resolve.ts b/x-pack/plugins/canvas/server/routes/workpad/resolve.ts
index dbd65e30482f8..d2a4b71f35af9 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/resolve.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/resolve.ts
@@ -23,7 +23,8 @@ export function initializeResolveWorkpadRoute(deps: RouteInitializerDeps) {
},
},
catchErrorHandler(async (context, request, response) => {
- const resolved = await context.canvas.workpad.resolve(request.params.id);
+ const canvasContext = await context.canvas;
+ const resolved = await canvasContext.workpad.resolve(request.params.id);
const { saved_object: workpad } = resolved;
shimWorkpad(workpad);
diff --git a/x-pack/plugins/canvas/server/routes/workpad/update.test.ts b/x-pack/plugins/canvas/server/routes/workpad/update.test.ts
index a0aaa05b0f718..2467ed56bdc37 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/update.test.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/update.test.ts
@@ -5,11 +5,12 @@
* 2.0.
*/
+import { AwaitedProperties } from '@kbn/utility-types';
import sinon from 'sinon';
import { CANVAS_TYPE } from '../../../common/lib/constants';
import { initializeUpdateWorkpadRoute, initializeUpdateWorkpadAssetsRoute } from './update';
import { kibanaResponseFactory, RequestHandler } from '@kbn/core/server';
-import { savedObjectsClientMock, httpServerMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks';
import { workpads } from '../../../__fixtures__/workpads';
import { okResponse } from '../ok_response';
import { getMockedRouterDeps } from '../test_helpers';
@@ -22,7 +23,7 @@ const mockRouteContext = {
},
},
canvas: workpadRouteContextMock.create(),
-} as unknown as MockWorkpadRouteContext;
+} as unknown as AwaitedProperties;
const workpad = workpads[0];
const now = new Date();
@@ -62,7 +63,11 @@ describe('PUT workpad', () => {
mockRouteContext.canvas.workpad.update.mockResolvedValue(true);
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(response.payload).toEqual(okResponse);
@@ -85,7 +90,11 @@ describe('PUT workpad', () => {
);
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(404);
});
@@ -104,7 +113,11 @@ describe('PUT workpad', () => {
throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request');
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(400);
});
@@ -160,7 +173,11 @@ describe('update assets', () => {
references: [],
});
- const response = await routeHandler(mockRouteContext, request, kibanaResponseFactory);
+ const response = await routeHandler(
+ coreMock.createCustomRequestHandlerContext(mockRouteContext),
+ request,
+ kibanaResponseFactory
+ );
expect(response.status).toBe(200);
expect(mockRouteContext.canvas.workpad.update).toBeCalledWith(id, {
diff --git a/x-pack/plugins/canvas/server/routes/workpad/update.ts b/x-pack/plugins/canvas/server/routes/workpad/update.ts
index 9d115c83c1def..d74e57f824f51 100644
--- a/x-pack/plugins/canvas/server/routes/workpad/update.ts
+++ b/x-pack/plugins/canvas/server/routes/workpad/update.ts
@@ -40,7 +40,8 @@ export function initializeUpdateWorkpadRoute(deps: RouteInitializerDeps) {
},
},
catchErrorHandler(async (context, request, response) => {
- await context.canvas.workpad.update(request.params.id, request.body as CanvasWorkpad);
+ const canvasContext = await context.canvas;
+ await canvasContext.workpad.update(request.params.id, request.body as CanvasWorkpad);
return response.ok({
body: okResponse,
@@ -65,7 +66,8 @@ export function initializeUpdateWorkpadRoute(deps: RouteInitializerDeps) {
},
},
catchErrorHandler(async (context, request, response) => {
- await context.canvas.workpad.update(request.params.id, request.body as CanvasWorkpad);
+ const canvasContext = await context.canvas;
+ await canvasContext.workpad.update(request.params.id, request.body as CanvasWorkpad);
return response.ok({
body: okResponse,
@@ -101,7 +103,8 @@ export function initializeUpdateWorkpadAssetsRoute(deps: RouteInitializerDeps) {
assets: AssetsRecordSchema.validate(request.body),
};
- await context.canvas.workpad.update(request.params.id, workpadAssets as CanvasWorkpad);
+ const canvasContext = await context.canvas;
+ await canvasContext.workpad.update(request.params.id, workpadAssets as CanvasWorkpad);
return response.ok({
body: okResponse,
diff --git a/x-pack/plugins/canvas/server/workpad_route_context.test.ts b/x-pack/plugins/canvas/server/workpad_route_context.test.ts
index a1da10b09a91d..290eed19d0fc5 100644
--- a/x-pack/plugins/canvas/server/workpad_route_context.test.ts
+++ b/x-pack/plugins/canvas/server/workpad_route_context.test.ts
@@ -7,9 +7,10 @@
import sinon from 'sinon';
import { fromExpression } from '@kbn/interpreter';
+import { AwaitedProperties } from '@kbn/utility-types';
import { createWorkpadRouteContext } from './workpad_route_context';
import { RequestHandlerContext, SavedObjectReference } from '@kbn/core/server';
-import { savedObjectsClientMock } from '@kbn/core/server/mocks';
+import { savedObjectsClientMock, coreMock } from '@kbn/core/server/mocks';
import { CanvasWorkpad } from '../types';
import { CANVAS_TYPE } from '../common/lib/constants';
@@ -26,7 +27,7 @@ const mockContext = {
client: savedObjectsClient,
},
},
-} as unknown as RequestHandlerContext;
+} as unknown as AwaitedProperties;
const workpadRouteContext = createWorkpadRouteContext({
expressions: mockedExpressionService as any,
@@ -86,7 +87,7 @@ describe('workpad route context', () => {
};
const canvasContext = await workpadRouteContext(
- mockContext,
+ coreMock.createCustomRequestHandlerContext(mockContext),
undefined as any,
undefined as any
);
@@ -120,7 +121,7 @@ describe('workpad route context', () => {
it('injects references to the saved object', async () => {
const id = 'so-id';
const canvasContext = await workpadRouteContext(
- mockContext,
+ coreMock.createCustomRequestHandlerContext(mockContext),
undefined as any,
undefined as any
);
@@ -145,7 +146,7 @@ describe('workpad route context', () => {
it('injects references to the saved object', async () => {
const id = 'so-id';
const canvasContext = await workpadRouteContext(
- mockContext,
+ coreMock.createCustomRequestHandlerContext(mockContext),
undefined as any,
undefined as any
);
@@ -172,7 +173,7 @@ describe('workpad route context', () => {
const createdDate = new Date(2020, 1, 1).toISOString();
const canvasContext = await workpadRouteContext(
- mockContext,
+ coreMock.createCustomRequestHandlerContext(mockContext),
undefined as any,
undefined as any
);
diff --git a/x-pack/plugins/canvas/server/workpad_route_context.ts b/x-pack/plugins/canvas/server/workpad_route_context.ts
index c154dd66d76be..0ae1699b8f57f 100644
--- a/x-pack/plugins/canvas/server/workpad_route_context.ts
+++ b/x-pack/plugins/canvas/server/workpad_route_context.ts
@@ -6,7 +6,7 @@
*/
import {
- RequestHandlerContext,
+ CustomRequestHandlerContext,
RequestHandlerContextProvider,
SavedObject,
SavedObjectsResolveResponse,
@@ -18,7 +18,7 @@ import { injectReferences, extractReferences } from './saved_objects/workpad_ref
import { getId } from '../common/lib/get_id';
import { CanvasWorkpad, ImportedCanvasWorkpad } from '../types';
-export interface CanvasRouteHandlerContext extends RequestHandlerContext {
+export type CanvasRouteHandlerContext = CustomRequestHandlerContext<{
canvas: {
workpad: {
create: (attributes: CanvasWorkpad) => Promise>;
@@ -31,7 +31,7 @@ export interface CanvasRouteHandlerContext extends RequestHandlerContext {
) => Promise>;
};
};
-}
+}>;
interface Deps {
expressions: ExpressionsServiceStart;
@@ -40,109 +40,107 @@ interface Deps {
export const createWorkpadRouteContext: (
deps: Deps
) => RequestHandlerContextProvider = ({ expressions }) => {
- return (context) => ({
- workpad: {
- create: async (workpad: CanvasWorkpad) => {
- const now = new Date().toISOString();
- const { id: maybeId, ...attributes } = workpad;
-
- const id = maybeId ? maybeId : getId('workpad');
-
- const { workpad: extractedAttributes, references } = extractReferences(
- attributes,
- expressions
- );
-
- return await context.core.savedObjects.client.create(
- CANVAS_TYPE,
- {
- ...extractedAttributes,
- '@timestamp': now,
- '@created': now,
- },
- { id, references }
- );
- },
- import: async (workpad: ImportedCanvasWorkpad) => {
- const now = new Date().toISOString();
- const { id: maybeId, ...workpadWithoutId } = workpad;
-
- // Functionality of running migrations on import of workpads was implemented in v8.1.0.
- // As only attributes of the saved object workpad are exported, to run migrations it is necessary
- // to specify the minimal version of possible migrations to execute them. It is v8.0.0 in the current case.
- const DEFAULT_MIGRATION_VERSION = { [CANVAS_TYPE]: '8.0.0' };
- const DEFAULT_CORE_MIGRATION_VERSION = '8.0.0';
-
- const id = maybeId ? maybeId : getId('workpad');
-
- return await context.core.savedObjects.client.create(
- CANVAS_TYPE,
- {
- isWriteable: true,
- ...workpadWithoutId,
- '@timestamp': now,
- '@created': now,
- },
- {
- migrationVersion: DEFAULT_MIGRATION_VERSION,
- coreMigrationVersion: DEFAULT_CORE_MIGRATION_VERSION,
+ return async (context) => {
+ const soClient = (await context.core).savedObjects.client;
+ return {
+ workpad: {
+ create: async (workpad: CanvasWorkpad) => {
+ const now = new Date().toISOString();
+ const { id: maybeId, ...attributes } = workpad;
+
+ const id = maybeId ? maybeId : getId('workpad');
+
+ const { workpad: extractedAttributes, references } = extractReferences(
+ attributes,
+ expressions
+ );
+
+ return await soClient.create(
+ CANVAS_TYPE,
+ {
+ ...extractedAttributes,
+ '@timestamp': now,
+ '@created': now,
+ },
+ { id, references }
+ );
+ },
+ import: async (workpad: ImportedCanvasWorkpad) => {
+ const now = new Date().toISOString();
+ const { id: maybeId, ...workpadWithoutId } = workpad;
+
+ // Functionality of running migrations on import of workpads was implemented in v8.1.0.
+ // As only attributes of the saved object workpad are exported, to run migrations it is necessary
+ // to specify the minimal version of possible migrations to execute them. It is v8.0.0 in the current case.
+ const DEFAULT_MIGRATION_VERSION = { [CANVAS_TYPE]: '8.0.0' };
+ const DEFAULT_CORE_MIGRATION_VERSION = '8.0.0';
+
+ const id = maybeId ? maybeId : getId('workpad');
+
+ return await soClient.create(
+ CANVAS_TYPE,
+ {
+ isWriteable: true,
+ ...workpadWithoutId,
+ '@timestamp': now,
+ '@created': now,
+ },
+ {
+ migrationVersion: DEFAULT_MIGRATION_VERSION,
+ coreMigrationVersion: DEFAULT_CORE_MIGRATION_VERSION,
+ id,
+ }
+ );
+ },
+ get: async (id: string) => {
+ const workpad = await soClient.get(CANVAS_TYPE, id);
+
+ workpad.attributes = injectReferences(
+ workpad.attributes,
+ workpad.references,
+ expressions
+ );
+
+ return workpad;
+ },
+ resolve: async (id: string) => {
+ const resolved = await soClient.resolve(CANVAS_TYPE, id);
+
+ resolved.saved_object.attributes = injectReferences(
+ resolved.saved_object.attributes,
+ resolved.saved_object.references,
+ expressions
+ );
+
+ return resolved;
+ },
+ update: async (id: string, { id: omittedId, ...workpad }: Partial) => {
+ const now = new Date().toISOString();
+
+ const workpadObject = await soClient.get(CANVAS_TYPE, id);
+
+ const injectedAttributes = injectReferences(
+ workpadObject.attributes,
+ workpadObject.references,
+ expressions
+ );
+
+ const updatedAttributes = {
+ ...injectedAttributes,
+ ...workpad,
+ '@timestamp': now, // always update the modified time
+ '@created': workpadObject.attributes['@created'], // ensure created is not modified
+ } as WorkpadAttributes;
+
+ const extracted = extractReferences(updatedAttributes, expressions);
+
+ return await soClient.create(CANVAS_TYPE, extracted.workpad, {
+ overwrite: true,
id,
- }
- );
- },
- get: async (id: string) => {
- const workpad = await context.core.savedObjects.client.get(
- CANVAS_TYPE,
- id
- );
-
- workpad.attributes = injectReferences(workpad.attributes, workpad.references, expressions);
-
- return workpad;
- },
- resolve: async (id: string) => {
- const resolved = await context.core.savedObjects.client.resolve(
- CANVAS_TYPE,
- id
- );
-
- resolved.saved_object.attributes = injectReferences(
- resolved.saved_object.attributes,
- resolved.saved_object.references,
- expressions
- );
-
- return resolved;
- },
- update: async (id: string, { id: omittedId, ...workpad }: Partial) => {
- const now = new Date().toISOString();
-
- const workpadObject = await context.core.savedObjects.client.get(
- CANVAS_TYPE,
- id
- );
-
- const injectedAttributes = injectReferences(
- workpadObject.attributes,
- workpadObject.references,
- expressions
- );
-
- const updatedAttributes = {
- ...injectedAttributes,
- ...workpad,
- '@timestamp': now, // always update the modified time
- '@created': workpadObject.attributes['@created'], // ensure created is not modified
- } as WorkpadAttributes;
-
- const extracted = extractReferences(updatedAttributes, expressions);
-
- return await context.core.savedObjects.client.create(CANVAS_TYPE, extracted.workpad, {
- overwrite: true,
- id,
- references: extracted.references,
- });
+ references: extracted.references,
+ });
+ },
},
- },
- });
+ };
+ };
};
diff --git a/x-pack/plugins/cases/server/plugin.ts b/x-pack/plugins/cases/server/plugin.ts
index 52d413cb1ef83..4ec2415bae54d 100644
--- a/x-pack/plugins/cases/server/plugin.ts
+++ b/x-pack/plugins/cases/server/plugin.ts
@@ -6,12 +6,12 @@
*/
import {
- CoreSetup,
- CoreStart,
IContextProvider,
KibanaRequest,
Logger,
PluginInitializerContext,
+ CoreSetup,
+ CoreStart,
} from '@kbn/core/server';
import { SecurityPluginSetup, SecurityPluginStart } from '@kbn/security-plugin/server';
@@ -198,10 +198,11 @@ export class CasePlugin {
return {
getCasesClient: async () => {
const [{ savedObjects }] = await core.getStartServices();
+ const coreContext = await context.core;
return this.clientFactory.create({
request,
- scopedClusterClient: context.core.elasticsearch.client.asCurrentUser,
+ scopedClusterClient: coreContext.elasticsearch.client.asCurrentUser,
savedObjectsService: savedObjects,
});
},
diff --git a/x-pack/plugins/cases/server/routes/api/cases/alerts/get_cases.ts b/x-pack/plugins/cases/server/routes/api/cases/alerts/get_cases.ts
index 00a368e834a0a..8a9c02cf574d7 100644
--- a/x-pack/plugins/cases/server/routes/api/cases/alerts/get_cases.ts
+++ b/x-pack/plugins/cases/server/routes/api/cases/alerts/get_cases.ts
@@ -24,7 +24,8 @@ export const getCasesByAlertIdRoute = createCasesRoute({
try {
const alertID = request.params.alert_id;
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
const options = request.query as CasesByAlertIDRequest;
return response.ok({
diff --git a/x-pack/plugins/cases/server/routes/api/cases/delete_cases.ts b/x-pack/plugins/cases/server/routes/api/cases/delete_cases.ts
index a63d07037de01..5a397841f976d 100644
--- a/x-pack/plugins/cases/server/routes/api/cases/delete_cases.ts
+++ b/x-pack/plugins/cases/server/routes/api/cases/delete_cases.ts
@@ -21,7 +21,8 @@ export const deleteCaseRoute = createCasesRoute({
},
handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
await client.cases.delete(request.query.ids);
return response.noContent();
diff --git a/x-pack/plugins/cases/server/routes/api/cases/find_cases.ts b/x-pack/plugins/cases/server/routes/api/cases/find_cases.ts
index 711c6909df46c..2a42bb3fa3353 100644
--- a/x-pack/plugins/cases/server/routes/api/cases/find_cases.ts
+++ b/x-pack/plugins/cases/server/routes/api/cases/find_cases.ts
@@ -15,7 +15,8 @@ export const findCaseRoute = createCasesRoute({
path: `${CASES_URL}/_find`,
handler: async ({ context, request, response }) => {
try {
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
const options = request.query as CasesFindRequest;
return response.ok({
diff --git a/x-pack/plugins/cases/server/routes/api/cases/get_case.ts b/x-pack/plugins/cases/server/routes/api/cases/get_case.ts
index f0e53e82f1494..736b9b973ce7d 100644
--- a/x-pack/plugins/cases/server/routes/api/cases/get_case.ts
+++ b/x-pack/plugins/cases/server/routes/api/cases/get_case.ts
@@ -41,7 +41,8 @@ export const getCaseRoute = createCasesRoute({
);
}
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
const id = request.params.case_id;
return response.ok({
@@ -70,7 +71,8 @@ export const resolveCaseRoute = createCasesRoute({
params,
handler: async ({ context, request, response }) => {
try {
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
const id = request.params.case_id;
return response.ok({
diff --git a/x-pack/plugins/cases/server/routes/api/cases/patch_cases.ts b/x-pack/plugins/cases/server/routes/api/cases/patch_cases.ts
index c148a45220a74..bb9649aaa092c 100644
--- a/x-pack/plugins/cases/server/routes/api/cases/patch_cases.ts
+++ b/x-pack/plugins/cases/server/routes/api/cases/patch_cases.ts
@@ -15,7 +15,8 @@ export const patchCaseRoute = createCasesRoute({
path: CASES_URL,
handler: async ({ context, request, response }) => {
try {
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
const cases = request.body as CasesPatchRequest;
return response.ok({
diff --git a/x-pack/plugins/cases/server/routes/api/cases/post_case.ts b/x-pack/plugins/cases/server/routes/api/cases/post_case.ts
index 226d0308a3152..8c4d43274f21a 100644
--- a/x-pack/plugins/cases/server/routes/api/cases/post_case.ts
+++ b/x-pack/plugins/cases/server/routes/api/cases/post_case.ts
@@ -15,7 +15,8 @@ export const postCaseRoute = createCasesRoute({
path: CASES_URL,
handler: async ({ context, request, response }) => {
try {
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
const theCase = request.body as CasePostRequest;
return response.ok({
diff --git a/x-pack/plugins/cases/server/routes/api/cases/push_case.ts b/x-pack/plugins/cases/server/routes/api/cases/push_case.ts
index 175838a9d313c..9ee30ed34f2a5 100644
--- a/x-pack/plugins/cases/server/routes/api/cases/push_case.ts
+++ b/x-pack/plugins/cases/server/routes/api/cases/push_case.ts
@@ -21,7 +21,8 @@ export const pushCaseRoute: CaseRoute = createCasesRoute({
path: CASE_PUSH_URL,
handler: async ({ context, request, response }) => {
try {
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
const params = pipe(
CasePushRequestParamsRt.decode(request.params),
diff --git a/x-pack/plugins/cases/server/routes/api/cases/reporters/get_reporters.ts b/x-pack/plugins/cases/server/routes/api/cases/reporters/get_reporters.ts
index ee413d73565ee..56465fd7be1c4 100644
--- a/x-pack/plugins/cases/server/routes/api/cases/reporters/get_reporters.ts
+++ b/x-pack/plugins/cases/server/routes/api/cases/reporters/get_reporters.ts
@@ -15,7 +15,8 @@ export const getReportersRoute = createCasesRoute({
path: CASE_REPORTERS_URL,
handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
const options = request.query as AllReportersFindRequest;
return response.ok({ body: await client.cases.getReporters({ ...options }) });
diff --git a/x-pack/plugins/cases/server/routes/api/cases/tags/get_tags.ts b/x-pack/plugins/cases/server/routes/api/cases/tags/get_tags.ts
index 7dfa948aa623c..8c2071750f5e6 100644
--- a/x-pack/plugins/cases/server/routes/api/cases/tags/get_tags.ts
+++ b/x-pack/plugins/cases/server/routes/api/cases/tags/get_tags.ts
@@ -15,7 +15,8 @@ export const getTagsRoute = createCasesRoute({
path: CASE_TAGS_URL,
handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
const options = request.query as AllTagsFindRequest;
return response.ok({ body: await client.cases.getTags({ ...options }) });
diff --git a/x-pack/plugins/cases/server/routes/api/comments/delete_all_comments.ts b/x-pack/plugins/cases/server/routes/api/comments/delete_all_comments.ts
index 0a1ebd3b66a74..317ebaec20a13 100644
--- a/x-pack/plugins/cases/server/routes/api/comments/delete_all_comments.ts
+++ b/x-pack/plugins/cases/server/routes/api/comments/delete_all_comments.ts
@@ -20,7 +20,8 @@ export const deleteAllCommentsRoute = createCasesRoute({
},
handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
await client.attachments.deleteAll({
caseID: request.params.case_id,
diff --git a/x-pack/plugins/cases/server/routes/api/comments/delete_comment.ts b/x-pack/plugins/cases/server/routes/api/comments/delete_comment.ts
index 220fbffc76cc0..775fabb846408 100644
--- a/x-pack/plugins/cases/server/routes/api/comments/delete_comment.ts
+++ b/x-pack/plugins/cases/server/routes/api/comments/delete_comment.ts
@@ -22,7 +22,8 @@ export const deleteCommentRoute = createCasesRoute({
},
handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
await client.attachments.delete({
attachmentID: request.params.comment_id,
caseID: request.params.case_id,
diff --git a/x-pack/plugins/cases/server/routes/api/comments/find_comments.ts b/x-pack/plugins/cases/server/routes/api/comments/find_comments.ts
index 14c6090d62ea1..23a7ecb601534 100644
--- a/x-pack/plugins/cases/server/routes/api/comments/find_comments.ts
+++ b/x-pack/plugins/cases/server/routes/api/comments/find_comments.ts
@@ -32,7 +32,8 @@ export const findCommentsRoute = createCasesRoute({
fold(throwErrors(Boom.badRequest), identity)
);
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
return response.ok({
body: await client.attachments.find({
caseID: request.params.case_id,
diff --git a/x-pack/plugins/cases/server/routes/api/comments/get_alerts.ts b/x-pack/plugins/cases/server/routes/api/comments/get_alerts.ts
index 4fa793059ed63..a0b0da466e7ce 100644
--- a/x-pack/plugins/cases/server/routes/api/comments/get_alerts.ts
+++ b/x-pack/plugins/cases/server/routes/api/comments/get_alerts.ts
@@ -23,7 +23,8 @@ export const getAllAlertsAttachedToCaseRoute = createCasesRoute({
try {
const caseId = request.params.case_id;
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
return response.ok({
body: await casesClient.attachments.getAllAlertsAttachToCase({ caseId }),
diff --git a/x-pack/plugins/cases/server/routes/api/comments/get_all_comment.ts b/x-pack/plugins/cases/server/routes/api/comments/get_all_comment.ts
index 44f8f59550fb3..72b8f7e6ac98b 100644
--- a/x-pack/plugins/cases/server/routes/api/comments/get_all_comment.ts
+++ b/x-pack/plugins/cases/server/routes/api/comments/get_all_comment.ts
@@ -23,9 +23,10 @@ export const getAllCommentsRoute = createCasesRoute({
}),
},
options: { deprecated: true },
- handler: async ({ context, request, response, logger, kibanaVersion }) => {
+ handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
return response.ok({
body: await client.attachments.getAll({
diff --git a/x-pack/plugins/cases/server/routes/api/comments/get_comment.ts b/x-pack/plugins/cases/server/routes/api/comments/get_comment.ts
index 91adf832f1ea6..2a863f3ee4df4 100644
--- a/x-pack/plugins/cases/server/routes/api/comments/get_comment.ts
+++ b/x-pack/plugins/cases/server/routes/api/comments/get_comment.ts
@@ -22,7 +22,8 @@ export const getCommentRoute = createCasesRoute({
},
handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
return response.ok({
body: await client.attachments.get({
diff --git a/x-pack/plugins/cases/server/routes/api/comments/patch_comment.ts b/x-pack/plugins/cases/server/routes/api/comments/patch_comment.ts
index ebc17daa25611..4bb6493475a9c 100644
--- a/x-pack/plugins/cases/server/routes/api/comments/patch_comment.ts
+++ b/x-pack/plugins/cases/server/routes/api/comments/patch_comment.ts
@@ -31,7 +31,8 @@ export const patchCommentRoute = createCasesRoute({
fold(throwErrors(Boom.badRequest), identity)
);
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
return response.ok({
body: await client.attachments.update({
diff --git a/x-pack/plugins/cases/server/routes/api/comments/post_comment.ts b/x-pack/plugins/cases/server/routes/api/comments/post_comment.ts
index 1ececb3653741..f501f3a425801 100644
--- a/x-pack/plugins/cases/server/routes/api/comments/post_comment.ts
+++ b/x-pack/plugins/cases/server/routes/api/comments/post_comment.ts
@@ -21,7 +21,8 @@ export const postCommentRoute = createCasesRoute({
},
handler: async ({ context, request, response }) => {
try {
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
const caseId = request.params.case_id;
const comment = request.body as CommentRequest;
diff --git a/x-pack/plugins/cases/server/routes/api/configure/get_configure.ts b/x-pack/plugins/cases/server/routes/api/configure/get_configure.ts
index 8dabf7862fc88..72ca1f6a38324 100644
--- a/x-pack/plugins/cases/server/routes/api/configure/get_configure.ts
+++ b/x-pack/plugins/cases/server/routes/api/configure/get_configure.ts
@@ -15,7 +15,8 @@ export const getCaseConfigureRoute = createCasesRoute({
path: CASE_CONFIGURE_URL,
handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
const options = request.query as GetConfigureFindRequest;
return response.ok({
diff --git a/x-pack/plugins/cases/server/routes/api/configure/get_connectors.ts b/x-pack/plugins/cases/server/routes/api/configure/get_connectors.ts
index da99cd19065d6..4c28b896bd855 100644
--- a/x-pack/plugins/cases/server/routes/api/configure/get_connectors.ts
+++ b/x-pack/plugins/cases/server/routes/api/configure/get_connectors.ts
@@ -17,7 +17,8 @@ export const getConnectorsRoute = createCasesRoute({
path: `${CASE_CONFIGURE_CONNECTORS_URL}/_find`,
handler: async ({ context, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
return response.ok({ body: await client.configure.getConnectors() });
} catch (error) {
diff --git a/x-pack/plugins/cases/server/routes/api/configure/patch_configure.ts b/x-pack/plugins/cases/server/routes/api/configure/patch_configure.ts
index 40b0d5123f429..b6754dc6da8f6 100644
--- a/x-pack/plugins/cases/server/routes/api/configure/patch_configure.ts
+++ b/x-pack/plugins/cases/server/routes/api/configure/patch_configure.ts
@@ -30,7 +30,8 @@ export const patchCaseConfigureRoute = createCasesRoute({
fold(throwErrors(Boom.badRequest), identity)
);
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
const configuration = request.body as CasesConfigurePatch;
return response.ok({
diff --git a/x-pack/plugins/cases/server/routes/api/configure/post_configure.ts b/x-pack/plugins/cases/server/routes/api/configure/post_configure.ts
index bb64175fb52ad..102d618fdc052 100644
--- a/x-pack/plugins/cases/server/routes/api/configure/post_configure.ts
+++ b/x-pack/plugins/cases/server/routes/api/configure/post_configure.ts
@@ -25,7 +25,8 @@ export const postCaseConfigureRoute = createCasesRoute({
fold(throwErrors(Boom.badRequest), identity)
);
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
return response.ok({
body: await client.configure.create(query),
diff --git a/x-pack/plugins/cases/server/routes/api/internal/bulk_create_attachments.ts b/x-pack/plugins/cases/server/routes/api/internal/bulk_create_attachments.ts
index 1940cd442eb27..cd2facd2391e3 100644
--- a/x-pack/plugins/cases/server/routes/api/internal/bulk_create_attachments.ts
+++ b/x-pack/plugins/cases/server/routes/api/internal/bulk_create_attachments.ts
@@ -23,7 +23,8 @@ export const bulkCreateAttachmentsRoute = createCasesRoute({
},
handler: async ({ context, request, response }) => {
try {
- const casesClient = await context.cases.getCasesClient();
+ const casesContext = await context.cases;
+ const casesClient = await casesContext.getCasesClient();
const caseId = request.params.case_id;
const attachments = request.body as BulkCreateCommentRequest;
diff --git a/x-pack/plugins/cases/server/routes/api/metrics/get_case_metrics.ts b/x-pack/plugins/cases/server/routes/api/metrics/get_case_metrics.ts
index b86b84410abe6..13bfa2093f623 100644
--- a/x-pack/plugins/cases/server/routes/api/metrics/get_case_metrics.ts
+++ b/x-pack/plugins/cases/server/routes/api/metrics/get_case_metrics.ts
@@ -24,7 +24,8 @@ export const getCaseMetricRoute = createCasesRoute({
},
handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
return response.ok({
body: await client.metrics.getCaseMetrics({
caseId: request.params.case_id,
diff --git a/x-pack/plugins/cases/server/routes/api/stats/get_status.ts b/x-pack/plugins/cases/server/routes/api/stats/get_status.ts
index c245f435835f6..d35d366534c14 100644
--- a/x-pack/plugins/cases/server/routes/api/stats/get_status.ts
+++ b/x-pack/plugins/cases/server/routes/api/stats/get_status.ts
@@ -19,9 +19,10 @@ export const getStatusRoute: CaseRoute = createCasesRoute({
method: 'get',
path: CASE_STATUS_URL,
options: { deprecated: true },
- handler: async ({ context, request, response, logger, kibanaVersion }) => {
+ handler: async ({ context, request, response }) => {
try {
- const client = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const client = await caseContext.getCasesClient();
return response.ok({
body: await client.metrics.getStatusTotalsByType(request.query as CasesStatusRequest),
});
diff --git a/x-pack/plugins/cases/server/routes/api/user_actions/get_all_user_actions.ts b/x-pack/plugins/cases/server/routes/api/user_actions/get_all_user_actions.ts
index ae686969974ea..257db8ab70f00 100644
--- a/x-pack/plugins/cases/server/routes/api/user_actions/get_all_user_actions.ts
+++ b/x-pack/plugins/cases/server/routes/api/user_actions/get_all_user_actions.ts
@@ -23,9 +23,10 @@ export const getUserActionsRoute = createCasesRoute({
}),
},
options: { deprecated: true },
- handler: async ({ context, request, response, logger, kibanaVersion }) => {
+ handler: async ({ context, request, response }) => {
try {
- const casesClient = await context.cases.getCasesClient();
+ const caseContext = await context.cases;
+ const casesClient = await caseContext.getCasesClient();
const caseId = request.params.case_id;
return response.ok({
diff --git a/x-pack/plugins/cases/server/types.ts b/x-pack/plugins/cases/server/types.ts
index 962dc9c85231d..2154aec6f5324 100644
--- a/x-pack/plugins/cases/server/types.ts
+++ b/x-pack/plugins/cases/server/types.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { IRouter, RequestHandlerContext } from '@kbn/core/server';
+import type { IRouter, CustomRequestHandlerContext } from '@kbn/core/server';
import {
ActionTypeConfig,
ActionTypeSecrets,
@@ -22,9 +22,9 @@ export interface CaseRequestContext {
/**
* @internal
*/
-export interface CasesRequestHandlerContext extends RequestHandlerContext {
+export type CasesRequestHandlerContext = CustomRequestHandlerContext<{
cases: CaseRequestContext;
-}
+}>;
/**
* @internal
diff --git a/x-pack/plugins/cloud_security_posture/server/plugin.ts b/x-pack/plugins/cloud_security_posture/server/plugin.ts
index 99900d4aed0d4..754d496965c20 100755
--- a/x-pack/plugins/cloud_security_posture/server/plugin.ts
+++ b/x-pack/plugins/cloud_security_posture/server/plugin.ts
@@ -48,9 +48,11 @@ export class CspPlugin
>
{
private readonly logger: Logger;
+
constructor(initializerContext: PluginInitializerContext) {
this.logger = initializerContext.logger.get();
}
+
private readonly CspAppService = new CspAppService();
public setup(
@@ -88,11 +90,8 @@ export class CspPlugin
request: KibanaRequest
): Promise => {
if (packagePolicy.package?.name === CIS_KUBERNETES_PACKAGE_NAME) {
- await onPackagePolicyPostCreateCallback(
- this.logger,
- packagePolicy,
- context.core.savedObjects.client
- );
+ const soClient = (await context.core).savedObjects.client;
+ await onPackagePolicyPostCreateCallback(this.logger, packagePolicy, soClient);
}
return packagePolicy;
@@ -117,5 +116,6 @@ export class CspPlugin
return {};
}
+
public stop() {}
}
diff --git a/x-pack/plugins/cloud_security_posture/server/routes/benchmarks/benchmarks.ts b/x-pack/plugins/cloud_security_posture/server/routes/benchmarks/benchmarks.ts
index f0c1dc6e1bf96..2112701f42d4a 100644
--- a/x-pack/plugins/cloud_security_posture/server/routes/benchmarks/benchmarks.ts
+++ b/x-pack/plugins/cloud_security_posture/server/routes/benchmarks/benchmarks.ts
@@ -146,12 +146,12 @@ export const defineGetBenchmarksRoute = (router: CspRouter, cspContext: CspAppCo
validate: { query: benchmarksInputSchema },
},
async (context, request, response) => {
- if (!context.fleet.authz.fleet.all) {
+ if (!(await context.fleet).authz.fleet.all) {
return response.forbidden();
}
try {
- const soClient = context.core.savedObjects.client;
+ const soClient = (await context.core).savedObjects.client;
const { query } = request;
const agentService = cspContext.service.agentService;
diff --git a/x-pack/plugins/cloud_security_posture/server/routes/compliance_dashboard/compliance_dashboard.ts b/x-pack/plugins/cloud_security_posture/server/routes/compliance_dashboard/compliance_dashboard.ts
index c271208120ae4..d1c0d7c0eb014 100644
--- a/x-pack/plugins/cloud_security_posture/server/routes/compliance_dashboard/compliance_dashboard.ts
+++ b/x-pack/plugins/cloud_security_posture/server/routes/compliance_dashboard/compliance_dashboard.ts
@@ -44,7 +44,7 @@ export const defineGetComplianceDashboardRoute = (
},
async (context, _, response) => {
try {
- const esClient = context.core.elasticsearch.client.asCurrentUser;
+ const esClient = (await context.core).elasticsearch.client.asCurrentUser;
const { id: pitId } = await esClient.openPointInTime({
index: LATEST_FINDINGS_INDEX_PATTERN,
diff --git a/x-pack/plugins/cloud_security_posture/server/routes/configuration/update_rules_configuration.ts b/x-pack/plugins/cloud_security_posture/server/routes/configuration/update_rules_configuration.ts
index 91bc47a19dad9..63fac62d6b4e1 100644
--- a/x-pack/plugins/cloud_security_posture/server/routes/configuration/update_rules_configuration.ts
+++ b/x-pack/plugins/cloud_security_posture/server/routes/configuration/update_rules_configuration.ts
@@ -106,13 +106,14 @@ export const defineUpdateRulesConfigRoute = (router: CspRouter, cspContext: CspA
validate: { query: configurationUpdateInputSchema },
},
async (context, request, response) => {
- if (!context.fleet.authz.fleet.all) {
+ if (!(await context.fleet).authz.fleet.all) {
return response.forbidden();
}
try {
- const esClient = context.core.elasticsearch.client.asCurrentUser;
- const soClient = context.core.savedObjects.client;
+ const coreContext = await context.core;
+ const esClient = coreContext.elasticsearch.client.asCurrentUser;
+ const soClient = coreContext.savedObjects.client;
const packagePolicyService = cspContext.service.packagePolicyService;
const packagePolicyId = request.query.package_policy_id;
diff --git a/x-pack/plugins/cloud_security_posture/server/routes/findings/findings.ts b/x-pack/plugins/cloud_security_posture/server/routes/findings/findings.ts
index 832a9266441ff..4c9851be902b3 100644
--- a/x-pack/plugins/cloud_security_posture/server/routes/findings/findings.ts
+++ b/x-pack/plugins/cloud_security_posture/server/routes/findings/findings.ts
@@ -111,12 +111,12 @@ export const defineFindingsIndexRoute = (router: CspRouter, cspContext: CspAppCo
validate: { query: findingsInputSchema },
},
async (context, request, response) => {
- if (!context.fleet.authz.fleet.all) {
+ if (!(await context.fleet).authz.fleet.all) {
return response.forbidden();
}
try {
- const esClient = context.core.elasticsearch.client.asCurrentUser;
+ const esClient = (await context.core).elasticsearch.client.asCurrentUser;
const options = buildOptionsRequest(request.query);
const latestCycleIds =
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts
index 3fe320fe5bdd4..d01ecb03dbaed 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts
@@ -34,7 +34,7 @@ export const registerCreateRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id, ...rest } = request.body;
const body = serializeAutoFollowPattern(rest as AutoFollowPattern);
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts
index 63ade6d1bd070..95da1239061b1 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts
@@ -30,7 +30,7 @@ export const registerDeleteRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
const ids = id.split(',');
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.ts
index 7cd9508bd7372..006199673410e 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.ts
@@ -23,7 +23,7 @@ export const registerFetchRoute = ({
validate: false,
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
try {
const { patterns } = await client.asCurrentUser.ccr.getAutoFollowPattern();
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.ts
index a5a70805d518d..0a0c2f4317d77 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.ts
@@ -31,7 +31,7 @@ export const registerGetRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
try {
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts
index 1428e33dee660..b355d37fc5919 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts
@@ -29,7 +29,7 @@ export const registerPauseRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
const ids = id.split(',');
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts
index 912ecd689054d..79d31f84398f1 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts
@@ -29,7 +29,7 @@ export const registerResumeRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
const ids = id.split(',');
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts
index 98a716eb88cc6..0a0ec51ad44d1 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts
@@ -39,7 +39,7 @@ export const registerUpdateRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
const body = serializeAutoFollowPattern(request.body as AutoFollowPattern);
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts
index dbee279a01336..e4b80b273d4eb 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts
@@ -22,7 +22,7 @@ export const registerPermissionsRoute = ({
validate: false,
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
if (!license.isEsSecurityEnabled) {
// If security has been disabled in elasticsearch.yml. we'll just let the user use CCR
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_stats_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_stats_route.ts
index bab31c53a83a2..b9bf86d877a69 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_stats_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_stats_route.ts
@@ -23,7 +23,7 @@ export const registerStatsRoute = ({
validate: false,
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
try {
const { auto_follow_stats: autoFollowStats } = await client.asCurrentUser.ccr.stats();
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts
index 0aae8f9c115bc..84b6096cb3f5b 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts
@@ -44,7 +44,7 @@ export const registerCreateRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { name, ...rest } = request.body;
const body = removeEmptyFields(serializeFollowerIndex(rest as FollowerIndex));
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.ts
index 7bbe2c8c05d4a..da71d96669efb 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.ts
@@ -23,7 +23,7 @@ export const registerFetchRoute = ({
validate: false,
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
try {
const { follower_indices: followerIndices } = await client.asCurrentUser.ccr.followInfo({
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.ts
index c33ed97c289f0..44babd1bbcc46 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.ts
@@ -30,7 +30,7 @@ export const registerGetRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
try {
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts
index 6c888e0a6e8bd..3d77ffefec9fe 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts
@@ -27,7 +27,7 @@ export const registerPauseRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
const ids = id.split(',');
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts
index 206de7d62fb38..da01b3d0e891f 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts
@@ -27,7 +27,7 @@ export const registerResumeRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
const ids = id.split(',');
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_unfollow_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_unfollow_route.ts
index e240a10df0684..f7987029ebc77 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_unfollow_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_unfollow_route.ts
@@ -27,7 +27,7 @@ export const registerUnfollowRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
const ids = id.split(',');
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts
index 0bacbd5fb3450..3c0850ac5984c 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts
@@ -44,7 +44,7 @@ export const registerUpdateRoute = ({
},
},
license.guardApiRoute(async (context, request, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
const { id } = request.params;
// We need to first pause the follower and then resume it by passing the advanced settings
diff --git a/x-pack/plugins/data_enhanced/server/routes/session.test.ts b/x-pack/plugins/data_enhanced/server/routes/session.test.ts
index 507bb173baf67..c6625a3491886 100644
--- a/x-pack/plugins/data_enhanced/server/routes/session.test.ts
+++ b/x-pack/plugins/data_enhanced/server/routes/session.test.ts
@@ -9,10 +9,7 @@ import type { MockedKeys } from '@kbn/utility-types/jest';
import type { CoreSetup, Logger } from '@kbn/core/server';
import { coreMock, httpServerMock } from '@kbn/core/server/mocks';
-import type {
- PluginStart as DataPluginStart,
- DataRequestHandlerContext,
-} from '@kbn/data-plugin/server';
+import type { PluginStart as DataPluginStart } from '@kbn/data-plugin/server';
import { dataPluginMock } from '@kbn/data-plugin/server/mocks';
import { registerSessionRoutes } from './session';
@@ -25,7 +22,7 @@ enum PostHandlerIndex {
describe('registerSessionRoutes', () => {
let mockCoreSetup: MockedKeys>;
- let mockContext: jest.Mocked;
+ let mockContext: ReturnType;
let mockLogger: Logger;
beforeEach(() => {
@@ -46,7 +43,7 @@ describe('registerSessionRoutes', () => {
const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value;
const [, saveHandler] = mockRouter.post.mock.calls[PostHandlerIndex.SAVE];
- saveHandler(mockContext, mockRequest, mockResponse);
+ await saveHandler(mockContext, mockRequest, mockResponse);
expect(mockContext.search!.saveSession).toHaveBeenCalledWith(sessionId, { name });
});
@@ -61,7 +58,7 @@ describe('registerSessionRoutes', () => {
const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value;
const [[, getHandler]] = mockRouter.get.mock.calls;
- getHandler(mockContext, mockRequest, mockResponse);
+ await getHandler(mockContext, mockRequest, mockResponse);
expect(mockContext.search!.getSession).toHaveBeenCalledWith(id);
});
@@ -80,7 +77,7 @@ describe('registerSessionRoutes', () => {
const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value;
const [, findHandler] = mockRouter.post.mock.calls[PostHandlerIndex.FIND];
- findHandler(mockContext, mockRequest, mockResponse);
+ await findHandler(mockContext, mockRequest, mockResponse);
expect(mockContext.search!.findSessions).toHaveBeenCalledWith(body);
});
@@ -98,7 +95,7 @@ describe('registerSessionRoutes', () => {
const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value;
const [, updateHandler] = mockRouter.put.mock.calls[0];
- updateHandler(mockContext, mockRequest, mockResponse);
+ await updateHandler(mockContext, mockRequest, mockResponse);
expect(mockContext.search!.updateSession).toHaveBeenCalledWith(id, body);
});
@@ -113,7 +110,7 @@ describe('registerSessionRoutes', () => {
const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value;
const [, cancelHandler] = mockRouter.post.mock.calls[PostHandlerIndex.CANCEL];
- cancelHandler(mockContext, mockRequest, mockResponse);
+ await cancelHandler(mockContext, mockRequest, mockResponse);
expect(mockContext.search!.cancelSession).toHaveBeenCalledWith(id);
});
@@ -145,7 +142,7 @@ describe('registerSessionRoutes', () => {
const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value;
const [, extendHandler] = mockRouter.post.mock.calls[PostHandlerIndex.EXTEND];
- extendHandler(mockContext, mockRequest, mockResponse);
+ await extendHandler(mockContext, mockRequest, mockResponse);
expect(mockContext.search.extendSession).toHaveBeenCalledWith(id, new Date(expires));
});
diff --git a/x-pack/plugins/data_enhanced/server/routes/session.ts b/x-pack/plugins/data_enhanced/server/routes/session.ts
index 399c9b236b35a..a0eea258c4db5 100644
--- a/x-pack/plugins/data_enhanced/server/routes/session.ts
+++ b/x-pack/plugins/data_enhanced/server/routes/session.ts
@@ -36,7 +36,8 @@ export function registerSessionRoutes(router: DataEnhancedPluginRouter, logger:
request.body;
try {
- const response = await context.search!.saveSession(sessionId, {
+ const searchContext = await context.search;
+ const response = await searchContext.saveSession(sessionId, {
name,
appId,
expires,
@@ -70,7 +71,8 @@ export function registerSessionRoutes(router: DataEnhancedPluginRouter, logger:
async (context, request, res) => {
const { id } = request.params;
try {
- const response = await context.search!.getSession(id);
+ const searchContext = await context.search;
+ const response = await searchContext!.getSession(id);
return res.ok({
body: response,
@@ -104,7 +106,8 @@ export function registerSessionRoutes(router: DataEnhancedPluginRouter, logger:
async (context, request, res) => {
const { page, perPage, sortField, sortOrder, filter, searchFields, search } = request.body;
try {
- const response = await context.search!.findSessions({
+ const searchContext = await context.search;
+ const response = await searchContext!.findSessions({
page,
perPage,
sortField,
@@ -139,7 +142,8 @@ export function registerSessionRoutes(router: DataEnhancedPluginRouter, logger:
async (context, request, res) => {
const { id } = request.params;
try {
- await context.search!.deleteSession(id);
+ const searchContext = await context.search;
+ await searchContext.deleteSession(id);
return res.ok();
} catch (e) {
@@ -165,7 +169,8 @@ export function registerSessionRoutes(router: DataEnhancedPluginRouter, logger:
async (context, request, res) => {
const { id } = request.params;
try {
- await context.search!.cancelSession(id);
+ const searchContext = await context.search;
+ await searchContext.cancelSession(id);
return res.ok();
} catch (e) {
@@ -196,7 +201,8 @@ export function registerSessionRoutes(router: DataEnhancedPluginRouter, logger:
const { id } = request.params;
const { name, expires } = request.body;
try {
- const response = await context.search!.updateSession(id, { name, expires });
+ const searchContext = await context.search;
+ const response = await searchContext.updateSession(id, { name, expires });
return res.ok({
body: response,
@@ -227,7 +233,8 @@ export function registerSessionRoutes(router: DataEnhancedPluginRouter, logger:
const { id } = request.params;
const { expires } = request.body;
try {
- const response = await context.search!.extendSession(id, new Date(expires));
+ const searchContext = await context.search;
+ const response = await searchContext.extendSession(id, new Date(expires));
return res.ok({
body: response,
diff --git a/x-pack/plugins/enterprise_search/server/routes/enterprise_search/indices.ts b/x-pack/plugins/enterprise_search/server/routes/enterprise_search/indices.ts
index 28359bc90052f..65868e4d17935 100644
--- a/x-pack/plugins/enterprise_search/server/routes/enterprise_search/indices.ts
+++ b/x-pack/plugins/enterprise_search/server/routes/enterprise_search/indices.ts
@@ -12,7 +12,7 @@ export function registerListRoute({ router }: RouteDependencies) {
router.get(
{ path: '/internal/enterprise_search/indices', validate: false },
async (context, _, response) => {
- const { client } = context.core.elasticsearch;
+ const { client } = (await context.core).elasticsearch;
try {
const indices = await fetchIndices(client);
return response.ok({
diff --git a/x-pack/plugins/event_log/server/routes/find.ts b/x-pack/plugins/event_log/server/routes/find.ts
index fd940d0f64ad5..4c9ab70bbe3a5 100644
--- a/x-pack/plugins/event_log/server/routes/find.ts
+++ b/x-pack/plugins/event_log/server/routes/find.ts
@@ -38,7 +38,7 @@ export const findRoute = (router: EventLogRouter, systemLogger: Logger) => {
if (!context.eventLog) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for eventLog' });
}
- const eventLogClient = context.eventLog.getEventLogClient();
+ const eventLogClient = (await context.eventLog).getEventLogClient();
const {
params: { id, type },
query,
diff --git a/x-pack/plugins/event_log/server/routes/find_by_ids.ts b/x-pack/plugins/event_log/server/routes/find_by_ids.ts
index 85346b1e87be5..a33a03c8242c4 100644
--- a/x-pack/plugins/event_log/server/routes/find_by_ids.ts
+++ b/x-pack/plugins/event_log/server/routes/find_by_ids.ts
@@ -44,7 +44,7 @@ export const findByIdsRoute = (router: EventLogRouter, systemLogger: Logger) =>
if (!context.eventLog) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for eventLog' });
}
- const eventLogClient = context.eventLog.getEventLogClient();
+ const eventLogClient = (await context.eventLog).getEventLogClient();
const {
params: { type },
body: { ids, legacyIds },
diff --git a/x-pack/plugins/event_log/server/types.ts b/x-pack/plugins/event_log/server/types.ts
index 10a472e802b9f..1336245741bd6 100644
--- a/x-pack/plugins/event_log/server/types.ts
+++ b/x-pack/plugins/event_log/server/types.ts
@@ -6,7 +6,7 @@
*/
import { schema, TypeOf } from '@kbn/config-schema';
-import type { IRouter, KibanaRequest, RequestHandlerContext } from '@kbn/core/server';
+import type { IRouter, KibanaRequest, CustomRequestHandlerContext } from '@kbn/core/server';
export type { IEvent, IValidatedEvent } from '../generated/schemas';
export { EventSchema, ECS_VERSION } from '../generated/schemas';
@@ -16,6 +16,7 @@ import {
AggregateEventsBySavedObjectResult,
QueryEventsBySavedObjectResult,
} from './es/cluster_client_adapter';
+
export type {
QueryEventsBySavedObjectResult,
AggregateEventsBySavedObjectResult,
@@ -79,9 +80,9 @@ export interface EventLogApiRequestHandlerContext {
/**
* @internal
*/
-export interface EventLogRequestHandlerContext extends RequestHandlerContext {
+export type EventLogRequestHandlerContext = CustomRequestHandlerContext<{
eventLog: EventLogApiRequestHandlerContext;
-}
+}>;
/**
* @internal
diff --git a/x-pack/plugins/features/server/routes/index.test.ts b/x-pack/plugins/features/server/routes/index.test.ts
index 4d61d131cc0ac..31cb1358f63fa 100644
--- a/x-pack/plugins/features/server/routes/index.test.ts
+++ b/x-pack/plugins/features/server/routes/index.test.ts
@@ -15,10 +15,9 @@ import { RequestHandler } from '@kbn/core/server';
import { FeatureKibanaPrivileges, KibanaFeatureConfig, SubFeatureConfig } from '../../common';
function createContextMock(licenseType: LicenseType = 'platinum') {
- return {
- core: coreMock.createRequestHandlerContext(),
+ return coreMock.createCustomRequestHandlerContext({
licensing: licensingMock.createRequestHandlerContext({ license: { type: licenseType } }),
- };
+ });
}
function createPrivilege(partial: Partial = {}): FeatureKibanaPrivileges {
@@ -138,7 +137,7 @@ describe('GET /api/features', () => {
it('returns a list of available features, sorted by their configured order', async () => {
const mockResponse = httpServerMock.createResponseFactory();
- routeHandler(createContextMock(), { query: {} } as any, mockResponse);
+ await routeHandler(createContextMock(), { query: {} } as any, mockResponse);
expect(mockResponse.ok).toHaveBeenCalledTimes(1);
const [call] = mockResponse.ok.mock.calls;
@@ -173,7 +172,7 @@ describe('GET /api/features', () => {
it(`by default does not return features that arent allowed by current license`, async () => {
const mockResponse = httpServerMock.createResponseFactory();
- routeHandler(createContextMock('basic'), { query: {} } as any, mockResponse);
+ await routeHandler(createContextMock('basic'), { query: {} } as any, mockResponse);
expect(mockResponse.ok).toHaveBeenCalledTimes(1);
const [call] = mockResponse.ok.mock.calls;
@@ -204,7 +203,7 @@ describe('GET /api/features', () => {
it(`ignoreValidLicenses=false does not return features that arent allowed by current license`, async () => {
const mockResponse = httpServerMock.createResponseFactory();
- routeHandler(
+ await routeHandler(
createContextMock('basic'),
{ query: { ignoreValidLicenses: false } } as any,
mockResponse
@@ -239,7 +238,7 @@ describe('GET /api/features', () => {
it(`ignoreValidLicenses=true returns features that arent allowed by current license`, async () => {
const mockResponse = httpServerMock.createResponseFactory();
- routeHandler(
+ await routeHandler(
createContextMock('basic'),
{ query: { ignoreValidLicenses: true } } as any,
mockResponse
diff --git a/x-pack/plugins/features/server/routes/index.ts b/x-pack/plugins/features/server/routes/index.ts
index 1f2b833663f1a..bb78f07bc56cc 100644
--- a/x-pack/plugins/features/server/routes/index.ts
+++ b/x-pack/plugins/features/server/routes/index.ts
@@ -26,8 +26,8 @@ export function defineRoutes({ router, featureRegistry }: RouteDefinitionParams)
query: schema.object({ ignoreValidLicenses: schema.boolean({ defaultValue: false }) }),
},
},
- (context, request, response) => {
- const currentLicense = context.licensing!.license;
+ async (context, request, response) => {
+ const { license: currentLicense } = await context.licensing;
const allFeatures = featureRegistry.getAllKibanaFeatures(
currentLicense,
diff --git a/x-pack/plugins/features/server/types.ts b/x-pack/plugins/features/server/types.ts
index 826d4282cc425..99a6c96e43322 100644
--- a/x-pack/plugins/features/server/types.ts
+++ b/x-pack/plugins/features/server/types.ts
@@ -5,15 +5,15 @@
* 2.0.
*/
-import type { RequestHandlerContext, IRouter } from '@kbn/core/server';
+import type { CustomRequestHandlerContext, IRouter } from '@kbn/core/server';
import type { LicensingApiRequestHandlerContext } from '@kbn/licensing-plugin/server';
/**
* @internal
*/
-export interface FeaturesRequestHandlerContext extends RequestHandlerContext {
+export type FeaturesRequestHandlerContext = CustomRequestHandlerContext<{
licensing: LicensingApiRequestHandlerContext;
-}
+}>;
/**
* @internal
diff --git a/x-pack/plugins/file_upload/server/routes.ts b/x-pack/plugins/file_upload/server/routes.ts
index 0abab34ebef7b..76d6443f47f54 100644
--- a/x-pack/plugins/file_upload/server/routes.ts
+++ b/x-pack/plugins/file_upload/server/routes.ts
@@ -102,11 +102,8 @@ export function fileUploadRoutes(coreSetup: CoreSetup, logge
},
async (context, request, response) => {
try {
- const result = await analyzeFile(
- context.core.elasticsearch.client,
- request.body,
- request.query
- );
+ const esClient = (await context.core).elasticsearch.client;
+ const result = await analyzeFile(esClient, request.body, request.query);
return response.ok({ body: result });
} catch (e) {
return response.customError(wrapError(e));
@@ -142,6 +139,7 @@ export function fileUploadRoutes(coreSetup: CoreSetup, logge
try {
const { id } = request.query;
const { index, data, settings, mappings, ingestPipeline } = request.body;
+ const esClient = (await context.core).elasticsearch.client;
// `id` being `undefined` tells us that this is a new import due to create a new index.
// follow-up import calls to just add additional data will include the `id` of the created
@@ -151,7 +149,7 @@ export function fileUploadRoutes(coreSetup: CoreSetup, logge
}
const result = await importData(
- context.core.elasticsearch.client,
+ esClient,
id,
index,
settings,
@@ -182,9 +180,8 @@ export function fileUploadRoutes(coreSetup: CoreSetup, logge
},
async (context, request, response) => {
try {
- const indexExists = await context.core.elasticsearch.client.asCurrentUser.indices.exists(
- request.body
- );
+ const esClient = (await context.core).elasticsearch.client;
+ const indexExists = await esClient.asCurrentUser.indices.exists(request.body);
return response.ok({ body: { exists: indexExists } });
} catch (e) {
return response.customError(wrapError(e));
@@ -225,8 +222,9 @@ export function fileUploadRoutes(coreSetup: CoreSetup, logge
async (context, request, response) => {
try {
const { index, timeFieldName, query, runtimeMappings } = request.body;
+ const esClient = (await context.core).elasticsearch.client;
const resp = await getTimeFieldRange(
- context.core.elasticsearch.client,
+ esClient,
index,
timeFieldName,
query,
diff --git a/x-pack/plugins/fleet/server/mocks/index.ts b/x-pack/plugins/fleet/server/mocks/index.ts
index 8fd23dfbbac83..01fe5b48f9e31 100644
--- a/x-pack/plugins/fleet/server/mocks/index.ts
+++ b/x-pack/plugins/fleet/server/mocks/index.ts
@@ -75,7 +75,7 @@ export const createAppContextStartContractMock = (
};
export const createFleetRequestHandlerContextMock = (): jest.Mocked<
- FleetRequestHandlerContext['fleet']
+ Awaited
> => {
return {
authz: createFleetAuthzMock(),
diff --git a/x-pack/plugins/fleet/server/plugin.ts b/x-pack/plugins/fleet/server/plugin.ts
index 20d55409e50d2..c9e3b9388087d 100644
--- a/x-pack/plugins/fleet/server/plugin.ts
+++ b/x-pack/plugins/fleet/server/plugin.ts
@@ -319,12 +319,11 @@ export class FleetPlugin
PLUGIN_ID,
async (context, request) => {
const plugin = this;
+ const esClient = (await context.core).elasticsearch.client;
return {
get agentClient() {
- const agentService = plugin.setupAgentService(
- context.core.elasticsearch.client.asInternalUser
- );
+ const agentService = plugin.setupAgentService(esClient.asInternalUser);
return {
asCurrentUser: agentService.asScoped(request),
@@ -382,6 +381,7 @@ export class FleetPlugin
this.telemetryEventsSender.setup(deps.telemetry);
}
+
public start(core: CoreStart, plugins: FleetStartDeps): FleetStartContract {
appContextService.start({
elasticsearch: core.elasticsearch,
diff --git a/x-pack/plugins/fleet/server/routes/agent/actions_handlers.ts b/x-pack/plugins/fleet/server/routes/agent/actions_handlers.ts
index 265fe4d9e4221..4f3cad9edab26 100644
--- a/x-pack/plugins/fleet/server/routes/agent/actions_handlers.ts
+++ b/x-pack/plugins/fleet/server/routes/agent/actions_handlers.ts
@@ -24,7 +24,7 @@ export const postNewAgentActionHandlerBuilder = function (
> {
return async (context, request, response) => {
try {
- const esClient = context.core.elasticsearch.client.asInternalUser;
+ const esClient = (await context.core).elasticsearch.client.asInternalUser;
const agent = await actionsService.getAgent(esClient, request.params.agentId);
diff --git a/x-pack/plugins/fleet/server/routes/agent/handlers.ts b/x-pack/plugins/fleet/server/routes/agent/handlers.ts
index b0c6a975dfead..b9e82e844e81b 100644
--- a/x-pack/plugins/fleet/server/routes/agent/handlers.ts
+++ b/x-pack/plugins/fleet/server/routes/agent/handlers.ts
@@ -32,8 +32,9 @@ import * as AgentService from '../../services/agents';
export const getAgentHandler: RequestHandler<
TypeOf
> = async (context, request, response) => {
- const soClient = context.core.savedObjects.client;
- const esClient = context.core.elasticsearch.client.asInternalUser;
+ const coreContext = await context.core;
+ const soClient = coreContext.savedObjects.client;
+ const esClient = coreContext.elasticsearch.client.asInternalUser;
try {
const body: GetOneAgentResponse = {
@@ -55,7 +56,8 @@ export const getAgentHandler: RequestHandler<
export const deleteAgentHandler: RequestHandler<
TypeOf
> = async (context, request, response) => {
- const esClient = context.core.elasticsearch.client.asInternalUser;
+ const coreContext = await context.core;
+ const esClient = coreContext.elasticsearch.client.asInternalUser;
try {
await AgentService.deleteAgent(esClient, request.params.agentId);
@@ -82,7 +84,8 @@ export const updateAgentHandler: RequestHandler<
undefined,
TypeOf
> = async (context, request, response) => {
- const esClient = context.core.elasticsearch.client.asInternalUser;
+ const coreContext = await context.core;
+ const esClient = coreContext.elasticsearch.client.asInternalUser;
try {
await AgentService.updateAgent(esClient, request.params.agentId, {
@@ -108,7 +111,8 @@ export const getAgentsHandler: RequestHandler<
undefined,
TypeOf
> = async (context, request, response) => {
- const esClient = context.core.elasticsearch.client.asInternalUser;
+ const coreContext = await context.core;
+ const esClient = coreContext.elasticsearch.client.asInternalUser;
try {
const { agents, total, page, perPage } = await AgentService.getAgentsByKuery(esClient, {
@@ -143,8 +147,9 @@ export const putAgentsReassignHandler: RequestHandler<
undefined,
TypeOf
> = async (context, request, response) => {
- const soClient = context.core.savedObjects.client;
- const esClient = context.core.elasticsearch.client.asInternalUser;
+ const coreContext = await context.core;
+ const soClient = coreContext.savedObjects.client;
+ const esClient = coreContext.elasticsearch.client.asInternalUser;
try {
await AgentService.reassignAgent(
soClient,
@@ -172,8 +177,9 @@ export const postBulkAgentsReassignHandler: RequestHandler<
});
}
- const soClient = context.core.savedObjects.client;
- const esClient = context.core.elasticsearch.client.asInternalUser;
+ const coreContext = await context.core;
+ const soClient = coreContext.savedObjects.client;
+ const esClient = coreContext.elasticsearch.client.asInternalUser;
const agentOptions = Array.isArray(request.body.agents)
? { agentIds: request.body.agents }
: { kuery: request.body.agents };
@@ -204,7 +210,8 @@ export const getAgentStatusForAgentPolicyHandler: RequestHandler<
undefined,
TypeOf
> = async (context, request, response) => {
- const esClient = context.core.elasticsearch.client.asInternalUser;
+ const coreContext = await context.core;
+ const esClient = coreContext.elasticsearch.client.asInternalUser;
try {
const results = await AgentService.getAgentStatusForAgentPolicy(
esClient,
@@ -224,7 +231,8 @@ export const getAgentDataHandler: RequestHandler<
undefined,
TypeOf