Skip to content

Commit

Permalink
feat: deferred client initialization (#75)
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] committed Mar 6, 2020
1 parent 6ca9763 commit 1f2a22e
Show file tree
Hide file tree
Showing 3 changed files with 159 additions and 31 deletions.
103 changes: 75 additions & 28 deletions packages/google-devtools-cloudbuild/src/v1/cloud_build_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,14 @@ export class CloudBuildClient {
private _descriptors: Descriptors = {page: {}, stream: {}, longrunning: {}};
private _innerApiCalls: {[name: string]: Function};
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;
operationsClient: gax.OperationsClient;
cloudBuildStub: Promise<{[name: string]: Function}>;
cloudBuildStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of CloudBuildClient.
Expand All @@ -77,8 +82,6 @@ export class CloudBuildClient {
* 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 @@ -108,25 +111,28 @@ export class CloudBuildClient {
// 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 CloudBuildClient).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 @@ -142,20 +148,20 @@ export class CloudBuildClient {
'protos',
'protos.json'
);
const protos = gaxGrpc.loadProto(
this._protos = this._gaxGrpc.loadProto(
opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath
);

// Some of the methods on this service return "paged" results,
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this._descriptors.page = {
listBuilds: new gaxModule.PageDescriptor(
listBuilds: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'builds'
),
listBuildTriggers: new gaxModule.PageDescriptor(
listBuildTriggers: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'triggers'
Expand All @@ -166,13 +172,15 @@ export class CloudBuildClient {
// an Operation object that allows for tracking of the operation,
// rather than holding a request open.
const protoFilesRoot = opts.fallback
? gaxModule.protobuf.Root.fromJSON(require('../../protos/protos.json'))
: gaxModule.protobuf.loadSync(nodejsProtoPath);
? this._gaxModule.protobuf.Root.fromJSON(
require('../../protos/protos.json')
)
: this._gaxModule.protobuf.loadSync(nodejsProtoPath);

this.operationsClient = gaxModule
this.operationsClient = this._gaxModule
.lro({
auth: this.auth,
grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined,
grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined,
})
.operationsClient(opts);
const createBuildResponse = protoFilesRoot.lookup(
Expand All @@ -195,25 +203,25 @@ export class CloudBuildClient {
) as gax.protobuf.Type;

this._descriptors.longrunning = {
createBuild: new gaxModule.LongrunningDescriptor(
createBuild: new this._gaxModule.LongrunningDescriptor(
this.operationsClient,
createBuildResponse.decode.bind(createBuildResponse),
createBuildMetadata.decode.bind(createBuildMetadata)
),
retryBuild: new gaxModule.LongrunningDescriptor(
retryBuild: new this._gaxModule.LongrunningDescriptor(
this.operationsClient,
retryBuildResponse.decode.bind(retryBuildResponse),
retryBuildMetadata.decode.bind(retryBuildMetadata)
),
runBuildTrigger: new gaxModule.LongrunningDescriptor(
runBuildTrigger: new this._gaxModule.LongrunningDescriptor(
this.operationsClient,
runBuildTriggerResponse.decode.bind(runBuildTriggerResponse),
runBuildTriggerMetadata.decode.bind(runBuildTriggerMetadata)
),
};

// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings(
this._defaults = this._gaxGrpc.constructSettings(
'google.devtools.cloudbuild.v1.CloudBuild',
gapicConfig as gax.ClientConfig,
opts.clientConfig || {},
Expand All @@ -224,17 +232,35 @@ export class CloudBuildClient {
// 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.cloudBuildStub) {
return this.cloudBuildStub;
}

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

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

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 @@ -287,6 +313,8 @@ export class CloudBuildClient {
return apiCall(argument, callOptions, callback);
};
}

return this.cloudBuildStub;
}

/**
Expand Down Expand Up @@ -407,6 +435,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.getBuild(request, options, callback);
}
cancelBuild(
Expand Down Expand Up @@ -474,6 +503,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.cancelBuild(request, options, callback);
}
createBuildTrigger(
Expand Down Expand Up @@ -551,6 +581,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.createBuildTrigger(request, options, callback);
}
getBuildTrigger(
Expand Down Expand Up @@ -628,6 +659,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.getBuildTrigger(request, options, callback);
}
deleteBuildTrigger(
Expand Down Expand Up @@ -705,6 +737,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.deleteBuildTrigger(request, options, callback);
}
updateBuildTrigger(
Expand Down Expand Up @@ -784,6 +817,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.updateBuildTrigger(request, options, callback);
}
createWorkerPool(
Expand Down Expand Up @@ -861,6 +895,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.createWorkerPool(request, options, callback);
}
getWorkerPool(
Expand Down Expand Up @@ -937,6 +972,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.getWorkerPool(request, options, callback);
}
deleteWorkerPool(
Expand Down Expand Up @@ -1013,6 +1049,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.deleteWorkerPool(request, options, callback);
}
updateWorkerPool(
Expand Down Expand Up @@ -1091,6 +1128,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.updateWorkerPool(request, options, callback);
}
listWorkerPools(
Expand Down Expand Up @@ -1166,6 +1204,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.listWorkerPools(request, options, callback);
}

Expand Down Expand Up @@ -1252,6 +1291,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.createBuild(request, options, callback);
}
retryBuild(
Expand Down Expand Up @@ -1359,6 +1399,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.retryBuild(request, options, callback);
}
runBuildTrigger(
Expand Down Expand Up @@ -1442,6 +1483,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.runBuildTrigger(request, options, callback);
}
listBuilds(
Expand Down Expand Up @@ -1527,6 +1569,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.listBuilds(request, options, callback);
}

Expand Down Expand Up @@ -1565,6 +1608,7 @@ export class CloudBuildClient {
request = request || {};
options = options || {};
const callSettings = new gax.CallSettings(options);
this.initialize();
return this._descriptors.page.listBuilds.createStream(
this._innerApiCalls.listBuilds as gax.GaxCall,
request,
Expand Down Expand Up @@ -1651,6 +1695,7 @@ export class CloudBuildClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.listBuildTriggers(request, options, callback);
}

Expand Down Expand Up @@ -1687,6 +1732,7 @@ export class CloudBuildClient {
request = request || {};
options = options || {};
const callSettings = new gax.CallSettings(options);
this.initialize();
return this._descriptors.page.listBuildTriggers.createStream(
this._innerApiCalls.listBuildTriggers as gax.GaxCall,
request,
Expand All @@ -1700,8 +1746,9 @@ export class CloudBuildClient {
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void> {
this.initialize();
if (!this._terminated) {
return this.cloudBuildStub.then(stub => {
return this.cloudBuildStub!.then(stub => {
this._terminated = true;
stub.close();
});
Expand Down
7 changes: 4 additions & 3 deletions packages/google-devtools-cloudbuild/synth.metadata
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
{
"updateTime": "2020-02-29T19:14:13.934361Z",
"updateTime": "2020-03-05T23:03:38.966192Z",
"sources": [
{
"git": {
"name": "googleapis",
"remote": "https://github.com/googleapis/googleapis.git",
"sha": "83c6f84035ee0f80eaa44d8b688a010461cc4080",
"internalRef": "297918498"
"sha": "f0b581b5bdf803e45201ecdb3688b60e381628a8",
"internalRef": "299181282",
"log": "f0b581b5bdf803e45201ecdb3688b60e381628a8\nfix: recommendationengine/v1beta1 update some comments\n\nPiperOrigin-RevId: 299181282\n\n10e9a0a833dc85ff8f05b2c67ebe5ac785fe04ff\nbuild: add generated BUILD file for Routes Preferred API\n\nPiperOrigin-RevId: 299164808\n\n86738c956a8238d7c77f729be78b0ed887a6c913\npublish v1p1beta1: update with absolute address in comments\n\nPiperOrigin-RevId: 299152383\n\n73d9f2ad4591de45c2e1f352bc99d70cbd2a6d95\npublish v1: update with absolute address in comments\n\nPiperOrigin-RevId: 299147194\n\nd2158f24cb77b0b0ccfe68af784c6a628705e3c6\npublish v1beta2: update with absolute address in comments\n\nPiperOrigin-RevId: 299147086\n\n7fca61292c11b4cd5b352cee1a50bf88819dd63b\npublish v1p2beta1: update with absolute address in comments\n\nPiperOrigin-RevId: 299146903\n\n583b7321624736e2c490e328f4b1957335779295\npublish v1p3beta1: update with absolute address in comments\n\nPiperOrigin-RevId: 299146674\n\n638253bf86d1ce1c314108a089b7351440c2f0bf\nfix: add java_multiple_files option for automl text_sentiment.proto\n\nPiperOrigin-RevId: 298971070\n\n373d655703bf914fb8b0b1cc4071d772bac0e0d1\nUpdate Recs AI Beta public bazel file\n\nPiperOrigin-RevId: 298961623\n\ndcc5d00fc8a8d8b56f16194d7c682027b2c66a3b\nfix: add java_multiple_files option for automl classification.proto\n\nPiperOrigin-RevId: 298953301\n\na3f791827266f3496a6a5201d58adc4bb265c2a3\nchore: automl/v1 publish annotations and retry config\n\nPiperOrigin-RevId: 298942178\n\n01c681586d8d6dbd60155289b587aee678530bd9\nMark return_immediately in PullRequest deprecated.\n\nPiperOrigin-RevId: 298893281\n\nc9f5e9c4bfed54bbd09227e990e7bded5f90f31c\nRemove out of date documentation for predicate support on the Storage API\n\nPiperOrigin-RevId: 298883309\n\nfd5b3b8238d783b04692a113ffe07c0363f5de0f\ngenerate webrisk v1 proto\n\nPiperOrigin-RevId: 298847934\n\n541b1ded4abadcc38e8178680b0677f65594ea6f\nUpdate cloud asset api v1p4beta1.\n\nPiperOrigin-RevId: 298686266\n\nc0d171acecb4f5b0bfd2c4ca34fc54716574e300\n Updated to include the Notification v1 API.\n\nPiperOrigin-RevId: 298652775\n\n2346a9186c0bff2c9cc439f2459d558068637e05\nAdd Service Directory v1beta1 protos and configs\n\nPiperOrigin-RevId: 298625638\n\na78ed801b82a5c6d9c5368e24b1412212e541bb7\nPublishing v3 protos and configs.\n\nPiperOrigin-RevId: 298607357\n\n4a180bfff8a21645b3a935c2756e8d6ab18a74e0\nautoml/v1beta1 publish proto updates\n\nPiperOrigin-RevId: 298484782\n\n6de6e938b7df1cd62396563a067334abeedb9676\nchore: use the latest gapic-generator and protoc-java-resource-name-plugin in Bazel workspace.\n\nPiperOrigin-RevId: 298474513\n\n244ab2b83a82076a1fa7be63b7e0671af73f5c02\nAdds service config definition for bigqueryreservation v1\n\nPiperOrigin-RevId: 298455048\n\n"
}
},
{
Expand Down
Loading

0 comments on commit 1f2a22e

Please sign in to comment.