Skip to content

Commit

Permalink
feat: deferred client initialization (#128)
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 5a1d8dd commit db85e57
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,13 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
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;
recaptchaEnterpriseServiceV1Beta1Stub: Promise<{[name: string]: Function}>;
recaptchaEnterpriseServiceV1Beta1Stub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of RecaptchaEnterpriseServiceV1Beta1Client.
Expand All @@ -69,8 +74,6 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
* 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 @@ -101,26 +104,29 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
// 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 RecaptchaEnterpriseServiceV1Beta1Client).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 @@ -136,36 +142,38 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
'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 = {
assessmentPathTemplate: new gaxModule.PathTemplate(
assessmentPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/assessments/{assessment}'
),
keyPathTemplate: new gaxModule.PathTemplate(
keyPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/keys/{key}'
),
projectPathTemplate: new gaxModule.PathTemplate('projects/{project}'),
projectPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}'
),
};

// 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 = {
listKeys: new gaxModule.PageDescriptor(
listKeys: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'keys'
),
};

// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings(
this._defaults = this._gaxGrpc.constructSettings(
'google.cloud.recaptchaenterprise.v1beta1.RecaptchaEnterpriseServiceV1Beta1',
gapicConfig as gax.ClientConfig,
opts.clientConfig || {},
Expand All @@ -176,18 +184,36 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
// 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.recaptchaEnterpriseServiceV1Beta1Stub) {
return this.recaptchaEnterpriseServiceV1Beta1Stub;
}

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

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

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

return this.recaptchaEnterpriseServiceV1Beta1Stub;
}

/**
Expand Down Expand Up @@ -364,6 +392,7 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.createAssessment(request, options, callback);
}
annotateAssessment(
Expand Down Expand Up @@ -448,6 +477,7 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.annotateAssessment(request, options, callback);
}
createKey(
Expand Down Expand Up @@ -531,6 +561,7 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.createKey(request, options, callback);
}
getKey(
Expand Down Expand Up @@ -612,6 +643,7 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.getKey(request, options, callback);
}
updateKey(
Expand Down Expand Up @@ -695,6 +727,7 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
] = gax.routingHeader.fromParams({
'key.name': request.key!.name || '',
});
this.initialize();
return this._innerApiCalls.updateKey(request, options, callback);
}
deleteKey(
Expand Down Expand Up @@ -776,6 +809,7 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.deleteKey(request, options, callback);
}

Expand Down Expand Up @@ -867,6 +901,7 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.listKeys(request, options, callback);
}

Expand Down Expand Up @@ -913,6 +948,7 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
parent: request.parent || '',
});
const callSettings = new gax.CallSettings(options);
this.initialize();
return this._descriptors.page.listKeys.createStream(
this._innerApiCalls.listKeys as gax.GaxCall,
request,
Expand Down Expand Up @@ -1026,8 +1062,9 @@ export class RecaptchaEnterpriseServiceV1Beta1Client {
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void> {
this.initialize();
if (!this._terminated) {
return this.recaptchaEnterpriseServiceV1Beta1Stub.then(stub => {
return this.recaptchaEnterpriseServiceV1Beta1Stub!.then(stub => {
this._terminated = true;
stub.close();
});
Expand Down
Loading

0 comments on commit db85e57

Please sign in to comment.