Skip to content

Commit

Permalink
feat: significantly increase timeout if GCF environment detected (#300)
Browse files Browse the repository at this point in the history
  • Loading branch information
bcoe authored Feb 24, 2020
1 parent 39d86f2 commit 8e507c6
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ async function metadataAccessor<T>(
retryConfig: {noResponseRetries},
params: options.params,
responseType: 'text',
timeout: 3000,
timeout: requestTimeout(),
});
// NOTE: node.js converts all incoming headers to lower case.
if (res.headers[HEADER_NAME.toLowerCase()] !== HEADER_VALUE) {
Expand Down Expand Up @@ -221,3 +221,17 @@ export async function isAvailable() {
export function resetIsAvailableCache() {
cachedIsAvailableResponse = undefined;
}

export function requestTimeout(): number {
// In testing, we were able to reproduce behavior similar to
// https://github.com/googleapis/google-auth-library-nodejs/issues/798
// by making many concurrent network requests. Requests do not actually fail,
// rather they take significantly longer to complete (and we hit our
// default 3000ms timeout).
//
// This logic detects a GCF environment, using the documented environment
// variables K_SERVICE and FUNCTION_NAME:
// https://cloud.google.com/functions/docs/env-var and, in a GCF environment
// eliminates timeouts (by setting the value to 0 to disable).
return process.env.K_SERVICE || process.env.FUNCTION_NAME ? 0 : 3000;
}
16 changes: 16 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -401,3 +401,19 @@ it('resets cache when resetIsAvailableCache() is called', async () => {
primary.done();
assert.strictEqual(isGCE, false);
});

it('returns request timeout of 3000ms, when not GCF', () => {
assert.strictEqual(gcp.requestTimeout(), 3000);
});

it('returns request timeout of 0, when FUNCTION_NAME set', () => {
process.env.FUNCTION_NAME = 'my-function';
assert.strictEqual(gcp.requestTimeout(), 0);
delete process.env.FUNCTION_NAME;
});

it('returns request timeout of 0, when K_SERVICE set', () => {
process.env.K_SERVICE = 'my-function';
assert.strictEqual(gcp.requestTimeout(), 0);
delete process.env.K_SERVICE;
});

0 comments on commit 8e507c6

Please sign in to comment.