Skip to content
Merged
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
4 changes: 0 additions & 4 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,6 @@ linters:
linters:
- gocognit
- gocyclo
- path: buffer/buffer.go # TODO(ldez) must be fixed
text: Function 'ServeHTTP' has too many statements
linters:
- funlen
- path: memmetrics/ratio_test.go # TODO(ldez) must be fixed
text: 'float-compare: use assert\.InEpsilon \(or InDelta\)'
linters:
Expand Down
146 changes: 80 additions & 66 deletions buffer/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const (
var errHandler utils.ErrorHandler = &SizeErrHandler{}

// Buffer is responsible for buffering requests and responses
// It buffers large requests and responses to disk,.
// It buffers large requests and responses to disk.
type Buffer struct {
disableRequest bool
maxRequestBodyBytes int64
Expand Down Expand Up @@ -166,7 +166,7 @@ func (b *Buffer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}

// Set request body to buffered reader that can replay the read and execute Seek
// Note that we don't change the original request body as it's handled by the http server
// Note that we don't change the original request body as it's handled by the http server,
// and we don't want to mess with standard library
defer func() {
if body != nil {
Expand Down Expand Up @@ -202,102 +202,117 @@ func (b *Buffer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
attempt := 1

for {
// We create a special writer that will limit the response size, buffer it to disk if necessary
writer, err := multibuf.NewWriterOnce(
multibuf.MaxBytes(b.maxResponseBodyBytes),
multibuf.MemBytes(b.memResponseBodyBytes),
multibuf.TempDir(b.tempDir),
)
if err != nil {
b.log.Error("vulcand/oxy/buffer: failed create response writer, err: %v", err)
b.errHandler.ServeHTTP(w, req, err)
var done bool

outReq, done = b.serveAttempt(w, req, outReq, body, totalSize, attempt)
if done {
return
}

// We are mimicking http.ResponseWriter to replace writer with our special writer
bw := &bufferWriter{
header: make(http.Header),
code: b.defaultStatusCode,
buffer: writer,
responseWriter: w,
log: b.log,
}
defer bw.Close()
attempt++
}
}

b.next.ServeHTTP(bw, outReq)
func (b *Buffer) serveAttempt(w http.ResponseWriter, req, outReq *http.Request, body multibuf.MultiReader, totalSize int64, attempt int) (*http.Request, bool) {
// We create a special writer that will limit the response size, buffer it to disk if necessary
writer, err := multibuf.NewWriterOnce(
multibuf.MaxBytes(b.maxResponseBodyBytes),
multibuf.MemBytes(b.memResponseBodyBytes),
multibuf.TempDir(b.tempDir),
)
if err != nil {
b.log.Error("vulcand/oxy/buffer: failed create response writer, err: %v", err)
b.errHandler.ServeHTTP(w, req, err)

if bw.hijacked {
b.log.Debug("vulcand/oxy/buffer: connection was hijacked downstream. Not taking any action in buffer.")
return
}
return outReq, true
}

if bw.writeError != nil {
b.log.Error("vulcand/oxy/buffer: failed to copy response, err: %v", bw.writeError)
b.errHandler.ServeHTTP(w, req, bw.writeError)
// We are mimicking http.ResponseWriter to replace writer with our special writer
bw := &bufferWriter{
header: make(http.Header),
code: b.defaultStatusCode,
buffer: writer,
responseWriter: w,
log: b.log,
}
defer bw.Close()

return
}
b.next.ServeHTTP(bw, outReq)

var reader multibuf.MultiReader
if bw.hijacked {
b.log.Debug("vulcand/oxy/buffer: connection was hijacked downstream. Not taking any action in buffer.")
return outReq, true
}

if bw.expectBody(outReq) {
if _, err := writer.Write([]byte{}); err != nil {
b.log.Error("vulcand/oxy/buffer: failed to initialize response writer, err: %v", err)
b.errHandler.ServeHTTP(w, req, err)
if bw.writeError != nil {
b.log.Error("vulcand/oxy/buffer: failed to copy response, err: %v", bw.writeError)
b.errHandler.ServeHTTP(w, req, bw.writeError)

return
}
return outReq, true
}

rdr, err := writer.Reader()
if err != nil {
b.log.Error("vulcand/oxy/buffer: failed to read response, err: %v", err)
b.errHandler.ServeHTTP(w, req, err)
var reader multibuf.MultiReader

return
}
defer rdr.Close()
if bw.expectBody(outReq) {
if _, err := writer.Write([]byte{}); err != nil {
b.log.Error("vulcand/oxy/buffer: failed to initialize response writer, err: %v", err)
b.errHandler.ServeHTTP(w, req, err)

reader = rdr
return outReq, true
}

if b.retryPredicate == nil || attempt > DefaultMaxRetryAttempts ||
req.Context().Err() != nil ||
!b.retryPredicate(&context{r: req, attempt: attempt, responseCode: bw.code}) {
utils.CopyHeaders(w.Header(), bw.Header())
w.WriteHeader(bw.code)

if reader != nil {
_, _ = io.Copy(w, reader)
}
rdr, err := writer.Reader()
if err != nil {
b.log.Error("vulcand/oxy/buffer: failed to read response, err: %v", err)
b.errHandler.ServeHTTP(w, req, err)

return
return outReq, true
}
defer rdr.Close()

attempt++
reader = rdr
}

if body != nil {
if _, err := body.Seek(0, 0); err != nil {
b.log.Error("vulcand/oxy/buffer: failed to rewind request body, err: %v", err)
b.errHandler.ServeHTTP(w, req, err)
if b.retryPredicate == nil || attempt > DefaultMaxRetryAttempts ||
req.Context().Err() != nil ||
!b.retryPredicate(&context{r: req, attempt: attempt, responseCode: bw.code}) {
utils.CopyHeaders(w.Header(), bw.Header())
w.WriteHeader(bw.code)

return
}
if reader != nil {
_, _ = io.Copy(w, reader)
}

outReq = b.copyRequest(req, body, totalSize)
b.log.Debug("vulcand/oxy/buffer: retry Request(%v %v) attempt %v", req.Method, req.URL, attempt)
return outReq, true
}

if body != nil {
if _, err := body.Seek(0, 0); err != nil {
b.log.Error("vulcand/oxy/buffer: failed to rewind request body, err: %v", err)
b.errHandler.ServeHTTP(w, req, err)

return outReq, true
}
}

b.log.Debug("vulcand/oxy/buffer: retry Request(%v %v) attempt %v", req.Method, req.URL, attempt+1)

return b.copyRequest(req, body, totalSize), false
}

func (b *Buffer) copyRequest(req *http.Request, body io.ReadCloser, bodySize int64) *http.Request {
o := *req

o.URL = utils.CopyURL(req.URL)

o.Header = make(http.Header)
utils.CopyHeaders(o.Header, req.Header)

o.ContentLength = bodySize

// remove TransferEncoding that could have been previously set because we have transformed the request from chunked encoding
o.TransferEncoding = []string{}

// http.Transport will close the request body on any error, we are controlling the close process ourselves, so we override the closer here
if body == nil {
o.Body = io.NopCloser(req.Body)
Expand Down Expand Up @@ -411,8 +426,7 @@ func (b *bufferWriter) expectBody(r *http.Request) bool {
type SizeErrHandler struct{}

func (e *SizeErrHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, err error) {
//nolint:errorlint // must be changed
if _, ok := err.(*multibuf.MaxSizeReachedError); ok {
if _, ok := errors.AsType[*multibuf.MaxSizeReachedError](err); ok {
w.WriteHeader(http.StatusRequestEntityTooLarge)
_, _ = w.Write([]byte(http.StatusText(http.StatusRequestEntityTooLarge)))

Expand Down
9 changes: 6 additions & 3 deletions buffer/buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -786,13 +786,15 @@ func TestBuffer_cleanFiles(t *testing.T) {
}
})

options := append([]Option{MemResponseBodyBytes(1024)}, test.options...)
options := append(
[]Option{tempBufferDir(dir), MemResponseBodyBytes(1024)},
test.options...,
)

if test.retry {
options = append(options, Retry(`ResponseCode() == 502 && Attempts() <= 1`))
}

options = append(options, tempBufferDir(dir))

st, err := New(handler, options...)
require.NoError(t, err)

Expand All @@ -803,6 +805,7 @@ func TestBuffer_cleanFiles(t *testing.T) {
assert.PanicsWithValue(t, http.ErrAbortHandler, func() { st.ServeHTTP(recorder, request) })
} else {
st.ServeHTTP(recorder, request)

assert.Equal(t, test.code, recorder.Code)
}

Expand Down
2 changes: 1 addition & 1 deletion buffer/threshold.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func IsValidExpression(expr string) bool {
return err == nil
}

// Parses expression in the go language into Failover predicates.
// Parses expression in the Go language into Failover predicates.
func parseExpression(in string) (hpredicate, error) {
p, err := predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
Expand Down
4 changes: 2 additions & 2 deletions internal/multibuf/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type MultiReader interface {
}

// New returns MultiReader that can limit the size of the buffer and persist large buffers to disk.
// By default New returns unbound buffer that will read up to 1MB in RAM and will start buffering to disk
// By default, New returns unbound buffer that will read up to 1MB in RAM and will start buffering to disk
// It supports multiple functional optional arguments:
//
// // Buffer up to 1MB in RAM and limit max buffer size to 20MB
Expand Down Expand Up @@ -60,7 +60,7 @@ func New(input io.Reader, setters ...OptionSetter) (MultiReader, error) {

var file *os.File

// This means that we have exceeded all the memory capacity and we will start buffering the body to disk.
// This means that we have exceeded all the memory capacity, and we will start buffering the body to disk.
totalBytes := int64(len(buffer))

if memReader.N <= 0 {
Expand Down
18 changes: 11 additions & 7 deletions internal/multibuf/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,22 @@ const (
writerErr
)

// WriterOnce implements write once, read many times writer. Create a WriterOnce and write to it, once Reader() function has been
// called, the internal data is transferred to MultiReader and this instance of WriterOnce should be no longer used.
// WriterOnce implements write once, read many times writer.
// Create a WriterOnce and write to it, once Reader() function has been called,
// the internal data is transferred to MultiReader and this instance of WriterOnce should be no longer used.
type WriterOnce interface {
// Write implements io.Writer
Write(p []byte) (int, error)
// Reader transfers all data written to this writer to MultiReader. If there was no data written it returns an error
Reader() (MultiReader, error)
// WriterOnce owns the data before Reader has been called, so Close will close all the underlying files if Reader has not been called.
// Close WriterOnce owns the data before Reader has been called, so Close will close all the underlying files if Reader has not been called.
Close() error
}

// NewWriterOnce returns io.ReadWrite compatible object that can limit the size of the buffer and persist large buffers to disk.
// WriterOnce implements write once, read many times writer. Create a WriterOnce and write to it, once Reader() function has been
// called, the internal data is transferred to MultiReader and this instance of WriterOnce should be no longer used.
// By default NewWriterOnce returns unbound buffer that will allow to write up to 1MB in RAM and will start buffering to disk
// By default, NewWriterOnce returns unbound buffer that will allow to write up to 1MB in RAM and will start buffering to disk
// It supports multiple functional optional arguments:
//
// // Buffer up to 1MB in RAM and limit max buffer size to 20MB
Expand Down Expand Up @@ -79,7 +80,7 @@ func (w *writerOnce) Reader() (MultiReader, error) {
return nil, err
}

// we are not responsible for file and buffer any more
// We are not responsible for file and buffer anymore.
w.state = writerCalledRead

br, fr := bytes.NewReader(w.mem.Bytes()), w.file
Expand All @@ -102,8 +103,11 @@ func (w *writerOnce) Close() error {
return nil
}

if w.cleanupFn != nil {
return w.cleanupFn()
// We are still responsible for the file.
if w.state != writerCalledRead {
if w.cleanupFn != nil {
return w.cleanupFn()
}
}

return w.file.Close()
Expand Down
Loading