Skip to content

Commit

Permalink
fixup! agent/http: refactor proxy for simpler error handling
Browse files Browse the repository at this point in the history
Use send time instead of channel.
  • Loading branch information
roobre committed Aug 2, 2023
1 parent 89429c7 commit 4c63bff
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions pkg/agent/protocol/http/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,18 @@ 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
upstreamReq.URL.Scheme = h.upstreamURL.Scheme
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)
Expand All @@ -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))
Expand All @@ -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
}

Expand All @@ -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
Expand Down

0 comments on commit 4c63bff

Please sign in to comment.