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

[event-hubs] fix eslint errors (round 1) #13013

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions sdk/eventhub/event-hubs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"description": "Azure Event Hubs SDK for JS.",
"author": "Microsoft Corporation",
"license": "MIT",
"homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventhub/event-hubs",
"homepage": "https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/eventhub/event-hubs/README.md",
"repository": "github:Azure/azure-sdk-for-js",
"sideEffects": false,
"keywords": [
Expand All @@ -31,7 +31,7 @@
"browser": {
"./dist-esm/src/util/runtimeInfo.js": "./dist-esm/src/util/runtimeInfo.browser.js"
},
"engine": {
"engines": {
"node": ">=8.0.0"
},
"files": [
Expand Down
33 changes: 15 additions & 18 deletions sdk/eventhub/event-hubs/src/connectionContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export interface ConnectionContextOptions extends EventHubClientOptions {
/**
* Helper type to get the names of all the functions on an object.
*/
type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T];
type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T]; // eslint-disable-line @typescript-eslint/ban-types
/**
* Helper type to get the types of all the functions on an object.
*/
Expand Down Expand Up @@ -387,43 +387,40 @@ export namespace ConnectionContext {
}
};

function addConnectionListeners(connection: Connection) {
function addConnectionListeners(connection: Connection): void {
// Add listeners on the connection object.
connection.on(ConnectionEvents.connectionOpen, onConnectionOpen);
connection.on(ConnectionEvents.disconnected, onDisconnected);
connection.on(ConnectionEvents.protocolError, protocolError);
connection.on(ConnectionEvents.error, error);
}

function cleanConnectionContext(connectionContext: ConnectionContext) {
function cleanConnectionContext(context: ConnectionContext): Promise<void> {
// Remove listeners from the connection object.
connectionContext.connection.removeListener(
ConnectionEvents.connectionOpen,
onConnectionOpen
);
connectionContext.connection.removeListener(ConnectionEvents.disconnected, onDisconnected);
connectionContext.connection.removeListener(ConnectionEvents.protocolError, protocolError);
connectionContext.connection.removeListener(ConnectionEvents.error, error);
context.connection.removeListener(ConnectionEvents.connectionOpen, onConnectionOpen);
context.connection.removeListener(ConnectionEvents.disconnected, onDisconnected);
context.connection.removeListener(ConnectionEvents.protocolError, protocolError);
context.connection.removeListener(ConnectionEvents.error, error);
// Close the connection
return connectionContext.connection.close();
return context.connection.close();
}

async function refreshConnection(connectionContext: ConnectionContext) {
const originalConnectionId = connectionContext.connectionId;
async function refreshConnection(context: ConnectionContext): Promise<void> {
const originalConnectionId = context.connectionId;
try {
await cleanConnectionContext(connectionContext);
await cleanConnectionContext(context);
} catch (err) {
logger.verbose(
`[${connectionContext.connectionId}] There was an error closing the connection before reconnecting: %O`,
`[${context.connectionId}] There was an error closing the connection before reconnecting: %O`,
err
);
}

// Create a new connection, id, locks, and cbs client.
connectionContext.refreshConnection();
addConnectionListeners(connectionContext.connection);
context.refreshConnection();
addConnectionListeners(context.connection);
logger.verbose(
`The connection "${originalConnectionId}" has been updated to "${connectionContext.connectionId}".`
`The connection "${originalConnectionId}" has been updated to "${context.connectionId}".`
);
}

Expand Down
4 changes: 3 additions & 1 deletion sdk/eventhub/event-hubs/src/dataTransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,15 @@ export const defaultDataTransformer = {
* - multiple: true | undefined.
*/
encode(body: any): any {
// eslint-disable-line @typescript-eslint/explicit-module-boundary-types
let result: any;
Copy link
Member

Choose a reason for hiding this comment

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

can we change any to unknown in the argument type throughout to fix the linting the issue? it could be a bit painful sometimes but it is safer to work with.

Copy link
Contributor

Choose a reason for hiding this comment

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

Another option is to refactor the if/else block to return early so that we don't need to have the result variable at all.

if (isBuffer(body) {
     return message.data_section(body);
}

try {
   const bodyStr = JSON.stringify(body);
   return message.data_section(Buffer.from(bodyStr, "utf8"));
} catch (err) {

}

Copy link
Member

@deyaaeldeen deyaaeldeen Jan 5, 2021

Choose a reason for hiding this comment

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

@ramya-rao-a sorry for the confusion by putting my comment on line 28 instead of line 26. I meant to do this change for arguments only (body in this case). This is where eslint complains.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed all of the @typescript-eslint/explicit-module-boundary-types overrides in #13285

if (isBuffer(body)) {
result = message.data_section(body);
} else {
// string, undefined, null, boolean, array, object, number should end up here
// coercing undefined to null as that will ensure that null value will be given to the
// customer on receive.
if (body === undefined) body = null; // tslint:disable-line
if (body === undefined) body = null;
try {
const bodyStr = JSON.stringify(body);
result = message.data_section(Buffer.from(bodyStr, "utf8"));
Expand All @@ -57,6 +58,7 @@ export const defaultDataTransformer = {
* @return {*} decoded body or the given body as-is.
*/
decode(body: any): any {
// eslint-disable-line @typescript-eslint/explicit-module-boundary-types
let processedBody: any = body;
Copy link
Member

Choose a reason for hiding this comment

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

👀

try {
if (body.content && isBuffer(body.content)) {
Expand Down
3 changes: 2 additions & 1 deletion sdk/eventhub/event-hubs/src/eventData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import { DeliveryAnnotations, Message as RheaMessage, MessageAnnotations } from "rhea-promise";
import { Constants } from "@azure/core-amqp";
import { isDefined } from "./util/isDefined";

/**
* Describes the delivery annotations.
Expand Down Expand Up @@ -203,7 +204,7 @@ export function toRheaMessage(data: EventData, partitionKey?: string): RheaMessa
if (data.properties) {
msg.application_properties = data.properties;
}
if (partitionKey != undefined) {
if (isDefined(partitionKey)) {
msg.message_annotations[Constants.partitionKey] = partitionKey;
// Event Hub service cannot route messages to a specific partition based on the partition key
// if AMQP message header is an empty object. Hence we make sure that header is always present
Expand Down
6 changes: 4 additions & 2 deletions sdk/eventhub/event-hubs/src/eventDataBatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Span, SpanContext } from "@opentelemetry/api";
import { TRACEPARENT_PROPERTY, instrumentEventData } from "./diagnostics/instrumentEventData";
import { createMessageSpan } from "./diagnostics/messageSpan";
import { defaultDataTransformer } from "./dataTransformer";
import { isDefined } from "./util/isDefined";

/**
* The amount of bytes to reserve as overhead for a small message.
Expand All @@ -30,6 +31,7 @@ const smallMessageMaxBytes = 255;
* @ignore
*/
export function isEventDataBatch(eventDataBatch: any): eventDataBatch is EventDataBatch {
// eslint-disable-line @typescript-eslint/explicit-module-boundary-types
return (
Copy link
Member

Choose a reason for hiding this comment

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

👀

eventDataBatch &&
typeof eventDataBatch.tryAdd === "function" &&
Expand Down Expand Up @@ -192,8 +194,8 @@ export class EventDataBatchImpl implements EventDataBatch {
) {
this._context = context;
this._maxSizeInBytes = maxSizeInBytes;
this._partitionKey = partitionKey != undefined ? String(partitionKey) : partitionKey;
this._partitionId = partitionId != undefined ? String(partitionId) : partitionId;
this._partitionKey = isDefined(partitionKey) ? String(partitionKey) : partitionKey;
this._partitionId = isDefined(partitionId) ? String(partitionId) : partitionId;
this._sizeInBytes = 0;
this._count = 0;
}
Expand Down
9 changes: 5 additions & 4 deletions sdk/eventhub/event-hubs/src/eventHubProducerClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
SendBatchOptions
} from "./models/public";
import { throwErrorIfConnectionClosed, throwTypeErrorIfParameterMissing } from "./util/error";
import { isDefined } from "./util/isDefined";
import { getParentSpan, OperationOptions } from "./util/operationOptions";

/**
Expand Down Expand Up @@ -174,7 +175,7 @@ export class EventHubProducerClient {
async createBatch(options: CreateBatchOptions = {}): Promise<EventDataBatch> {
throwErrorIfConnectionClosed(this._context);

if (options.partitionId != undefined && options.partitionKey != undefined) {
if (isDefined(options.partitionId) && isDefined(options.partitionKey)) {
throw new Error("partitionId and partitionKey cannot both be set when creating a batch");
}

Expand Down Expand Up @@ -316,16 +317,16 @@ export class EventHubProducerClient {
}
}
}
if (partitionId != undefined && partitionKey != undefined) {
if (isDefined(partitionId) && isDefined(partitionKey)) {
throw new Error(
`The partitionId (${partitionId}) and partitionKey (${partitionKey}) cannot both be specified.`
);
}

if (partitionId != undefined) {
if (isDefined(partitionId)) {
partitionId = String(partitionId);
}
if (partitionKey != undefined) {
if (isDefined(partitionKey)) {
partitionKey = String(partitionKey);
}

Expand Down
10 changes: 7 additions & 3 deletions sdk/eventhub/event-hubs/src/eventHubReceiver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,10 @@ export class EventHubReceiver extends LinkEntity {
await this.abort();
}
} catch (err) {
return this._onError === onError && onError(err);
if (this._onError === onError) {
onError(err);
}
return;
}
} else {
logger.verbose(
Expand All @@ -478,6 +481,7 @@ export class EventHubReceiver extends LinkEntity {
0
);
this._addCredit(creditsToAdd);
return;
})
.catch((err) => {
// something really unexpected happened, so attempt to call user's error handler
Expand Down Expand Up @@ -700,13 +704,13 @@ export class EventHubReceiver extends LinkEntity {
try {
await this.close();
} finally {
return reject(new AbortError("The receive operation has been cancelled by the user."));
reject(new AbortError("The receive operation has been cancelled by the user."));
richardpark-msft marked this conversation as resolved.
Show resolved Hide resolved
}
};

// operation has been cancelled, so exit immediately
if (abortSignal && abortSignal.aborted) {
return await rejectOnAbort();
return rejectOnAbort();
}

// updates the prefetch count so that the baseConsumer adds
Expand Down
52 changes: 26 additions & 26 deletions sdk/eventhub/event-hubs/src/eventHubSender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ export class EventHubSender extends LinkEntity {
this.address = context.config.getSenderAddress(partitionId);
this.audience = context.config.getSenderAudience(partitionId);

this._onAmqpError = (context: EventContext) => {
const senderError = context.sender && context.sender.error;
this._onAmqpError = (eventContext: EventContext) => {
const senderError = eventContext.sender && eventContext.sender.error;
logger.verbose(
"[%s] 'sender_error' event occurred on the sender '%s' with address '%s'. " +
"The associated error is: %O",
Expand All @@ -102,8 +102,8 @@ export class EventHubSender extends LinkEntity {
// TODO: Consider rejecting promise in trySendBatch() or createBatch()
};

this._onSessionError = (context: EventContext) => {
const sessionError = context.session && context.session.error;
this._onSessionError = (eventContext: EventContext) => {
const sessionError = eventContext.session && eventContext.session.error;
logger.verbose(
"[%s] 'session_error' event occurred on the session of sender '%s' with address '%s'. " +
"The associated error is: %O",
Expand All @@ -115,8 +115,8 @@ export class EventHubSender extends LinkEntity {
// TODO: Consider rejecting promise in trySendBatch() or createBatch()
};

this._onAmqpClose = async (context: EventContext) => {
const sender = this._sender || context.sender!;
this._onAmqpClose = async (eventContext: EventContext) => {
const sender = this._sender || eventContext.sender!;
logger.verbose(
"[%s] 'sender_close' event occurred on the sender '%s' with address '%s'. " +
"Value for isItselfClosed on the receiver is: '%s' " +
Expand All @@ -140,8 +140,8 @@ export class EventHubSender extends LinkEntity {
}
};

this._onSessionClose = async (context: EventContext) => {
const sender = this._sender || context.sender!;
this._onSessionClose = async (eventContext: EventContext) => {
const sender = this._sender || eventContext.sender!;
logger.verbose(
"[%s] 'session_close' event occurred on the session of sender '%s' with address '%s'. " +
"Value for isSessionItselfClosed on the session is: '%s' " +
Expand Down Expand Up @@ -322,9 +322,9 @@ export class EventHubSender extends LinkEntity {
const messages: RheaMessage[] = [];
// Convert EventData to RheaMessage.
for (let i = 0; i < events.length; i++) {
const message = toRheaMessage(events[i], partitionKey);
message.body = defaultDataTransformer.encode(events[i].body);
messages[i] = message;
const rheaMessage = toRheaMessage(events[i], partitionKey);
rheaMessage.body = defaultDataTransformer.encode(events[i].body);
messages[i] = rheaMessage;
}
// Encode every amqp message and then convert every encoded message to amqp data section
const batchMessage: RheaMessage = {
Expand Down Expand Up @@ -391,11 +391,11 @@ export class EventHubSender extends LinkEntity {
* We have implemented a synchronous send over here in the sense that we shall be waiting
* for the message to be accepted or rejected and accordingly resolve or reject the promise.
* @ignore
* @param message The message to be sent to EventHub.
* @param rheaMessage The message to be sent to EventHub.
* @returns Promise<void>
*/
private _trySendBatch(
message: RheaMessage | Buffer,
rheaMessage: RheaMessage | Buffer,
options: SendOptions & EventHubProducerOptions = {}
): Promise<void> {
const abortSignal: AbortSignalLike | undefined = options.abortSignal;
Expand Down Expand Up @@ -464,15 +464,15 @@ export class EventHubSender extends LinkEntity {
});
} catch (err) {
removeListeners();
err = translate(err);
const translatedError = translate(err);
logger.warning(
"[%s] An error occurred while creating the sender %s: %s",
this._context.connectionId,
this.name,
`${err?.name}: ${err?.message}`
`${translatedError?.name}: ${translatedError?.message}`
);
logErrorStackTrace(err);
return reject(err);
logErrorStackTrace(translatedError);
return reject(translatedError);
}
}
const timeTakenByInit = Date.now() - initStartTime;
Expand All @@ -496,7 +496,7 @@ export class EventHubSender extends LinkEntity {
}
try {
this._sender!.sendTimeoutInSeconds = (timeoutInMs - timeTakenByInit) / 1000;
const delivery = await this._sender!.send(message, undefined, 0x80013700);
const delivery = await this._sender!.send(rheaMessage, undefined, 0x80013700);
logger.info(
"[%s] Sender '%s', sent message with delivery id: %d",
this._context.connectionId,
Expand All @@ -505,14 +505,14 @@ export class EventHubSender extends LinkEntity {
);
return resolve();
} catch (err) {
err = translate(err.innerError || err);
const translatedError = translate(err.innerError || err);
logger.warning(
"[%s] An error occurred while sending the message %s",
this._context.connectionId,
`${err?.name}: ${err?.message}`
`${translatedError?.name}: ${translatedError?.message}`
);
logErrorStackTrace(err);
return reject(err);
logErrorStackTrace(translatedError);
return reject(translatedError);
} finally {
removeListeners();
}
Expand Down Expand Up @@ -586,15 +586,15 @@ export class EventHubSender extends LinkEntity {
}
} catch (err) {
this.isConnecting = false;
err = translate(err);
const translatedError = translate(err);
logger.warning(
"[%s] An error occurred while creating the sender %s: %s",
this._context.connectionId,
this.name,
`${err?.name}: ${err?.message}`
`${translatedError?.name}: ${translatedError?.message}`
);
logErrorStackTrace(err);
throw err;
logErrorStackTrace(translatedError);
throw translatedError;
}
}

Expand Down
Loading