Skip to content

Commit

Permalink
[eem] add server entity client (elastic#191645)
Browse files Browse the repository at this point in the history
  • Loading branch information
klacabane authored Aug 30, 2024
1 parent f264632 commit 0a99955
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 44 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { EntityDefinition } from '@kbn/entities-schema';
import { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server';
import { ElasticsearchClient } from '@kbn/core-elasticsearch-server';
import { Logger } from '@kbn/logging';
import { installEntityDefinition } from './entities/install_entity_definition';
import { startTransform } from './entities/start_transform';
import { findEntityDefinitions } from './entities/find_entity_definition';
import { uninstallEntityDefinition } from './entities/uninstall_entity_definition';
import { EntityDefinitionNotFound } from './entities/errors/entity_not_found';

export class EntityClient {
constructor(
private options: {
esClient: ElasticsearchClient;
soClient: SavedObjectsClientContract;
logger: Logger;
}
) {}

async createEntityDefinition({
definition,
installOnly = false,
}: {
definition: EntityDefinition;
installOnly?: boolean;
}) {
const installedDefinition = await installEntityDefinition({
definition,
soClient: this.options.soClient,
esClient: this.options.esClient,
logger: this.options.logger,
});

if (!installOnly) {
await startTransform(this.options.esClient, definition, this.options.logger);
}

return installedDefinition;
}

async deleteEntityDefinition({ id, deleteData = false }: { id: string; deleteData?: boolean }) {
const [definition] = await findEntityDefinitions({
id,
perPage: 1,
soClient: this.options.soClient,
esClient: this.options.esClient,
});

if (!definition) {
const message = `Unable to find entity definition with [${id}]`;
this.options.logger.error(message);
throw new EntityDefinitionNotFound(message);
}

await uninstallEntityDefinition({
definition,
deleteData,
soClient: this.options.soClient,
esClient: this.options.esClient,
logger: this.options.logger,
});
}

async getEntityDefinitions({ page = 1, perPage = 10 }: { page?: number; perPage?: number }) {
const definitions = await findEntityDefinitions({
esClient: this.options.esClient,
soClient: this.options.soClient,
page,
perPage,
});

return { definitions };
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
PluginInitializerContext,
PluginConfigDescriptor,
Logger,
KibanaRequest,
} from '@kbn/core/server';
import { installEntityManagerTemplates } from './lib/manage_index_templates';
import { setupRoutes } from './routes';
Expand All @@ -26,6 +27,7 @@ import { EntityManagerConfig, configSchema, exposeToBrowserConfig } from '../com
import { entityDefinition, EntityDiscoveryApiKeyType } from './saved_objects';
import { upgradeBuiltInEntityDefinitions } from './lib/entities/upgrade_entity_definition';
import { builtInDefinitions } from './lib/entities/built_in';
import { EntityClient } from './lib/entity_client';

export type EntityManagerServerPluginSetup = ReturnType<EntityManagerServerPlugin['setup']>;
export type EntityManagerServerPluginStart = ReturnType<EntityManagerServerPlugin['start']>;
Expand Down Expand Up @@ -73,6 +75,12 @@ export class EntityManagerServerPlugin
router,
logger: this.logger,
server: this.server,
getScopedClient: async ({ request }: { request: KibanaRequest }) => {
const [coreStart] = await core.getStartServices();
const esClient = coreStart.elasticsearch.client.asScoped(request).asCurrentUser;
const soClient = coreStart.savedObjects.getScopedClient(request);
return new EntityClient({ esClient, soClient, logger: this.logger });
},
});

return {};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ import { SetupRouteOptions } from '../types';
import { EntityIdConflict } from '../../lib/entities/errors/entity_id_conflict_error';
import { EntitySecurityException } from '../../lib/entities/errors/entity_security_exception';
import { InvalidTransformError } from '../../lib/entities/errors/invalid_transform_error';
import { startTransform } from '../../lib/entities/start_transform';
import { installEntityDefinition } from '../../lib/entities/install_entity_definition';
import { EntityDefinitionIdInvalid } from '../../lib/entities/errors/entity_definition_id_invalid';

/**
Expand Down Expand Up @@ -56,7 +54,8 @@ import { EntityDefinitionIdInvalid } from '../../lib/entities/errors/entity_defi
*/
export function createEntityDefinitionRoute<T extends RequestHandlerContext>({
router,
server,
getScopedClient,
logger,
}: SetupRouteOptions<T>) {
router.post<unknown, CreateEntityDefinitionQuery, EntityDefinition>(
{
Expand All @@ -66,24 +65,14 @@ export function createEntityDefinitionRoute<T extends RequestHandlerContext>({
query: createEntityDefinitionQuerySchema,
},
},
async (context, req, res) => {
const { logger } = server;
const core = await context.core;
const soClient = core.savedObjects.client;
const esClient = core.elasticsearch.client.asCurrentUser;

async (context, request, res) => {
try {
const definition = await installEntityDefinition({
soClient,
esClient,
logger,
definition: req.body,
const client = await getScopedClient({ request });
const definition = await client.createEntityDefinition({
definition: request.body,
installOnly: request.query.installOnly,
});

if (!req.query.installOnly) {
await startTransform(esClient, definition, logger);
}

return res.ok({ body: definition });
} catch (e) {
logger.error(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ import {
import { SetupRouteOptions } from '../types';
import { EntitySecurityException } from '../../lib/entities/errors/entity_security_exception';
import { InvalidTransformError } from '../../lib/entities/errors/invalid_transform_error';
import { readEntityDefinition } from '../../lib/entities/read_entity_definition';
import { EntityDefinitionNotFound } from '../../lib/entities/errors/entity_not_found';
import { uninstallEntityDefinition } from '../../lib/entities/uninstall_entity_definition';

/**
* @openapi
Expand Down Expand Up @@ -53,7 +51,7 @@ import { uninstallEntityDefinition } from '../../lib/entities/uninstall_entity_d
*/
export function deleteEntityDefinitionRoute<T extends RequestHandlerContext>({
router,
server,
getScopedClient,
logger,
}: SetupRouteOptions<T>) {
router.delete<{ id: string }, { deleteData?: boolean }, unknown>(
Expand All @@ -64,18 +62,12 @@ export function deleteEntityDefinitionRoute<T extends RequestHandlerContext>({
query: deleteEntityDefinitionQuerySchema.strict(),
},
},
async (context, req, res) => {
async (context, request, res) => {
try {
const soClient = (await context.core).savedObjects.client;
const esClient = (await context.core).elasticsearch.client.asCurrentUser;

const definition = await readEntityDefinition(soClient, req.params.id, logger);
await uninstallEntityDefinition({
definition,
soClient,
esClient,
logger,
deleteData: req.query.deleteData,
const client = await getScopedClient({ request });
await client.deleteEntityDefinition({
id: request.params.id,
deleteData: request.query.deleteData,
});

return res.ok({ body: { acknowledged: true } });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { z } from '@kbn/zod';
import { RequestHandlerContext } from '@kbn/core/server';
import { getEntityDefinitionQuerySchema } from '@kbn/entities-schema';
import { SetupRouteOptions } from '../types';
import { findEntityDefinitions } from '../../lib/entities/find_entity_definition';

/**
* @openapi
Expand Down Expand Up @@ -52,6 +51,7 @@ import { findEntityDefinitions } from '../../lib/entities/find_entity_definition
*/
export function getEntityDefinitionRoute<T extends RequestHandlerContext>({
router,
getScopedClient,
logger,
}: SetupRouteOptions<T>) {
router.get<{ id?: string }, { page?: number; perPage?: number }, unknown>(
Expand All @@ -62,18 +62,15 @@ export function getEntityDefinitionRoute<T extends RequestHandlerContext>({
params: z.object({ id: z.optional(z.string()) }),
},
},
async (context, req, res) => {
async (context, request, res) => {
try {
const esClient = (await context.core).elasticsearch.client.asCurrentUser;
const soClient = (await context.core).savedObjects.client;
const definitions = await findEntityDefinitions({
esClient,
soClient,
page: req.query.page ?? 1,
perPage: req.query.perPage ?? 10,
id: req.params.id,
const client = await getScopedClient({ request });
const result = await client.getEntityDefinitions({
page: request.query.page,
perPage: request.query.perPage,
});
return res.ok({ body: { definitions } });

return res.ok({ body: result });
} catch (e) {
logger.error(e);
return res.customError({ body: e, statusCode: 500 });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
* 2.0.
*/

import { IRouter, RequestHandlerContextBase } from '@kbn/core-http-server';
import { IRouter, KibanaRequest, RequestHandlerContextBase } from '@kbn/core-http-server';
import { Logger } from '@kbn/core/server';
import { EntityManagerServerSetup } from '../types';
import { EntityClient } from '../lib/entity_client';

export interface SetupRouteOptions<T extends RequestHandlerContextBase> {
router: IRouter<T>;
server: EntityManagerServerSetup;
logger: Logger;
getScopedClient: ({ request }: { request: KibanaRequest }) => Promise<EntityClient>;
}

0 comments on commit 0a99955

Please sign in to comment.