Skip to content

Commit

Permalink
extract 502 code error from message to perform retries
Browse files Browse the repository at this point in the history
  • Loading branch information
cyrilevos committed Mar 28, 2024
1 parent b9f4489 commit 89c31e2
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions middlewares/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"bytes"
"net/http"
"strings"
"regexp"
"strconv"

"github.com/labstack/echo/v4"
"github.com/marigold-dev/tzproxy/config"
Expand All @@ -22,11 +24,28 @@ func Retry(config *config.Config) echo.MiddlewareFunc {
delayedResponse := echo.NewResponse(&writer, c.Echo())
c.SetResponse(delayedResponse)

var statusFromMsg int
err = next(c)

status := c.Response().Status
if (c.Request().Method == http.MethodGet && (status == http.StatusNotFound || status == http.StatusForbidden)) ||
(c.Request().Method == http.MethodPost && status == http.StatusBadGateway) {
// Extract the status code from the error message
if err != nil {
re := regexp.MustCompile(`code=(\d+)`)
match := re.FindStringSubmatch(err.Error())
if len(match) > 1 {
statusFromMsg, _ = strconv.Atoi(match[1])
}
}
// Check the request method and path
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 &&
(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 shouldRetry {
c.Logger().Infof("Triggering retry for status %d", status)
writer.Reset()
delayedResponse.Committed = false
Expand Down

0 comments on commit 89c31e2

Please sign in to comment.