### Install locker with go get Source: https://github.com/assurrussa/locker/blob/master/README.md Command to fetch the locker module at version v0.1.0. Run this in your Go module directory. ```sh go get github.com/assurrussa/locker@v0.1.0 ``` -------------------------------- ### WithLeaseTTL usage example Source: https://github.com/assurrussa/locker Example of using WithLeaseTTL with a 45-second TTL when creating a Locker. ```go locks, err := locker.New(store, locker.WithLeaseTTL(45*time.Second)) ``` -------------------------------- ### WithRefreshInterval usage example Source: https://github.com/assurrussa/locker Example of using WithRefreshInterval with a 5-second interval when creating a Locker. ```go locks, err := locker.New(store, locker.WithRefreshInterval(5*time.Second)) ``` -------------------------------- ### TryAcquire example: handle acquisition and contention Source: https://github.com/assurrussa/locker Example usage of TryAcquire. On error, returns the error; on contention (acquired false), returns nil to skip the run; otherwise defers lease release. ```go lease, acquired, err := locks.TryAcquire(ctx, "jobs:reindex") switch { case err != nil: return err case !acquired: return nil // someone else holds the lock; skip this run } defer lease.Release(context.Background()) ``` -------------------------------- ### Run repository gates with make verify Source: https://github.com/assurrussa/locker/blob/master/CONTRIBUTING.md Runs the non-networked repository gates. Requires Go 1.24 or newer and golangci-lint 2.x. ```sh make verify ``` -------------------------------- ### New usage example Source: https://github.com/assurrussa/locker Shows how to create a Store with a goredis client and handle the error. The client is closed after use. ```go client := goredis.NewClient(&goredis.Options{Addr: "127.0.0.1:6379"}) defer client.Close() store, err := lockerredis.New(client) if err != nil { return err } ``` -------------------------------- ### WithLock example: handle ErrLost Source: https://github.com/assurrussa/locker Example using WithLock to run a critical section. Checks for ErrLost to know when the protected work is no longer exclusive. ```go err := locks.WithLock(ctx, "jobs:reindex", func(lockCtx context.Context) error { // Work must stop if lockCtx is canceled. return reindex(lockCtx) }) if errors.Is(err, locker.ErrLost) { // The protected work can no longer be assumed exclusive. } return err ``` -------------------------------- ### Full lifecycle example Source: https://github.com/assurrussa/locker Shows creating a Store, creating a locker, and using WithLock to run a critical section. Handles locker.ErrLost to return a typed outcome. ```go store, err := lockerredis.New(client) if err != nil { return err } locks, err := locker.New(store) if err != nil { return err } err = locks.WithLock(ctx, "jobs:reindex", func(lockCtx context.Context) error { if err := reindex(lockCtx); err != nil { return err } return nil }) if errors.Is(err, locker.ErrLost) { // callback or cleanup reported loss; return a typed outcome return err } ``` -------------------------------- ### WithTryLock example with contention handling Source: https://github.com/assurrussa/locker Shows using WithTryLock to run a critical section (reindex) only if the lock is acquired. If ran is false, the callback did not execute due to contention; the example returns nil in that case. ```go ran, err := locks.WithTryLock(ctx, "jobs:reindex", func(lockCtx context.Context) error { return reindex(lockCtx) }) if err != nil { return err } if !ran { return nil // contended; nothing executed } ``` -------------------------------- ### ObserverFunc example for logging events Source: https://github.com/assurrussa/locker Example ObserverFunc that logs lock events, warning on errors and info otherwise. Uses logger.Warn and logger.Info. ```go obs := locker.ObserverFunc(func(ctx context.Context, event locker.Event) { if event.Err != nil { logger.Warn("lock event", "type", event.Type, "err", event.Err) return } logger.Info("lock event", "type", event.Type, "duration", event.Duration) }) ``` -------------------------------- ### Quick start with Redis: acquire lock and run critical section Source: https://github.com/assurrussa/locker/blob/master/README.md Shows how to create a Redis-backed locker, acquire a lock with WithLock, and handle ErrLost. The Redis adapter accepts a go-redis client, cluster client, or ring, and never closes the borrowed client. Requires Go 1.24 or newer. ```go package main import ( "context" "errors" "time" "github.com/assurrussa/locker" lockerredis "github.com/assurrussa/locker/redis" goredis "github.com/redis/go-redis/v9" ) func run(ctx context.Context) error { client := goredis.NewClient(&goredis.Options{Addr: "127.0.0.1:6379"}) defer client.Close() store, err := lockerredis.New(client) if err != nil { return err } locks, err := locker.New(store) if err != nil { return err } err = locks.WithLock(ctx, "jobs:reindex", func(lockCtx context.Context) error { // Work must stop if lockCtx is canceled. return reindex(lockCtx) }) if errors.Is(err, locker.ErrLost) { // The protected work can no longer be assumed exclusive. } return err } func reindex(context.Context) error { return nil } ``` -------------------------------- ### WithTryLock example with error wrapping Source: https://github.com/assurrussa/locker Demonstrates wrapping callback errors with fmt.Errorf. Guarantees that if ran is true, the callback error is (or is joined in) the returned err. ```go ran, err := locks.WithTryLock(ctx, "cache:warm", func(lockCtx context.Context) error { if err := warmCache(lockCtx); err != nil { return fmt.Errorf("warm cache: %w", err) } return nil }) if err != nil { return err // guarantee: if ran == true, callback error is (or is joined in) err } ``` -------------------------------- ### WithLock example: wrap callback error Source: https://github.com/assurrussa/locker Example using WithLock with error wrapping in the callback. The returned error may be a join of callback and cleanup errors; inspect with errors.Is. ```go err := locks.WithLock(ctx, "config:write", func(lockCtx context.Context) error { if err := writeConfig(lockCtx); err != nil { return fmt.Errorf("write config: %w", err) } return nil }) if err != nil { // joined callback + cleanup error; inspect with errors.Is } ``` -------------------------------- ### Err usage example Source: https://github.com/assurrussa/locker Shows checking Err() after a clean release, which returns nil. The example acquires a lease, performs work, releases it, and then checks Err(). ```go lease, err := locks.Acquire(ctx, "job:leader") if err != nil { return err } // ...work... if err := lease.Release(ctx); err != nil { if errors.Is(err, locker.ErrLost) { // the lease had already been lost; release only reported it } return err } _ = lease.Err() // nil after a clean release ``` -------------------------------- ### NewSharded usage example Source: https://github.com/assurrussa/locker Shows how to create a sharded Store with a resolver that selects a client based on the storage key, then create a locker instance. ```go store, err := lockerredis.NewSharded(func( ctx context.Context, storageKey string, ) (lockerredis.Client, error) { return shardFor(storageKey) }) if err != nil { return err } locks, err := locker.New(store) ``` -------------------------------- ### StorageKey usage example Source: https://github.com/assurrussa/locker Example call to `StorageKey` with the raw key `"update_configs"`, producing the storage key `"locker:update:becfe150a2e0c205"` as shown in the golden table. ```go storageKey := lockerredis.StorageKey("update_configs") // -> "locker:update:becfe150a2e0c205" (see golden table above) ``` -------------------------------- ### Release with deferred cleanup Source: https://github.com/assurrussa/locker Shows a typical release pattern using defer to ensure release even on early return. The example acquires a lease, defers release with error logging, and then runs a critical section. ```go lease, err := locks.Acquire(ctx, "job:reindex") if err != nil { return err } defer func() { if err := lease.Release(context.Background()); err != nil { log.Printf("release: %v", err) } }() // critical section ``` -------------------------------- ### Run vulnerability gate with make vulncheck Source: https://github.com/assurrussa/locker/blob/master/CONTRIBUTING.md Runs the networked vulnerability gate using the current patched Go toolchain. ```sh make vulncheck ``` -------------------------------- ### Lease.Key() usage example Source: https://github.com/assurrussa/locker Acquires a lease and prints its key. The output is "acquired worker:leader" for the given key. ```go lease, err := locks.Acquire(ctx, "worker:leader") if err != nil { return err } fmt.Println("acquired", lease.Key()) // prints "acquired worker:leader" ``` -------------------------------- ### Run Redis integration tests with LOCKER_REDIS_ADDRS Source: https://github.com/assurrussa/locker/blob/master/CONTRIBUTING.md Runs Redis integration tests with two addresses. Requires two disposable Redis instances. ```sh LOCKER_REDIS_ADDRS=127.0.0.1:6379,127.0.0.1:6380 make test-integration-race ``` -------------------------------- ### TryAcquire example: poll with explicit cadence Source: https://github.com/assurrussa/locker Polls TryAcquire with a one-second timeout instead of blocking backoff. Returns the lease when acquired, or exits on context cancellation. ```go // Poll with an explicit cadence instead of the blocking backoff. for { lease, ok, err := locks.TryAcquire(ctx, "worker:leader") if err == nil && ok { return lease // became leader } select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(time.Second): } } ``` -------------------------------- ### Typed-nil store rejection example Source: https://github.com/assurrussa/locker Shows that a typed-nil store is rejected by nilInterface, producing the error "locker/redis: client must not be nil". The Locker constructor then returns an error. ```go // Typed-nil store is rejected by nilInterface. var client *goredis.Client = nil store, err := lockerredis.New(client) // "locker/redis: client must not be nil" if err != nil { return err } if _, err := locker.New(store); err != nil { return err } ``` -------------------------------- ### Lease.Lost() usage example Source: https://github.com/assurrussa/locker Acquires a lease and selects between context cancellation and loss of leadership. On loss, the protected resource should stop being served. ```go lease, err := locks.Acquire(ctx, "worker:leader") if err != nil { return err } defer lease.Release(context.Background()) select { case <-ctx.Done(): // shutdown requested case <-lease.Lost(): // leadership lost: stop serving the protected resource } ``` -------------------------------- ### ObserverFunc with WithObserver for lost events Source: https://github.com/assurrussa/locker Example registering an ObserverFunc via WithObserver to increment a metric on EventLost. Shows quick export of bounded metric or trace event. ```go locks, err := locker.New(store, locker.WithObserver(locker.ObserverFunc(func(ctx context.Context, event locker.Event) { // E.g. export a bounded metric or trace event quickly. if event.Type == locker.EventLost { metrics.Inc("lock.lost") } }))) ``` -------------------------------- ### Release with cleanup retry on store failure Source: https://github.com/assurrussa/locker Shows handling a store failure during release. One cleanup retry is allowed, but even a store-successful cleanup still returns an ErrLost error. The example joins errors if both attempts fail. ```go lease, err := locks.Acquire(ctx, "job:reindex") if err != nil { return err } if err := lease.Release(ctx); err != nil { // Store failed; the outcome is ambiguous. One cleanup retry is allowed, // but even a store-successful cleanup still returns an ErrLost error. if err2 := lease.Release(context.Background()); err2 != nil { if errors.Is(err2, locker.ErrLost) { // ownership is permanently lost despite the cleanup } return errors.Join(err, err2) } return err } ``` -------------------------------- ### Release Lua script Source: https://github.com/assurrussa/locker Lua script that checks ownership via GET and deletes the key with DEL. Returns 1 on success, 0 otherwise. ```lua if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end ``` -------------------------------- ### Refresh Lua script Source: https://github.com/assurrussa/locker Lua script that checks ownership via GET and extends the lease with PEXPIRE. Returns 1 on success, 0 otherwise. ```lua if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('pexpire', KEYS[1], ARGV[2]) else return 0 end ``` -------------------------------- ### Shared observer across two Locker instances Source: https://github.com/assurrussa/locker Example sharing one ObserverFunc across two Locker instances; may be called concurrently. Adds a trace event for each event type. ```go // Shared observer across two Locker instances: may be called concurrently. obs := locker.ObserverFunc(func(ctx context.Context, event locker.Event) { trace.AddEvent(ctx, "lock."+string(event.Type)) }) a, _ := locker.New(storeA, locker.WithObserver(obs)) b, _ := locker.New(storeB, locker.WithObserver(obs)) ``` -------------------------------- ### Fully configured Locker with all options Source: https://github.com/assurrussa/locker Creates a Locker instance with lease TTL, refresh interval, operation timeout, retry backoff, jitter ratio, and an observer. Returns an error like "locker: invalid options: ..." if any constraint is violated. ```go locks, err := locker.New( store, locker.WithLeaseTTL(2*time.Second), locker.WithRefreshInterval(250*time.Millisecond), locker.WithOperationTimeout(250*time.Millisecond), locker.WithRetryBackoff(time.Millisecond, 20*time.Millisecond), locker.WithJitterRatio(0.1), locker.WithObserver(locker.ObserverFunc(func(ctx context.Context, event locker.Event) { metrics.Observe(event.Type, event.Duration) })), ) if err != nil { return err // "locker: invalid options: ..." on constraint violation } ``` -------------------------------- ### Wiring a custom store Source: https://github.com/assurrussa/locker Shows how to plug a custom store into locker.New. When Acquire returns false, Locker treats it as contention and retries with backoff; when Refresh returns false, Locker permanently marks the lease lost and cancels the callback context. ```go store := myDatabaseStore{} // implements locker.Store locks, err := locker.New(store, locker.WithLeaseTTL(30*time.Second)) if err != nil { return err } err = locks.WithLock(ctx, "job:reindex", func(lockCtx context.Context) error { return reindex(lockCtx) }) ``` -------------------------------- ### Acquire method signature Source: https://github.com/assurrussa/locker Creates a lease only when the key does not already exist. Returns (true, nil) on success, (false, nil) on contention, (false, err) on ambiguous failure. ```go Acquire(ctx context.Context, key, token string, ttl time.Duration) (bool, error) ``` -------------------------------- ### Acquire Source: https://github.com/assurrussa/locker Creates a lease for the given key only if the key does not already exist. Returns true if the lease was created, false on contention, and an error on ambiguous failure. ```APIDOC ## Acquire ### Description Creates a lease for the given key only if the key does not already exist. Returns true if the lease was created, false on contention, and an error on ambiguous failure. ### Method Acquire ### Signature `Acquire(ctx context.Context, key, token string, ttl time.Duration) (bool, error)` ### Parameters - `ctx` (context.Context) - Required - Operation context; must be honored. - `key` (string) - Required - Raw application key that the Locker passes through unchanged. - `token` (string) - Required - Ownership token (20 random bytes, hex-encoded). - `ttl` (time.Duration) - Required - Lease duration; the stored lease must be at least this long. ### Response Returns `(true, nil)` when the lease was created, `(false, nil)` on contention (key already exists), `(false, err)` on an ambiguous failure. ``` -------------------------------- ### Configuration Options Source: https://github.com/assurrussa/locker/blob/master/README.md Configuration options for the Locker, including lease TTL, refresh interval, operation timeout, retry backoff, jitter ratio, and ownership token. ```APIDOC ## Configuration Options ### Description Configuration options for the Locker, including lease TTL, refresh interval, operation timeout, retry backoff, jitter ratio, and ownership token. ### Options - **WithLeaseTTL** - Lease TTL (default: 1 minute) - **WithRefreshInterval** - Refresh interval (default: 10 seconds) - **WithOperationTimeout** - Per-operation timeout (default: 10 seconds) - **WithRetryBackoff** - Retry backoff (nominally 10 milliseconds initially, with a hard 1-second maximum) - **WithJitterRatio** - Retry jitter (20%, bounded by a positive delay and the configured hard maximum) - **Ownership token** - 20 cryptographically random bytes ### Constraints The refresh interval plus twice the operation timeout must be less than the lease TTL. The extra operation budget covers TTL time already consumed before an acquire or refresh response reaches the caller. The caller's context limits the total blocking acquisition time. ``` -------------------------------- ### Supported import paths for locker and redis adapter Source: https://github.com/assurrussa/locker/blob/master/README.md Lists the import paths for the locker library and its Redis adapter. Use these paths to import the packages in Go code. ```text github.com/assurrussa/locker github.com/assurrussa/locker/redis ``` -------------------------------- ### Run published-consumer probe Source: https://github.com/assurrussa/locker/blob/master/README.md Runs the published-consumer probe, which is intentionally a post-tag gate. Pass the version tag as an argument. ```sh scripts/check-published-consumer.sh v0.1.0 ``` -------------------------------- ### WithObserver Source: https://github.com/assurrussa/locker/blob/master/README.md Use WithObserver with an Observer or ObserverFunc to receive acquisition, contention, refresh, release, failure, and loss events. Observer delivery is asynchronous and never blocks acquisition, refresh, or release. ```APIDOC ## WithObserver ### Description Use `WithObserver` with an `Observer` or `ObserverFunc` to receive acquisition, contention, refresh, release, failure, and loss events. Observer delivery is asynchronous and never blocks acquisition, refresh, or release. ### Method N/A (Go function) ### Endpoint N/A (Go function) ### Parameters #### Observer - **observer** (Observer or ObserverFunc) - Required - The observer to receive events. ### Response #### Events - **event** (Event) - The event delivered to the observer. ### Request Example ```go observer := locker.ObserverFunc(func(ctx context.Context, event locker.Event) { // Export a bounded metric or trace event quickly. }) ``` ``` -------------------------------- ### Public lifecycle API for lease management Source: https://github.com/assurrussa/locker/blob/master/README.md Shows the core methods for acquiring and releasing leases. Acquire retries with exponential backoff; TryAcquire does one attempt; Release performs a token-checked release. ```go func (*Locker) Acquire(context.Context, string) (*Lease, error) func (*Locker) TryAcquire(context.Context, string) (*Lease, bool, error) func (*Lease) Release(context.Context) error ``` -------------------------------- ### Lease Methods Source: https://github.com/assurrussa/locker/blob/master/README.md Methods on an acquired *Lease to access the key, detect loss, and retrieve the error. ```APIDOC ## Lease Methods ### Description Methods on an acquired *Lease to access the key, detect loss, and retrieve the error. ### Methods #### Key() Returns the raw application key. #### Lost() Returns a channel that is closed once on permanent lease loss. #### Err() Returns ErrLost joined with the first loss cause. ### Notes - Lost() and Err() report unexpected ownership loss. A successful Release() does not close Lost(), and Err() remains nil. - The lease must not be copied. Any ambiguous refresh or release error makes it permanently unsafe. - Refresh=false also means ownership is lost. Release=false returns an error satisfying both ErrLost and ErrNotOwner. - When release returns an error, another lease.Release is allowed only as a cleanup attempt. A successful cleanup does not restore safety and still returns ErrLost. - Ownership is encapsulated by the lease, so callers do not pass it back to a Locker; nil, incomplete, concurrent, and already released leases return ErrInvalidLease. ``` -------------------------------- ### Store interface for storage backend Source: https://github.com/assurrussa/locker/blob/master/README.md Defines the minimal storage interface that locker uses for lease management. Implementations must be safe for concurrent use, honor context cancellation, and provide leases not shorter than the requested TTL. ```go type Store interface { Acquire(context.Context, string, string, time.Duration) (bool, error) Refresh(context.Context, string, string, time.Duration) (bool, error) Release(context.Context, string, string) (bool, error) } ``` -------------------------------- ### Using WithObserver with ObserverFunc Source: https://github.com/assurrussa/locker Creates a locker with an observer that records lock events. The observer is an ObserverFunc that calls metrics.ObserveLockEvent with the event type and duration. ```go obs := locker.ObserverFunc(func(ctx context.Context, event locker.Event) { metrics.ObserveLockEvent(event.Type, event.Duration) }) locks, err := locker.New(store, locker.WithObserver(obs)) ``` -------------------------------- ### Redis storage key format Source: https://github.com/assurrussa/locker/blob/master/README.md `redis.StorageKey` preserves the previous format to prevent old and new deployments from creating independent locks for the same raw key. The format is `locker::<16-character-xxhash64>`. Acquire uses `SET ... NX` with TTL; refresh and release use Lua scripts comparing the ownership token atomically. ```text locker::<16-character-xxhash64> ``` -------------------------------- ### Create ObserverFunc for lock events Source: https://github.com/assurrussa/locker/blob/master/README.md Use `WithObserver` with an `Observer` or `ObserverFunc` to receive acquisition, contention, refresh, release, failure, and loss events. Delivery is asynchronous and never blocks lock operations; events are serialized per Locker but may be dropped under sustained backpressure. Observers must return quickly and panics are recovered. `Event.Key` is raw and may be sensitive; avoid using it as an uncontrolled metric label. ```go observer := locker.ObserverFunc(func(ctx context.Context, event locker.Event) { // Export a bounded metric or trace event quickly. }) ``` -------------------------------- ### config struct fields Source: https://github.com/assurrussa/locker Private config struct holding all option fields: leaseTTL, refreshInterval, operationTimeout, retryBackoff, retryBackoffMax, jitterRatio, and observer. ```go type config struct { leaseTTL time.Duration refreshInterval time.Duration operationTimeout time.Duration retryBackoff time.Duration retryBackoffMax time.Duration jitterRatio float64 observer Observer } ``` -------------------------------- ### Locker.TryAcquire Source: https://github.com/assurrussa/locker/blob/master/README.md Performs a single attempt to acquire a lease for the given key. Contention is indicated by returning (nil, false, nil). ```APIDOC ## Locker.TryAcquire ### Description Performs a single attempt to acquire a lease for the given key. Contention is indicated by returning (nil, false, nil). ### Method TryAcquire ### Signature ```go func (*Locker) TryAcquire(context.Context, string) (*Lease, bool, error) ``` ### Parameters - **ctx** (context.Context) - Required - The context for the acquisition. - **key** (string) - Required - The key to acquire the lease for. ### Returns - **Lease** - The acquired lease, or nil if not acquired. - **bool** - Whether the lease was acquired. - **error** - Any error encountered. ``` -------------------------------- ### Acquire with lease loss handling Source: https://github.com/assurrussa/locker Acquires a lease and defers release. After acquisition, the lease lifetime is not controlled by ctx; use Lease.Release and react to Lease.Lost. On failure, the error satisfies ErrNotAcquired. ```go lease, err := locks.Acquire(ctx, "worker:leader") if err != nil { return err // errors.Is(err, locker.ErrNotAcquired) } defer lease.Release(context.Background()) // or a storage-scoped context select { case <-lease.Lost(): // leadership is gone; stop serving } ``` -------------------------------- ### Locker.Acquire Source: https://github.com/assurrussa/locker/blob/master/README.md Acquires a lease for the given key, retrying with exponential backoff until it acquires the key or its context ends. After success, the acquisition context no longer controls the lease lifetime. ```APIDOC ## Locker.Acquire ### Description Acquires a lease for the given key, retrying with exponential backoff until it acquires the key or its context ends. After success, the acquisition context no longer controls the lease lifetime. ### Method Acquire ### Signature ```go func (*Locker) Acquire(context.Context, string) (*Lease, error) ``` ### Parameters - **ctx** (context.Context) - Required - The context for the acquisition. - **key** (string) - Required - The key to acquire the lease for. ### Returns - **Lease** - The acquired lease. - **error** - Any error encountered. ``` -------------------------------- ### Lease.Release Source: https://github.com/assurrussa/locker/blob/master/README.md Performs a token-checked release of the lease and respects its caller context. ```APIDOC ## Lease.Release ### Description Performs a token-checked release of the lease and respects its caller context. ### Method Release ### Signature ```go func (*Lease) Release(context.Context) error ``` ### Parameters - **ctx** (context.Context) - Required - The context for the release. ### Returns - **error** - Any error encountered. ``` -------------------------------- ### WithJitterRatio Source: https://github.com/assurrussa/locker Sets the retry jitter as a ratio in the inclusive range [0, 1]. Jitter bounds are derived as base ± round(base*ratio), bounded below by 1 ns and above by the retry backoff maximum. ```APIDOC ## WithJitterRatio ### Description Sets retry jitter as a ratio in the inclusive range `[0, 1]`. Jitter bounds are derived as `base ± round(base*ratio)`, bounded below by 1 ns and above by `retryBackoffMax`. ### Function Signature ```go func WithJitterRatio(ratio float64) Option ``` ### Parameters - `ratio` (float64) - Required - Must satisfy `0 <= ratio <= 1` and must not be NaN. Default: `0.20`. ### Example ```go locks, err := locker.New(store, locker.WithJitterRatio(0.5)) ``` ``` -------------------------------- ### New Source: https://github.com/assurrussa/locker Constructor for a Locker backed by a Store. It returns a configured Locker or an error if the store is nil or option validation fails. ```APIDOC ## New ### Description Constructor for a `Locker` backed by a [`Store`](store.md). It returns a configured `Locker`, or an error if the store is nil or option validation fails. ### Method `func New(store Store, options ...Option) (*Locker, error)` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `store` | [`Store`](store.md) | yes | — | Storage backend. Must not be nil (including a typed-nil interface value). | | `options` | `...Option` | no | defaults (see [configuration](../configuration.md)) | Functional options applied in order; `nil` options are skipped. | ### Return `(*Locker, error)` — a configured `Locker`, or an error if the store is nil or option validation fails. ### Errors | Error | Condition | |-------|-----------| | `errors.New("locker: store must not be nil")` | `store` is nil or a typed-nil interface value. | | `fmt.Errorf("locker: invalid options: %w", err)` | `config.validate()` fails — see the full list in [configuration](../configuration.md). | ### Request Example ```go store, err := lockerredis.New(client) // github.com/assurrussa/locker/redis if err != nil { return err } locks, err := locker.New(store, locker.WithLeaseTTL(30*time.Second)) if err != nil { return err } ``` ```go // Typed-nil store is rejected by nilInterface. var client *goredis.Client = nil store, err := lockerredis.New(client) // "locker/redis: client must not be nil" if err != nil { return err } if _, err := locker.New(store); err != nil { return err } ``` ``` -------------------------------- ### Release method signature Source: https://github.com/assurrussa/locker Deletes the lease only when the token still owns it. Returns (true, nil) when deleted, (false, nil) when the token did not own it, (false, err) on ambiguous failure. ```go Release(ctx context.Context, key, token string) (bool, error) ``` -------------------------------- ### Refresh method signature Source: https://github.com/assurrussa/locker Extends the lease only when the token still owns it. Returns (true, nil) on success, (false, nil) when the token no longer owns it (permanent ownership loss), (false, err) on ambiguous failure. ```go Refresh(ctx context.Context, key, token string, ttl time.Duration) (bool, error) ``` -------------------------------- ### New constructor signature Source: https://github.com/assurrussa/locker Declares the constructor for a Locker backed by a Store. Returns an error if the store is nil or option validation fails. ```go func New(store Store, options ...Option) (*Locker, error) ``` -------------------------------- ### Store interface Source: https://github.com/assurrussa/locker/blob/master/README.md The storage boundary for lease-based distributed mutual exclusion. Implementations must be safe for concurrent use, honor context cancellation, and provide leases not shorter than the requested TTL. ```APIDOC ## Store interface ### Description The storage boundary for lease-based distributed mutual exclusion. Implementations must be safe for concurrent use, honor context cancellation, and provide leases not shorter than the requested TTL. ### Methods #### Acquire Acquires a lease for the given key with the specified token and TTL. ##### Signature ```go Acquire(context.Context, string, string, time.Duration) (bool, error) ``` ##### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **key** (string) - Required - The key to acquire the lease for. - **token** (string) - Required - The token to associate with the lease. - **ttl** (time.Duration) - Required - The lease duration. ##### Returns - **bool** - Whether the lease was acquired. - **error** - Any error encountered. #### Refresh Refreshes an existing lease for the given key with the specified token and TTL. ##### Signature ```go Refresh(context.Context, string, string, time.Duration) (bool, error) ``` ##### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **key** (string) - Required - The key of the lease to refresh. - **token** (string) - Required - The token associated with the lease. - **ttl** (time.Duration) - Required - The new lease duration. ##### Returns - **bool** - Whether the refresh was successful. - **error** - Any error encountered. #### Release Releases a lease for the given key with the specified token. ##### Signature ```go Release(context.Context, string, string) (bool, error) ``` ##### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **key** (string) - Required - The key of the lease to release. - **token** (string) - Required - The token associated with the lease. ##### Returns - **bool** - Whether the release was successful. - **error** - Any error encountered. ``` -------------------------------- ### WithObserver Source: https://github.com/assurrussa/locker Registers a lock-lifecycle observer. A nil observer (or a typed-nil ObserverFunc) disables observations. ```APIDOC ## WithObserver ### Description Registers a lock-lifecycle observer. A `nil` observer (or a typed-nil `ObserverFunc`) disables observations. ### Function Signature ```go func WithObserver(observer Observer) Option ``` ### Parameters - `observer` (Observer) - Required - Receives lifecycle `Event`s asynchronously. ### Request Example ```go obs := locker.ObserverFunc(func(ctx context.Context, event locker.Event) { metrics.ObserveLockEvent(event.Type, event.Duration) }) locks, err := locker.New(store, locker.WithObserver(obs)) ``` ``` -------------------------------- ### Acquire with release error handling Source: https://github.com/assurrussa/locker Acquires a lease and releases it with a different context. Checks for ErrNotAcquired on acquisition and ErrLost on release to handle ownership loss. ```go lease, err := locks.Acquire(ctx, "jobs:reindex") if err != nil { if errors.Is(err, locker.ErrNotAcquired) { return err // acquisition stopped because the parent context ended } return err } if err := lease.Release(ctx2); err != nil && errors.Is(err, locker.ErrLost) { // ownership was no longer verifiable at release time } ``` -------------------------------- ### Create sharded Redis store with resolver Source: https://github.com/assurrussa/locker/blob/master/README.md Use `redis.NewSharded` with a context-aware resolver that receives the computed storage key. The resolver must map each storage key deterministically and identically in every process for the complete lease lifetime; changing the mapping while leases are live can create independent locks. Acquire, refresh, and release are routed independently. ```go store, err := lockerredis.NewSharded(func( ctx context.Context, storageKey string, ) (lockerredis.Client, error) { return shardFor(storageKey) }) ``` -------------------------------- ### Release Source: https://github.com/assurrussa/locker Deletes the lease only when the token still owns it. Returns true when deleted, false when the token did not own it, and an error on ambiguous failure. ```APIDOC ## Release ### Description Deletes the lease only when the token still owns it. Returns true when deleted, false when the token did not own it, and an error on ambiguous failure. ### Method Release ### Signature `Release(ctx context.Context, key, token string) (bool, error)` ### Parameters - `ctx` (context.Context) - Required - Operation context; must be honored. - `key` (string) - Required - Raw application key that the Locker passes through unchanged. - `token` (string) - Required - Ownership token (20 random bytes, hex-encoded). ### Response Returns `(true, nil)` when deleted, `(false, nil)` when the token did not own it, `(false, err)` on an ambiguous failure. ``` -------------------------------- ### Sentinel errors Source: https://github.com/assurrussa/locker/blob/master/README.md Public sentinel errors for the locker library. Always inspect returned errors with errors.Is; one result can preserve several causes. ```APIDOC ## Sentinel errors ### Description Public sentinel errors for the locker library. Always inspect returned errors with errors.Is; one result can preserve several causes. ### Errors - **ErrNotAcquired** - Indicates that a lease was not acquired. - **ErrLost** - Indicates that the lease was lost. - **ErrInvalidLease** - Indicates that the lease is invalid. - **ErrNotOwner** - Indicates that the caller is not the owner of the lease. ``` -------------------------------- ### Acquire method signature Source: https://github.com/assurrussa/locker Creates a TTL lease with Redis NX semantics. Sub-millisecond TTL fractions are rounded up to Redis millisecond precision. Uses SET NX PX . Returns (true, nil) on 'OK', (false, nil) on goredis.Nil (contention), or (false, err) on validation/client/resolver errors wrapped as 'locker/redis: acquire: %w'. Validation precedes routing. ```go func (s *Store) Acquire(ctx context.Context, key, token string, ttl time.Duration) (bool, error) ``` -------------------------------- ### WithObserver function signature Source: https://github.com/assurrussa/locker Registers a lock-lifecycle observer. A nil observer (or typed-nil ObserverFunc) disables observations. The observer receives lifecycle Events asynchronously. ```go func WithObserver(observer Observer) Option ``` -------------------------------- ### Store interface (root package) Source: https://github.com/assurrussa/locker Defines the backend contract for acquiring, refreshing, and releasing locks. Implemented by redis.Store and custom backends; accepted by Locker.New. ```go type Store interface { Acquire(ctx context.Context, key, token string, ttl time.Duration) (bool, error) Refresh(ctx context.Context, key, token string, ttl time.Duration) (bool, error) Release(ctx context.Context, key, token string) (bool, error) } ``` -------------------------------- ### New with redis store and lease TTL Source: https://github.com/assurrussa/locker Creates a Locker using a redis store and a lease TTL option. Returns an error if the store creation or Locker construction fails. ```go store, err := lockerredis.New(client) // github.com/assurrussa/locker/redis if err != nil { return err } locks, err := locker.New(store, locker.WithLeaseTTL(30*time.Second)) if err != nil { return err } ``` -------------------------------- ### New function signature Source: https://github.com/assurrussa/locker Creates a Store that sends every operation to one client. The client must not be nil (typed-nil pointers rejected via nilClient). Returns error 'locker/redis: client must not be nil' if invalid. ```go func New(client Client) (*Store, error) ``` -------------------------------- ### TryAcquire Source: https://github.com/assurrussa/locker Attempts to acquire a lock key exactly once. Returns a lease if acquired, or a boolean indicating contention without error. ```APIDOC ## TryAcquire ### Description Attempts to acquire `key` exactly once. Returns a lease if acquired, or a boolean indicating contention without error. ### Method Function call ### Signature `func (l *Locker) TryAcquire(ctx context.Context, key string) (*Lease, bool, error)` ### Parameters - `ctx` (context.Context) - Required - Bounds the single storage operation. - `key` (string) - Required - Raw application lock key. Must not be empty. ### Return `(*Lease, bool, error)`: - `(*Lease, true, nil)` - Acquired; lease is active until `Release` or loss. - `(nil, false, nil)` - Contention — the key is held by someone else. This is a normal outcome, not an error. - `(nil, false, error)` - Failure satisfying `ErrNotAcquired` (nil receiver, empty key, context canceled, token generation failure, or store error). ### Request Example ```go lease, acquired, err := locks.TryAcquire(ctx, "jobs:reindex") switch { case err != nil: return err case !acquired: return nil // someone else holds the lock; skip this run } defer lease.Release(context.Background()) ``` ```go // Poll with an explicit cadence instead of the blocking backoff. for { lease, ok, err := locks.TryAcquire(ctx, "worker:leader") if err == nil && ok { return lease // became leader } select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(time.Second): } } ``` ``` -------------------------------- ### WithJitterRatio - Set retry jitter ratio Source: https://github.com/assurrussa/locker Sets retry jitter as a ratio in the inclusive range [0, 1]. Jitter bounds are derived as base ± round(base*ratio), bounded below by 1 ns and above by retryBackoffMax. Default is 0.20. ```go func WithJitterRatio(ratio float64) Option ``` ```go locks, err := locker.New(store, locker.WithJitterRatio(0.5)) ``` -------------------------------- ### Option type definition Source: https://github.com/assurrussa/locker Defines the Option type used to configure a Locker via New. Options are applied in order; a nil option is silently skipped. ```go type Option func(*config) ``` -------------------------------- ### redis.Client Source: https://github.com/assurrussa/locker The redis.Client interface defines the minimal Redis client operations required by the locker system. It is implemented by *goredis.Client, *goredis.ClusterClient, and *goredis.Ring, and accepted by redis.New. ```APIDOC ## redis.Client ### Description The redis.Client interface defines the minimal Redis client operations required by the locker system. It is implemented by *goredis.Client, *goredis.ClusterClient, and *goredis.Ring, and accepted by redis.New. ### Interface Definition ```go type Client interface { SetArgs(ctx context.Context, key string, value any, args goredis.SetArgs) *goredis.StatusCmd Eval(ctx context.Context, script string, keys []string, args ...any) *goredis.Cmd } ``` ### Methods - **SetArgs** (ctx context.Context, key string, value any, args goredis.SetArgs) *goredis.StatusCmd - Sets a value with additional arguments. - **Eval** (ctx context.Context, script string, keys []string, args ...any) *goredis.Cmd - Evaluates a Lua script. ``` -------------------------------- ### WithRetryBackoff Source: https://github.com/assurrussa/locker Sets the initial and maximum delay between blocking acquisition attempts. The delay doubles per attempt and is clamped at the maximum, with each actual sleep jittered per the jitter ratio. ```APIDOC ## WithRetryBackoff ### Description Sets the initial and maximum delay between blocking acquisition attempts. The delay doubles per attempt and is clamped at `maximum`; each actual sleep is jittered per `jitterRatio`. ### Function Signature ```go func WithRetryBackoff(initial, maximum time.Duration) Option ``` ### Parameters - `initial` (time.Duration) - Required - Must be positive. Default: `10 * time.Millisecond`. - `maximum` (time.Duration) - Required - Must be at least `initial`. Default: `time.Second`. ### Example ```go locks, err := locker.New(store, locker.WithRetryBackoff(5*time.Millisecond, 100*time.Millisecond)) ``` ``` -------------------------------- ### Acquire method signature Source: https://github.com/assurrussa/locker Signature for the Acquire method. Waits until the key is acquired or the context ends. Works even with a nil pointer receiver or nil store, failing via the sentinel path. ```go func (l *Locker) Acquire(ctx context.Context, key string) (*Lease, error) ``` -------------------------------- ### Client interface for go-redis store Source: https://github.com/assurrussa/locker Defines the narrow go-redis API used by Store: SetArgs for acquire (NX + TTL) and Eval for Lua-based refresh/release. Implementations: *goredis.Client, *goredis.ClusterClient, *goredis.Ring. ```go type Client interface { SetArgs(ctx context.Context, key string, value any, args goredis.SetArgs) *goredis.StatusCmd Eval(ctx context.Context, script string, keys []string, args ...any) *goredis.Cmd } ``` -------------------------------- ### TryAcquire function signature Source: https://github.com/assurrussa/locker Signature for TryAcquire, which attempts to acquire a lock exactly once. Returns a lease, a boolean indicating acquisition, and an error. The key must not be empty. ```go func (l *Locker) TryAcquire(ctx context.Context, key string) (*Lease, bool, error) ``` -------------------------------- ### New Source: https://github.com/assurrussa/locker Creates a Store that sends every operation to one client. The client must not be nil. ```APIDOC ## New ### Description Creates a Store that sends every operation to one client. The client must not be nil. ### Method Constructor ### Signature `func New(client Client) (*Store, error)` ### Parameters - `client` (Client) - Required - Must not be nil (typed-nil pointers rejected via `nilClient`). ### Errors - `errors.New("locker/redis: client must not be nil")` ### Example ```go client := goredis.NewClient(&goredis.Options{Addr: "127.0.0.1:6379"}) defer client.Close() store, err := lockerredis.New(client) if err != nil { return err } ``` ``` -------------------------------- ### redis.NewSharded Source: https://github.com/assurrussa/locker/blob/master/README.md Creates a new sharded Redis locker with a context-aware resolver. The resolver receives the computed storage key and must map it deterministically to a client. ```APIDOC ## redis.NewSharded ### Description Creates a new sharded Redis locker with a context-aware resolver. The resolver receives the computed storage key and must map it deterministically to a client. ### Method N/A (Go function) ### Endpoint N/A (Go function) ### Parameters #### Resolver - **resolver** (func(ctx context.Context, storageKey string) (lockerredis.Client, error)) - Required - The resolver that maps storage keys to clients. ### Response #### Returns - **store** (lockerredis.Store) - The sharded Redis store. - **err** (error) - Any error encountered during creation. ### Request Example ```go store, err := lockerredis.NewSharded(func( ctx context.Context, storageKey string, ) (lockerredis.Client, error) { return shardFor(storageKey) }) ``` ``` -------------------------------- ### Option Source: https://github.com/assurrussa/locker A function type used to configure the Locker instance. It is accepted by Locker.New as a variadic parameter. ```APIDOC ## Option ### Description A function type used to configure the Locker instance. It is accepted by `Locker.New` as a variadic parameter. ### Type ```go type Option func(*config) ``` ### Usage Accepted by `Locker.New` (variadic). ```