Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

client: properly close down internal idpool on Close #68

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"io"
"net"
"net/http"
"runtime"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -68,19 +69,25 @@ type idPool struct {
}

// AllocID implements Client.AllocID
func (p *idPool) Alloc() uint16 {
func (p idPool) Alloc() (id uint16) {
return <-p.IDs
}

// ReleaseID implements Client.ReleaseID
func (p *idPool) Release(id uint16) {
func (p idPool) Release(id uint16) {
go func() {
defer recoverSendOnClosedChannel()

// release the ID back to channel for reuse
// use goroutine to prev0, ent blocking ReleaseID
p.IDs <- id
}()
}

func (p idPool) Close() {
close(p.IDs)
}

func newIDs(limit uint32) (p idPool) {

// sanatize limit
Expand Down Expand Up @@ -342,14 +349,19 @@ func (c *client) Do(req *Request) (resp *ResponsePipe, err error) {
}

// Close implements Client.Close
//
// If the inner connection has been closed before,
// this method would do nothing and return nil
// this method would do nothing and return nil.
//
// This will also close the IDPool.
func (c *client) Close() (err error) {
// Close inner connection.
if c.conn == nil {
return
}
err = c.conn.Close()
c.conn = nil
c.ids.Close() // close the
return
}

Expand Down Expand Up @@ -585,3 +597,17 @@ func (c ClientFunc) Do(req *Request) (resp *ResponsePipe, err error) {
func (c ClientFunc) Close() error {
return nil
}

func recoverSendOnClosedChannel() {
if r := recover(); r != nil {
switch v := r.(type) {
case runtime.Error:
if v.Error() == "send on closed channel" {
// ignore
return
}
default:
panic(r)
}
}
}