cluster

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 26 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

Index

Constants

This section is empty.

Variables

View Source
var (
	SnapshotMagic = [4]byte{'B', 'S', 'N', 'P'}
	SnapshotVer   = uint8(1)

	ErrInvalidSnapshotMagic     = errors.New("snapshot: invalid magic bytes")
	ErrUnsupportedSnapshotVer   = errors.New("snapshot: unsupported format version")
	ErrSnapshotChecksumMismatch = errors.New("snapshot: CRC32 checksum mismatch")
)
View Source
var (
	ErrNotLeader      = errors.New("cluster: not leader")
	ErrLeaderLost     = errors.New("cluster: leader lost")
	ErrNodeNotFound   = errors.New("cluster: node not found")
	ErrPartitioned    = errors.New("cluster: node partitioned")
	ErrSnapshotFailed = errors.New("cluster: snapshot failed")
	ErrLogCorrupted   = errors.New("cluster: log corrupted")
	ErrTermMismatch   = errors.New("cluster: term mismatch")
	ErrQuorumLost     = errors.New("cluster: quorum lost")
	ErrSplitBrain     = errors.New("cluster: split-brain detected")
	ErrClosed         = errors.New("cluster: closed")
	ErrStaleEpoch     = errors.New("cluster: stale leader epoch")
	ErrQuorumNotMet   = errors.New("cluster: replication quorum not met")
	ErrReplicaLagging = errors.New("cluster: replica lagging behind ISR threshold")
)

Common errors.

View Source
var (
	ErrPartitionNotFound = errors.New("cluster: partition metadata not found")
)

Functions

func DecodeUint64

func DecodeUint64(b []byte) uint64

DecodeUint64 decodes a uint64 from bytes (big-endian).

func EncodeBrokerCommand

func EncodeBrokerCommand(cmd *BrokerCommand) ([]byte, error)

EncodeBrokerCommand serializes a BrokerCommand for embedding in a LogEntry.

func EncodeLogEntry

func EncodeLogEntry(entry *LogEntry) ([]byte, error)

EncodeLogEntry encodes a LogEntry to bytes.

func EncodeMessage

func EncodeMessage(msg *RaftMessage) ([]byte, error)

EncodeMessage encodes a RaftMessage to bytes.

func EncodeSnapshot

func EncodeSnapshot(s *Snapshot) ([]byte, error)

EncodeSnapshot serializes a Snapshot to JSON bytes.

func EncodeUint64

func EncodeUint64(v uint64) []byte

EncodeUint64 encodes a uint64 to bytes (big-endian).

func ReadBytes

func ReadBytes(r io.Reader) ([]byte, error)

ReadBytes reads a length-prefixed byte slice from a reader.

func WriteBytes

func WriteBytes(w io.Writer, data []byte) error

WriteBytes writes a byte slice to a writer with length prefix.

Types

type AckCommand

type AckCommand struct {
	MessageID  string `json:"message_id"`
	Queue      string `json:"queue"`
	LeaseToken string `json:"lease_token"`
	ConsumerID string `json:"consumer_id"`
}

AckCommand mirrors broker.AckRequest for replication.

type AppendCommand

type AppendCommand struct {
	ID               string               `json:"id"`
	ParentID         string               `json:"parent_id,omitempty"`
	Topic            string               `json:"topic,omitempty"`
	Queue            string               `json:"queue,omitempty"`
	Stream           string               `json:"stream,omitempty"`
	Partition        int                  `json:"partition,omitempty"`
	Offset           uint64               `json:"offset,omitempty"`
	Key              string               `json:"key,omitempty"`
	RoutingKey       string               `json:"routing_key,omitempty"`
	Type             string               `json:"type,omitempty"`
	ContentType      string               `json:"content_type,omitempty"`
	Schema           string               `json:"schema,omitempty"`
	SchemaVersion    string               `json:"schema_version,omitempty"`
	Payload          []byte               `json:"payload,omitempty"`
	Headers          map[string]string    `json:"headers,omitempty"`
	Metadata         map[string]string    `json:"metadata,omitempty"`
	TraceID          string               `json:"trace_id,omitempty"`
	SpanID           string               `json:"span_id,omitempty"`
	CorrelationID    string               `json:"correlation_id,omitempty"`
	CausationID      string               `json:"causation_id,omitempty"`
	RequestID        string               `json:"request_id,omitempty"`
	ReplyTo          string               `json:"reply_to,omitempty"`
	ReplyGroup       string               `json:"reply_group,omitempty"`
	IdempotencyKey   string               `json:"idempotency_key,omitempty"`
	DeduplicationID  string               `json:"deduplication_id,omitempty"`
	Checksum         string               `json:"checksum,omitempty"`
	Priority         int                  `json:"priority,omitempty"`
	CreatedAt        time.Time            `json:"created_at"`
	AvailableAt      time.Time            `json:"available_at,omitempty"`
	ExpiresAt        time.Time            `json:"expires_at,omitempty"`
	Attempts         int                  `json:"attempts,omitempty"`
	MaxAttempts      int                  `json:"max_attempts,omitempty"`
	Redeliveries     int                  `json:"redeliveries,omitempty"`
	TenantID         string               `json:"tenant_id,omitempty"`
	ProducerID       string               `json:"producer_id,omitempty"`
	ProducerEpoch    int32                `json:"producer_epoch,omitempty"`
	ProducerSequence *uint64              `json:"producer_sequence,omitempty"`
	ConsumerID       string               `json:"consumer_id,omitempty"`
	ConsumerGroup    string               `json:"consumer_group,omitempty"`
	LeaseToken       string               `json:"lease_token,omitempty"`
	LeaseUntil       time.Time            `json:"lease_until,omitempty"`
	OriginalTopic    string               `json:"original_topic,omitempty"`
	OriginalQueue    string               `json:"original_queue,omitempty"`
	OriginalStream   string               `json:"original_stream,omitempty"`
	OriginalOffset   uint64               `json:"original_offset,omitempty"`
	Status           string               `json:"status"`
	LastError        string               `json:"last_error,omitempty"`
	DeadLetterReason string               `json:"dead_letter_reason,omitempty"`
	TaskID           string               `json:"task_id,omitempty"`
	TaskName         string               `json:"task_name,omitempty"`
	Destinations     []CommandDestination `json:"destinations"`
}

AppendCommand contains the message fields and destinations for replication. Fields mirror the broker.Message struct.

type AppendEntriesRequest

type AppendEntriesRequest struct {
	Term         uint64     `json:"term"`
	LeaderID     string     `json:"leader_id"`
	PrevLogIndex uint64     `json:"prev_log_index"`
	PrevLogTerm  uint64     `json:"prev_log_term"`
	Entries      []LogEntry `json:"entries"`
	LeaderCommit uint64     `json:"leader_commit"`
}

AppendEntriesRequest is sent by the leader to replicate log entries.

type AppendEntriesResponse

type AppendEntriesResponse struct {
	Term    uint64 `json:"term"`
	Success bool   `json:"success"`
	// The index of the last entry the follower has (for fast backup)
	LastLogIndex uint64 `json:"last_log_index"`
}

AppendEntriesResponse is the reply to AppendEntries.

type BrokerCommand

type BrokerCommand struct {
	Type    BrokerCommandType `json:"type"`
	Payload json.RawMessage   `json:"payload"`
}

BrokerCommand is the serialized command embedded in a Raft LogEntry.Data.

func MakeBrokerCommand

func MakeBrokerCommand(cmdType BrokerCommandType, payload any) (*BrokerCommand, error)

MakeBrokerCommand creates a BrokerCommand with the given type and payload.

type BrokerCommandType

type BrokerCommandType string

BrokerCommandType identifies the broker operation to replicate.

const (
	BrokerCmdDeclareQueue  BrokerCommandType = "declare_queue"
	BrokerCmdDeclareTopic  BrokerCommandType = "declare_topic"
	BrokerCmdDeclareStream BrokerCommandType = "declare_stream"
	BrokerCmdAppend        BrokerCommandType = "append"
	BrokerCmdAppendAtomic  BrokerCommandType = "append_atomic"
	BrokerCmdAck           BrokerCommandType = "ack"
	BrokerCmdNack          BrokerCommandType = "nack"
	BrokerCmdLease         BrokerCommandType = "lease"
	BrokerCmdUpdate        BrokerCommandType = "update"
	BrokerCmdUpdateBatch   BrokerCommandType = "update_batch"
	BrokerCmdMove          BrokerCommandType = "move"
	BrokerCmdCommitOffset  BrokerCommandType = "commit_offset"
	BrokerCmdPauseQueue    BrokerCommandType = "pause_queue"
	BrokerCmdResumeQueue   BrokerCommandType = "resume_queue"
	BrokerCmdPurgeQueue    BrokerCommandType = "purge_queue"
)

type BrokerStateMachine

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

BrokerStateMachine implements StateMachine by forwarding committed entries to a broker store. It runs on every node in the cluster so that the local store stays consistent with the Raft log.

func NewBrokerStateMachine

func NewBrokerStateMachine(store BrokerStore) *BrokerStateMachine

NewBrokerStateMachine creates a new BrokerStateMachine.

func (*BrokerStateMachine) Apply

func (sm *BrokerStateMachine) Apply(entry *LogEntry) error

Apply applies a committed Raft log entry to the local broker store.

func (*BrokerStateMachine) Restore

func (sm *BrokerStateMachine) Restore(snapshot []byte) error

Restore restores the state machine from a snapshot.

func (*BrokerStateMachine) Snapshot

func (sm *BrokerStateMachine) Snapshot() ([]byte, error)

type BrokerStore

type BrokerStore interface {
	ReplicateDeclareQueue(ctx context.Context, cmd DeclareQueueCommand) error
	ReplicateDeclareTopic(ctx context.Context, cmd DeclareTopicCommand) error
	ReplicateDeclareStream(ctx context.Context, cmd DeclareStreamCommand) error
	ReplicateAppend(ctx context.Context, cmd AppendCommand) error
	ReplicateAck(ctx context.Context, cmd AckCommand) error
	ReplicateNack(ctx context.Context, cmd NackCommand) error
	ReplicatePauseQueue(ctx context.Context, name string) error
	ReplicateResumeQueue(ctx context.Context, name string) error
	ReplicatePurgeQueue(ctx context.Context, name string) (int, error)
}

BrokerStore is the subset of the broker's Store interface needed for replicated state machine operations. The broker package satisfies this via its MemoryStore / FileWALStore / BinaryFileWALStore.

type Cluster

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

Cluster manages the Raft cluster and provides a high-level API.

func NewCluster

func NewCluster(cfg ClusterConfig) *Cluster

NewCluster creates a new cluster instance.

func (*Cluster) ActiveNodes

func (c *Cluster) ActiveNodes() []*NodeInfo

ActiveNodes returns all active nodes.

func (*Cluster) ID

func (c *Cluster) ID() string

ID returns the node ID.

func (*Cluster) IsLeader

func (c *Cluster) IsLeader() bool

IsLeader returns true if this node is the leader.

func (*Cluster) Join

func (c *Cluster) Join(node NodeInfo) error

Join adds a new node to the cluster.

func (*Cluster) Leader

func (c *Cluster) Leader() string

Leader returns the current leader.

func (*Cluster) Leave

func (c *Cluster) Leave(nodeID string) error

Leave removes a node from the cluster.

func (*Cluster) MarshalJSON

func (c *Cluster) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Cluster) Nodes

func (c *Cluster) Nodes() []*NodeInfo

Nodes returns all nodes in the cluster.

func (*Cluster) Raft

func (c *Cluster) Raft() *Raft

Raft returns the underlying Raft instance.

func (*Cluster) Start

func (c *Cluster) Start() error

Start starts the cluster.

func (*Cluster) State

func (c *Cluster) State() RaftState

State returns the current cluster state.

func (*Cluster) Stats

func (c *Cluster) Stats() map[string]any

Stats returns cluster statistics.

func (*Cluster) Stop

func (c *Cluster) Stop() error

Stop stops the cluster.

func (*Cluster) Submit

func (c *Cluster) Submit(command []byte) (uint64, error)

Submit submits a command to the Raft cluster.

type ClusterConfig

type ClusterConfig struct {
	ID             string
	Address        string
	Peers          []string
	Transport      Transport
	StateMachine   StateMachine
	HealthTimeout  time.Duration
	OnLeaderChange func(leader string)
	OnNodeJoin     func(node *NodeInfo)
	OnNodeLeave    func(nodeID string)
	OnNodeFail     func(nodeID string)
}

ClusterConfig holds configuration for the cluster.

type ClusterMetadata

type ClusterMetadata struct {
	Nodes      map[string]*NodeInfo                    `json:"nodes"`
	Partitions map[PartitionGroupID]*PartitionMetadata `json:"partitions"`
	// contains filtered or unexported fields
}

ClusterMetadata holds the in-memory replicated topology.

func NewClusterMetadata

func NewClusterMetadata() *ClusterMetadata

type ClusterState

type ClusterState struct {
	Nodes     []*NodeInfo `json:"nodes"`
	Leader    string      `json:"leader"`
	Term      uint64      `json:"term"`
	Committed uint64      `json:"committed"`
}

ClusterState represents the serialized cluster state.

type ClusterStateMachine

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

ClusterStateMachine implements StateMachine for the cluster.

func NewClusterStateMachine

func NewClusterStateMachine(cluster *Cluster) *ClusterStateMachine

NewClusterStateMachine creates a new cluster state machine.

func (*ClusterStateMachine) Apply

func (sm *ClusterStateMachine) Apply(entry *LogEntry) error

Apply applies a committed log entry.

func (*ClusterStateMachine) Get

func (sm *ClusterStateMachine) Get(key string) ([]byte, bool)

Get retrieves data by key.

func (*ClusterStateMachine) Restore

func (sm *ClusterStateMachine) Restore(snapshot []byte) error

Restore restores the state from a snapshot.

func (*ClusterStateMachine) Set

func (sm *ClusterStateMachine) Set(key string, value []byte)

Set sets a key-value pair.

func (*ClusterStateMachine) Snapshot

func (sm *ClusterStateMachine) Snapshot() ([]byte, error)

Snapshot returns a snapshot of the current state.

type CommandDestination

type CommandDestination struct {
	Kind string `json:"kind"`
	Name string `json:"name"`
}

CommandDestination mirrors broker.Destination for replication.

type ConfigChange

type ConfigChange struct {
	Type   ConfigChangeType `json:"type"`
	PeerID string           `json:"peer_id"`
}

ConfigChange is the payload for EntryConfig log entries.

type ConfigChangeType

type ConfigChangeType uint8

ConfigChangeType represents the type of configuration change.

const (
	ConfigAdd    ConfigChangeType = 0
	ConfigRemove ConfigChangeType = 1
)

type ControllerQuorum

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

ControllerQuorum coordinates cluster topology and partition assignments.

func NewControllerQuorum

func NewControllerQuorum(cfg ControllerQuorumConfig) (*ControllerQuorum, error)

NewControllerQuorum creates a metadata consensus controller.

func (*ControllerQuorum) AdvanceEpoch

func (cq *ControllerQuorum) AdvanceEpoch(ctx context.Context, topic string, partition int, newLeader string) error

AdvanceEpoch advances the leader epoch and sets a new leader if provided.

func (*ControllerQuorum) AssignPartition

func (cq *ControllerQuorum) AssignPartition(ctx context.Context, topic string, partition int, replicas []string, leader string) error

AssignPartition creates or updates a partition assignment across the cluster.

func (*ControllerQuorum) DeregisterNode

func (cq *ControllerQuorum) DeregisterNode(ctx context.Context, nodeID string) error

DeregisterNode removes a node registration through consensus.

func (*ControllerQuorum) GetNodes

func (cq *ControllerQuorum) GetNodes() []*NodeInfo

GetNodes returns all currently registered nodes.

func (*ControllerQuorum) GetPartition

func (cq *ControllerQuorum) GetPartition(topic string, partition int) (*PartitionMetadata, error)

GetPartition retrieves current partition metadata from the replicated state.

func (*ControllerQuorum) IsLeader

func (cq *ControllerQuorum) IsLeader() bool

IsLeader checks if this controller is the active leader of the metadata quorum.

func (*ControllerQuorum) ListPartitions

func (cq *ControllerQuorum) ListPartitions() []*PartitionMetadata

ListPartitions returns all active partition metadata entries.

func (*ControllerQuorum) RegisterNode

func (cq *ControllerQuorum) RegisterNode(ctx context.Context, node *NodeInfo) error

RegisterNode submits a node registration command through consensus.

func (*ControllerQuorum) UpdateISR

func (cq *ControllerQuorum) UpdateISR(ctx context.Context, topic string, partition int, isr []string) error

UpdateISR submits an updated in-sync replica set for a partition.

type ControllerQuorumConfig

type ControllerQuorumConfig struct {
	Controller *RaftController
	Metadata   *ClusterMetadata
	Timeout    time.Duration
}

ControllerQuorumConfig configures the metadata consensus quorum.

type DeclareQueueCommand

type DeclareQueueCommand struct {
	Name              string        `json:"name"`
	Workers           int           `json:"workers"`
	MaxInFlight       int           `json:"max_inflight"`
	MaxDepth          int           `json:"max_depth"`
	VisibilityTimeout time.Duration `json:"visibility_timeout"`
	AckMode           string        `json:"ack_mode"`
	RetryMaxAttempts  int           `json:"retry_max_attempts"`
	RetryInitial      time.Duration `json:"retry_initial"`
	RetryMax          time.Duration `json:"retry_max"`
	RetryFactor       float64       `json:"retry_factor"`
	DLQ               string        `json:"dlq"`
	Ordering          string        `json:"ordering"`
	Backpressure      string        `json:"backpressure"`
	Strategy          string        `json:"strategy,omitempty"`
}

DeclareQueueCommand mirrors broker.QueueConfig for replication.

type DeclareStreamCommand

type DeclareStreamCommand struct {
	Name       string        `json:"name"`
	Partitions int           `json:"partitions"`
	Retention  time.Duration `json:"retention"`
	Compact    bool          `json:"compact"`
}

DeclareStreamCommand mirrors broker.StreamConfig for replication.

type DeclareTopicCommand

type DeclareTopicCommand struct {
	Name       string        `json:"name"`
	Partitions int           `json:"partitions"`
	Retention  time.Duration `json:"retention"`
	Paused     bool          `json:"paused"`
}

DeclareTopicCommand mirrors broker.TopicConfig for replication.

type EntryType

type EntryType uint8

Log entry types.

const (
	EntryNormal   EntryType = 0
	EntryConfig   EntryType = 1
	EntrySnapshot EntryType = 2
)

type EtcdRaftCore

type EtcdRaftCore struct {
	RawNode *etcdraft.RawNode
	Storage *etcdraft.MemoryStorage
	// contains filtered or unexported fields
}

EtcdRaftCore is the audited etcd/raft state machine foundation.

func NewEtcdRaftCore

func NewEtcdRaftCore(cfg EtcdRaftCoreConfig) (*EtcdRaftCore, error)

type EtcdRaftCoreConfig

type EtcdRaftCoreConfig struct {
	ID                        uint64
	Peers                     []uint64
	ElectionTick              int
	HeartbeatTick             int
	MaxMessageBytes           uint64
	MaxInflightMessages       int
	MaxUncommittedEntryBytes  uint64
	DisableProposalForwarding bool
	StorageDir                string
	SkipBootstrap             bool
}

EtcdRaftCoreConfig configures the consensus core shared by controller and partition groups.

type FencingToken

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

FencingToken is used to prevent stale leaders from acting.

func NewFencingToken

func NewFencingToken() *FencingToken

NewFencingToken creates a new fencing token.

func (*FencingToken) Current

func (ft *FencingToken) Current() uint64

Current returns the current fencing token.

func (*FencingToken) Epoch

func (ft *FencingToken) Epoch() uint64

Epoch returns the current epoch.

func (*FencingToken) Increment

func (ft *FencingToken) Increment() uint64

Increment increments the fencing token.

func (*FencingToken) IncrementEpoch

func (ft *FencingToken) IncrementEpoch() uint64

IncrementEpoch increments the epoch.

func (*FencingToken) Validate

func (ft *FencingToken) Validate(token uint64) bool

Validate validates a fencing token.

type InstallSnapshotRequest

type InstallSnapshotRequest struct {
	Term              uint64 `json:"term"`
	LeaderID          string `json:"leader_id"`
	LastIncludedIndex uint64 `json:"last_included_index"`
	LastIncludedTerm  uint64 `json:"last_included_term"`
	Data              []byte `json:"data"`
}

InstallSnapshotRequest is sent by the leader to install a snapshot.

type InstallSnapshotResponse

type InstallSnapshotResponse struct {
	Term uint64 `json:"term"`
}

InstallSnapshotResponse is the reply to InstallSnapshot.

type LogEntry

type LogEntry struct {
	Term    uint64    `json:"term"`
	Index   uint64    `json:"index"`
	Type    EntryType `json:"type"`
	Data    []byte    `json:"data"`
	Command []byte    `json:"command,omitempty"`
}

LogEntry represents a single entry in the Raft log.

func DecodeLogEntry

func DecodeLogEntry(data []byte) (*LogEntry, error)

DecodeLogEntry decodes a LogEntry from bytes.

type MemoryTransport

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

MemoryTransport is a transport for testing (in-process).

func NewMemoryTransport

func NewMemoryTransport(id string) *MemoryTransport

NewMemoryTransport creates a new in-memory transport for testing.

func (*MemoryTransport) Close

func (t *MemoryTransport) Close() error

Close stops the transport.

func (*MemoryTransport) Listen

func (t *MemoryTransport) Listen(addr string, handler func(from string, msg *RaftMessage)) error

Listen starts handling incoming messages.

func (*MemoryTransport) Register

func (t *MemoryTransport) Register(registry map[string]*MemoryTransport)

Register registers this transport with a cluster registry.

func (*MemoryTransport) Send

func (t *MemoryTransport) Send(nodeID string, msg *RaftMessage) error

Send sends a message to a node.

func (*MemoryTransport) SendAppendEntries

func (t *MemoryTransport) SendAppendEntries(nodeID string, req *AppendEntriesRequest) (*AppendEntriesResponse, error)

SendAppendEntries sends AppendEntries to a node.

func (*MemoryTransport) SendInstallSnapshot

func (t *MemoryTransport) SendInstallSnapshot(nodeID string, req *InstallSnapshotRequest) (*InstallSnapshotResponse, error)

SendInstallSnapshot sends a snapshot to a node.

func (*MemoryTransport) SendRequestVote

func (t *MemoryTransport) SendRequestVote(nodeID string, req *RequestVoteRequest) (*RequestVoteResponse, error)

SendRequestVote sends RequestVote to a node.

func (*MemoryTransport) SetPartition

func (t *MemoryTransport) SetPartition(nodeID string, partitioned bool)

SetPartition toggles a bidirectional test-network partition between this transport and nodeID. Send checks both endpoints, so changing either side is sufficient to isolate the link.

type MessageType

type MessageType uint8

Raft message types.

const (
	MsgAppendEntries       MessageType = 0
	MsgAppendEntriesResp   MessageType = 1
	MsgRequestVote         MessageType = 2
	MsgRequestVoteResp     MessageType = 3
	MsgInstallSnapshot     MessageType = 4
	MsgInstallSnapshotResp MessageType = 5
	MsgHeartbeat           MessageType = 6
	MsgHeartbeatResp       MessageType = 7
	MsgEtcdRaft            MessageType = 8
)

type MetadataCommand

type MetadataCommand struct {
	Op        MetadataOpType    `json:"op"`
	Node      *NodeInfo         `json:"node,omitempty"`
	Partition *PartitionGroupID `json:"partition,omitempty"`
	Replicas  []string          `json:"replicas,omitempty"`
	Leader    string            `json:"leader,omitempty"`
	ISR       []string          `json:"isr,omitempty"`
	Epoch     uint64            `json:"epoch,omitempty"`
}

MetadataCommand represents a serialized mutation submitted to the controller quorum.

type MetadataOpType

type MetadataOpType byte

MetadataOpType identifies a cluster metadata mutation.

const (
	OpRegisterNode    MetadataOpType = 1
	OpDeregisterNode  MetadataOpType = 2
	OpAssignPartition MetadataOpType = 3
	OpUpdateISR       MetadataOpType = 4
	OpAdvanceEpoch    MetadataOpType = 5
)

type MetadataStateMachine

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

MetadataStateMachine applies metadata commands to ClusterMetadata.

func NewMetadataStateMachine

func NewMetadataStateMachine(meta *ClusterMetadata) *MetadataStateMachine

func (*MetadataStateMachine) Apply

func (sm *MetadataStateMachine) Apply(entry *LogEntry) error

func (*MetadataStateMachine) Restore

func (sm *MetadataStateMachine) Restore(data []byte) error

func (*MetadataStateMachine) Snapshot

func (sm *MetadataStateMachine) Snapshot() ([]byte, error)

type NackCommand

type NackCommand struct {
	MessageID        string        `json:"message_id"`
	Queue            string        `json:"queue"`
	LeaseToken       string        `json:"lease_token"`
	ConsumerID       string        `json:"consumer_id"`
	Action           string        `json:"action"`
	Reason           string        `json:"reason"`
	Error            string        `json:"error"`
	Delay            time.Duration `json:"delay"`
	DLQ              string        `json:"dlq"`
	ResetLease       bool          `json:"reset_lease"`
	IncrementAttempt bool          `json:"increment_attempt"`
}

NackCommand mirrors broker.NackRequest for replication.

type NodeInfo

type NodeInfo struct {
	ID        string            `json:"id"`
	Address   string            `json:"address"`
	State     NodeState         `json:"state"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	JoinedAt  time.Time         `json:"joined_at"`
	UpdatedAt time.Time         `json:"updated_at"`
	LastSeen  time.Time         `json:"last_seen"`
	IsLeader  bool              `json:"is_leader"`
}

NodeInfo contains information about a cluster node.

type NodeState

type NodeState string

Node states.

const (
	NodeJoining  NodeState = "joining"
	NodeActive   NodeState = "active"
	NodeDraining NodeState = "draining"
	NodeLeft     NodeState = "left"
	NodeFailed   NodeState = "failed"
)

type Partition

type Partition struct {
	ID        string     `json:"id"`
	Nodes     []string   `json:"nodes"`
	StartTime time.Time  `json:"start_time"`
	EndTime   *time.Time `json:"end_time,omitempty"`
	Resolved  bool       `json:"resolved"`
}

Partition represents a network partition.

type PartitionGroup

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

PartitionGroup manages consensus, replication and ISR membership for one partition.

func NewPartitionGroup

func NewPartitionGroup(cfg PartitionGroupConfig) (*PartitionGroup, error)

NewPartitionGroup creates a PartitionGroup backed by etcd/raft.

func (*PartitionGroup) Close

func (pg *PartitionGroup) Close() error

Close marks the partition group as closed.

func (*PartitionGroup) ID

ID returns the partition group identifier.

func (*PartitionGroup) ISR

func (pg *PartitionGroup) ISR() []string

ISR returns a list of node IDs currently in the in-sync replica set.

func (*PartitionGroup) IncrementEpoch

func (pg *PartitionGroup) IncrementEpoch() uint64

IncrementEpoch advances the leader epoch upon leadership acquisition.

func (*PartitionGroup) IsLeader

func (pg *PartitionGroup) IsLeader() bool

IsLeader checks if this node is currently the leader of this partition.

func (*PartitionGroup) LeaderEpoch

func (pg *PartitionGroup) LeaderEpoch() uint64

LeaderEpoch returns the current leader epoch for fencing.

func (*PartitionGroup) LeaderID

func (pg *PartitionGroup) LeaderID() uint64

LeaderID returns the current leader Raft ID.

func (*PartitionGroup) Propose

func (pg *PartitionGroup) Propose(ctx context.Context, epoch uint64, data []byte) error

Propose submits a payload to the partition consensus group, validating leader epoch.

func (*PartitionGroup) Replicas

func (pg *PartitionGroup) Replicas() []*ReplicaState

Replicas returns a snapshot of all known replica states.

func (*PartitionGroup) UpdateReplicaProgress

func (pg *PartitionGroup) UpdateReplicaProgress(nodeID string, lastIndex uint64)

UpdateReplicaProgress records the latest acknowledged log index for a replica and adjusts ISR membership accordingly.

type PartitionGroupConfig

type PartitionGroupConfig struct {
	ID                 PartitionGroupID
	Controller         *RaftController
	ReplicationFactor  int
	MinISR             int
	MaxReplicationLag  uint64
	ReplicationTimeout time.Duration
	Replicas           []string
}

PartitionGroupConfig configures a replicated partition group.

type PartitionGroupID

type PartitionGroupID struct {
	Topic     string `json:"topic"`
	Partition int    `json:"partition"`
}

PartitionGroupID uniquely identifies a stream or topic partition.

func (PartitionGroupID) MarshalText

func (p PartitionGroupID) MarshalText() ([]byte, error)

func (PartitionGroupID) String

func (p PartitionGroupID) String() string

func (*PartitionGroupID) UnmarshalText

func (p *PartitionGroupID) UnmarshalText(text []byte) error

type PartitionMetadata

type PartitionMetadata struct {
	ID          PartitionGroupID `json:"id"`
	Leader      string           `json:"leader"`
	LeaderEpoch uint64           `json:"leader_epoch"`
	Replicas    []string         `json:"replicas"`
	ISR         []string         `json:"isr"`
	UpdatedAt   time.Time        `json:"updated_at"`
}

PartitionMetadata describes the current topology of a single partition.

type QuorumQueue

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

QuorumQueue is a replicated queue that requires majority acknowledgment.

func NewQuorumQueue

func NewQuorumQueue(cfg QuorumQueueConfig) *QuorumQueue

NewQuorumQueue creates a new quorum queue.

func (*QuorumQueue) Ack

func (qq *QuorumQueue) Ack(messageID string, nodeID string) error

Ack acknowledges a message replica.

func (*QuorumQueue) CommitIndex

func (qq *QuorumQueue) CommitIndex() uint64

CommitIndex returns the committed index.

func (*QuorumQueue) Get

func (qq *QuorumQueue) Get(limit int) []ReplicatedMessage

Get retrieves a message from the quorum queue.

func (*QuorumQueue) Publish

func (qq *QuorumQueue) Publish(data []byte, headers map[string]string) (*ReplicatedMessage, error)

Publish publishes a message to the quorum queue.

func (*QuorumQueue) Start

func (qq *QuorumQueue) Start() error

Start starts the quorum queue.

func (*QuorumQueue) Stats

func (qq *QuorumQueue) Stats() map[string]any

Stats returns quorum queue statistics.

func (*QuorumQueue) Stop

func (qq *QuorumQueue) Stop()

Stop stops the quorum queue.

type QuorumQueueConfig

type QuorumQueueConfig struct {
	Name     string
	Cluster  *Cluster
	Replicas []string
}

QuorumQueueConfig holds configuration for a quorum queue.

type Raft

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

Raft implements the Raft consensus algorithm.

func NewRaft

func NewRaft(cfg RaftConfig) *Raft

NewRaft creates a new Raft instance.

func (*Raft) AddPeer

func (r *Raft) AddPeer(peerID string) error

AddPeer submits a configuration change to add a peer to the cluster.

func (*Raft) AppendEntry

func (r *Raft) AppendEntry(data []byte) (uint64, error)

AppendEntry appends a new entry to the log (only works on leader).

func (*Raft) CommitIndex

func (r *Raft) CommitIndex() uint64

CommitIndex returns the current commit index.

func (*Raft) CurrentTerm

func (r *Raft) CurrentTerm() uint64

CurrentTerm returns the current term.

func (*Raft) GetEntry

func (r *Raft) GetEntry(index uint64) (*LogEntry, error)

GetEntry reads a log entry by index from the in-memory log.

func (*Raft) HandleMessage

func (r *Raft) HandleMessage(from string, msg *RaftMessage)

HandleMessage processes an incoming Raft message.

func (*Raft) IsLeader

func (r *Raft) IsLeader() bool

IsLeader returns true if this node is the leader.

func (*Raft) LastApplied

func (r *Raft) LastApplied() uint64

LastApplied returns the last applied index.

func (*Raft) Leader

func (r *Raft) Leader() string

Leader returns the current leader ID.

func (*Raft) Peers

func (r *Raft) Peers() []string

Peers returns the list of peers.

func (*Raft) QuorumSize

func (r *Raft) QuorumSize() int

QuorumSize returns the quorum size.

func (*Raft) ReadIndex

func (r *Raft) ReadIndex() (uint64, error)

ReadIndex returns the current commit index after confirming leadership. If this node is not the leader, it returns ErrNotLeader. For linearizable reads, the caller should wait until its local state machine has applied up to the returned index before serving the read.

func (*Raft) RemovePeer

func (r *Raft) RemovePeer(peerID string) error

RemovePeer submits a configuration change to remove a peer from the cluster.

func (*Raft) Start

func (r *Raft) Start() error

Start starts the Raft node.

func (*Raft) State

func (r *Raft) State() RaftState

State returns the current Raft state.

func (*Raft) Stop

func (r *Raft) Stop()

Stop stops the Raft node.

func (*Raft) Submit

func (r *Raft) Submit(command []byte) (uint64, error)

Submit submits a command to the Raft cluster.

type RaftConfig

type RaftConfig struct {
	ID                string
	Peers             []string
	Transport         Transport
	StateMachine      StateMachine
	WAL               *RaftWAL
	ElectionTimeout   time.Duration
	HeartbeatTimeout  time.Duration
	SnapshotThreshold uint64
	OnStateChange     func(state RaftState)
	OnLeaderChange    func(leader string)
	OnConfigChange    func(peers []string)
}

RaftConfig holds configuration for a Raft node.

type RaftController

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

RaftController runs an etcd/raft consensus engine with network transport, local state machine application, and linearizable command proposals.

func NewRaftController

func NewRaftController(cfg RaftControllerConfig) (*RaftController, error)

NewRaftController creates a complete Raft controller backed by etcd/raft.

func (*RaftController) AddPeer

func (c *RaftController) AddPeer(ctx context.Context, address string) (uint64, error)

AddPeer adds a voting member and returns its allocated Raft ID.

func (*RaftController) AppliedIndex

func (c *RaftController) AppliedIndex() uint64

AppliedIndex is the highest committed entry applied to the broker state.

func (*RaftController) Campaign

func (c *RaftController) Campaign() error

Campaign forces the Raft controller to campaign for leadership.

func (*RaftController) FatalError

func (c *RaftController) FatalError() error

FatalError reports a terminal persistence or state-machine failure. Once set, the controller rejects new writes until it is restarted and recovered.

func (*RaftController) HandleMessage

func (c *RaftController) HandleMessage(from string, msg *RaftMessage) error

HandleMessage decodes and processes an incoming transport message carrying etcd/raft frames.

func (*RaftController) IsLeader

func (c *RaftController) IsLeader() bool

IsLeader reports whether this node is currently the cluster leader.

func (*RaftController) LeaderID

func (c *RaftController) LeaderID() uint64

LeaderID returns the current known cluster leader ID.

func (*RaftController) PeerAddress

func (c *RaftController) PeerAddress(id uint64) (string, bool)

PeerAddress resolves a Raft ID to its current transport address.

func (*RaftController) PeerID

func (c *RaftController) PeerID(address string) (uint64, bool)

PeerID resolves a transport address to its current Raft ID.

func (*RaftController) Propose

func (c *RaftController) Propose(ctx context.Context, data []byte) error

Propose submits a command to the Raft cluster and waits for quorum commit.

func (*RaftController) ProposeConfChange

func (c *RaftController) ProposeConfChange(ctx context.Context, cc *raftpb.ConfChange) error

ProposeConfChange proposes a membership change.

func (*RaftController) RegisterTransportHandler

func (c *RaftController) RegisterTransportHandler(addr string) error

RegisterTransportHandler attaches this controller to a network transport.

func (*RaftController) RemovePeer

func (c *RaftController) RemovePeer(ctx context.Context, id uint64) error

RemovePeer removes a voting member by numeric Raft ID.

func (*RaftController) SnapshotIndex

func (c *RaftController) SnapshotIndex() uint64

SnapshotIndex is the highest applied index captured in a durable snapshot.

func (*RaftController) Start

func (c *RaftController) Start() error

Start launches the background event and tick loops.

func (*RaftController) Status

func (c *RaftController) Status() etcdraft.Status

Status returns the current status of the Raft core.

func (*RaftController) Step

func (c *RaftController) Step(ctx context.Context, msg *raftpb.Message) error

Step handles an incoming etcd/raft message received from a peer.

func (*RaftController) Stop

func (c *RaftController) Stop() error

Stop cleanly terminates the controller.

func (*RaftController) Term

func (c *RaftController) Term() uint64

Term returns the current election term.

func (*RaftController) TransferLeadership

func (c *RaftController) TransferLeadership(ctx context.Context, transferee uint64)

TransferLeadership transfers leadership to transferee.

type RaftControllerConfig

type RaftControllerConfig struct {
	ID                        uint64
	NodeID                    string
	Peers                     map[uint64]string // ID -> address/nodeID
	ElectionTick              int
	HeartbeatTick             int
	TickInterval              time.Duration
	MaxMessageBytes           uint64
	MaxInflightMessages       int
	MaxUncommittedEntryBytes  uint64
	DisableProposalForwarding bool
	Transport                 Transport
	StateMachine              StateMachine
	StorageDir                string
	SkipBootstrap             bool
	// SnapshotEntries controls automatic state-machine snapshots and Raft log
	// compaction. Zero uses 10,000 committed entries.
	SnapshotEntries uint64
	// SnapshotCatchUpEntries are retained behind the snapshot for lagging peers.
	// Zero uses 1,024 entries.
	SnapshotCatchUpEntries uint64
}

RaftControllerConfig configures an active RaftController.

type RaftMessage

type RaftMessage struct {
	CorrelationID       uint64                   `json:"correlation_id,omitempty"`
	Type                MessageType              `json:"type"`
	AppendEntries       *AppendEntriesRequest    `json:"append_entries,omitempty"`
	AppendEntriesResp   *AppendEntriesResponse   `json:"append_entries_resp,omitempty"`
	RequestVote         *RequestVoteRequest      `json:"request_vote,omitempty"`
	RequestVoteResp     *RequestVoteResponse     `json:"request_vote_resp,omitempty"`
	InstallSnapshot     *InstallSnapshotRequest  `json:"install_snapshot,omitempty"`
	InstallSnapshotResp *InstallSnapshotResponse `json:"install_snapshot_resp,omitempty"`
	EtcdMessage         []byte                   `json:"etcd_message,omitempty"`
}

RaftMessage wraps all Raft RPC messages.

func DecodeMessage

func DecodeMessage(data []byte) (*RaftMessage, error)

DecodeMessage decodes a RaftMessage from bytes.

func (*RaftMessage) MarshalJSON

func (m *RaftMessage) MarshalJSON() ([]byte, error)

JSON serialization helpers for Raft messages.

func (*RaftMessage) UnmarshalJSON

func (m *RaftMessage) UnmarshalJSON(data []byte) error

type RaftState

type RaftState int

Raft states.

const (
	StateFollower RaftState = iota
	StateCandidate
	StateLeader
	StateDead
)

func (RaftState) String

func (s RaftState) String() string

type RaftWAL

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

RaftWAL is a write-ahead log for Raft entries. Format per record: [4-byte CRC32][4-byte length][payload]

func NewRaftWAL

func NewRaftWAL(cfg WALConfig) (*RaftWAL, error)

NewRaftWAL creates or opens a Raft WAL at the given directory.

func (*RaftWAL) Append

func (w *RaftWAL) Append(entry *LogEntry) error

Append appends a log entry to the WAL.

func (*RaftWAL) Close

func (w *RaftWAL) Close() error

Close closes the WAL.

func (*RaftWAL) Compact

func (w *RaftWAL) Compact(beforeIndex uint64) error

Compact removes entries before the given index.

func (*RaftWAL) Contains

func (w *RaftWAL) Contains(index uint64) bool

Contains returns true if the WAL contains the given index.

func (*RaftWAL) FirstIndex

func (w *RaftWAL) FirstIndex() uint64

FirstIndex returns the first index in the WAL.

func (*RaftWAL) LastIndex

func (w *RaftWAL) LastIndex() uint64

LastIndex returns the last index in the WAL.

func (*RaftWAL) Read

func (w *RaftWAL) Read(index uint64) (*LogEntry, error)

Read reads a log entry by index.

func (*RaftWAL) ReadRange

func (w *RaftWAL) ReadRange(from, to uint64) ([]*LogEntry, error)

ReadRange reads a range of log entries [from, to].

func (*RaftWAL) Snapshot

func (w *RaftWAL) Snapshot(snapshot *Snapshot) error

Snapshot writes a snapshot marker to the WAL and truncates entries up to lastIncludedIndex.

func (*RaftWAL) Stats

func (w *RaftWAL) Stats() map[string]any

Stats returns WAL statistics.

func (*RaftWAL) Sync

func (w *RaftWAL) Sync() error

Sync explicitly fsyncs the WAL file. Useful before taking a snapshot or when the caller needs durability guarantees in SyncBatched mode.

func (*RaftWAL) Truncate

func (w *RaftWAL) Truncate(lastIndex uint64) error

Truncate removes all entries with index > lastIndex.

type ReplicaState

type ReplicaState struct {
	NodeID       string    `json:"node_id"`
	LastAckIndex uint64    `json:"last_ack_index"`
	LastAckTime  time.Time `json:"last_ack_time"`
	IsISR        bool      `json:"is_isr"`
}

ReplicaState holds synchronization details for a single partition replica.

type ReplicatedMessage

type ReplicatedMessage struct {
	ID        string            `json:"id"`
	Index     uint64            `json:"index"`
	Term      uint64            `json:"term"`
	Data      []byte            `json:"data"`
	Headers   map[string]string `json:"headers,omitempty"`
	Replicas  []string          `json:"replicas"`
	Acks      int               `json:"acks"`
	Committed bool              `json:"committed"`
	CreatedAt time.Time         `json:"created_at"`
}

ReplicatedMessage represents a message with replication metadata.

type RequestVoteRequest

type RequestVoteRequest struct {
	Term         uint64 `json:"term"`
	CandidateID  string `json:"candidate_id"`
	LastLogIndex uint64 `json:"last_log_index"`
	LastLogTerm  uint64 `json:"last_log_term"`
}

RequestVoteRequest is sent by candidates to gather votes.

type RequestVoteResponse

type RequestVoteResponse struct {
	Term        uint64 `json:"term"`
	VoteGranted bool   `json:"vote_granted"`
}

RequestVoteResponse is the reply to RequestVote.

type Snapshot

type Snapshot struct {
	Term              uint64 `json:"term"`
	LastIncludedIndex uint64 `json:"last_included_index"`
	LastIncludedTerm  uint64 `json:"last_included_term"`
	Data              []byte `json:"data"`
}

Snapshot represents a point-in-time snapshot of the Raft state.

func DecodeSnapshot

func DecodeSnapshot(data []byte) (*Snapshot, error)

DecodeSnapshot deserializes a Snapshot from JSON bytes.

type SnapshotData

type SnapshotData struct {
	Term      uint64
	Index     uint64
	Timestamp time.Time
	Payload   []byte
}

SnapshotData represents an in-memory or persisted snapshot.

func DecodeBinarySnapshot

func DecodeBinarySnapshot(data []byte) (*SnapshotData, error)

DecodeBinarySnapshot parses binary snapshot bytes into SnapshotData, verifying checksum.

func (*SnapshotData) Encode

func (s *SnapshotData) Encode() ([]byte, error)

Encode encodes snapshot data into the binary format: [Magic:4][Version:1][Reserved:3][Term:8][Index:8][Timestamp:8][DataLen:8][Checksum:4][Payload:N]

type SnapshotHeader

type SnapshotHeader struct {
	Magic     [4]byte
	Version   uint8
	Reserved  [3]byte
	Term      uint64
	Index     uint64
	Timestamp int64
	DataLen   uint64
	Checksum  uint32
}

SnapshotHeader contains metadata describing a state machine snapshot.

type SnapshotManager

type SnapshotManager struct{}

SnapshotManager manages snapshot creation, validation, and restoration.

func NewSnapshotManager

func NewSnapshotManager() *SnapshotManager

func (*SnapshotManager) CreateSnapshot

func (sm *SnapshotManager) CreateSnapshot(term, index uint64, stateMachine StateMachine) ([]byte, error)

CreateSnapshot captures a snapshot from the state machine and returns encoded bytes.

func (*SnapshotManager) RestoreSnapshot

func (sm *SnapshotManager) RestoreSnapshot(data []byte, stateMachine StateMachine) error

RestoreSnapshot restores snapshot bytes into the state machine.

type SplitBrainConfig

type SplitBrainConfig struct {
	Cluster       *Cluster
	CheckInterval time.Duration
	OnSplitBrain  func(partition Partition)
}

SplitBrainConfig holds configuration for split-brain detection.

type SplitBrainDetector

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

SplitBrainDetector detects and handles split-brain scenarios.

func NewSplitBrainDetector

func NewSplitBrainDetector(cfg SplitBrainConfig) *SplitBrainDetector

NewSplitBrainDetector creates a new split-brain detector.

func (*SplitBrainDetector) GetPartitions

func (d *SplitBrainDetector) GetPartitions() []Partition

GetPartitions returns all detected partitions.

func (*SplitBrainDetector) HasQuorum

func (d *SplitBrainDetector) HasQuorum() bool

HasQuorum returns true if the cluster currently has quorum.

func (*SplitBrainDetector) Start

func (d *SplitBrainDetector) Start() error

Start starts the split-brain detector.

func (*SplitBrainDetector) Stop

func (d *SplitBrainDetector) Stop()

Stop stops the split-brain detector.

type StateMachine

type StateMachine interface {
	// Apply applies a committed log entry to the state machine.
	Apply(entry *LogEntry) error
	// Snapshot returns a snapshot of the current state.
	Snapshot() ([]byte, error)
	// Restore restores the state machine from a snapshot.
	Restore(snapshot []byte) error
}

StateMachine defines the interface for the replicated state machine.

type SyncMode

type SyncMode int

SyncMode controls how often the WAL fsyncs to disk.

const (
	SyncAlways  SyncMode = iota // fsync on every Append
	SyncBatched                 // fsync at regular intervals (default)
	SyncNone                    // no fsync (testing/benchmarking only)
)

type TCPTransport

type TCPTransport struct {
	TLSConfig *tls.Config

	HandshakeTimeout time.Duration
	ReadTimeout      time.Duration
	WriteTimeout     time.Duration
	WriteBufLimit    int64
	// contains filtered or unexported fields
}

TCPTransport implements the Transport interface using TCP.

func NewTCPTransport

func NewTCPTransport() *TCPTransport

NewTCPTransport creates a new TCP transport.

func (*TCPTransport) Addr

func (t *TCPTransport) Addr() string

Addr returns the local address.

func (*TCPTransport) Close

func (t *TCPTransport) Close() error

Close stops the transport.

func (*TCPTransport) ConnectedNodes

func (t *TCPTransport) ConnectedNodes() []string

ConnectedNodes returns the list of connected node IDs.

func (*TCPTransport) Listen

func (t *TCPTransport) Listen(addr string, handler func(from string, msg *RaftMessage)) error

Listen starts listening for incoming connections.

func (*TCPTransport) Send

func (t *TCPTransport) Send(nodeID string, msg *RaftMessage) error

Send sends a message to a specific node.

func (*TCPTransport) SendAppendEntries

func (t *TCPTransport) SendAppendEntries(nodeID string, req *AppendEntriesRequest) (*AppendEntriesResponse, error)

SendAppendEntries sends AppendEntries to a node and waits for the response.

func (*TCPTransport) SendInstallSnapshot

func (t *TCPTransport) SendInstallSnapshot(nodeID string, req *InstallSnapshotRequest) (*InstallSnapshotResponse, error)

SendInstallSnapshot sends a snapshot to a node and waits for the response.

func (*TCPTransport) SendRequestVote

func (t *TCPTransport) SendRequestVote(nodeID string, req *RequestVoteRequest) (*RequestVoteResponse, error)

SendRequestVote sends RequestVote to a node and waits for the response.

func (*TCPTransport) Stats

func (t *TCPTransport) Stats() map[string]any

Stats returns a snapshot of transport statistics.

type Transport

type Transport interface {
	// Send sends a message to a specific node.
	Send(nodeID string, msg *RaftMessage) error
	// SendAppendEntries sends AppendEntries to a node.
	SendAppendEntries(nodeID string, req *AppendEntriesRequest) (*AppendEntriesResponse, error)
	// SendRequestVote sends RequestVote to a node.
	SendRequestVote(nodeID string, req *RequestVoteRequest) (*RequestVoteResponse, error)
	// SendInstallSnapshot sends a snapshot to a node.
	SendInstallSnapshot(nodeID string, req *InstallSnapshotRequest) (*InstallSnapshotResponse, error)
	// Listen starts listening for incoming messages.
	Listen(addr string, handler func(from string, msg *RaftMessage)) error
	// Close stops the transport.
	Close() error
}

Transport defines the interface for inter-node communication.

type WALCommandType

type WALCommandType string

WALCommandType is the type of WAL command.

const (
	WALCommandReplicate WALCommandType = "replicate"
	WALCommandAck       WALCommandType = "ack"
	WALCommandTrim      WALCommandType = "trim"
)

type WALConfig

type WALConfig struct {
	Directory    string
	SyncMode     SyncMode
	SyncInterval time.Duration
	PreallocSize int64
}

WALConfig holds configuration for the Raft WAL.

type WALReplication

type WALReplication struct {
	Index     uint64    `json:"index"`
	Data      []byte    `json:"data"`
	Replicas  []string  `json:"replicas"`
	Acks      int       `json:"acks"`
	Quorum    int       `json:"quorum"`
	CreatedAt time.Time `json:"created_at"`
}

WALReplication represents a pending WAL replication.

type WALReplicationCommand

type WALReplicationCommand struct {
	Type  WALCommandType `json:"type"`
	Index uint64         `json:"index"`
	Data  []byte         `json:"data"`
}

WALReplicationCommand is a command for WAL replication.

type WALReplicator

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

WALReplicator handles replication of the Write-Ahead Log across cluster nodes.

func NewWALReplicator

func NewWALReplicator(cfg WALReplicatorConfig) *WALReplicator

NewWALReplicator creates a new WAL replicator.

func (*WALReplicator) Acknowledge

func (r *WALReplicator) Acknowledge(index uint64, nodeID string) error

Acknowledge acknowledges a replication from a replica.

func (*WALReplicator) IsReplicated

func (r *WALReplicator) IsReplicated(index uint64) bool

IsReplicated returns true if an index has been replicated.

func (*WALReplicator) LastReplicated

func (r *WALReplicator) LastReplicated() uint64

LastReplicated returns the last replicated index.

func (*WALReplicator) Replicate

func (r *WALReplicator) Replicate(index uint64, data []byte) error

Replicate replicates a WAL entry to all replicas.

func (*WALReplicator) Start

func (r *WALReplicator) Start() error

Start starts the WAL replicator.

func (*WALReplicator) Stats

func (r *WALReplicator) Stats() map[string]any

Stats returns replication statistics.

func (*WALReplicator) Stop

func (r *WALReplicator) Stop()

Stop stops the WAL replicator.

type WALReplicatorConfig

type WALReplicatorConfig struct {
	Cluster      *Cluster
	FencingToken *FencingToken
	OnReplicated func(index uint64, data []byte)
}

WALReplicatorConfig holds configuration for the WAL replicator.

Jump to

Keyboard shortcuts

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