Skip to content

Commit

Permalink
feat: deferred client initialization (#281)
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 2b7b17a commit 7b9ec87
Show file tree
Hide file tree
Showing 9 changed files with 358 additions and 100 deletions.
92 changes: 64 additions & 28 deletions packages/google-cloud-asset/src/v1/asset_service_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,14 @@ export class AssetServiceClient {
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;
operationsClient: gax.OperationsClient;
assetServiceStub: Promise<{[name: string]: Function}>;
assetServiceStub?: Promise<{[name: string]: Function}>;

/**
* Construct an instance of AssetServiceClient.
Expand All @@ -68,8 +73,6 @@ export class AssetServiceClient {
* 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 @@ -99,25 +102,28 @@ export class AssetServiceClient {
// 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 AssetServiceClient).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 @@ -133,21 +139,21 @@ export class AssetServiceClient {
'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 = {
folderFeedPathTemplate: new gaxModule.PathTemplate(
folderFeedPathTemplate: new this._gaxModule.PathTemplate(
'folders/{folder}/feeds/{feed}'
),
organizationFeedPathTemplate: new gaxModule.PathTemplate(
organizationFeedPathTemplate: new this._gaxModule.PathTemplate(
'organizations/{organization}/feeds/{feed}'
),
projectFeedPathTemplate: new gaxModule.PathTemplate(
projectFeedPathTemplate: new this._gaxModule.PathTemplate(
'projects/{project}/feeds/{feed}'
),
};
Expand All @@ -156,13 +162,15 @@ export class AssetServiceClient {
// 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 exportAssetsResponse = protoFilesRoot.lookup(
Expand All @@ -173,15 +181,15 @@ export class AssetServiceClient {
) as gax.protobuf.Type;

this._descriptors.longrunning = {
exportAssets: new gaxModule.LongrunningDescriptor(
exportAssets: new this._gaxModule.LongrunningDescriptor(
this.operationsClient,
exportAssetsResponse.decode.bind(exportAssetsResponse),
exportAssetsMetadata.decode.bind(exportAssetsMetadata)
),
};

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

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

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

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

return this.assetServiceStub;
}

/**
Expand Down Expand Up @@ -404,6 +432,7 @@ export class AssetServiceClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.batchGetAssetsHistory(
request,
options,
Expand Down Expand Up @@ -493,6 +522,7 @@ export class AssetServiceClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.createFeed(request, options, callback);
}
getFeed(
Expand Down Expand Up @@ -567,6 +597,7 @@ export class AssetServiceClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.getFeed(request, options, callback);
}
listFeeds(
Expand Down Expand Up @@ -640,6 +671,7 @@ export class AssetServiceClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.listFeeds(request, options, callback);
}
updateFeed(
Expand Down Expand Up @@ -719,6 +751,7 @@ export class AssetServiceClient {
] = gax.routingHeader.fromParams({
'feed.name': request.feed!.name || '',
});
this.initialize();
return this._innerApiCalls.updateFeed(request, options, callback);
}
deleteFeed(
Expand Down Expand Up @@ -793,6 +826,7 @@ export class AssetServiceClient {
] = gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this._innerApiCalls.deleteFeed(request, options, callback);
}

Expand Down Expand Up @@ -824,7 +858,7 @@ export class AssetServiceClient {
/**
* Exports assets with time and resource types to a given Cloud Storage
* location. The output format is newline-delimited JSON.
* This API implements the [google.longrunning.Operation][google.longrunning.Operation] API allowing you
* This API implements the {@link google.longrunning.Operation|google.longrunning.Operation} API allowing you
* to keep track of the export.
*
* @param {Object} request
Expand Down Expand Up @@ -904,6 +938,7 @@ export class AssetServiceClient {
] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
this.initialize();
return this._innerApiCalls.exportAssets(request, options, callback);
}
// --------------------
Expand Down Expand Up @@ -1032,8 +1067,9 @@ export class AssetServiceClient {
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void> {
this.initialize();
if (!this._terminated) {
return this.assetServiceStub.then(stub => {
return this.assetServiceStub!.then(stub => {
this._terminated = true;
stub.close();
});
Expand Down
Loading

0 comments on commit 7b9ec87

Please sign in to comment.