Skip to content

Commit

Permalink
replace any with unknown in event log
Browse files Browse the repository at this point in the history
  • Loading branch information
gmmorris committed Apr 22, 2020
1 parent 78d11a7 commit 61d9018
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 28 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -736,7 +736,7 @@ module.exports = {
{
// typescript only for front and back end
files: [
'x-pack/{,legacy/}plugins/{alerting,alerting_builtins,actions,task_manager}/**/*.{ts,tsx}',
'x-pack/{,legacy/}plugins/{alerting,alerting_builtins,actions,task_manager,event_log}/**/*.{ts,tsx}',
],
rules: {
'@typescript-eslint/no-explicit-any': 'error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ describe('indexDocument', () => {
});

describe('doesIlmPolicyExist', () => {
// ElasticsearchError can be a bit random in shape, we need an any here
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const notFoundError = new Error('Not found') as any;
notFoundError.statusCode = 404;

Expand Down Expand Up @@ -187,6 +189,8 @@ describe('createIndex', () => {
});

test(`shouldn't throw when an error of type resource_already_exists_exception is thrown`, async () => {
// ElasticsearchError can be a bit random in shape, we need an any here
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const err = new Error('Already exists') as any;
err.body = {
error: {
Expand Down
50 changes: 32 additions & 18 deletions x-pack/plugins/event_log/server/es/cluster_client_adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import { reject, isUndefined } from 'lodash';
import { SearchResponse, Client } from 'elasticsearch';
import { Logger, ClusterClient } from '../../../../../src/core/server';
import { IEvent } from '../types';
import { FindOptionsType } from '../event_log_client';
Expand Down Expand Up @@ -33,8 +34,8 @@ export class ClusterClientAdapter {
this.clusterClientPromise = opts.clusterClientPromise;
}

public async indexDocument(doc: any): Promise<void> {
await this.callEs('index', doc);
public async indexDocument(doc: unknown): Promise<void> {
await this.callEs<ReturnType<Client['index']>>('index', doc);
}

public async doesIlmPolicyExist(policyName: string): Promise<boolean> {
Expand All @@ -51,7 +52,7 @@ export class ClusterClientAdapter {
return true;
}

public async createIlmPolicy(policyName: string, policy: any): Promise<void> {
public async createIlmPolicy(policyName: string, policy: unknown): Promise<void> {
const request = {
method: 'PUT',
path: `_ilm/policy/${policyName}`,
Expand All @@ -67,21 +68,27 @@ export class ClusterClientAdapter {
public async doesIndexTemplateExist(name: string): Promise<boolean> {
let result;
try {
result = await this.callEs('indices.existsTemplate', { name });
result = await this.callEs<ReturnType<Client['indices']['existsTemplate']>>(
'indices.existsTemplate',
{ name }
);
} catch (err) {
throw new Error(`error checking existance of index template: ${err.message}`);
}
return result as boolean;
}

public async createIndexTemplate(name: string, template: any): Promise<void> {
public async createIndexTemplate(name: string, template: unknown): Promise<void> {
const addTemplateParams = {
name,
create: true,
body: template,
};
try {
await this.callEs('indices.putTemplate', addTemplateParams);
await this.callEs<ReturnType<Client['indices']['putTemplate']>>(
'indices.putTemplate',
addTemplateParams
);
} catch (err) {
// The error message doesn't have a type attribute we can look to guarantee it's due
// to the template already existing (only long message) so we'll check ourselves to see
Expand All @@ -97,16 +104,19 @@ export class ClusterClientAdapter {
public async doesAliasExist(name: string): Promise<boolean> {
let result;
try {
result = await this.callEs('indices.existsAlias', { name });
result = await this.callEs<ReturnType<Client['indices']['existsAlias']>>(
'indices.existsAlias',
{ name }
);
} catch (err) {
throw new Error(`error checking existance of initial index: ${err.message}`);
}
return result as boolean;
}

public async createIndex(name: string, body: any = {}): Promise<void> {
public async createIndex(name: string, body: unknown = {}): Promise<void> {
try {
await this.callEs('indices.create', {
await this.callEs<ReturnType<Client['indices']['create']>>('indices.create', {
index: name,
body,
});
Expand All @@ -125,12 +135,14 @@ export class ClusterClientAdapter {
): Promise<QueryEventsBySavedObjectResult> {
try {
const {
hits: {
hits,
total: { value: total },
},
} = await this.callEs('search', {
hits: { hits, total },
}: SearchResponse<unknown> = await this.callEs('search', {
index,
/*
This ensures the hits.total is rturned as an int instead of an object value as
the SearchResponse type only supports total as an int, not as an object
*/
rest_total_hits_as_int: true,
body: {
size: perPage,
from: (page - 1) * perPage,
Expand Down Expand Up @@ -189,7 +201,7 @@ export class ClusterClientAdapter {
page,
per_page: perPage,
total,
data: hits.map((hit: any) => hit._source) as IEvent[],
data: hits.map(hit => hit._source) as IEvent[],
};
} catch (err) {
throw new Error(
Expand All @@ -198,13 +210,15 @@ export class ClusterClientAdapter {
}
}

private async callEs(operation: string, body?: any): Promise<any> {
// We have a common problem typing ES-DSL Queries
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private async callEs<ESQueryResult = unknown>(operation: string, body?: any) {
try {
this.debug(`callEs(${operation}) calls:`, body);
const clusterClient = await this.clusterClientPromise;
const result = await clusterClient.callAsInternalUser(operation, body);
this.debug(`callEs(${operation}) result:`, result);
return result;
return result as ESQueryResult;
} catch (err) {
this.debug(`callEs(${operation}) error:`, {
message: err.message,
Expand All @@ -214,7 +228,7 @@ export class ClusterClientAdapter {
}
}

private debug(message: string, object?: any) {
private debug(message: string, object?: unknown) {
const objectString = object == null ? '' : JSON.stringify(object);
this.logger.debug(`esContext: ${message} ${objectString}`);
}
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/event_log/server/es/documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import mappings from '../../generated/mappings.json';

// returns the body of an index template used in an ES indices.putTemplate call
export function getIndexTemplate(esNames: EsNames) {
const indexTemplateBody: any = {
const indexTemplateBody = {
index_patterns: [esNames.indexPatternWithVersion],
settings: {
number_of_shards: 1,
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/event_log/server/event_logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,14 @@ function indexEventDoc(esContext: EsContext, doc: Doc): void {
}

// whew, the thing that actually writes the event log document!
async function indexLogEventDoc(esContext: EsContext, doc: any) {
async function indexLogEventDoc(esContext: EsContext, doc: unknown) {
esContext.logger.debug(`writing to event log: ${JSON.stringify(doc)}`);
await esContext.waitTillReady();
await esContext.esAdapter.indexDocument(doc);
esContext.logger.debug(`writing to event log complete`);
}

// TODO: write log entry to a bounded queue buffer
function writeLogEventDocOnError(esContext: EsContext, doc: any) {
function writeLogEventDocOnError(esContext: EsContext, doc: unknown) {
esContext.logger.warn(`unable to write event doc: ${JSON.stringify(doc)}`);
}
2 changes: 1 addition & 1 deletion x-pack/plugins/event_log/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export class Plugin implements CorePlugin<IEventLogService, IEventLogClientServi
}

private createRouteHandlerContext = (): IContextProvider<
RequestHandler<any, any, any>,
RequestHandler<unknown, unknown, unknown>,
'eventLog'
> => {
return async (context, request) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import { IEventLogClient } from '../types';

export function mockHandlerArguments(
eventLogClient: IEventLogClient,
req: any,
req: unknown,
res?: Array<MethodKeysOf<KibanaResponseFactory>>
): [RequestHandlerContext, KibanaRequest<any, any, any, any>, KibanaResponseFactory] {
): [RequestHandlerContext, KibanaRequest<unknown, unknown, unknown>, KibanaResponseFactory] {
return [
({
eventLog: {
Expand All @@ -22,7 +22,7 @@ export function mockHandlerArguments(
},
},
} as unknown) as RequestHandlerContext,
req as KibanaRequest<any, any, any, any>,
req as KibanaRequest<unknown, unknown, unknown>,
mockResponseFactory(res),
];
}
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/event_log/server/routes/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ export const findRoute = (router: IRouter) => {
},
router.handleLegacyErrors(async function(
context: RequestHandlerContext,
req: KibanaRequest<TypeOf<typeof paramSchema>, FindOptionsType, any, any>,
req: KibanaRequest<TypeOf<typeof paramSchema>, FindOptionsType, unknown>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
): Promise<IKibanaResponse> {
if (!context.eventLog) {
return res.badRequest({ body: 'RouteHandlerContext is not registered for eventLog' });
}
Expand Down

0 comments on commit 61d9018

Please sign in to comment.