Skip to content

Commit

Permalink
fix(types): enable noImplicitAny in tsconfig (#679)
Browse files Browse the repository at this point in the history
* enable noimplicitany in tsconfig

* fix type except test

* fix type for src

* fix type for src

* fix type for src

* final fix for type except test

* fix browser test

* fix system-test

* fix type for tests

* make browser test work

* fix lint

* fix some unit tests

* debug

* fix: make typing changes only

* fix

* make all work

* remove unneccessary tsignore annotation

* no ts-ignore
  • Loading branch information
xiaozhenliu-gg5 authored and alexander-fenster committed Dec 13, 2019
1 parent f9276c9 commit 6ecdeb7
Show file tree
Hide file tree
Showing 25 changed files with 573 additions and 252 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"dependencies": {
"@grpc/grpc-js": "^0.6.12",
"@grpc/proto-loader": "^0.5.1",
"@types/fs-extra": "^8.0.1",
"@types/long": "^4.0.0",
"abort-controller": "^3.0.0",
"duplexify": "^3.6.0",
Expand All @@ -37,6 +38,7 @@
"@types/mocha": "^5.2.1",
"@types/ncp": "^2.0.1",
"@types/node": "^10.3.2",
"@types/node-fetch": "^2.5.4",
"@types/proxyquire": "^1.3.28",
"@types/pumpify": "^1.4.1",
"@types/rimraf": "^2.0.2",
Expand Down
16 changes: 8 additions & 8 deletions src/bundlingCalls/bundleExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ import {Task, TaskCallback} from './task';
function noop() {}

export interface BundleOptions {
elementCountLimit: number;
requestByteLimit: number;
elementCountThreshold: number;
requestByteThreshold: number;
delayThreshold: number;
elementCountLimit?: number;
requestByteLimit?: number;
elementCountThreshold?: number;
requestByteThreshold?: number;
delayThreshold?: number;
}

/**
Expand Down Expand Up @@ -202,11 +202,11 @@ export class BundleExecutor {
return ret;
}

if (!(bundleId in this._timers) && this._options.delayThreshold > 0) {
this._timers[bundleId] = setTimeout(() => {
if (!(bundleId in this._timers) && this._options.delayThreshold! > 0) {
this._timers[bundleId] = (setTimeout(() => {
delete this._timers[bundleId];
this._runNow(bundleId);
}, this._options.delayThreshold);
}, this._options.delayThreshold) as unknown) as NodeJS.Timeout;
}

return ret;
Expand Down
6 changes: 3 additions & 3 deletions src/bundlingCalls/bundlingUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

import at = require('lodash.at');
import {RequestType} from '../apitypes';
import {Dictionary} from 'lodash';

/**
* Compute the identifier of the `obj`. The objects of the same ID
Expand All @@ -51,11 +52,10 @@ export function computeBundleId(
obj: RequestType,
discriminatorFields: string[]
) {
const ids: Array<{} | null> = [];
const ids: unknown[] = [];
let hasIds = false;
for (let i = 0; i < discriminatorFields.length; ++i) {
// @ts-ignore lodash.at types
const id = at(obj, discriminatorFields[i])[0];
const id = at(obj as Dictionary<unknown>, discriminatorFields[i])[0];
if (id === undefined) {
ids.push(null);
} else {
Expand Down
82 changes: 63 additions & 19 deletions src/fallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,16 @@ export {

export {StreamType} from './streamingCalls/streaming';

interface NodeFetchType {
(url: RequestInfo, init?: RequestInit): Promise<Response>;
}

const CLIENT_VERSION_HEADER = 'x-goog-api-client';

interface FallbackServiceStub {
[method: string]: Function;
}

export class GrpcClient {
auth?: OAuth2Client | GoogleAuth;
authClient?: OAuth2Client | Compute | JWT | UserRefreshClient;
Expand Down Expand Up @@ -111,7 +119,7 @@ export class GrpcClient {
* @param {Object} jsonObject - A JSON version of a protofile created usin protobuf.js
* @returns {Object} Root namespace of proto JSON
*/
loadProto(jsonObject) {
loadProto(jsonObject: {}) {
const rootObject = protobuf.Root.fromJSON(jsonObject);
return rootObject;
}
Expand Down Expand Up @@ -144,8 +152,8 @@ export class GrpcClient {
configOverrides: gax.ClientConfig,
headers: OutgoingHttpHeaders
) {
function buildMetadata(abTests, moreHeaders) {
const metadata = {};
function buildMetadata(abTests: {}, moreHeaders: OutgoingHttpHeaders) {
const metadata: OutgoingHttpHeaders = {};
if (!headers) {
headers = {};
}
Expand All @@ -154,18 +162,22 @@ export class GrpcClient {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
metadata[key] = Array.isArray(headers[key])
? headers[key]
: [headers[key]];
? (headers[key] as string[])
: ([headers[key]] as string[]);
}
}

// gRPC-fallback request must have 'grpc-web/' in 'x-goog-api-client'
const clientVersions: string[] = [];
if (
metadata[CLIENT_VERSION_HEADER] &&
metadata[CLIENT_VERSION_HEADER][0]
(metadata[CLIENT_VERSION_HEADER] as Array<
string | number | string[]
>)[0]
) {
clientVersions.push(...metadata[CLIENT_VERSION_HEADER][0].split(' '));
clientVersions.push(
...(metadata[CLIENT_VERSION_HEADER] as string[])[0].split(' ')
);
}
clientVersions.push(`grpc-web/${version}`);
metadata[CLIENT_VERSION_HEADER] = [clientVersions.join(' ')];
Expand All @@ -183,10 +195,18 @@ export class GrpcClient {
if (metadata[key] === undefined) {
metadata[key] = value;
} else {
metadata[key].push(...value);
if (Array.isArray(metadata[key])) {
(metadata[key]! as Array<
string | number | string[] | undefined
>).push(...value);
} else {
throw new Error(
`Can not add value ${value} to the call metadata.`
);
}
}
} else {
metadata[key] = [value];
metadata[key] = [value] as string[];
}
}
}
Expand Down Expand Up @@ -215,7 +235,16 @@ export class GrpcClient {
*/
async createStub(service: protobuf.Service, opts: ClientStubOptions) {
// an RPC function to be passed to protobufjs RPC API
function serviceClientImpl(method, requestData, callback) {
function serviceClientImpl(
method:
| protobuf.Method
| protobuf.rpc.ServiceMethod<
protobuf.Message<{}>,
protobuf.Message<{}>
>,
requestData: Uint8Array,
callback: protobuf.RPCImplCallback
) {
return [method, requestData, callback];
}

Expand All @@ -233,17 +262,30 @@ export class GrpcClient {
throw new Error('No authentication was provided');
}
const authHeader = await this.authClient.getRequestHeaders();
const serviceStub = service.create(serviceClientImpl, false, false);
const serviceStub = (service.create(
serviceClientImpl,
false,
false
) as unknown) as FallbackServiceStub;
const methods = this.getServiceMethods(service);

const newServiceStub = service.create(serviceClientImpl, false, false);
const newServiceStub = (service.create(
serviceClientImpl,
false,
false
) as unknown) as FallbackServiceStub;
for (const methodName of methods) {
newServiceStub[methodName] = (req, options, metadata, callback) => {
newServiceStub[methodName] = (
req: {},
options: {[name: string]: string},
metadata: {},
callback: Function
) => {
const [method, requestData, serviceCallback] = serviceStub[
methodName
].apply(serviceStub, [req, callback]);

let cancelController, cancelSignal;
// tslint:disable-next-line no-any
let cancelController: AbortController, cancelSignal: any;
if (isBrowser && typeof AbortController !== 'undefined') {
cancelController = new AbortController();
} else {
Expand Down Expand Up @@ -297,27 +339,29 @@ export class GrpcClient {

const url = `${grpcFallbackProtocol}://${servicePath}:${servicePort}/$rpc/${protoServiceName}/${rpcName}`;

const fetch = isBrowser() ? window.fetch : nodeFetch;
const fetch = isBrowser()
? window.fetch
: ((nodeFetch as unknown) as NodeFetchType);
fetch(url, {
headers,
method: 'post',
body: requestData,
signal: cancelSignal,
})
.then(response => {
.then((response: Response | nodeFetch.Response) => {
return Promise.all([
Promise.resolve(response.ok),
response.arrayBuffer(),
]);
})
.then(([ok, buffer]) => {
.then(([ok, buffer]: [boolean, Buffer | ArrayBuffer]) => {
if (!ok) {
const status = statusDecoder.decodeRpcStatus(buffer);
throw new Error(JSON.stringify(status));
}
serviceCallback(null, new Uint8Array(buffer));
})
.catch(err => {
.catch((err: Error) => {
if (!cancelRequested || err.name !== 'AbortError') {
serviceCallback(err);
}
Expand Down
35 changes: 17 additions & 18 deletions src/gax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ export function createMaxRetriesBackoffSettings(
* @return {BundleOptions} - A new options.
*/
export function createBundleOptions(options: BundlingConfig): BundleOptions {
const params = [
const params: Array<keyof BundlingConfig> = [
'element_count_threshold',
'element_count_limit',
'request_byte_threshold',
Expand Down Expand Up @@ -494,9 +494,9 @@ export function createBundleOptions(options: BundlingConfig): BundleOptions {
* @return {?RetryOptions} The new retry options.
*/
function constructRetry(
methodConfig: MethodConfig,
retryCodes: {[index: string]: string[]},
retryParams: {[index: string]: {}},
methodConfig: MethodConfig | null,
retryCodes: {[index: string]: string[]} | undefined,
retryParams: {[index: string]: {}} | undefined,
retryNames: {[index: string]: {}}
): RetryOptions | null | undefined {
if (!methodConfig) {
Expand All @@ -506,15 +506,15 @@ function constructRetry(
let codes: number[] | null = null;
if (retryCodes && 'retry_codes_name' in methodConfig) {
const retryCodesName = methodConfig['retry_codes_name'];
codes = (retryCodes[retryCodesName] || []).map(name => {
codes = (retryCodes[retryCodesName!] || []).map(name => {
return Number(retryNames[name]);
});
}

let backoffSettings: BackoffSettings | null = null;
if (retryParams && 'retry_params_name' in methodConfig) {
const params = retryParams[
methodConfig.retry_params_name
methodConfig.retry_params_name!
] as RetryParamsConfig;
backoffSettings = createBackoffSettings(
params.initial_retry_delay_millis,
Expand Down Expand Up @@ -566,9 +566,9 @@ function mergeRetryOptions(
}

export interface ServiceConfig {
retry_codes: {[index: string]: string[]};
retry_params: {[index: string]: RetryParamsConfig};
methods: {[index: string]: MethodConfig};
retry_codes?: {[index: string]: string[]};
retry_params?: {[index: string]: RetryParamsConfig};
methods: {[index: string]: MethodConfig | null};
}

export interface RetryParamsConfig {
Expand All @@ -582,19 +582,18 @@ export interface RetryParamsConfig {
}

export interface MethodConfig {
retry_codes_name: string;
retry_params_name: string;
bundling?: BundlingConfig;
retry_codes_name?: string;
retry_params_name?: string;
bundling?: BundlingConfig | null;
timeout_millis?: number;
}

export interface BundlingConfig {
[index: string]: number;
element_count_threshold: number;
element_count_limit: number;
request_byte_threshold: number;
request_byte_limit: number;
delay_threshold_millis: number;
request_byte_threshold?: number;
request_byte_limit?: number;
delay_threshold_millis?: number;
}

export interface ClientConfig {
Expand Down Expand Up @@ -694,8 +693,8 @@ export function constructSettings(
serviceConfig.retry_params,
retryNames
);
let bundlingConfig = methodConfig.bundling;
let timeout = methodConfig.timeout_millis;
let bundlingConfig = methodConfig!.bundling;
let timeout = methodConfig!.timeout_millis;
if (methodName in overridingMethods) {
const overridingMethod = overridingMethods[methodName];
if (overridingMethod) {
Expand Down
14 changes: 11 additions & 3 deletions src/grpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import * as semver from 'semver';
import * as walk from 'walkdir';

import * as gax from './gax';
import {ClientOptions} from '@grpc/grpc-js/build/src/client';

const googleProtoFilesDir = path.join(__dirname, '..', '..', 'protos');

Expand Down Expand Up @@ -82,6 +83,7 @@ export interface ClientStubOptions {
// TODO: use sslCreds?: grpc.ChannelCredentials;
// tslint:disable-next-line no-any
sslCreds?: any;
[index: string]: string | number | undefined | {};
}

export class ClientStub extends grpc.Client {
Expand Down Expand Up @@ -293,13 +295,19 @@ export class GrpcClient {
async createStub(CreateStub: typeof ClientStub, options: ClientStubOptions) {
const serviceAddress = options.servicePath + ':' + options.port;
const creds = await this._getCredentials(options);
const grpcOptions: {[index: string]: string} = {};
const grpcOptions: ClientOptions = {};
Object.keys(options).forEach(key => {
if (key.startsWith('grpc.')) {
grpcOptions[key.replace(/^grpc\./, '')] = options[key];
grpcOptions[key.replace(/^grpc\./, '')] = options[key] as
| string
| number;
}
});
const stub = new CreateStub(serviceAddress, creds, grpcOptions);
const stub = new CreateStub(
serviceAddress,
creds,
grpcOptions as ClientOptions
);
return stub;
}

Expand Down
1 change: 0 additions & 1 deletion src/normalCalls/retries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@ export function retryable(
callback(err);
} else {
const toSleep = Math.random() * delay;
// @ts-ignore
timeoutId = setTimeout(() => {
now = new Date();
delay = Math.min(delay * delayMult, maxDelay);
Expand Down
Loading

0 comments on commit 6ecdeb7

Please sign in to comment.