Make Close() idempotent and close connection if session fails to close

This commit is contained in:
Elara 2023-01-04 14:08:18 -08:00
parent dfc248e5bb
commit 9944612ff5

View File

@ -14,9 +14,10 @@ var _ drpc.Conn = &Conn{}
// Conn implements drpc.Conn using the yamux // Conn implements drpc.Conn using the yamux
// multiplexer to allow concurrent RPCs // multiplexer to allow concurrent RPCs
type Conn struct { type Conn struct {
conn io.ReadWriteCloser conn io.ReadWriteCloser
sess *yamux.Session sess *yamux.Session
closed chan struct{} isClosed bool
closed chan struct{}
} }
// New returns a new multiplexed DRPC connection // New returns a new multiplexed DRPC connection
@ -36,13 +37,18 @@ func New(conn io.ReadWriteCloser) (*Conn, error) {
// Close closes the multiplexer session // Close closes the multiplexer session
// and the underlying connection. // and the underlying connection.
func (m *Conn) Close() error { func (m *Conn) Close() error {
defer close(m.closed) if !m.isClosed {
m.isClosed = true
defer close(m.closed)
err := m.sess.Close() err := m.sess.Close()
if err != nil { if err != nil {
return err m.conn.Close()
return err
}
return m.conn.Close()
} }
return m.conn.Close() return nil
} }
// Closed returns a channel that will be closed // Closed returns a channel that will be closed