Debian Codegraph @

db/db.go

raw
1 package db
2
3 import (
4 "context"
5 "database/sql"
6 "sync/atomic"
7 "time"
8
9 "heckel.io/ntfy/v2/log"
10 )
11
12 const (
13 tag = "db"
14 replicaHealthCheckInitialDelay = 5 * time.Second
15 replicaHealthCheckInterval = 30 * time.Second
16 replicaHealthCheckTimeout = 10 * time.Second
17 )
18
19 // DB wraps a primary *sql.DB and optional read replicas. All standard query/exec methods
20 // delegate to the primary. The ReadOnly() method returns a *sql.DB from a healthy replica
21 // (round-robin), falling back to the primary if no replicas are configured or all are unhealthy.
22 type DB struct {
23 primary *Host
24 replicas []*Host
25 counter atomic.Uint64
26 cancel context.CancelFunc
27 }
28
29 // New creates a new DB that wraps the given primary and optional replica connections.
30 // If replicas is nil or empty, ReadOnly() simply returns the primary.
31 // Replicas start unhealthy and are checked immediately by a background goroutine.
32 func New(primary *Host, replicas []*Host) *DB {
33 ctx, cancel := context.WithCancel(context.Background())
34 d := &DB{
35 primary: primary,
36 replicas: replicas,
37 cancel: cancel,
38 }
39 if len(d.replicas) > 0 {
40 go d.healthCheckLoop(ctx)
41 }
42 return d
43 }
44
45 // Query delegates to the primary database.
46 func (d *DB) Query(query string, args ...any) (*sql.Rows, error) {
47 return d.primary.DB.Query(query, args...)
48 }
49
50 // QueryRow delegates to the primary database.
51 func (d *DB) QueryRow(query string, args ...any) *sql.Row {
52 return d.primary.DB.QueryRow(query, args...)
53 }
54
55 // Exec delegates to the primary database.
56 func (d *DB) Exec(query string, args ...any) (sql.Result, error) {
57 return d.primary.DB.Exec(query, args...)
58 }
59
60 // Begin delegates to the primary database.
61 func (d *DB) Begin() (*sql.Tx, error) {
62 return d.primary.DB.Begin()
63 }
64
65 // Ping delegates to the primary database.
66 func (d *DB) Ping() error {
67 return d.primary.DB.Ping()
68 }
69
70 // Primary returns the underlying primary *sql.DB. This is only intended for
71 // one-time schema setup during store initialization, not for regular queries.
72 func (d *DB) Primary() *sql.DB {
73 return d.primary.DB
74 }
75
76 // ReadOnly returns a *sql.DB suitable for read-only queries. It round-robins across healthy
77 // replicas. If all replicas are unhealthy or none are configured, the primary is returned.
78 func (d *DB) ReadOnly() *sql.DB {
79 if len(d.replicas) == 0 {
80 return d.primary.DB
81 }
82 n := len(d.replicas)
83 start := int(d.counter.Add(1) - 1)
84 for i := 0; i < n; i++ {
85 r := d.replicas[(start+i)%n]
86 if r.healthy.Load() {
87 return r.DB
88 }
89 }
90 return d.primary.DB
91 }
92
93 // MarkReplicasHealthyForTest immediately marks all configured replicas as healthy, bypassing the
94 // async health-check loop's initial delay. It exists so tests can deterministically route
95 // ReadOnly() to a replica without waiting; it is not used in production code.
96 func (d *DB) MarkReplicasHealthyForTest() {
97 for _, r := range d.replicas {
98 r.healthy.Store(true)
99 }
100 }
101
102 // Close closes the primary database and all replicas, and stops the health-check goroutine.
103 func (d *DB) Close() error {
104 d.cancel()
105 for _, r := range d.replicas {
106 r.DB.Close()
107 }
108 return d.primary.DB.Close()
109 }
110
111 // healthCheckLoop checks replicas immediately, then periodically on a ticker.
112 func (d *DB) healthCheckLoop(ctx context.Context) {
113 select {
114 case <-ctx.Done():
115 return
116 case <-time.After(replicaHealthCheckInitialDelay):
117 d.checkReplicas(ctx)
118 }
119 for {
120 select {
121 case <-ctx.Done():
122 return
123 case <-time.After(replicaHealthCheckInterval):
124 d.checkReplicas(ctx)
125 }
126 }
127 }
128
129 // checkReplicas pings each replica with a timeout and updates its health status.
130 func (d *DB) checkReplicas(ctx context.Context) {
131 for _, r := range d.replicas {
132 wasHealthy := r.healthy.Load()
133 pingCtx, cancel := context.WithTimeout(ctx, replicaHealthCheckTimeout)
134 err := r.DB.PingContext(pingCtx)
135 cancel()
136 if err != nil {
137 r.healthy.Store(false)
138 log.Tag(tag).Error("Database replica %s is unhealthy: %s", r.Addr, err)
139 } else {
140 r.healthy.Store(true)
141 if !wasHealthy {
142 log.Tag(tag).Info("Database replica %s is healthy", r.Addr)
143 }
144 }
145 }
146 }