Skip to content

Commit

Permalink
fix(ec2-metadata-service): set timeout for requests (#6072)
Browse files Browse the repository at this point in the history
* fix(ec2-metadata-service): set timeout for requests

* test(ec2-metadata-service): fix test for TimeOut error

* fix(ec2-metadata-service): add connectionTimeout
  • Loading branch information
siddsriv committed May 10, 2024
1 parent ac9ef80 commit 8f310ec
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
13 changes: 13 additions & 0 deletions packages/ec2-metadata-service/src/MetadataService.e2e.spec.ts
Expand Up @@ -94,4 +94,17 @@ describe("MetadataService E2E Tests", () => {
expect(lines).toContain("services/");
}
});

it("should timeout as expected when a request exceeds the specified duration", async () => {
if (!metadataServiceAvailable) {
return;
}
metadataService = new MetadataService({ httpOptions: { timeout: 0.1 } }); // 0.1ms timeout for testing
try {
await metadataService.request("/latest/meta-data/", {});
} catch (error) {
expect(error).toBeDefined();
expect(error.message).toMatch(/TimeoutError/);
}
});
});
14 changes: 10 additions & 4 deletions packages/ec2-metadata-service/src/MetadataService.ts
Expand Up @@ -32,8 +32,11 @@ export class MetadataService {
}

async request(path: string, options: { method?: string; headers?: Record<string, string> }): Promise<string> {
const { endpoint, ec2MetadataV1Disabled } = await this.config;
const handler = new NodeHttpHandler();
const { endpoint, ec2MetadataV1Disabled, httpOptions } = await this.config;
const handler = new NodeHttpHandler({
requestTimeout: httpOptions?.timeout,
connectionTimeout: httpOptions?.timeout,
});
const endpointUrl = new URL(endpoint!);
const headers = options.headers || {};
/**
Expand Down Expand Up @@ -82,8 +85,11 @@ export class MetadataService {
/**
* Refer: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html
*/
const { endpoint } = await this.config;
const handler = new NodeHttpHandler();
const { endpoint, httpOptions } = await this.config;
const handler = new NodeHttpHandler({
requestTimeout: httpOptions?.timeout,
connectionTimeout: httpOptions?.timeout,
});
const endpointUrl = new URL(endpoint!);
const tokenRequest = new HttpRequest({
method: "PUT",
Expand Down

0 comments on commit 8f310ec

Please sign in to comment.