diff --git a/pkg/agent/protocol/http/proxy.go b/pkg/agent/protocol/http/proxy.go index ccea74e1..d230caf0 100644 --- a/pkg/agent/protocol/http/proxy.go +++ b/pkg/agent/protocol/http/proxy.go @@ -99,8 +99,10 @@ func (h *httpHandler) isExcluded(r *http.Request) bool { } // proxy proxies a request to the upstream URL. -// Request is performed immediately, but response won't be copied to the client until wait has been consumed. -func (h *httpHandler) proxy(rw http.ResponseWriter, req *http.Request, wait <-chan time.Time) { +// Request is performed immediately, but response won't be sent until sendAt. +func (h *httpHandler) proxy(rw http.ResponseWriter, req *http.Request, delay time.Duration) { + timer := time.After(delay) + upstreamReq := req.Clone(context.Background()) upstreamReq.Host = h.upstreamURL.Host upstreamReq.URL.Host = h.upstreamURL.Host @@ -108,8 +110,7 @@ func (h *httpHandler) proxy(rw http.ResponseWriter, req *http.Request, wait <-ch upstreamReq.RequestURI = "" // It is an error to set this field in an HTTP client request. response, err := h.client.Do(req) - <-wait - + <-timer if err != nil { rw.WriteHeader(http.StatusBadGateway) _, _ = fmt.Fprint(rw, err) @@ -136,9 +137,9 @@ func (h *httpHandler) proxy(rw http.ResponseWriter, req *http.Request, wait <-ch _, _ = io.Copy(rw, response.Body) } -// fault consumes wait and then writes to rw the configured error code and body. -func (h *httpHandler) fault(rw http.ResponseWriter, wait <-chan time.Time) { - <-wait +// fault sleeps until sendAt and then writes the configured error downstream. +func (h *httpHandler) fault(rw http.ResponseWriter, delay time.Duration) { + time.Sleep(delay) rw.WriteHeader(int(h.disruption.ErrorCode)) _, _ = rw.Write([]byte(h.disruption.ErrorBody)) @@ -147,7 +148,7 @@ func (h *httpHandler) fault(rw http.ResponseWriter, wait <-chan time.Time) { func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { if h.isExcluded(req) { //nolint:contextcheck // Unclear which context the linter requires us to propagate here. - h.proxy(rw, req, time.After(0)) + h.proxy(rw, req, 0) return } @@ -157,15 +158,13 @@ func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { delay += time.Duration(variation - 2*rand.Int63n(variation)) } - responseTimer := time.After(delay) - if h.disruption.ErrorRate > 0 && rand.Float32() <= h.disruption.ErrorRate { - h.fault(rw, responseTimer) + h.fault(rw, delay) return } //nolint:contextcheck // Unclear which context the linter requires us to propagate here. - h.proxy(rw, req, responseTimer) + h.proxy(rw, req, delay) } // Start starts the execution of the proxy