Skip to content

Commit 8219833

Browse files
kolodnystephenplusplus
authored andcommitted
Cache proto objects (#2755)
1 parent b8a00b2 commit 8219833

File tree

2 files changed

+44
-6
lines changed

2 files changed

+44
-6
lines changed

packages/common-grpc/src/service.js

+21-6
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ var Service = require('@google-cloud/common').Service;
3131
var through = require('through2');
3232
var util = require('@google-cloud/common').util;
3333

34+
/**
35+
* @const {object} - A cache of proto objects.
36+
* @private
37+
*/
38+
var protoObjectCache = {};
39+
3440
/**
3541
* @const {object} - A map of protobuf codes to HTTP status codes.
3642
* @private
@@ -752,13 +758,22 @@ GrpcService.prototype.loadProtoFile_ = function(protoConfig, config) {
752758
};
753759
}
754760

755-
var services = grpc.load({
756-
root: config.protosDir,
757-
file: protoConfig.path
758-
}, 'proto', grpcOpts);
761+
var protoObjectCacheKey = [
762+
config.protosDir,
763+
protoConfig.path,
764+
protoConfig.service
765+
].join('$');
766+
767+
if (!protoObjectCache[protoObjectCacheKey]) {
768+
var services = grpc.load({
769+
root: config.protosDir,
770+
file: protoConfig.path
771+
}, 'proto', grpcOpts);
772+
var service = dotProp.get(services.google, protoConfig.service);
773+
protoObjectCache[protoObjectCacheKey] = service;
774+
}
759775

760-
var service = dotProp.get(services.google, protoConfig.service);
761-
return service;
776+
return protoObjectCache[protoObjectCacheKey];
762777
};
763778

764779
/**

packages/common-grpc/test/service.js

+23
Original file line numberDiff line numberDiff line change
@@ -1780,6 +1780,29 @@ describe('GrpcService', function() {
17801780
assert.strictEqual(service, fakeServices.google.FakeService);
17811781
});
17821782

1783+
it('should cache the expensive proto object creation', function() {
1784+
var protoConfig = {
1785+
path: '/root/dir/path',
1786+
service: 'FakeService'
1787+
};
1788+
1789+
var mainConfig = {
1790+
service: 'OtherFakeService',
1791+
apiVersion: 'v2'
1792+
};
1793+
1794+
var gprcLoadCalled = 0;
1795+
grpcLoadOverride = function() {
1796+
gprcLoadCalled++;
1797+
return fakeServices;
1798+
};
1799+
1800+
var service1 = grpcService.loadProtoFile_(protoConfig, mainConfig);
1801+
var service2 = grpcService.loadProtoFile_(protoConfig, mainConfig);
1802+
assert.strictEqual(service1, service2);
1803+
assert.strictEqual(gprcLoadCalled, 1);
1804+
});
1805+
17831806
it('should return the services object if invalid version', function() {
17841807
var fakeProtoConfig = {
17851808
path: '/root/dir/path',

0 commit comments

Comments
 (0)