|
| 1 | +package postgres |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" |
| 10 | + "gorm.io/gorm" |
| 11 | +) |
| 12 | + |
| 13 | +// SessionLock represents a lock record in the database |
| 14 | +type SessionLock struct { |
| 15 | + Key string `gorm:"primaryKey"` |
| 16 | + ExpiresAt time.Time |
| 17 | + CreatedAt time.Time |
| 18 | + UpdatedAt time.Time |
| 19 | +} |
| 20 | + |
| 21 | +// Lock implements the sessions.Lock interface using a custom table. |
| 22 | +// This implementation uses a dedicated table to track locks with expiration times. |
| 23 | +// |
| 24 | +// Important notes about this implementation: |
| 25 | +// 1. Locks have built-in expiration functionality |
| 26 | +// 2. Locks are automatically cleaned up when they expire |
| 27 | +// 3. The lock key is stored directly in the table |
| 28 | +// 4. If the database connection is lost, the lock will be automatically released |
| 29 | +type Lock struct { |
| 30 | + db *gorm.DB |
| 31 | + key string |
| 32 | +} |
| 33 | + |
| 34 | +// NewLock creates a new PostgreSQL lock instance |
| 35 | +func NewLock(db *gorm.DB, key string) sessions.Lock { |
| 36 | + return &Lock{ |
| 37 | + db: db, |
| 38 | + key: key, |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +// Obtain obtains a lock by inserting a record into the session_lock table. |
| 43 | +// If a lock already exists and hasn't expired, it will return ErrLockNotObtained. |
| 44 | +func (l *Lock) Obtain(ctx context.Context, expiration time.Duration) error { |
| 45 | + // Verify database connection is healthy |
| 46 | + if err := l.verifyConnection(ctx); err != nil { |
| 47 | + return fmt.Errorf("database connection error: %w", err) |
| 48 | + } |
| 49 | + |
| 50 | + // Start a transaction to ensure atomicity |
| 51 | + tx := l.db.WithContext(ctx).Begin() |
| 52 | + if tx.Error != nil { |
| 53 | + return fmt.Errorf("error starting transaction: %w", tx.Error) |
| 54 | + } |
| 55 | + defer func() { |
| 56 | + if r := recover(); r != nil { |
| 57 | + tx.Rollback() |
| 58 | + } |
| 59 | + }() |
| 60 | + |
| 61 | + // Clean up expired locks |
| 62 | + if err := tx.Where("expires_at < ?", time.Now()).Delete(&SessionLock{}).Error; err != nil { |
| 63 | + tx.Rollback() |
| 64 | + return fmt.Errorf("error cleaning up expired locks: %w", err) |
| 65 | + } |
| 66 | + |
| 67 | + // Check if lock exists and is valid |
| 68 | + var existingLock SessionLock |
| 69 | + err := tx.Where("key = ?", l.key).First(&existingLock).Error |
| 70 | + if err == nil { |
| 71 | + // Lock exists and hasn't expired |
| 72 | + tx.Rollback() |
| 73 | + return sessions.ErrLockNotObtained |
| 74 | + } |
| 75 | + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 76 | + tx.Rollback() |
| 77 | + return fmt.Errorf("error checking existing lock: %w", err) |
| 78 | + } |
| 79 | + |
| 80 | + // Create new lock |
| 81 | + lock := &SessionLock{ |
| 82 | + Key: l.key, |
| 83 | + ExpiresAt: time.Now().Add(expiration), |
| 84 | + } |
| 85 | + if err := tx.Create(lock).Error; err != nil { |
| 86 | + tx.Rollback() |
| 87 | + return fmt.Errorf("error creating lock: %w", err) |
| 88 | + } |
| 89 | + |
| 90 | + return tx.Commit().Error |
| 91 | +} |
| 92 | + |
| 93 | +// Peek checks if the lock is still held by checking if it exists and hasn't expired |
| 94 | +func (l *Lock) Peek(ctx context.Context) (bool, error) { |
| 95 | + // Verify database connection is healthy |
| 96 | + if err := l.verifyConnection(ctx); err != nil { |
| 97 | + return false, fmt.Errorf("database connection error: %w", err) |
| 98 | + } |
| 99 | + |
| 100 | + // Clean up expired locks |
| 101 | + if err := l.db.WithContext(ctx).Where("expires_at < ?", time.Now()).Delete(&SessionLock{}).Error; err != nil { |
| 102 | + return false, fmt.Errorf("error cleaning up expired locks: %w", err) |
| 103 | + } |
| 104 | + |
| 105 | + // Check if lock exists and is valid |
| 106 | + var lock SessionLock |
| 107 | + err := l.db.WithContext(ctx).Where("key = ?", l.key).First(&lock).Error |
| 108 | + if err == nil { |
| 109 | + return true, nil |
| 110 | + } |
| 111 | + if err == gorm.ErrRecordNotFound { |
| 112 | + return false, nil |
| 113 | + } |
| 114 | + return false, fmt.Errorf("error checking lock: %w", err) |
| 115 | +} |
| 116 | + |
| 117 | +// Refresh refreshes the lock by updating its expiration time |
| 118 | +func (l *Lock) Refresh(ctx context.Context, expiration time.Duration) error { |
| 119 | + // Verify database connection is healthy |
| 120 | + if err := l.verifyConnection(ctx); err != nil { |
| 121 | + return fmt.Errorf("database connection error: %w", err) |
| 122 | + } |
| 123 | + |
| 124 | + // Start a transaction to ensure atomicity |
| 125 | + tx := l.db.WithContext(ctx).Begin() |
| 126 | + if tx.Error != nil { |
| 127 | + return fmt.Errorf("error starting transaction: %w", tx.Error) |
| 128 | + } |
| 129 | + defer func() { |
| 130 | + if r := recover(); r != nil { |
| 131 | + tx.Rollback() |
| 132 | + } |
| 133 | + }() |
| 134 | + |
| 135 | + // First verify we hold the lock |
| 136 | + var existingLock SessionLock |
| 137 | + err := tx.Where("key = ? AND expires_at > ?", l.key, time.Now()).First(&existingLock).Error |
| 138 | + if err != nil { |
| 139 | + tx.Rollback() |
| 140 | + if errors.Is(err, gorm.ErrRecordNotFound) { |
| 141 | + return sessions.ErrNotLocked |
| 142 | + } |
| 143 | + return fmt.Errorf("error checking existing lock: %w", err) |
| 144 | + } |
| 145 | + |
| 146 | + // Update lock expiration |
| 147 | + result := tx.Model(&SessionLock{}). |
| 148 | + Where("key = ?", l.key). |
| 149 | + Update("expires_at", time.Now().Add(expiration)) |
| 150 | + if result.Error != nil { |
| 151 | + tx.Rollback() |
| 152 | + return fmt.Errorf("error refreshing lock: %w", result.Error) |
| 153 | + } |
| 154 | + if result.RowsAffected == 0 { |
| 155 | + tx.Rollback() |
| 156 | + return sessions.ErrNotLocked |
| 157 | + } |
| 158 | + |
| 159 | + return tx.Commit().Error |
| 160 | +} |
| 161 | + |
| 162 | +// Release releases the lock by deleting the record from the session_lock table |
| 163 | +func (l *Lock) Release(ctx context.Context) error { |
| 164 | + // Verify database connection is healthy |
| 165 | + if err := l.verifyConnection(ctx); err != nil { |
| 166 | + return fmt.Errorf("database connection error: %w", err) |
| 167 | + } |
| 168 | + |
| 169 | + // Start a transaction to ensure atomicity |
| 170 | + tx := l.db.WithContext(ctx).Begin() |
| 171 | + if tx.Error != nil { |
| 172 | + return fmt.Errorf("error starting transaction: %w", tx.Error) |
| 173 | + } |
| 174 | + defer func() { |
| 175 | + if r := recover(); r != nil { |
| 176 | + tx.Rollback() |
| 177 | + } |
| 178 | + }() |
| 179 | + |
| 180 | + // Clean up expired locks |
| 181 | + if err := tx.Where("expires_at < ?", time.Now()).Delete(&SessionLock{}).Error; err != nil { |
| 182 | + tx.Rollback() |
| 183 | + return fmt.Errorf("error cleaning up expired locks: %w", err) |
| 184 | + } |
| 185 | + |
| 186 | + // Delete the lock |
| 187 | + result := tx.Where("key = ?", l.key).Delete(&SessionLock{}) |
| 188 | + if result.Error != nil { |
| 189 | + tx.Rollback() |
| 190 | + return fmt.Errorf("error releasing lock: %w", result.Error) |
| 191 | + } |
| 192 | + if result.RowsAffected == 0 { |
| 193 | + tx.Rollback() |
| 194 | + return sessions.ErrNotLocked |
| 195 | + } |
| 196 | + |
| 197 | + return tx.Commit().Error |
| 198 | +} |
| 199 | + |
| 200 | +// verifyConnection checks if the database connection is healthy |
| 201 | +func (l *Lock) verifyConnection(ctx context.Context) error { |
| 202 | + sqlDB, err := l.db.DB() |
| 203 | + if err != nil { |
| 204 | + return fmt.Errorf("error getting database instance: %w", err) |
| 205 | + } |
| 206 | + if err := sqlDB.PingContext(ctx); err != nil { |
| 207 | + return fmt.Errorf("error pinging database: %w", err) |
| 208 | + } |
| 209 | + return nil |
| 210 | +} |
0 commit comments