From e9a6ef8f965c5f89bdea3d76d5e1c7d20a884957 Mon Sep 17 00:00:00 2001 From: Cyril B Date: Thu, 28 Mar 2024 14:55:35 +0100 Subject: [PATCH] extract 502 code error from message to perform retries pt2 --- config/config.go | 2 +- middlewares/retry.go | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/config/config.go b/config/config.go index 82a1a26..44efe1d 100644 --- a/config/config.go +++ b/config/config.go @@ -68,7 +68,7 @@ func NewConfig() *Config { Str("uri", c.Request().URL.Path). Str("ip", c.RealIP()). Str("user_agent", c.Request().UserAgent()). - Msg("proxy error - detailed log") + Msg("proxy error") return err }, } diff --git a/middlewares/retry.go b/middlewares/retry.go index aaa3304..0b08319 100644 --- a/middlewares/retry.go +++ b/middlewares/retry.go @@ -2,6 +2,7 @@ package middlewares import ( "bytes" + "io" "net/http" "strings" "regexp" @@ -24,6 +25,11 @@ func Retry(config *config.Config) echo.MiddlewareFunc { delayedResponse := echo.NewResponse(&writer, c.Echo()) c.SetResponse(delayedResponse) + // Read the request body + bodyBytes, _ := io.ReadAll(c.Request().Body) + // Replace the request body with a buffer + c.Request().Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) + var statusFromMsg int err = next(c) @@ -40,18 +46,18 @@ func Retry(config *config.Config) echo.MiddlewareFunc { method := c.Request().Method path := c.Request().URL.Path shouldRetry := (method == http.MethodGet && (status == http.StatusNotFound || status == http.StatusForbidden)) || - (method == http.MethodPost && status == http.StatusOK && statusFromMsg == http.StatusBadGateway && + (method == http.MethodPost && statusFromMsg == 502 && (path == "/chains/main/blocks/head/helpers/scripts/run_script_view" || path == "/chains/main/blocks/head/helpers/scripts/run_view" || path == "/chains/main/blocks/head/helpers/scripts/pack_data")) - if err != nil && statusFromMsg == http.StatusBadGateway { - c.Logger().Infof("Error occurred with status 502. Request method: %s, path: %s, response status: %d", method, path, status) + if err != nil && statusFromMsg == 502 { + c.Logger().Infof("Error occurred with status 502. Request method: %s, path: %s, response status: %d", method, path, statusFromMsg) c.Logger().Infof("Should retry: %v", shouldRetry) } if shouldRetry { - c.Logger().Infof("Triggering retry for status %d", status) + c.Logger().Infof("Triggering retry for http status %d", status) writer.Reset() delayedResponse.Committed = false delayedResponse.Size = 0 @@ -62,6 +68,9 @@ func Retry(config *config.Config) echo.MiddlewareFunc { // so we need to reset this as well. c.Set("_error", nil) + // Reset the request body + c.Request().Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) + err = next(c) }