Skip to content

Commit

Permalink
fix: avoid scheduling an instance refresh if the context is done (#491)
Browse files Browse the repository at this point in the history
Fixes #493
  • Loading branch information
jomaresch committed Jan 24, 2024
1 parent ff5ca35 commit 42c8ae3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
20 changes: 14 additions & 6 deletions internal/alloydb/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,11 @@ func (i *Instance) OpenConns() *uint64 {
// Close closes the instance; it stops the refresh cycle and prevents it from
// making additional calls to the AlloyDB Admin API.
func (i *Instance) Close() error {
i.resultGuard.Lock()
defer i.resultGuard.Unlock()
i.cancel()
i.cur.cancel()
i.next.cancel()
return nil
}

Expand Down Expand Up @@ -230,6 +234,8 @@ func (i *Instance) result(ctx context.Context) (*refreshOperation, error) {
err = res.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 @@ -260,6 +266,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 @@ -280,6 +293,7 @@ func (i *Instance) scheduleRefresh(d time.Duration) *refreshOperation {
// result and schedule a new refresh
i.resultGuard.Lock()
defer i.resultGuard.Unlock()

// if failed, scheduled the next refresh immediately
if r.err != nil {
i.next = i.scheduleRefresh(0)
Expand All @@ -297,12 +311,6 @@ func (i *Instance) scheduleRefresh(d time.Duration) *refreshOperation {
// Update the current results, and schedule the next refresh in
// the future
i.cur = r
select {
case <-i.ctx.Done():
// instance has been closed, don't schedule anything
return
default:
}
t := refreshDuration(time.Now(), i.cur.result.expiry)
i.next = i.scheduleRefresh(t)
})
Expand Down
3 changes: 1 addition & 2 deletions internal/alloydb/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 @@ -216,7 +215,7 @@ func TestClose(t *testing.T) {
i.Close()

_, _, err = i.ConnectInfo(ctx)
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 42c8ae3

Please sign in to comment.