Skip to content

Commit 8f310ec

Browse files
authored
fix(ec2-metadata-service): set timeout for requests (#6072)
* fix(ec2-metadata-service): set timeout for requests * test(ec2-metadata-service): fix test for TimeOut error * fix(ec2-metadata-service): add connectionTimeout
1 parent ac9ef80 commit 8f310ec

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

packages/ec2-metadata-service/src/MetadataService.e2e.spec.ts

+13
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,17 @@ describe("MetadataService E2E Tests", () => {
9494
expect(lines).toContain("services/");
9595
}
9696
});
97+
98+
it("should timeout as expected when a request exceeds the specified duration", async () => {
99+
if (!metadataServiceAvailable) {
100+
return;
101+
}
102+
metadataService = new MetadataService({ httpOptions: { timeout: 0.1 } }); // 0.1ms timeout for testing
103+
try {
104+
await metadataService.request("/latest/meta-data/", {});
105+
} catch (error) {
106+
expect(error).toBeDefined();
107+
expect(error.message).toMatch(/TimeoutError/);
108+
}
109+
});
97110
});

packages/ec2-metadata-service/src/MetadataService.ts

+10-4
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,11 @@ export class MetadataService {
3232
}
3333

3434
async request(path: string, options: { method?: string; headers?: Record<string, string> }): Promise<string> {
35-
const { endpoint, ec2MetadataV1Disabled } = await this.config;
36-
const handler = new NodeHttpHandler();
35+
const { endpoint, ec2MetadataV1Disabled, httpOptions } = await this.config;
36+
const handler = new NodeHttpHandler({
37+
requestTimeout: httpOptions?.timeout,
38+
connectionTimeout: httpOptions?.timeout,
39+
});
3740
const endpointUrl = new URL(endpoint!);
3841
const headers = options.headers || {};
3942
/**
@@ -82,8 +85,11 @@ export class MetadataService {
8285
/**
8386
* Refer: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html
8487
*/
85-
const { endpoint } = await this.config;
86-
const handler = new NodeHttpHandler();
88+
const { endpoint, httpOptions } = await this.config;
89+
const handler = new NodeHttpHandler({
90+
requestTimeout: httpOptions?.timeout,
91+
connectionTimeout: httpOptions?.timeout,
92+
});
8793
const endpointUrl = new URL(endpoint!);
8894
const tokenRequest = new HttpRequest({
8995
method: "PUT",

0 commit comments

Comments
 (0)