Skip to content

Commit 6f383d8

Browse files
committed
feat: recover addIdleConn may occur panic
Signed-off-by: monkey92t <[email protected]>
1 parent bd0d1c2 commit 6f383d8

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

internal/pool/export_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,11 @@ func (cn *Conn) SetCreatedAt(tm time.Time) {
1212
func (cn *Conn) NetConn() net.Conn {
1313
return cn.netConn
1414
}
15+
16+
func (p *ConnPool) CheckMinIdleConns() {
17+
p.checkMinIdleConns()
18+
}
19+
20+
func (p *ConnPool) QueueLen() int {
21+
return len(p.queue)
22+
}

internal/pool/pool.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,18 @@ func (p *ConnPool) checkMinIdleConns() {
118118
p.idleConnsLen++
119119

120120
go func() {
121+
defer func() {
122+
if err := recover(); err != nil {
123+
p.connsMu.Lock()
124+
p.poolSize--
125+
p.idleConnsLen--
126+
p.connsMu.Unlock()
127+
128+
p.freeTurn()
129+
internal.Logger.Printf(context.Background(), "addIdleConn panic: %+v", err)
130+
}
131+
}()
132+
121133
err := p.addIdleConn()
122134
if err != nil && err != ErrClosed {
123135
p.connsMu.Lock()

internal/pool/pool_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,4 +353,22 @@ var _ = Describe("race", func() {
353353
Expect(stats.IdleConns).To(Equal(uint32(0)))
354354
Expect(stats.TotalConns).To(Equal(uint32(opt.PoolSize)))
355355
})
356+
357+
It("recover addIdleConn panic", func() {
358+
opt := &pool.Options{
359+
Dialer: func(ctx context.Context) (net.Conn, error) {
360+
panic("test panic")
361+
},
362+
PoolSize: 100,
363+
MinIdleConns: 30,
364+
}
365+
p := pool.NewConnPool(opt)
366+
367+
p.CheckMinIdleConns()
368+
369+
Eventually(func() bool {
370+
state := p.Stats()
371+
return state.TotalConns == 0 && state.IdleConns == 0 && p.QueueLen() == 0
372+
}, "3s", "50ms").Should(BeTrue())
373+
})
356374
})

0 commit comments

Comments
 (0)