cluster

package
v1.17.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 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

本文件在已有归属Gateway心跳中重放现存订阅摘要,恢复新启动peer的正式中继索引。

本文件只处理 Redis legacy 自动编号的启动租约。槽位与旧版 Register 共用。

Package cluster 提供服务发现和水平扩展身份分配能力。

Package cluster provides the service discovery, membership management, and load balancing infrastructure for horizontally scaled core services.

Architecture:

ClusterProvider (local / etcd / consul)
  └─ ClusterRegistry  — register, deregister, list nodes
  └─ DiscoveryProvider — watch changes
  └─ MembershipManager — heartbeat, lease, fault detection
  └─ LoadBalancer      — local-first / round-robin / consistent-hash / weighted
  └─ ServiceShardRouter — shard-key based routing rules

本文件以 etcd 事务原子保护持久 owner 和带租约节点。

本文件提供 local Provider 的原子稳定注册,不检查生成器槽位。

本文件以单次 Lua 原子操作保护 owner 和实际 Redis 注册记录。

本文件定义与 MachineID 无关的稳定注册所有权能力。

Index

Constants

View Source
const (
	// DefaultEtcdTTL is the default lease TTL when no TTL is configured.
	DefaultEtcdTTL = 10 * time.Second
	// DefaultEtcdPrefix preserves the existing runtime etcd keyspace.
	DefaultEtcdPrefix = "/core/cluster"
)

Variables

View Source
var (
	// ErrNodeNotFound is returned when a node lookup finds no matching entry.
	ErrNodeNotFound = errors.New("cluster: node not found")

	// ErrSlotConflict is returned when a node tries to register a
	// DataCenterID+MachineID pair that is already held by a different running node.
	ErrSlotConflict = errors.New("cluster: DataCenterID+MachineID slot already taken")

	// ErrMigrationInProgress is returned when Begin is called while another
	// provider migration is already underway.
	ErrMigrationInProgress = errors.New("cluster: provider migration already in progress")

	// ErrNotStarted is returned when an operation is attempted before the
	// cluster provider has been started.
	ErrNotStarted = errors.New("cluster: provider not started")

	// ErrEmptyCandidates is returned by the load balancer when the filtered
	// candidate list is empty.
	ErrEmptyCandidates = errors.New("cluster: no candidates after filtering")
)

Sentinel errors for the cluster package.

View Source
var ErrRegistrationAuthorityMissing = errors.New("cluster: registration authority missing")

ErrRegistrationAuthorityMissing 表示持久注册世代丢失,需要显式恢复。

View Source
var ErrRegistrationFenced = errors.New("cluster: registration fenced by another boot")

ErrRegistrationFenced 表示注册已由更高启动世代持有。

Functions

func AllocateMachineID

func AllocateMachineID(ctx context.Context, provider DiscoveryProvider, serviceName string, dataCenterID, maxMachineID int64) (int64, error)

AllocateMachineID 从当前发现 Provider 中查找可用 MachineID。

func VerifyRegistration added in v1.4.0

func VerifyRegistration(ctx context.Context, registry ClusterRegistry, expected *NodeInfo, owner RegistrationOwner) error

VerifyRegistration 读回完整节点,确认注册可见且属于本次启动。

Types

type BalanceHint

type BalanceHint struct {
	// HashKey is used by consistent-hash balancing.
	HashKey string
	// PreferLocal makes local-first strategy prefer the current process.
	PreferLocal bool
	// LocalServiceName is used by local-first to identify the current node.
	LocalNodeID string
}

BalanceHint carries optional data used by certain strategies (e.g. hash key).

type ClusterRegistry

type ClusterRegistry interface {
	// Register adds or refreshes a node entry. Returns an error if the slot
	// (DataCenterID + MachineID combination) is already taken by a different running node.
	Register(ctx context.Context, node *NodeInfo) error

	// Deregister marks a node as offline.
	Deregister(ctx context.Context, nodeID string) error

	// Heartbeat refreshes the node's last-seen timestamp and ensures Status=running.
	Heartbeat(ctx context.Context, nodeID string) error

	// Get returns the node with the given ID, or ErrNodeNotFound.
	Get(ctx context.Context, nodeID string) (*NodeInfo, error)

	// List returns nodes for the given service, optionally filtered by status.
	// An empty serviceName returns nodes across all services.
	List(ctx context.Context, serviceName string, statuses ...NodeStatus) ([]*NodeInfo, error)

	// Watch calls onChange whenever the node list for serviceName changes.
	// The returned cancel function stops watching.
	Watch(ctx context.Context, serviceName string, onChange func([]*NodeInfo)) (cancel func(), err error)

	// Close releases all resources.
	Close() error
}

ClusterRegistry provides node registration and lookup.

type ConsistentHashBalancer

type ConsistentHashBalancer struct{}

ConsistentHashBalancer 使用 rendezvous hash 将相同 HashKey 稳定路由到同一节点。 候选顺序不会改变 owner;新增节点时只有迁移到新节点的 key 会改变 owner。

func NewConsistentHashBalancer

func NewConsistentHashBalancer() *ConsistentHashBalancer

func (*ConsistentHashBalancer) Pick

func (b *ConsistentHashBalancer) Pick(_ context.Context, candidates []*NodeInfo, hint BalanceHint) (*NodeInfo, error)

type ConsulProvider

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

ConsulProvider implements DiscoveryProvider using HashiCorp Consul. Each node is registered as a Consul service entry:

ServiceID: "<serviceName>-<nodeID>"
Tags: ["core-cluster", "<serviceName>"]
Meta: JSON-encoded extra NodeInfo fields

func NewConsulProvider

func NewConsulProvider(address string) (*ConsulProvider, error)

NewConsulProvider creates a provider connected to the given Consul address.

func (*ConsulProvider) AllocateMachineID

func (c *ConsulProvider) AllocateMachineID(ctx context.Context, serviceName string, dataCenterID int64) (int64, error)

AllocateMachineID finds the lowest available MachineID (0–1023) not held by a running node for the given service and DataCenterID.

func (*ConsulProvider) Close

func (c *ConsulProvider) Close() error

func (*ConsulProvider) Deregister

func (c *ConsulProvider) Deregister(ctx context.Context, nodeID string) error

Deregister removes the node from Consul.

func (*ConsulProvider) Get

func (c *ConsulProvider) Get(ctx context.Context, nodeID string) (*NodeInfo, error)

Get returns the NodeInfo for the given nodeID.

func (*ConsulProvider) Heartbeat

func (c *ConsulProvider) Heartbeat(ctx context.Context, nodeID string) error

Heartbeat updates the TTL health check to passing.

func (*ConsulProvider) List

func (c *ConsulProvider) List(ctx context.Context, serviceName string, statuses ...NodeStatus) ([]*NodeInfo, error)

List returns nodes for the given service, optionally filtered by status.

func (*ConsulProvider) Name

func (c *ConsulProvider) Name() string

func (*ConsulProvider) Register

func (c *ConsulProvider) Register(ctx context.Context, node *NodeInfo) error

Register registers the node in Consul with a TTL health check.

func (*ConsulProvider) Watch

func (c *ConsulProvider) Watch(ctx context.Context, serviceName string, onChange func([]*NodeInfo)) (func(), error)

Watch calls onChange whenever the service catalog changes.

type ContextCloser

type ContextCloser interface {
	CloseContext(ctx context.Context) error
}

ContextCloser is an optional provider capability for cancellable shutdown. DiscoveryProvider intentionally keeps its original Close contract.

type CrossNodeNoticeBroker

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

CrossNodeNoticeBroker implements types.ICrossNodeForwarder by forwarding WebSocket notices to peer nodes via HTTP and tracking peer subscriptions.

When ForwardNotice is called on node A, it:

  1. Looks up peer subscriptions in the registry.
  2. For each peer node that has subscribers for routePath+hash, sends an HTTP POST to /api/servermanage/ws/notice.
  3. The receiving node's relay endpoint calls RouterInfo.ExecuteLocalNotice.

func NewCrossNodeNoticeBroker

func NewCrossNodeNoticeBroker(provider DiscoveryProvider, serviceName, localNodeID string) *CrossNodeNoticeBroker

NewCrossNodeNoticeBroker creates a broker backed by the given provider.

func (*CrossNodeNoticeBroker) DrainAndStop

func (b *CrossNodeNoticeBroker) DrainAndStop(ctx context.Context)

DrainAndStop broadcasts subscription-removed events for all local subscriptions and marks the broker as stopped. Called by ServiceContext.Stop().

func (*CrossNodeNoticeBroker) ForwardNotice

func (b *CrossNodeNoticeBroker) ForwardNotice(ctx context.Context, routePath string, hash uint64, message interface{})

ForwardNotice implements types.ICrossNodeForwarder. It checks which peer nodes have subscribed to the given routePath+hash and forwards the message to them asynchronously.

func (*CrossNodeNoticeBroker) OnSubscriptionChange

func (b *CrossNodeNoticeBroker) OnSubscriptionChange(routePath string, hash uint64, active bool)

OnSubscriptionChange implements types.ICrossNodeForwarder. It broadcasts local subscription state to all running peer nodes.

func (*CrossNodeNoticeBroker) PeerSubscribedHashes added in v1.2.1

func (b *CrossNodeNoticeBroker) PeerSubscribedHashes(routePath string) []uint64

PeerSubscribedHashes 返回指定路由当前由对等节点持有的订阅 hash 快照。

func (*CrossNodeNoticeBroker) ReplayLocalSubscriptions added in v1.8.0

func (b *CrossNodeNoticeBroker) ReplayLocalSubscriptions(ctx context.Context) error

ReplayLocalSubscriptions 复用现存会话索引与正式中继;每次最多128条摘要且受ctx约束。 不按peerID永久缓存成功,因此同标识/同地址的新进程也能恢复。调用方复用原有心跳。 持读锁到摘要发送结束,并发退订的false必定在本次true之后发出。

func (*CrossNodeNoticeBroker) SetSender

func (b *CrossNodeNoticeBroker) SetSender(sender CrossNodeSender)

SetSender configures an optional transport-level sender for cross-node requests. When set, notices and subscription summaries are routed through the sender instead of the default http.Client. Sender errors are final; replaying through HTTP could duplicate remote effects.

func (*CrossNodeNoticeBroker) UpdatePeerSubscription

func (b *CrossNodeNoticeBroker) UpdatePeerSubscription(routePath string, hash uint64, nodeID string, active bool)

UpdatePeerSubscription updates the local registry when a peer node notifies us of a subscription change. Called by the relay endpoint.

type CrossNodeSender

type CrossNodeSender func(ctx context.Context, target *NodeInfo, data []byte, path string) ([]byte, error)

CrossNodeSender is an optional hook for sending cross-node requests. NodeInfo carries every protocol endpoint so protocol selection happens before the request is handed to a transport.

type DiscoveryProvider

type DiscoveryProvider interface {
	ClusterRegistry
	Name() string
}

DiscoveryProvider extends ClusterRegistry with provider identity.

func BuildProvider

func BuildProvider(cfg *config.ClusterConfig, sharedLocal *LocalProvider) (DiscoveryProvider, error)

BuildProvider creates a DiscoveryProvider from the cluster configuration. sharedLocal is the process-level LocalProvider used both for intra-process MachineID claiming and as the fallback/default provider for local mode.

type EmptyCandidatePolicy

type EmptyCandidatePolicy string

EmptyCandidatePolicy controls what happens when no candidates match the shard rule.

const (
	EmptyCandidatePolicyError    EmptyCandidatePolicy = "error"
	EmptyCandidatePolicyFallback EmptyCandidatePolicy = "fallback"
)

type EtcdProvider

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

EtcdProvider implements DiscoveryProvider using etcd v3. Nodes are stored as JSON values under the key prefix:

/core/cluster/<serviceName>/<nodeID>

func NewEtcdProvider

func NewEtcdProvider(endpoints []string, ttl time.Duration) (*EtcdProvider, error)

NewEtcdProvider creates a provider connected to the given etcd endpoints. ttl is the lease TTL; if zero, DefaultEtcdTTL is used.

func NewEtcdProviderWithPrefix

func NewEtcdProviderWithPrefix(endpoints []string, ttl time.Duration, prefix string) (*EtcdProvider, error)

NewEtcdProviderWithPrefix creates a provider using the configured etcd key prefix. An empty prefix preserves the existing runtime keyspace.

func (*EtcdProvider) AcquireRegistration added in v1.4.0

func (p *EtcdProvider) AcquireRegistration(ctx context.Context, n *NodeInfo, o RegistrationOwner) error

AcquireRegistration 原子建立/提升世代并发布节点。

func (*EtcdProvider) AllocateMachineID

func (e *EtcdProvider) AllocateMachineID(ctx context.Context, serviceName string, dataCenterID int64) (int64, error)

AllocateMachineID finds the lowest available MachineID (0–1023) not held by a running node for the given DataCenterID.

func (*EtcdProvider) Close

func (e *EtcdProvider) Close() error

func (*EtcdProvider) Deregister

func (e *EtcdProvider) Deregister(ctx context.Context, nodeID string) error

Deregister marks a node offline and revokes its lease.

func (*EtcdProvider) Get

func (e *EtcdProvider) Get(ctx context.Context, nodeID string) (*NodeInfo, error)

Get returns the node with the given ID.

func (*EtcdProvider) Heartbeat

func (e *EtcdProvider) Heartbeat(ctx context.Context, nodeID string) error

Heartbeat keeps alive the node's etcd lease.

func (*EtcdProvider) List

func (e *EtcdProvider) List(ctx context.Context, serviceName string, statuses ...NodeStatus) ([]*NodeInfo, error)

List returns all nodes for the given service, optionally filtered by status.

func (*EtcdProvider) Name

func (e *EtcdProvider) Name() string

func (*EtcdProvider) Register

func (e *EtcdProvider) Register(ctx context.Context, node *NodeInfo) error

Register stores the node in etcd with a lease. If the DC+MachineID slot is already taken by a running node with a different ID, returns ErrSlotConflict.

func (*EtcdProvider) RegistrationTTL added in v1.4.0

func (p *EtcdProvider) RegistrationTTL() time.Duration

RegistrationTTL 返回实际注册有效期,供本地准入保守计时。

func (*EtcdProvider) ReleaseRegistration added in v1.4.0

func (p *EtcdProvider) ReleaseRegistration(ctx context.Context, n *NodeInfo, o RegistrationOwner) error

ReleaseRegistration 仅删除当前 owner 节点,不撤销其他实例的 lease。

func (*EtcdProvider) RenewRegistration added in v1.4.0

func (p *EtcdProvider) RenewRegistration(ctx context.Context, n *NodeInfo, o RegistrationOwner) error

RenewRegistration 同一 owner 可以重建被删除或过期的节点键。

func (*EtcdProvider) Watch

func (e *EtcdProvider) Watch(ctx context.Context, serviceName string, onChange func([]*NodeInfo)) (func(), error)

Watch calls onChange whenever the node list for serviceName changes.

type LegacyMachineIDLease added in v1.17.0

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

LegacyMachineIDLease holds a Redis MachineID slot without advertising a node.

func (*LegacyMachineIDLease) Publish added in v1.17.0

func (l *LegacyMachineIDLease) Publish(ctx context.Context, node *NodeInfo) error

Publish promotes the live reservation to normal discovery, using final endpoint data.

func (*LegacyMachineIDLease) Release added in v1.17.0

func (l *LegacyMachineIDLease) Release(ctx context.Context) error

Release removes this claimant's reservation and any ambiguous publication.

func (*LegacyMachineIDLease) Renew added in v1.17.0

func (l *LegacyMachineIDLease) Renew(ctx context.Context) error

Renew extends only the existing lease, so an expired claimant cannot revive itself.

func (*LegacyMachineIDLease) TTL added in v1.17.0

TTL returns the Redis lease duration used by startup renewal.

type LoadBalancer

type LoadBalancer interface {
	// Pick returns a single node from candidates.
	// Returns ErrEmptyCandidates when the list is empty.
	Pick(ctx context.Context, candidates []*NodeInfo, hint BalanceHint) (*NodeInfo, error)
}

LoadBalancer selects a single node from a candidate list.

type LocalFirstBalancer

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

LocalFirstBalancer prefers the node whose ID matches LocalNodeID, falling back to round-robin among remaining candidates.

func NewLocalFirstBalancer

func NewLocalFirstBalancer() *LocalFirstBalancer

func (*LocalFirstBalancer) Pick

func (b *LocalFirstBalancer) Pick(_ context.Context, candidates []*NodeInfo, hint BalanceHint) (*NodeInfo, error)

type LocalProvider

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

LocalProvider is an in-memory ClusterRegistry suitable for single-node development and unit testing. It supports heartbeat and fault detection but has no network distribution; all nodes must share the same process (or the registry must be passed by pointer).

func NewLocalProvider

func NewLocalProvider(heartbeatTimeout, suspectTimeout, cooldown time.Duration) *LocalProvider

NewLocalProvider creates an in-memory registry. heartbeatTimeout: how long without heartbeat before node becomes suspect. suspectTimeout: how long in suspect before becoming offline. cooldown: minimum time offline before the MachineID slot can be reused.

func (*LocalProvider) AcquireRegistration added in v1.4.0

func (p *LocalProvider) AcquireRegistration(ctx context.Context, n *NodeInfo, o RegistrationOwner) error

AcquireRegistration 取得或升级本实例的持久运行世代。

func (*LocalProvider) AllocateMachineID

func (p *LocalProvider) AllocateMachineID(serviceName string, dataCenterID int64, maxMachineID ...int64) int64

AllocateMachineID 返回指定服务和数据中心的最小可用 MachineID,耗尽时返回 -1。 与 Register 一致,运行中及最后心跳尚在冷却期内的离线节点均占用槽位。 此方法只选择候选,不预留槽位;并发竞争仍由 Register 在写锁下裁决。

func (*LocalProvider) Close

func (p *LocalProvider) Close() error

Close stops the background goroutine.

func (*LocalProvider) Deregister

func (p *LocalProvider) Deregister(_ context.Context, nodeID string) error

Deregister marks a node as offline.

func (*LocalProvider) Get

func (p *LocalProvider) Get(_ context.Context, nodeID string) (*NodeInfo, error)

Get returns the node with the given ID.

func (*LocalProvider) Heartbeat

func (p *LocalProvider) Heartbeat(_ context.Context, nodeID string) error

Heartbeat refreshes a node's last-seen timestamp and resets Status to running.

func (*LocalProvider) List

func (p *LocalProvider) List(_ context.Context, serviceName string, statuses ...NodeStatus) ([]*NodeInfo, error)

List returns nodes for the service, filtered by status (empty = all).

func (*LocalProvider) Name

func (p *LocalProvider) Name() string

func (*LocalProvider) Register

func (p *LocalProvider) Register(_ context.Context, node *NodeInfo) error

Register adds or refreshes a node. If the DataCenterID+MachineID slot is held by a different running node, ErrSlotConflict is returned. If the slot is held by an offline node past its cooldown, the slot is reclaimed.

func (*LocalProvider) RegistrationTTL added in v1.4.0

func (p *LocalProvider) RegistrationTTL() time.Duration

RegistrationTTL 返回实际注册有效期,供本地准入保守计时。

func (*LocalProvider) ReleaseRegistration added in v1.4.0

func (p *LocalProvider) ReleaseRegistration(ctx context.Context, n *NodeInfo, o RegistrationOwner) error

ReleaseRegistration 仅删除当前 owner 的节点,保留世代记录。

func (*LocalProvider) RenewRegistration added in v1.4.0

func (p *LocalProvider) RenewRegistration(ctx context.Context, n *NodeInfo, o RegistrationOwner) error

RenewRegistration 按同一 owner 重建节点,不重新分配 MachineID。

func (*LocalProvider) Start

func (p *LocalProvider) Start()

Start begins the background goroutine that advances suspect/offline states.

func (*LocalProvider) Watch

func (p *LocalProvider) Watch(_ context.Context, serviceName string, onChange func([]*NodeInfo)) (func(), error)

Watch registers a callback that is fired whenever the node list for the service changes. The cancel function removes the watcher.

type MembershipManager

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

MembershipManager sends heartbeats for a registered node and handles graceful deregistration on shutdown.

func NewMembershipManager

func NewMembershipManager(registry ClusterRegistry, nodeID string, interval time.Duration, options ...MembershipOption) *MembershipManager

NewMembershipManager creates a manager that heartbeats every interval.

func (*MembershipManager) Start

func (m *MembershipManager) Start(ctx context.Context)

Start begins sending heartbeats in a background goroutine.

func (*MembershipManager) Stop

func (m *MembershipManager) Stop(ctx context.Context) error

Stop gracefully deregisters the node and stops heartbeating.

type MembershipOption

type MembershipOption func(*MembershipManager)

MembershipOption 调整成员注销策略。

func WithDeregisterRetry

func WithDeregisterRetry(attempts int, delay time.Duration) MembershipOption

WithDeregisterRetry 配置有界注销重试,主要用于环境调优和确定性测试。

func WithDeregisterTimeout

func WithDeregisterTimeout(timeout time.Duration) MembershipOption

WithDeregisterTimeout limits the shared deregistration operation. Each Stop caller may use a shorter context without cancelling the shared cleanup.

func WithOwnedRegistration added in v1.4.0

func WithOwnedRegistration(node *NodeInfo, owner RegistrationOwner, verify func(context.Context) error, observe func(time.Time, error)) MembershipOption

WithOwnedRegistration 为稳定实例保存完整节点信息、权威检查和就绪观察器。

type MissingKeyPolicy

type MissingKeyPolicy string

MissingKeyPolicy controls what happens when a required shard key is absent.

const (
	MissingKeyPolicyError    MissingKeyPolicy = "error"
	MissingKeyPolicyFallback MissingKeyPolicy = "fallback"
)

type NodeInfo

type NodeInfo struct {
	// StableBootID 与 StableBootEpoch 是内部所有权诊断字段,不参与注册主键。
	StableBootID    string `json:"stable_boot_id,omitempty"`
	StableBootEpoch uint64 `json:"stable_boot_epoch,omitempty"`

	// ID is globally unique, e.g. "<service>-<datacenter>-<machine>-<pid>"
	ID string `json:"id"`

	ServiceName       string            `json:"service_name"`
	ServiceInstanceID string            `json:"service_instance_id,omitempty"`
	DataCenterID      int64             `json:"datacenter_id"`
	MachineID         int64             `json:"machine_id"`
	Address           string            `json:"address"`
	Port              int               `json:"port"`
	GRPCPort          int               `json:"grpc_port,omitempty"`
	Status            NodeStatus        `json:"status"`
	Weight            int               `json:"weight"` // for weighted balancing; default 1
	RegisteredAt      time.Time         `json:"registered_at"`
	LastHeartbeat     time.Time         `json:"last_heartbeat"`
	Metadata          map[string]string `json:"metadata,omitempty"`
}

NodeInfo describes a single service instance in the cluster.

func (*NodeInfo) IsHealthy

func (n *NodeInfo) IsHealthy(timeout time.Duration) bool

IsHealthy returns true when the node is running and has a recent heartbeat.

type NodeStatus

type NodeStatus string

NodeStatus represents the lifecycle state of a cluster node.

const (
	NodeStatusRunning NodeStatus = "running"
	NodeStatusSuspect NodeStatus = "suspect"
	NodeStatusOffline NodeStatus = "offline"
)

type OwnedRegistry added in v1.4.0

type OwnedRegistry interface {
	RegistrationTTL() time.Duration
	AcquireRegistration(context.Context, *NodeInfo, RegistrationOwner) error
	RenewRegistration(context.Context, *NodeInfo, RegistrationOwner) error
	ReleaseRegistration(context.Context, *NodeInfo, RegistrationOwner) error
}

OwnedRegistry 原子比较启动世代并写入/撤销实际发现记录。

type ProviderSwitchShutdown

type ProviderSwitchShutdown interface {
	Shutdown(ctx context.Context, active DiscoveryProvider) error
}

ProviderSwitchShutdown is an optional switcher capability used by service shutdown to abort an active migration and release its pending provider.

type ProviderSwitchTransaction

type ProviderSwitchTransaction interface {
	Promote(ctx context.Context) error
	Finalize(ctx context.Context) error
}

ProviderSwitchTransaction exposes the two phases required by ServiceContext: Promote changes the discovery authority while retaining the old provider; Finalize closes that retired provider after runtime state is synchronized. It is separate from ProviderSwitcher to preserve legacy implementations.

type ProviderSwitcher

type ProviderSwitcher interface {
	// Current returns the active provider.
	Current() DiscoveryProvider

	// Begin starts the migration to the new provider.
	Begin(ctx context.Context, to DiscoveryProvider) error

	// Complete promotes the pending provider and closes the old provider.
	// Callers that need runtime synchronization between those phases may use
	// the optional ProviderSwitchTransaction interface.
	Complete(ctx context.Context) error

	// Rollback aborts and reverts to the old provider.
	Rollback(ctx context.Context) error
}

ProviderSwitcher manages zero-downtime migration between two ClusterRegistry providers (e.g. local → etcd).

func NewClusterSwitcher

func NewClusterSwitcher(initial DiscoveryProvider, serviceName string) ProviderSwitcher

NewClusterSwitcher 创建按服务名隔离的 Provider 切换器。

type RedisProvider

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

RedisProvider 使用带 TTL 的节点键保存服务成员,并通过 Stream 唤醒 Watch。 Watch 同时周期对账,因此不依赖 Redis keyspace notification 才能观察异常退出。

func NewRedisProvider

func NewRedisProvider(addr string, db int, prefix string, ttl time.Duration) (*RedisProvider, error)

NewRedisProvider 创建并验证 Redis 服务发现连接。

func (*RedisProvider) AcquireRegistration added in v1.4.0

func (p *RedisProvider) AcquireRegistration(ctx context.Context, n *NodeInfo, o RegistrationOwner) error

AcquireRegistration 原子发布新世代及节点,不占用 MachineID 槽位。

func (*RedisProvider) Close

func (p *RedisProvider) Close() error

func (*RedisProvider) Deregister

func (p *RedisProvider) Deregister(ctx context.Context, nodeID string) error

func (*RedisProvider) Get

func (p *RedisProvider) Get(ctx context.Context, nodeID string) (*NodeInfo, error)

func (*RedisProvider) Heartbeat

func (p *RedisProvider) Heartbeat(ctx context.Context, nodeID string) error

func (*RedisProvider) List

func (p *RedisProvider) List(ctx context.Context, serviceName string, statuses ...NodeStatus) ([]*NodeInfo, error)

func (*RedisProvider) Name

func (p *RedisProvider) Name() string

func (*RedisProvider) Register

func (p *RedisProvider) Register(ctx context.Context, node *NodeInfo) error

func (*RedisProvider) RegistrationTTL added in v1.4.0

func (p *RedisProvider) RegistrationTTL() time.Duration

RegistrationTTL 返回实际注册有效期,供本地准入保守计时。

func (*RedisProvider) ReleaseRegistration added in v1.4.0

func (p *RedisProvider) ReleaseRegistration(ctx context.Context, n *NodeInfo, o RegistrationOwner) error

ReleaseRegistration 原子保护注销,不删除持久 owner。

func (*RedisProvider) RenewRegistration added in v1.4.0

func (p *RedisProvider) RenewRegistration(ctx context.Context, n *NodeInfo, o RegistrationOwner) error

RenewRegistration 只允许同一持久 owner 续期或恢复已过期节点。

func (*RedisProvider) ReserveLegacyMachineID added in v1.17.0

func (p *RedisProvider) ReserveLegacyMachineID(ctx context.Context, node *NodeInfo) (*LegacyMachineIDLease, error)

ReserveLegacyMachineID reserves exactly the nominated slot without discovery writes.

func (*RedisProvider) Watch

func (p *RedisProvider) Watch(ctx context.Context, serviceName string, onChange func([]*NodeInfo)) (func(), error)

type RegistrationError

type RegistrationError struct {
	Cause       error
	Compensated bool
}

RegistrationError reports whether a provider compensated a registration that became uncertain after the remote entry had already been created. Cause remains available through errors.Is/errors.As via Unwrap.

func (*RegistrationError) Error

func (e *RegistrationError) Error() string

func (*RegistrationError) Unwrap

func (e *RegistrationError) Unwrap() error

type RegistrationOwner added in v1.4.0

type RegistrationOwner struct {
	BootID string
	Epoch  uint64
}

RegistrationOwner 标识内部启动世代,不参与服务发现身份。

type RoundRobinBalancer

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

RoundRobinBalancer distributes calls uniformly across all candidates.

func NewRoundRobinBalancer

func NewRoundRobinBalancer() *RoundRobinBalancer

func (*RoundRobinBalancer) Pick

func (b *RoundRobinBalancer) Pick(_ context.Context, candidates []*NodeInfo, _ BalanceHint) (*NodeInfo, error)

type ServiceShardRouter

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

ServiceShardRouter filters a node candidate list according to configured shard rules.

func NewServiceShardRouter

func NewServiceShardRouter() *ServiceShardRouter

NewServiceShardRouter creates an empty router.

func (*ServiceShardRouter) AddRule

func (r *ServiceShardRouter) AddRule(serviceName string, rule ServiceShardRule)

AddRule registers a shard rule for the given service.

func (*ServiceShardRouter) Filter

func (r *ServiceShardRouter) Filter(serviceName string, candidates []*NodeInfo, params map[string]string) ([]*NodeInfo, error)

Filter applies the shard rule for serviceName (if any) to the candidate list. params are caller-supplied key-value pairs from the request (e.g. payload metadata). Returns the filtered candidate list, which may equal the input if no rule applies.

type ServiceShardRule

type ServiceShardRule struct {
	// MetadataKey is the node metadata key to match against (e.g. "accountTypeid").
	MetadataKey string

	// PayloadKey is the key looked up in the payload's shard parameters.
	PayloadKey string

	// Mode determines the routing algorithm.
	Mode ShardMode

	// MissingKey controls behaviour when PayloadKey is not present in the payload.
	MissingKey MissingKeyPolicy

	// EmptyCandidate controls behaviour when no nodes match the rule.
	EmptyCandidate EmptyCandidatePolicy
}

ServiceShardRule defines a shard-routing rule for a specific service.

type ShardMode

type ShardMode string

ShardMode controls how shard-key routing decisions are made.

const (
	// ShardModeExact requires an exact match between the payload shard key value and a node's metadata.
	ShardModeExact ShardMode = "exact"
	// ShardModeGroup routes to a named group of nodes sharing a common metadata tag.
	ShardModeGroup ShardMode = "group"
	// ShardModeHash distributes using consistent hash over the shard key value.
	ShardModeHash ShardMode = "hash"
	// ShardModeOptional applies the rule when the shard key is present; otherwise uses all candidates.
	ShardModeOptional ShardMode = "optional"
)

type WeightedBalancer

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

WeightedBalancer picks nodes proportionally to their Weight field. Weight=0 nodes are skipped.

func NewWeightedBalancer

func NewWeightedBalancer() *WeightedBalancer

func (*WeightedBalancer) Pick

func (b *WeightedBalancer) Pick(_ context.Context, candidates []*NodeInfo, _ BalanceHint) (*NodeInfo, error)

Jump to

Keyboard shortcuts

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