Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
442 lines (352 loc) · 12.2 KB
/
Copy pathconfig.go
File metadata and controls
442 lines (352 loc) · 12.2 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
430
431
432
433
434
435
436
437
438
439
440
441
442
package pgpool
import (
"fmt"
"time"
)
// Config represents the complete plugin configuration structure
type Config struct {
// Enabled determines if the plugin is active
Enabled bool `mapstructure:"enabled"`
// Proxy configuration for PostgreSQL wire protocol server
Proxy ProxyConfig `mapstructure:"proxy"`
// Backends defines database connections
Backends BackendsConfig `mapstructure:"backends"`
// Routing configuration for read/write splitting
Routing RoutingConfig `mapstructure:"routing"`
// Monitoring and metrics configuration
Monitoring MonitoringConfig `mapstructure:"monitoring"`
// Logging configuration
Logging LoggingConfig `mapstructure:"logging"`
// Advanced features configuration
Features FeaturesConfig `mapstructure:"features"`
// Additional database configurations
Databases map[string]DatabaseConfig `mapstructure:"databases"`
}
// ProxyConfig defines the local proxy server settings
type ProxyConfig struct {
// Address where the proxy listens (e.g., "tcp://127.0.0.1:5433")
Address string `mapstructure:"address"`
// MaxClients limits concurrent client connections
MaxClients int `mapstructure:"max_clients"`
// ClientTimeout for idle client connections
ClientTimeout time.Duration `mapstructure:"client_timeout"`
// AuthMode specifies authentication method: "none", "password", "trust"
AuthMode string `mapstructure:"auth_mode"`
}
// BackendsConfig defines primary and replica database connections
type BackendsConfig struct {
// Primary database configuration
Primary BackendConfig `mapstructure:"primary"`
// Replicas for read scaling (optional)
Replicas []ReplicaConfig `mapstructure:"replicas"`
}
// BackendConfig defines a single database backend configuration
type BackendConfig struct {
// DSN is the PostgreSQL connection string
DSN string `mapstructure:"dsn"`
// Alternative structured configuration
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Database string `mapstructure:"database"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
SSLMode string `mapstructure:"sslmode"`
// Pool configuration
Pool PoolConfig `mapstructure:"pool"`
// Behavior configuration
Behavior BehaviorConfig `mapstructure:"behavior"`
}
// PoolConfig defines connection pool parameters
type PoolConfig struct {
// MaxConnections is the maximum number of connections in the pool
MaxConnections int `mapstructure:"max_connections"`
// MinConnections is the minimum idle connections to maintain
MinConnections int `mapstructure:"min_connections"`
// MaxLifetime is the maximum connection lifetime
MaxLifetime time.Duration `mapstructure:"max_lifetime"`
// MaxIdleTime is the maximum idle time before closing
MaxIdleTime time.Duration `mapstructure:"max_idle_time"`
// HealthCheckPeriod for periodic connection validation
HealthCheckPeriod time.Duration `mapstructure:"health_check_period"`
// AcquireTimeout when waiting for available connection
AcquireTimeout time.Duration `mapstructure:"acquire_timeout"`
// WaitQueueSize limits pending connection requests
WaitQueueSize int `mapstructure:"wait_queue_size"`
}
// BehaviorConfig defines connection behavior settings
type BehaviorConfig struct {
// Mode specifies pooling mode: "session", "transaction", "statement", "auto"
Mode string `mapstructure:"mode"`
// ResetOnReturn resets connection state when returned to pool
ResetOnReturn bool `mapstructure:"reset_on_return"`
// LazyConnect delays connection establishment until first use
LazyConnect bool `mapstructure:"lazy_connect"`
// StatementCacheSize for prepared statements per connection
StatementCacheSize int `mapstructure:"statement_cache_size"`
// QueryTimeout for individual queries (0 = no timeout)
QueryTimeout time.Duration `mapstructure:"query_timeout"`
}
// ReplicaConfig extends BackendConfig with replica-specific settings
type ReplicaConfig struct {
BackendConfig `mapstructure:",squash"`
// Weight for load balancing (higher = more traffic)
Weight int `mapstructure:"weight"`
}
// RoutingConfig defines query routing behavior
type RoutingConfig struct {
// ReadWriteSplit enables automatic read/write query routing
ReadWriteSplit bool `mapstructure:"read_write_split"`
// ReadPatterns are regex patterns identifying read queries
ReadPatterns []string `mapstructure:"read_patterns"`
// WritePatterns are regex patterns identifying write queries
WritePatterns []string `mapstructure:"write_patterns"`
// LoadBalance strategy: "round_robin", "least_connections", "random", "weighted"
LoadBalance string `mapstructure:"load_balance"`
// Failover configuration
Failover FailoverConfig `mapstructure:"failover"`
}
// FailoverConfig defines failover behavior
type FailoverConfig struct {
// Enabled allows automatic failover to replicas
Enabled bool `mapstructure:"enabled"`
// RetryInterval before retrying failed backend
RetryInterval time.Duration `mapstructure:"retry_interval"`
// MaxFailures before marking backend as down
MaxFailures int `mapstructure:"max_failures"`
}
// MonitoringConfig defines metrics and monitoring settings
type MonitoringConfig struct {
// Enabled activates metrics collection
Enabled bool `mapstructure:"enabled"`
// Interval between metrics updates
Interval time.Duration `mapstructure:"interval"`
// ExposeRPC makes metrics available via RPC
ExposeRPC bool `mapstructure:"expose_rpc"`
// Prometheus configuration
Prometheus PrometheusConfig `mapstructure:"prometheus"`
// Collect specifies which metrics to gather
Collect []string `mapstructure:"collect"`
}
// PrometheusConfig defines Prometheus metrics settings
type PrometheusConfig struct {
// Enabled exposes Prometheus metrics
Enabled bool `mapstructure:"enabled"`
// Namespace for metrics
Namespace string `mapstructure:"namespace"`
// Subsystem for metrics
Subsystem string `mapstructure:"subsystem"`
}
// LoggingConfig defines logging behavior
type LoggingConfig struct {
// Level specifies log level: "debug", "info", "warn", "error"
Level string `mapstructure:"level"`
// SlowQuery logging configuration
SlowQuery SlowQueryConfig `mapstructure:"slow_query"`
// LogQueries enables query logging (debug mode)
LogQueries bool `mapstructure:"log_queries"`
// LogParams includes query parameters in logs
LogParams bool `mapstructure:"log_params"`
}
// SlowQueryConfig defines slow query logging
type SlowQueryConfig struct {
// Enabled activates slow query logging
Enabled bool `mapstructure:"enabled"`
// Threshold for slow query detection
Threshold time.Duration `mapstructure:"threshold"`
}
// FeaturesConfig defines optional advanced features
type FeaturesConfig struct {
// Cache configuration for query results
Cache CacheConfig `mapstructure:"cache"`
// CircuitBreaker for backend failure handling
CircuitBreaker CircuitBreakerConfig `mapstructure:"circuit_breaker"`
// RateLimit per client configuration
RateLimit RateLimitConfig `mapstructure:"rate_limit"`
}
// CacheConfig defines query caching layer
type CacheConfig struct {
// Enabled activates query caching
Enabled bool `mapstructure:"enabled"`
// TTL for cached results
TTL time.Duration `mapstructure:"ttl"`
// MaxSize limits cache memory usage
MaxSize string `mapstructure:"max_size"`
}
// CircuitBreakerConfig defines circuit breaker behavior
type CircuitBreakerConfig struct {
// Enabled activates circuit breaker
Enabled bool `mapstructure:"enabled"`
// Threshold of failures to open circuit
Threshold int `mapstructure:"threshold"`
// Timeout before attempting reset
Timeout time.Duration `mapstructure:"timeout"`
}
// RateLimitConfig defines rate limiting per client
type RateLimitConfig struct {
// Enabled activates rate limiting
Enabled bool `mapstructure:"enabled"`
// RequestsPerSecond allowed per client
RequestsPerSecond int `mapstructure:"requests_per_second"`
// Burst allows temporary exceeding of rate limit
Burst int `mapstructure:"burst"`
}
// DatabaseConfig defines configuration for additional databases
type DatabaseConfig struct {
// Primary backend for this database
Primary BackendConfig `mapstructure:"primary"`
// Routing configuration (optional, inherits from global if not set)
Routing *RoutingConfig `mapstructure:"routing"`
}
// Validate checks configuration for errors and applies defaults
func (c *Config) Validate() error {
if !c.Enabled {
return fmt.Errorf("plugin is disabled")
}
// Validate proxy configuration
if c.Proxy.Address == "" {
return fmt.Errorf("proxy.address is required")
}
// Apply default values
c.applyDefaults()
// Validate primary backend
if err := c.Backends.Primary.Validate(); err != nil {
return fmt.Errorf("primary backend validation failed: %w", err)
}
// Validate replicas
for i, replica := range c.Backends.Replicas {
if err := replica.BackendConfig.Validate(); err != nil {
return fmt.Errorf("replica %d validation failed: %w", i, err)
}
}
// Validate additional databases
for name, dbConfig := range c.Databases {
if err := dbConfig.Primary.Validate(); err != nil {
return fmt.Errorf("database %s validation failed: %w", name, err)
}
}
return nil
}
// applyDefaults sets default values for unspecified configuration options
func (c *Config) applyDefaults() {
// Proxy defaults
if c.Proxy.MaxClients == 0 {
c.Proxy.MaxClients = 100
}
if c.Proxy.ClientTimeout == 0 {
c.Proxy.ClientTimeout = 30 * time.Second
}
if c.Proxy.AuthMode == "" {
c.Proxy.AuthMode = "trust"
}
// Monitoring defaults
if c.Monitoring.Interval == 0 {
c.Monitoring.Interval = 10 * time.Second
}
if c.Monitoring.Prometheus.Namespace == "" {
c.Monitoring.Prometheus.Namespace = "roadrunner"
}
if c.Monitoring.Prometheus.Subsystem == "" {
c.Monitoring.Prometheus.Subsystem = "pgpool"
}
// Logging defaults
if c.Logging.Level == "" {
c.Logging.Level = "info"
}
if c.Logging.SlowQuery.Threshold == 0 {
c.Logging.SlowQuery.Threshold = 100 * time.Millisecond
}
// Apply defaults to backends
c.Backends.Primary.applyDefaults()
for i := range c.Backends.Replicas {
c.Backends.Replicas[i].BackendConfig.applyDefaults()
if c.Backends.Replicas[i].Weight == 0 {
c.Backends.Replicas[i].Weight = 1
}
}
}
// Validate checks backend configuration for errors
func (b *BackendConfig) Validate() error {
// Must have either DSN or structured config
if b.DSN == "" && b.Host == "" {
return fmt.Errorf("either dsn or host must be specified")
}
// Validate pool configuration
if b.Pool.MaxConnections <= 0 {
return fmt.Errorf("pool.max_connections must be positive")
}
if b.Pool.MinConnections < 0 {
return fmt.Errorf("pool.min_connections cannot be negative")
}
if b.Pool.MinConnections > b.Pool.MaxConnections {
return fmt.Errorf("pool.min_connections cannot exceed max_connections")
}
// Validate behavior mode
validModes := map[string]bool{
"session": true,
"transaction": true,
"statement": true,
"auto": true,
}
if b.Behavior.Mode != "" && !validModes[b.Behavior.Mode] {
return fmt.Errorf("invalid behavior.mode: %s", b.Behavior.Mode)
}
return nil
}
// applyDefaults sets default values for backend configuration
func (b *BackendConfig) applyDefaults() {
// Pool defaults
if b.Pool.MaxConnections == 0 {
b.Pool.MaxConnections = 25
}
if b.Pool.MinConnections == 0 {
b.Pool.MinConnections = 5
}
if b.Pool.MaxLifetime == 0 {
b.Pool.MaxLifetime = 1 * time.Hour
}
if b.Pool.MaxIdleTime == 0 {
b.Pool.MaxIdleTime = 30 * time.Minute
}
if b.Pool.HealthCheckPeriod == 0 {
b.Pool.HealthCheckPeriod = 30 * time.Second
}
if b.Pool.AcquireTimeout == 0 {
b.Pool.AcquireTimeout = 5 * time.Second
}
if b.Pool.WaitQueueSize == 0 {
b.Pool.WaitQueueSize = 100
}
// Behavior defaults
if b.Behavior.Mode == "" {
b.Behavior.Mode = "transaction"
}
if b.Behavior.StatementCacheSize == 0 {
b.Behavior.StatementCacheSize = 100
}
if b.Behavior.QueryTimeout == 0 {
b.Behavior.QueryTimeout = 30 * time.Second
}
// SSL mode default
if b.SSLMode == "" {
b.SSLMode = "prefer"
}
// Port default
if b.Port == 0 {
b.Port = 5432
}
}
// BuildDSN constructs a PostgreSQL DSN from structured configuration
func (b *BackendConfig) BuildDSN() string {
if b.DSN != "" {
return b.DSN
}
return fmt.Sprintf(
"postgres://%s:%s@%s:%d/%s?sslmode=%s",
b.User,
b.Password,
b.Host,
b.Port,
b.Database,
b.SSLMode,
)
}