-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
268 lines (235 loc) · 8.29 KB
/
Copy pathpool.go
File metadata and controls
268 lines (235 loc) · 8.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package pool
import (
"crypto/tls"
"net"
"net/http"
"net/url"
"sync"
"time"
)
// ConnectionPool manages HTTP client connections with connection pooling
type ConnectionPool struct {
// Connection pool settings
maxIdleConns int
maxIdleConnsPerHost int
maxConnsPerHost int
idleConnTimeout time.Duration
keepAliveTimeout time.Duration
tlsHandshakeTimeout time.Duration
expectContinueTimeout time.Duration
// Client cache for different proxy configurations
clients map[string]*http.Client
mutex sync.RWMutex
// Transport settings
disableKeepAlives bool
disableCompression bool
insecureSkipVerify bool
}
// Config represents connection pool configuration
type Config struct {
MaxIdleConns int `yaml:"max_idle_conns"`
MaxIdleConnsPerHost int `yaml:"max_idle_conns_per_host"`
MaxConnsPerHost int `yaml:"max_conns_per_host"`
IdleConnTimeout time.Duration `yaml:"idle_conn_timeout"`
KeepAliveTimeout time.Duration `yaml:"keep_alive_timeout"`
TLSHandshakeTimeout time.Duration `yaml:"tls_handshake_timeout"`
ExpectContinueTimeout time.Duration `yaml:"expect_continue_timeout"`
DisableKeepAlives bool `yaml:"disable_keep_alives"`
DisableCompression bool `yaml:"disable_compression"`
InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
}
// DefaultConfig returns a connection pool configuration with sensible defaults
func DefaultConfig() Config {
return Config{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
MaxConnsPerHost: 50,
IdleConnTimeout: 90 * time.Second,
KeepAliveTimeout: 30 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DisableKeepAlives: false,
DisableCompression: false,
InsecureSkipVerify: false,
}
}
// NewConnectionPool creates a new connection pool with the given configuration
func NewConnectionPool(config Config) *ConnectionPool {
return &ConnectionPool{
maxIdleConns: config.MaxIdleConns,
maxIdleConnsPerHost: config.MaxIdleConnsPerHost,
maxConnsPerHost: config.MaxConnsPerHost,
idleConnTimeout: config.IdleConnTimeout,
keepAliveTimeout: config.KeepAliveTimeout,
tlsHandshakeTimeout: config.TLSHandshakeTimeout,
expectContinueTimeout: config.ExpectContinueTimeout,
disableKeepAlives: config.DisableKeepAlives,
disableCompression: config.DisableCompression,
insecureSkipVerify: config.InsecureSkipVerify,
clients: make(map[string]*http.Client),
mutex: sync.RWMutex{},
}
}
// GetClient returns an HTTP client configured for the given proxy URL
// It reuses existing clients when possible to leverage connection pooling
func (p *ConnectionPool) GetClient(proxyURL string, timeout time.Duration) (*http.Client, error) {
// Create a cache key that includes proxy URL and timeout
cacheKey := p.getCacheKey(proxyURL, timeout)
// Check if we already have a client for this configuration
p.mutex.RLock()
if client, exists := p.clients[cacheKey]; exists {
p.mutex.RUnlock()
return client, nil
}
p.mutex.RUnlock()
// Create a new client
client, err := p.createClient(proxyURL, timeout)
if err != nil {
return nil, err
}
// Store the client in the cache
p.mutex.Lock()
p.clients[cacheKey] = client
p.mutex.Unlock()
return client, nil
}
// GetDirectClient returns an HTTP client for direct connections (no proxy)
func (p *ConnectionPool) GetDirectClient(timeout time.Duration) *http.Client {
return p.createDirectClient(timeout)
}
// createClient creates a new HTTP client with the specified proxy configuration
func (p *ConnectionPool) createClient(proxyURL string, timeout time.Duration) (*http.Client, error) {
// Parse proxy URL
parsedProxy, err := url.Parse(proxyURL)
if err != nil {
return nil, err
}
// Create custom dialer with keep-alive settings
dialer := &net.Dialer{
Timeout: timeout,
KeepAlive: p.keepAliveTimeout,
}
// Create transport with connection pooling settings
transport := &http.Transport{
Proxy: http.ProxyURL(parsedProxy),
DialContext: dialer.DialContext,
MaxIdleConns: p.maxIdleConns,
MaxIdleConnsPerHost: p.maxIdleConnsPerHost,
MaxConnsPerHost: p.maxConnsPerHost,
IdleConnTimeout: p.idleConnTimeout,
TLSHandshakeTimeout: p.tlsHandshakeTimeout,
ExpectContinueTimeout: p.expectContinueTimeout,
DisableKeepAlives: p.disableKeepAlives,
DisableCompression: p.disableCompression,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: p.insecureSkipVerify,
},
// Enable HTTP/2 support
ForceAttemptHTTP2: true,
}
return &http.Client{
Transport: transport,
Timeout: timeout,
}, nil
}
// createDirectClient creates an HTTP client for direct connections
func (p *ConnectionPool) createDirectClient(timeout time.Duration) *http.Client {
// Create custom dialer with keep-alive settings
dialer := &net.Dialer{
Timeout: timeout,
KeepAlive: p.keepAliveTimeout,
}
// Create transport with connection pooling settings
transport := &http.Transport{
DialContext: dialer.DialContext,
MaxIdleConns: p.maxIdleConns,
MaxIdleConnsPerHost: p.maxIdleConnsPerHost,
MaxConnsPerHost: p.maxConnsPerHost,
IdleConnTimeout: p.idleConnTimeout,
TLSHandshakeTimeout: p.tlsHandshakeTimeout,
ExpectContinueTimeout: p.expectContinueTimeout,
DisableKeepAlives: p.disableKeepAlives,
DisableCompression: p.disableCompression,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: p.insecureSkipVerify,
},
// Enable HTTP/2 support
ForceAttemptHTTP2: true,
}
return &http.Client{
Transport: transport,
Timeout: timeout,
}
}
// getCacheKey generates a cache key for the client based on proxy URL and timeout
func (p *ConnectionPool) getCacheKey(proxyURL string, timeout time.Duration) string {
return proxyURL + ":" + timeout.String()
}
// CloseIdleConnections closes idle connections for all cached clients
func (p *ConnectionPool) CloseIdleConnections() {
p.mutex.RLock()
defer p.mutex.RUnlock()
for _, client := range p.clients {
if transport, ok := client.Transport.(*http.Transport); ok {
transport.CloseIdleConnections()
}
}
}
// GetStats returns statistics about the connection pool
func (p *ConnectionPool) GetStats() PoolStats {
p.mutex.RLock()
defer p.mutex.RUnlock()
stats := PoolStats{
CachedClients: len(p.clients),
MaxIdleConns: p.maxIdleConns,
MaxIdleConnsPerHost: p.maxIdleConnsPerHost,
MaxConnsPerHost: p.maxConnsPerHost,
IdleConnTimeout: p.idleConnTimeout,
KeepAliveTimeout: p.keepAliveTimeout,
}
return stats
}
// PoolStats contains statistics about the connection pool
type PoolStats struct {
CachedClients int `json:"cached_clients"`
MaxIdleConns int `json:"max_idle_conns"`
MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"`
MaxConnsPerHost int `json:"max_conns_per_host"`
IdleConnTimeout time.Duration `json:"idle_conn_timeout"`
KeepAliveTimeout time.Duration `json:"keep_alive_timeout"`
}
// Reset clears all cached clients and forces recreation
func (p *ConnectionPool) Reset() {
p.mutex.Lock()
defer p.mutex.Unlock()
// Close idle connections before clearing cache
for _, client := range p.clients {
if transport, ok := client.Transport.(*http.Transport); ok {
transport.CloseIdleConnections()
}
}
// Clear the cache
p.clients = make(map[string]*http.Client)
}
// UpdateConfig updates the connection pool configuration
// Note: This only affects newly created clients
func (p *ConnectionPool) UpdateConfig(config Config) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.maxIdleConns = config.MaxIdleConns
p.maxIdleConnsPerHost = config.MaxIdleConnsPerHost
p.maxConnsPerHost = config.MaxConnsPerHost
p.idleConnTimeout = config.IdleConnTimeout
p.keepAliveTimeout = config.KeepAliveTimeout
p.tlsHandshakeTimeout = config.TLSHandshakeTimeout
p.expectContinueTimeout = config.ExpectContinueTimeout
p.disableKeepAlives = config.DisableKeepAlives
p.disableCompression = config.DisableCompression
p.insecureSkipVerify = config.InsecureSkipVerify
}
// GetClientCount returns the number of cached HTTP clients
func (p *ConnectionPool) GetClientCount() int {
p.mutex.RLock()
defer p.mutex.RUnlock()
return len(p.clients)
}