Skip to content

Commit

Permalink
feat: retry logic catches thrown errors (#774)
Browse files Browse the repository at this point in the history
  • Loading branch information
krpeacock authored Sep 29, 2023
1 parent 62ba61b commit 75fcb03
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/generated/changelog.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ <h1>Agent-JS Changelog</h1>
<section>
<h2>Version x.x.x</h2>
<ul>
<li>feat: retry logic will catch and retry for thrown errors</li>
<li>
feat!: adds certificate logic to decode subnet and node key paths from the hashtree.
Changes the interface for `lookup_path` to allow returning a HashTree, but also constrains
Expand Down
17 changes: 17 additions & 0 deletions packages/agent/src/agent/http/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -811,3 +811,20 @@ describe('default host', () => {
}
});
});

test('retry requests that fail due to a network failure', async () => {
const mockFetch: jest.Mock = jest.fn(() => {
throw new Error('Network failure');
});

const agent = new HttpAgent({ host: HTTP_AGENT_HOST, fetch: mockFetch });
try {
await agent.call(Principal.managementCanister(), {
methodName: 'test',
arg: new Uint8Array().buffer,
});
} catch (error) {
// One try + three retries
expect(mockFetch.mock.calls.length).toBe(4);
}
});
15 changes: 14 additions & 1 deletion packages/agent/src/agent/http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,20 @@ export class HttpAgent implements Agent {
}

private async _requestAndRetry(request: () => Promise<Response>, tries = 0): Promise<Response> {
const response = await request();
let response: Response;
try {
response = await request();
} catch (error) {
if (this._retryTimes > tries) {
console.warn(
`Caught exception while attempting to make request:\n` +
` ${error}\n` +
` Retrying request.`,
);
return await this._requestAndRetry(request, tries + 1);
}
throw error;
}
if (response.ok) {
return response;
}
Expand Down

0 comments on commit 75fcb03

Please sign in to comment.