[go: up one dir, main page]

Skip to content

Commit

Permalink
Merge pull request #1345 from Patrick-Remy/patch/grpc-js-linting
Browse files Browse the repository at this point in the history
grpc-js fix linting
  • Loading branch information
murgatroid99 authored Apr 13, 2020
2 parents 7eca188 + e7b25e3 commit 4ec023c
Show file tree
Hide file tree
Showing 31 changed files with 523 additions and 374 deletions.
10 changes: 10 additions & 0 deletions packages/grpc-js/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"root": true,
"extends": "./node_modules/gts",
"rules": {
"node/no-unpublished-import": ["error", {
"tryExtensions": [".ts", ".js", ".json", ".node"]
}],
"@typescript-eslint/no-unused-vars": "off"
}
}
8 changes: 4 additions & 4 deletions packages/grpc-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"@types/semver": "^6.0.1",
"clang-format": "^1.0.55",
"execa": "^2.0.3",
"gts": "^1.1.0",
"gts": "^2.0.0",
"gulp": "^4.0.2",
"gulp-mocha": "^6.0.0",
"lodash": "^4.17.4",
Expand All @@ -46,11 +46,11 @@
"clean": "gts clean",
"compile": "tsc -p .",
"format": "clang-format -i -style=\"{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}\" src/*.ts test/*.ts",
"lint": "tslint -c node_modules/google-ts-style/tslint.json -p . -t codeFrame --type-check",
"lint": "npm run check",
"prepare": "npm run compile",
"test": "gulp test",
"check": "gts check",
"fix": "gts fix",
"check": "gts check src/**/*.ts",
"fix": "gts fix src/**/*.ts",
"pretest": "npm run compile",
"posttest": "npm run check"
},
Expand Down
1 change: 0 additions & 1 deletion packages/grpc-js/src/call-credentials-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
*
*/

import { CallCredentials } from './call-credentials';
import { Call } from './call-stream';
import { Channel } from './channel';
import { BaseFilter, Filter, FilterFactory } from './filter';
Expand Down
3 changes: 1 addition & 2 deletions packages/grpc-js/src/call-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
*/

import { Metadata } from './metadata';
import { Call } from '.';

export interface CallMetadataOptions {
service_url: string;
Expand Down Expand Up @@ -79,7 +78,7 @@ class ComposedCallCredentials extends CallCredentials {
async generateMetadata(options: CallMetadataOptions): Promise<Metadata> {
const base: Metadata = new Metadata();
const generated: Metadata[] = await Promise.all(
this.creds.map(cred => cred.generateMetadata(options))
this.creds.map((cred) => cred.generateMetadata(options))
);
for (const gen of generated) {
base.merge(gen);
Expand Down
35 changes: 22 additions & 13 deletions packages/grpc-js/src/call-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export interface MetadataListener {
}

export interface MessageListener {
// tslint:disable-next-line no-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(message: any, next: (message: any) => void): void;
}

Expand All @@ -90,7 +90,7 @@ export type Listener = Partial<FullListener>;
*/
export interface InterceptingListener {
onReceiveMetadata(metadata: Metadata): void;
// tslint:disable-next-line no-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onReceiveMessage(message: any): void;
onReceiveStatus(status: StatusObject): void;
}
Expand All @@ -113,16 +113,16 @@ export class InterceptingListenerImpl implements InterceptingListener {
) {}

onReceiveMetadata(metadata: Metadata): void {
this.listener.onReceiveMetadata(metadata, metadata => {
this.listener.onReceiveMetadata(metadata, (metadata) => {
this.nextListener.onReceiveMetadata(metadata);
});
}
// tslint:disable-next-line no-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onReceiveMessage(message: any): void {
/* If this listener processes messages asynchronously, the last message may
* be reordered with respect to the status */
this.processingMessage = true;
this.listener.onReceiveMessage(message, msg => {
this.listener.onReceiveMessage(message, (msg) => {
this.processingMessage = false;
this.nextListener.onReceiveMessage(msg);
if (this.pendingStatus) {
Expand All @@ -131,7 +131,7 @@ export class InterceptingListenerImpl implements InterceptingListener {
});
}
onReceiveStatus(status: StatusObject): void {
this.listener.onReceiveStatus(status, processedStatus => {
this.listener.onReceiveStatus(status, (processedStatus) => {
if (this.processingMessage) {
this.pendingStatus = processedStatus;
} else {
Expand Down Expand Up @@ -224,7 +224,9 @@ export class Http2CallStream implements Call {
/* Precondition: this.finalStatus !== null */
if (!this.statusOutput) {
this.statusOutput = true;
const filteredStatus = this.filterStack.receiveTrailers(this.finalStatus!);
const filteredStatus = this.filterStack.receiveTrailers(
this.finalStatus!
);
this.listener!.onReceiveStatus(filteredStatus);
if (this.subchannel) {
this.subchannel.callUnref();
Expand Down Expand Up @@ -355,7 +357,7 @@ export class Http2CallStream implements Call {
private handleTrailers(headers: http2.IncomingHttpHeaders) {
let headersString = '';
for (const header of Object.keys(headers)) {
headersString += '\t\t' + header + ': ' + headers[header] + '\n'
headersString += '\t\t' + header + ': ' + headers[header] + '\n';
}
this.trace('Received server trailers:\n' + headersString);
let metadata: Metadata;
Expand All @@ -366,7 +368,10 @@ export class Http2CallStream implements Call {
}
const metadataMap = metadata.getMap();
let code: Status = this.mappedStatusCode;
if (code === Status.UNKNOWN && typeof metadataMap['grpc-status'] === 'string') {
if (
code === Status.UNKNOWN &&
typeof metadataMap['grpc-status'] === 'string'
) {
const receivedStatus = Number(metadataMap['grpc-status']);
if (receivedStatus in Status) {
code = receivedStatus;
Expand All @@ -378,7 +383,9 @@ export class Http2CallStream implements Call {
if (typeof metadataMap['grpc-message'] === 'string') {
details = decodeURI(metadataMap['grpc-message']);
metadata.remove('grpc-message');
this.trace('received status details string "' + details + '" from server');
this.trace(
'received status details string "' + details + '" from server'
);
}
const status: StatusObject = { code, details, metadata };
let finalStatus;
Expand Down Expand Up @@ -415,7 +422,7 @@ export class Http2CallStream implements Call {
stream.on('response', (headers, flags) => {
let headersString = '';
for (const header of Object.keys(headers)) {
headersString += '\t\t' + header + ': ' + headers[header] + '\n'
headersString += '\t\t' + header + ': ' + headers[header] + '\n';
}
this.trace('Received server headers:\n' + headersString);
switch (headers[':status']) {
Expand Down Expand Up @@ -578,7 +585,9 @@ export class Http2CallStream implements Call {
}

cancelWithStatus(status: Status, details: string): void {
this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"');
this.trace(
'cancelWithStatus code: ' + status + ' details: "' + details + '"'
);
this.destroyHttp2Stream();
this.endCall({ code: status, details, metadata: new Metadata() });
}
Expand Down Expand Up @@ -653,7 +662,7 @@ export class Http2CallStream implements Call {
};
const cb: WriteCallback = context.callback ?? (() => {});
this.isWriteFilterPending = true;
this.filterStack.sendMessage(Promise.resolve(writeObj)).then(message => {
this.filterStack.sendMessage(Promise.resolve(writeObj)).then((message) => {
this.isWriteFilterPending = false;
if (this.http2Stream === null) {
this.trace(
Expand Down
12 changes: 4 additions & 8 deletions packages/grpc-js/src/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,7 @@ export class ClientUnaryCallImpl extends EventEmitter
export class ClientReadableStreamImpl<ResponseType> extends Readable
implements ClientReadableStream<ResponseType> {
public call?: InterceptingCallInterface;
constructor(
readonly deserialize: (chunk: Buffer) => ResponseType
) {
constructor(readonly deserialize: (chunk: Buffer) => ResponseType) {
super({ objectMode: true });
}

Expand All @@ -122,9 +120,7 @@ export class ClientReadableStreamImpl<ResponseType> extends Readable
export class ClientWritableStreamImpl<RequestType> extends Writable
implements ClientWritableStream<RequestType> {
public call?: InterceptingCallInterface;
constructor(
readonly serialize: (value: RequestType) => Buffer
) {
constructor(readonly serialize: (value: RequestType) => Buffer) {
super({ objectMode: true });
}

Expand All @@ -140,7 +136,7 @@ export class ClientWritableStreamImpl<RequestType> extends Writable
const context: MessageContext = {
callback: cb,
};
const flags: number = Number(encoding);
const flags = Number(encoding);
if (!Number.isNaN(flags)) {
context.flags = flags;
}
Expand Down Expand Up @@ -179,7 +175,7 @@ export class ClientDuplexStreamImpl<RequestType, ResponseType> extends Duplex
const context: MessageContext = {
callback: cb,
};
const flags: number = Number(encoding);
const flags = Number(encoding);
if (!Number.isNaN(flags)) {
context.flags = flags;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/grpc-js/src/channel-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { ConnectionOptions, createSecureContext, PeerCertificate } from 'tls';
import { CallCredentials } from './call-credentials';
import { CIPHER_SUITES, getDefaultRootsData } from './tls-helpers';

// tslint:disable-next-line:no-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function verifyIsBufferOrNull(obj: any, friendlyName: string): void {
if (obj && !(obj instanceof Buffer)) {
throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`);
Expand Down
81 changes: 50 additions & 31 deletions packages/grpc-js/src/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ import { CallCredentialsFilterFactory } from './call-credentials-filter';
import { DeadlineFilterFactory } from './deadline-filter';
import { CompressionFilterFactory } from './compression-filter';
import { getDefaultAuthority } from './resolver';
import { LoadBalancingConfig } from './load-balancing-config';
import { ServiceConfig, validateServiceConfig } from './service-config';
import { trace, log } from './logging';
import { SubchannelAddress } from './subchannel';
Expand Down Expand Up @@ -112,7 +111,7 @@ export interface Channel {
method: string,
deadline: Deadline,
host: string | null | undefined,
parentCall: any,
parentCall: any, // eslint-disable-line @typescript-eslint/no-explicit-any
propagateFlags: number | null | undefined
): Call;
}
Expand Down Expand Up @@ -144,11 +143,23 @@ export class ChannelImplementation implements Channel {
throw new TypeError('Channel target must be a string');
}
if (!(credentials instanceof ChannelCredentials)) {
throw new TypeError('Channel credentials must be a ChannelCredentials object');
throw new TypeError(
'Channel credentials must be a ChannelCredentials object'
);
}
if (options) {
if ((typeof options !== 'object') || !Object.values(options).every(value => typeof value === 'string' || typeof value === 'number' || typeof value === 'undefined')) {
throw new TypeError('Channel options must be an object with string or number values');
if (
typeof options !== 'object' ||
!Object.values(options).every(
(value) =>
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'undefined'
)
) {
throw new TypeError(
'Channel options must be an object with string or number values'
);
}
}
/* The global boolean parameter to getSubchannelPool has the inverse meaning to what
Expand Down Expand Up @@ -265,7 +276,7 @@ export class ChannelImplementation implements Channel {
callStream.filterStack
.sendMetadata(Promise.resolve(callMetadata.clone()))
.then(
finalMetadata => {
(finalMetadata) => {
const subchannelState: ConnectivityState = pickResult.subchannel!.getConnectivityState();
if (subchannelState === ConnectivityState.READY) {
try {
Expand All @@ -274,41 +285,47 @@ export class ChannelImplementation implements Channel {
callStream
);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ERR_HTTP2_GOAWAY_SESSION') {
if (
(error as NodeJS.ErrnoException).code ===
'ERR_HTTP2_GOAWAY_SESSION'
) {
/* An error here indicates that something went wrong with
* the picked subchannel's http2 stream right before we
* tried to start the stream. We are handling a promise
* result here, so this is asynchronous with respect to the
* original tryPick call, so calling it again is not
* recursive. We call tryPick immediately instead of
* queueing this pick again because handling the queue is
* triggered by state changes, and we want to immediately
* check if the state has already changed since the
* previous tryPick call. We do this instead of cancelling
* the stream because the correct behavior may be
* re-queueing instead, based on the logic in the rest of
* tryPick */
* the picked subchannel's http2 stream right before we
* tried to start the stream. We are handling a promise
* result here, so this is asynchronous with respect to the
* original tryPick call, so calling it again is not
* recursive. We call tryPick immediately instead of
* queueing this pick again because handling the queue is
* triggered by state changes, and we want to immediately
* check if the state has already changed since the
* previous tryPick call. We do this instead of cancelling
* the stream because the correct behavior may be
* re-queueing instead, based on the logic in the rest of
* tryPick */
trace(
LogVerbosity.INFO,
'channel',
'Failed to start call on picked subchannel ' +
pickResult.subchannel!.getAddress() +
' with error ' +
(error as Error).message +
'. Retrying pick'
pickResult.subchannel!.getAddress() +
' with error ' +
(error as Error).message +
'. Retrying pick'
);
this.tryPick(callStream, callMetadata);
} else {
trace(
LogVerbosity.INFO,
'channel',
'Failed to start call on picked subchanel ' +
pickResult.subchannel!.getAddress() +
' with error ' +
(error as Error).message +
'. Ending call'
pickResult.subchannel!.getAddress() +
' with error ' +
(error as Error).message +
'. Ending call'
);
callStream.cancelWithStatus(
Status.INTERNAL,
'Failed to start HTTP/2 stream'
);
callStream.cancelWithStatus(Status.INTERNAL, 'Failed to start HTTP/2 stream');
}
}
} else {
Expand Down Expand Up @@ -360,7 +377,7 @@ export class ChannelImplementation implements Channel {
watcherObject: ConnectivityStateWatcher
) {
const watcherIndex = this.connectivityStateWatchers.findIndex(
value => value === watcherObject
(value) => value === watcherObject
);
if (watcherIndex >= 0) {
this.connectivityStateWatchers.splice(watcherIndex, 1);
Expand Down Expand Up @@ -443,14 +460,16 @@ export class ChannelImplementation implements Channel {
method: string,
deadline: Deadline,
host: string | null | undefined,
parentCall: any,
parentCall: any, // eslint-disable-line @typescript-eslint/no-explicit-any
propagateFlags: number | null | undefined
): Call {
if (typeof method !== 'string') {
throw new TypeError('Channel#createCall: method must be a string');
}
if (!(typeof deadline === 'number' || deadline instanceof Date)) {
throw new TypeError('Channel#createCall: deadline must be a number or Date');
throw new TypeError(
'Channel#createCall: deadline must be a number or Date'
);
}
if (this.connectivityState === ConnectivityState.SHUTDOWN) {
throw new Error('Channel has been shut down');
Expand Down
Loading

0 comments on commit 4ec023c

Please sign in to comment.