File: pool.go

package info (click to toggle)
golang-github-bsm-pool 0.8.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 88 kB
  • sloc: makefile: 14
file content (203 lines) | stat: -rw-r--r-- 3,624 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Package pool is a generic, high-performance pool for net.Conn
// objects.
package pool

import (
	"net"
	"sync"
	"sync/atomic"
	"time"
)

// Factory must returns new connections
type Factory func() (net.Conn, error)

// Options can tweak Pool configuration
type Options struct {
	// InitialSize creates a number of connection on pool initialization
	// Default: 0
	InitialSize int

	// MaxCap sets the maximum pool capacity. Will be automatically adjusted when InitialSize
	// is larger.
	// Default: 10
	MaxCap int

	// IdleTimeout timeout after which connections are reaped and
	// automatically removed from the pool.
	// Default: 0 (= never)
	IdleTimeout time.Duration

	// ReapInterval determines the frequency of reap cycles
	// Default: 1 minute
	ReapInterval time.Duration
}

func (o *Options) norm() Options {
	x := *o
	if x.ReapInterval <= 0 {
		x.ReapInterval = time.Minute
	}
	if x.MaxCap <= 0 {
		x.MaxCap = 10
	}
	if x.MaxCap < x.InitialSize {
		x.MaxCap = x.InitialSize
	}
	return x
}

type none struct{}

// Pool contains a number of connections
type Pool struct {
	conns   []member
	opt     Options
	factory Factory

	dying, dead chan none

	avail  uint32
	closed int32

	mu sync.Mutex
}

// New creates a pool with an initial number of connection and a maximum cap
func New(opt *Options, factory Factory) (*Pool, error) {
	if opt == nil {
		opt = new(Options)
	}

	p := &Pool{
		conns:   make([]member, 0, opt.MaxCap),
		factory: factory,
		opt:     opt.norm(),
		dying:   make(chan none),
		dead:    make(chan none),
	}

	for i := 0; i < opt.InitialSize; i++ {
		cn, err := factory()
		if err != nil {
			_ = p.close()
			return nil, err
		}
		p.Put(cn)
	}

	go p.loop()
	return p, nil
}

// Len returns the number of available connections in the pool
func (s *Pool) Len() int { return int(atomic.LoadUint32(&s.avail)) }

// Get returns a connection from the pool or creates a new one
func (s *Pool) Get() (net.Conn, error) {
	if cn := s.pop(); cn != nil {
		return cn, nil
	}

	return s.factory()
}

// Put adds/returns a connection to the pool
func (s *Pool) Put(cn net.Conn) bool {
	if s.Len() >= s.opt.MaxCap || atomic.LoadInt32(&s.closed) == 1 {
		_ = cn.Close()
		return false
	}

	m := member{cn: cn, lastAccess: time.Now()}
	s.mu.Lock()
	s.conns = append(s.conns, m)
	atomic.StoreUint32(&s.avail, uint32(len(s.conns)))
	s.mu.Unlock()

	return true
}

// Close closes all connections and the pool
func (s *Pool) Close() error {
	if !atomic.CompareAndSwapInt32(&s.closed, 0, 1) {
		return nil
	}

	close(s.dying)
	<-s.dead
	return s.close()
}

func (s *Pool) pop() net.Conn {
	s.mu.Lock()

	pos := len(s.conns) - 1
	if pos < 0 {
		s.mu.Unlock()
		return nil
	}

	m := s.conns[pos]
	s.conns = s.conns[:pos]
	atomic.StoreUint32(&s.avail, uint32(len(s.conns)))
	s.mu.Unlock()

	return m.cn

}

func (s *Pool) close() (err error) {
	for {
		cn := s.pop()
		if cn == nil {
			break
		}
		if e := cn.Close(); e != nil {
			err = e
		}
	}
	return err
}

func (s *Pool) reap() {
	timeout := s.opt.IdleTimeout
	if timeout <= 0 {
		return
	}

	cutoff := time.Now().Add(-timeout)

	s.mu.Lock()
	if sz := len(s.conns); sz != 0 {
		if m := s.conns[0]; m.lastAccess.Before(cutoff) {
			defer m.cn.Close()

			copy(s.conns, s.conns[1:])
			s.conns = s.conns[:sz-1]
			atomic.StoreUint32(&s.avail, uint32(len(s.conns)))
		}
	}
	s.mu.Unlock()
}

func (s *Pool) loop() {
	defer close(s.dead)

	ticker := time.NewTicker(s.opt.ReapInterval)
	defer ticker.Stop()

	for {
		select {
		case <-s.dying:
			return
		case <-ticker.C:
			s.reap()
		}
	}
}

type member struct {
	cn         net.Conn
	lastAccess time.Time
}