Documentation
¶
Overview ¶
Package coordination 提供建立在单 key 线性一致租约锁之上的分布式协调原语。
本包不会把单 OwnerId/LockCount 模型错误地解释为多持有者状态:信号量使用 固定的独立 slot,每个 slot 都是一把独立的 StorageLock。
Index ¶
- Variables
- func IsNoTokens(err error) bool
- type AtomicLong
- func (c *AtomicLong) AddAndGet(ctx context.Context, delta int64) (int64, error)
- func (c *AtomicLong) CompareAndSet(ctx context.Context, expect, update int64) (bool, error)
- func (c *AtomicLong) CounterID() string
- func (c *AtomicLong) DecrementAndGet(ctx context.Context) (int64, error)
- func (c *AtomicLong) Get(ctx context.Context) (int64, error)
- func (c *AtomicLong) GetAndAdd(ctx context.Context, delta int64) (int64, error)
- func (c *AtomicLong) GetAndDecrement(ctx context.Context) (int64, error)
- func (c *AtomicLong) GetAndIncrement(ctx context.Context) (int64, error)
- func (c *AtomicLong) IncrementAndGet(ctx context.Context) (int64, error)
- func (c *AtomicLong) Namespace() string
- func (c *AtomicLong) Reset(ctx context.Context) error
- func (c *AtomicLong) Set(ctx context.Context, value int64) error
- type CompositeLease
- type DelayedItem
- type DelayedQueue
- func (q *DelayedQueue) AckByOwner(ctx context.Context, id, owner string) error
- func (q *DelayedQueue) Claim(ctx context.Context, owner string) (*DelayedItem, error)
- func (q *DelayedQueue) Peek(ctx context.Context) ([]PendingItem, error)
- func (q *DelayedQueue) Push(ctx context.Context, id, payload string, delay time.Duration) error
- type LeaderElector
- type LeaderOptions
- type Leadership
- type LeadershipStatus
- type OnceTask
- type OrderedCompositeLock
- type PendingItem
- type Permit
- func (p *Permit) ExpiresIn(ctx context.Context) (time.Duration, error)
- func (p *Permit) FencingToken() storage.Version
- func (p *Permit) Lost() <-chan struct{}
- func (p *Permit) OwnerID() string
- func (p *Permit) Release(ctx context.Context) error
- func (p *Permit) Renew(ctx context.Context) error
- func (p *Permit) SlotID() string
- func (p *Permit) TTL(ctx context.Context) (time.Duration, error)
- type Queue
- type QueueItem
- type RateLimiter
- func (r *RateLimiter) Allow(ctx context.Context) bool
- func (r *RateLimiter) BucketID() string
- func (r *RateLimiter) Namespace() string
- func (r *RateLimiter) Refill(ctx context.Context, n int64) error
- func (r *RateLimiter) Tokens(ctx context.Context) (int64, error)
- func (r *RateLimiter) TryAcquire(ctx context.Context, n int64) (bool, error)
- type RateLimiterOptions
- type Semaphore
- type SemaphoreOptions
- type TaskRun
Constants ¶
This section is empty.
Variables ¶
var ( ErrCompositeLockIDsEmpty = errors.New("composite lock ids must not be empty") ErrCompositeDuplicateLockID = errors.New("composite lock ids must be unique") )
var ( ErrInvalidLeaderLockID = errors.New("leader lock id must not be empty") ErrLeadershipLost = errors.New("leadership lost") ErrLeadershipUncertain = errors.New("leadership state is uncertain") ErrLeadershipResigned = errors.New("leadership already resigned") )
var ( // ErrTaskAlreadyRan 表示这个任务已经被某个持有者执行过,不能再跑一次。 ErrTaskAlreadyRan = errors.New("task already ran") // ErrTaskBusy 表示另一个持有者正在执行这个任务且租约仍有效。 ErrTaskBusy = errors.New("task is running") )
var ( // ErrInvalidRateLimit 表示限流速率必须大于零。 ErrInvalidRateLimit = errors.New("rate must be greater than zero") // ErrInvalidRateNamespace 表示限流器 namespace 不能为空。 ErrInvalidRateNamespace = errors.New("rate limiter namespace must not be empty") // ErrTokenBurstCapacity 表示令牌桶容量不能小于每秒补充速率。 ErrTokenBurstCapacity = errors.New("burst capacity must be >= tokens per second") )
var ( ErrInvalidSemaphoreCapacity = errors.New("semaphore capacity must be greater than zero") ErrInvalidSemaphoreNamespace = errors.New("semaphore namespace must not be empty") ErrPermitReleased = errors.New("semaphore permit already released") ErrPermitLost = errors.New("semaphore permit lease lost") ErrPermitUncertain = errors.New("semaphore permit state is uncertain") ErrNoPermitAvailable = errors.New("no semaphore permit available") )
var ( // ErrAtomicNamespaceEmpty 表示原子计数器的 namespace 不能为空。 ErrAtomicNamespaceEmpty = errors.New("atomic counter namespace must not be empty") )
var ( // ErrInvalidDelay 表示延迟必须为正。 ErrInvalidDelay = errors.New("delay must be greater than zero") )
var ErrNoTokens = errors.New("not enough tokens in the bucket")
ErrNoTokens 表示桶内令牌不足,本次请求未被放行。
早先这里复用 storage_lock.ErrLockBusy,导致调用方必须知道"限流内部是用锁记录实现", 而且日志里会显示成"锁被别人占着"——完全误导。限流不是互斥, "现在额度不够"和"资源被占用"必须能区分。
var ErrQueueEmpty = errors.New("queue is empty")
ErrQueueEmpty 表示队列里没有可见的任务。
Functions ¶
func IsNoTokens ¶
IsNoTokens 判断错误是否表示"令牌不足"。
同时识别旧的 ErrLockBusy:升级前调用方把"额度不够"当 ErrLockBusy 处理, 只要还可能有旧版本客户端 / 旧错误路径,就不能让它们的判断突然失效。
Types ¶
type AtomicLong ¶
type AtomicLong struct {
// contains filtered or unexported fields
}
AtomicLong 是分布式原子计数器。
计数由一条 StorageLock 记录承载:值放在 LockCount 字段(int64),版本号 承载乐观锁,LockBeginTime 记录最近一次更新时刻。所有读写操作都是基于 CreateWithVersion / UpdateWithVersion 的 CAS 循环,跨节点线性一致, 可安全用于库存扣减、发号、统计等场景。
func NewAtomicLong ¶
func NewAtomicLong(s storage.Storage, namespace string) (*AtomicLong, error)
NewAtomicLong 创建分布式原子计数器。namespace 是全集群共享的计数名。
func (*AtomicLong) CompareAndSet ¶
CompareAndSet 仅当当前值等于 expect 时更新为 update,返回是否成功。
func (*AtomicLong) DecrementAndGet ¶
func (c *AtomicLong) DecrementAndGet(ctx context.Context) (int64, error)
DecrementAndGet 自减 1 并返回新值。
func (*AtomicLong) Get ¶
func (c *AtomicLong) Get(ctx context.Context) (int64, error)
Get 返回当前计数值。从未写入时返回 0。
func (*AtomicLong) GetAndDecrement ¶
func (c *AtomicLong) GetAndDecrement(ctx context.Context) (int64, error)
GetAndDecrement 返回旧值并把计数值 -1。
func (*AtomicLong) GetAndIncrement ¶
func (c *AtomicLong) GetAndIncrement(ctx context.Context) (int64, error)
GetAndIncrement 返回旧值并把计数值 +1。
func (*AtomicLong) IncrementAndGet ¶
func (c *AtomicLong) IncrementAndGet(ctx context.Context) (int64, error)
IncrementAndGet 自增 1 并返回新值。
type CompositeLease ¶
type CompositeLease struct {
// contains filtered or unexported fields
}
CompositeLease 是所有子锁成功后的组合句柄。
func (*CompositeLease) FencingTokens ¶
func (l *CompositeLease) FencingTokens() map[string]storage.Version
FencingTokens 返回每个子锁独立的 token 副本。
type DelayedItem ¶
type DelayedItem struct {
Queue string
ID string
Payload string
ReadyAt time.Time
Token storage.Version
Owner string
// contains filtered or unexported fields
}
DelayedItem 是一次成功抢占到的、已到可见时间的延迟元素。
func (*DelayedItem) Ack ¶
func (i *DelayedItem) Ack(ctx context.Context) error
Ack 确认元素已处理并释放它的租约;释放后元素成为墓碑,不再可见。
func (*DelayedItem) Context ¶
func (i *DelayedItem) Context(ctx context.Context) (context.Context, context.CancelFunc)
Context 返回处理期间的业务上下文,持有权丢失时取消。
type DelayedQueue ¶
type DelayedQueue struct {
// contains filtered or unexported fields
}
DelayedQueue 是分布式延迟队列。
Push 写入一条独立租约记录,租约时长等于延迟;延迟未到之前元素保持"隐藏" (LockCount=1 且租约未过期),Claim 会跳过。延迟到点后租约自然过期, 任何客户端都可以抢占该元素,无需持有者主动释放。Ack 后记录变为墓碑 (LockCount=0),不再可见。
元素到点后没有显式"激活"步骤:到期即重可见,由 Claim 的抢占路径完成。
func NewDelayedQueue ¶
func NewDelayedQueue(s storage.Storage, name string, options storage_lock.StorageLockOptions) (*DelayedQueue, error)
NewDelayedQueue 创建延迟队列。name 是全集群共享的队列名。
func (*DelayedQueue) AckByOwner ¶
func (q *DelayedQueue) AckByOwner(ctx context.Context, id, owner string) error
AckByOwner 按 "元素 id + owner" 确认完成,等价于 DelayedItem.Ack。
Claim 与 Ack 通常发生在不同进程里(Agent 每次调用都是新进程), 只有 DelayedItem 的话调用方必须把对象留在内存里,跨进程做不到。 owner 对不上时底层 UnLock 会拒绝,不会误删别人的元素。
func (*DelayedQueue) Claim ¶
func (q *DelayedQueue) Claim(ctx context.Context, owner string) (*DelayedItem, error)
Claim 抢占一个已到可见时间的元素。没有可领元素时返回 ErrQueueEmpty。 抢占后元素由看门狗续租,处理方崩溃后租约到期、元素重新可见。
func (*DelayedQueue) Peek ¶
func (q *DelayedQueue) Peek(ctx context.Context) ([]PendingItem, error)
Peek 列出当前可见(延迟已到且未被领走)的元素,只读不抢占。 返回值与列表快照一致,不保证与随后 Claim 的结果一一对应。
type LeaderElector ¶
type LeaderElector struct {
// contains filtered or unexported fields
}
LeaderElector 在一把线性一致租约锁上提供 leader campaign。
func NewLeaderElector ¶
func NewLeaderElector(s storage.Storage, lockID string, options LeaderOptions) (*LeaderElector, error)
NewLeaderElector 创建选主器。
func (*LeaderElector) Campaign ¶
func (e *LeaderElector) Campaign(ctx context.Context) (*Leadership, error)
Campaign 等待直到成为 leader 或 ctx 取消。
func (*LeaderElector) TryCampaign ¶
func (e *LeaderElector) TryCampaign(ctx context.Context) (*Leadership, error)
type LeaderOptions ¶
type LeaderOptions struct {
LockOptions storage_lock.StorageLockOptions
OwnerID string
}
LeaderOptions 配置租约选主。OwnerID 为空时由本包生成唯一 session owner。
type Leadership ¶
type Leadership struct {
// contains filtered or unexported fields
}
Leadership 是一次选主 session 的句柄。
func (*Leadership) FencingToken ¶
func (l *Leadership) FencingToken() storage.Version
FencingToken 返回本次领导权的 fencing token。
func (*Leadership) Renew ¶
func (l *Leadership) Renew(ctx context.Context) error
Renew 手动续租;任何不确定错误都 fail-closed。
func (*Leadership) Resign ¶
func (l *Leadership) Resign(ctx context.Context) error
Resign 使用 owner/CAS 语义释放并保留墓碑版本。
func (*Leadership) Status ¶
func (l *Leadership) Status() LeadershipStatus
type LeadershipStatus ¶
type LeadershipStatus string
Status 表示当前句柄状态。
const ( LeadershipActive LeadershipStatus = "active" LeadershipLost LeadershipStatus = "lost" LeadershipUncertain LeadershipStatus = "uncertain" LeadershipResigned LeadershipStatus = "resigned" )
type OnceTask ¶
type OnceTask struct {
// contains filtered or unexported fields
}
OnceTask 保证同一个 taskID 在全集群只成功执行一次。 执行中的租约过期后允许另一个实例接管;完成后永久拒绝。
func NewOnceTask ¶
func NewOnceTask(s storage.Storage, taskID string, options storage_lock.StorageLockOptions) (*OnceTask, error)
NewOnceTask 创建单次任务。taskID 是全集群共享的任务标识。
type OrderedCompositeLock ¶
type OrderedCompositeLock struct {
// contains filtered or unexported fields
}
OrderedCompositeLock 是受限的组合锁:逐个获取独立锁,全部成功后才返回。 它不是跨 key 原子锁,也不是 RedLock;返回的 fencing token 按 lock ID 分别计算。
func NewOrderedCompositeLock ¶
func NewOrderedCompositeLock(s storage.Storage, lockIDs []string, options storage_lock.StorageLockOptions) (*OrderedCompositeLock, error)
NewOrderedCompositeLock 创建按字典序获取的组合锁。
func (*OrderedCompositeLock) Lock ¶
func (c *OrderedCompositeLock) Lock(ctx context.Context, ownerID string) (*CompositeLease, error)
Lock 获取所有子锁;任意失败时按逆序释放已获取的子锁。
type PendingItem ¶
type PendingItem struct {
ID string `json:"id"`
Payload string `json:"payload,omitempty"`
ReadyAt time.Time `json:"ready_at,omitzero"`
Held bool `json:"held"`
}
PendingItem 是 Peek 返回的队列观测条目。 Queue 与 DelayedQueue 共用这个类型:Queue 不使用 ReadyAt(其元素没有延迟概念)。
type Permit ¶
type Permit struct {
// contains filtered or unexported fields
}
Permit 是绑定到具体 slot 的不可转移 permit。
func (*Permit) ExpiresIn ¶
ExpiresIn 返回可过期许可的剩余有效期。 可过期许可(PermitTTL > 0)到期由 watcher 主动释放,之后其他客户端可抢占该 slot; 普通许可由 supervisor 持续续租,返回 0 表示"不会因时间到期而失效"。
func (*Permit) FencingToken ¶
FencingToken 返回此 slot 本次持有的 fencing token。
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue 是可见性超时队列。 Push 写入一条独立租约记录;Claim 在租约过期或无人持有时抢占,处理期间由看门狗续租。 处理方崩溃后租约到期,元素自动重新可见。
func NewQueue ¶
func NewQueue(s storage.Storage, name string, options storage_lock.StorageLockOptions) (*Queue, error)
NewQueue 创建队列。name 是全集群共享的队列名。
func (*Queue) AckByOwner ¶
AckByOwner 按 "元素 id + owner" 确认完成,等价于 QueueItem.Ack。
为什么需要它:Claim 与 Ack 常常发生在**不同进程**里(Agent 每次调用都是新进程, 甚至可能由别的 Agent 接手)。只有 QueueItem 的话,调用方必须把整个对象留在内存里, 跨进程就做不到。owner 是租约的凭证,对不上时 UnLock 会拒绝, 因此这不会让任何人"顺手删掉别人的元素"。
type QueueItem ¶
type QueueItem struct {
Queue string
ID string
Payload string
Token storage.Version
Owner string
// contains filtered or unexported fields
}
QueueItem 是一次成功租约到的队列元素。
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter 是分布式令牌桶限流器。
桶状态由一条 StorageLock 记录承载,直接使用底层 Storage 的原子 CAS (CreateWithVersion / UpdateWithVersion)演进,不经过 StorageLock 的 锁语义——限流不是互斥。令牌数与上次补充时间编码在 LockCount / LockBeginTime 字段里,版本号承载乐观锁,天然线性一致。
func NewRateLimiter ¶
func NewRateLimiter(s storage.Storage, namespace string, options RateLimiterOptions) (*RateLimiter, error)
NewRateLimiter 创建分布式令牌桶限流器。namespace 是全集群共享的桶名。
func (*RateLimiter) Allow ¶
func (r *RateLimiter) Allow(ctx context.Context) bool
Allow 等价于 TryAcquire(ctx, 1),只报告是否放行。
func (*RateLimiter) Refill ¶
func (r *RateLimiter) Refill(ctx context.Context, n int64) error
Refill 手动向桶里补充 n 个令牌(不超容量上限)。常与 TokensPerSecond=0 的纯手动模式配合。
func (*RateLimiter) Tokens ¶
func (r *RateLimiter) Tokens(ctx context.Context) (int64, error)
Tokens 返回当前桶内可用令牌数(含按时间已补充的部分),只读,不消耗。
func (*RateLimiter) TryAcquire ¶
TryAcquire 尝试一次性消耗 n 个令牌(n 必须为正)。令牌不足时返回 (false, ErrLockBusy), 调用方可以据此决定是否等待后重试。CAS 冲突时内部自动重试。
type RateLimiterOptions ¶
type RateLimiterOptions struct {
// TokensPerSecond 每秒补充的令牌数。必须为正整数。
TokensPerSecond int64
// BurstCapacity 令牌桶最大容量。为 0 时默认等于 TokensPerSecond。
BurstCapacity int64
// OwnerID 是业务 owner 的可选标识(仅用于事件链路)。
OwnerID string
}
RateLimiterOptions 配置分布式令牌桶限流器。
type Semaphore ¶
type Semaphore struct {
// contains filtered or unexported fields
}
Semaphore 是固定容量的分布式信号量。 capacity 是部署契约:同一 namespace 的所有客户端必须使用相同容量。 它不承诺 FIFO 公平性,也不提供跨所有 slot 的全局 fencing token。
func NewSemaphore ¶
func NewSemaphore(s storage.Storage, namespace string, capacity int, options SemaphoreOptions) (*Semaphore, error)
NewSemaphore 创建固定容量信号量。
type SemaphoreOptions ¶
type SemaphoreOptions struct {
LockOptions storage_lock.StorageLockOptions
// OwnerID 是业务 owner 的可选标识。每次 Acquire 都会在它后面追加唯一 nonce。
OwnerID string
// PermitTTL 是许可的最大持有时间。为 0 时许可由 supervisor 持续续租,
// 持有者不释放就一直占着(现有行为)。大于 0 时许可到期自动过期:
// 到期后持有者持有的 slot 被主动释放,其他客户端可立即抢占,无需等待
// 持有者主动释放——适合"必须在限时内用完许可"的场景。
PermitTTL time.Duration
}
SemaphoreOptions 配置固定 slot 信号量。
type TaskRun ¶
type TaskRun struct {
TaskID string
Owner string
Fence storage.Version
// contains filtered or unexported fields
}
TaskRun 是一次成功抢到的单次执行权。
func (*TaskRun) Complete ¶
Complete 标记任务已完成。完成后任何实例再抢都会得到 ErrTaskAlreadyRan。
顺序至关重要:**先写 done 标记,再释放租约**。
反过来(先 UnLock 再写标记)会开一个真实存在的致命窗口:
进程 A: UnLock 成功 ────────────────→ 写 done 标记 进程 B: ← TryRun 成功(记录已空闲) 进程 C: ← TryRun 成功(记录仍空闲)
在这几毫秒里,多个进程都能抢到同一个"一次性任务",违背了 once 的全部意义。 实测 12 进程并发时稳定复现 3 个 claimed。
先写标记则不会:标记没写成功之前租约一直被 A 持有,B/C 只能拿到 busy; 标记写完之后,后来的 TryRun 一律得到 ErrTaskAlreadyRan。 崩溃兜底也完好:A 若在写标记前崩溃,租约到期后 B 可以接管重试—— 这正是"至少执行一次、完成才置标记"的语义。