-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy_fill_holes.go
100 lines (83 loc) Β· 2.23 KB
/
strategy_fill_holes.go
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
package main
import (
"fmt"
"net/http"
"sync"
)
// FillHolesStrategy selects the transport with the least ongoing requests.
type FillHolesStrategy struct {
transports []http.RoundTripper
requestCounts []int
mutex sync.Mutex
}
// NewFillHolesStrategy initializes the fill-holes strategy.
func NewFillHolesStrategy(transports []http.RoundTripper) *FillHolesStrategy {
return &FillHolesStrategy{
transports: transports,
requestCounts: make([]int, len(transports)),
}
}
// Acquire picks the transport with the least ongoing requests.
func (fh *FillHolesStrategy) Acquire() (http.RoundTripper, error) {
if len(fh.transports) == 0 {
return nil, ErrNoTransports
}
fh.mutex.Lock()
defer fh.mutex.Unlock()
minIndex := 0
minCount := fh.requestCounts[0]
for i, count := range fh.requestCounts {
if count < minCount {
minIndex = i
minCount = count
}
}
fh.requestCounts[minIndex]++
return fh.transports[minIndex], nil
}
// Release decrements the request count for a transport.
func (fh *FillHolesStrategy) Release(transport http.RoundTripper) {
fh.mutex.Lock()
defer fh.mutex.Unlock()
for i, t := range fh.transports {
if t == transport {
fh.requestCounts[i]--
if fh.requestCounts[i] < 0 {
fh.requestCounts[i] = 0
}
return
}
}
}
type (
OptFillHoles func(*FillHolesConfig)
FillHolesConfig struct {
Proxies []string
TransportFactory func(string) (*http.Transport, error)
}
)
// TransportFillHoles creates a round-robin StrategyTransport with configurable options.
func TransportFillHoles(proxies []string, opts ...OptFillHoles) http.RoundTripper {
cfg := &FillHolesConfig{
Proxies: proxies,
TransportFactory: DefaultTransportFactory,
}
for _, opt := range opts {
opt(cfg)
}
var transports []http.RoundTripper
for _, proxy := range cfg.Proxies {
transport, err := cfg.TransportFactory(proxy)
if err != nil {
fmt.Printf("Error creating transport for proxy %s: %v\n", proxy, err)
continue
}
transports = append(transports, transport)
}
return Transport(NewFillHolesStrategy(transports))
}
func OptFillHolesWithTransportFactory(factory func(string) (*http.Transport, error)) OptFillHoles {
return func(cfg *FillHolesConfig) {
cfg.TransportFactory = factory
}
}