|
| 1 | +package worker |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "database/sql" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "sync" |
| 9 | + |
| 10 | + "github.com/prometheus/client_golang/prometheus" |
| 11 | + "github.com/prometheus/client_golang/prometheus/promauto" |
| 12 | +) |
| 13 | + |
| 14 | +// LeaderLocker exposes PostgreSQL advisory-lock behavior for singleton worker jobs. |
| 15 | +type LeaderLocker interface { |
| 16 | + AcquireLock(ctx context.Context, key int64) (bool, error) |
| 17 | + ReleaseLock(ctx context.Context, key int64) error |
| 18 | + Close() error |
| 19 | +} |
| 20 | + |
| 21 | +// postgresLeaderLocker holds a dedicated SQL connection so advisory locks can be |
| 22 | +// released by the same session that acquired them. |
| 23 | +type postgresLeaderLocker struct { |
| 24 | + conn *sql.Conn |
| 25 | +} |
| 26 | + |
| 27 | +func NewPostgresLeaderLocker(db *sql.DB) (LeaderLocker, error) { |
| 28 | + if db == nil { |
| 29 | + return nil, errors.New("database connection required for leader election") |
| 30 | + } |
| 31 | + |
| 32 | + conn, err := db.Conn(context.Background()) |
| 33 | + if err != nil { |
| 34 | + return nil, fmt.Errorf("acquire leader-election connection: %w", err) |
| 35 | + } |
| 36 | + |
| 37 | + return &postgresLeaderLocker{conn: conn}, nil |
| 38 | +} |
| 39 | + |
| 40 | +func (l *postgresLeaderLocker) AcquireLock(ctx context.Context, key int64) (bool, error) { |
| 41 | + if l == nil || l.conn == nil { |
| 42 | + return false, errors.New("leader-election connection unavailable") |
| 43 | + } |
| 44 | + |
| 45 | + var acquired bool |
| 46 | + err := l.conn.QueryRowContext(ctx, "SELECT pg_try_advisory_lock($1)", key).Scan(&acquired) |
| 47 | + if err != nil { |
| 48 | + return false, fmt.Errorf("acquire advisory lock: %w", err) |
| 49 | + } |
| 50 | + return acquired, nil |
| 51 | +} |
| 52 | + |
| 53 | +func (l *postgresLeaderLocker) ReleaseLock(ctx context.Context, key int64) error { |
| 54 | + if l == nil || l.conn == nil { |
| 55 | + return nil |
| 56 | + } |
| 57 | + |
| 58 | + var released bool |
| 59 | + err := l.conn.QueryRowContext(ctx, "SELECT pg_advisory_unlock($1)", key).Scan(&released) |
| 60 | + if err != nil { |
| 61 | + return fmt.Errorf("release advisory lock: %w", err) |
| 62 | + } |
| 63 | + _ = released |
| 64 | + return nil |
| 65 | +} |
| 66 | + |
| 67 | +func (l *postgresLeaderLocker) Close() error { |
| 68 | + if l == nil || l.conn == nil { |
| 69 | + return nil |
| 70 | + } |
| 71 | + conn := l.conn |
| 72 | + l.conn = nil |
| 73 | + return conn.Close() |
| 74 | +} |
| 75 | + |
| 76 | +var ( |
| 77 | + leaderStatusMetricsOnce sync.Once |
| 78 | + leaderStatusMetrics *prometheus.GaugeVec |
| 79 | +) |
| 80 | + |
| 81 | +func initLeaderStatusMetrics() { |
| 82 | + leaderStatusMetricsOnce.Do(func() { |
| 83 | + leaderStatusMetrics = promauto.NewGaugeVec(prometheus.GaugeOpts{ |
| 84 | + Name: "leader_status", |
| 85 | + Help: "Whether a singleton worker job currently holds the advisory lock.", |
| 86 | + }, []string{"job"}) |
| 87 | + }) |
| 88 | +} |
| 89 | + |
| 90 | +func setLeaderStatus(job string, value float64) { |
| 91 | + initLeaderStatusMetrics() |
| 92 | + leaderStatusMetrics.WithLabelValues(job).Set(value) |
| 93 | +} |
| 94 | + |
| 95 | +var errNotLeader = errors.New("not leader") |
| 96 | + |
| 97 | +type leaderGuard struct { |
| 98 | + locker LeaderLocker |
| 99 | + job string |
| 100 | + key int64 |
| 101 | + |
| 102 | + mu sync.Mutex |
| 103 | + hold bool |
| 104 | +} |
| 105 | + |
| 106 | +func newLeaderGuard(locker LeaderLocker, job string, key int64) *leaderGuard { |
| 107 | + return &leaderGuard{locker: locker, job: job, key: key} |
| 108 | +} |
| 109 | + |
| 110 | +func (g *leaderGuard) Run(ctx context.Context, fn func(context.Context) error) error { |
| 111 | + if g == nil || g.locker == nil { |
| 112 | + return fn(ctx) |
| 113 | + } |
| 114 | + |
| 115 | + acquired, err := g.locker.AcquireLock(ctx, g.key) |
| 116 | + if err != nil { |
| 117 | + setLeaderStatus(g.job, 0) |
| 118 | + return fmt.Errorf("acquire leader lock for %s: %w", g.job, err) |
| 119 | + } |
| 120 | + if !acquired { |
| 121 | + setLeaderStatus(g.job, 0) |
| 122 | + return errNotLeader |
| 123 | + } |
| 124 | + |
| 125 | + g.mu.Lock() |
| 126 | + g.hold = true |
| 127 | + g.mu.Unlock() |
| 128 | + setLeaderStatus(g.job, 1) |
| 129 | + |
| 130 | + defer func() { |
| 131 | + g.mu.Lock() |
| 132 | + hold := g.hold |
| 133 | + g.hold = false |
| 134 | + g.mu.Unlock() |
| 135 | + if hold { |
| 136 | + setLeaderStatus(g.job, 0) |
| 137 | + _ = g.locker.ReleaseLock(context.Background(), g.key) |
| 138 | + } |
| 139 | + }() |
| 140 | + |
| 141 | + return fn(ctx) |
| 142 | +} |
| 143 | + |
| 144 | +func (g *leaderGuard) Release(ctx context.Context) { |
| 145 | + if g == nil || g.locker == nil { |
| 146 | + return |
| 147 | + } |
| 148 | + |
| 149 | + g.mu.Lock() |
| 150 | + if !g.hold { |
| 151 | + g.mu.Unlock() |
| 152 | + return |
| 153 | + } |
| 154 | + g.hold = false |
| 155 | + g.mu.Unlock() |
| 156 | + |
| 157 | + setLeaderStatus(g.job, 0) |
| 158 | + _ = g.locker.ReleaseLock(ctx, g.key) |
| 159 | +} |
| 160 | + |
| 161 | +func (g *leaderGuard) Close() error { |
| 162 | + if g == nil || g.locker == nil { |
| 163 | + return nil |
| 164 | + } |
| 165 | + return g.locker.Close() |
| 166 | +} |
0 commit comments