Skip to content

Commit

Permalink
feat: force early refresh of instance info if connect fails (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
kurtisvg authored May 7, 2021
1 parent 1092ccc commit eb06ae2
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
4 changes: 4 additions & 0 deletions dialer.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ func (d *Dialer) Dial(ctx context.Context, instance string, opts ...DialOption)

conn, err := proxy.Dial(ctx, "tcp", addr)
if err != nil {
// refresh the instance info in case it caused the connection failure
i.ForceRefresh()
return nil, err
}
if c, ok := conn.(*net.TCPConn); ok {
Expand All @@ -152,6 +154,8 @@ func (d *Dialer) Dial(ctx context.Context, instance string, opts ...DialOption)
}
tlsConn := tls.Client(conn, tlsCfg)
if err := tlsConn.Handshake(); err != nil {
// refresh the instance info in case it caused the handshake failure
i.ForceRefresh()
tlsConn.Close()
return nil, fmt.Errorf("handshake failed: %w", err)
}
Expand Down
12 changes: 12 additions & 0 deletions internal/cloudsql/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,18 @@ func (i *Instance) ConnectInfo(ctx context.Context) (map[string]string, *tls.Con
return res.md.ipAddrs, res.tlsCfg, nil
}

// ForceRefresh triggers an immediate refresh operation to be scheduled and used for future connection attempts.
func (i *Instance) ForceRefresh() {
i.resultGuard.Lock()
defer i.resultGuard.Unlock()
// If the next refresh hasn't started yet, we can cancel it and start an immediate one
if i.next.Cancel() {
i.next = i.scheduleRefresh(0)
}
// block all sequential connection attempts on the next refresh result
i.cur = i.next
}

// scheduleRefresh schedules a refresh operation to be triggered after a given duration. The returned refreshResult
// can be used to either Cancel or Wait for the operations result.
func (i *Instance) scheduleRefresh(d time.Duration) *refreshResult {
Expand Down
2 changes: 1 addition & 1 deletion internal/cloudsql/refresh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func TestFetchMetadata(t *testing.T) {
t.Fatalf("%s", err)
}
}
func TestFetchEmpheralCert(t *testing.T) {
func TestFetchEphemeralCert(t *testing.T) {
ctx := context.Background()

client, err := sqladmin.NewService(ctx)
Expand Down

0 comments on commit eb06ae2

Please sign in to comment.