| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package worker |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "encoding/json" |
| 22 | "errors" |
| 23 | "io" |
| 24 | "net/http" |
| 25 | "strconv" |
| 26 | "strings" |
| 27 | "time" |
| 28 | |
| 29 | "github.com/rs/zerolog/log" |
| 30 | "github.com/sassoftware/relic/v7/internal/httperror" |
| 31 | "github.com/sassoftware/relic/v7/internal/workerrpc" |
| 32 | "github.com/sassoftware/relic/v7/token" |
| 33 | "github.com/sassoftware/relic/v7/token/tokencache" |
| 34 | ) |
| 35 | |
| 36 | const ( |
| 37 | initialDelay = 1 * time.Second |
| 38 | scaleFactor = 2.718 |
| 39 | maxDelay = 30 * time.Second |
| 40 | ) |
| 41 | |
| 42 | func (t *WorkerToken) doRetry(req *http.Request) (rresp *workerrpc.Response, err error) { |
| 43 | retries := t.tconf.Retries |
| 44 | if retries == 0 { |
| 45 | retries = defaultRetries |
| 46 | } |
| 47 | timeout := time.Duration(t.tconf.Timeout) * time.Second |
| 48 | if timeout == 0 { |
| 49 | timeout = defaultTimeout |
| 50 | } |
| 51 | baseCtx := req.Context() |
| 52 | delay := float32(initialDelay) |
| 53 | var last error |
| 54 | for i := 0; i < retries; i++ { |
| 55 | if i != 0 { |
| 56 | log.Warn(). |
| 57 | Int("attempt", i). |
| 58 | Int("max_attempts", retries). |
| 59 | AnErr("last_error", last). |
| 60 | Msg("token error; retrying") |
| 61 | // delay retry with backoff |
| 62 | ctx, cancel := context.WithTimeout(baseCtx, time.Duration(delay)) |
| 63 | <-ctx.Done() |
| 64 | cancel() |
| 65 | if baseCtx.Err() != nil { |
| 66 | // cancelled |
| 67 | return nil, baseCtx.Err() |
| 68 | } |
| 69 | delay *= scaleFactor |
| 70 | if delay > float32(maxDelay) { |
| 71 | delay = float32(maxDelay) |
| 72 | } |
| 73 | } |
| 74 | start := time.Now() |
| 75 | rresp, err := t.doOnce(req, timeout) |
| 76 | if err == nil { |
| 77 | t.observe(req, start, http.StatusOK) |
| 78 | return rresp, nil |
| 79 | } |
| 80 | // translate various outcomes into a status code for metrics |
| 81 | var retry bool |
| 82 | code := http.StatusInternalServerError |
| 83 | if httperror.Temporary(err) { |
| 84 | code = http.StatusServiceUnavailable |
| 85 | retry = true |
| 86 | } else if errors.As(err, new(token.KeyUsageError)) { |
| 87 | code = http.StatusBadRequest |
| 88 | } |
| 89 | if e := new(httperror.ResponseError); errors.As(err, e) { |
| 90 | code = e.StatusCode |
| 91 | } |
| 92 | if baseCtx.Err() != nil { |
| 93 | // request canceled |
| 94 | code = 499 |
| 95 | } else if errors.Is(err, context.DeadlineExceeded) { |
| 96 | code = http.StatusGatewayTimeout |
| 97 | } |
| 98 | t.observe(req, start, code) |
| 99 | if !retry { |
| 100 | return nil, err |
| 101 | } |
| 102 | last = err |
| 103 | } |
| 104 | return nil, last |
| 105 | } |
| 106 | |
| 107 | func (t *WorkerToken) doOnce(req *http.Request, timeout time.Duration) (*workerrpc.Response, error) { |
| 108 | ctx, cancel := context.WithTimeout(req.Context(), timeout) |
| 109 | defer cancel() |
| 110 | if req.GetBody != nil { |
| 111 | var err error |
| 112 | req.Body, err = req.GetBody() |
| 113 | if err != nil { |
| 114 | return nil, err |
| 115 | } |
| 116 | } |
| 117 | resp, err := http.DefaultClient.Do(req.WithContext(ctx)) |
| 118 | if err != nil { |
| 119 | return nil, err |
| 120 | } |
| 121 | defer resp.Body.Close() |
| 122 | if resp.StatusCode != http.StatusOK { |
| 123 | // http error |
| 124 | return nil, httperror.FromResponse(resp) |
| 125 | } |
| 126 | // json response |
| 127 | blob, err := io.ReadAll(resp.Body) |
| 128 | if err != nil { |
| 129 | return nil, err |
| 130 | } |
| 131 | rresp := new(workerrpc.Response) |
| 132 | if err := json.Unmarshal(blob, rresp); err != nil { |
| 133 | return nil, err |
| 134 | } |
| 135 | if rresp.Err == "" { |
| 136 | // success |
| 137 | return rresp, nil |
| 138 | } else if rresp.Usage { |
| 139 | return nil, token.KeyUsageError{ |
| 140 | Key: rresp.Key, |
| 141 | Err: errors.New(rresp.Err), |
| 142 | } |
| 143 | } |
| 144 | return nil, tokenError{Err: rresp.Err, Retryable: rresp.Retryable} |
| 145 | } |
| 146 | |
| 147 | func (t *WorkerToken) observe(req *http.Request, start time.Time, code int) { |
| 148 | dur := time.Since(start).Seconds() |
| 149 | name := t.tconf.Name() |
| 150 | op := strings.TrimLeft(req.URL.Path, "/") |
| 151 | scode := strconv.FormatInt(int64(code), 10) |
| 152 | tokencache.MetricOperations.WithLabelValues(name, op).Observe(dur) |
| 153 | tokencache.MetricResponses.WithLabelValues(name, op, scode).Inc() |
| 154 | } |
| 155 | |
| 156 | type tokenError struct { |
| 157 | Err string |
| 158 | Retryable bool |
| 159 | } |
| 160 | |
| 161 | func (e tokenError) Error() string { return e.Err } |
| 162 | func (e tokenError) Temporary() bool { return e.Retryable } |