lease

package
v0.1.78 Latest Latest
Warning

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

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

README

Distributed leases

Import github.com/flanksource/commons-db/lease to coordinate callers that share a backend and application scope. Keep the backend client open for the lifetime of its leases.

Constructor Client Coordination boundary
NewSQLServer(db, Options{Scope: "deploy"}) *sql.DB using the SQL Server driver The current database and application scope
NewRedis(client, ExpiringOptions{Options: Options{Scope: "deploy"}}) valkey.Client connected to a Redis or Valkey primary The primary's database and application scope
NewKubernetes(client, ExpiringOptions{Options: Options{Scope: "deploy"}}) A namespaced CoordinationV1().Leases(namespace) client The cluster, namespace, and application scope

Lock modes

  • Mutex("git/azure/oma") admits one holder. The same call can claim a leadership term.
  • ReadWriteLock(key) allows concurrent readers or a single writer. A registered writer blocks new readers and group holders until the writer acquires or leaves. Writers and mutex holders on the same key exclude each other.
  • GroupLock("country", "USA") can be held by several USA callers. A try-lock for GroupLock("country", "RSA") reports contention until every USA caller releases. Ungrouped readers on country can coexist with USA holders.

Use Lock(ctx) to wait, TryLock(ctx) to make one admission attempt, or LockWait(ctx) to receive the acquired lease asynchronously. TryLock returns a false acquisition flag and a nil error on contention. Use a cancellable context for channel waits and cancel it if you stop receiving. The channel can close without a result if the caller cancels before handoff. Receiving a successful result transfers the lease to the caller. Read acquisition uses RLock, TryRLock, or RLockWait.

// updateRepo must return when its context is canceled.
func update(ctx context.Context, locks lease.Locker, updateRepo func(context.Context) error) (err error) {
    held, err := locks.Mutex("git/azure/oma").Lock(ctx)
    if err != nil {
        return err
    }
    work, cancel := context.WithCancel(ctx)
    defer cancel()
    defer func() { err = errors.Join(err, held.Unlock(ctx), held.Err()) }()
    go func() {
        select {
        case <-held.Done():
            cancel()
        case <-work.Done():
        }
    }()
    return updateRepo(work)
}
usa, err := locks.GroupLock("country", "USA").Lock(ctx)
if err != nil {
    return err
}
rsa, acquired, tryErr := locks.GroupLock("country", "RSA").TryLock(ctx)
if acquired {
    // USA ownership may have been lost before the try-lock.
    tryErr = errors.Join(rsa.Unlock(ctx), usa.Err())
}
return errors.Join(tryErr, usa.Unlock(ctx))

Backend setup

SQL Server leases last as long as their session. Size a dedicated connection pool for the number of holders and waiting writers so lock sessions cannot starve the pool used by protected work. Grouped locks use 257 app locks per holder and require no schema objects. SQL Server ownership probes run every 10 seconds.

Redis and Valkey use a single authoritative primary per key. Asynchronous failover, data loss, or key eviction can allow overlapping holders. Use a primary with adequate memory and a noeviction policy. Writer leases use a local copy of Redsync. Include the Redsync license in distribution materials for binaries containing it.

Kubernetes requires get, create, and update on coordination.k8s.io Leases. The adapter retains empty Lease objects for reuse. A new observer can need a full TTL to declare a crashed holder stale.

The default expiry is 30 seconds. Redis/Valkey and Kubernetes renew every third of the TTL and signal loss before expiry when ownership cannot be confirmed. The context used to acquire a lock bounds acquisition. Work cancellation is cooperative and callers are responsible for relinquishing a lease after guarded work stops.

Integration tests

Run go test -race ./lease/... with any of COMMONS_DB_LEASE_SQLSERVER_URL, COMMONS_DB_LEASE_REDIS_URL, COMMONS_DB_LEASE_VALKEY_URL, or COMMONS_DB_LEASE_KUBECONFIG set for a disposable service. The Kubernetes integration suite creates temporary namespaces.

Documentation

Overview

Package lease coordinates keyed locks across processes using a shared backend.

Index

Constants

This section is empty.

Variables

View Source
var ErrLost = errors.New("lease lost")

ErrLost indicates that the library can no longer confirm ownership.

Functions

This section is empty.

Types

type ExpiringOptions

type ExpiringOptions struct {
	Options
	// TTL defaults to 30 seconds. Specify whole seconds from 3 seconds to 24 hours.
	TTL time.Duration
}

ExpiringOptions configures a backend that expires abandoned lease records.

type Lease

type Lease interface {
	Unlock(context.Context) error
	Done() <-chan struct{}
	Err() error
}

Lease represents a single acquisition. Stop protected work before unlocking.

type Lock

type Lock interface {
	Lock(context.Context) (Lease, error)
	TryLock(context.Context) (Lease, bool, error)
	LockWait(context.Context) <-chan Result
}

Lock acquires a mutex or a share of a group.

type Locker

type Locker interface {
	Mutex(key string) Lock
	ReadWriteLock(key string) ReadWriteLock
	GroupLock(key, group string) Lock
}

Locker creates handles in a backend's configured scope.

func NewKubernetes

func NewKubernetes(client coordination.LeaseInterface, options ExpiringOptions) (Locker, error)

NewKubernetes uses a namespaced coordination/v1 Lease client.

func NewRedis

func NewRedis(client valkey.Client, options ExpiringOptions) (Locker, error)

NewRedis uses one authoritative Redis or Valkey primary per key.

func NewSQLServer

func NewSQLServer(db *sql.DB, options Options) (Locker, error)

NewSQLServer uses session-owned app locks. Size the caller's lock pool for the maximum number of simultaneous holders and waiting writers.

type Options

type Options struct {
	Scope            string
	RetryInterval    time.Duration
	OperationTimeout time.Duration
}

Options configures the coordination scope and bounds individual backend calls.

type ReadWriteLock

type ReadWriteLock interface {
	Lock
	RLock(context.Context) (Lease, error)
	TryRLock(context.Context) (Lease, bool, error)
	RLockWait(context.Context) <-chan Result
}

ReadWriteLock admits concurrent readers or an exclusive writer.

type Result

type Result struct {
	Lease Lease
	Err   error
}

Result is the outcome delivered by LockWait and RLockWait.

Directories

Path Synopsis
internal
redsync
Package redsync provides a Redis-based distributed mutual exclusion lock implementation as described in the post http://redis.io/topics/distlock.
Package redsync provides a Redis-based distributed mutual exclusion lock implementation as described in the post http://redis.io/topics/distlock.

Jump to

Keyboard shortcuts

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