Skip to content
Open
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
18 changes: 18 additions & 0 deletions middleware/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type ProxyConfig struct {

// RetryCount defines the number of times a failed proxied request should be retried
// using the next available ProxyTarget. Defaults to 0, meaning requests are never retried.
// Retrying can repeat upstream side effects; use RetryFilter to select operations that are safe to retry.
RetryCount int

// RetryFilter defines a function used to determine if a failed request to a
Expand Down Expand Up @@ -312,6 +313,7 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
req.Header.Del("Forwarded")

retries := config.RetryCount
var previousBody *proxyRetryBody
for {
tgt, err := config.Balancer.Next(c)
if err != nil {
Expand All @@ -333,6 +335,18 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
// This is needed for ProxyConfig.ModifyResponse and/or ProxyConfig.Transport to be able to process the Request
// that Balancer may have replaced with c.SetRequest.
req = c.Request()
if previousBody != nil && req.Body == previousBody && req.GetBody != nil {
body, bodyErr := req.GetBody()
if bodyErr != nil {
return config.ErrorHandler(c, bodyErr)
}
req.Body = body
}
if retries > 0 && req.Body != nil && req.Body != http.NoBody {
// Mark the body forwarded by this attempt. A balancer may supply a fresh body on the next attempt.
previousBody = &proxyRetryBody{ReadCloser: req.Body}
req.Body = previousBody
}

// ReverseProxy validates upgrades and closes both sides when a tunnel ends.
proxyHTTP(c, tgt, config, clientIP, scheme).ServeHTTP(res, req)
Expand All @@ -353,6 +367,10 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
}, nil
}

type proxyRetryBody struct {
io.ReadCloser
}

// StatusCodeContextCanceled is a custom HTTP status code for situations
// where a client unexpectedly closed the connection to the server.
// As there is no standard error code for "client closed connection", but
Expand Down
148 changes: 148 additions & 0 deletions middleware/proxy_retry_balancer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package middleware

import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestProxyRetryPreservesBalancerBody(t *testing.T) {
for _, replaceRequest := range []bool{false, true} {
for _, failGetBody := range []bool{false, true} {
name := "same request"
if replaceRequest {
name = "replacement request"
}
if failGetBody {
name += "/GetBody error"
}
t.Run(name, func(t *testing.T) {
e := echo.New()
target, err := url.Parse("http://upstream.example.test")
require.NoError(t, err)
original := &proxyBodyCloseCounter{Reader: strings.NewReader("original payload")}
fresh := &proxyBodyCloseCounter{Reader: strings.NewReader("balancer payload")}
req := httptest.NewRequest(http.MethodPost, "http://proxy.example.test/", nil)
req.Body = original
req.ContentLength = int64(len("original payload"))
attempts, selections, getBodyCalls := 0, 0, 0
balancer := &proxyBodyReplacingBalancer{
ProxyBalancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}),
beforeNext: func(c *echo.Context) {
selections++
if selections != 2 {
return
}
r := c.Request()
if replaceRequest {
r = r.Clone(r.Context())
}
r.Body = fresh
r.ContentLength = int64(len("balancer payload"))
r.GetBody = func() (io.ReadCloser, error) {
getBodyCalls++
if failGetBody {
return nil, errors.New("fresh body does not need reopening")
}
return io.NopCloser(strings.NewReader("unused replay")), nil
}
c.SetRequest(r)
},
}
transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) {
attempts++
b, readErr := io.ReadAll(r.Body)
require.NoError(t, readErr)
if attempts == 1 {
require.Equal(t, "original payload", string(b))
return nil, errors.New("temporary transport failure")
}
assert.Equal(t, "balancer payload", string(b))
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok"))}, nil
})
handler := ProxyWithConfig(ProxyConfig{Balancer: balancer, RetryCount: 1, Transport: transport})(func(*echo.Context) error { return nil })
err = handler(e.NewContext(req, httptest.NewRecorder()))
assert.NoError(t, err)
assert.Equal(t, 2, attempts)
assert.Zero(t, getBodyCalls, "a new body supplied by the balancer must be forwarded as supplied")
assert.Equal(t, 1, original.closes)
assert.Equal(t, 1, fresh.closes)
})
}
}
}

func TestProxyRetryReplaysClonedRequestBody(t *testing.T) {
e := echo.New()
target, err := url.Parse("http://upstream.example.test")
require.NoError(t, err)
original := &proxyBodyCloseCounter{Reader: strings.NewReader("payload")}
bodies := []*proxyBodyCloseCounter{original}
req := httptest.NewRequest(http.MethodPost, "http://proxy.example.test/", nil)
// Non-comparable implementations are valid io.ReadClosers too.
req.Body = proxyUncomparableBody{ReadCloser: original}
req.ContentLength = int64(len("payload"))
req.GetBody = func() (io.ReadCloser, error) {
body := &proxyBodyCloseCounter{Reader: strings.NewReader("payload")}
bodies = append(bodies, body)
return proxyUncomparableBody{ReadCloser: body}, nil
}
attempts := 0
balancer := &proxyBodyReplacingBalancer{
ProxyBalancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}),
beforeNext: func(c *echo.Context) {
c.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), testContextKey("attempt"), attempts)))
},
}
transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) {
attempts++
b, readErr := io.ReadAll(r.Body)
require.NoError(t, readErr)
require.Equal(t, "payload", string(b))
if attempts < 3 {
return nil, errors.New("temporary transport failure")
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok"))}, nil
})
handler := ProxyWithConfig(ProxyConfig{Balancer: balancer, RetryCount: 2, Transport: transport})(func(*echo.Context) error { return nil })
require.NoError(t, handler(e.NewContext(req, httptest.NewRecorder())))
require.Equal(t, 3, attempts)
require.Len(t, bodies, 3)
for _, body := range bodies {
require.Equal(t, 1, body.closes)
}
}

type proxyBodyCloseCounter struct {
*strings.Reader
closes int
}

func (b *proxyBodyCloseCounter) Close() error {
b.closes++
return nil
}

type proxyUncomparableBody struct {
io.ReadCloser
_ []byte
}

type proxyBodyReplacingBalancer struct {
ProxyBalancer
beforeNext func(*echo.Context)
}

func (b *proxyBodyReplacingBalancer) Next(c *echo.Context) (*ProxyTarget, error) {
b.beforeNext(c)
return b.ProxyBalancer.Next(c)
}
59 changes: 59 additions & 0 deletions middleware/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1428,3 +1428,62 @@ func TestProxy_DotSegmentsAfterRouting(t *testing.T) {
assert.True(t, called)
})
}

func TestProxyRetryReplaysBody(t *testing.T) {
e := echo.New()
target, err := url.Parse("http://upstream.example.test")
assert.NoError(t, err)
attempts := 0
transport := proxyRetryBodyTransport(func(req *http.Request) (*http.Response, error) {
attempts++
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
_ = req.Body.Close()
assert.Equal(t, "request payload", string(body), "attempt %d", attempts)
if attempts == 1 {
return nil, errors.New("temporary transport failure")
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok"))}, nil
})
handler := ProxyWithConfig(ProxyConfig{Balancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}), RetryCount: 1, Transport: transport})(func(*echo.Context) error { return nil })
req, err := http.NewRequest(http.MethodPost, "http://proxy.example.test/", strings.NewReader("request payload"))
assert.NoError(t, err)
rec := httptest.NewRecorder()
err = handler(e.NewContext(req, rec))
assert.NoError(t, err)
assert.Equal(t, 2, attempts)
assert.Equal(t, "ok", rec.Body.String())
}

func TestProxyRetryGetBodyError(t *testing.T) {
e := echo.New()
target, err := url.Parse("http://upstream.example.test")
assert.NoError(t, err)
sentinel := errors.New("cannot reopen request body")
attempts := 0
transport := proxyRetryBodyTransport(func(req *http.Request) (*http.Response, error) {
attempts++
_, _ = io.Copy(io.Discard, req.Body)
_ = req.Body.Close()
return nil, errors.New("temporary transport failure")
})
var handled error
handler := ProxyWithConfig(ProxyConfig{
Balancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}),
RetryCount: 1, Transport: transport,
ErrorHandler: func(_ *echo.Context, err error) error { handled = err; return err },
})(func(*echo.Context) error { return nil })
req, err := http.NewRequest(http.MethodPost, "http://proxy.example.test/", strings.NewReader("payload"))
assert.NoError(t, err)
req.GetBody = func() (io.ReadCloser, error) { return nil, sentinel }
err = handler(e.NewContext(req, httptest.NewRecorder()))
assert.ErrorIs(t, err, sentinel)
assert.ErrorIs(t, handled, sentinel)
assert.Equal(t, 1, attempts)
}

type proxyRetryBodyTransport func(*http.Request) (*http.Response, error)

func (f proxyRetryBodyTransport) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }
Loading