Skip to content

Commit

Permalink
Update token refresh loop
Browse files Browse the repository at this point in the history
Signed-off-by: Marek Aufart <[email protected]>
  • Loading branch information
aufi committed Jan 15, 2024
1 parent 54b1667 commit c104568
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
23 changes: 17 additions & 6 deletions binding/richclient.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package binding

import (
"time"

"github.com/jortel/go-utils/logr"
"github.com/konveyor/tackle2-hub/api"
"github.com/konveyor/tackle2-hub/settings"
Expand Down Expand Up @@ -149,12 +151,21 @@ func (r *RichClient) Login(user, password string) (err error) {

//
// Refresh client token.
func (r *RichClient) RefreshToken() (err error) {
login := api.Login{Refresh: r.Client.token.Refresh}
err = r.Client.Post(api.AuthRefreshRoot, &login)
if err != nil {
return
func (r *RichClient) KeepFreshToken() (err error) {
if r.Client.token.Refresh != "" && r.Client.token.Expiry > 1 {
go func() {
for {
refreshIn := time.Duration(float64(r.Client.token.Expiry) * 0.9)
time.Sleep(refreshIn * time.Second)

login := api.Login{Refresh: r.Client.token.Refresh}
err = r.Client.Post(api.AuthRefreshRoot, &login)
if err != nil {
return
}
r.Client.SetToken(login)
}
}()
}
r.Client.SetToken(login)
return
}
10 changes: 3 additions & 7 deletions test/api/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package client
import (
"fmt"
"os"
"time"

"github.com/konveyor/tackle2-hub/binding"
"github.com/konveyor/tackle2-hub/settings"
Expand All @@ -23,16 +22,13 @@ func PrepareRichClient() (richClient *binding.RichClient) {
// Prepare RichClient and login to Hub API
richClient = binding.New(settings.Settings.Addon.Hub.URL)
err := richClient.Login(os.Getenv(Username), os.Getenv(Password))

// Start goroutine with token refresh.
go func () {
time.Sleep(1 * time.Minute) // TODO: base sleep time on token expiration
richClient.RefreshToken()
}()

if err != nil {
panic(fmt.Sprintf("Cannot login to API: %v.", err.Error()))
}

// Start goroutine with token refresh.
richClient.KeepFreshToken()

// Disable HTTP requests retry for network-related errors to fail quickly.
richClient.Client.Retry = 0
Expand Down

0 comments on commit c104568

Please sign in to comment.