Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions internal/oauth/http_transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ var _ http.Transport
var _ http.RoundTripper = (*Transport)(nil)

type Transport struct {
Base http.RoundTripper
Base http.RoundTripper
//Token is a OAuth token (which has a refresh token) that should be used during roundtrip to automatically
//refresh the OAuth access token once the current one has expired or is soon to expire
Token *Token

//mu is a mutex that should be acquired whenever token used
mu sync.Mutex
}

Expand All @@ -29,16 +32,25 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
if err := t.refreshToken(ctx); err != nil {
return nil, err
}
token := t.getToken()
Comment on lines 32 to +35
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

very minor: you lock in refresh and in getToken, and this is the only place you call both. Maybe instead you can refactor it to read like this

Suggested change
if err := t.refreshToken(ctx); err != nil {
return nil, err
}
token := t.getToken()
token, err := t.getToken(ctx)
if err != nil {
return nil, err
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah I tend to agree. It did feel bit 💩 to do it - only thing that stopped me was getToken does more than what it says, although it's minor in the long run.

I'll update it in a bit.


req2 := req.Clone(req.Context())
req2.Header.Set("Authorization", "Bearer "+t.Token.AccessToken)
req2.Header.Set("Authorization", "Bearer "+token.AccessToken)

if t.Base != nil {
return t.Base.RoundTrip(req2)
}
return http.DefaultTransport.RoundTrip(req2)
}

// getToken returns a value copy of token and is guarded by a mutex
func (t *Transport) getToken() Token {
t.mu.Lock()
defer t.mu.Unlock()

return *t.Token
}

// refreshToken checks if the token has expired or expiring soon and refreshes it. Once the token is
// refreshed, the in-memory token is updated and a best effort is made to store the token.
// If storing the token fails, no error is returned.
Expand Down
Loading