Skip to content
Draft
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
29 changes: 23 additions & 6 deletions lib/http-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export default class HttpClient {
*/
constructor({
abortController = undefined,
agent = undefined,
autoRenewAbortController = false,
clientName = '',
connections = 50,
Expand Down Expand Up @@ -96,12 +97,14 @@ export default class HttpClient {
}
}

this.#agent = new Agent({
keepAliveMaxTimeout,
keepAliveTimeout,
connections,
pipelining,
});
this.#agent =
agent ||
new Agent({
keepAliveMaxTimeout,
keepAliveTimeout,
connections,
pipelining,
});

if (fallback) {
if (typeof fallback === 'string') {
Expand All @@ -121,6 +124,7 @@ export default class HttpClient {
return this.#metrics;
}

// TODO add some type support for these options
async #request(options = {}) {
if (options.redirectable) {
const { redirect } = interceptors;
Expand All @@ -130,6 +134,18 @@ export default class HttpClient {
} else {
options.dispatcher = this.#agent;
}
if (options.retries) {
const { retry } = interceptors;
console.log(options.dispatcher);
options.dispatcher = this.#agent.compose(
retry({
retry: function () {
console.log('-------------------');
},
maxRetries: options.retries,
}),
);
}

const { statusCode, headers, trailers, body } = await request({
...options,
Expand Down Expand Up @@ -185,6 +201,7 @@ export default class HttpClient {
* @returns {Promise<any>}
*/
async request(options = {}) {
console.log('............', options);
return await this.#breaker.fire(options);
}

Expand Down
30 changes: 30 additions & 0 deletions tests/http-client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import http from 'node:http';

import HttpClient from '../lib/http-client.js';
import { wait } from './utilities.js';
import { MockAgent, setGlobalDispatcher } from 'undici';

let httpServer,
host = 'localhost',
Expand Down Expand Up @@ -205,6 +206,35 @@ await test('http-client - redirects', async (t) => {
});
});

await test('http-client - retries', async (t) => {
await t.test(
`uses the 'retries' options on incoming requests`,
async () => {
const agent = new MockAgent();
agent.disableNetConnect();
// setGlobalDispatcher(agent);
agent
.get('http://somepath.dk')
.intercept({
path: '/',
method: 'GET',
})
.reply(400, {});

const client = new HttpClient({ agent });
await client.request({
path: '/',
origin: 'http://somepath.dk',
method: 'GET',
retries: 2,
dispatcher: agent,
});
strictEqual(agent._eventsCount, 2);
agent.assertNoPendingInterceptors();
},
);
});

await test('http-client - circuit breaker behaviour', async (t) => {
const url = `http://${host}:${port}`;
beforeEach(startServer);
Expand Down