From 29f77ce3d2e002d8598b95c65c20172149c7e008 Mon Sep 17 00:00:00 2001 From: Ali Ijaz Sheikh Date: Tue, 16 Jun 2015 21:10:24 -0700 Subject: [PATCH] cache auth client The authClient from the google-auth-library ought to be cached. Otherwise we end up creating a new AuthClient on each request which ends up fetching fresh credentials on every API request. This can potentially double the latency of each API request. --- lib/common/util.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/lib/common/util.js b/lib/common/util.js index 5a1d4a7030f..0d25bb8aebb 100644 --- a/lib/common/util.js +++ b/lib/common/util.js @@ -468,6 +468,8 @@ util.shouldRetryRequest = shouldRetryRequest; * for authenticating API requests. * * @param {object} config - Configuration object. + * @param {object=} config.authClient - AuthClient object. If not provided, + * it will be created and cached here. * @param {object=} config.credentials - Credentials object. * @param {string=} config.email - Account email address, required for PEM/P12 * usage. @@ -476,6 +478,12 @@ util.shouldRetryRequest = shouldRetryRequest; * @param {function} callback - The callback function. */ function getAuthClient(config, callback) { + if (config.authClient) { + setImmediate(function() { + callback(null, config.authClient); + }); + return; + } var googleAuth = new GoogleAuth(); if (config.keyFile) { @@ -500,6 +508,7 @@ function getAuthClient(config, callback) { authClient = authClient.createScoped(config.scopes); } + config.authClient = authClient; callback(null, authClient); } } @@ -510,6 +519,8 @@ util.getAuthClient = getAuthClient; * Authenticate a request by extending its headers object with an access token. * * @param {object} config - Configuration object. + * @param {object=} config.authClient - AuthClient object. If not provided, + * it will be created and cached here. * @param {object=} config.credentials - Credentials object. * @param {string=} config.email - Account email address, required for PEM/P12 * usage. @@ -563,6 +574,8 @@ util.authorizeRequest = authorizeRequest; * response is related to rate limits or certain intermittent server errors. * We will exponentially backoff subsequent requests by default. (default: * true) + * @param {object=} config.authClient - AuthClient object. If not provided, + * it will be created and cached here. * @param {object=} config.credentials - Credentials object. * @param {boolean=} config.customEndpoint - If true, just return the provided * request options. Default: false.