Skip to content

Commit

Permalink
Merge pull request #5 from randall-fulton/factory-failure-draining-pool
Browse files Browse the repository at this point in the history
Restore semaphore on failure creating new conn
  • Loading branch information
buraksezer authored Sep 7, 2022
2 parents 590c63f + b46b2c0 commit 2a06e4c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
2 changes: 2 additions & 0 deletions channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ func (c *channelPool) Get(ctx context.Context) (net.Conn, error) {
case c.semaphore <- struct{}{}:
conn, err := factory()
if err != nil {
// restore claimed slot, otherwise max is permanently decreased
<-c.semaphore
return nil, err
}

Expand Down
29 changes: 29 additions & 0 deletions channel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,3 +412,32 @@ func TestPool_ClosedConnectionsReplaced(t *testing.T) {
t.Errorf("expected non-nil conn")
}
}

func TestPool_FailedFactoryRestoresConnectionSlot(t *testing.T) {
// regression test to ensure failed factory doesn't permanently decrease connection max
// this happened previously due to semaphore not being released when factory failed
factory := func() (net.Conn, error) {
// a dial guaranteed to fail
return net.DialTimeout("tcp", "localhost:1234", time.Millisecond)
}

max := 2
pool, err := NewChannelPool(0, max, factory)
if err != nil {
t.Fatalf("error creating pool: %v", err)
}

for i := 0; i < max+1; i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
defer cancel()

conn, err := pool.Get(ctx)
if err == nil && conn != nil {
conn.Close()
}
}

if len(pool.(*channelPool).semaphore) != 0 {
t.Fatal("max connections decreased")
}
}

0 comments on commit 2a06e4c

Please sign in to comment.