Skip to content

Commit

Permalink
fix: ensure background refresh is closed cleanly (#715)
Browse files Browse the repository at this point in the history
  • Loading branch information
enocom committed Jan 24, 2024
1 parent a968b79 commit 0b4c342
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
20 changes: 13 additions & 7 deletions internal/cloudsql/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,11 @@ func (i *Instance) OpenConns() *uint64 {
// Close closes the instance; it stops the refresh cycle and prevents it from
// making additional calls to the Cloud SQL Admin API.
func (i *Instance) Close() error {
i.mu.Lock()
defer i.mu.Unlock()
i.cancel()
i.cur.cancel()
i.next.cancel()
return nil
}

Expand Down Expand Up @@ -254,6 +258,8 @@ func (i *Instance) refreshOperation(ctx context.Context) (*refreshOperation, err
err = cur.err
case <-ctx.Done():
err = ctx.Err()
case <-i.ctx.Done():
err = i.ctx.Err()
}
if err != nil {
return nil, err
Expand Down Expand Up @@ -285,6 +291,13 @@ func (i *Instance) scheduleRefresh(d time.Duration) *refreshOperation {
r := &refreshOperation{}
r.ready = make(chan struct{})
r.timer = time.AfterFunc(d, func() {
// instance has been closed, don't schedule anything
if err := i.ctx.Err(); err != nil {
r.err = err
close(r.ready)
return
}

ctx, cancel := context.WithTimeout(i.ctx, i.refreshTimeout)
defer cancel()

Expand All @@ -304,13 +317,6 @@ func (i *Instance) scheduleRefresh(d time.Duration) *refreshOperation {

close(r.ready)

select {
case <-i.ctx.Done():
// instance has been closed, don't schedule anything
return
default:
}

// Once the refresh is complete, update "current" with working
// refreshOperation and schedule a new refresh
i.mu.Lock()
Expand Down
3 changes: 1 addition & 2 deletions internal/cloudsql/instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"crypto/rand"
"crypto/rsa"
"errors"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -223,7 +222,7 @@ func TestClose(t *testing.T) {
i.Close()

_, _, err = i.ConnectInfo(ctx, PublicIP)
if !strings.Contains(err.Error(), "context was canceled or expired") {
if !errors.Is(err, context.Canceled) {
t.Fatalf("failed to retrieve connect info: %v", err)
}
}
Expand Down

0 comments on commit 0b4c342

Please sign in to comment.