package pool
import (
"context"
"net"
"sync"
"sync/atomic"
)
type PubSubStats struct {
Created uint32
Untracked uint32
Active uint32
}
type PubSubPool struct {
opt *Options
netDialer func (ctx context .Context , network, addr string ) (net .Conn , error )
activeConns sync .Map
closed atomic .Bool
stats PubSubStats
}
func NewPubSubPool (opt *Options , netDialer func (ctx context .Context , network , addr string ) (net .Conn , error )) *PubSubPool {
return &PubSubPool {
opt : opt ,
netDialer : netDialer ,
}
}
func (p *PubSubPool ) NewConn (ctx context .Context , network string , addr string , channels []string ) (*Conn , error ) {
if p .closed .Load () {
return nil , ErrClosed
}
netConn , err := p .netDialer (ctx , network , addr )
if err != nil {
return nil , err
}
cn := NewConnWithBufferSize (netConn , p .opt .ReadBufferSize , p .opt .WriteBufferSize )
cn .pubsub = true
cn .SetPoolName (p .opt .Name )
atomic .AddUint32 (&p .stats .Created , 1 )
return cn , nil
}
func (p *PubSubPool ) TrackConn (cn *Conn ) {
atomic .AddUint32 (&p .stats .Active , 1 )
p .activeConns .Store (cn .GetID (), cn )
if cb := getMetricConnectionCountCallback (); cb != nil {
cb (context .Background (), 1 , cn , "used" , true )
}
}
func (p *PubSubPool ) UntrackConn (cn *Conn ) {
if _ , loaded := p .activeConns .LoadAndDelete (cn .GetID ()); !loaded {
return
}
atomic .AddUint32 (&p .stats .Active , ^uint32 (0 ))
atomic .AddUint32 (&p .stats .Untracked , 1 )
if cb := getMetricConnectionCountCallback (); cb != nil {
cb (context .Background (), -1 , cn , "used" , true )
}
}
func (p *PubSubPool ) Close () error {
p .closed .Store (true )
cb := getMetricConnectionCountCallback ()
p .activeConns .Range (func (key , value interface {}) bool {
cn := value .(*Conn )
if _ , loaded := p .activeConns .LoadAndDelete (key ); !loaded {
return true
}
atomic .AddUint32 (&p .stats .Active , ^uint32 (0 ))
atomic .AddUint32 (&p .stats .Untracked , 1 )
if cb != nil {
cb (context .Background (), -1 , cn , "used" , true )
}
_ = cn .Close ()
return true
})
return nil
}
func (p *PubSubPool ) Stats () *PubSubStats {
return &PubSubStats {
Created : atomic .LoadUint32 (&p .stats .Created ),
Untracked : atomic .LoadUint32 (&p .stats .Untracked ),
Active : atomic .LoadUint32 (&p .stats .Active ),
}
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .