Skip to content

Commit ea00264

Browse files
authored
fix(compute/metadata): remove heavy gax dependency (#4784)
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
1 parent e52c204 commit ea00264

2 files changed

Lines changed: 37 additions & 6 deletions

File tree

compute/metadata/metadata.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,6 @@ import (
3232
"strings"
3333
"sync"
3434
"time"
35-
36-
"github.com/googleapis/gax-go/v2"
3735
)
3836

3937
const (
@@ -317,7 +315,7 @@ func (c *Client) getETag(suffix string) (value, etag string, err error) {
317315
code = res.StatusCode
318316
}
319317
if delay, shouldRetry := retryer.Retry(code, reqErr); shouldRetry {
320-
if err := gax.Sleep(ctx, delay); err != nil {
318+
if err := sleep(ctx, delay); err != nil {
321319
return "", "", err
322320
}
323321
continue

compute/metadata/retry.go

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@
1515
package metadata
1616

1717
import (
18+
"context"
1819
"io"
20+
"math/rand"
1921
"net/http"
2022
"time"
21-
22-
"github.com/googleapis/gax-go/v2"
2323
)
2424

2525
const (
@@ -30,8 +30,41 @@ var (
3030
syscallRetryable = func(err error) bool { return false }
3131
)
3232

33+
// defaultBackoff is basically equivalent to gax.Backoff without the need for
34+
// the dependency.
35+
type defaultBackoff struct {
36+
max time.Duration
37+
mul float64
38+
cur time.Duration
39+
}
40+
41+
func (b *defaultBackoff) Pause() time.Duration {
42+
d := time.Duration(1 + rand.Int63n(int64(b.cur)))
43+
b.cur = time.Duration(float64(b.cur) * b.mul)
44+
if b.cur > b.max {
45+
b.cur = b.max
46+
}
47+
return d
48+
}
49+
50+
// sleep is the equivalent of gax.Sleep without the need for the dependency.
51+
func sleep(ctx context.Context, d time.Duration) error {
52+
t := time.NewTimer(d)
53+
select {
54+
case <-ctx.Done():
55+
t.Stop()
56+
return ctx.Err()
57+
case <-t.C:
58+
return nil
59+
}
60+
}
61+
3362
func newRetryer() *metadataRetryer {
34-
return &metadataRetryer{bo: &gax.Backoff{Initial: 100 * time.Millisecond}}
63+
return &metadataRetryer{bo: &defaultBackoff{
64+
cur: 100 * time.Millisecond,
65+
max: 30 * time.Second,
66+
mul: 2,
67+
}}
3568
}
3669

3770
type backoff interface {

0 commit comments

Comments
 (0)