@@ -59,7 +59,7 @@ type ClientCredentials struct {
5959 httpClient * http.Client
6060 fetchTokenFn func (context.Context ) (* oauth2.Token , error )
6161
62- lock sync.RWMutex
62+ lock sync.Mutex
6363}
6464
6565func NewClientCredentials (ctx context.Context , opts ClientCredentialsOptions ) (* ClientCredentials , error ) {
@@ -126,37 +126,28 @@ func (c *ClientCredentialsOptions) toConfig() (*ccreds.Config, *http.Client, err
126126}
127127
128128func (c * ClientCredentials ) Token () (string , error ) {
129- c .lock .RLock ()
130- defer c .lock .RUnlock ()
131-
132- if ! c .currentToken .Valid () {
133- ctx , cancel := context .WithTimeout (context .Background (), time .Second * 10 )
134- defer cancel ()
135- if err := c .renewToken (ctx ); err != nil {
136- return "" , err
137- }
138- }
139-
140- return c .currentToken .AccessToken , nil
141- }
142-
143- func (c * ClientCredentials ) renewToken (ctx context.Context ) error {
144129 c .lock .Lock ()
145130 defer c .lock .Unlock ()
146131
147- // We need to check if the current token is valid because we might have lost
148- // the mutex lock race from the caller and we don't want to double-fetch a
149- // token unnecessarily!
150132 if c .currentToken .Valid () {
151- return nil
133+ return c .currentToken .AccessToken , nil
134+ }
135+
136+ ctx , cancel := context .WithTimeout (context .Background (), time .Second * 10 )
137+ defer cancel ()
138+ if err := c .renewToken (ctx ); err != nil {
139+ return "" , err
152140 }
141+ return c .currentToken .AccessToken , nil
142+ }
153143
144+ func (c * ClientCredentials ) renewToken (ctx context.Context ) error {
154145 token , err := c .fetchTokenFn (context .WithValue (ctx , oauth2 .HTTPClient , c .httpClient ))
155146 if err != nil {
156147 return err
157148 }
158149
159- if ! c . currentToken .Valid () {
150+ if ! token .Valid () {
160151 return errors .New ("oauth2 client_credentials token source returned an invalid token" )
161152 }
162153
0 commit comments