Skip to content

Commit

Permalink
[alerting] removes usage of any throughout Alerting Services code (#6…
Browse files Browse the repository at this point in the history
…4161)

This removes unneeded use of `any` throughout:
1. alerting
2. alerting_builtin
3. actions
4. task manager
5. event log

It also adds a linting rule that will prevent us from adding more `any` in the future unless an explicit exemption is made.
  • Loading branch information
gmmorris authored Apr 24, 2020
1 parent 4051c94 commit a012ddf
Show file tree
Hide file tree
Showing 131 changed files with 839 additions and 541 deletions.
13 changes: 13 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,19 @@ module.exports = {
},
},

/**
* Alerting Services overrides
*/
{
// typescript only for front and back end
files: [
'x-pack/{,legacy/}plugins/{alerting,alerting_builtins,actions,task_manager,event_log}/**/*.{ts,tsx}',
],
rules: {
'@typescript-eslint/no-explicit-any': 'error',
},
},

/**
* Lens overrides
*/
Expand Down
9 changes: 7 additions & 2 deletions x-pack/legacy/plugins/actions/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@
import { Root } from 'joi';
import { Legacy } from 'kibana';
import mappings from './mappings.json';
import {
LegacyPluginApi,
LegacyPluginSpec,
ArrayOrItem,
} from '../../../../../src/legacy/plugin_discovery/types';

export function actions(kibana: any) {
export function actions(kibana: LegacyPluginApi): ArrayOrItem<LegacyPluginSpec> {
return new kibana.Plugin({
id: 'actions',
configPrefix: 'xpack.actions',
Expand All @@ -29,5 +34,5 @@ export function actions(kibana: any) {
uiExports: {
mappings,
},
});
} as Legacy.PluginSpecOptions);
}
9 changes: 7 additions & 2 deletions x-pack/legacy/plugins/alerting/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@
import { Legacy } from 'kibana';
import { Root } from 'joi';
import mappings from './mappings.json';
import {
LegacyPluginApi,
LegacyPluginSpec,
ArrayOrItem,
} from '../../../../../src/legacy/plugin_discovery/types';

export function alerting(kibana: any) {
export function alerting(kibana: LegacyPluginApi): ArrayOrItem<LegacyPluginSpec> {
return new kibana.Plugin({
id: 'alerting',
configPrefix: 'xpack.alerting',
Expand All @@ -31,5 +36,5 @@ export function alerting(kibana: any) {
uiExports: {
mappings,
},
});
} as Legacy.PluginSpecOptions);
}
17 changes: 14 additions & 3 deletions x-pack/legacy/plugins/task_manager/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,26 @@ export { LegacyTaskManagerApi, getTaskManagerSetup, getTaskManagerStart } from '
// Once all plugins are migrated to NP, this can be removed
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { TaskManager } from '../../../../plugins/task_manager/server/task_manager';
import {
LegacyPluginApi,
LegacyPluginSpec,
ArrayOrItem,
} from '../../../../../src/legacy/plugin_discovery/types';

const savedObjectSchemas = {
task: {
hidden: true,
isNamespaceAgnostic: true,
convertToAliasScript: `ctx._id = ctx._source.type + ':' + ctx._id`,
// legacy config is marked as any in core, no choice here
// eslint-disable-next-line @typescript-eslint/no-explicit-any
indexPattern(config: any) {
return config.get('xpack.task_manager.index');
},
},
};

export function taskManager(kibana: any) {
export function taskManager(kibana: LegacyPluginApi): ArrayOrItem<LegacyPluginSpec> {
return new kibana.Plugin({
id: 'task_manager',
require: ['kibana', 'elasticsearch', 'xpack_main'],
Expand Down Expand Up @@ -58,7 +65,11 @@ export function taskManager(kibana: any) {
// instead we will start the internal Task Manager plugin when
// all legacy plugins have finished initializing
// Once all plugins are migrated to NP, this can be removed
this.kbnServer.afterPluginsInit(() => {

// the typing for the lagcy server isn't quite correct, so
// we'll bypase it for now
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(this as any).kbnServer.afterPluginsInit(() => {
taskManagerPlugin.start();
});
return taskManagerPlugin;
Expand All @@ -71,5 +82,5 @@ export function taskManager(kibana: any) {
migrations,
savedObjectSchemas,
},
});
} as Legacy.PluginSpecOptions);
}
4 changes: 2 additions & 2 deletions x-pack/legacy/plugins/task_manager/server/legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ export function createLegacyApi(legacyTaskManager: Promise<TaskManager>): Legacy
fetch: (opts: SearchOpts) => legacyTaskManager.then((tm: TaskManager) => tm.fetch(opts)),
get: (id: string) => legacyTaskManager.then((tm: TaskManager) => tm.get(id)),
remove: (id: string) => legacyTaskManager.then((tm: TaskManager) => tm.remove(id)),
schedule: (taskInstance: TaskInstanceWithDeprecatedFields, options?: any) =>
schedule: (taskInstance: TaskInstanceWithDeprecatedFields, options?: object) =>
legacyTaskManager.then((tm: TaskManager) => tm.schedule(taskInstance, options)),
runNow: (taskId: string) => legacyTaskManager.then((tm: TaskManager) => tm.runNow(taskId)),
ensureScheduled: (taskInstance: TaskInstanceWithId, options?: any) =>
ensureScheduled: (taskInstance: TaskInstanceWithId, options?: object) =>
legacyTaskManager.then((tm: TaskManager) => tm.ensureScheduled(taskInstance, options)),
};
}
4 changes: 2 additions & 2 deletions x-pack/legacy/plugins/task_manager/server/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { SavedObject } from '../../../../../src/core/server';

export const migrations = {
task: {
'7.4.0': (doc: SavedObject<Record<any, any>>) => ({
'7.4.0': (doc: SavedObject<Record<string, unknown>>) => ({
...doc,
updated_at: new Date().toISOString(),
}),
Expand All @@ -18,7 +18,7 @@ export const migrations = {
function moveIntervalIntoSchedule({
attributes: { interval, ...attributes },
...doc
}: SavedObject<Record<any, any>>) {
}: SavedObject<Record<string, unknown>>) {
return {
...doc,
attributes: {
Expand Down
2 changes: 2 additions & 0 deletions x-pack/plugins/actions/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export interface ActionResult {
id: string;
actionTypeId: string;
name: string;
// This will have to remain `any` until we can extend Action Executors with generics
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: Record<string, any>;
isPreconfigured: boolean;
}
2 changes: 1 addition & 1 deletion x-pack/plugins/actions/server/action_type_registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export class ActionTypeRegistry {
title: actionType.name,
type: `actions:${actionType.id}`,
maxAttempts: actionType.maxAttempts || 1,
getRetry(attempts: number, error: any) {
getRetry(attempts: number, error: unknown) {
if (error instanceof ExecutorError) {
return error.retry == null ? false : error.retry;
}
Expand Down
7 changes: 5 additions & 2 deletions x-pack/plugins/actions/server/actions_client.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
import { ActionsClient } from './actions_client';

type ActionsClientContract = PublicMethodsOf<ActionsClient>;
export type ActionsClientMock = jest.Mocked<ActionsClientContract>;

const createActionsClientMock = () => {
const mocked: jest.Mocked<ActionsClientContract> = {
const mocked: ActionsClientMock = {
create: jest.fn(),
get: jest.fn(),
delete: jest.fn(),
Expand All @@ -19,6 +20,8 @@ const createActionsClientMock = () => {
return mocked;
};

export const actionsClientMock = {
export const actionsClientMock: {
create: () => ActionsClientMock;
} = {
create: createActionsClientMock,
};
4 changes: 2 additions & 2 deletions x-pack/plugins/actions/server/actions_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export class ActionsClient {
id,
actionTypeId: result.attributes.actionTypeId as string,
name: result.attributes.name as string,
config: result.attributes.config as Record<string, any>,
config: result.attributes.config as Record<string, unknown>,
isPreconfigured: false,
};
}
Expand Down Expand Up @@ -228,7 +228,7 @@ async function injectExtraFindData(
scopedClusterClient: IScopedClusterClient,
actionResults: ActionResult[]
): Promise<FindActionResult[]> {
const aggs: Record<string, any> = {};
const aggs: Record<string, unknown> = {};
for (const actionResult of actionResults) {
aggs[actionResult.id] = {
filter: {
Expand Down
12 changes: 6 additions & 6 deletions x-pack/plugins/actions/server/builtin_action_types/email.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const NO_OP_FN = () => {};

const services = {
log: NO_OP_FN,
callCluster: async (path: string, opts: any) => {},
callCluster: async (path: string, opts: unknown) => {},
savedObjectsClient: savedObjectsClientMock.create(),
};

Expand All @@ -52,7 +52,7 @@ describe('actionTypeRegistry.get() works', () => {

describe('config validation', () => {
test('config validation succeeds when config is valid', () => {
const config: Record<string, any> = {
const config: Record<string, unknown> = {
service: 'gmail',
from: 'bob@example.com',
};
Expand All @@ -74,7 +74,7 @@ describe('config validation', () => {
});

test('config validation fails when config is not valid', () => {
const baseConfig: Record<string, any> = {
const baseConfig: Record<string, unknown> = {
from: 'bob@example.com',
};

Expand Down Expand Up @@ -177,15 +177,15 @@ describe('config validation', () => {

describe('secrets validation', () => {
test('secrets validation succeeds when secrets is valid', () => {
const secrets: Record<string, any> = {
const secrets: Record<string, unknown> = {
user: 'bob',
password: 'supersecret',
};
expect(validateSecrets(actionType, secrets)).toEqual(secrets);
});

test('secrets validation succeeds when secrets props are null/undefined', () => {
const secrets: Record<string, any> = {
const secrets: Record<string, unknown> = {
user: null,
password: null,
};
Expand All @@ -197,7 +197,7 @@ describe('secrets validation', () => {

describe('params validation', () => {
test('params validation succeeds when params is valid', () => {
const params: Record<string, any> = {
const params: Record<string, unknown> = {
to: ['bob@example.com'],
subject: 'this is a test',
message: 'this is the message',
Expand Down
8 changes: 4 additions & 4 deletions x-pack/plugins/actions/server/builtin_action_types/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ const ConfigSchema = schema.object(ConfigSchemaProps);

function validateConfig(
configurationUtilities: ActionsConfigurationUtilities,
configObject: any
configObject: unknown
): string | void {
// avoids circular reference ...
const config: ActionTypeConfigType = configObject;
const config = configObject as ActionTypeConfigType;

// Make sure service is set, or if not, both host/port must be set.
// If service is set, host/port are ignored, when the email is sent.
Expand Down Expand Up @@ -95,9 +95,9 @@ const ParamsSchema = schema.object(
}
);

function validateParams(paramsObject: any): string | void {
function validateParams(paramsObject: unknown): string | void {
// avoids circular reference ...
const params: ActionParamsType = paramsObject;
const params = paramsObject as ActionParamsType;

const { to, cc, bcc } = params;
const addrs = to.length + cc.length + bcc.length;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ describe('actionTypeRegistry.get() works', () => {

describe('config validation', () => {
test('config validation succeeds when config is valid', () => {
const config: Record<string, any> = {
const config: Record<string, unknown> = {
index: 'testing-123',
refresh: false,
};
Expand Down Expand Up @@ -97,7 +97,7 @@ describe('config validation', () => {
});

test('config validation fails when config is not valid', () => {
const baseConfig: Record<string, any> = {
const baseConfig: Record<string, unknown> = {
indeX: 'bob',
};

Expand All @@ -111,7 +111,7 @@ describe('config validation', () => {

describe('params validation', () => {
test('params validation succeeds when params is valid', () => {
const params: Record<string, any> = {
const params: Record<string, unknown> = {
documents: [{ rando: 'thing' }],
};
expect(validateParams(actionType, params)).toMatchInlineSnapshot(`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,12 @@ async function executor(
bulkBody.push(document);
}

const bulkParams: any = {
const bulkParams: unknown = {
index,
body: bulkBody,
refresh: config.refresh,
};

bulkParams.refresh = config.refresh;

let result;
try {
result = await services.callCluster('bulk', bulkParams);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Services } from '../../types';

interface PostPagerdutyOptions {
apiUrl: string;
data: any;
data: unknown;
headers: Record<string, string>;
services: Services;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,15 @@ describe('send_email module', () => {
});

test('handles unauthenticated email using not secure host/port', async () => {
const sendEmailOptions = getSendEmailOptions();
const sendEmailOptions = getSendEmailOptions({
transport: {
host: 'example.com',
port: 1025,
},
});
delete sendEmailOptions.transport.service;
delete sendEmailOptions.transport.user;
delete sendEmailOptions.transport.password;
sendEmailOptions.transport.host = 'example.com';
sendEmailOptions.transport.port = 1025;
const result = await sendEmail(mockLogger, sendEmailOptions);
expect(result).toBe(sendMailMockResult);
expect(createTransportMock.mock.calls[0]).toMatchInlineSnapshot(`
Expand Down Expand Up @@ -105,13 +108,17 @@ describe('send_email module', () => {
});

test('handles unauthenticated email using secure host/port', async () => {
const sendEmailOptions = getSendEmailOptions();
const sendEmailOptions = getSendEmailOptions({
transport: {
host: 'example.com',
port: 1025,
secure: true,
},
});
delete sendEmailOptions.transport.service;
delete sendEmailOptions.transport.user;
delete sendEmailOptions.transport.password;
sendEmailOptions.transport.host = 'example.com';
sendEmailOptions.transport.port = 1025;
sendEmailOptions.transport.secure = true;

const result = await sendEmail(mockLogger, sendEmailOptions);
expect(result).toBe(sendMailMockResult);
expect(createTransportMock.mock.calls[0]).toMatchInlineSnapshot(`
Expand Down Expand Up @@ -154,19 +161,22 @@ describe('send_email module', () => {
});
});

function getSendEmailOptions(): any {
function getSendEmailOptions({ content = {}, routing = {}, transport = {} } = {}) {
return {
content: {
...content,
message: 'a message',
subject: 'a subject',
},
routing: {
...routing,
from: 'fred@example.com',
to: ['jim@example.com'],
cc: ['bob@example.com', 'robert@example.com'],
bcc: [],
},
transport: {
...transport,
service: 'whatever',
user: 'elastic',
password: 'changeme',
Expand Down
Loading

0 comments on commit a012ddf

Please sign in to comment.