grpc-js-core: fix lint

This commit makes the lint Gulp task pass again.
This commit is contained in:
cjihrig 2018-09-01 11:26:15 -04:00
parent 37f956d92a
commit eecefd3249
No known key found for this signature in database
GPG Key ID: 7434390BDBE9B9C5
9 changed files with 78 additions and 73 deletions

View File

@ -104,13 +104,13 @@ export abstract class ChannelCredentials {
key: privateKey || undefined, key: privateKey || undefined,
cert: certChain || undefined cert: certChain || undefined
}); });
let connectionOptions: ConnectionOptions = { const connectionOptions: ConnectionOptions = {
secureContext secureContext
}; };
if (verifyOptions && verifyOptions.checkServerIdentity) { if (verifyOptions && verifyOptions.checkServerIdentity) {
connectionOptions.checkServerIdentity = (host: string, cert: PeerCertificate) => { connectionOptions.checkServerIdentity = (host: string, cert: PeerCertificate) => {
return verifyOptions.checkServerIdentity!(host, {raw: cert.raw}); return verifyOptions.checkServerIdentity!(host, {raw: cert.raw});
} };
} }
return new SecureChannelCredentialsImpl(connectionOptions); return new SecureChannelCredentialsImpl(connectionOptions);
} }
@ -141,7 +141,7 @@ class InsecureChannelCredentialsImpl extends ChannelCredentials {
} }
class SecureChannelCredentialsImpl extends ChannelCredentials { class SecureChannelCredentialsImpl extends ChannelCredentials {
connectionOptions: ConnectionOptions connectionOptions: ConnectionOptions;
constructor(connectionOptions: ConnectionOptions, callCredentials?: CallCredentials) { constructor(connectionOptions: ConnectionOptions, callCredentials?: CallCredentials) {
super(callCredentials); super(callCredentials);

View File

@ -177,7 +177,7 @@ export class Http2Channel extends EventEmitter implements Channel {
} }
private startConnecting(): void { private startConnecting(): void {
let connectionOptions: http2.SecureClientSessionOptions = this.credentials._getConnectionOptions() || {}; const connectionOptions: http2.SecureClientSessionOptions = this.credentials._getConnectionOptions() || {};
if (connectionOptions.secureContext !== null) { if (connectionOptions.secureContext !== null) {
// If provided, the value of grpc.ssl_target_name_override should be used // If provided, the value of grpc.ssl_target_name_override should be used
// to override the target hostname when checking server identity. // to override the target hostname when checking server identity.
@ -226,7 +226,7 @@ export class Http2Channel extends EventEmitter implements Channel {
address: string, readonly credentials: ChannelCredentials, address: string, readonly credentials: ChannelCredentials,
private readonly options: Partial<ChannelOptions>) { private readonly options: Partial<ChannelOptions>) {
super(); super();
for (let option in options) { for (const option in options) {
if (options.hasOwnProperty(option)) { if (options.hasOwnProperty(option)) {
if (!recognizedOptions.hasOwnProperty(option)) { if (!recognizedOptions.hasOwnProperty(option)) {
console.warn(`Unrecognized channel argument '${option}' will be ignored.`); console.warn(`Unrecognized channel argument '${option}' will be ignored.`);
@ -300,7 +300,7 @@ export class Http2Channel extends EventEmitter implements Channel {
throw new Error('Channel has been shut down'); throw new Error('Channel has been shut down');
} }
const finalOptions: CallStreamOptions = { const finalOptions: CallStreamOptions = {
deadline: (deadline === null || deadline == undefined) ? Infinity : deadline, deadline: (deadline === null || deadline === undefined) ? Infinity : deadline,
flags: propagateFlags || 0, flags: propagateFlags || 0,
host: host || this.defaultAuthority, host: host || this.defaultAuthority,
parentCall: parentCall || null parentCall: parentCall || null
@ -358,7 +358,7 @@ export class Http2Channel extends EventEmitter implements Channel {
* we assume that a state change has successfully occurred */ * we assume that a state change has successfully occurred */
setImmediate(callback); setImmediate(callback);
} else { } else {
let deadlineMs: number = 0; let deadlineMs = 0;
if (deadline instanceof Date) { if (deadline instanceof Date) {
deadlineMs = deadline.getTime(); deadlineMs = deadline.getTime();
} else { } else {
@ -368,11 +368,11 @@ export class Http2Channel extends EventEmitter implements Channel {
if (timeout < 0) { if (timeout < 0) {
timeout = 0; timeout = 0;
} }
let timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
this.removeListener('connectivityStateChanged', eventCb); this.removeListener('connectivityStateChanged', eventCb);
callback(new Error('Channel state did not change before deadline')); callback(new Error('Channel state did not change before deadline'));
}, timeout); }, timeout);
let eventCb = () => { const eventCb = () => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
callback(); callback();
}; };

View File

@ -19,11 +19,11 @@ export interface UnaryCallback<ResponseType> {
} }
export interface CallOptions { export interface CallOptions {
deadline?: Deadline, deadline?: Deadline;
host?: string, host?: string;
parent?: Call, parent?: Call;
propagate_flags?: number, propagate_flags?: number;
credentials?: CallCredentials credentials?: CallCredentials;
} }
export type ClientOptions = Partial<ChannelOptions> & { export type ClientOptions = Partial<ChannelOptions> & {
@ -64,18 +64,18 @@ export class Client {
callback(new Error('Failed to connect before the deadline')); callback(new Error('Failed to connect before the deadline'));
return; return;
} }
var new_state; let newState;
try { try {
new_state = this[kChannel].getConnectivityState(true); newState = this[kChannel].getConnectivityState(true);
} catch (e) { } catch (e) {
callback(new Error('The channel has been closed')); callback(new Error('The channel has been closed'));
return; return;
} }
if (new_state === ConnectivityState.READY) { if (newState === ConnectivityState.READY) {
callback(); callback();
} else { } else {
try { try {
this[kChannel].watchConnectivityState(new_state, deadline, checkState); this[kChannel].watchConnectivityState(newState, deadline, checkState);
} catch (e) { } catch (e) {
callback(new Error('The channel has been closed')); callback(new Error('The channel has been closed'));
} }

View File

@ -19,7 +19,7 @@ abstract class CompressionHandler {
if (compress) { if (compress) {
messageBuffer = await this.compressMessage(messageBuffer); messageBuffer = await this.compressMessage(messageBuffer);
} }
let output = Buffer.allocUnsafe(messageBuffer.length + 5); const output = Buffer.allocUnsafe(messageBuffer.length + 5);
output.writeUInt8(compress ? 1 : 0, 0); output.writeUInt8(compress ? 1 : 0, 0);
output.writeUInt32BE(messageBuffer.length, 1); output.writeUInt32BE(messageBuffer.length, 1);
messageBuffer.copy(output, 5); messageBuffer.copy(output, 5);
@ -45,7 +45,7 @@ class IdentityHandler extends CompressionHandler {
} }
async writeMessage(message: Buffer, compress: boolean): Promise<Buffer> { async writeMessage(message: Buffer, compress: boolean): Promise<Buffer> {
let output = Buffer.allocUnsafe(message.length + 5); const output = Buffer.allocUnsafe(message.length + 5);
/* With "identity" compression, messages should always be marked as /* With "identity" compression, messages should always be marked as
* uncompressed */ * uncompressed */
output.writeUInt8(0, 0); output.writeUInt8(0, 0);
@ -62,49 +62,53 @@ class IdentityHandler extends CompressionHandler {
class DeflateHandler extends CompressionHandler { class DeflateHandler extends CompressionHandler {
compressMessage(message: Buffer) { compressMessage(message: Buffer) {
return new Promise<Buffer>( return new Promise<Buffer>((resolve, reject) => {
(resolve, reject) => {zlib.deflate(message, (err, output) => { zlib.deflate(message, (err, output) => {
if (err) { if (err) {
reject(err); reject(err);
} else { } else {
resolve(output); resolve(output);
} }
})}); });
});
} }
decompressMessage(message: Buffer) { decompressMessage(message: Buffer) {
return new Promise<Buffer>( return new Promise<Buffer>((resolve, reject) => {
(resolve, reject) => {zlib.inflate(message, (err, output) => { zlib.inflate(message, (err, output) => {
if (err) { if (err) {
reject(err); reject(err);
} else { } else {
resolve(output); resolve(output);
} }
})}); });
});
} }
} }
class GzipHandler extends CompressionHandler { class GzipHandler extends CompressionHandler {
compressMessage(message: Buffer) { compressMessage(message: Buffer) {
return new Promise<Buffer>( return new Promise<Buffer>((resolve, reject) => {
(resolve, reject) => {zlib.gzip(message, (err, output) => { zlib.gzip(message, (err, output) => {
if (err) { if (err) {
reject(err); reject(err);
} else { } else {
resolve(output); resolve(output);
} }
})}); });
});
} }
decompressMessage(message: Buffer) { decompressMessage(message: Buffer) {
return new Promise<Buffer>( return new Promise<Buffer>((resolve, reject) => {
(resolve, reject) => {zlib.unzip(message, (err, output) => { zlib.unzip(message, (err, output) => {
if (err) { if (err) {
reject(err); reject(err);
} else { } else {
resolve(output); resolve(output);
} }
})}); });
});
} }
} }
@ -150,7 +154,7 @@ export class CompressionFilter extends BaseFilter implements Filter {
async receiveMetadata(metadata: Promise<Metadata>): Promise<Metadata> { async receiveMetadata(metadata: Promise<Metadata>): Promise<Metadata> {
const headers: Metadata = await metadata; const headers: Metadata = await metadata;
let receiveEncoding: MetadataValue[] = headers.get('grpc-encoding'); const receiveEncoding: MetadataValue[] = headers.get('grpc-encoding');
if (receiveEncoding.length > 0) { if (receiveEncoding.length > 0) {
const encoding: MetadataValue = receiveEncoding[0]; const encoding: MetadataValue = receiveEncoding[0];
if (typeof encoding === 'string') { if (typeof encoding === 'string') {

View File

@ -18,15 +18,15 @@ if (!semver.satisfies(process.version, supportedNodeVersions)) {
} }
interface IndexedObject { interface IndexedObject {
[key: string]: any; [key: string]: any; // tslint:disable-line no-any
[key: number]: any; [key: number]: any; // tslint:disable-line no-any
} }
function mixin(...sources: IndexedObject[]) { function mixin(...sources: IndexedObject[]) {
const result: {[key: string]: Function} = {}; const result: {[key: string]: Function} = {};
for (const source of sources) { for (const source of sources) {
for (const propName of Object.getOwnPropertyNames(source)) { for (const propName of Object.getOwnPropertyNames(source)) {
const property: any = source[propName]; const property: any = source[propName]; // tslint:disable-line no-any
if (typeof property === 'function') { if (typeof property === 'function') {
result[propName] = property; result[propName] = property;
} }

View File

@ -15,6 +15,7 @@ export const setLoggerVerbosity = (verbosity: LogVerbosity): void => {
_logVerbosity = verbosity; _logVerbosity = verbosity;
}; };
// tslint:disable-next-line no-any
export const log = (severity: LogVerbosity, ...args: any[]): void => { export const log = (severity: LogVerbosity, ...args: any[]): void => {
if (severity >= _logVerbosity && typeof _logger.error === 'function') { if (severity >= _logVerbosity && typeof _logger.error === 'function') {
_logger.error(...args); _logger.error(...args);

View File

@ -35,7 +35,7 @@ export interface SubChannel extends EventEmitter {
export class Http2SubChannel extends EventEmitter implements SubChannel { export class Http2SubChannel extends EventEmitter implements SubChannel {
private session: http2.ClientHttp2Session; private session: http2.ClientHttp2Session;
private refCount: number = 0; private refCount = 0;
private userAgent: string; private userAgent: string;
private keepaliveTimeMs: number = KEEPALIVE_TIME_MS; private keepaliveTimeMs: number = KEEPALIVE_TIME_MS;
@ -57,7 +57,7 @@ export class Http2SubChannel extends EventEmitter implements SubChannel {
this.session.on('error', () => { this.session.on('error', () => {
this.stopKeepalivePings(); this.stopKeepalivePings();
this.emit('close'); this.emit('close');
}) });
this.userAgent = userAgent; this.userAgent = userAgent;
if (channelArgs['grpc.keepalive_time_ms']) { if (channelArgs['grpc.keepalive_time_ms']) {
@ -120,7 +120,7 @@ export class Http2SubChannel extends EventEmitter implements SubChannel {
headers[HTTP2_HEADER_METHOD] = 'POST'; headers[HTTP2_HEADER_METHOD] = 'POST';
headers[HTTP2_HEADER_PATH] = callStream.getMethod(); headers[HTTP2_HEADER_PATH] = callStream.getMethod();
headers[HTTP2_HEADER_TE] = 'trailers'; headers[HTTP2_HEADER_TE] = 'trailers';
let http2Stream = this.session.request(headers); const http2Stream = this.session.request(headers);
this.ref(); this.ref();
http2Stream.on('close', () => { http2Stream.on('close', () => {
this.unref(); this.unref();
@ -131,4 +131,4 @@ export class Http2SubChannel extends EventEmitter implements SubChannel {
close() { close() {
this.session.close(); this.session.close();
} }
} }

View File

@ -90,7 +90,7 @@ describe('CallStream', () => {
* but this might break if we start checking channel arguments, in which case * but this might break if we start checking channel arguments, in which case
* we will need a more sophisticated fake */ * we will need a more sophisticated fake */
const filterStackFactory = const filterStackFactory =
new FilterStackFactory([new CompressionFilterFactory(<Channel>{})]); new FilterStackFactory([new CompressionFilterFactory({} as Channel)]);
const message = 'eat this message'; // 16 bytes const message = 'eat this message'; // 16 bytes
beforeEach(() => { beforeEach(() => {
@ -102,7 +102,7 @@ describe('CallStream', () => {
const responseMetadata = new Metadata(); const responseMetadata = new Metadata();
responseMetadata.add('key', 'value'); responseMetadata.add('key', 'value');
const callStream = const callStream =
new Http2CallStream('foo', <Http2Channel>{}, callStreamArgs, filterStackFactory); new Http2CallStream('foo', {} as Http2Channel, callStreamArgs, filterStackFactory);
const http2Stream = new ClientHttp2StreamMock( const http2Stream = new ClientHttp2StreamMock(
{payload: Buffer.alloc(0), frameLengths: []}); {payload: Buffer.alloc(0), frameLengths: []});
@ -140,7 +140,7 @@ describe('CallStream', () => {
maybeSkip(it)(`for error code ${key}`, () => { maybeSkip(it)(`for error code ${key}`, () => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const callStream = const callStream =
new Http2CallStream('foo', <Http2Channel>{}, callStreamArgs, filterStackFactory); new Http2CallStream('foo', {} as Http2Channel, callStreamArgs, filterStackFactory);
const http2Stream = new ClientHttp2StreamMock( const http2Stream = new ClientHttp2StreamMock(
{payload: Buffer.alloc(0), frameLengths: []}); {payload: Buffer.alloc(0), frameLengths: []});
callStream.attachHttp2Stream(http2Stream); callStream.attachHttp2Stream(http2Stream);
@ -160,7 +160,7 @@ describe('CallStream', () => {
it('should have functioning getters', (done) => { it('should have functioning getters', (done) => {
const callStream = const callStream =
new Http2CallStream('foo', <Http2Channel>{}, callStreamArgs, filterStackFactory); new Http2CallStream('foo', {} as Http2Channel, callStreamArgs, filterStackFactory);
assert.strictEqual(callStream.getDeadline(), callStreamArgs.deadline); assert.strictEqual(callStream.getDeadline(), callStreamArgs.deadline);
assert.strictEqual(callStream.getStatus(), null); assert.strictEqual(callStream.getStatus(), null);
const credentials = CallCredentials.createEmpty(); const credentials = CallCredentials.createEmpty();
@ -179,7 +179,7 @@ describe('CallStream', () => {
describe('attachHttp2Stream', () => { describe('attachHttp2Stream', () => {
it('should handle an empty message', (done) => { it('should handle an empty message', (done) => {
const callStream = const callStream =
new Http2CallStream('foo', <Http2Channel>{}, callStreamArgs, filterStackFactory); new Http2CallStream('foo', {} as Http2Channel, callStreamArgs, filterStackFactory);
const http2Stream = const http2Stream =
new ClientHttp2StreamMock({payload: serialize(''), frameLengths: []}); new ClientHttp2StreamMock({payload: serialize(''), frameLengths: []});
callStream.once('data', assert2.mustCall((buffer) => { callStream.once('data', assert2.mustCall((buffer) => {
@ -206,7 +206,7 @@ describe('CallStream', () => {
it(`should handle a short message where ${testCase.description}`, it(`should handle a short message where ${testCase.description}`,
(done) => { (done) => {
const callStream = const callStream =
new Http2CallStream('foo', <Http2Channel>{}, callStreamArgs, filterStackFactory); new Http2CallStream('foo', {} as Http2Channel, callStreamArgs, filterStackFactory);
const http2Stream = new ClientHttp2StreamMock({ const http2Stream = new ClientHttp2StreamMock({
payload: serialize(message), // 21 bytes payload: serialize(message), // 21 bytes
frameLengths: testCase.frameLengths frameLengths: testCase.frameLengths
@ -236,7 +236,7 @@ describe('CallStream', () => {
}].forEach((testCase: {description: string, frameLengths: number[]}) => { }].forEach((testCase: {description: string, frameLengths: number[]}) => {
it(`should handle two messages where ${testCase.description}`, (done) => { it(`should handle two messages where ${testCase.description}`, (done) => {
const callStream = const callStream =
new Http2CallStream('foo', <Http2Channel>{}, callStreamArgs, filterStackFactory); new Http2CallStream('foo', {} as Http2Channel, callStreamArgs, filterStackFactory);
const http2Stream = new ClientHttp2StreamMock({ const http2Stream = new ClientHttp2StreamMock({
payload: Buffer.concat( payload: Buffer.concat(
[serialize(message), serialize(message)]), // 42 bytes [serialize(message), serialize(message)]), // 42 bytes
@ -256,7 +256,7 @@ describe('CallStream', () => {
it('should send buffered writes', (done) => { it('should send buffered writes', (done) => {
const callStream = const callStream =
new Http2CallStream('foo', <Http2Channel>{}, callStreamArgs, filterStackFactory); new Http2CallStream('foo', {} as Http2Channel, callStreamArgs, filterStackFactory);
const http2Stream = new ClientHttp2StreamMock( const http2Stream = new ClientHttp2StreamMock(
{payload: Buffer.alloc(0), frameLengths: []}); {payload: Buffer.alloc(0), frameLengths: []});
let streamFlushed = false; let streamFlushed = false;
@ -279,7 +279,7 @@ describe('CallStream', () => {
it('should cause data chunks in write calls afterward to be written to the given stream', it('should cause data chunks in write calls afterward to be written to the given stream',
(done) => { (done) => {
const callStream = const callStream =
new Http2CallStream('foo', <Http2Channel>{}, callStreamArgs, filterStackFactory); new Http2CallStream('foo', {} as Http2Channel, callStreamArgs, filterStackFactory);
const http2Stream = new ClientHttp2StreamMock( const http2Stream = new ClientHttp2StreamMock(
{payload: Buffer.alloc(0), frameLengths: []}); {payload: Buffer.alloc(0), frameLengths: []});
http2Stream.once('write', assert2.mustCall((chunk: Buffer) => { http2Stream.once('write', assert2.mustCall((chunk: Buffer) => {
@ -297,7 +297,7 @@ describe('CallStream', () => {
it('should handle underlying stream errors', () => { it('should handle underlying stream errors', () => {
const callStream = const callStream =
new Http2CallStream('foo', <Http2Channel>{}, callStreamArgs, filterStackFactory); new Http2CallStream('foo', {} as Http2Channel, callStreamArgs, filterStackFactory);
const http2Stream = new ClientHttp2StreamMock( const http2Stream = new ClientHttp2StreamMock(
{payload: Buffer.alloc(0), frameLengths: []}); {payload: Buffer.alloc(0), frameLengths: []});
callStream.once('status', assert2.mustCall((status) => { callStream.once('status', assert2.mustCall((status) => {

View File

@ -4,7 +4,7 @@ import * as grpc from '../src';
import * as logging from '../src/logging'; import * as logging from '../src/logging';
describe('Logging', () => { describe('Logging', () => {
afterEach(function() { afterEach(() => {
// Ensure that the logger is restored to its defaults after each test. // Ensure that the logger is restored to its defaults after each test.
grpc.setLogger(console); grpc.setLogger(console);
grpc.setLogVerbosity(grpc.logVerbosity.DEBUG); grpc.setLogVerbosity(grpc.logVerbosity.DEBUG);
@ -22,9 +22,9 @@ describe('Logging', () => {
}); });
it('gates logging based on severity', () => { it('gates logging based on severity', () => {
const output: any[] = []; const output: Array<string | string[]> = [];
const logger: Partial<Console> = { const logger: Partial<Console> = {
error(...args: any[]): void { error(...args: string[]): void {
output.push(args); output.push(args);
} }
}; };