Skip to content

Commit

Permalink
OAUth2: Respect disable keepalives option; Implement close idle conne…
Browse files Browse the repository at this point in the history
…ctions

Signed-off-by: Julien Pivotto <roidelapluie@o11y.eu>
  • Loading branch information
roidelapluie committed Jul 8, 2022
1 parent cdc09f0 commit eebbb56
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions config/http_config.go
Expand Up @@ -632,6 +632,7 @@ type oauth2RoundTripper struct {
secret string
mtx sync.RWMutex
opts *httpClientOptions
client *http.Client
}

func NewOAuth2RoundTripper(config *OAuth2, next http.RoundTripper, opts *httpClientOptions) http.RoundTripper {
Expand Down Expand Up @@ -680,14 +681,16 @@ func (rt *oauth2RoundTripper) RoundTrip(req *http.Request) (*http.Response, erro
var t http.RoundTripper
if len(rt.config.TLSConfig.CAFile) == 0 {
t = &http.Transport{
TLSClientConfig: tlsConfig,
Proxy: http.ProxyURL(rt.config.ProxyURL.URL),
TLSClientConfig: tlsConfig,
Proxy: http.ProxyURL(rt.config.ProxyURL.URL),
DisableKeepAlives: !rt.opts.keepAlivesEnabled,
}
} else {
t, err = NewTLSRoundTripper(tlsConfig, rt.config.TLSConfig.CAFile, func(tls *tls.Config) (http.RoundTripper, error) {
return &http.Transport{
TLSClientConfig: tls,
Proxy: http.ProxyURL(rt.config.ProxyURL.URL),
TLSClientConfig: tls,
Proxy: http.ProxyURL(rt.config.ProxyURL.URL),
DisableKeepAlives: !rt.opts.keepAlivesEnabled,
}, nil
})
if err != nil {
Expand All @@ -699,7 +702,8 @@ func (rt *oauth2RoundTripper) RoundTrip(req *http.Request) (*http.Response, erro
t = NewUserAgentRoundTripper(rt.opts.userAgent, t)
}

ctx := context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{Transport: t})
client := &http.Client{Transport: t}
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, client)
tokenSource := config.TokenSource(ctx)

rt.mtx.Lock()
Expand All @@ -708,6 +712,10 @@ func (rt *oauth2RoundTripper) RoundTrip(req *http.Request) (*http.Response, erro
Base: rt.next,
Source: tokenSource,
}
if rt.client != nil {
rt.client.CloseIdleConnections()
}
rt.client = client
rt.mtx.Unlock()
}

Expand All @@ -718,7 +726,9 @@ func (rt *oauth2RoundTripper) RoundTrip(req *http.Request) (*http.Response, erro
}

func (rt *oauth2RoundTripper) CloseIdleConnections() {
// OAuth2 RT does not support CloseIdleConnections() but the next RT might.
if rt.client != nil {
rt.client.CloseIdleConnections()
}
if ci, ok := rt.next.(closeIdler); ok {
ci.CloseIdleConnections()
}
Expand Down

0 comments on commit eebbb56

Please sign in to comment.