Skip to content

Commit

Permalink
fix: improve reliability of certificate refresh (#448)
Browse files Browse the repository at this point in the history
  • Loading branch information
jackwotherspoon committed Feb 6, 2023
1 parent ef6a39d commit 47bd3f3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
14 changes: 9 additions & 5 deletions internal/cloudsql/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ import (
sqladmin "google.golang.org/api/sqladmin/v1beta4"
)

// the refresh buffer is the amount of time before a refresh's result expires
// that a new refresh operation begins.
const refreshBuffer = 4 * time.Minute

var (
// Instance connection name is the format <PROJECT>:<REGION>:<INSTANCE>
// Additionally, we have to support legacy "domain-scoped" projects (e.g. "google.com:PROJECT")
Expand Down Expand Up @@ -115,8 +119,8 @@ type RefreshCfg struct {
}

// Instance manages the information used to connect to the Cloud SQL instance by periodically calling
// the Cloud SQL Admin API. It automatically refreshes the required information approximately 5 minutes
// before the previous certificate expires (every 55 minutes).
// the Cloud SQL Admin API. It automatically refreshes the required information approximately 4 minutes
// before the previous certificate expires (every ~56 minutes).
type Instance struct {
// OpenConns is the number of open connections to the instance.
OpenConns uint64
Expand Down Expand Up @@ -275,11 +279,11 @@ func refreshDuration(now, certExpiry time.Time) time.Duration {
d := certExpiry.Sub(now)
if d < time.Hour {
// Something is wrong with the certificate, refresh now.
if d < 5*time.Minute {
if d < refreshBuffer {
return 0
}
// Otherwise, wait five minutes before starting the refresh cycle.
return 5 * time.Minute
// Otherwise wait until 4 minutes before expiration for next refresh cycle.
return d - refreshBuffer
}
return d / 2
}
Expand Down
10 changes: 5 additions & 5 deletions internal/cloudsql/instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,13 +278,13 @@ func TestRefreshDuration(t *testing.T) {
want: 30 * time.Minute,
},
{
desc: "when expiration is less than 1 hour, but greater than 5 minutes",
expiry: now.Add(6 * time.Minute),
want: 5 * time.Minute,
desc: "when expiration is less than 1 hour, but greater than 4 minutes",
expiry: now.Add(5 * time.Minute),
want: time.Minute,
},
{
desc: "when expiration is less than 5 minutes",
expiry: now.Add(4 * time.Minute),
desc: "when expiration is less than 4 minutes",
expiry: now.Add(3 * time.Minute),
want: 0,
},
{
Expand Down

0 comments on commit 47bd3f3

Please sign in to comment.