Documentation
¶
Overview ¶
Package lock provides an abstraction layer for locking mechanisms.
This package supports both local (single-instance) and distributed (multi-instance) locking implementations through a common interface. Local locks use standard sync.Mutex and sync.RWMutex. Distributed locks use Redis with the Redlock algorithm.
Index ¶
- Constants
- func CalculateBackoff(cfg RetryConfig, attempt int) time.Duration
- func RecordLockAcquisition(ctx context.Context, lockType, mode, result string)
- func RecordLockDuration(ctx context.Context, lockType, mode string, duration float64)
- func RecordLockFailure(ctx context.Context, lockType, mode, reason string)
- func RecordLockRetryAttempt(ctx context.Context, lockType string)
- type Locker
- type RWLocker
- type RetryConfig
Constants ¶
const ( // Lock type constants for metrics. LockTypeExclusive = "exclusive" LockTypeRead = "read" LockTypeWrite = "write" // Lock mode constants for metrics. LockModeLocal = "local" LockModeDistributed = "distributed" // Lock result constants for metrics. LockResultSuccess = "success" LockResultFailure = "failure" LockResultContention = "contention" // Lock failure reason constants for metrics. LockFailureTimeout = "timeout" LockFailureRedisError = "redis_error" LockFailureContextCanceled = "context_canceled" LockFailureCircuitBreaker = "circuit_breaker" LockFailureMaxRetries = "max_retries" LockFailureDatabaseError = "database_error" )
const DefaultJitterFactor = 0.5
DefaultJitterFactor is the default proportion of delay to add as random jitter.
Variables ¶
This section is empty.
Functions ¶
func CalculateBackoff ¶ added in v0.7.0
func CalculateBackoff(cfg RetryConfig, attempt int) time.Duration
CalculateBackoff calculates the backoff duration based on retry config and attempt number. The attempt number is 0-indexed (first attempt is 0, first retry is 1).
func RecordLockAcquisition ¶
RecordLockAcquisition records a lock acquisition attempt. lockType should be one of LockType* constants. mode should be one of LockMode* constants. result should be one of LockResult* constants.
func RecordLockDuration ¶
RecordLockDuration records how long a lock was held. lockType should be one of LockType* constants. mode should be one of LockMode* constants. duration should be in seconds.
func RecordLockFailure ¶
RecordLockFailure records a lock failure. lockType should be one of LockType* constants. mode should be one of LockMode* constants. reason should be one of LockFailure* constants.
func RecordLockRetryAttempt ¶
RecordLockRetryAttempt records a lock retry attempt. lockType should be one of LockType* constants.
Types ¶
type Locker ¶
type Locker interface {
// Lock acquires an exclusive lock for the given key with the specified TTL.
//
// For local implementations, the key and ttl parameters are ignored and the
// method behaves like sync.Mutex.Lock().
//
// For distributed implementations (Redis), this method will:
// - Attempt to acquire the lock using the Redlock algorithm
// - Retry with exponential backoff if configured
// - Return an error if the lock cannot be acquired after max retries
//
// The context can be used to cancel lock acquisition attempts.
Lock(ctx context.Context, key string, ttl time.Duration) error
// Unlock releases an exclusive lock for the given key.
//
// For local implementations, the key parameter is ignored and the method
// behaves like sync.Mutex.Unlock().
//
// For distributed implementations, this releases the Redis lock. If unlock
// fails, the lock will eventually expire based on its TTL.
//
// It is safe to call Unlock even if Lock failed, but it may return an error.
Unlock(ctx context.Context, key string) error
// TryLock attempts to acquire an exclusive lock without blocking.
//
// For local implementations, this uses sync.Mutex.TryLock().
//
// For distributed implementations, this attempts to acquire the Redis lock
// with a single attempt (no retries).
//
// Returns:
// - (true, nil) if the lock was acquired
// - (false, nil) if the lock is held by someone else
// - (false, error) if an error occurred
TryLock(ctx context.Context, key string, ttl time.Duration) (bool, error)
}
Locker provides exclusive locking semantics.
Implementations can be local (using sync.Mutex) or distributed (using Redis). The interface is designed to support key-based locking for distributed scenarios while allowing local implementations to ignore the key parameter.
type RWLocker ¶
type RWLocker interface {
Locker
// RLock acquires a shared read lock for the given key with the specified TTL.
//
// For local implementations, the key and ttl parameters are ignored and the
// method behaves like sync.RWMutex.RLock().
//
// For distributed implementations (Redis), multiple readers can acquire the
// lock concurrently, but they must wait for any active writers to finish.
RLock(ctx context.Context, key string, ttl time.Duration) error
// RUnlock releases a shared read lock for the given key.
//
// For local implementations, the key parameter is ignored and the method
// behaves like sync.RWMutex.RUnlock().
RUnlock(ctx context.Context, key string) error
}
RWLocker provides read-write locking semantics.
Multiple readers can hold the lock simultaneously, but writers have exclusive access. This is useful for protecting resources during read-heavy operations while allowing safe cleanup operations.
type RetryConfig ¶ added in v0.7.0
type RetryConfig struct {
// MaxAttempts is the maximum number of attempts to acquire a lock.
MaxAttempts int
// InitialDelay is the initial delay between retry attempts.
InitialDelay time.Duration
// MaxDelay is the maximum delay between retry attempts.
// Exponential backoff will be capped at this value.
MaxDelay time.Duration
// Jitter enables random jitter in retry delays to prevent thundering herd.
Jitter bool
// JitterFactor is the maximum proportion of delay to add as random jitter.
// Only used if Jitter is true. Defaults to DefaultJitterFactor if not set.
JitterFactor float64
}
RetryConfig holds retry configuration for lock acquisition. This is used by the Redis distributed lock implementation.
func DefaultRetryConfig ¶ added in v0.7.0
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns sensible default retry configuration.
func (RetryConfig) GetJitterFactor ¶ added in v0.7.0
func (c RetryConfig) GetJitterFactor() float64
GetJitterFactor returns the JitterFactor if it's set and valid (> 0), otherwise it returns DefaultJitterFactor.