election

package
v0.1.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 11, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateNodeID

func GenerateNodeID() string

GenerateNodeID creates a unique node ID from hostname + random bytes.

Types

type Elector

type Elector struct {

	// OnElected is called when this node becomes the leader.
	OnElected func()
	// OnDemoted is called when this node loses leadership.
	OnDemoted func()
	// contains filtered or unexported fields
}

Elector implements leader election using Redis SET NX EX + Lua refresh.

Algorithm:

  1. Attempt SET leader {nodeID} NX EX {ttl} — atomic, fails if key exists.
  2. If elected: refresh the key every TTL/3 using a Lua script.
  3. If not elected: retry step 1 at TTL/3 intervals.
  4. On graceful shutdown: delete the key for fast failover.

func NewElector

func NewElector(cfg ElectorConfig) *Elector

NewElector creates a new Redis-based elector.

func (*Elector) Epoch added in v0.1.3

func (e *Elector) Epoch() uint64

Epoch returns the current leader epoch (monotonically increasing fencing token).

func (*Elector) IsLeader

func (e *Elector) IsLeader(_ context.Context) error

IsLeader returns nil if this node is the leader, or ErrNotLeader otherwise.

func (*Elector) LeaderID

func (e *Elector) LeaderID() string

LeaderID returns the current leader's node ID.

func (*Elector) NodeID

func (e *Elector) NodeID() string

NodeID returns this elector's node ID.

func (*Elector) Start

func (e *Elector) Start(ctx context.Context) error

Start begins the election loop. Non-blocking — spawns a goroutine.

func (*Elector) Stop

func (e *Elector) Stop() error

Stop gracefully stops the elector and releases leadership if held.

type ElectorConfig

type ElectorConfig struct {
	RDB    rueidis.Client
	Prefix string
	NodeID string
	TTL    time.Duration // Default: 10s
	Logger gochainedlog.Logger
}

ElectorConfig holds configuration for the elector.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL