Skip to content
This repository has been archived by the owner on Dec 19, 2023. It is now read-only.

feat: deferred client initialization #359

Merged
merged 1 commit into from
Mar 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
67 changes: 48 additions & 19 deletions 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
67 changes: 48 additions & 19 deletions src/v1beta1/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.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