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

Commit

Permalink
feat: deferred client initialization (#378)
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 b155b00 commit 61eca6a
Show file tree
Hide file tree
Showing 13 changed files with 808 additions and 292 deletions.
131 changes: 83 additions & 48 deletions src/v3/alert_policy_service_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,13 @@ export class AlertPolicyServiceClient {
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;
alertPolicyServiceStub: Promise<{[name: string]: Function}>;
alertPolicyServiceStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of AlertPolicyServiceClient.
Expand All @@ -77,8 +82,6 @@ export class AlertPolicyServiceClient {
* 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 @@ -108,25 +111,28 @@ export class AlertPolicyServiceClient {
// 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 AlertPolicyServiceClient).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 @@ -142,85 +148,87 @@ export class AlertPolicyServiceClient {
'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 = {
folderAlertPolicyPathTemplate: new gaxModule.PathTemplate(
folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/alertPolicies/{alert_policy}'
),
folderAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate(
folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}'
),
folderChannelDescriptorPathTemplate: new gaxModule.PathTemplate(
folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}'
),
folderGroupPathTemplate: new gaxModule.PathTemplate(
folderGroupPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/groups/{group}'
),
folderNotificationChannelPathTemplate: new gaxModule.PathTemplate(
folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/notificationChannels/{notification_channel}'
),
folderServicePathTemplate: new gaxModule.PathTemplate(
folderServicePathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/services/{service}'
),
folderServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate(
folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}'
),
folderUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate(
folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}'
),
organizationAlertPolicyPathTemplate: new gaxModule.PathTemplate(
organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/alertPolicies/{alert_policy}'
),
organizationAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate(
organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}'
),
organizationChannelDescriptorPathTemplate: new gaxModule.PathTemplate(
organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}'
),
organizationGroupPathTemplate: new gaxModule.PathTemplate(
organizationGroupPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/groups/{group}'
),
organizationNotificationChannelPathTemplate: new gaxModule.PathTemplate(
organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/notificationChannels/{notification_channel}'
),
organizationServicePathTemplate: new gaxModule.PathTemplate(
organizationServicePathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/services/{service}'
),
organizationServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate(
organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}'
),
organizationUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate(
organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}'
),
projectPathTemplate: new gaxModule.PathTemplate('projects/{project}'),
projectAlertPolicyPathTemplate: new gaxModule.PathTemplate(
projectPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}'
),
projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/alertPolicies/{alert_policy}'
),
projectAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate(
projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}'
),
projectChannelDescriptorPathTemplate: new gaxModule.PathTemplate(
projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/notificationChannelDescriptors/{channel_descriptor}'
),
projectGroupPathTemplate: new gaxModule.PathTemplate(
projectGroupPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/groups/{group}'
),
projectNotificationChannelPathTemplate: new gaxModule.PathTemplate(
projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/notificationChannels/{notification_channel}'
),
projectServicePathTemplate: new gaxModule.PathTemplate(
projectServicePathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/services/{service}'
),
projectServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate(
projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}'
),
projectUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate(
projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/uptimeCheckConfigs/{uptime_check_config}'
),
};
Expand All @@ -229,15 +237,15 @@ export class AlertPolicyServiceClient {
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this._descriptors.page = {
listAlertPolicies: new gaxModule.PageDescriptor(
listAlertPolicies: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'alertPolicies'
),
};

// Put together the default options sent with requests.
const defaults = gaxGrpc.constructSettings(
this._defaults = this._gaxGrpc.constructSettings(
'google.monitoring.v3.AlertPolicyService',
gapicConfig as gax.ClientConfig,
opts.clientConfig || {},
Expand All @@ -248,17 +256,35 @@ export class AlertPolicyServiceClient {
// 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.alertPolicyServiceStub) {
return this.alertPolicyServiceStub;
}

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

// Iterate over each of the methods that the service provides
Expand All @@ -284,9 +310,9 @@ export class AlertPolicyServiceClient {
}
);

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

return this.alertPolicyServiceStub;
}

/**
Expand Down Expand Up @@ -427,6 +455,7 @@ export class AlertPolicyServiceClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.getAlertPolicy(request, options, callback);
}
createAlertPolicy(
Expand Down Expand Up @@ -512,6 +541,7 @@ export class AlertPolicyServiceClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.createAlertPolicy(request, options, callback);
}
deleteAlertPolicy(
Expand Down Expand Up @@ -543,7 +573,7 @@ export class AlertPolicyServiceClient {
*
* projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID]
*
* For more information, see [AlertPolicy][google.monitoring.v3.AlertPolicy].
* For more information, see {@link google.monitoring.v3.AlertPolicy|AlertPolicy}.
* @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 @@ -588,6 +618,7 @@ export class AlertPolicyServiceClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.deleteAlertPolicy(request, options, callback);
}
updateAlertPolicy(
Expand Down Expand Up @@ -688,6 +719,7 @@ export class AlertPolicyServiceClient {
] = gax.routingHeader.fromParams({
'alert_policy.name': request.alertPolicy!.name || '',
});
this.initialize();
return this._innerApiCalls.updateAlertPolicy(request, options, callback);
}

Expand Down Expand Up @@ -723,7 +755,7 @@ export class AlertPolicyServiceClient {
* Note that this field names the parent container in which the alerting
* policies to be listed are stored. To retrieve a single alerting policy
* by name, use the
* [GetAlertPolicy][google.monitoring.v3.AlertPolicyService.GetAlertPolicy]
* {@link google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy}
* operation, instead.
* @param {string} request.filter
* If provided, this field specifies the criteria that must be met by
Expand Down Expand Up @@ -799,6 +831,7 @@ export class AlertPolicyServiceClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.listAlertPolicies(request, options, callback);
}

Expand All @@ -825,7 +858,7 @@ export class AlertPolicyServiceClient {
* Note that this field names the parent container in which the alerting
* policies to be listed are stored. To retrieve a single alerting policy
* by name, use the
* [GetAlertPolicy][google.monitoring.v3.AlertPolicyService.GetAlertPolicy]
* {@link google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy}
* operation, instead.
* @param {string} request.filter
* If provided, this field specifies the criteria that must be met by
Expand Down Expand Up @@ -865,6 +898,7 @@ export class AlertPolicyServiceClient {
name: request.name || '',
});
const callSettings = new gax.CallSettings(options);
this.initialize();
return this._descriptors.page.listAlertPolicies.createStream(
this._innerApiCalls.listAlertPolicies as gax.GaxCall,
request,
Expand Down Expand Up @@ -2075,8 +2109,9 @@ export class AlertPolicyServiceClient {
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void> {
this.initialize();
if (!this._terminated) {
return this.alertPolicyServiceStub.then(stub => {
return this.alertPolicyServiceStub!.then(stub => {
this._terminated = true;
stub.close();
});
Expand Down
Loading

0 comments on commit 61eca6a

Please sign in to comment.