Skip to content

Commit

Permalink
feat: deferred client initialization (#12)
Browse files Browse the repository at this point in the history
This PR includes changes from googleapis/gapic-generator-typescript#317
that will move the asynchronous initialization and authentication from the client constructor
to an `initialize()` method. This method will be automatically called when the first RPC call
is performed.

The client library usage has not changed, there is no need to update any code.

If you want to make sure the client is authenticated _before_ the first RPC call, you can do
```js
await client.initialize();
```
manually before calling any client method.
  • Loading branch information
gcf-merge-on-green[bot] authored Mar 6, 2020
1 parent 1f1f97a commit edf9643
Show file tree
Hide file tree
Showing 5 changed files with 205 additions and 51 deletions.
89 changes: 65 additions & 24 deletions packages/google-cloud-billing/src/v1/cloud_billing_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,13 @@ export class CloudBillingClient {
private _innerApiCalls: {[name: string]: Function};
private _pathTemplates: {[name: string]: gax.PathTemplate};
private _terminated = false;
private _opts: ClientOptions;
private _gaxModule: typeof gax | typeof gax.fallback;
private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient;
private _protos: {};
private _defaults: {[method: string]: gax.CallSettings};
auth: gax.GoogleAuth;
cloudBillingStub: Promise<{[name: string]: Function}>;
cloudBillingStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of CloudBillingClient.
Expand All @@ -69,8 +74,6 @@ export class CloudBillingClient {
* app is running in an environment which supports
* {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
*/
Expand Down Expand Up @@ -100,25 +103,28 @@ export class CloudBillingClient {
// If we are in browser, we are already using fallback because of the
// "browser" field in package.json.
// But if we were explicitly requested to use fallback, let's do it now.
const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax;
this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax;

// Create a `gaxGrpc` object, with any grpc-specific options
// sent to the client.
opts.scopes = (this.constructor as typeof CloudBillingClient).scopes;
const gaxGrpc = new gaxModule.GrpcClient(opts);
this._gaxGrpc = new this._gaxModule.GrpcClient(opts);

// Save options to use in initialize() method.
this._opts = opts;

// Save the auth object to the client, for use by other methods.
this.auth = gaxGrpc.auth as gax.GoogleAuth;
this.auth = this._gaxGrpc.auth as gax.GoogleAuth;

// Determine the client header string.
const clientHeader = [`gax/${gaxModule.version}`, `gapic/${version}`];
const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`];
if (typeof process !== 'undefined' && 'versions' in process) {
clientHeader.push(`gl-node/${process.versions.node}`);
} else {
clientHeader.push(`gl-web/${gaxModule.version}`);
clientHeader.push(`gl-web/${this._gaxModule.version}`);
}
if (!opts.fallback) {
clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`);
clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`);
}
if (opts.libName && opts.libVersion) {
clientHeader.push(`${opts.libName}/${opts.libVersion}`);
Expand All @@ -134,19 +140,21 @@ export class CloudBillingClient {
'protos',
'protos.json'
);
const protos = gaxGrpc.loadProto(
this._protos = this._gaxGrpc.loadProto(
opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath
);

// This API contains "path templates"; forward-slash-separated
// identifiers to uniquely identify resources within the API.
// Create useful helper objects for these.
this._pathTemplates = {
billingAccountPathTemplate: new gaxModule.PathTemplate(
billingAccountPathTemplate: new this._gaxModule.PathTemplate(
'billingAccounts/{billing_account}'
),
servicePathTemplate: new gaxModule.PathTemplate('services/{service}'),
skuPathTemplate: new gaxModule.PathTemplate(
servicePathTemplate: new this._gaxModule.PathTemplate(
'services/{service}'
),
skuPathTemplate: new this._gaxModule.PathTemplate(
'services/{service}/skus/{sku}'
),
};
Expand All @@ -155,20 +163,20 @@ export class CloudBillingClient {
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this._descriptors.page = {
listBillingAccounts: new gaxModule.PageDescriptor(
listBillingAccounts: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'billingAccounts'
),
listProjectBillingInfo: new gaxModule.PageDescriptor(
listProjectBillingInfo: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'projectBillingInfo'
),
};

// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings(
this._defaults = this._gaxGrpc.constructSettings(
'google.cloud.billing.v1.CloudBilling',
gapicConfig as gax.ClientConfig,
opts.clientConfig || {},
Expand All @@ -179,17 +187,35 @@ export class CloudBillingClient {
// of calling the API is handled in `google-gax`, with this code
// merely providing the destination and request information.
this._innerApiCalls = {};
}

/**
* Initialize the client.
* Performs asynchronous operations (such as authentication) and prepares the client.
* This function will be called automatically when any class method is called for the
* first time, but if you need to initialize it before calling an actual method,
* feel free to call initialize() directly.
*
* You can await on this method if you want to make sure the client is initialized.
*
* @returns {Promise} A promise that resolves to an authenticated service stub.
*/
initialize() {
// If the client stub promise is already initialized, return immediately.
if (this.cloudBillingStub) {
return this.cloudBillingStub;
}

// Put together the "service stub" for
// google.cloud.billing.v1.CloudBilling.
this.cloudBillingStub = gaxGrpc.createStub(
opts.fallback
? (protos as protobuf.Root).lookupService(
this.cloudBillingStub = this._gaxGrpc.createStub(
this._opts.fallback
? (this._protos as protobuf.Root).lookupService(
'google.cloud.billing.v1.CloudBilling'
)
: // tslint:disable-next-line no-any
(protos as any).google.cloud.billing.v1.CloudBilling,
opts
(this._protos as any).google.cloud.billing.v1.CloudBilling,
this._opts
) as Promise<{[method: string]: Function}>;

// Iterate over each of the methods that the service provides
Expand Down Expand Up @@ -220,9 +246,9 @@ export class CloudBillingClient {
}
);

const apiCall = gaxModule.createApiCall(
const apiCall = this._gaxModule.createApiCall(
innerCallPromise,
defaults[methodName],
this._defaults[methodName],
this._descriptors.page[methodName] ||
this._descriptors.stream[methodName] ||
this._descriptors.longrunning[methodName]
Expand All @@ -236,6 +262,8 @@ export class CloudBillingClient {
return apiCall(argument, callOptions, callback);
};
}

return this.cloudBillingStub;
}

/**
Expand Down Expand Up @@ -361,6 +389,7 @@ export class CloudBillingClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.getBillingAccount(request, options, callback);
}
updateBillingAccount(
Expand Down Expand Up @@ -451,6 +480,7 @@ export class CloudBillingClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.updateBillingAccount(request, options, callback);
}
createBillingAccount(
Expand Down Expand Up @@ -536,6 +566,7 @@ export class CloudBillingClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.createBillingAccount(request, options, callback);
}
getProjectBillingInfo(
Expand Down Expand Up @@ -620,6 +651,7 @@ export class CloudBillingClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.getProjectBillingInfo(
request,
options,
Expand Down Expand Up @@ -738,6 +770,7 @@ export class CloudBillingClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.updateProjectBillingInfo(
request,
options,
Expand Down Expand Up @@ -814,6 +847,7 @@ export class CloudBillingClient {
] = gax.routingHeader.fromParams({
resource: request.resource || '',
});
this.initialize();
return this._innerApiCalls.getIamPolicy(request, options, callback);
}
setIamPolicy(
Expand Down Expand Up @@ -887,6 +921,7 @@ export class CloudBillingClient {
] = gax.routingHeader.fromParams({
resource: request.resource || '',
});
this.initialize();
return this._innerApiCalls.setIamPolicy(request, options, callback);
}
testIamPermissions(
Expand Down Expand Up @@ -958,6 +993,7 @@ export class CloudBillingClient {
] = gax.routingHeader.fromParams({
resource: request.resource || '',
});
this.initialize();
return this._innerApiCalls.testIamPermissions(request, options, callback);
}

Expand Down Expand Up @@ -1049,6 +1085,7 @@ export class CloudBillingClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.listBillingAccounts(request, options, callback);
}

Expand Down Expand Up @@ -1093,6 +1130,7 @@ export class CloudBillingClient {
request = request || {};
options = options || {};
const callSettings = new gax.CallSettings(options);
this.initialize();
return this._descriptors.page.listBillingAccounts.createStream(
this._innerApiCalls.listBillingAccounts as gax.GaxCall,
request,
Expand Down Expand Up @@ -1191,6 +1229,7 @@ export class CloudBillingClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.listProjectBillingInfo(
request,
options,
Expand Down Expand Up @@ -1242,6 +1281,7 @@ export class CloudBillingClient {
name: request.name || '',
});
const callSettings = new gax.CallSettings(options);
this.initialize();
return this._descriptors.page.listProjectBillingInfo.createStream(
this._innerApiCalls.listProjectBillingInfo as gax.GaxCall,
request,
Expand Down Expand Up @@ -1342,8 +1382,9 @@ export class CloudBillingClient {
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void> {
this.initialize();
if (!this._terminated) {
return this.cloudBillingStub.then(stub => {
return this.cloudBillingStub!.then(stub => {
this._terminated = true;
stub.close();
});
Expand Down
Loading

0 comments on commit edf9643

Please sign in to comment.