raft

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 17 Imported by: ? 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 raft implements fixed-membership Raft with weighted votes and priority-biased election delays. Election and commit require strictly more than half of the configured voting weight; priority never changes vote share.

A Node owns its durable bbolt WAL and background tasks. Applications supply authenticated Call/Handle transport and an idempotent Apply callback for opaque committed commands. ReadBarrier obtains a fresh quorum for each call; Status is diagnostic and does not authorize a linearizable read.

The implementation retains the complete WAL. It does not implement log compaction, snapshot installation or online membership changes.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotLeader     = errors.New("raft node is not the leader")
	ErrNotReady      = errors.New("raft node is not ready")
	ErrIndeterminate = errors.New("raft commit outcome is indeterminate")
	ErrDiverged      = errors.New("raft log histories diverged")
	ErrSequence      = errors.New("invalid raft log sequence")
	ErrClosed        = errors.New("raft node is closed")
)

These errors describe consensus admission and durable log outcomes. An application adapter may translate them into its own service error vocabulary.

Functions

func Initialize

func Initialize(cfg Config) error

Initialize provisions the initial durable voting identity without starting a process. Provision every initial member once, before first start. It refuses an existing WAL. Runtime Open should leave Bootstrap false, so loss of the WAL never silently recreates a voting identity from an empty disk.

func InitializeFromCommands

func InitializeFromCommands(ctx context.Context, cfg Config, visit func(yield func([]byte) error) error) (result error)

InitializeFromCommands provisions a NEW fixed-member group from an offline, trusted sequence of opaque commands. All previous voters must be isolated; this is not an online membership change or snapshot installation protocol.

visit calls yield serially, in application order. Each command is copied before yield returns. visit must return when ctx is canceled and must not retain yield after returning. Entry size, batch count and batch bytes are bounded by Config; a single entry may exceed MaxBatchBytes but not MaxEntryBytes. The core assigns contiguous indices starting at one, in term one, and persists the complete committed prefix before publishing weighted-raft.db without replacement. Errors and cancellation before publication leave no voter file. No Apply or Call callback is invoked. The resulting node has not applied the commands: Start replays them through the caller's idempotent Apply callback.

Types

type Config

type Config struct {
	Directory, ClusterID, NodeID                   string
	Members                                        []Member
	Bootstrap                                      bool // Only provision an entirely new cluster; never use to reopen a lost voter disk.
	Call                                           func(context.Context, string, Request) (Response, error)
	Apply                                          func(context.Context, uint64, uint64, []byte) error
	ElectionTimeout, HeartbeatInterval, RPCTimeout time.Duration
	MaxEntryBytes, MaxBatchEntries, MaxBatchBytes  int
}

type Entry

type Entry struct {
	Index    uint64 `json:"index"`
	Term     uint64 `json:"term"`
	Kind     string `json:"kind"`
	Data     []byte `json:"data,omitempty"`
	Checksum string `json:"checksum"`
}

type Member

type Member struct {
	ID       string `json:"id"`
	Weight   uint64 `json:"weight"`
	Priority uint32 `json:"priority"`
}

Member is one immutable member of a weighted Raft configuration. Weight zero is a learner. Priority zero may vote but never campaigns. Positive priorities bias election delay, not quorum weight or vote validity.

type Node

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

Node owns its own WAL. It does not compact: an empty learner/voter receives the complete retained log. Apply must durably and idempotently apply each command; Start replays ALL committed commands on every process restart. No native database is owned or closed by this type.

func Open

func Open(cfg Config) (*Node, error)

Open validates durable identity, checksums and the entire log. It does not elect, accept RPC, or invoke Apply until Start is called.

func (*Node) Close

func (r *Node) Close() error

func (*Node) Handle

func (r *Node) Handle(ctx context.Context, from string, q Request) (Response, error)

Handle must only receive an authenticated physical member ID in from. A configuration hash mismatch is rejected before it can change term or disk.

func (*Node) Propose

func (r *Node) Propose(ctx context.Context, data []byte) (uint64, error)

Propose serializes one command until its durable weighted-quorum commit and local native Apply. A timeout never rolls back a possibly committed command; the returned nonzero index identifies the indeterminate proposal.

func (*Node) ProposeInTerm

func (r *Node) ProposeInTerm(ctx context.Context, expectedTerm uint64, data []byte) (uint64, error)

ProposeInTerm rejects a payload prepared under a different leadership term. The expected term is checked after acquiring the proposal gate and under the state mutex immediately before append; a stale payload never enters the WAL.

func (*Node) ReadBarrier

func (r *Node) ReadBarrier(ctx context.Context) error

ReadBarrier proves leadership using a new, nonce-bound weighted quorum round. It serializes with proposals and covers the complete captured local log tail, including earlier indeterminate commands. It never reuses a heartbeat ACK. The first barrier of a term may append a noop if no current-term entry is yet committed; steady-state reads add no log entries or native transactions.

func (*Node) Start

func (r *Node) Start(ctx context.Context) error

Start replays all committed commands before admitting RPC and elections. Apply callbacks must use native transactional markers to tolerate this replay.

func (*Node) Status

func (r *Node) Status() Status

type Request

type Request struct {
	ReadID       string  `json:"read_id,omitempty"`
	Operation    string  `json:"operation"`
	ClusterID    string  `json:"cluster_id"`
	ConfigHash   string  `json:"config_hash"`
	NodeID       string  `json:"node_id"`
	Term         uint64  `json:"term"`
	LastLogIndex uint64  `json:"last_log_index,omitempty"`
	LastLogTerm  uint64  `json:"last_log_term,omitempty"`
	PrevLogIndex uint64  `json:"prev_log_index,omitempty"`
	PrevLogTerm  uint64  `json:"prev_log_term,omitempty"`
	Entries      []Entry `json:"entries,omitempty"`
	LeaderCommit uint64  `json:"leader_commit,omitempty"`
}

type Response

type Response struct {
	ReadID        string `json:"read_id,omitempty"`
	Role          string `json:"role"`
	LeaderID      string `json:"leader_id"`
	Commit        uint64 `json:"commit"`
	CommitTerm    uint64 `json:"commit_term"`
	VotingReady   bool   `json:"voting_ready"`
	NodeID        string `json:"node_id"`
	ConfigHash    string `json:"config_hash"`
	Term          uint64 `json:"term"`
	VoteGranted   bool   `json:"vote_granted,omitempty"`
	Success       bool   `json:"success,omitempty"`
	MatchIndex    uint64 `json:"match_index,omitempty"`
	ConflictIndex uint64 `json:"conflict_index,omitempty"`
}

type Status

type Status struct {
	VotingReady bool   `json:"voting_ready"`
	Term        uint64 `json:"term"`
	Role        string `json:"role"`
	LeaderID    string `json:"leader_id"`
	Commit      uint64 `json:"commit"`
	Applied     uint64 `json:"applied"`
	Last        uint64 `json:"last"`
	ConfigHash  string `json:"config_hash"`
	Ready       bool   `json:"ready"`
	Error       string `json:"error,omitempty"`
}

Jump to

Keyboard shortcuts

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