coordination

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 14 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.

README

go-storage-lock-coordination

在 go-storage 的单 key 线性一致 CAS、可靠时间源和租约锁之上提供有限的协调原语。

已实现

  • Semaphore:固定容量 slot 信号量。每个 permit 是独立的 StorageLock,具有独立 slot 和 fencing token;不承诺 FIFO,也没有跨 slot 的全局 token。SemaphoreOptions.PermitTTL > 0 时获得可过期许可:到期由 watcher 主动释放 slot,其他客户端无需等待持有者释放即可抢占——适合"必须在限时内用完许可"的场景。
  • Leader Election:基于单个租约锁的选主。Leadership 提供显式 Renew、Resign、Lost 和 fencing token。
  • OrderedCompositeLock:按 lock ID 字典序逐个获取的组合锁。全部成功后才返回,失败时逆序尽力释放;它不是跨 key 原子事务。
  • OnceTask:同一个任务标识全集群只成功执行一次。执行中持有租约和 fencing token,Complete 后永久拒绝,Abandon 后允许接管且 token 继续递增。
  • Queue:可见性超时队列。Claim 独占一个元素并返回 fencing token,处理方崩溃后租约到期,元素重新可见。
  • DelayedQueue:延迟队列。Push 写入元素并声明延迟,延迟到点前元素隐藏(Claim 返回空),到点后任意客户端可抢占;Ack 后元素成为墓碑不再可见。处理方崩溃后租约到期、元素重新可见。
  • RateLimiter:分布式令牌桶限流器。桶状态由单条记录以 CAS 演进(值放 LockCount、上次补充时间放 LockBeginTime),TryAcquire 原子放行或拒绝,支持整数令牌、突发容量与手动 Refill;不感知调用者身份,只提供次数限流。
  • AtomicLong:分布式原子计数器。基于 CAS 循环的 IncrementAndGet / GetAndAdd / CompareAndSet / Reset,跨节点线性一致,可安全用于库存扣减、发号、统计等场景。

所有新能力都要求底层 Storage 的 CAS 真正线性一致,并使用可靠、单调的时间源。Watch 只能优化等待,不能作为正确性依据。业务资源必须原子校验 fencing token;token 不是锁有效性的持续证明。

明确不实现的语义

当前模型中的 LockInformation 只有单个 owner 和重入计数,不能安全表达参与者集合、幂等 countDown、屏障代际或 broken/reset 状态。因此本模块不提供伪装成完整分布式语义的 CountDownLatch/CyclicBarrier。

本模块也不实现 RedLock。多个独立后端的多数成功无法在网络分区、异步复制、进程暂停、延迟和时钟不确定时证明线性一致 ownership。需要严格全有全无的多 key 锁时,应使用单一协调记录、事务性数据库接口或 etcd/ZooKeeper 等共识租约。

运行测试

go test ./...
go test -race ./...
go vet ./...

Documentation

Overview

Package coordination 提供建立在单 key 线性一致租约锁之上的分布式协调原语。

本包不会把单 OwnerId/LockCount 模型错误地解释为多持有者状态:信号量使用 固定的独立 slot,每个 slot 都是一把独立的 StorageLock。

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCompositeLockIDsEmpty    = errors.New("composite lock ids must not be empty")
	ErrCompositeDuplicateLockID = errors.New("composite lock ids must be unique")
)
View Source
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")
)
View Source
var (
	// ErrTaskAlreadyRan 表示这个任务已经被某个持有者执行过,不能再跑一次。
	ErrTaskAlreadyRan = errors.New("task already ran")
	// ErrTaskBusy 表示另一个持有者正在执行这个任务且租约仍有效。
	ErrTaskBusy = errors.New("task is running")
)
View Source
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")
)
View Source
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")
)
View Source
var (
	// ErrAtomicNamespaceEmpty 表示原子计数器的 namespace 不能为空。
	ErrAtomicNamespaceEmpty = errors.New("atomic counter namespace must not be empty")
)
View Source
var (
	// ErrInvalidDelay 表示延迟必须为正。
	ErrInvalidDelay = errors.New("delay must be greater than zero")
)
View Source
var ErrNoTokens = errors.New("not enough tokens in the bucket")

ErrNoTokens 表示桶内令牌不足,本次请求未被放行。

早先这里复用 storage_lock.ErrLockBusy,导致调用方必须知道"限流内部是用锁记录实现", 而且日志里会显示成"锁被别人占着"——完全误导。限流不是互斥, "现在额度不够"和"资源被占用"必须能区分。

View Source
var ErrQueueEmpty = errors.New("queue is empty")

ErrQueueEmpty 表示队列里没有可见的任务。

Functions

func IsNoTokens

func IsNoTokens(err error) bool

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) AddAndGet

func (c *AtomicLong) AddAndGet(ctx context.Context, delta int64) (int64, error)

AddAndGet 加上 delta 并返回新值。

func (*AtomicLong) CompareAndSet

func (c *AtomicLong) CompareAndSet(ctx context.Context, expect, update int64) (bool, error)

CompareAndSet 仅当当前值等于 expect 时更新为 update,返回是否成功。

func (*AtomicLong) CounterID

func (c *AtomicLong) CounterID() string

CounterID 返回计数器对应的存储记录 ID。

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) GetAndAdd

func (c *AtomicLong) GetAndAdd(ctx context.Context, delta int64) (int64, error)

GetAndAdd 返回旧值并把计数值加上 delta。

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 并返回新值。

func (*AtomicLong) Namespace

func (c *AtomicLong) Namespace() string

Namespace 返回计数器 namespace。

func (*AtomicLong) Reset

func (c *AtomicLong) Reset(ctx context.Context) error

Reset 把计数值归零。

func (*AtomicLong) Set

func (c *AtomicLong) Set(ctx context.Context, value int64) error

Set 无条件把计数值设为 value。

与 CompareAndSet 的区别:Set 不检查当前值,适合"运维手动纠正"。 业务代码里做状态机守卫请用 CompareAndSet——Set 会覆盖掉并发写入。

type CompositeLease

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

CompositeLease 是所有子锁成功后的组合句柄。

func (*CompositeLease) FencingTokens

func (l *CompositeLease) FencingTokens() map[string]storage.Version

FencingTokens 返回每个子锁独立的 token 副本。

func (*CompositeLease) Release

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

Release 按逆序释放全部子锁;返回第一个错误。

func (*CompositeLease) Renew

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

Renew 续租所有子锁;失败后调用方必须停止临界区业务并按 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

Context 返回处理期间的业务上下文,持有权丢失时取消。

func (*DelayedItem) Renew

func (i *DelayedItem) Renew(ctx context.Context) error

Renew 手动延长处理租约。看门狗开启时不需要调用。

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 的结果一一对应。

func (*DelayedQueue) Push

func (q *DelayedQueue) Push(ctx context.Context, id, payload string, delay time.Duration) error

Push 追加一个带延迟的元素。id 在队列内必须唯一,重复返回 storage_lock.ErrLockBusy。

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) Lost

func (l *Leadership) Lost() <-chan struct{}

Lost 在领导权确认丢失或状态不确定时关闭。

func (*Leadership) OwnerID

func (l *Leadership) OwnerID() string

OwnerID 返回内部唯一 session owner。

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 是全集群共享的任务标识。

func (*OnceTask) TryRun

func (t *OnceTask) TryRun(ctx context.Context, owner string) (*TaskRun, error)

TryRun 尝试获取一次执行权,不等待。 已完成返回 ErrTaskAlreadyRan,他人正在执行返回 ErrTaskBusy。

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

func (p *Permit) ExpiresIn(ctx context.Context) (time.Duration, error)

ExpiresIn 返回可过期许可的剩余有效期。 可过期许可(PermitTTL > 0)到期由 watcher 主动释放,之后其他客户端可抢占该 slot; 普通许可由 supervisor 持续续租,返回 0 表示"不会因时间到期而失效"。

func (*Permit) FencingToken

func (p *Permit) FencingToken() storage.Version

FencingToken 返回此 slot 本次持有的 fencing token。

func (*Permit) Lost

func (p *Permit) Lost() <-chan struct{}

Lost 在 permit 确认失效或续租状态不确定时关闭。

func (*Permit) OwnerID

func (p *Permit) OwnerID() string

OwnerID 返回内部唯一 owner。它包含每次 Acquire 的 nonce。

func (*Permit) Release

func (p *Permit) Release(ctx context.Context) error

Release 释放当前 permit。重复调用返回 ErrPermitReleased。

func (*Permit) Renew

func (p *Permit) Renew(ctx context.Context) error

Renew 手动续租。Permit 使用显式 supervisor,因此调用方也可主动续租。

func (*Permit) SlotID

func (p *Permit) SlotID() string

SlotID 返回此 permit 占用的 slot。

func (*Permit) TTL

func (p *Permit) TTL(ctx context.Context) (time.Duration, error)

TTL 返回 permit 剩余租期。

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

func (q *Queue) AckByOwner(ctx context.Context, id, owner string) error

AckByOwner 按 "元素 id + owner" 确认完成,等价于 QueueItem.Ack。

为什么需要它:Claim 与 Ack 常常发生在**不同进程**里(Agent 每次调用都是新进程, 甚至可能由别的 Agent 接手)。只有 QueueItem 的话,调用方必须把整个对象留在内存里, 跨进程就做不到。owner 是租约的凭证,对不上时 UnLock 会拒绝, 因此这不会让任何人"顺手删掉别人的元素"。

func (*Queue) Claim

func (q *Queue) Claim(ctx context.Context, owner string) (*QueueItem, error)

Claim 抢占一个可见元素。没有可见元素时返回 ErrQueueEmpty。

func (*Queue) Peek

func (q *Queue) Peek(ctx context.Context) ([]PendingItem, error)

Peek 列出当前可见(未被任何人有效持有)的元素,只读不抢占。

存在的意义:Agent 是无状态的,每次调用都是新进程。 没有它,调用方只能靠"试一次 Claim"来猜队列里有没有活干, 而 Claim 一旦成功就已经占用了元素——观测不该产生副作用。

func (*Queue) Push

func (q *Queue) Push(ctx context.Context, id, payload string) error

Push 追加一个元素。id 在队列内必须唯一,重复返回 storage_lock.ErrLockBusy。

type QueueItem

type QueueItem struct {
	Queue   string
	ID      string
	Payload string
	Token   storage.Version
	Owner   string
	// contains filtered or unexported fields
}

QueueItem 是一次成功租约到的队列元素。

func (*QueueItem) Ack

func (i *QueueItem) Ack(ctx context.Context) error

Ack 确认元素已处理并释放它的租约。

func (*QueueItem) Context

Context 返回处理期间的业务上下文,持有权丢失时取消。

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) BucketID

func (r *RateLimiter) BucketID() string

BucketID 返回桶对应的存储记录 ID。

func (*RateLimiter) Namespace

func (r *RateLimiter) Namespace() string

Namespace 返回限流器 namespace。

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

func (r *RateLimiter) TryAcquire(ctx context.Context, n int64) (bool, error)

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 创建固定容量信号量。

func (*Semaphore) Acquire

func (s *Semaphore) Acquire(ctx context.Context) (*Permit, error)

Acquire 阻塞等待一个 permit,直到 ctx 取消。

func (*Semaphore) Capacity

func (s *Semaphore) Capacity() int

Capacity 返回固定容量。

func (*Semaphore) Namespace

func (s *Semaphore) Namespace() string

Namespace 返回信号量 namespace。

func (*Semaphore) TryAcquire

func (s *Semaphore) TryAcquire(ctx context.Context) (*Permit, error)

TryAcquire 只扫描一次 slot,不等待其他 permit 释放。

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) Abandon

func (r *TaskRun) Abandon(ctx context.Context) error

Abandon 放弃本次执行,让其他实例可以重新抢。任务没有被标记完成。

func (*TaskRun) Complete

func (r *TaskRun) Complete(ctx context.Context) error

Complete 标记任务已完成。完成后任何实例再抢都会得到 ErrTaskAlreadyRan。

顺序至关重要:**先写 done 标记,再释放租约**。

反过来(先 UnLock 再写标记)会开一个真实存在的致命窗口:

进程 A: UnLock 成功 ────────────────→ 写 done 标记
进程 B:          ← TryRun 成功(记录已空闲)
进程 C:                       ← TryRun 成功(记录仍空闲)

在这几毫秒里,多个进程都能抢到同一个"一次性任务",违背了 once 的全部意义。 实测 12 进程并发时稳定复现 3 个 claimed。

先写标记则不会:标记没写成功之前租约一直被 A 持有,B/C 只能拿到 busy; 标记写完之后,后来的 TryRun 一律得到 ErrTaskAlreadyRan。 崩溃兜底也完好:A 若在写标记前崩溃,租约到期后 B 可以接管重试—— 这正是"至少执行一次、完成才置标记"的语义。

func (*TaskRun) Context

Context 返回在持有权丢失时取消的上下文。取消不能追回已发出的写入。

func (*TaskRun) Renew

func (r *TaskRun) Renew(ctx context.Context) error

Renew 手动延长执行租约。看门狗开启时不需要调用。

func (*TaskRun) Token

func (r *TaskRun) Token() storage.Version

Token 返回本次执行的 fencing token。业务写入必须校验它。

Jump to

Keyboard shortcuts

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