Skip to content

Commit

Permalink
[ML] AIOps: Refactor routes to use handlers. (elastic#170096)
Browse files Browse the repository at this point in the history
This refactors the code for server side routes in the AIOps plugin. It
splits up the routes into an outer `define_route.ts` and an inner
`route_handler_factory.ts` file.

- `define_route.ts` creates a versioned route and uses
`route_handler_factory.ts` to be passed in as the route handler.
- `route_handler_factory.ts` includes all logic for the route,
previously this was an inline callback in the route definition.

The aim of this PR is to be better prepared for future route versioning.
Splitting out the handler simplifies the route definition and will allow
the reuse of handlers for different versions or the usage of different
handlers.
  • Loading branch information
walterra authored Oct 30, 2023
1 parent fe62cd5 commit 9a68094
Show file tree
Hide file tree
Showing 50 changed files with 1,088 additions and 1,037 deletions.
3 changes: 3 additions & 0 deletions x-pack/plugins/aiops/common/api/log_categorization/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,6 @@ export const categorizationFieldValidationSchema = schema.object({
indicesOptions: indicesOptionsSchema,
includeExamples: schema.boolean(),
});
export type CategorizationFieldValidationSchema = TypeOf<
typeof categorizationFieldValidationSchema
>;
7 changes: 3 additions & 4 deletions x-pack/plugins/aiops/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ import {
AiopsPluginSetupDeps,
AiopsPluginStartDeps,
} from './types';

import { defineLogRateAnalysisRoute } from './routes';
import { defineLogCategorizationRoutes } from './routes/log_categorization';
import { defineRoute as defineLogRateAnalysisRoute } from './routes/log_rate_analysis/define_route';
import { defineRoute as defineCategorizationFieldValidationRoute } from './routes/categorization_field_validation/define_route';
import { registerCasesPersistableState } from './register_cases';

export class AiopsPlugin
Expand Down Expand Up @@ -59,7 +58,7 @@ export class AiopsPlugin
// Register server side APIs
core.getStartServices().then(([coreStart, depsStart]) => {
defineLogRateAnalysisRoute(router, aiopsLicense, this.logger, coreStart, this.usageCounter);
defineLogCategorizationRoutes(router, aiopsLicense, this.usageCounter);
defineCategorizationFieldValidationRoute(router, aiopsLicense, this.usageCounter);
});

return {};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* 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 type { IRouter } from '@kbn/core/server';
import type { DataRequestHandlerContext } from '@kbn/data-plugin/server';
import type { UsageCounter } from '@kbn/usage-collection-plugin/server';
import { categorizationFieldValidationSchema } from '../../../common/api/log_categorization/schema';
import { AIOPS_API_ENDPOINT } from '../../../common/api';
import type { AiopsLicense } from '../../types';
import { routeHandlerFactory } from './route_handler_factory';

export const defineRoute = (
router: IRouter<DataRequestHandlerContext>,
license: AiopsLicense,
usageCounter?: UsageCounter
) => {
router.versioned
.post({
path: AIOPS_API_ENDPOINT.CATEGORIZATION_FIELD_VALIDATION,
access: 'internal',
})
.addVersion(
{
version: '1',
validate: {
request: {
body: categorizationFieldValidationSchema,
},
},
},
routeHandlerFactory(license, usageCounter)
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* 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 type {
KibanaRequest,
RequestHandlerContext,
RequestHandler,
KibanaResponseFactory,
} from '@kbn/core/server';
import { categorizationExamplesProvider } from '@kbn/ml-category-validator';
import type { UsageCounter } from '@kbn/usage-collection-plugin/server';
import { wrapError } from '../error_wrapper';
import { trackAIOpsRouteUsage } from '../../lib/track_route_usage';
import { AIOPS_TELEMETRY_ID } from '../../../common/constants';
import { AIOPS_API_ENDPOINT } from '../../../common/api';
import type { AiopsLicense } from '../../types';
import type { CategorizationFieldValidationSchema } from '../../../common/api/log_categorization/schema';

export const routeHandlerFactory: (
license: AiopsLicense,
usageCounter?: UsageCounter
) => RequestHandler<unknown, unknown, CategorizationFieldValidationSchema> =
(license, usageCounter) =>
async (
context: RequestHandlerContext,
request: KibanaRequest<unknown, unknown, CategorizationFieldValidationSchema>,
response: KibanaResponseFactory
) => {
const { headers } = request;
trackAIOpsRouteUsage(
`POST ${AIOPS_API_ENDPOINT.CATEGORIZATION_FIELD_VALIDATION}`,
headers[AIOPS_TELEMETRY_ID.AIOPS_ANALYSIS_RUN_ORIGIN],
usageCounter
);

if (!license.isActivePlatinumLicense) {
return response.forbidden();
}
try {
const {
elasticsearch: { client },
} = await context.core;

const {
indexPatternTitle,
timeField,
query,
size,
field,
start,
end,
analyzer,
runtimeMappings,
indicesOptions,
includeExamples,
} = request.body;

const { validateCategoryExamples } = categorizationExamplesProvider(client);
const resp = await validateCategoryExamples(
indexPatternTitle,
query,
size,
field,
timeField,
start,
end,
analyzer ?? {},
runtimeMappings,
indicesOptions,
includeExamples
);

return response.ok({
body: resp,
});
} catch (e) {
return response.customError(wrapError(e));
}
};
8 changes: 0 additions & 8 deletions x-pack/plugins/aiops/server/routes/index.ts

This file was deleted.

91 changes: 0 additions & 91 deletions x-pack/plugins/aiops/server/routes/log_categorization.ts

This file was deleted.

Loading

0 comments on commit 9a68094

Please sign in to comment.