refactor: update the client retry by the pkg retryablehttp (#2752)
Signed-off-by: saltbo <saltbo@foxmail.com>
This commit is contained in:
@@ -21,10 +21,9 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
|
"github.com/hashicorp/go-retryablehttp"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
@@ -39,12 +38,13 @@ type (
|
|||||||
Client struct {
|
Client struct {
|
||||||
logger *zap.Logger
|
logger *zap.Logger
|
||||||
url string
|
url string
|
||||||
httpClient *http.Client
|
httpClient *retryablehttp.Client
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func MakeClient(logger *zap.Logger, builderUrl string) *Client {
|
func MakeClient(logger *zap.Logger, builderUrl string) *Client {
|
||||||
hc := &http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}
|
hc := retryablehttp.NewClient()
|
||||||
|
hc.HTTPClient.Transport = otelhttp.NewTransport(hc.HTTPClient.Transport)
|
||||||
return &Client{
|
return &Client{
|
||||||
logger: logger.Named("builder_client"),
|
logger: logger.Named("builder_client"),
|
||||||
url: strings.TrimSuffix(builderUrl, "/"),
|
url: strings.TrimSuffix(builderUrl, "/"),
|
||||||
@@ -60,27 +60,10 @@ func (c *Client) Build(ctx context.Context, req *builder.PackageBuildRequest) (*
|
|||||||
return nil, errors.Wrap(err, "error marshaling json")
|
return nil, errors.Wrap(err, "error marshaling json")
|
||||||
}
|
}
|
||||||
|
|
||||||
maxRetries := 20
|
resp, err := ctxhttp.Post(ctx, c.httpClient.StandardClient(), c.url, "application/json", bytes.NewReader(body))
|
||||||
var resp *http.Response
|
if err != nil {
|
||||||
|
return nil, ferror.MakeErrorFromHTTP(resp)
|
||||||
for i := 0; i < maxRetries; i++ {
|
|
||||||
resp, err = ctxhttp.Post(ctx, c.httpClient, c.url, "application/json", bytes.NewReader(body))
|
|
||||||
if err == nil {
|
|
||||||
if resp.StatusCode == 200 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
err = ferror.MakeErrorFromHTTP(resp)
|
|
||||||
}
|
|
||||||
|
|
||||||
if i < maxRetries-1 {
|
|
||||||
time.Sleep(50 * time.Duration(2*i) * time.Millisecond)
|
|
||||||
logger.Error("error building package, retrying", zap.Error(err))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
rBody, err := io.ReadAll(resp.Body)
|
rBody, err := io.ReadAll(resp.Body)
|
||||||
|
|||||||
Reference in New Issue
Block a user