From 75ba452149fe12e1b896fb718b5124041d4a0d86 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sun, 20 Nov 2022 13:26:31 +0100 Subject: [PATCH] Fix: Renew token early, prevent concurrent token refreshes Signed-off-by: Knut Ahlers --- fetcher.go | 2 +- internal/mercedes/impl.go | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/fetcher.go b/fetcher.go index 41012f6..c9ff7de 100644 --- a/fetcher.go +++ b/fetcher.go @@ -10,7 +10,7 @@ import ( func getCronFunc(mc mercedes.Client) func() { return func() { for i := range cfg.VehicleID { - go runFetcher(mc, cfg.VehicleID[i]) + runFetcher(mc, cfg.VehicleID[i]) } } } diff --git a/internal/mercedes/impl.go b/internal/mercedes/impl.go index 1fcc9ef..f8f4011 100644 --- a/internal/mercedes/impl.go +++ b/internal/mercedes/impl.go @@ -19,8 +19,9 @@ import ( ) const ( - requestTimeout = 10 * time.Second - stateExpiry = 5 * time.Minute + requestTimeout = 10 * time.Second + stateExpiry = 5 * time.Minute + tokenGraceRenew = -5 * time.Minute ) type ( @@ -181,7 +182,7 @@ func (a APIClient) request(path string, output any) error { tok := &oauth2.Token{AccessToken: at, RefreshToken: rt, Expiry: exp} // Renew token if required - if tok.Expiry.Before(time.Now()) { + if tok.Expiry.Add(tokenGraceRenew).Before(time.Now()) { src := a.getOauth2Config("").TokenSource(ctx, tok) if tok, err = src.Token(); err != nil { return errors.Wrap(err, "renewing token")