Skip to content

Commit

Permalink
fix(compute/metadata): remove heavy gax dependency (#4784)
Browse files Browse the repository at this point in the history
Because of how the gax package is structured today it ends up
pulling in proto and gRPC which can add a lot of extra deps to the
tree if all you really need is this package.

Fixes: #4783
  • Loading branch information
codyoss authored Sep 21, 2021
1 parent e52c204 commit ea00264
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
4 changes: 1 addition & 3 deletions compute/metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ import (
"strings"
"sync"
"time"

"github.com/googleapis/gax-go/v2"
)

const (
Expand Down Expand Up @@ -317,7 +315,7 @@ func (c *Client) getETag(suffix string) (value, etag string, err error) {
code = res.StatusCode
}
if delay, shouldRetry := retryer.Retry(code, reqErr); shouldRetry {
if err := gax.Sleep(ctx, delay); err != nil {
if err := sleep(ctx, delay); err != nil {
return "", "", err
}
continue
Expand Down
39 changes: 36 additions & 3 deletions compute/metadata/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
package metadata

import (
"context"
"io"
"math/rand"
"net/http"
"time"

"github.com/googleapis/gax-go/v2"
)

const (
Expand All @@ -30,8 +30,41 @@ var (
syscallRetryable = func(err error) bool { return false }
)

// defaultBackoff is basically equivalent to gax.Backoff without the need for
// the dependency.
type defaultBackoff struct {
max time.Duration
mul float64
cur time.Duration
}

func (b *defaultBackoff) Pause() time.Duration {
d := time.Duration(1 + rand.Int63n(int64(b.cur)))
b.cur = time.Duration(float64(b.cur) * b.mul)
if b.cur > b.max {
b.cur = b.max
}
return d
}

// sleep is the equivalent of gax.Sleep without the need for the dependency.
func sleep(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
select {
case <-ctx.Done():
t.Stop()
return ctx.Err()
case <-t.C:
return nil
}
}

func newRetryer() *metadataRetryer {
return &metadataRetryer{bo: &gax.Backoff{Initial: 100 * time.Millisecond}}
return &metadataRetryer{bo: &defaultBackoff{
cur: 100 * time.Millisecond,
max: 30 * time.Second,
mul: 2,
}}
}

type backoff interface {
Expand Down

0 comments on commit ea00264

Please sign in to comment.