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

feat: deferred client initialization #323

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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 57 additions & 24 deletions src/v1/autoscaling_policy_service_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,13 @@ export class AutoscalingPolicyServiceClient {
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;
autoscalingPolicyServiceStub: Promise<{[name: string]: Function}>;
autoscalingPolicyServiceStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of AutoscalingPolicyServiceClient.
Expand All @@ -62,8 +67,6 @@ export class AutoscalingPolicyServiceClient {
* 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 @@ -91,28 +94,31 @@ export class AutoscalingPolicyServiceClient {
// 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 AutoscalingPolicyServiceClient).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}`,
`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 @@ -122,7 +128,7 @@ export class AutoscalingPolicyServiceClient {
// For browsers, pass the JSON content.

const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json');
const protos = gaxGrpc.loadProto(
this._protos = this._gaxGrpc.loadProto(
opts.fallback ?
require("../../protos/protos.json") :
nodejsProtoPath
Expand All @@ -132,16 +138,16 @@ export class AutoscalingPolicyServiceClient {
// identifiers to uniquely identify resources within the API.
// Create useful helper objects for these.
this._pathTemplates = {
projectLocationAutoscalingPolicyPathTemplate: new gaxModule.PathTemplate(
projectLocationAutoscalingPolicyPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}'
),
projectLocationWorkflowTemplatePathTemplate: new gaxModule.PathTemplate(
projectLocationWorkflowTemplatePathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/locations/{location}/workflowTemplates/{workflow_template}'
),
projectRegionAutoscalingPolicyPathTemplate: new gaxModule.PathTemplate(
projectRegionAutoscalingPolicyPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/regions/{region}/autoscalingPolicies/{autoscaling_policy}'
),
projectRegionWorkflowTemplatePathTemplate: new gaxModule.PathTemplate(
projectRegionWorkflowTemplatePathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/regions/{region}/workflowTemplates/{workflow_template}'
),
};
Expand All @@ -151,27 +157,45 @@ export class AutoscalingPolicyServiceClient {
// pages). Denote the keys used for pagination and results.
this._descriptors.page = {
listAutoscalingPolicies:
new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'policies')
new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'policies')
};

// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings(
this._defaults = this._gaxGrpc.constructSettings(
'google.cloud.dataproc.v1.AutoscalingPolicyService', gapicConfig as gax.ClientConfig,
opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')});

// Set up a dictionary of "inner API calls"; the core implementation
// 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.autoscalingPolicyServiceStub) {
return this.autoscalingPolicyServiceStub;
}

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

// Iterate over each of the methods that the service provides
// and create an API call method for each.
Expand All @@ -190,9 +214,9 @@ export class AutoscalingPolicyServiceClient {
throw err;
});

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

return this.autoscalingPolicyServiceStub;
}

/**
Expand Down Expand Up @@ -327,6 +353,7 @@ export class AutoscalingPolicyServiceClient {
] = gax.routingHeader.fromParams({
'parent': request.parent || '',
});
this.initialize();
return this._innerApiCalls.createAutoscalingPolicy(request, options, callback);
}
updateAutoscalingPolicy(
Expand Down Expand Up @@ -389,6 +416,7 @@ export class AutoscalingPolicyServiceClient {
] = gax.routingHeader.fromParams({
'policy.name': request.policy!.name || '',
});
this.initialize();
return this._innerApiCalls.updateAutoscalingPolicy(request, options, callback);
}
getAutoscalingPolicy(
Expand Down Expand Up @@ -457,6 +485,7 @@ export class AutoscalingPolicyServiceClient {
] = gax.routingHeader.fromParams({
'name': request.name || '',
});
this.initialize();
return this._innerApiCalls.getAutoscalingPolicy(request, options, callback);
}
deleteAutoscalingPolicy(
Expand Down Expand Up @@ -526,6 +555,7 @@ export class AutoscalingPolicyServiceClient {
] = gax.routingHeader.fromParams({
'name': request.name || '',
});
this.initialize();
return this._innerApiCalls.deleteAutoscalingPolicy(request, options, callback);
}

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

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