Skip to content

Commit

Permalink
feat: deferred client initialization (#171)
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 9e4d28f commit 4870fe1
Show file tree
Hide file tree
Showing 15 changed files with 848 additions and 362 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,13 @@ export class ApplicationServiceClient {
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;
applicationServiceStub: Promise<{[name: string]: Function}>;
applicationServiceStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of ApplicationServiceClient.
Expand All @@ -70,8 +75,6 @@ export class ApplicationServiceClient {
* 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,25 +104,28 @@ export class ApplicationServiceClient {
// 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 ApplicationServiceClient).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 @@ -135,33 +141,33 @@ export class ApplicationServiceClient {
'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 = {
applicationPathTemplate: new gaxModule.PathTemplate(
applicationPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}'
),
profilePathTemplate: new gaxModule.PathTemplate(
profilePathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/tenants/{tenant}/profiles/{profile}'
),
projectCompanyPathTemplate: new gaxModule.PathTemplate(
projectCompanyPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/companies/{company}'
),
projectJobPathTemplate: new gaxModule.PathTemplate(
projectJobPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/jobs/{job}'
),
projectTenantCompanyPathTemplate: new gaxModule.PathTemplate(
projectTenantCompanyPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/tenants/{tenant}/companies/{company}'
),
projectTenantJobPathTemplate: new gaxModule.PathTemplate(
projectTenantJobPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/tenants/{tenant}/jobs/{job}'
),
tenantPathTemplate: new gaxModule.PathTemplate(
tenantPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/tenants/{tenant}'
),
};
Expand All @@ -170,15 +176,15 @@ export class ApplicationServiceClient {
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this._descriptors.page = {
listApplications: new gaxModule.PageDescriptor(
listApplications: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'applications'
),
};

// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings(
this._defaults = this._gaxGrpc.constructSettings(
'google.cloud.talent.v4beta1.ApplicationService',
gapicConfig as gax.ClientConfig,
opts.clientConfig || {},
Expand All @@ -189,17 +195,35 @@ export class ApplicationServiceClient {
// 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.applicationServiceStub) {
return this.applicationServiceStub;
}

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

// Iterate over each of the methods that the service provides
Expand All @@ -225,9 +249,9 @@ export class ApplicationServiceClient {
}
);

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

return this.applicationServiceStub;
}

/**
Expand Down Expand Up @@ -380,6 +406,7 @@ export class ApplicationServiceClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.createApplication(request, options, callback);
}
getApplication(
Expand Down Expand Up @@ -464,6 +491,7 @@ export class ApplicationServiceClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.getApplication(request, options, callback);
}
updateApplication(
Expand Down Expand Up @@ -499,11 +527,11 @@ export class ApplicationServiceClient {
* @param {google.protobuf.FieldMask} request.updateMask
* Strongly recommended for the best service experience.
*
* If [update_mask][google.cloud.talent.v4beta1.UpdateApplicationRequest.update_mask] is provided, only the specified fields in
* [application][google.cloud.talent.v4beta1.UpdateApplicationRequest.application] are updated. Otherwise all the fields are updated.
* If {@link google.cloud.talent.v4beta1.UpdateApplicationRequest.update_mask|update_mask} is provided, only the specified fields in
* {@link google.cloud.talent.v4beta1.UpdateApplicationRequest.application|application} are updated. Otherwise all the fields are updated.
*
* A field mask to specify the application fields to be updated. Only
* top level fields of [Application][google.cloud.talent.v4beta1.Application] are supported.
* top level fields of {@link google.cloud.talent.v4beta1.Application|Application} are supported.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Promise} - The promise which resolves to an array.
Expand Down Expand Up @@ -552,6 +580,7 @@ export class ApplicationServiceClient {
] = gax.routingHeader.fromParams({
'application.name': request.application!.name || '',
});
this.initialize();
return this._innerApiCalls.updateApplication(request, options, callback);
}
deleteApplication(
Expand Down Expand Up @@ -636,6 +665,7 @@ export class ApplicationServiceClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.deleteApplication(request, options, callback);
}

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

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

0 comments on commit 4870fe1

Please sign in to comment.