1
1
import fetch from "node-fetch" ;
2
2
import { CommunicationProtocolEnum } from "../../.." ;
3
3
import IClient from "../../../interfaces/Client/IClient" ;
4
+ import http from "node:http" ;
5
+ import https from "node:https" ;
4
6
5
7
export default class HTTPClient implements IClient {
6
8
private readonly isInitialized : boolean ;
@@ -9,6 +11,9 @@ export default class HTTPClient implements IClient {
9
11
private readonly clientPort : string ;
10
12
private readonly clientUrl : string ;
11
13
14
+ private readonly httpAgent ;
15
+ private readonly httpsAgent ;
16
+
12
17
constructor ( host = "127.0.0.1" , port = "50050" ) {
13
18
this . isInitialized = true ;
14
19
this . clientHost = host ;
@@ -21,6 +26,9 @@ export default class HTTPClient implements IClient {
21
26
}
22
27
23
28
this . client = fetch ;
29
+
30
+ this . httpAgent = new http . Agent ( { keepAlive : true , keepAliveMsecs : 30 * 1000 } ) ;
31
+ this . httpsAgent = new https . Agent ( { keepAlive : true , keepAliveMsecs : 30 * 1000 } ) ;
24
32
}
25
33
26
34
getClient ( ) : typeof fetch {
@@ -64,7 +72,14 @@ export default class HTTPClient implements IClient {
64
72
}
65
73
}
66
74
75
+
67
76
const urlFull = url . startsWith ( "http" ) ? url : `${ this . clientUrl } ${ url } ` ;
77
+
78
+ // Decide which agent to use
79
+ // we use an agent so we can reuse an open connection, limiting handshake requirements
80
+ const agent = urlFull . startsWith ( "https" ) ? this . httpsAgent : this . httpAgent ;
81
+ params . agent = agent ;
82
+
68
83
// console.log(`${params.method} - ${urlFull} (${params.body})`);
69
84
const res = await fetch ( urlFull , params ) ;
70
85
0 commit comments