Skip to content

Commit

Permalink
feat: deferred client initialization (#359)
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 635c543 commit 518e1b0
Show file tree
Hide file tree
Showing 5 changed files with 148 additions and 42 deletions.
67 changes: 48 additions & 19 deletions packages/google-cloud-texttospeech/src/v1/text_to_speech_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,13 @@ export class TextToSpeechClient {
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;
textToSpeechStub: Promise<{[name: string]: Function}>;
textToSpeechStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of TextToSpeechClient.
Expand All @@ -65,8 +70,6 @@ export class TextToSpeechClient {
* 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 @@ -96,25 +99,28 @@ export class TextToSpeechClient {
// 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 TextToSpeechClient).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 @@ -130,12 +136,12 @@ export class TextToSpeechClient {
'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.texttospeech.v1.TextToSpeech',
gapicConfig as gax.ClientConfig,
opts.clientConfig || {},
Expand All @@ -146,17 +152,35 @@ export class TextToSpeechClient {
// 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.textToSpeechStub) {
return this.textToSpeechStub;
}

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

// Iterate over each of the methods that the service provides
Expand All @@ -176,9 +200,9 @@ export class TextToSpeechClient {
}
);

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

return this.textToSpeechStub;
}

/**
Expand Down Expand Up @@ -314,6 +340,7 @@ export class TextToSpeechClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.listVoices(request, options, callback);
}
synthesizeSpeech(
Expand Down Expand Up @@ -392,6 +419,7 @@ export class TextToSpeechClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.synthesizeSpeech(request, options, callback);
}

Expand All @@ -401,8 +429,9 @@ export class TextToSpeechClient {
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void> {
this.initialize();
if (!this._terminated) {
return this.textToSpeechStub.then(stub => {
return this.textToSpeechStub!.then(stub => {
this._terminated = true;
stub.close();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,13 @@ export class TextToSpeechClient {
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;
textToSpeechStub: Promise<{[name: string]: Function}>;
textToSpeechStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of TextToSpeechClient.
Expand All @@ -65,8 +70,6 @@ export class TextToSpeechClient {
* 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 @@ -96,25 +99,28 @@ export class TextToSpeechClient {
// 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 TextToSpeechClient).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 @@ -130,12 +136,12 @@ export class TextToSpeechClient {
'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.texttospeech.v1beta1.TextToSpeech',
gapicConfig as gax.ClientConfig,
opts.clientConfig || {},
Expand All @@ -146,17 +152,35 @@ export class TextToSpeechClient {
// 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.textToSpeechStub) {
return this.textToSpeechStub;
}

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

// Iterate over each of the methods that the service provides
Expand All @@ -176,9 +200,9 @@ export class TextToSpeechClient {
}
);

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

return this.textToSpeechStub;
}

/**
Expand Down Expand Up @@ -322,6 +348,7 @@ export class TextToSpeechClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.listVoices(request, options, callback);
}
synthesizeSpeech(
Expand Down Expand Up @@ -400,6 +427,7 @@ export class TextToSpeechClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.synthesizeSpeech(request, options, callback);
}

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

0 comments on commit 518e1b0

Please sign in to comment.