forked from go-gorm/dbresolver
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhealth.go
More file actions
420 lines (345 loc) · 11.7 KB
/
health.go
File metadata and controls
420 lines (345 loc) · 11.7 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
package dbresolver
import (
"context"
"database/sql"
"errors"
"fmt"
"net"
"reflect"
"strings"
"time"
"gorm.io/gorm"
)
// ErrorClassifier determines if an error should cause a replica to be marked as bad.
type ErrorClassifier func(err error) bool
// DefaultErrorClassifier detects unambiguous instance-level failures where the
// entire replica endpoint is unreachable. These errors cannot be caused by a single
// expired connection — they indicate the server itself is down or unreachable.
//
// Use this when your connection pool (database/sql, pgxpool) is properly configured
// to handle idle connection expiration internally (which they do by default).
func DefaultErrorClassifier(err error) bool {
if err == nil {
return false
}
// Application-level context errors are not replica failures.
// Must be checked before the net.Error check below because
// context.DeadlineExceeded implements net.Error (Timeout() == true).
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false
}
msg := err.Error()
// pgx validation error (replica incorrectly configured as read-only)
if strings.Contains(msg, "ValidateConnect failed") && strings.Contains(msg, "not read only") {
return true
}
// net.Error covers network-level timeouts (TCP connect, DNS) — instance-level issues.
// context.DeadlineExceeded also implements net.Error but is excluded above.
var netErr net.Error
if errors.As(err, &netErr) {
// Connection pool exhaustion is a concurrency issue, not a replica failure.
// Catching it here would mark a healthy replica as bad under high load.
l := strings.ToLower(msg)
if strings.Contains(l, "timeout acquiring conn from pool") ||
strings.Contains(l, "connection pool exhausted") ||
strings.Contains(l, "conn busy") {
return false
}
return true
}
l := strings.ToLower(msg)
// Unambiguous: server refused all connections (port closed) or DNS failed
if strings.Contains(l, "connection refused") ||
strings.Contains(l, "no such host") {
return true
}
return false
}
// StrictConnectionErrorClassifier extends DefaultErrorClassifier to also catch
// connection-level errors that are ambiguous: they can result from either a single
// idle connection being recycled by the server, or from the server going down.
//
// Modern pools (database/sql, pgxpool) handle idle connection recycling internally
// via driver.ErrBadConn and automatic retry. If these errors still escape to the
// application, it most likely means the server closed an in-use connection (not
// just idle), which indicates a real replica problem.
//
// Use this classifier if you observe false negatives with DefaultErrorClassifier
// (i.e., a failing replica is not being marked as bad).
func StrictConnectionErrorClassifier(err error) bool {
if DefaultErrorClassifier(err) {
return true
}
l := strings.ToLower(err.Error())
return strings.Contains(l, "broken pipe") ||
strings.Contains(l, "connection reset by peer") ||
strings.Contains(l, "server closed the connection") ||
strings.Contains(l, "eof") ||
strings.Contains(l, "i/o timeout")
}
// registerHealthCallbacks registers GORM callbacks that track replica health.
// When a query fails on a replica with a transient error, the replica is marked as bad.
// When a query succeeds on a previously-bad replica, it's unmarked (recovered).
func (dr *DBResolver) registerHealthCallbacks(db *gorm.DB) error {
if dr.healthTracker == nil || dr.errorClassifier == nil {
return nil // Health tracking not enabled
}
// Track errors after Query callback (Find, First, Take, etc.)
if err := db.Callback().Query().After("gorm:query").
Register("dbresolver:track_query_health", dr.trackQueryHealth); err != nil {
return err
}
// Track errors after Row callback (db.Raw().Scan())
if err := db.Callback().Row().After("gorm:row").
Register("dbresolver:track_row_health", dr.trackRowHealth); err != nil {
return err
}
// Track successes to unmark recovered replicas
if err := db.Callback().Query().After("dbresolver:track_query_health").
Register("dbresolver:track_query_success", dr.trackQuerySuccess); err != nil {
return err
}
if err := db.Callback().Row().After("dbresolver:track_row_health").
Register("dbresolver:track_row_success", dr.trackRowSuccess); err != nil {
return err
}
return nil
}
// trackQueryHealth marks a replica as bad if a query fails with a transient error
func (dr *DBResolver) trackQueryHealth(tx *gorm.DB) {
if tx == nil || tx.Statement == nil || tx.Error == nil {
return
}
// Only track read operations (not writes)
if !looksLikeSelectOp(tx.Statement) {
return
}
// Don't track errors within transactions (can't switch mid-transaction)
if isSQLTx(tx.Statement.ConnPool) {
return
}
// Check if this error indicates an unhealthy replica
if !dr.errorClassifier(tx.Error) {
return
}
// Mark the bad replica
if tx.Statement.ConnPool != nil {
dr.healthTracker.MarkBad(tx.Statement.ConnPool)
tx.Logger.Warn(tx.Statement.Context, "Marked replica as unhealthy temporary: %v", tx.Error)
}
// Retry on writer if enabled
if !dr.retryOnWriter || alreadyRetried(tx.Statement.Context) {
return
}
// Capture Dest immediately while it's still available
dest := tx.Statement.Dest
if isNilInterface(dest) {
return
}
tx.Logger.Info(tx.Statement.Context, "Retrying query on writer after replica failure")
// Clear error before retry
tx.Error = nil
// Optional delay before retry
if dr.retryDelay > 0 {
time.Sleep(dr.retryDelay)
}
// Mark context as retried to prevent infinite loops
tx.Statement.Context = markRetried(tx.Statement.Context)
// Force writer routing
tx.Clauses(Write)
// Ensure we don't reuse the failing pool
tx.Statement.ConnPool = nil
// Keep the existing Dest for the retry
tx.Statement.Dest = dest
// Re-execute the Query callback
tx.Callback().Query().Execute(tx)
}
// trackRowHealth marks a replica as bad if a Raw().Scan() fails with a transient error
func (dr *DBResolver) trackRowHealth(tx *gorm.DB) {
if tx == nil || tx.Statement == nil || tx.Error == nil {
return
}
// Only track read operations
if !looksLikeSelectOp(tx.Statement) {
return
}
// Don't track errors within transactions
if isSQLTx(tx.Statement.ConnPool) {
return
}
// Check if this error indicates an unhealthy replica
if !dr.errorClassifier(tx.Error) {
return
}
// Mark the bad replica
if tx.Statement.ConnPool != nil {
dr.healthTracker.MarkBad(tx.Statement.ConnPool)
tx.Logger.Warn(tx.Statement.Context, "Marked replica as unhealthy temporary: %v", tx.Error)
}
// Retry on writer if enabled
if !dr.retryOnWriter || alreadyRetried(tx.Statement.Context) {
return
}
tx.Logger.Info(tx.Statement.Context, "Retrying row query on writer after replica failure")
// Clear error before retry
tx.Error = nil
// Optional delay before retry
if dr.retryDelay > 0 {
time.Sleep(dr.retryDelay)
}
// Mark context as retried to prevent infinite loops
tx.Statement.Context = markRetried(tx.Statement.Context)
// Force writer routing
tx.Clauses(Write)
// Ensure we don't reuse the failing pool
tx.Statement.ConnPool = nil
tx.Statement.Dest = nil
tx.Set("rows", true)
tx.Callback().Row().Execute(tx)
// Check for errors in the retry
switch d := tx.Statement.Dest.(type) {
case *sql.Rows:
if d != nil && d.Err() != nil {
tx.Error = d.Err()
}
case nil:
tx.Error = errors.New("no rows returned from retry")
default:
tx.Error = fmt.Errorf("unexpected dest type %T", tx.Statement.Dest)
}
}
// looksLikeSelectOp returns true if the statement appears to be a read operation
func looksLikeSelectOp(stmt *gorm.Statement) bool {
if stmt == nil {
return false
}
sqlText := strings.TrimSpace(strings.ToUpper(stmt.SQL.String()))
if sqlText == "" {
// Query/Row callbacks are typically read paths
return true
}
return strings.HasPrefix(sqlText, "SELECT") ||
strings.HasPrefix(sqlText, "WITH") ||
strings.HasPrefix(sqlText, "SHOW") ||
strings.HasPrefix(sqlText, "EXPLAIN")
}
// isSQLTx returns true if the pool is a SQL transaction
func isSQLTx(pool gorm.ConnPool) bool {
if pool == nil {
return false
}
_, ok := pool.(*sql.Tx)
return ok
}
// Context key for tracking retries
type ctxKey string
const retriedKey ctxKey = "dbresolver_retried"
// alreadyRetried checks if a context has already been retried
func alreadyRetried(ctx context.Context) bool {
if ctx == nil {
return false
}
v := ctx.Value(retriedKey)
b, _ := v.(bool)
return b
}
// markRetried marks a context as having been retried
func markRetried(ctx context.Context) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, retriedKey, true)
}
// isNilInterface checks if an interface value is nil or contains a nil pointer
func isNilInterface(v interface{}) bool {
if v == nil {
return true
}
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Func, reflect.Interface, reflect.Chan:
return rv.IsNil()
default:
return false
}
}
// trackQuerySuccess unmarks a replica as bad when a query succeeds on it.
// With consecutive success tracking, this increments the success counter
// and only fully recovers the replica after N consecutive successes.
func (dr *DBResolver) trackQuerySuccess(tx *gorm.DB) {
if tx == nil || tx.Statement == nil {
return
}
// Only track successful read operations
if tx.Error != nil {
return
}
if !looksLikeSelectOp(tx.Statement) {
return
}
// Don't track transactions
if isSQLTx(tx.Statement.ConnPool) {
return
}
// Track success for pools that are in the bad list (including half-open state)
if tx.Statement.ConnPool != nil && dr.healthTracker != nil {
pool := tx.Statement.ConnPool
// Check if pool is being tracked (in bad list, including half-open state)
wasTracking, _, _ := dr.healthTracker.isTracking(pool)
if wasTracking {
// Mark as healthy (increments counter or fully recovers)
dr.healthTracker.MarkHealthy(pool)
// Check post-state for appropriate logging
stillTracking, currentSuccesses, neededSuccesses := dr.healthTracker.isTracking(pool)
if stillTracking {
tx.Logger.Info(tx.Statement.Context,
"Replica success %d/%d for recovery",
currentSuccesses, neededSuccesses)
} else {
tx.Logger.Info(tx.Statement.Context,
"Replica fully recovered after %d consecutive successes",
neededSuccesses)
}
}
}
}
// trackRowSuccess unmarks a replica as bad when a row query succeeds on it.
// With consecutive success tracking, this increments the success counter
// and only fully recovers the replica after N consecutive successes.
func (dr *DBResolver) trackRowSuccess(tx *gorm.DB) {
if tx == nil || tx.Statement == nil {
return
}
// Only track successful read operations
if tx.Error != nil {
return
}
if !looksLikeSelectOp(tx.Statement) {
return
}
// Don't track transactions
if isSQLTx(tx.Statement.ConnPool) {
return
}
// Track success for pools that are in the bad list (including half-open state)
if tx.Statement.ConnPool != nil && dr.healthTracker != nil {
pool := tx.Statement.ConnPool
// Check if pool is being tracked (in bad list, including half-open state)
wasTracking, _, _ := dr.healthTracker.isTracking(pool)
if wasTracking {
// Mark as healthy (increments counter or fully recovers)
dr.healthTracker.MarkHealthy(pool)
// Check post-state for appropriate logging
stillTracking, currentSuccesses, neededSuccesses := dr.healthTracker.isTracking(pool)
if stillTracking {
tx.Logger.Info(tx.Statement.Context,
"Replica (row) success %d/%d for recovery",
currentSuccesses, neededSuccesses)
} else {
tx.Logger.Info(tx.Statement.Context,
"Replica (row) fully recovered after %d consecutive successes",
neededSuccesses)
}
}
}
}