Skip to content
This repository has been archived by the owner on Apr 3, 2024. It is now read-only.

Commit

Permalink
fix: change getRegion method to return undefined upon not available
Browse files Browse the repository at this point in the history
  • Loading branch information
Louis-Ye committed May 3, 2021
1 parent 7acf9bd commit 80d6287
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
28 changes: 18 additions & 10 deletions src/agent/debuglet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -475,12 +475,7 @@ export class Debuglet extends EventEmitter {
const platform = Debuglet.getPlatform();
let region: string | undefined;
if (platform === Platforms.CLOUD_FUNCTION) {
try {
region = await Debuglet.getRegion();
} catch (err) {
/* something wrong with the metadata service. */
that.logger.warn('Could not infer region: ', err);
}
region = await Debuglet.getRegion();
}

// We can register as a debuggee now.
Expand Down Expand Up @@ -601,7 +596,7 @@ export class Debuglet extends EventEmitter {
}

if (region) {
desc += region;
desc += ' region:' + region;
}

if (!description && process.env.FUNCTION_NAME) {
Expand Down Expand Up @@ -661,12 +656,25 @@ export class Debuglet extends EventEmitter {
return (await metadata.instance('attributes/cluster-name')).data as string;
}

static async getRegion(): Promise<string> {
/**
* Returns the region from environment varaible if available.
* Otherwise, returns the region from the metadata service.
* If metadata is not available, returns undefined.
*/
static async getRegion(): Promise<string | undefined> {
if (process.env.FUNCTION_REGION) {
return process.env.FUNCTION_REGION;
}
const segments = ((await metadata.instance('region')) as string).split('/');
return segments[segments.length - 1];

try {
// Example returned region format: /process/1234567/us-central
const segments = ((await metadata.instance('region')) as string).split(
'/'
);
return segments[segments.length - 1];
} catch (err) {
return undefined;
}
}

static async getSourceContextFromFile(): Promise<SourceContext> {
Expand Down
11 changes: 11 additions & 0 deletions test/test-debuglet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1669,6 +1669,17 @@ describe('Debuglet', () => {

clusterScope.done();
});

it('should return undefined when cannot get region metadata', async () => {
const clusterScope = nock(gcpMetadata.HOST_ADDRESS)
.get('/computeMetadata/v1/instance/region')
.once()
.reply(400);

assert.ok((await Debuglet.getRegion()) === undefined);

clusterScope.done();
});
});

describe('_createUniquifier', () => {
Expand Down

0 comments on commit 80d6287

Please sign in to comment.