Skip to content

Commit

Permalink
feat: deferred client initialization (#384)
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 and sofisl committed Oct 13, 2022
1 parent 124fbb5 commit a84e4d8
Show file tree
Hide file tree
Showing 5 changed files with 190 additions and 58 deletions.
73 changes: 53 additions & 20 deletions packages/google-cloud-language/src/v1/language_service_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,13 @@ export class LanguageServiceClient {
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;
languageServiceStub: Promise<{[name: string]: Function}>;
languageServiceStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of LanguageServiceClient.
Expand All @@ -66,8 +71,6 @@ export class LanguageServiceClient {
* 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 @@ -97,25 +100,28 @@ export class LanguageServiceClient {
// 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 LanguageServiceClient).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 @@ -131,12 +137,12 @@ export class LanguageServiceClient {
'protos',
'protos.json'
);
const protos = gaxGrpc.loadProto(
this._protos = this._gaxGrpc.loadProto(
opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath
);

// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings(
this._defaults = this._gaxGrpc.constructSettings(
'google.cloud.language.v1.LanguageService',
gapicConfig as gax.ClientConfig,
opts.clientConfig || {},
Expand All @@ -147,17 +153,35 @@ export class LanguageServiceClient {
// 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.languageServiceStub) {
return this.languageServiceStub;
}

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

// Iterate over each of the methods that the service provides
Expand All @@ -184,9 +208,9 @@ export class LanguageServiceClient {
}
);

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

return this.languageServiceStub;
}

/**
Expand Down Expand Up @@ -320,6 +346,7 @@ export class LanguageServiceClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.analyzeSentiment(request, options, callback);
}
analyzeEntities(
Expand Down Expand Up @@ -389,6 +416,7 @@ export class LanguageServiceClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.analyzeEntities(request, options, callback);
}
analyzeEntitySentiment(
Expand All @@ -415,7 +443,7 @@ export class LanguageServiceClient {
>
): void;
/**
* Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] in the text and analyzes
* Finds entities, similar to {@link google.cloud.language.v1.LanguageService.AnalyzeEntities|AnalyzeEntities} in the text and analyzes
* sentiment associated with each entity and its mentions.
*
* @param {Object} request
Expand Down Expand Up @@ -465,6 +493,7 @@ export class LanguageServiceClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.analyzeEntitySentiment(
request,
options,
Expand Down Expand Up @@ -538,6 +567,7 @@ export class LanguageServiceClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.analyzeSyntax(request, options, callback);
}
classifyText(
Expand Down Expand Up @@ -602,6 +632,7 @@ export class LanguageServiceClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.classifyText(request, options, callback);
}
annotateText(
Expand Down Expand Up @@ -671,6 +702,7 @@ export class LanguageServiceClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.annotateText(request, options, callback);
}

Expand All @@ -680,8 +712,9 @@ export class LanguageServiceClient {
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void> {
this.initialize();
if (!this._terminated) {
return this.languageServiceStub.then(stub => {
return this.languageServiceStub!.then(stub => {
this._terminated = true;
stub.close();
});
Expand Down
Loading

0 comments on commit a84e4d8

Please sign in to comment.