election

package
v0.7.4 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2025 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Campaign

type Campaign struct {
	CampaignID    string
	Term          uint64
	StartTime     time.Time
	EndTime       time.Time
	Status        CampaignStatus
	Strategy      CampaignStrategy
	TargetPeers   []string
	VoteResponses map[string]*VoteResponse
	VotesNeeded   int
	VotesGranted  int
	VotesDenied   int
	PreVotePhase  bool
	// contains filtered or unexported fields
}

Campaign represents an active election campaign.

type CampaignManager

type CampaignManager struct {
	// contains filtered or unexported fields
}

CampaignManager manages election campaigns with strategies.

func NewCampaignManager

func NewCampaignManager(config CampaignManagerConfig, logger forge.Logger) *CampaignManager

NewCampaignManager creates a new campaign manager.

func (*CampaignManager) EndCampaign

func (cm *CampaignManager) EndCampaign(status CampaignStatus)

EndCampaign ends the active campaign with a status.

func (*CampaignManager) GetActiveCampaign

func (cm *CampaignManager) GetActiveCampaign() *Campaign

GetActiveCampaign returns the active campaign.

func (*CampaignManager) GetCampaignHistory

func (cm *CampaignManager) GetCampaignHistory(limit int) []CampaignRecord

GetCampaignHistory returns campaign history.

func (*CampaignManager) GetCampaignProgress

func (cm *CampaignManager) GetCampaignProgress() *CampaignProgress

GetCampaignProgress returns campaign progress information.

func (*CampaignManager) GetCampaignStatistics

func (cm *CampaignManager) GetCampaignStatistics() CampaignStatistics

GetCampaignStatistics returns campaign statistics.

func (*CampaignManager) GetPeersToContact

func (cm *CampaignManager) GetPeersToContact(campaign *Campaign) []string

GetPeersToContact returns peers to contact based on strategy.

func (*CampaignManager) RecordVoteResponse

func (cm *CampaignManager) RecordVoteResponse(response *VoteResponse) error

RecordVoteResponse records a vote response for the active campaign.

func (*CampaignManager) StartCampaign

func (cm *CampaignManager) StartCampaign(term uint64, peers []string) (*Campaign, error)

StartCampaign starts a new election campaign.

type CampaignManagerConfig

type CampaignManagerConfig struct {
	NodeID         string
	Strategy       CampaignStrategy
	PriorityPeers  []string
	ParallelVotes  bool
	EarlyAbort     bool
	PreVoteEnabled bool
	MaxHistorySize int
}

CampaignManagerConfig contains campaign manager configuration.

type CampaignProgress

type CampaignProgress struct {
	CampaignID        string
	Term              uint64
	Status            CampaignStatus
	VotesGranted      int
	VotesDenied       int
	VotesNeeded       int
	TotalPeers        int
	ResponsesReceived int
	Duration          time.Duration
	ProgressPercent   float64
}

CampaignProgress represents campaign progress.

type CampaignRecord

type CampaignRecord struct {
	CampaignID   string
	Term         uint64
	StartTime    time.Time
	EndTime      time.Time
	Duration     time.Duration
	Status       CampaignStatus
	VotesGranted int
	VotesDenied  int
	TotalPeers   int
}

CampaignRecord represents a historical campaign record.

type CampaignStatistics

type CampaignStatistics struct {
	TotalCampaigns   int
	CampaignsWon     int
	CampaignsLost    int
	CampaignsAborted int
	AverageDuration  time.Duration
	WinRate          float64
}

CampaignStatistics contains campaign statistics.

type CampaignStatus

type CampaignStatus int

CampaignStatus represents campaign status.

const (
	// CampaignStatusActive campaign is active.
	CampaignStatusActive CampaignStatus = iota
	// CampaignStatusWon campaign was won.
	CampaignStatusWon
	// CampaignStatusLost campaign was lost.
	CampaignStatusLost
	// CampaignStatusAborted campaign was aborted.
	CampaignStatusAborted
	// CampaignStatusTimeout campaign timed out.
	CampaignStatusTimeout
)

func (CampaignStatus) String

func (cs CampaignStatus) String() string

String returns string representation of campaign status.

type CampaignStrategy

type CampaignStrategy int

CampaignStrategy represents campaign strategy.

const (
	// CampaignStrategySequential votes sequentially.
	CampaignStrategySequential CampaignStrategy = iota
	// CampaignStrategyParallel votes in parallel.
	CampaignStrategyParallel
	// CampaignStrategyPriority votes priority peers first.
	CampaignStrategyPriority
	// CampaignStrategyAdaptive adapts based on responses.
	CampaignStrategyAdaptive
)

func (CampaignStrategy) String

func (cs CampaignStrategy) String() string

String returns string representation of campaign strategy.

type ElectionManager

type ElectionManager struct {
	// contains filtered or unexported fields
}

ElectionManager manages leader elections.

func NewElectionManager

func NewElectionManager(config ElectionManagerConfig, raftNode internal.RaftNode, logger forge.Logger) *ElectionManager

NewElectionManager creates a new election manager.

func (*ElectionManager) CleanupOldVotes

func (em *ElectionManager) CleanupOldVotes(keepTerms int)

CleanupOldVotes removes vote records for old terms.

func (*ElectionManager) GetCurrentTerm

func (em *ElectionManager) GetCurrentTerm() uint64

GetCurrentTerm returns the current term.

func (*ElectionManager) GetElectionTimeout

func (em *ElectionManager) GetElectionTimeout() time.Duration

GetElectionTimeout returns the current election timeout.

func (*ElectionManager) GetHeartbeatInterval

func (em *ElectionManager) GetHeartbeatInterval() time.Duration

GetHeartbeatInterval returns the heartbeat interval.

func (*ElectionManager) GetVotedFor

func (em *ElectionManager) GetVotedFor() string

GetVotedFor returns who we voted for in current term.

func (*ElectionManager) HandleVoteRequest

HandleVoteRequest handles a vote request.

func (*ElectionManager) RecordVote

func (em *ElectionManager) RecordVote(term uint64, nodeID string, granted bool)

RecordVote records a vote response.

func (*ElectionManager) ResetElectionTimeout

func (em *ElectionManager) ResetElectionTimeout()

ResetElectionTimeout resets the election timeout.

func (*ElectionManager) SetCurrentTerm

func (em *ElectionManager) SetCurrentTerm(term uint64)

SetCurrentTerm sets the current term.

func (*ElectionManager) Start

func (em *ElectionManager) Start(ctx context.Context) error

Start starts the election manager.

func (*ElectionManager) StartElection

func (em *ElectionManager) StartElection() error

StartElection starts a new election.

func (*ElectionManager) Stop

func (em *ElectionManager) Stop(ctx context.Context) error

Stop stops the election manager.

func (*ElectionManager) TallyVotes

func (em *ElectionManager) TallyVotes(term uint64, quorumSize int) (votesFor, votesAgainst int, wonElection bool)

TallyVotes tallies votes for the given term.

type ElectionManagerConfig

type ElectionManagerConfig struct {
	NodeID             string
	MinElectionTimeout time.Duration
	MaxElectionTimeout time.Duration
	HeartbeatInterval  time.Duration
}

ElectionManagerConfig contains election manager configuration.

type TimeoutEvent

type TimeoutEvent struct {
	Timestamp time.Time
	Timeout   time.Duration
	Fired     bool
	Reset     bool
}

TimeoutEvent represents a timeout event.

type TimeoutManager

type TimeoutManager struct {
	// contains filtered or unexported fields
}

TimeoutManager manages election timeout with adaptive algorithms.

func NewTimeoutManager

func NewTimeoutManager(config TimeoutManagerConfig, logger forge.Logger) *TimeoutManager

NewTimeoutManager creates a new timeout manager.

func (*TimeoutManager) ClearHistory

func (tm *TimeoutManager) ClearHistory()

ClearHistory clears timeout history.

func (*TimeoutManager) EnableAdaptive

func (tm *TimeoutManager) EnableAdaptive(enable bool)

EnableAdaptive enables adaptive timeout.

func (*TimeoutManager) GetCurrentTimeout

func (tm *TimeoutManager) GetCurrentTimeout() time.Duration

GetCurrentTimeout returns the current timeout value.

func (*TimeoutManager) GetRecentElectionDurations

func (tm *TimeoutManager) GetRecentElectionDurations() []time.Duration

GetRecentElectionDurations returns recent election durations.

func (*TimeoutManager) GetTimeUntilTimeout

func (tm *TimeoutManager) GetTimeUntilTimeout() time.Duration

GetTimeUntilTimeout returns time remaining until timeout.

func (*TimeoutManager) GetTimeoutHistory

func (tm *TimeoutManager) GetTimeoutHistory(limit int) []TimeoutEvent

GetTimeoutHistory returns timeout history.

func (*TimeoutManager) GetTimeoutStatistics

func (tm *TimeoutManager) GetTimeoutStatistics() TimeoutStatistics

GetTimeoutStatistics returns timeout statistics.

func (*TimeoutManager) IsAdaptiveEnabled

func (tm *TimeoutManager) IsAdaptiveEnabled() bool

IsAdaptiveEnabled returns whether adaptive timeout is enabled.

func (*TimeoutManager) IsTimerActive

func (tm *TimeoutManager) IsTimerActive() bool

IsTimerActive returns whether the timer is active.

func (*TimeoutManager) RecordElectionDuration

func (tm *TimeoutManager) RecordElectionDuration(duration time.Duration)

RecordElectionDuration records an election duration for adaptive timeout.

func (*TimeoutManager) ResetTimer

func (tm *TimeoutManager) ResetTimer()

ResetTimer resets the election timeout timer.

func (*TimeoutManager) SetTimeoutRange

func (tm *TimeoutManager) SetTimeoutRange(min, max time.Duration)

SetTimeoutRange updates the timeout range.

func (*TimeoutManager) Start

func (tm *TimeoutManager) Start(ctx context.Context) error

Start starts the timeout manager.

func (*TimeoutManager) StartTimer

func (tm *TimeoutManager) StartTimer()

StartTimer starts the election timeout timer.

func (*TimeoutManager) Stop

func (tm *TimeoutManager) Stop(ctx context.Context) error

Stop stops the timeout manager.

func (*TimeoutManager) StopTimer

func (tm *TimeoutManager) StopTimer()

StopTimer stops the election timeout timer.

type TimeoutManagerConfig

type TimeoutManagerConfig struct {
	NodeID          string
	MinTimeout      time.Duration
	MaxTimeout      time.Duration
	Multiplier      float64
	AdaptiveEnabled bool
	MaxHistorySize  int
	OnTimeout       func()
}

TimeoutManagerConfig contains timeout manager configuration.

type TimeoutStatistics

type TimeoutStatistics struct {
	TotalEvents             int
	TimeoutsFired           int
	ResetsCount             int
	MinTimeout              time.Duration
	MaxTimeout              time.Duration
	CurrentTimeout          time.Duration
	AverageTimeout          time.Duration
	AverageElectionDuration time.Duration
}

TimeoutStatistics contains timeout statistics.

type VoteManager

type VoteManager struct {
	// contains filtered or unexported fields
}

VoteManager manages vote collection and tracking.

func NewVoteManager

func NewVoteManager(config VoteManagerConfig, logger forge.Logger) *VoteManager

NewVoteManager creates a new vote manager.

func (*VoteManager) CastVote

func (vm *VoteManager) CastVote(term uint64, candidateID string, granted bool, reason string) error

CastVote casts a vote for a candidate.

func (*VoteManager) ClearOldVotes

func (vm *VoteManager) ClearOldVotes(keepTerms int)

ClearOldVotes clears vote records for old terms.

func (*VoteManager) ExportVoteData

func (vm *VoteManager) ExportVoteData() map[string]any

ExportVoteData exports vote data for analysis.

func (*VoteManager) GetAverageVoteLatency

func (vm *VoteManager) GetAverageVoteLatency(term uint64) time.Duration

GetAverageVoteLatency returns average vote response latency.

func (*VoteManager) GetCurrentVote

func (vm *VoteManager) GetCurrentVote() (term uint64, votedFor string, votedAt time.Time)

GetCurrentVote returns current vote information.

func (*VoteManager) GetSlowVoters

func (vm *VoteManager) GetSlowVoters(term uint64, threshold time.Duration) []string

GetSlowVoters returns nodes that took longer than threshold to respond.

func (*VoteManager) GetVoteCount

func (vm *VoteManager) GetVoteCount(term uint64) (granted, denied, total int)

GetVoteCount returns vote counts for a term.

func (*VoteManager) GetVoteHistory

func (vm *VoteManager) GetVoteHistory(limit int) []VoteRecord

GetVoteHistory returns vote history.

func (*VoteManager) GetVoteResponseRate

func (vm *VoteManager) GetVoteResponseRate(term uint64, totalPeers int) float64

GetVoteResponseRate returns the vote response rate for a term.

func (*VoteManager) GetVoteStatistics

func (vm *VoteManager) GetVoteStatistics() VoteStatistics

GetVoteStatistics returns vote statistics.

func (*VoteManager) GetVotesForTerm

func (vm *VoteManager) GetVotesForTerm(term uint64) []*VoteResponse

GetVotesForTerm returns all votes for a specific term.

func (*VoteManager) HasVotedInTerm

func (vm *VoteManager) HasVotedInTerm(term uint64) (bool, string)

HasVotedInTerm checks if we voted in a specific term.

func (*VoteManager) RecordVoteResponse

func (vm *VoteManager) RecordVoteResponse(response VoteResponse)

RecordVoteResponse records a vote response from a peer.

func (*VoteManager) ResetForNewTerm

func (vm *VoteManager) ResetForNewTerm(term uint64)

ResetForNewTerm resets vote state for a new term.

func (*VoteManager) ValidateVoteRequest

func (vm *VoteManager) ValidateVoteRequest(req internal.RequestVoteRequest) (bool, string)

ValidateVoteRequest validates a vote request.

type VoteManagerConfig

type VoteManagerConfig struct {
	NodeID         string
	MaxHistorySize int
}

VoteManagerConfig contains vote manager configuration.

type VoteRecord

type VoteRecord struct {
	Term        uint64
	CandidateID string
	Granted     bool
	Timestamp   time.Time
	Reason      string
}

VoteRecord represents a historical vote record.

type VoteResponse

type VoteResponse struct {
	NodeID    string
	Term      uint64
	Granted   bool
	Timestamp time.Time
	Latency   time.Duration
}

VoteResponse represents a vote response with metadata.

type VoteStatistics

type VoteStatistics struct {
	TotalVotesCast int
	VotesGranted   int
	VotesDenied    int
	TermsWithVotes int
	GrantRate      float64
}

VoteStatistics contains vote statistics.

Jump to

Keyboard shortcuts

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