Skip to content

Commit

Permalink
feat: deferred client initialization (#548)
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 7c61f12 commit 14143d5
Show file tree
Hide file tree
Showing 6 changed files with 179 additions and 54 deletions.
82 changes: 57 additions & 25 deletions packages/google-cloud-speech/src/v1/speech_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,14 @@ export class SpeechClient {
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;
speechStub: Promise<{[name: string]: Function}>;
speechStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of SpeechClient.
Expand All @@ -67,8 +72,6 @@ export class SpeechClient {
* 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 @@ -98,25 +101,28 @@ export class SpeechClient {
// 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 SpeechClient).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 @@ -132,14 +138,14 @@ export class SpeechClient {
'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 provide streaming responses.
// Provide descriptors for these.
this._descriptors.stream = {
streamingRecognize: new gaxModule.StreamDescriptor(
streamingRecognize: new this._gaxModule.StreamDescriptor(
gax.StreamType.BIDI_STREAMING
),
};
Expand All @@ -148,13 +154,15 @@ export class SpeechClient {
// 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 longRunningRecognizeResponse = protoFilesRoot.lookup(
Expand All @@ -165,15 +173,15 @@ export class SpeechClient {
) as gax.protobuf.Type;

this._descriptors.longrunning = {
longRunningRecognize: new gaxModule.LongrunningDescriptor(
longRunningRecognize: new this._gaxModule.LongrunningDescriptor(
this.operationsClient,
longRunningRecognizeResponse.decode.bind(longRunningRecognizeResponse),
longRunningRecognizeMetadata.decode.bind(longRunningRecognizeMetadata)
),
};

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

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

// Iterate over each of the methods that the service provides
Expand All @@ -218,9 +244,9 @@ export class SpeechClient {
}
);

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

return this.speechStub;
}

/**
Expand Down Expand Up @@ -352,6 +380,7 @@ export class SpeechClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.recognize(request, options, callback);
}

Expand All @@ -367,6 +396,7 @@ export class SpeechClient {
* will emit objects representing [StreamingRecognizeResponse]{@link google.cloud.speech.v1.StreamingRecognizeResponse} on 'data' event asynchronously.
*/
_streamingRecognize(options?: gax.CallOptions): gax.CancellableStream {
this.initialize();
return this._innerApiCalls.streamingRecognize(options);
}

Expand Down Expand Up @@ -455,6 +485,7 @@ export class SpeechClient {
options = optionsOrCallback as gax.CallOptions;
}
options = options || {};
this.initialize();
return this._innerApiCalls.longRunningRecognize(request, options, callback);
}

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

0 comments on commit 14143d5

Please sign in to comment.