Skip to content

Commit b5a0552

Browse files
authored
refactor: refreshToken -> getToken (#1270)
- fold getToken and refreshToken into one so that we reduce locking
1 parent c6de254 commit b5a0552

File tree

1 file changed

+10
-16
lines changed

1 file changed

+10
-16
lines changed

internal/oauth/http_transport.go

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,10 @@ var storeRefreshedTokenFn = StoreToken
2929
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
3030
ctx := req.Context()
3131

32-
if err := t.refreshToken(ctx); err != nil {
32+
token, err := t.getToken(ctx)
33+
if err != nil {
3334
return nil, err
3435
}
35-
token := t.getToken()
3636

3737
req2 := req.Clone(req.Context())
3838
req2.Header.Set("Authorization", "Bearer "+token.AccessToken)
@@ -43,33 +43,27 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
4343
return http.DefaultTransport.RoundTrip(req2)
4444
}
4545

46-
// getToken returns a value copy of token and is guarded by a mutex
47-
func (t *Transport) getToken() Token {
48-
t.mu.Lock()
49-
defer t.mu.Unlock()
50-
51-
return *t.Token
52-
}
53-
54-
// refreshToken checks if the token has expired or expiring soon and refreshes it. Once the token is
55-
// refreshed, the in-memory token is updated and a best effort is made to store the token.
56-
// If storing the token fails, no error is returned.
57-
func (t *Transport) refreshToken(ctx context.Context) error {
46+
// getToken returns a value copy of the token. If the token has expired or expiring soon it will be refreshed before returning.
47+
// Once the token is refreshed, the in-memory token is updated and a best effort is made to store the token.
48+
//
49+
// If storing the token fails, no error is returned. An error is only returned if refreshing the token
50+
// fails.
51+
func (t *Transport) getToken(ctx context.Context) (Token, error) {
5852
t.mu.Lock()
5953
defer t.mu.Unlock()
6054

6155
prevToken := t.Token
6256
token, err := maybeRefresh(ctx, t.Token)
6357
if err != nil {
64-
return err
58+
return Token{}, err
6559
}
6660
t.Token = token
6761
if token != prevToken {
6862
// try to save the token if we fail let the request continue with in memory token
6963
_ = storeRefreshedTokenFn(ctx, token)
7064
}
7165

72-
return nil
66+
return *t.Token, nil
7367
}
7468

7569
// maybeRefresh conditionally refreshes the token. If the token has expired or is expriing in the next 30s

0 commit comments

Comments
 (0)