google: add CredentialsParams.EarlyTokenRefresh

This option is a followup to to cl/479676 where an option was added
to configure the preemptive token refresh. Currently the option
in this package is only being used by compute credentials. In the
future we can support more/all auth flows but that would require
a lot of new surfaces to be added. Compute credentials are currently
the only case where we are expirencing the need to configure this
setting.

Change-Id: Ib78ca4beec44d0fe030ae81e84c8fcc4924793ba
Reviewed-on: https://go-review.googlesource.com/c/oauth2/+/479956
Run-TryBot: Cody Oss <codyoss@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
diff --git a/google/default.go b/google/default.go
index 91b538b..b3e8783 100644
--- a/google/default.go
+++ b/google/default.go
@@ -13,6 +13,7 @@
 	"os"
 	"path/filepath"
 	"runtime"
+	"time"
 
 	"cloud.google.com/go/compute/metadata"
 	"golang.org/x/oauth2"
@@ -68,6 +69,14 @@
 	// The OAuth2 TokenURL default override. This value overrides the default TokenURL,
 	// unless explicitly specified by the credentials config file. Optional.
 	TokenURL string
+
+	// EarlyTokenRefresh is the amount of time before a token expires that a new
+	// token will be preemptively fetched. If unset the default value is 10
+	// seconds.
+	//
+	// Note: This option is currently only respected when using credentials
+	// fetched from the GCE metadata server.
+	EarlyTokenRefresh time.Duration
 }
 
 func (params CredentialsParams) deepCopy() CredentialsParams {
@@ -155,7 +164,7 @@
 		id, _ := metadata.ProjectID()
 		return &Credentials{
 			ProjectID:   id,
-			TokenSource: ComputeTokenSource("", params.Scopes...),
+			TokenSource: computeTokenSource("", params.EarlyTokenRefresh, params.Scopes...),
 		}, nil
 	}
 
diff --git a/google/google.go b/google/google.go
index a1b629a..cc12238 100644
--- a/google/google.go
+++ b/google/google.go
@@ -231,7 +231,11 @@
 // Further information about retrieving access tokens from the GCE metadata
 // server can be found at https://cloud.google.com/compute/docs/authentication.
 func ComputeTokenSource(account string, scope ...string) oauth2.TokenSource {
-	return oauth2.ReuseTokenSource(nil, computeSource{account: account, scopes: scope})
+	return computeTokenSource(account, 0, scope...)
+}
+
+func computeTokenSource(account string, earlyExpiry time.Duration, scope ...string) oauth2.TokenSource {
+	return oauth2.ReuseTokenSourceWithExpiry(nil, computeSource{account: account, scopes: scope}, earlyExpiry)
 }
 
 type computeSource struct {