|
| 1 | +package mysql |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "database/sql" |
| 6 | + "strings" |
| 7 | + "time" |
| 8 | + |
| 9 | + _ "github.com/go-sql-driver/mysql" |
| 10 | + |
| 11 | + "github.com/unkeyed/unkey/pkg/assert" |
| 12 | + "github.com/unkeyed/unkey/pkg/fault" |
| 13 | + "github.com/unkeyed/unkey/pkg/logger" |
| 14 | + "github.com/unkeyed/unkey/pkg/retry" |
| 15 | +) |
| 16 | + |
| 17 | +// Config defines the parameters needed to establish database connections. |
| 18 | +// It supports separate connections for read and write operations to allow |
| 19 | +// for primary/replica setups. |
| 20 | +type Config struct { |
| 21 | + // The primary DSN for your database. This must support both reads and writes. |
| 22 | + PrimaryDSN string |
| 23 | + |
| 24 | + // The readonly replica will be used for most read queries. |
| 25 | + // If omitted, the primary is used. |
| 26 | + ReadOnlyDSN string |
| 27 | +} |
| 28 | + |
| 29 | +// database implements the Database interface, providing access to database replicas |
| 30 | +// and handling connection lifecycle. |
| 31 | +type database struct { |
| 32 | + writeReplica *Replica // Primary database connection used for write operations |
| 33 | + readReplica *Replica // Connection used for read operations (may be same as primary) |
| 34 | +} |
| 35 | + |
| 36 | +func open(dsn string) (db *sql.DB, err error) { |
| 37 | + if !strings.Contains(dsn, "parseTime=true") { |
| 38 | + return nil, fault.New("DSN must contain parseTime=true, see https://stackoverflow.com/questions/29341590/how-to-parse-time-from-database/29343013#29343013") |
| 39 | + } |
| 40 | + |
| 41 | + // sql.Open only validates the DSN, it doesn't actually connect. |
| 42 | + // We need to call Ping() to verify connectivity. |
| 43 | + db, err = sql.Open("mysql", dsn) |
| 44 | + if err != nil { |
| 45 | + return nil, fault.Wrap(err, fault.Internal("failed to open database")) |
| 46 | + } |
| 47 | + |
| 48 | + // Configure connection pool for better performance |
| 49 | + // These settings prevent cold-start latency by maintaining warm connections |
| 50 | + db.SetMaxOpenConns(25) // Max concurrent connections |
| 51 | + db.SetMaxIdleConns(10) // Keep 10 idle connections ready |
| 52 | + db.SetConnMaxLifetime(5 * time.Minute) // Refresh connections every 5 min (PlanetScale recommendation) |
| 53 | + db.SetConnMaxIdleTime(1 * time.Minute) // Close idle connections after 1 min of inactivity |
| 54 | + |
| 55 | + // Verify connectivity at startup with retries - this establishes at least one connection |
| 56 | + // so the first request doesn't pay the connection establishment cost |
| 57 | + err = retry.New( |
| 58 | + retry.Attempts(5), |
| 59 | + retry.Backoff(func(n int) time.Duration { |
| 60 | + return time.Duration(n) * time.Second |
| 61 | + }), |
| 62 | + ).Do(func() error { |
| 63 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 64 | + defer cancel() |
| 65 | + pingErr := db.PingContext(ctx) |
| 66 | + if pingErr != nil { |
| 67 | + logger.Info("mysql not ready yet, retrying...", "error", pingErr.Error()) |
| 68 | + } |
| 69 | + return pingErr |
| 70 | + }) |
| 71 | + if err != nil { |
| 72 | + _ = db.Close() |
| 73 | + return nil, fault.Wrap(err, fault.Internal("failed to ping database after retries")) |
| 74 | + } |
| 75 | + |
| 76 | + logger.Info("database connection pool initialized successfully") |
| 77 | + return db, nil |
| 78 | +} |
| 79 | + |
| 80 | +func NewReplica(url string, mode string) (*Replica, error) { |
| 81 | + db, err := open(url) |
| 82 | + if err != nil { |
| 83 | + return nil, fault.Wrap(err, fault.Internal("cannot open replica")) |
| 84 | + } |
| 85 | + |
| 86 | + return &Replica{ |
| 87 | + db: db, |
| 88 | + mode: mode, |
| 89 | + debugLogs: false, |
| 90 | + }, nil |
| 91 | +} |
| 92 | + |
| 93 | +// New creates a new database instance with the provided configuration. |
| 94 | +// It establishes connections to the primary database and optionally to a read-only replica. |
| 95 | +// Returns an error if connections cannot be established or if DSNs are misconfigured. |
| 96 | +func New(config Config) (*database, error) { |
| 97 | + err := assert.All( |
| 98 | + assert.NotEmpty(config.PrimaryDSN), |
| 99 | + ) |
| 100 | + if err != nil { |
| 101 | + return nil, fault.Wrap(err, fault.Internal("invalid configuration")) |
| 102 | + } |
| 103 | + |
| 104 | + // Initialize primary replica |
| 105 | + writeReplica, err := NewReplica(config.PrimaryDSN, "rw") |
| 106 | + if err != nil { |
| 107 | + return nil, fault.Wrap(err, fault.Internal("cannot initialize primary replica")) |
| 108 | + } |
| 109 | + |
| 110 | + // Initialize read replica with primary by default |
| 111 | + readReplica := &Replica{ |
| 112 | + db: writeReplica.db, |
| 113 | + mode: "rw", |
| 114 | + debugLogs: false, |
| 115 | + } |
| 116 | + |
| 117 | + // If a separate read-only DSN is provided, establish that connection |
| 118 | + if config.ReadOnlyDSN != "" { |
| 119 | + readReplica, err = NewReplica(config.ReadOnlyDSN, "ro") |
| 120 | + if err != nil { |
| 121 | + return nil, fault.Wrap(err, fault.Internal("cannot initialize read replica")) |
| 122 | + } |
| 123 | + logger.Info("database configured with separate read replica") |
| 124 | + } else { |
| 125 | + logger.Info("database configured without separate read replica, using primary for reads") |
| 126 | + } |
| 127 | + |
| 128 | + return &database{ |
| 129 | + writeReplica: writeReplica, |
| 130 | + readReplica: readReplica, |
| 131 | + }, nil |
| 132 | +} |
| 133 | + |
| 134 | +// RW returns the write replica for performing database write operations. |
| 135 | +func (d *database) RW() *Replica { |
| 136 | + return d.writeReplica |
| 137 | +} |
| 138 | + |
| 139 | +// RO returns the read replica for performing database read operations. |
| 140 | +// If no dedicated read replica is configured, it returns the write replica. |
| 141 | +func (d *database) RO() *Replica { |
| 142 | + if d.readReplica != nil { |
| 143 | + return d.readReplica |
| 144 | + } |
| 145 | + return d.writeReplica |
| 146 | +} |
| 147 | + |
| 148 | +// Close properly closes all database connections. |
| 149 | +// This should be called when the application is shutting down. |
| 150 | +func (d *database) Close() error { |
| 151 | + // Close the write replica connection |
| 152 | + writeCloseErr := d.writeReplica.db.Close() |
| 153 | + |
| 154 | + // Only close the read replica if it's a separate connection |
| 155 | + if d.readReplica != nil { |
| 156 | + readCloseErr := d.readReplica.db.Close() |
| 157 | + if readCloseErr != nil { |
| 158 | + return fault.Wrap(readCloseErr) |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + // Return any write replica close error |
| 163 | + if writeCloseErr != nil { |
| 164 | + return fault.Wrap(writeCloseErr) |
| 165 | + } |
| 166 | + return nil |
| 167 | +} |
0 commit comments