-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
220 lines (177 loc) · 5.1 KB
/
http.go
File metadata and controls
220 lines (177 loc) · 5.1 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
package main
import (
"context"
"crypto/tls"
"encoding/json"
"io"
"net/http"
"net/http/httptrace"
"net/url"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.ntppool.org/common/apitls"
"go.ntppool.org/common/logger"
"go.ntppool.org/common/tracing"
"go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
// Default interval for SRV record refresh.
const defaultSRVTTL = 120 * time.Second
type httpClientManager struct {
client *http.Client
currentTimeout time.Duration
tlsConfig *tls.Config
apiURL string
// SRV target management
targetPool *TargetPool
srvTTL time.Duration
stopCh chan struct{}
}
func NewHTTPClientManager(certProvider apitls.CertificateProvider, apiURL string, metrics prometheus.Registerer) (*httpClientManager, error) {
log := logger.Setup()
capool, err := apitls.CAPool()
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
InsecureSkipVerify: false,
GetClientCertificate: certProvider.GetClientCertificate,
RootCAs: capool,
MinVersion: tls.VersionTLS13,
// MaxVersion: tls.VersionTLS13,
}
// Parse the upstream URL
upstreamURL, err := url.Parse(apiURL)
if err != nil {
return nil, err
}
// Initialize SRV metrics and target pool
srvMetrics := NewSRVMetrics(metrics)
targetPool := NewTargetPool(upstreamURL, srvMetrics)
cm := &httpClientManager{
tlsConfig: tlsConfig,
apiURL: apiURL,
targetPool: targetPool,
srvTTL: defaultSRVTTL,
stopCh: make(chan struct{}),
}
cm.client = &http.Client{}
// set transport and timeouts
cm.SetTimeout(60 * time.Second)
// Initial SRV resolution
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if !targetPool.ResolveSRV(ctx) {
log.Info("SRV resolution failed, using direct upstream")
}
cancel()
// Start background goroutines
go cm.runConfigLoop()
go cm.runSRVRefresh()
return cm, nil
}
// runConfigLoop periodically fetches config from the server.
func (cm *httpClientManager) runConfigLoop() {
for {
cm.getConfig(context.Background())
select {
case <-cm.stopCh:
return
case <-time.After(1 * time.Hour):
}
}
}
// runSRVRefresh periodically re-resolves SRV records based on TTL.
func (cm *httpClientManager) runSRVRefresh() {
log := logger.Setup()
for {
select {
case <-cm.stopCh:
return
case <-time.After(cm.srvTTL):
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if !cm.targetPool.ResolveSRV(ctx) {
log.Warn("SRV refresh failed or timed out")
}
cancel()
}
}
func (cm *httpClientManager) SetTimeout(baseTimeout time.Duration) {
if baseTimeout == cm.currentTimeout {
return
}
cm.currentTimeout = baseTimeout
baseTimeoutMs := baseTimeout.Milliseconds()
responseHeaderTimeout := time.Duration(time.Millisecond * time.Duration(float64(baseTimeoutMs)*0.85))
log := logger.Setup()
log.Info("timeouts", "responseHeader", responseHeaderTimeout)
tr := otelhttp.NewTransport(&http.Transport{
TLSClientConfig: cm.tlsConfig,
MaxIdleConns: 3,
IdleConnTimeout: 15 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: responseHeaderTimeout,
ExpectContinueTimeout: 5 * time.Second,
},
otelhttp.WithMessageEvents(otelhttp.ReadEvents, otelhttp.WriteEvents),
otelhttp.WithClientTrace(func(ctx context.Context) *httptrace.ClientTrace {
return otelhttptrace.NewClientTrace(ctx)
}),
)
cm.client.Transport = tr
cm.client.Timeout = baseTimeout
}
func (cm *httpClientManager) Client() *http.Client {
return cm.client
}
// APIBase returns the original upstream URL (for fallback/config purposes).
func (cm *httpClientManager) APIBase() string {
return cm.apiURL
}
// GetTargetURL returns the URL for the current target to use for requests.
// This implements SRV-based target selection with health tracking.
func (cm *httpClientManager) GetTargetURL() string {
return cm.targetPool.SelectTarget()
}
// TargetPool returns the SRV target pool for health tracking.
func (cm *httpClientManager) TargetPool() *TargetPool {
return cm.targetPool
}
// Stop shuts down background goroutines.
func (cm *httpClientManager) Stop() {
close(cm.stopCh)
}
func (cm *httpClientManager) getConfig(ctx context.Context) error {
ctx, span := tracing.Tracer().Start(ctx, "get_config")
defer span.End()
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
log := logger.Setup()
configURL := cm.apiURL + "api/v1/config"
log.Info("config", "url", configURL)
req, err := http.NewRequestWithContext(ctx, "GET", configURL, nil)
if err != nil {
span.RecordError(err)
return err
}
resp, err := cm.Client().Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
conf := struct{ Timeout time.Duration }{}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil
}
err = json.Unmarshal(data, &conf)
if err != nil {
return err
}
cm.SetTimeout(conf.Timeout)
} else {
log.Warn("config status", "code", resp.StatusCode, "status", resp.Status)
}
return nil
}