lock

package
v1.8.2 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// DefaultLockTime is the default lock expiration time (15 seconds)
	DefaultLockTime = 15 * time.Second

	// DefaultOperationTimeout is the default timeout for lock operations (5 seconds)
	DefaultOperationTimeout = 5 * time.Second
)

Variables

View Source
var (
	// ErrLockNotHeld indicates the lock was not held by this locker instance.
	ErrLockNotHeld = errors.New("lock not held")
	// ErrLockValueMismatch indicates the lock value doesn't match or lock expired.
	ErrLockValueMismatch = errors.New("lock value mismatch or lock has expired")
	// ErrLockValueType indicates the stored lock value has an unexpected type.
	ErrLockValueType = errors.New("lock value type error")
	// ErrLockExpired indicates this locker's conservative lease elapsed before
	// an acquisition/extension reply arrived or before Unlock was called, so
	// the lock may already be held by someone else. A late Unlock reports it
	// without touching Redis, precisely so it cannot delete a later holder's
	// key.
	ErrLockExpired = errors.New("lock lease expired before release")
	// ErrRedisUnavailable indicates a Redis operation failed. A HybridLocker
	// returns it rather than silently degrading to a process-local lock, which
	// would drop mutual exclusion across instances at the moment it matters.
	ErrRedisUnavailable = errors.New("redis unavailable")
	// ErrLockTrackingLimit indicates that the legacy key-only API cannot safely
	// remember another distinct key. Old routing records cannot be discarded:
	// a late Unlock would otherwise be able to consume a later holder's token.
	// Acquire returns a token-bearing Handle and has no such process-local cap.
	ErrLockTrackingLimit = errors.New("legacy lock tracking limit reached")
)

Functions

This section is empty.

Types

type Handle added in v1.6.0

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

Handle is an acquired lock. It carries the token of the acquisition that produced it, so releasing it can never affect a lock somebody else acquired after this one's lease expired.

This is the API to prefer over Locker.Lock/Unlock. Those identify a lock by key alone and keep the token in a process-wide map, which cannot distinguish two acquisitions of the same key.

func (*Handle) ExpiresAt added in v1.6.0

func (h *Handle) ExpiresAt() time.Time

ExpiresAt returns when this lease elapses if it is not extended.

func (*Handle) Extend added in v1.6.0

func (h *Handle) Extend(ctx context.Context, ttl time.Duration) error

Extend refreshes the lease by ttl, so work that outlives the original lease does not end up running alongside a second holder.

Without this a lock is simply lost when the lease elapses, silently and with no error anywhere: the critical section keeps running while another instance acquires the same key.

func (*Handle) Key added in v1.6.0

func (h *Handle) Key() string

Key returns the locked key.

func (*Handle) Release added in v1.6.0

func (h *Handle) Release(ctx context.Context) error

Release gives the lock back.

It is a compare-and-delete on the token, so a Handle whose lease already elapsed cannot delete a lock a different holder has since taken. Releasing a lease that has already elapsed reports ErrLockExpired.

type HybridLocker

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

HybridLocker locks through Redis when a client is configured, and through a process-local lock when one is not.

It does NOT fall back to the local lock when Redis is merely failing, unless allowLocalFallback is set. A process-local lock provides no mutual exclusion between instances, so degrading to it during a Redis outage silently drops the guarantee at exactly the moment it matters -- and the caller sees (true, nil), indistinguishable from a real distributed lock. Use NewHybridLockerWithLocalFallback to opt back in where losing exclusion is genuinely acceptable (a cache warmer, say, but never a payment or a coupon).

func NewHybridLocker

func NewHybridLocker(client redis.UniversalClient) *HybridLocker

NewHybridLocker creates a hybrid locker that uses Redis when client is non-nil and a process-local lock when it is nil.

If a Redis operation fails, the error is returned rather than silently degrading to the local lock.

Example

With no client at all, a HybridLocker is a process-local lock. Passing an unassigned *redis.Client field counts as "no client" too -- it is a typed nil, and locking through it would panic.

package main

import (
	"fmt"

	"github.com/redis/go-redis/v9"

	"github.com/soulteary/redis-kit/lock"
)

func main() {
	var unset *redis.Client // never assigned

	locker := lock.NewHybridLocker(unset)

	first, err := locker.Lock("job:nightly")
	fmt.Println("first:", first, err)

	second, err := locker.Lock("job:nightly")
	fmt.Println("second:", second, err)

	fmt.Println("unlock:", locker.Unlock("job:nightly"))
}
Output:
first: true <nil>
second: false <nil>
unlock: <nil>

func NewHybridLockerWithLocalFallback added in v1.6.0

func NewHybridLockerWithLocalFallback(client redis.UniversalClient) *HybridLocker

NewHybridLockerWithLocalFallback is NewHybridLocker with the pre-existing behaviour of falling back to a process-local lock when Redis fails.

Mutual exclusion across instances is lost while the fallback is in effect. Only use it where a concurrent second holder is acceptable.

func (*HybridLocker) Lock

func (h *HybridLocker) Lock(key string) (bool, error)

Lock acquires a lock through Redis when configured.

On a Redis failure it returns the error, so the caller can fail closed. Only a locker built with NewHybridLockerWithLocalFallback degrades to the process-local lock instead.

func (*HybridLocker) Unlock

func (h *HybridLocker) Unlock(key string) error

Unlock releases a lock through the backend that acquired it.

The routing is recorded, not guessed. Trying Redis first and falling back to the local lock on error was a lock-stealing path in both directions: a locally-acquired key was released by deleting whatever Redis held for it -- another goroutine's token, once Redis recovered -- and a Redis-acquired key whose release failed went on to release whatever was held locally.

type LocalLocker

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

LocalLocker provides local lock functionality using sync.Mutex Suitable for single-machine deployment scenarios, does not support distributed environments

func NewLocalLocker

func NewLocalLocker() *LocalLocker

NewLocalLocker creates a new local lock instance

func (*LocalLocker) Lock

func (l *LocalLocker) Lock(key string) (bool, error)

Lock acquires a local lock Returns true if the lock was successfully acquired, false if the lock is already held

func (*LocalLocker) Unlock

func (l *LocalLocker) Unlock(key string) error

Unlock releases a local lock

type Locker

type Locker interface {
	// Lock acquires a distributed lock
	// Returns true if the lock was successfully acquired, false if the lock is already held
	Lock(key string) (bool, error)

	// Unlock releases a distributed lock
	// Returns an error if the lock cannot be released (e.g., lock value mismatch or lock expired)
	Unlock(key string) error
}

Locker provides distributed lock functionality Compatible with gocron.Locker interface and similar use cases

type RedisLocker

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

RedisLocker provides Redis-based distributed lock functionality

func NewRedisLocker

func NewRedisLocker(client redis.UniversalClient) *RedisLocker

NewRedisLocker creates a new Redis-based distributed locker.

client is a redis.UniversalClient, so *redis.Client, *redis.ClusterClient, *redis.Ring and a Sentinel-backed failover client all work here.

Every command this locker issues names exactly one key, so nothing here is cross-slot on a cluster. Note what a cluster does NOT give you: a lock lives on one node, and its replica is asynchronous, so a failover can lose an acquisition that was already acknowledged. That is a property of the deployment, not of this locker -- a single-master lock is only as safe as the failover behind it.

Example (ClusterClient)

NewRedisLocker takes a redis.UniversalClient, so a cluster or a Sentinel-backed failover client goes in where a standalone client does. Compiled but not run: there is no cluster here.

package main

import (
	"context"
	"time"

	"github.com/redis/go-redis/v9"

	"github.com/soulteary/redis-kit/lock"
)

func main() {
	cluster := redis.NewClusterClient(&redis.ClusterOptions{
		Addrs: []string{"10.0.0.1:6379", "10.0.0.2:6379", "10.0.0.3:6379"},
	})
	defer func() { _ = cluster.Close() }()

	locker := lock.NewRedisLocker(cluster)
	handle, err := locker.Acquire(context.Background(), "job:nightly", 30*time.Second)
	if err != nil || handle == nil {
		return
	}
	defer func() { _ = handle.Release(context.Background()) }()
}

func NewRedisLockerWithLockTime

func NewRedisLockerWithLockTime(client redis.UniversalClient, lockTime time.Duration) *RedisLocker

NewRedisLockerWithLockTime creates a new Redis-based distributed locker with custom lock time

func (*RedisLocker) Acquire added in v1.6.0

func (l *RedisLocker) Acquire(ctx context.Context, key string, ttl time.Duration) (*Handle, error)

Acquire takes the lock for key, holding it for ttl.

It returns (nil, nil) when the lock is already held by someone else: that is contention, not an error. Any other non-nil error is a Redis failure and is wrapped in ErrRedisUnavailable, so callers can fail closed rather than guess.

Example

Acquire is the API to prefer. The returned Handle carries the token of this acquisition, so releasing it can never affect a lock somebody else took after this lease elapsed.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/soulteary/redis-kit/lock"
	"github.com/soulteary/redis-kit/testutil"
)

func main() {
	client, _ := testutil.NewMockRedisClient() // in real code, your own client
	defer func() { _ = client.Close() }()

	locker := lock.NewRedisLocker(client)
	ctx := context.Background()

	handle, err := locker.Acquire(ctx, "job:nightly", 30*time.Second)
	if err != nil {
		fmt.Println("acquire:", err)
		return
	}
	if handle == nil {
		fmt.Println("someone else holds it")
		return
	}

	// A second acquisition of the same key is contention, not an error:
	// (nil, nil).
	other, err := locker.Acquire(ctx, "job:nightly", 30*time.Second)
	fmt.Println("contended:", other == nil, err == nil)

	// Work outliving the lease renews it rather than losing the lock silently.
	if err := handle.Extend(ctx, 30*time.Second); err != nil {
		fmt.Println("extend:", err)
		return
	}

	fmt.Println("key:", handle.Key())
	fmt.Println("release:", handle.Release(ctx))
}
Output:
contended: true true
key: job:nightly
release: <nil>
Example (RedisUnavailable)

A Redis failure is reported, not silently downgraded to a process-local lock -- which would provide no mutual exclusion between instances at exactly the moment it matters.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/soulteary/redis-kit/lock"
	"github.com/soulteary/redis-kit/testutil"
)

func main() {
	client, mock := testutil.NewMockRedisClient()
	defer func() { _ = client.Close() }()
	mock.SetShouldFail(true)

	_, err := lock.NewRedisLocker(client).Acquire(context.Background(), "job:nightly", time.Second)

	fmt.Println(errors.Is(err, lock.ErrRedisUnavailable))
}
Output:
true

func (*RedisLocker) Lock

func (r *RedisLocker) Lock(key string) (bool, error)

Lock acquires a distributed lock using Redis SET key value NX Returns true if the lock was successfully acquired, false if the lock is already held

func (*RedisLocker) Unlock

func (r *RedisLocker) Unlock(key string) error

Unlock releases a distributed lock using a Lua script to ensure atomicity. Only releases the lock if the lock value matches, preventing accidental release of another process's lock.

It consumes the OLDEST outstanding acquisition of key -- and only on a DEFINITIVE result -- which is this caller's own in the paired usage this API assumes. The key alone cannot identify the caller, so when two holders of one key finish out of order -- the second one's lease outliving the first's -- the second's Unlock takes the first's expired entry, reports ErrLockExpired, and leaves its own lock in place until the TTL elapses. That is the safe half of the trade: letting an Unlock skip an expired entry to find a live one is exactly how a late caller comes to delete a current holder's lock. Acquire returns a Handle carrying its own token and has neither problem.

Jump to

Keyboard shortcuts

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