Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[alerting] removes usage of any throughout Alerting Services code #64161

Merged
merged 18 commits into from
Apr 24, 2020
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,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
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 @@ -230,7 +230,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
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 @@ -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 @@ -43,13 +43,13 @@ export interface Content {
}

// send an email
export async function sendEmail(logger: Logger, options: SendEmailOptions): Promise<any> {
export async function sendEmail(logger: Logger, options: SendEmailOptions): Promise<unknown> {
const { transport, routing, content } = options;
const { service, host, port, secure, user, password } = transport;
const { from, to, cc, bcc } = routing;
const { subject, message } = content;

const transportConfig: Record<string, any> = {};
const transportConfig: Record<string, unknown> = {};

if (user != null && password != null) {
transportConfig.auth = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const postPagerdutyMock = postPagerduty as jest.Mock;
const ACTION_TYPE_ID = '.pagerduty';

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

Expand Down
21 changes: 16 additions & 5 deletions x-pack/plugins/actions/server/builtin_action_types/pagerduty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,8 @@ const ParamsSchema = schema.object(
{ validate: validateParams }
);

function validateParams(paramsObject: any): string | void {
const params: ActionParamsType = paramsObject;
const { timestamp } = params;
function validateParams(paramsObject: unknown): string | void {
const { timestamp } = paramsObject as ActionParamsType;
if (timestamp != null) {
try {
const date = Date.parse(timestamp);
Expand Down Expand Up @@ -218,11 +217,23 @@ async function executor(

const AcknowledgeOrResolve = new Set([EVENT_ACTION_ACKNOWLEDGE, EVENT_ACTION_RESOLVE]);

function getBodyForEventAction(actionId: string, params: ActionParamsType): any {
function getBodyForEventAction(actionId: string, params: ActionParamsType): unknown {
const eventAction = params.eventAction || EVENT_ACTION_TRIGGER;
const dedupKey = params.dedupKey || `action:${actionId}`;

const data: any = {
const data: {
event_action: ActionParamsType['eventAction'];
dedup_key: string;
payload?: {
summary: string;
source: string;
severity: string;
timestamp?: string;
component?: string;
group?: string;
class?: string;
};
} = {
Comment on lines +224 to +236
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not that this is a change strictly to typing, not actual object, so compile-time addition, not runtime.

event_action: eventAction,
dedup_key: dedupKey,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,14 @@ export const handleCreateIncident = async ({
comments &&
Array.isArray(comments) &&
comments.length > 0 &&
mapping.get('comments').actionType !== 'nothing'
mapping.get('comments')?.actionType !== 'nothing'
) {
comments = transformComments(comments, params, ['informationAdded']);
res.comments = [
...(await createComments(
serviceNow,
res.incidentId,
mapping.get('comments').target,
mapping.get('comments')!.target,
comments
)),
];
Expand Down Expand Up @@ -103,11 +103,11 @@ export const handleUpdateIncident = async ({
comments &&
Array.isArray(comments) &&
comments.length > 0 &&
mapping.get('comments').actionType !== 'nothing'
mapping.get('comments')?.actionType !== 'nothing'
) {
comments = transformComments(comments, params, ['informationAdded']);
res.comments = [
...(await createComments(serviceNow, incidentId, mapping.get('comments').target, comments)),
...(await createComments(serviceNow, incidentId, mapping.get('comments')!.target, comments)),
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const buildMap = (mapping: MapEntry[]): Mapping => {
}, new Map());
};

export const mapParams = (params: any, mapping: Mapping) => {
export const mapParams = (params: Record<string, unknown>, mapping: Mapping) => {
return Object.keys(params).reduce((prev: KeyAny, curr: string): KeyAny => {
const field = mapping.get(curr);
if (field) {
Expand All @@ -61,11 +61,11 @@ export const prepareFieldsForTransformation = ({
defaultPipes = ['informationCreated'],
}: PrepareFieldsForTransformArgs): PipedField[] => {
return Object.keys(params.incident)
.filter(p => mapping.get(p).actionType !== 'nothing')
.filter(p => mapping.get(p)!.actionType !== 'nothing')
.map(p => ({
key: p,
value: params.incident[p],
actionType: mapping.get(p).actionType,
value: params.incident[p] as string,
actionType: mapping.get(p)!.actionType,
pipes: [...defaultPipes],
}))
.map(p => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ async function serviceNowExecutor(
const { comments, incidentId, ...restParams } = params;

const mapping = buildMap(configurationMapping);
const incident = mapParams(restParams, mapping);
const incident = mapParams((restParams as unknown) as Record<string, unknown>, mapping);
const serviceNow = new ServiceNow({ url: apiUrl, username, password });

const handlerInput = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ class ServiceNow {
}: {
url: string;
method?: Method;
data?: any;
data?: unknown;
}): Promise<AxiosResponse> {
const res = await this.axios(url, { method, data });
this._throwIfNotAlive(res.status, res.headers['content-type']);
return res;
}

private _patch({ url, data }: { url: string; data: any }): Promise<AxiosResponse> {
private _patch({ url, data }: { url: string; data: unknown }): Promise<AxiosResponse> {
return this._request({
url,
method: 'patch',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ export type CasesConfigurationType = TypeOf<typeof CasesConfigurationSchema>;
export type MapEntry = TypeOf<typeof MapEntrySchema>;
export type Comment = TypeOf<typeof CommentSchema>;

export type Mapping = Map<string, any>;
export type Mapping = Map<string, Omit<MapEntry, 'source'>>;

export interface Params extends ExecutorParams {
incident: Record<string, any>;
incident: Record<string, unknown>;
}
export interface CreateHandlerArguments {
serviceNow: ServiceNow;
Expand Down Expand Up @@ -66,7 +66,7 @@ export interface AppendFieldArgs {
}

export interface KeyAny {
[index: string]: string;
[index: string]: unknown;
}

export interface AppendInformationFieldArgs {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ async function slackExecutor(
return successResult(actionId, result);
}

function successResult(actionId: string, data: any): ActionTypeExecutorResult {
function successResult(actionId: string, data: unknown): ActionTypeExecutorResult {
return { status: 'ok', data, actionId };
}

Expand Down
Loading