Repository navigation
Expand file tree
/
Copy pathpool.go
More file actions
429 lines (353 loc) · 10.8 KB
/
Copy pathpool.go
File metadata and controls
429 lines (353 loc) · 10.8 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package pgpool
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"go.uber.org/zap"
)
// DatabasePool manages a pool of PostgreSQL connections for a single database
type DatabasePool struct {
// Pool name for identification
name string
// Primary connection pool
primary *pgxpool.Pool
// Replica pools for read scaling
replicas []*pgxpool.Pool
// Configuration
config *BackendConfig
// Logger
log *zap.Logger
// Statistics
stats *PoolStats
// Lifecycle management
mu sync.RWMutex
closed atomic.Bool
// Circuit breaker for backend health
circuitBreaker *CircuitBreaker
}
// PoolStats tracks pool usage metrics
type PoolStats struct {
// Connection statistics
TotalConnections int32
IdleConnections int32
ActiveConnections int32
WaitingClients int32
TotalAcquired int64
TotalReleased int64
AcquireCount int64
AcquireDuration time.Duration
CanceledAcquireCount int64
ConstructingConns int32
MaxConnections int32
// Query statistics
QueryCount int64
QueryDuration time.Duration
ErrorCount int64
SlowQueryCount int64
// Pool health
HealthChecksPassed int64
HealthChecksFailed int64
LastHealthCheck time.Time
LastError error
mu sync.RWMutex
}
// NewDatabasePool creates a new connection pool for the specified database
func NewDatabasePool(
name string,
config *BackendConfig,
log *zap.Logger,
) (*DatabasePool, error) {
pool := &DatabasePool{
name: name,
config: config,
log: log,
stats: &PoolStats{},
}
// Initialize circuit breaker
pool.circuitBreaker = NewCircuitBreaker(
5, // max failures
30*time.Second, // timeout
log.Named("circuit_breaker"),
)
// Create primary connection pool
if err := pool.initPrimaryPool(); err != nil {
return nil, fmt.Errorf("failed to initialize primary pool: %w", err)
}
log.Info("database pool initialized",
zap.String("name", name),
zap.Int("max_connections", config.Pool.MaxConnections),
zap.String("mode", config.Behavior.Mode))
return pool, nil
}
// initPrimaryPool creates the pgxpool for primary database
func (p *DatabasePool) initPrimaryPool() error {
// Parse DSN
dsn := p.config.BuildDSN()
// Build pool configuration
poolConfig, err := pgxpool.ParseConfig(dsn)
if err != nil {
return fmt.Errorf("invalid DSN: %w", err)
}
// Apply pool settings
poolConfig.MaxConns = int32(p.config.Pool.MaxConnections)
poolConfig.MinConns = int32(p.config.Pool.MinConnections)
poolConfig.MaxConnLifetime = p.config.Pool.MaxLifetime
poolConfig.MaxConnIdleTime = p.config.Pool.MaxIdleTime
poolConfig.HealthCheckPeriod = p.config.Pool.HealthCheckPeriod
// Configure connection behavior
poolConfig.BeforeAcquire = p.beforeAcquire
poolConfig.AfterRelease = p.afterRelease
poolConfig.BeforeClose = p.beforeClose
// Set query timeout if configured
if p.config.Behavior.QueryTimeout > 0 {
poolConfig.ConnConfig.ConnectTimeout = p.config.Behavior.QueryTimeout
}
// Create pool with context
ctx := context.Background()
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return fmt.Errorf("failed to create pool: %w", err)
}
// Lazy connect or test connection immediately
if !p.config.Behavior.LazyConnect {
if err := pool.Ping(ctx); err != nil {
pool.Close()
return fmt.Errorf("failed to ping database: %w", err)
}
p.log.Info("database connection verified")
}
p.primary = pool
return nil
}
// beforeAcquire is called before a connection is acquired from the pool
func (p *DatabasePool) beforeAcquire(ctx context.Context, conn *pgx.Conn) bool {
// Check circuit breaker state
if !p.circuitBreaker.Allow() {
p.log.Warn("circuit breaker is open, rejecting connection request")
return false
}
// Update statistics
atomic.AddInt64(&p.stats.AcquireCount, 1)
return true
}
// afterRelease is called after a connection is released back to the pool
func (p *DatabasePool) afterRelease(conn *pgx.Conn) bool {
// Update statistics
atomic.AddInt64(&p.stats.TotalReleased, 1)
// Reset connection state if configured
if p.config.Behavior.ResetOnReturn {
// Execute DISCARD ALL to reset session state
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
if _, err := conn.Exec(ctx, "DISCARD ALL"); err != nil {
p.log.Warn("failed to reset connection state", zap.Error(err))
return false // Discard this connection
}
}
return true
}
// beforeClose is called before a connection is closed
func (p *DatabasePool) beforeClose(conn *pgx.Conn) {
// Connection is being removed from pool
p.log.Debug("connection closed")
}
// Acquire obtains a connection from the pool
// The connection must be released back to the pool when done
func (p *DatabasePool) Acquire(ctx context.Context) (*pgxpool.Conn, error) {
if p.closed.Load() {
return nil, fmt.Errorf("pool is closed")
}
// Apply acquisition timeout from config
if p.config.Pool.AcquireTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, p.config.Pool.AcquireTimeout)
defer cancel()
}
start := time.Now()
conn, err := p.primary.Acquire(ctx)
duration := time.Since(start)
// Update statistics
p.stats.mu.Lock()
p.stats.AcquireDuration += duration
atomic.AddInt64(&p.stats.TotalAcquired, 1)
p.stats.mu.Unlock()
if err != nil {
atomic.AddInt64(&p.stats.ErrorCount, 1)
p.circuitBreaker.RecordFailure()
return nil, fmt.Errorf("failed to acquire connection: %w", err)
}
p.circuitBreaker.RecordSuccess()
return conn, nil
}
// Query executes a query and returns the result rows
func (p *DatabasePool) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) {
if p.closed.Load() {
return nil, fmt.Errorf("pool is closed")
}
start := time.Now()
rows, err := p.primary.Query(ctx, sql, args...)
duration := time.Since(start)
// Update statistics
atomic.AddInt64(&p.stats.QueryCount, 1)
p.stats.mu.Lock()
p.stats.QueryDuration += duration
p.stats.mu.Unlock()
// Log slow queries
if p.config.Behavior.QueryTimeout > 0 && duration > p.config.Behavior.QueryTimeout {
atomic.AddInt64(&p.stats.SlowQueryCount, 1)
p.log.Warn("slow query detected",
zap.Duration("duration", duration),
zap.String("query", sql))
}
if err != nil {
atomic.AddInt64(&p.stats.ErrorCount, 1)
p.circuitBreaker.RecordFailure()
return nil, err
}
p.circuitBreaker.RecordSuccess()
return rows, nil
}
// QueryRow executes a query that returns at most one row
func (p *DatabasePool) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {
if p.closed.Load() {
// Return an error row
return &errorRow{err: fmt.Errorf("pool is closed")}
}
start := time.Now()
row := p.primary.QueryRow(ctx, sql, args...)
duration := time.Since(start)
// Update statistics
atomic.AddInt64(&p.stats.QueryCount, 1)
p.stats.mu.Lock()
p.stats.QueryDuration += duration
p.stats.mu.Unlock()
// Log slow queries
if p.config.Behavior.QueryTimeout > 0 && duration > p.config.Behavior.QueryTimeout {
atomic.AddInt64(&p.stats.SlowQueryCount, 1)
p.log.Warn("slow query detected",
zap.Duration("duration", duration),
zap.String("query", sql))
}
return row
}
// Exec executes a command (INSERT, UPDATE, DELETE, etc.)
func (p *DatabasePool) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) {
if p.closed.Load() {
return pgconn.CommandTag{}, fmt.Errorf("pool is closed")
}
start := time.Now()
tag, err := p.primary.Exec(ctx, sql, args...)
duration := time.Since(start)
// Update statistics
atomic.AddInt64(&p.stats.QueryCount, 1)
p.stats.mu.Lock()
p.stats.QueryDuration += duration
p.stats.mu.Unlock()
if err != nil {
atomic.AddInt64(&p.stats.ErrorCount, 1)
p.circuitBreaker.RecordFailure()
return tag, err
}
p.circuitBreaker.RecordSuccess()
return tag, nil
}
// Begin starts a new transaction
func (p *DatabasePool) Begin(ctx context.Context) (pgx.Tx, error) {
if p.closed.Load() {
return nil, fmt.Errorf("pool is closed")
}
tx, err := p.primary.Begin(ctx)
if err != nil {
atomic.AddInt64(&p.stats.ErrorCount, 1)
p.circuitBreaker.RecordFailure()
return nil, err
}
p.circuitBreaker.RecordSuccess()
return tx, nil
}
// HealthCheck verifies pool connectivity and health
func (p *DatabasePool) HealthCheck(ctx context.Context) error {
if p.closed.Load() {
return fmt.Errorf("pool is closed")
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Ping the database
err := p.primary.Ping(ctx)
// Update health check statistics
p.stats.mu.Lock()
p.stats.LastHealthCheck = time.Now()
if err != nil {
p.stats.LastError = err
atomic.AddInt64(&p.stats.HealthChecksFailed, 1)
p.circuitBreaker.RecordFailure()
} else {
atomic.AddInt64(&p.stats.HealthChecksPassed, 1)
p.circuitBreaker.RecordSuccess()
}
p.stats.mu.Unlock()
return err
}
// Stats returns current pool statistics
func (p *DatabasePool) Stats() *PoolStats {
if p.primary == nil {
return p.stats
}
// Get pgxpool stats
pgxStats := p.primary.Stat()
// Copy statistics atomically
stats := &PoolStats{
TotalConnections: pgxStats.TotalConns(),
IdleConnections: pgxStats.IdleConns(),
ActiveConnections: pgxStats.AcquiredConns(),
ConstructingConns: pgxStats.ConstructingConns(),
MaxConnections: pgxStats.MaxConns(),
TotalAcquired: atomic.LoadInt64(&p.stats.TotalAcquired),
TotalReleased: atomic.LoadInt64(&p.stats.TotalReleased),
AcquireCount: atomic.LoadInt64(&p.stats.AcquireCount),
CanceledAcquireCount: atomic.LoadInt64(&p.stats.CanceledAcquireCount),
QueryCount: atomic.LoadInt64(&p.stats.QueryCount),
ErrorCount: atomic.LoadInt64(&p.stats.ErrorCount),
SlowQueryCount: atomic.LoadInt64(&p.stats.SlowQueryCount),
HealthChecksPassed: atomic.LoadInt64(&p.stats.HealthChecksPassed),
HealthChecksFailed: atomic.LoadInt64(&p.stats.HealthChecksFailed),
}
p.stats.mu.RLock()
stats.AcquireDuration = p.stats.AcquireDuration
stats.QueryDuration = p.stats.QueryDuration
stats.LastHealthCheck = p.stats.LastHealthCheck
stats.LastError = p.stats.LastError
p.stats.mu.RUnlock()
return stats
}
// Close gracefully shuts down the pool
func (p *DatabasePool) Close(ctx context.Context) error {
if !p.closed.CompareAndSwap(false, true) {
return fmt.Errorf("pool already closed")
}
p.log.Info("closing database pool", zap.String("name", p.name))
// Close primary pool
if p.primary != nil {
p.primary.Close()
}
// Close replica pools
for _, replica := range p.replicas {
if replica != nil {
replica.Close()
}
}
p.log.Info("database pool closed successfully", zap.String("name", p.name))
return nil
}
// errorRow is a pgx.Row that always returns an error
type errorRow struct {
err error
}
func (e *errorRow) Scan(dest ...interface{}) error {
return e.err
}