lock

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 5 Imported by: 0

README

lock

Unified distributed locking for Go services. All backends implement the same lock.Locker interface:

  • Lock(ctx) — block until acquired or context cancelled
  • TryLock(ctx) — single attempt
  • Unlock(ctx) — release
  • Refresh(ctx) — extend lease where supported

Shared configuration uses functional options: WithTTL, WithRetryDelay, and WithValue (auto-generated token when empty).

On-demand modules

Module path Third-party deps
github.com/LingByte/ling-base/lock none (+ lock/memory)
.../lock/redis go-redis
.../lock/redlock lock/redis
.../lock/etcd etcd clientv3
.../lock/zookeeper go-zookeeper/zk
.../lock/consul hashicorp/consul/api
.../lock/mysql database/sql only
.../lock/postgres database/sql only
go get github.com/LingByte/ling-base/lock/redis

Backends

Package Use case TTL / lease Refresh
memory Process-local (tests, single instance) In-memory expiry Yes
redis Single Redis node (SET NX + Lua unlock/refresh) Required Yes
redlock Multiple Redis nodes (quorum) Required Yes (quorum)
etcd etcd v3 lease + transactional create ≥ 1s KeepAlive
zookeeper Ephemeral sequential nodes Session No-op (session)
consul Session + KV lock ≥ 1s Session renew
mysql GET_LOCK / RELEASE_LOCK N/A (connection) No-op
postgres Advisory locks (pg_try_advisory_lock) N/A (session) No-op

Quick start

import (
    "context"
    "time"

    "github.com/LingByte/ling-base/lock"
    lockredis "github.com/LingByte/ling-base/lock/redis"
    goredis "github.com/redis/go-redis/v9"
)

func run(client *goredis.Client) error {
    mu, err := lockredis.NewMutex(client, "orders:42",
        lock.WithTTL(30*time.Second),
        lock.WithRetryDelay(100*time.Millisecond),
    )
    if err != nil {
        return err
    }
    ctx := context.Background()
    if err := mu.Lock(ctx); err != nil {
        return err
    }
    defer mu.Unlock(ctx)
    return mu.Refresh(ctx)
}

Documentation

Overview

Package lock defines a unified distributed lock interface.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotObtained is returned when a lock cannot be acquired.
	ErrNotObtained = errors.New("lock: not obtained")

	// ErrNotHeld is returned when unlocking or refreshing a lock that is not held.
	ErrNotHeld = errors.New("lock: not held")

	// ErrInvalidTTL is returned when TTL is invalid for the backend.
	ErrInvalidTTL = errors.New("lock: ttl must be greater than zero")

	// ErrEmptyKey is returned when the lock key is empty.
	ErrEmptyKey = errors.New("lock: key must not be empty")
)

Functions

func NewToken

func NewToken() (string, error)

NewToken generates a random ownership token.

func ResolveValue

func ResolveValue(opts *Options) (string, error)

ResolveValue returns opts.Value or a newly generated token.

Types

type Locker

type Locker interface {
	// Lock blocks until the lock is acquired or ctx is done.
	Lock(ctx context.Context) error

	// TryLock attempts to acquire the lock once without blocking.
	TryLock(ctx context.Context) error

	// Unlock releases the lock.
	Unlock(ctx context.Context) error

	// Refresh extends the lock lease/TTL when supported.
	Refresh(ctx context.Context) error
}

Locker is a distributed mutual-exclusion lock for a single key.

type Option

type Option func(*Options)

Option mutates Options.

func WithRetryDelay

func WithRetryDelay(d time.Duration) Option

WithRetryDelay sets the delay between acquire retries.

func WithTTL

func WithTTL(ttl time.Duration) Option

WithTTL sets the lock TTL / lease.

func WithValue

func WithValue(v string) Option

WithValue sets a custom ownership token.

type Options

type Options struct {
	// TTL is the lock lease duration. Required by most backends.
	TTL time.Duration

	// RetryDelay is the wait between Lock attempts.
	RetryDelay time.Duration

	// Value is an optional owner token. Generated when empty.
	Value string
}

Options holds shared lock configuration.

func ApplyOptions

func ApplyOptions(opts ...Option) Options

ApplyOptions builds Options with defaults.

Directories

Path Synopsis
Package memory provides a process-local lock (useful for tests / single instance).
Package memory provides a process-local lock (useful for tests / single instance).

Jump to

Keyboard shortcuts

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