authority

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: 22 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 authority supplies an ordered application authority journal and fixed-membership weighted Raft consensus for metadata and auth state machines. The paired authority protocol is also present; its configured fencer must actually isolate the peer before promotion.

Index

Constants

View Source
const MaxSnapshotBytes int64 = 1 << 30
View Source
const Version = 1

Variables

View Source
var (
	ErrNotLeader     = errors.New("metadata authority is not the active leader")
	ErrNotReady      = errors.New("metadata authority requires recovery and activation")
	ErrIndeterminate = errors.New("metadata commit outcome is indeterminate; recovery required")
	ErrDiverged      = errors.New("metadata authority histories diverged")
	ErrSequence      = errors.New("invalid metadata authority sequence")
	ErrFenceRequired = errors.New("successful external fencing is required")
	ErrClosed        = errors.New("metadata authority is closed")
)

Functions

func InitializeWeightedRaftFromAuthority

func InitializeWeightedRaftFromAuthority(cfg raft.Config, source io.Reader) error

InitializeWeightedRaftFromAuthority provisions an offline NEW group from a complete, stable application journal. It preserves all committed and aborted application sequence/hash links. All original voters must already be stopped and isolated; this is disaster recovery, not an online membership change. No Apply or transport callback is run. The finished hard state is published without replacement only after every command and the final commit are durable.

func RunFailoverCommand

func RunFailoverCommand(ctx context.Context, argv []string, s FailoverTransition) error

RunFailoverCommand executes an argv array without a shell. Provisioners see the same persisted transition ID after crashes and must reconcile idempotently.

func WithFailoverTransition

func WithFailoverTransition(ctx context.Context, s FailoverTransition) context.Context

WithFailoverTransition passes the durable coordinator identity through a composed promotion path. The actual fencer receives this same ID on retries.

Types

type ApplyFunc

type ApplyFunc func(context.Context, uint64, []byte) error

type Authority

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

func Open

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

func (*Authority) Activate

func (a *Authority) Activate(ctx context.Context, installDataGates func(context.Context, Status) error) error

Activate opens the client read/write gate only after the caller has durably installed this exact epoch/incarnation at every configured Data node.

func (*Authority) AppendRestoreRecords

func (a *Authority) AppendRestoreRecords(ctx context.Context, mutations []DomainMutation) error

AppendRestoreRecords appends one offline batch to a full retained journal copied by RestoreRecord(..., AppendRecords:true). All domains and native watermarks must already be registered against copies of the current DBs. It deliberately requires no peer: the destination remains unpublished and inactive until a fresh consensus group replays the full WAL and activates. A crash is resumed using the identical complete batch; committed entries and applied markers are never erased. An ordinary inactive leader cannot use it.

func (*Authority) Bootstrap

func (a *Authority) Bootstrap(ctx context.Context, domain string, payload []byte) error

Bootstrap is restricted to the first application command of a fresh group. It installs a complete deterministic native seed before client admission. Existing committed history wins; replaying an old seed is never allowed.

func (*Authority) Check

func (a *Authority) Check(ctx context.Context) error

Check waits for an in-progress commit, then checks service admission. It releases the gate before callbacks which may themselves transact.

func (*Authority) Close

func (a *Authority) Close() error

func (*Authority) Commit

func (a *Authority) Commit(ctx context.Context, domain string, payload []byte) (Result, error)

func (*Authority) Deactivate

func (a *Authority) Deactivate(ctx context.Context) error

func (*Authority) Exchange

func (a *Authority) Exchange(ctx context.Context, r Request) (Response, error)

Exchange implements the persisted replica state machine. It is also useful for explicit fault-injection peers; production callers use authenticated RPC.

func (*Authority) Export

func (a *Authority) Export(w io.Writer) error

Export writes the complete journal and header. The caller must hold an existing ViewBarrier or stop all authority operations; Export never acquires the gate recursively and does not release the caller's snapshot barrier.

func (*Authority) FenceProof

func (a *Authority) FenceProof(id string) (FenceProof, error)

func (*Authority) HandleRPC

func (a *Authority) HandleRPC(ctx context.Context, p cluster.Principal, method string, raw json.RawMessage) (any, error)

HandleRPC can be composed into a control server. Authentication must map the configured peer's offline identity to its physical node ID and role "meta".

func (*Authority) LeaderBarrier

func (a *Authority) LeaderBarrier(ctx context.Context) error

LeaderBarrier admits only consensus-internal leader work, such as initial node registration before storage activation. Client work must use Check.

func (*Authority) Promote

func (a *Authority) Promote(ctx context.Context, opts PromoteOptions) (FenceProof, error)

Promote performs an actual operator-supplied external fence. Exit zero is accepted only from executing that command, never from a user-provided proof string. The command's real isolation guarantee remains an operator contract. Promotion stays inactive and requires a replacement synchronous peer.

func (*Authority) Quiesce

func (a *Authority) Quiesce(ctx context.Context, fn func(Status) error) error

func (*Authority) RaftStatus

func (a *Authority) RaftStatus() raft.Status

RaftStatus describes consensus progress for discovery and diagnostics; it is never a read or write admission proof. Check supplies a fresh quorum barrier.

func (*Authority) Recover

func (a *Authority) Recover(ctx context.Context) error

Recover replays only durable decisions and reconciles the entire authority prefix before marking it ready. It never activates client service.

func (*Authority) Register

func (a *Authority) Register(domain string, apply ApplyFunc) error

func (*Authority) RegisterWatermark

func (a *Authority) RegisterWatermark(domain string, read func(context.Context) (uint64, error)) error

func (*Authority) SetPeer

func (a *Authority) SetPeer(peer Peer) error

func (*Authority) StartWeightedRaft

func (a *Authority) StartWeightedRaft(ctx context.Context, cfg raft.Config, activate func(context.Context, Status) error) error

StartWeightedRaft starts durable replay and automatic election only after all native domains have registered. Each new leader term must pass a fresh quorum barrier and the admission hook before becoming visible to clients. The hook may Bootstrap a previously empty Auth domain. It must honor cancellation.

func (*Authority) Status

func (a *Authority) Status() Status

func (*Authority) Transact

func (a *Authority) Transact(ctx context.Context, domain string, prepare PrepareFunc) (Result, error)

func (*Authority) ViewBarrier

func (a *Authority) ViewBarrier(ctx context.Context, fn func(Status) error) error

type Config

type Config struct {
	Directory, ClusterID, NodeID, PeerNodeID, Incarnation string
	Epoch                                                 uint64
	Role                                                  Role
	Peer                                                  Peer
	MaxEntryBytes                                         int
	ReplicationTimeout                                    time.Duration
	// Weighted selects a fixed-membership weighted Raft authority. It cannot
	// reopen a journal created by the legacy paired protocol (or vice versa).
	Weighted bool
}

type DomainMutation

type DomainMutation struct {
	Domain  string
	Payload []byte
}

DomainMutation is an already determined state-machine change, never a callback which re-evaluates filesystem state during replica replay.

type Entry

type Entry struct {
	Sequence    uint64 `json:"sequence"`
	Epoch       uint64 `json:"epoch"`
	Incarnation string `json:"incarnation"`
	Domain      string `json:"domain"`
	Payload     []byte `json:"payload"`
	Previous    string `json:"previous"`
	Hash        string `json:"hash"`
	Decision    string `json:"decision,omitempty"`
}

type FailoverConfig

type FailoverConfig struct {
	StatePath, ClusterID, ReplicaID, OldLeaderID, NewPeerID string
	Epoch                                                   uint64
	FenceCommand, ProvisionCommand                          []string
	FailureTimeout, ProbeInterval, OperationTimeout         time.Duration
	Probe                                                   func(context.Context) error
	StopReplica                                             func(context.Context) error
	Promote                                                 func(context.Context, FailoverTransition) (FenceProof, error)
	StartLeader                                             func(context.Context, FailoverTransition) error
	OnError                                                 func(error)
}

FailoverConfig supervises a locally owned replica. Probe failure only starts fencing; it never authorizes leadership by itself. Promote must call the existing Authority.Promote path and return its durable executed fence proof. StartLeader must use the normal Recover/gate-ACK/Activate startup path.

type FailoverController

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

func NewFailoverController

func NewFailoverController(cfg FailoverConfig) (*FailoverController, error)

func (*FailoverController) Close

func (c *FailoverController) Close() error

func (*FailoverController) Run

func (*FailoverController) State

func (*FailoverController) Step

func (c *FailoverController) Step(ctx context.Context) (done bool, err error)

Step performs at most one phase. Callers serialize Step; the built-in Run retries the same persisted phase after failure without choosing a new epoch.

type FailoverTransition

type FailoverTransition struct {
	Version                                          int `json:"version"`
	ID, ClusterID, ReplicaID, OldLeaderID, NewPeerID string
	Epoch                                            uint64
	Incarnation, Phase, FenceID                      string
	FenceCommand, ProvisionCommand                   []string
	FailedSince, Updated                             time.Time
	LastError                                        string
}

FailoverTransition is durable before fencing starts. External commands must be idempotent for ID: a crash can leave a command's result unknown.

type FenceProof

type FenceProof struct {
	ID           string    `json:"id"`
	TransitionID string    `json:"transition_id,omitempty"`
	OldLeaderID  string    `json:"old_leader_id"`
	Command      []string  `json:"command"`
	Started      time.Time `json:"started"`
	Finished     time.Time `json:"finished"`
	Success      bool      `json:"success"`
	OutputHash   string    `json:"output_hash"`
	Output       string    `json:"output"`
	Error        string    `json:"error,omitempty"`
}

func ReadFenceProof

func ReadFenceProof(directory, id string) (FenceProof, error)

ReadFenceProof opens a stopped authority's durable audit record read-only.

type Peer

type Peer interface {
	Call(context.Context, Request) (Response, error)
}

type PrepareFunc

type PrepareFunc func(context.Context, uint64) ([]byte, error)

PrepareFunc runs under the common authority gate against the last committed state. It must not recursively call Commit, Transact or ViewBarrier.

type PromoteOptions

type PromoteOptions struct {
	FenceCommand  []string
	OldLeaderID   string
	NewPeerNodeID string
	Incarnation   string
	Epoch         uint64
}

type RPCPeer

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

func NewRPCPeer

func NewRPCPeer(endpoint string, cfg cluster.RPCClientConfig) (*RPCPeer, error)

func (*RPCPeer) Call

func (p *RPCPeer) Call(ctx context.Context, r Request) (Response, error)

func (*RPCPeer) Close

func (p *RPCPeer) Close() error

type Request

type Request struct {
	Operation   string `json:"operation"`
	ClusterID   string `json:"cluster_id"`
	NodeID      string `json:"node_id"`
	Epoch       uint64 `json:"epoch"`
	Incarnation string `json:"incarnation"`
	Entry       *Entry `json:"entry,omitempty"`
	Sequence    uint64 `json:"sequence,omitempty"`
}

type Response

type Response struct {
	Status Status `json:"status"`
	Entry  *Entry `json:"entry,omitempty"`
}

type RestoreOptions

type RestoreOptions struct {
	NodeID, PeerNodeID, Incarnation string
	Epoch                           uint64
	Role                            Role
	// AppendRecords reserves this fresh, inactive leader for one deterministic
	// offline restore batch. Recover remains closed until the batch is sealed.
	AppendRecords bool
}

type Result

type Result struct {
	Sequence    uint64 `json:"sequence"`
	Epoch       uint64 `json:"epoch"`
	Incarnation string `json:"incarnation"`
}

type Role

type Role string
const (
	Leader   Role = "leader"
	Follower Role = "follower"
)

type Status

type Status struct {
	Version       int               `json:"version"`
	ClusterID     string            `json:"cluster_id"`
	NodeID        string            `json:"node_id"`
	PeerNodeID    string            `json:"peer_node_id"`
	Incarnation   string            `json:"incarnation"`
	Epoch         uint64            `json:"epoch"`
	Role          Role              `json:"role"`
	Last          uint64            `json:"last"`
	Committed     uint64            `json:"committed"`
	Applied       uint64            `json:"applied"`
	HeadHash      string            `json:"head_hash"`
	Ready         bool              `json:"ready"`
	Active        bool              `json:"active"`
	Pending       bool              `json:"pending"`
	FenceID       string            `json:"fence_id,omitempty"`
	DomainApplied map[string]uint64 `json:"domain_applied,omitempty"`
	Consensus     string            `json:"consensus,omitempty"`
	Term          uint64            `json:"term,omitempty"`
	LeaderID      string            `json:"leader_id,omitempty"`
	Activation    uint64            `json:"activation,omitempty"`
	VotingReady   bool              `json:"voting_ready,omitempty"`
}

func InspectRecord

func InspectRecord(r io.Reader) (Status, error)

InspectRecord validates native pages, the complete hash chain and per-domain watermarks without changing the input or opening a live authority writer.

func ReplicaRestoreExactGeneration

func ReplicaRestoreExactGeneration(r io.Reader, directory string, opts RestoreOptions) (result Status, err error)

ReplicaRestoreExactGeneration clones a complete, inactive leader checkpoint into its fresh follower. The caller must supply the native domain snapshots from that same checkpoint and fence the old owner of opts.NodeID. This only creates a follower: it never advances a generation or authorizes leadership. The complete journal, head and domain watermarks are retained for recovery.

func RestoreRecord

func RestoreRecord(r io.Reader, directory string, opts RestoreOptions) (result Status, err error)

RestoreRecord installs a stable offline journal with a new admission incarnation and strictly greater epoch. It retains history/sequence but requires Recover, Data gate acknowledgements and Activate before serving.

Jump to

Keyboard shortcuts

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