Documentation
¶
Index ¶
- Constants
- Variables
- func ResetDefaultKit()
- func SetDefaultKit(kit Kit)
- func SnowflakeStartTime() time.Time
- func SubscribeLeaderChanged(handler LeaderChangedHandler) error
- type Action
- type Atomic
- type DistributedMutex
- type ElectionController
- type ElectionOption
- type EventLeaderChanged
- type IDGenerator
- type Kit
- type LeaderChangedEvent
- type LeaderChangedHandler
- type LockOption
- type LockOptionOp
- type MutexFactory
- type NumberAllocator
- type SnowflakeIDGenerator
Constants ¶
const ( // ErrCodeDKitInvalidOption indicates invalid DKit options or configuration. ErrCodeDKitInvalidOption = 20100 // ErrCodeDKitLockNotAcquired indicates that a non-blocking lock attempt did not acquire the lock. ErrCodeDKitLockNotAcquired = 20101 // ErrCodeDKitAlreadyUnlocked indicates that the lock has already been released or expired. ErrCodeDKitAlreadyUnlocked = 20102 // ErrCodeDKitElectionNotEnabled indicates that election APIs are used before election is enabled. ErrCodeDKitElectionNotEnabled = 20103 // ErrCodeDKitNoAvailableNumber indicates that the bounded number range is temporarily exhausted. ErrCodeDKitNoAvailableNumber = 20104 ErrCodeDKitBackendUnavailable = 10100 // ErrCodeDKitDefaultKitNotConfigured indicates that the provider-owned default Kit has not been initialized. ErrCodeDKitDefaultKitNotConfigured = 10101 )
const DefaultLockSpinInterval = 500 * time.Millisecond
DefaultLockSpinInterval is the default interval used by blocking lock retries.
const DefaultLockTTL = 30 * time.Second
DefaultLockTTL is the default lease duration used by lock helpers.
const TopicLeaderChanged = "dkit.leader.changed"
TopicLeaderChanged is the in-memory event topic for leader-state transitions.
Variables ¶
var ErrAlreadyUnlocked = datax.NewError(ErrCodeDKitAlreadyUnlocked, "dkit: already unlocked", nil)
ErrAlreadyUnlocked indicates that the lock has already been released or expired.
ErrBackendUnavailable indicates that the underlying coordination backend is unavailable.
var ErrDefaultKitNotConfigured = datax.NewError(ErrCodeDKitDefaultKitNotConfigured, "dkit: default kit not configured", nil)
ErrDefaultKitNotConfigured indicates that the provider-owned default Kit has not been initialized.
var ErrElectionNotEnabled = datax.NewError(ErrCodeDKitElectionNotEnabled, "dkit: election not enabled", nil)
ErrElectionNotEnabled indicates that election or heartbeat APIs are used before election is enabled.
var ErrInvalidOption = datax.NewError(ErrCodeDKitInvalidOption, "dkit: invalid option", nil)
ErrInvalidOption indicates that a DKit option is invalid.
var ErrLockNotAcquired = datax.NewError(ErrCodeDKitLockNotAcquired, "dkit: lock not acquired", nil)
ErrLockNotAcquired indicates that a non-blocking lock attempt did not acquire the lock.
var ErrNoAvailableNumber = datax.NewError(ErrCodeDKitNoAvailableNumber, "dkit: no available number", nil)
ErrNoAvailableNumber indicates that the bounded number range is temporarily exhausted.
Functions ¶
func ResetDefaultKit ¶
func ResetDefaultKit()
ResetDefaultKit clears the provider-owned default Kit.
ResetDefaultKit does not close the previous Kit; the bootstrap code that owns the instance remains responsible for closing it.
func SetDefaultKit ¶
func SetDefaultKit(kit Kit)
SetDefaultKit replaces the provider-owned default Kit.
It is intended for application bootstrap and tests that need controlled replacement. Passing nil clears the default Kit.
func SnowflakeStartTime ¶
SnowflakeStartTime returns the fixed epoch shared by dev-ofa Sonyflake generators.
The date is intentionally earlier than Sonyflake's default 2014-09-01 epoch so newly generated decimal IDs are already 19 digits in 2026-era systems. This avoids a future 18-to-19-digit boundary where plain decimal string ordering would temporarily diverge from numeric ordering. Treat this value as a cross-language compatibility constant; changing it after launch can break ID ordering assumptions and may risk collisions with generators using another epoch.
func SubscribeLeaderChanged ¶
func SubscribeLeaderChanged(handler LeaderChangedHandler) error
SubscribeLeaderChanged subscribes an in-memory handler for leader-state transitions.
Types ¶
type Atomic ¶
type Atomic interface {
NumberAllocator
MutexFactory
ElectionController
// Close releases resources held by the backend implementation.
Close() error
}
Atomic groups backend-backed distributed primitives.
type DistributedMutex ¶
type DistributedMutex interface {
// Lock waits until the lock is acquired, the context is canceled, or MaxWaitTime is reached.
Lock(ctx context.Context, ops ...LockOptionOp) error
// TryLock attempts to acquire the lock once and returns false when it is held by another owner.
TryLock(ctx context.Context, ops ...LockOptionOp) (bool, error)
// Unlock releases the lock owned by the current holder.
Unlock(ctx context.Context) error
// ExistLock reports whether a non-expired lock currently exists.
ExistLock(ctx context.Context) (bool, error)
}
DistributedMutex protects a distributed resource identified by a resource key.
type ElectionController ¶
type ElectionController interface {
// EnableElection enables leader election and optional heartbeat behavior.
EnableElection(opt *ElectionOption) error
// NodeKey returns the current node identity.
NodeKey() string
// IsLeader reports whether the current node is the leader.
IsLeader() bool
// AliveNodes returns non-expired heartbeat nodes when heartbeat is enabled.
AliveNodes() ([]string, error)
// IsAlive reports whether nodeKey has a non-expired heartbeat.
IsAlive(nodeKey string) (bool, error)
}
ElectionController exposes leader election and heartbeat operations.
type ElectionOption ¶
type ElectionOption struct {
// NodeKey uniquely identifies the current node in the election domain.
NodeKey string
// KeepHeartbeat enables heartbeat reporting for the current node.
KeepHeartbeat bool
// UnhealthyTime defines the leader or heartbeat lease duration.
UnhealthyTime time.Duration
// Timeout defines the timeout for one backend operation.
Timeout time.Duration
// IsolationKey separates independent election domains.
IsolationKey string
// CanElect is called before campaigning; returning false prevents this node from becoming leader.
CanElect func() bool
}
ElectionOption configures leader election and optional heartbeat behavior.
type EventLeaderChanged ¶
type EventLeaderChanged = LeaderChangedEvent
EventLeaderChanged is kept as a compatibility alias for go-dev/dkit users.
type IDGenerator ¶
type IDGenerator interface {
// NextID returns a globally unique ID.
NextID(ctx context.Context) (uint64, error)
// NextIDString returns a globally unique ID formatted as a string.
NextIDString(ctx context.Context) (string, error)
}
IDGenerator generates globally unique IDs.
type Kit ¶
type Kit interface {
Atomic
IDGenerator
SnowflakeIDGenerator
// MutexTryDo tries to acquire mutexKey with the backend default TTL before executing action.
MutexTryDo(mutexKey string, action Action) (bool, error)
// MutexCtxTryDo tries to acquire mutexKey in ctx before executing action.
MutexCtxTryDo(ctx context.Context, mutexKey string, action Action) (bool, error)
// MutexDo acquires mutexKey with the backend default TTL before executing action.
MutexDo(mutexKey string, action Action) error
// MutexCtxDo acquires mutexKey in ctx before executing action.
MutexCtxDo(ctx context.Context, mutexKey string, action Action) error
}
Kit combines backend-backed primitives with ID generation and lock helpers.
func DefaultKit ¶
func DefaultKit() Kit
DefaultKit returns the provider-owned default Kit.
DefaultKit panics when the default Kit has not been initialized. Applications should call SetDefaultKit or InitDefaultKit during bootstrap before business code attempts to discover DKit.
func InitDefaultKit ¶
InitDefaultKit initializes and registers the provider-owned default Kit.
The default Kit is only replaced after initialization succeeds. Callers that need explicit ownership can continue using NewDefaultKitWithContext directly.
func NewDefaultKit ¶
NewDefaultKit creates a Kit using context.Background for machine ID allocation.
type LeaderChangedEvent ¶
type LeaderChangedEvent struct {
// IsLeader reports whether the current node became leader.
IsLeader bool
// NodeKey is the stable identity of the node whose leader state changed.
NodeKey string
// IsolationKey identifies the election domain.
IsolationKey string
}
LeaderChangedEvent describes a local leader-state transition.
func (LeaderChangedEvent) Topic ¶
func (e LeaderChangedEvent) Topic() []string
Topic returns the in-memory event topic for leader-state transitions.
type LeaderChangedHandler ¶
type LeaderChangedHandler func(event LeaderChangedEvent)
LeaderChangedHandler handles leader-state transition notifications.
type LockOption ¶
type LockOption struct {
// TTL is the lock lease duration.
TTL time.Duration
// ReentrantIdentity allows the same logical holder to re-enter a supported lock implementation.
ReentrantIdentity string
// SpinInterval controls the retry interval used by blocking Lock implementations.
SpinInterval time.Duration
// MaxWaitTime limits how long Lock may wait for the lock.
MaxWaitTime time.Duration
}
LockOption configures lock acquisition behavior.
func NewLockOption ¶
func NewLockOption(defaultTTL time.Duration, ops []LockOptionOp) *LockOption
NewLockOption builds lock options from a default TTL and functional options.
type LockOptionOp ¶
type LockOptionOp func(option *LockOption)
LockOptionOp mutates LockOption.
func LockTTL ¶
func LockTTL(d time.Duration) LockOptionOp
LockTTL configures the lock lease duration.
func LockWithMaxWait ¶
func LockWithMaxWait(waitTime time.Duration) LockOptionOp
LockWithMaxWait configures the maximum wait duration for blocking Lock.
func LockWithSpinInterval ¶
func LockWithSpinInterval(interval time.Duration) LockOptionOp
LockWithSpinInterval configures the retry interval for blocking Lock.
func Reentrant ¶
func Reentrant(identity string) LockOptionOp
Reentrant configures the reentrant holder identity.
type MutexFactory ¶
type MutexFactory interface {
// NewMutex creates a distributed mutex bound to key.
NewMutex(key string) DistributedMutex
// GetMutexDefaultTTL returns the default lock TTL used by helper methods.
GetMutexDefaultTTL() time.Duration
}
MutexFactory creates distributed mutexes and exposes their default TTL.
type NumberAllocator ¶
type NumberAllocator interface {
// GetUniqueRandomNumber returns a unique number in [0, max).
GetUniqueRandomNumber(ctx context.Context, max int) (int, error)
}
NumberAllocator allocates a unique number from a bounded range.
type SnowflakeIDGenerator ¶
type SnowflakeIDGenerator interface {
// GetID returns a globally unique ID and panics when generation fails.
GetID() uint64
// GetSnowflakeID returns a globally unique SnowflakeID and panics when generation fails.
GetSnowflakeID() model.SnowflakeID
// GetIDString returns a globally unique string ID and panics when generation fails.
GetIDString() string
}
SnowflakeIDGenerator generates globally unique snowflake IDs.