Skip to content

Commit 51f6fcc

Browse files
monkey92tndyakov
authored andcommitted
feat: recover addIdleConn may occur panic (#2445)
* feat: recover addIdleConn may occur panic Signed-off-by: monkey92t <[email protected]> * fix test race Signed-off-by: monkey92t <[email protected]> --------- Signed-off-by: monkey92t <[email protected]> Co-authored-by: Nedyalko Dyakov <[email protected]>
1 parent ef444ea commit 51f6fcc

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

internal/pool/export_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,13 @@ 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.connsMu.Lock()
18+
p.checkMinIdleConns()
19+
p.connsMu.Unlock()
20+
}
21+
22+
func (p *ConnPool) QueueLen() int {
23+
return len(p.queue)
24+
}

internal/pool/pool.go

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

132132
go func() {
133+
defer func() {
134+
if err := recover(); err != nil {
135+
p.connsMu.Lock()
136+
p.poolSize--
137+
p.idleConnsLen--
138+
p.connsMu.Unlock()
139+
140+
p.freeTurn()
141+
internal.Logger.Printf(context.Background(), "addIdleConn panic: %+v", err)
142+
}
143+
}()
144+
133145
err := p.addIdleConn()
134146
if err != nil && err != ErrClosed {
135147
p.connsMu.Lock()

internal/pool/pool_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,24 @@ var _ = Describe("race", func() {
361361
Expect(stats.TotalConns).To(Equal(uint32(opt.PoolSize)))
362362
})
363363

364+
It("recover addIdleConn panic", func() {
365+
opt := &pool.Options{
366+
Dialer: func(ctx context.Context) (net.Conn, error) {
367+
panic("test panic")
368+
},
369+
PoolSize: 100,
370+
MinIdleConns: 30,
371+
}
372+
p := pool.NewConnPool(opt)
373+
374+
p.CheckMinIdleConns()
375+
376+
Eventually(func() bool {
377+
state := p.Stats()
378+
return state.TotalConns == 0 && state.IdleConns == 0 && p.QueueLen() == 0
379+
}, "3s", "50ms").Should(BeTrue())
380+
})
381+
364382
It("wait", func() {
365383
opt := &pool.Options{
366384
Dialer: func(ctx context.Context) (net.Conn, error) {

0 commit comments

Comments
 (0)