From 36bab9c8dc72a894c81a2d23171c95a0815af8d8 Mon Sep 17 00:00:00 2001 From: Oleg Stotsky Date: Thu, 15 Feb 2024 00:14:50 +0400 Subject: [PATCH] fix ConnPool race in newConn (#2885) Co-authored-by: Oleg Stotskiy Co-authored-by: ofekshenawa <104765379+ofekshenawa@users.noreply.github.com> --- internal/pool/pool.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/internal/pool/pool.go b/internal/pool/pool.go index 986c05d0..2125f3e1 100644 --- a/internal/pool/pool.go +++ b/internal/pool/pool.go @@ -168,9 +168,12 @@ func (p *ConnPool) newConn(ctx context.Context, pooled bool) (*Conn, error) { return nil, ErrClosed } + p.connsMu.Lock() if p.cfg.MaxActiveConns > 0 && p.poolSize >= p.cfg.MaxActiveConns { + p.connsMu.Unlock() return nil, ErrPoolExhausted } + p.connsMu.Unlock() cn, err := p.dialConn(ctx, pooled) if err != nil { @@ -180,6 +183,11 @@ func (p *ConnPool) newConn(ctx context.Context, pooled bool) (*Conn, error) { p.connsMu.Lock() defer p.connsMu.Unlock() + if p.cfg.MaxActiveConns > 0 && p.poolSize >= p.cfg.MaxActiveConns { + _ = cn.Close() + return nil, ErrPoolExhausted + } + p.conns = append(p.conns, cn) if pooled { // If pool is full remove the cn on next Put.