Skip to content

Commit

Permalink
feat: add isAvailable method (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinBeckwith committed Feb 7, 2018
1 parent a042275 commit 9686277
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,18 @@ export function instance(options?: string|Options) {
export function project(options?: string|Options) {
return metadataAccessor('project', options);
}

/**
* Determine if the metadata server is currently available.
*/
export async function isAvailable() {
try {
// Attempt to read instance metadata. As configured, this will
// retry 3 times if there is a valid response, and fail fast
// if there is an ETIMEDOUT or ENOTFOUND error.
await instance();
return true;
} catch (err) {
return false;
}
}
20 changes: 20 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,23 @@ test.serial('should not retry on DNS errors', async t => {
await t.throws(gcp.instance());
scope.done();
});

test.serial(
'should report isGCE if the server returns a 500 first', async t => {
const scopes = [
nock(HOST).get(`${PATH}/${TYPE}`).reply(500),
nock(HOST).get(`${PATH}/${TYPE}`).reply(200, {}, HEADERS)
];
const isGCE = await gcp.isAvailable();
scopes.forEach(s => s.done());
t.true(isGCE);
});

test.serial(
'should fail fast on isAvailable if a network err is returned', async t => {
const scope =
nock(HOST).get(`${PATH}/${TYPE}`).replyWithError({code: 'ENOTFOUND'});
const isGCE = await gcp.isAvailable();
scope.done();
t.false(isGCE);
});

0 comments on commit 9686277

Please sign in to comment.