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 (#283)
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] authored Mar 6, 2020
1 parent 3d34bd4 commit b70a193
Show file tree
Hide file tree
Showing 3 changed files with 168 additions and 28 deletions.
96 changes: 72 additions & 24 deletions src/v1/device_manager_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,13 @@ export class DeviceManagerClient {
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;
deviceManagerStub: Promise<{[name: string]: Function}>;
deviceManagerStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of DeviceManagerClient.
Expand All @@ -69,8 +74,6 @@ export class DeviceManagerClient {
* 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 @@ -100,25 +103,28 @@ export class DeviceManagerClient {
// 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 DeviceManagerClient).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 @@ -134,21 +140,21 @@ export class DeviceManagerClient {
'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 = {
devicePathTemplate: new gaxModule.PathTemplate(
devicePathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/locations/{location}/registries/{registry}/devices/{device}'
),
locationPathTemplate: new gaxModule.PathTemplate(
locationPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/locations/{location}'
),
registryPathTemplate: new gaxModule.PathTemplate(
registryPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/locations/{location}/registries/{registry}'
),
};
Expand All @@ -157,20 +163,20 @@ export class DeviceManagerClient {
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this._descriptors.page = {
listDeviceRegistries: new gaxModule.PageDescriptor(
listDeviceRegistries: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'deviceRegistries'
),
listDevices: new gaxModule.PageDescriptor(
listDevices: new this._gaxModule.PageDescriptor(
'pageToken',
'nextPageToken',
'devices'
),
};

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

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

// Iterate over each of the methods that the service provides
Expand Down Expand Up @@ -231,9 +255,9 @@ export class DeviceManagerClient {
}
);

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

return this.deviceManagerStub;
}

/**
Expand Down Expand Up @@ -377,6 +403,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.createDeviceRegistry(request, options, callback);
}
getDeviceRegistry(
Expand Down Expand Up @@ -449,6 +476,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.getDeviceRegistry(request, options, callback);
}
updateDeviceRegistry(
Expand Down Expand Up @@ -529,6 +557,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
'device_registry.name': request.deviceRegistry!.name || '',
});
this.initialize();
return this._innerApiCalls.updateDeviceRegistry(request, options, callback);
}
deleteDeviceRegistry(
Expand Down Expand Up @@ -602,6 +631,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.deleteDeviceRegistry(request, options, callback);
}
createDevice(
Expand Down Expand Up @@ -679,6 +709,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.createDevice(request, options, callback);
}
getDevice(
Expand Down Expand Up @@ -755,6 +786,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.getDevice(request, options, callback);
}
updateDevice(
Expand Down Expand Up @@ -834,6 +866,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
'device.name': request.device!.name || '',
});
this.initialize();
return this._innerApiCalls.updateDevice(request, options, callback);
}
deleteDevice(
Expand Down Expand Up @@ -907,6 +940,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.deleteDevice(request, options, callback);
}
modifyCloudToDeviceConfig(
Expand Down Expand Up @@ -999,6 +1033,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.modifyCloudToDeviceConfig(
request,
options,
Expand Down Expand Up @@ -1090,6 +1125,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.listDeviceConfigVersions(
request,
options,
Expand Down Expand Up @@ -1172,6 +1208,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.listDeviceStates(request, options, callback);
}
setIamPolicy(
Expand Down Expand Up @@ -1242,6 +1279,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
resource: request.resource || '',
});
this.initialize();
return this._innerApiCalls.setIamPolicy(request, options, callback);
}
getIamPolicy(
Expand Down Expand Up @@ -1313,6 +1351,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
resource: request.resource || '',
});
this.initialize();
return this._innerApiCalls.getIamPolicy(request, options, callback);
}
testIamPermissions(
Expand Down Expand Up @@ -1384,6 +1423,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
resource: request.resource || '',
});
this.initialize();
return this._innerApiCalls.testIamPermissions(request, options, callback);
}
sendCommandToDevice(
Expand Down Expand Up @@ -1478,6 +1518,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.sendCommandToDevice(request, options, callback);
}
bindDeviceToGateway(
Expand Down Expand Up @@ -1558,6 +1599,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.bindDeviceToGateway(request, options, callback);
}
unbindDeviceFromGateway(
Expand Down Expand Up @@ -1646,6 +1688,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.unbindDeviceFromGateway(
request,
options,
Expand Down Expand Up @@ -1744,6 +1787,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.listDeviceRegistries(request, options, callback);
}

Expand Down Expand Up @@ -1793,6 +1837,7 @@ export class DeviceManagerClient {
parent: request.parent || '',
});
const callSettings = new gax.CallSettings(options);
this.initialize();
return this._descriptors.page.listDeviceRegistries.createStream(
this._innerApiCalls.listDeviceRegistries as gax.GaxCall,
request,
Expand Down Expand Up @@ -1902,6 +1947,7 @@ export class DeviceManagerClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.listDevices(request, options, callback);
}

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

0 comments on commit b70a193

Please sign in to comment.