Skip to content

Commit

Permalink
refactor: fastFailMetadataRequest to use Promise.any (#604)
Browse files Browse the repository at this point in the history
* chore: refactor fastFailMetadataRequest function

* chore: update unit tests

* chore: change target lib to support promise.any

* chore: remove then and catch blocks

---------

Co-authored-by: d-goog <[email protected]>
  • Loading branch information
Dhoni77 and d-goog authored Feb 7, 2025
1 parent 47fc3dd commit d2a81fc
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 40 deletions.
35 changes: 4 additions & 31 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,41 +201,14 @@ async function fastFailMetadataRequest<T>(
// 2. we can't just check the IP, which is tarpitted and slow to respond
// on a user's local machine.
//
// Additional logic has been added to make sure that we don't create an
// unhandled rejection in scenarios where a failure happens sometime
// after a success.
// Returns first resolved promise or if all promises get rejected we return an AggregateError.
//
// Note, however, if a failure happens prior to a success, a rejection should
// occur, this is for folks running locally.
//
let responded = false;
const r1: Promise<GaxiosResponse> = request<T>(options)
.then(res => {
responded = true;
return res;
})
.catch(err => {
if (responded) {
return r2;
} else {
responded = true;
throw err;
}
});
const r2: Promise<GaxiosResponse> = request<T>(secondaryOptions)
.then(res => {
responded = true;
return res;
})
.catch(err => {
if (responded) {
return r1;
} else {
responded = true;
throw err;
}
});
return Promise.race([r1, r2]);
const r1: Promise<GaxiosResponse> = request<T>(options);
const r2: Promise<GaxiosResponse> = request<T>(secondaryOptions);
return Promise.any([r1, r2]);
}

/**
Expand Down
16 changes: 8 additions & 8 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ describe('unit test', () => {
err = _err;
};

const secondary = secondaryHostRequest(500);
const secondary = secondaryHostRequest(500, 'ENOTFOUND');
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.replyWithError({code: 'ENOTFOUND'});
Expand All @@ -470,7 +470,7 @@ describe('unit test', () => {
primary.done();
console.info = info;
delete process.env.DEBUG_AUTH;
assert.strictEqual(/failed, reason/.test(err!.message), true);
assert.strictEqual(/All promises were rejected/.test(err!.message), true);
});

[
Expand All @@ -481,8 +481,8 @@ describe('unit test', () => {
'ENOTFOUND',
'ECONNREFUSED',
].forEach(errorCode => {
it(`should fail fast on isAvailable if ${errorCode} is returned`, async () => {
const secondary = secondaryHostRequest(500);
it(`should fail on isAvailable if ${errorCode} is returned for primary and secondary requests`, async () => {
const secondary = secondaryHostRequest(500, errorCode);
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.replyWithError({code: errorCode});
Expand All @@ -493,13 +493,13 @@ describe('unit test', () => {
});
});

it('should fail fast on isAvailable if 404 status code is returned', async () => {
it('should return first successful response', async () => {
const secondary = secondaryHostRequest(500);
const primary = nock(HOST).get(`${PATH}/${TYPE}`).reply(404);
const isGCE = await gcp.isAvailable();
await secondary;
primary.done();
assert.strictEqual(false, isGCE);
assert.strictEqual(true, isGCE);
});

it('should fail fast with GCE_METADATA_HOST 404 on isAvailable', async () => {
Expand Down Expand Up @@ -654,8 +654,8 @@ describe('unit test', () => {
it('resets cache when resetIsAvailableCache() is called', async () => {
// we will attempt to hit the secondary and primary server twice,
// mock accordingly.
const secondary = secondaryHostRequest(250);
const secondary2 = secondaryHostRequest(500);
const secondary = secondaryHostRequest(250, 'ENOENT');
const secondary2 = secondaryHostRequest(500, 'ENOENT');
const primary = nock(HOST)
.get(`${PATH}/${TYPE}`)
.reply(200, {}, HEADERS)
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"extends": "./node_modules/gts/tsconfig-google.json",
"compilerOptions": {
"lib": ["es2018", "dom"],
"lib": ["es2021", "dom"],
"rootDir": ".",
"outDir": "build"
},
Expand Down

0 comments on commit d2a81fc

Please sign in to comment.