Documentation
¶
Overview ¶
Package leaderelection provides Postgres advisory lock-based leader election.
A single Postgres session-scoped advisory lock determines the leader. The lock is held for the lifetime of the dedicated database connection; there is no renewal or TTL. If the connection dies, Postgres automatically releases the lock server-side (timing depends on TCP keepalive settings).
The heartbeat ping exists solely to detect local connection death so the leader can stop its duties promptly. It does NOT renew the lock.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Elector ¶
type Elector struct {
// contains filtered or unexported fields
}
Elector manages leader election using a Postgres advisory lock.
func New ¶
func New( db *sql.DB, lockKey int64, retryInterval, heartbeatInterval time.Duration, onElected func(ctx context.Context), onDemoted func(), ) *Elector
New creates a new Elector.
onElected is called in a new goroutine when this instance acquires the lock. The provided context is cancelled when leadership is lost. onElected should start leader duties (scheduler, reconciler) and return quickly.
onDemoted is called synchronously when leadership is lost. It should stop leader duties and block until they are fully stopped. It must be idempotent.
func (*Elector) WithMetrics ¶
func (e *Elector) WithMetrics(sink MetricsSink) *Elector
WithMetrics attaches a metrics sink to the elector.
type MetricsSink ¶
type MetricsSink interface {
LeaderStatusChanged(isLeader bool)
LeaderAcquired()
LeaderLost(reason string) // reason: "shutdown", "conn_lost", "error"
}
MetricsSink defines the interface for recording leader election metrics. All methods must be non-blocking and fire-and-forget.