Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: retry logic catches thrown errors #774

Merged
merged 4 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) {
krpeacock marked this conversation as resolved.
Show resolved Hide resolved
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
Loading