Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify client timeouts implementation by using context cancellation #2186

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/api/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (h *handler) discoverSubscriptions(w http.ResponseWriter, r *http.Request)
}

requestBuilder := fetcher.NewRequestBuilder()
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
requestBuilder.WithUserAgent(subscriptionDiscoveryRequest.UserAgent)
requestBuilder.WithCookie(subscriptionDiscoveryRequest.Cookie)
Expand Down
16 changes: 8 additions & 8 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1586,9 +1586,9 @@ func TestHTTPSOn(t *testing.T) {
}
}

func TestHTTPClientTimeout(t *testing.T) {
func TestHTTPClientMaxRequestDuration(t *testing.T) {
os.Clearenv()
os.Setenv("HTTP_CLIENT_TIMEOUT", "42")
os.Setenv("HTTP_CLIENT_MAX_REQUEST_DURATION", "42")

parser := NewParser()
opts, err := parser.ParseEnvironmentVariables()
Expand All @@ -1597,14 +1597,14 @@ func TestHTTPClientTimeout(t *testing.T) {
}

expected := 42
result := opts.HTTPClientTimeout()
result := opts.HTTPClientMaxRequestDuration()

if result != expected {
t.Fatalf(`Unexpected HTTP_CLIENT_TIMEOUT value, got %d instead of %d`, result, expected)
t.Fatalf(`Unexpected HTTP_CLIENT_MAX_REQUEST_DURATION value, got %d instead of %d`, result, expected)
}
}

func TestDefaultHTTPClientTimeoutValue(t *testing.T) {
func TestDefaultHTTPClientMaxRequestDurationValue(t *testing.T) {
os.Clearenv()

parser := NewParser()
Expand All @@ -1613,11 +1613,11 @@ func TestDefaultHTTPClientTimeoutValue(t *testing.T) {
t.Fatalf(`Parsing failure: %v`, err)
}

expected := defaultHTTPClientTimeout
result := opts.HTTPClientTimeout()
expected := defaultHTTPClientMaxRequestDuration
result := opts.HTTPClientMaxRequestDuration()

if result != expected {
t.Fatalf(`Unexpected HTTP_CLIENT_TIMEOUT value, got %d instead of %d`, result, expected)
t.Fatalf(`Unexpected HTTP_CLIENT_MAX_REQUEST_DURATION value, got %d instead of %d`, result, expected)
}
}

Expand Down
14 changes: 7 additions & 7 deletions internal/config/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const (
defaultOAuth2OidcDiscoveryEndpoint = ""
defaultOAuth2Provider = ""
defaultPocketConsumerKey = ""
defaultHTTPClientTimeout = 20
defaultHTTPClientMaxRequestDuration = 60
defaultHTTPClientMaxBodySize = 15
defaultHTTPClientProxy = ""
defaultHTTPServerTimeout = 300
Expand Down Expand Up @@ -145,7 +145,7 @@ type Options struct {
oidcDiscoveryEndpoint string
oauth2Provider string
pocketConsumerKey string
httpClientTimeout int
httpClientMaxRequestDuration int
httpClientMaxBodySize int64
httpClientProxy string
httpClientUserAgent string
Expand Down Expand Up @@ -220,7 +220,7 @@ func NewOptions() *Options {
oidcDiscoveryEndpoint: defaultOAuth2OidcDiscoveryEndpoint,
oauth2Provider: defaultOAuth2Provider,
pocketConsumerKey: defaultPocketConsumerKey,
httpClientTimeout: defaultHTTPClientTimeout,
httpClientMaxRequestDuration: defaultHTTPClientMaxRequestDuration,
httpClientMaxBodySize: defaultHTTPClientMaxBodySize * 1024 * 1024,
httpClientProxy: defaultHTTPClientProxy,
httpClientUserAgent: defaultHTTPClientUserAgent,
Expand Down Expand Up @@ -515,9 +515,9 @@ func (o *Options) PocketConsumerKey(defaultValue string) string {
return defaultValue
}

// HTTPClientTimeout returns the time limit in seconds before the HTTP client cancel the request.
func (o *Options) HTTPClientTimeout() int {
return o.httpClientTimeout
// HTTPClientMaxRequestDuration returns the time limit in seconds before the HTTP client cancel the request.
func (o *Options) HTTPClientMaxRequestDuration() int {
return o.httpClientMaxRequestDuration
}

// HTTPClientMaxBodySize returns the number of bytes allowed for the HTTP client to transfer.
Expand Down Expand Up @@ -629,8 +629,8 @@ func (o *Options) SortedOptions(redactSecret bool) []*Option {
"FETCH_ODYSEE_WATCH_TIME": o.fetchOdyseeWatchTime,
"HTTPS": o.HTTPS,
"HTTP_CLIENT_MAX_BODY_SIZE": o.httpClientMaxBodySize,
"HTTP_CLIENT_MAX_REQUEST_DURATION": o.httpClientMaxRequestDuration,
"HTTP_CLIENT_PROXY": o.httpClientProxy,
"HTTP_CLIENT_TIMEOUT": o.httpClientTimeout,
"HTTP_CLIENT_USER_AGENT": o.httpClientUserAgent,
"HTTP_SERVER_TIMEOUT": o.httpServerTimeout,
"HTTP_SERVICE": o.httpService,
Expand Down
4 changes: 2 additions & 2 deletions internal/config/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,8 @@ func (p *Parser) parseLines(lines []string) (err error) {
p.opts.oidcDiscoveryEndpoint = parseString(value, defaultOAuth2OidcDiscoveryEndpoint)
case "OAUTH2_PROVIDER":
p.opts.oauth2Provider = parseString(value, defaultOAuth2Provider)
case "HTTP_CLIENT_TIMEOUT":
p.opts.httpClientTimeout = parseInt(value, defaultHTTPClientTimeout)
case "HTTP_CLIENT_MAX_REQUEST_DURATION":
p.opts.httpClientMaxRequestDuration = parseInt(value, defaultHTTPClientMaxRequestDuration)
case "HTTP_CLIENT_MAX_BODY_SIZE":
p.opts.httpClientMaxBodySize = int64(parseInt(value, defaultHTTPClientMaxBodySize) * 1024 * 1024)
case "HTTP_CLIENT_PROXY":
Expand Down
2 changes: 1 addition & 1 deletion internal/googlereader/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ func (h *handler) quickAddHandler(w http.ResponseWriter, r *http.Request) {
}

requestBuilder := fetcher.NewRequestBuilder()
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())

var rssBridgeURL string
Expand Down
48 changes: 18 additions & 30 deletions internal/reader/fetcher/request_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,33 @@
package fetcher // import "miniflux.app/v2/internal/reader/fetcher"

import (
"context"
"crypto/tls"
"encoding/base64"
"log/slog"
"net"
"net/http"
"net/url"
"time"
)

const (
defaultHTTPClientTimeout = 20
defaultHTTPClientMaxBodySize = 15 * 1024 * 1024
defaultHTTPClientMaxRequestDuration = 60
defaultHTTPClientMaxBodySize = 15 * 1024 * 1024
)

type RequestBuilder struct {
headers http.Header
clientProxyURL string
useClientProxy bool
clientTimeout int
withoutRedirects bool
ignoreTLSErrors bool
headers http.Header
clientProxyURL string
useClientProxy bool
maxRequestDuration int
withoutRedirects bool
ignoreTLSErrors bool
}

func NewRequestBuilder() *RequestBuilder {
return &RequestBuilder{
headers: make(http.Header),
clientTimeout: defaultHTTPClientTimeout,
headers: make(http.Header),
maxRequestDuration: defaultHTTPClientMaxRequestDuration,
}
}

Expand Down Expand Up @@ -86,8 +86,8 @@ func (r *RequestBuilder) UseProxy(value bool) *RequestBuilder {
return r
}

func (r *RequestBuilder) WithTimeout(timeout int) *RequestBuilder {
r.clientTimeout = timeout
func (r *RequestBuilder) WithMaxRequestDuration(timeout int) *RequestBuilder {
r.maxRequestDuration = timeout
return r
}

Expand All @@ -104,20 +104,6 @@ func (r *RequestBuilder) IgnoreTLSErrors(value bool) *RequestBuilder {
func (r *RequestBuilder) ExecuteRequest(requestURL string) (*http.Response, error) {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
// Default is 30s.
Timeout: 10 * time.Second,

// Default is 30s.
KeepAlive: 15 * time.Second,
}).DialContext,

// Default is 100.
MaxIdleConns: 50,

// Default is 90s.
IdleConnTimeout: 10 * time.Second,

TLSClientConfig: &tls.Config{
InsecureSkipVerify: r.ignoreTLSErrors,
},
Expand All @@ -135,7 +121,7 @@ func (r *RequestBuilder) ExecuteRequest(requestURL string) (*http.Response, erro
}

client := &http.Client{
Timeout: time.Duration(r.clientTimeout) * time.Second,
Transport: transport,
}

if r.withoutRedirects {
Expand All @@ -144,9 +130,10 @@ func (r *RequestBuilder) ExecuteRequest(requestURL string) (*http.Response, erro
}
}

client.Transport = transport
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(r.maxRequestDuration)*time.Second)
defer cancel()

req, err := http.NewRequest("GET", requestURL, nil)
req, err := http.NewRequestWithContext(ctx, "GET", requestURL, nil)
if err != nil {
return nil, err
}
Expand All @@ -159,6 +146,7 @@ func (r *RequestBuilder) ExecuteRequest(requestURL string) (*http.Response, erro
slog.String("method", req.Method),
slog.String("url", req.URL.String()),
slog.Any("headers", req.Header),
slog.Int("max_request_duration", r.maxRequestDuration),
slog.Bool("without_redirects", r.withoutRedirects),
slog.Bool("with_proxy", r.useClientProxy),
slog.String("proxy_url", r.clientProxyURL),
Expand Down
6 changes: 3 additions & 3 deletions internal/reader/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func CreateFeedFromSubscriptionDiscovery(store *storage.Storage, userID int64, f
requestBuilder.WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password)
requestBuilder.WithUserAgent(feedCreationRequest.UserAgent)
requestBuilder.WithCookie(feedCreationRequest.Cookie)
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
requestBuilder.UseProxy(feedCreationRequest.FetchViaProxy)
requestBuilder.IgnoreTLSErrors(feedCreationRequest.AllowSelfSignedCertificates)
Expand Down Expand Up @@ -123,7 +123,7 @@ func CreateFeed(store *storage.Storage, userID int64, feedCreationRequest *model
requestBuilder.WithUsernameAndPassword(feedCreationRequest.Username, feedCreationRequest.Password)
requestBuilder.WithUserAgent(feedCreationRequest.UserAgent)
requestBuilder.WithCookie(feedCreationRequest.Cookie)
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
requestBuilder.UseProxy(feedCreationRequest.FetchViaProxy)
requestBuilder.IgnoreTLSErrors(feedCreationRequest.AllowSelfSignedCertificates)
Expand Down Expand Up @@ -232,7 +232,7 @@ func RefreshFeed(store *storage.Storage, userID, feedID int64, forceRefresh bool
requestBuilder.WithUsernameAndPassword(originalFeed.Username, originalFeed.Password)
requestBuilder.WithUserAgent(originalFeed.UserAgent)
requestBuilder.WithCookie(originalFeed.Cookie)
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
requestBuilder.UseProxy(originalFeed.FetchViaProxy)
requestBuilder.IgnoreTLSErrors(originalFeed.AllowSelfSignedCertificates)
Expand Down
8 changes: 4 additions & 4 deletions internal/reader/processor/processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func ProcessFeedEntries(store *storage.Storage, feed *model.Feed, user *model.Us
requestBuilder := fetcher.NewRequestBuilder()
requestBuilder.WithUserAgent(feed.UserAgent)
requestBuilder.WithCookie(feed.Cookie)
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
requestBuilder.UseProxy(feed.FetchViaProxy)
requestBuilder.IgnoreTLSErrors(feed.AllowSelfSignedCertificates)
Expand Down Expand Up @@ -168,7 +168,7 @@ func ProcessEntryWebPage(feed *model.Feed, entry *model.Entry, user *model.User)
requestBuilder := fetcher.NewRequestBuilder()
requestBuilder.WithUserAgent(feed.UserAgent)
requestBuilder.WithCookie(feed.Cookie)
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
requestBuilder.UseProxy(feed.FetchViaProxy)
requestBuilder.IgnoreTLSErrors(feed.AllowSelfSignedCertificates)
Expand Down Expand Up @@ -294,7 +294,7 @@ func shouldFetchOdyseeWatchTime(entry *model.Entry) bool {

func fetchYouTubeWatchTime(websiteURL string) (int, error) {
requestBuilder := fetcher.NewRequestBuilder()
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())

responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(websiteURL))
Expand Down Expand Up @@ -325,7 +325,7 @@ func fetchYouTubeWatchTime(websiteURL string) (int, error) {

func fetchOdyseeWatchTime(websiteURL string) (int, error) {
requestBuilder := fetcher.NewRequestBuilder()
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())

responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(websiteURL))
Expand Down
2 changes: 1 addition & 1 deletion internal/ui/opml_upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (h *handler) fetchOPML(w http.ResponseWriter, r *http.Request) {
view.Set("countErrorFeeds", h.store.CountUserFeedsWithErrors(user.ID))

requestBuilder := fetcher.NewRequestBuilder()
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())

responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(opmlFileURL))
Expand Down
2 changes: 1 addition & 1 deletion internal/ui/subscription_submit.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (h *handler) submitSubscription(w http.ResponseWriter, r *http.Request) {
}

requestBuilder := fetcher.NewRequestBuilder()
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
requestBuilder.WithMaxRequestDuration(config.Opts.HTTPClientMaxRequestDuration())
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
requestBuilder.WithUserAgent(subscriptionForm.UserAgent)
requestBuilder.WithCookie(subscriptionForm.Cookie)
Expand Down
4 changes: 2 additions & 2 deletions miniflux.1
Original file line number Diff line number Diff line change
Expand Up @@ -449,10 +449,10 @@ Sets a server to proxy media through\&.
.br
Default is empty, miniflux does the proxying\&.
.TP
.B HTTP_CLIENT_TIMEOUT
.B HTTP_CLIENT_MAX_REQUEST_DURATION
Time limit in seconds before the HTTP client cancel the request\&.
.br
Default is 20 seconds\&.
Default is 60 seconds\&.
.TP
.B HTTP_CLIENT_MAX_BODY_SIZE
Maximum body size for HTTP requests in Mebibyte (MiB)\&.
Expand Down