ha

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ha elects one leader among the sqi servers sharing a database. The authority is the lease row the store keeps (store.LeadershipStore): a standby polls to take it, the leader renews it, and every judgement of whether it has lapsed is made in SQL on the database's clock, so servers whose clocks disagree still agree on who leads.

The leader also fences itself. It notes its own monotonic clock before sending each renewal and treats a success as authority for 80% of the lease from that instant. The database set the expiry no earlier than the request was sent, so a standby cannot take over before the full lease has passed; the remaining 20% absorbs clocks that run at slightly different rates and the leader's own reaction time. A leader whose deadline passes without a successful renewal stops on its own, before a standby can have started.

A loss of authority is final: Elector.Hold returns a *LostError and the server exits, to be restarted as a standby.

Index

Constants

View Source
const (
	// RoleLeader is the member holding the unexpired leader lease.
	RoleLeader = "leader"
	// RoleStandby is a member seen within the lease TTL that does not lead.
	RoleStandby = "standby"
	// RoleMissing is a member not seen within the lease TTL: stopped, crashed
	// or cut off from the database.
	RoleMissing = "missing"
)

The roles a member of the group can have in a Roster.

Variables

This section is empty.

Functions

func RenewInterval

func RenewInterval(ttl time.Duration) time.Duration

RenewInterval is the time between renewals, and between membership upserts, for a group whose lease lasts ttl: a third of it. A server watching its group observes at the same cadence.

Types

type Clock

type Clock interface {
	Now() time.Time
	NewTimer(d time.Duration) Timer
}

Clock is the elector's time source. Its readings are only ever compared with each other, never with another server's or the database's, so it needs to run at the right rate but not to agree with anyone; the real clock's readings carry a monotonic component for that.

type Config

type Config struct {
	// Self is this server's membership row. Its InstanceID is the lease
	// holder name; LastSeenUS, BrokerOK and BrokerOKUS are set by the elector
	// and the store.
	Self store.ServerMember
	// LeaseTTL is the lease lifetime. Renewals run every third of it and a
	// renewal's authority lasts four fifths of it. It must be positive.
	LeaseTTL time.Duration
	// BrokerUp reports whether the bus connection is up now. Nil means always
	// up. The elector reads only up: it times an outage itself, on Clock,
	// from the first time it sees the connection down, so since may be
	// anything (bus.Client.BusUpSince reports zero while down, and a UTC wall
	// time while up) and is not used.
	BrokerUp func() (up bool, since time.Time)
	// Clock is nil for the real clock.
	Clock Clock
	// Logger is nil for [slog.Default].
	Logger *slog.Logger
}

Config is an elector's identity and timing.

type Elector

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

Elector campaigns for, holds and gives up the leader lease for one server. Its methods are safe for concurrent use; Campaign and Hold are meant to be called one after the other from a single goroutine.

func New

func New(cfg Config, st store.LeadershipStore) *Elector

New returns an elector for cfg.Self over st. It panics when cfg.LeaseTTL is not positive, which configuration validation rules out.

func (*Elector) Authorized

func (e *Elector) Authorized() bool

Authorized reports whether this server may act as the leader now: it leads at an epoch and the self-fence deadline of its last acquire or renewal has not passed. Unlike Elector.Epoch it judges the deadline itself rather than waiting for Hold to notice it, so a process that was frozen and has just resumed answers false before Hold's loop has run.

func (*Elector) Campaign

func (e *Elector) Campaign(ctx context.Context) (int64, error)

Campaign tries to take the lease every second while the broker is up, and returns the epoch won. A standby without a broker never tries: it could do no work as leader. Campaign returns ctx.Err() when ctx ends first.

func (*Elector) Epoch

func (e *Elector) Epoch() int64

Epoch returns the epoch this server leads at, or 0 when it does not lead.

func (*Elector) Hold

func (e *Elector) Hold(ctx context.Context, epoch int64) error

Hold keeps the lease at epoch, which Campaign must have won, renewing it every third of the lease. It returns nil when ctx ends with no loss recorded, leaving the lease to lapse unless the caller calls Release, and otherwise a *LostError the moment authority is gone (the caller then calls Release and exits):

  • a renewal is refused (ReasonRenewRefused);
  • the self-fence deadline passes with no successful renewal (ReasonDeadline); a renewal that errors is retried, and is not a loss on its own;
  • the broker has been seen down continuously for longer than the lease while some standby reaches it (ReasonBrokerLost); the lease is released first, so that standby takes over at its next poll;
  • Elector.Lose reports a loss found elsewhere.

A renewal that has not answered is never stacked with another, and the deadline is judged whether or not one is in flight.

func (*Elector) Lose

func (e *Elector) Lose(r Reason, err error)

Lose reports a loss of authority found outside the elector, such as a fenced store write or a lost broker guard. Hold returns it promptly, and any later Hold returns it at once. Only the first loss is kept.

func (*Elector) Release

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

Release gives up the last epoch this elector won, for a graceful stop or after a loss of authority (release, then exit): releasing after a loss lets a standby take over at its next poll rather than when the lease lapses, and neutralizes a late-committing renewal Hold abandoned. It is safe whoever holds the lease now, because the store releases only for this holder at that epoch. Stop Hold first, or its next renewal is refused. Release does nothing when nothing was won or it was already released, and either way this server no longer leads afterwards.

func (*Elector) RunMembership

func (e *Elector) RunMembership(ctx context.Context)

RunMembership keeps this server's membership row fresh until ctx ends: at once, then every third of the lease, whether it leads or not. Each upsert reports whether the broker is up, which is what lets a leader that lost its broker tell whether a standby could do better. Pruning members long gone is the leader's job, not this loop's.

type LostError

type LostError struct {
	Reason Reason
	// Err is the cause, when there is one beyond the reason itself.
	Err error
}

LostError reports a loss of leadership. Once returned, the Elector that returned it never leads again: the server exits and restarts as a standby.

func (*LostError) Error

func (e *LostError) Error() string

Error names the reason and the cause.

func (*LostError) Unwrap

func (e *LostError) Unwrap() error

Unwrap returns the cause.

type Reason

type Reason string

Reason names why a leader lost its authority. It is the label on the demotion metric and the word in the one ERROR a demoted leader logs.

const (
	// ReasonRenewRefused means a renewal found the lease held by another
	// server or at another epoch: a standby has already taken over.
	ReasonRenewRefused Reason = "renew_refused"
	// ReasonDeadline means the self-fence deadline passed with no successful
	// renewal, so a standby may be about to take over.
	ReasonDeadline Reason = "deadline"
	// ReasonFenced means a store write was refused for a stale epoch.
	ReasonFenced Reason = "fenced"
	// ReasonGuardLost means another server took the broker guard.
	ReasonGuardLost Reason = "guard_lost"
	// ReasonBrokerLost means the leader lost its broker for longer than the
	// lease while a standby still reaches it, so the leader stepped down.
	ReasonBrokerLost Reason = "broker_lost"
	// ReasonPromotion means a step of taking up leadership failed.
	ReasonPromotion Reason = "promotion_failed"
)

type Roster

type Roster struct {
	Epoch   int64
	Members []RosterMember
}

Roster is the group as the database holds it: the current epoch and every member, leader first.

func BuildRoster

func BuildRoster(lease store.Lease, members []store.ServerMember, nowUS int64, ttl time.Duration) Roster

BuildRoster classifies members against lease on the database clock nowUS, so no server's own clock enters it. A member leads when it holds the lease and the lease has not lapsed; otherwise it is a standby when seen within ttl, and missing when not. Members are ordered leader first, then by name, then by instance id. Members is never nil.

func ReadRoster

func ReadRoster(ctx context.Context, st store.LeadershipStore, ttl time.Duration) (Roster, error)

ReadRoster reads the lease and the membership from st and classifies them (BuildRoster) against ttl, the group's lease_ttl.

type RosterMember

type RosterMember struct {
	InstanceID string
	Name       string
	Host       string
	PID        int
	Version    string
	Role       string
	StartedAt  time.Time
	// LastSeenAgo is how long before the database clock read the member last
	// refreshed its row. Never negative.
	LastSeenAgo time.Duration
	// BrokerOK reports whether the member reached its broker within the lease
	// TTL.
	BrokerOK bool
}

RosterMember is one server of the group as an operator sees it.

type Timer

type Timer interface {
	C() <-chan time.Time
	Stop() bool
}

Timer is a one-shot timer from a Clock, as time.Timer is.

Jump to

Keyboard shortcuts

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