Documentation
¶
Overview ¶
Package coordination defines backend-neutral contracts for distributed coordination: fenced leases, lease keepalive, mutexes, leader election, expiring group membership and reusable barriers.
A Backend grants exclusive, time-bounded [Lease]s on string keys. Every successful acquisition carries a FencingToken that is strictly greater than every token previously granted for the same key, even after release or expiry. Protected resources must check the token: a lease alone cannot stop a paused former owner from writing late.
The helpers in this package (KeepAlive, Mutex, Campaign) work with any Backend. Implementations live in sub-packages:
- memory: a synchronized in-process reference backend that also implements Registry and Barrier;
- file: a cross-process backend over lock files in a local directory;
- conformance: the test suite every Backend implementation must pass.
Errors ¶
Operations report the sentinel errors ErrInvalidRequest, ErrNotAcquired, ErrLeaseLost and ErrNotOwner; test for them with errors.Is. Canceled operations return the context's error or cancellation cause.
Concurrency ¶
All interfaces in this package must be safe for concurrent use by implementations. Mutex is safe for concurrent use; Leadership values may be copied and their Resign method called from any goroutine.
Example ¶
Acquire a fenced lease and pass its token to the protected resource.
package main
import (
"context"
"errors"
"fmt"
"time"
coordination "github.com/justusschock/distributed-coordination"
"github.com/justusschock/distributed-coordination/memory"
)
func main() {
ctx := context.Background()
backend := memory.NewBackend(nil)
lease, err := backend.Acquire(ctx, coordination.AcquireRequest{
Key: "reports/daily",
Owner: "worker-a",
TTL: 30 * time.Second,
Wait: true,
})
if err != nil {
fmt.Println("acquire:", err)
return
}
defer func() { _ = lease.Release(context.Background()) }()
// A second owner cannot take the key while the lease is held.
_, err = backend.Acquire(ctx, coordination.AcquireRequest{
Key: "reports/daily",
Owner: "worker-b",
TTL: 30 * time.Second,
})
fmt.Println("contended:", errors.Is(err, coordination.ErrNotAcquired))
// The protected store must reject writes carrying an older token.
fmt.Println("token:", lease.Info().Token)
}
Output: contended: true token: 1
Index ¶
- Variables
- func KeepAlive(ctx context.Context, lease Lease, ttl time.Duration) (*concurrency.Future[LeaseInfo], error)
- type AcquireRequest
- type Backend
- type Barrier
- type BarrierRequest
- type BarrierResult
- type Clock
- type ElectionOptions
- type FencingToken
- type Leadership
- type Lease
- type LeaseInfo
- type Member
- type MemberInfo
- type Membership
- type Mutex
- type Registry
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidRequest reports an empty required field, a non-positive // count or a non-positive TTL. ErrInvalidRequest = errors.New("coordination: invalid request") // ErrNotAcquired reports immediate lease contention (Wait: false), a // duplicate active membership, or a barrier arrival whose TTL expired. ErrNotAcquired = errors.New("coordination: not acquired") // ErrLeaseLost reports that a lease or membership expired, was released // or was replaced, so it can no longer be renewed or released. ErrLeaseLost = errors.New("coordination: lease lost") // ErrNotOwner reports a Mutex or Leadership operation without matching // active ownership. ErrNotOwner = errors.New("coordination: not owner") )
Sentinel errors returned by the coordination helpers and by conforming backends. Test for them with errors.Is; implementations may wrap them.
Functions ¶
func KeepAlive ¶
func KeepAlive(ctx context.Context, lease Lease, ttl time.Duration) (*concurrency.Future[LeaseInfo], error)
KeepAlive renews lease with ttl immediately and then every ttl/3 (at least every nanosecond) on its own goroutine. The returned future resolves with the latest LeaseInfo and
- the cancellation cause of ctx when ctx is done,
- ErrLeaseLost when lease.Done closes, or
- the first error returned by Renew.
Cancel ctx to stop renewing; the lease itself is not released. KeepAlive returns ErrInvalidRequest for a nil lease or a non-positive ttl.
Example ¶
package main
import (
"context"
"fmt"
"time"
coordination "github.com/justusschock/distributed-coordination"
"github.com/justusschock/distributed-coordination/memory"
)
func main() {
backend := memory.NewBackend(nil)
lease, err := backend.Acquire(context.Background(), coordination.AcquireRequest{
Key: "index/rebuild", Owner: "worker-a", TTL: 30 * time.Second,
})
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = lease.Release(context.Background()) }()
ctx, stop := context.WithCancel(context.Background())
defer stop()
future, err := coordination.KeepAlive(ctx, lease, 30*time.Second)
if err != nil {
fmt.Println(err)
return
}
// ... long-running work protected by lease.Info().Token ...
stop()
_, err = future.Await(context.Background())
fmt.Println("keepalive stopped:", err)
}
Output: keepalive stopped: context canceled
Types ¶
type AcquireRequest ¶
type AcquireRequest struct {
// Key names the coordinated resource. It must not be empty.
Key string
// Owner identifies the requester. It must not be empty and is recorded
// in [LeaseInfo]; backends do not interpret it.
Owner string
// TTL bounds the lease lifetime from the moment of acquisition. It must
// be positive.
TTL time.Duration
// Wait selects the behaviour under contention: false returns
// [ErrNotAcquired] immediately, true waits for release or expiry until
// the context is done.
Wait bool
}
AcquireRequest describes a lease acquisition.
type Backend ¶
type Backend interface {
// Acquire grants a lease on request.Key. It returns [ErrInvalidRequest]
// for an empty key or owner or a non-positive TTL, [ErrNotAcquired] when
// the key is held and request.Wait is false, and the context's error
// when ctx is done while waiting.
Acquire(ctx context.Context, request AcquireRequest) (Lease, error)
}
Backend grants fenced leases. Implementations must be safe for concurrent use and must pass the conformance suite in package conformance.
type Barrier ¶
type Barrier interface {
// Wait blocks until Parties distinct, unexpired participants have
// arrived, then returns the completed generation to every active waiter.
// It returns [ErrInvalidRequest] for invalid fields or a party count
// that differs from the barrier's, [ErrNotAcquired] when the arrival's
// TTL expires first, and the context's cancellation cause when ctx is
// done first. Expired and canceled arrivals are removed from the
// generation.
Wait(ctx context.Context, request BarrierRequest) (BarrierResult, error)
}
Barrier is a reusable rendezvous of a fixed number of participants. Implementations must be safe for concurrent use.
type BarrierRequest ¶
type BarrierRequest struct {
// Name identifies the barrier. It must not be empty.
Name string
// Participant identifies the arriving party. It must not be empty; a
// participant counts once per generation even with concurrent waiters.
Participant string
// Parties is the number of distinct participants that complete a
// generation. It must be positive, and every waiter of a barrier must
// use the same value.
Parties int
// TTL bounds how long the arrival counts towards the current generation.
// It must be positive.
TTL time.Duration
}
BarrierRequest describes one participant's arrival at a named barrier.
type BarrierResult ¶
type BarrierResult struct {
Name string
// Generation increases monotonically per barrier name, starting at 1.
Generation uint64
// Participants lists the participants of the generation, sorted.
Participants []string
}
BarrierResult describes a completed barrier generation.
type Clock ¶
type Clock interface {
// Now returns the current time.
Now() time.Time
// After returns a channel that receives the time once d has elapsed.
After(d time.Duration) <-chan time.Time
}
Clock is the time source a backend uses for lease timestamps and expiry. Backends accept a Clock so adapters and tests can control time; pass nil to the constructors in this module to use the real clock.
type ElectionOptions ¶
type ElectionOptions struct {
// Name identifies the election; the lease key is "election/" + Name.
Name string
// Candidate identifies this participant and becomes the lease owner.
Candidate string
// TTL is the leadership lease lifetime, renewed every TTL/3.
TTL time.Duration
}
ElectionOptions configures Campaign.
type FencingToken ¶
type FencingToken uint64
FencingToken orders the leases granted for one key. Each successful acquisition of a key receives a token strictly greater than every token previously granted for that key. Tokens of different keys are unrelated and must not be compared.
type Leadership ¶
type Leadership struct {
// Token is the fencing token of the leadership lease.
Token FencingToken
// Lost is closed when the lease is lost or its keepalive stops, including
// after Resign or cancellation of the Campaign context.
Lost <-chan struct{}
// contains filtered or unexported fields
}
Leadership is won leadership of an election. It may be copied; all copies share the same lease.
func Campaign ¶
func Campaign(ctx context.Context, backend Backend, options ElectionOptions) (Leadership, error)
Campaign waits until it acquires the election lease for options.Name, then keeps it alive with KeepAlive until ctx is done, the lease is lost or Leadership.Resign is called. It returns ErrInvalidRequest for a nil backend, an empty name or candidate, or a non-positive TTL, and otherwise the backend's acquisition error.
Example ¶
package main
import (
"context"
"fmt"
"time"
coordination "github.com/justusschock/distributed-coordination"
"github.com/justusschock/distributed-coordination/memory"
)
func main() {
ctx := context.Background()
backend := memory.NewBackend(nil)
leadership, err := coordination.Campaign(ctx, backend, coordination.ElectionOptions{
Name: "scheduler",
Candidate: "node-a",
TTL: 15 * time.Second,
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("leader with token", leadership.Token)
if err := leadership.Resign(ctx); err != nil {
fmt.Println(err)
}
<-leadership.Lost
fmt.Println("resigned")
}
Output: leader with token 1 resigned
func (Leadership) Resign ¶
func (l Leadership) Resign(ctx context.Context) error
Resign stops the keepalive and releases the leadership lease. The release happens at most once; every call returns the first call's result. The zero Leadership returns ErrNotOwner.
type Lease ¶
type Lease interface {
// Info returns the latest snapshot of the lease, including renewals.
Info() LeaseInfo
// Done is closed exactly once when the lease is released or lost
// (expiry, replacement or, for some backends, loss of the underlying
// lock).
Done() <-chan struct{}
// Renew extends the deadline to the backend clock's current time plus
// ttl. It returns [ErrInvalidRequest] for a non-positive ttl and
// [ErrLeaseLost] after release, expiry or replacement.
Renew(ctx context.Context, ttl time.Duration) (LeaseInfo, error)
// Release gives up the lease and closes Done. It returns [ErrLeaseLost]
// if the lease was already released, expired or replaced.
Release(ctx context.Context) error
}
Lease is exclusive, time-bounded ownership of one key. Implementations must be safe for concurrent use.
type LeaseInfo ¶
type LeaseInfo struct {
Key string
Owner string
Token FencingToken
AcquiredAt time.Time
ExpiresAt time.Time
}
LeaseInfo is a snapshot of a lease.
type Member ¶
type Member struct {
// Group names the group. It must not be empty.
Group string
// ID identifies the member within the group. It must not be empty.
ID string
// Metadata is optional, opaque data published with the member.
// Registries copy it defensively.
Metadata map[string]string
}
Member identifies a participant in a group.
type MemberInfo ¶
MemberInfo is a snapshot of an active membership.
type Membership ¶
type Membership interface {
// Info returns the latest snapshot of the membership.
Info() MemberInfo
// Done is closed exactly once when the membership is left or expires.
Done() <-chan struct{}
// Renew extends the deadline to the registry clock's current time plus
// ttl. It returns [ErrInvalidRequest] for a non-positive ttl and
// [ErrLeaseLost] after leave, expiry or replacement.
Renew(ctx context.Context, ttl time.Duration) (MemberInfo, error)
// Leave ends the membership and closes Done. It returns [ErrLeaseLost]
// if the membership already ended.
Leave(ctx context.Context) error
}
Membership is an expiring registration of one member. Implementations must be safe for concurrent use.
type Mutex ¶
type Mutex struct {
// contains filtered or unexported fields
}
Mutex is a fenced mutual-exclusion lock over a Backend for one key and one owner. A Mutex value holds at most one lease at a time and does not renew it: choose a TTL that bounds the critical section or use KeepAlive on a raw Lease.
A Mutex is safe for concurrent use, but concurrent Lock calls on the same value do not queue: the second returns ErrNotOwner.
func NewMutex ¶
NewMutex returns a Mutex for key and owner whose leases last ttl. It returns ErrInvalidRequest for a nil backend, an empty key or owner, or a non-positive ttl.
Example ¶
package main
import (
"context"
"fmt"
"time"
coordination "github.com/justusschock/distributed-coordination"
"github.com/justusschock/distributed-coordination/memory"
)
func main() {
ctx := context.Background()
backend := memory.NewBackend(nil)
mutex, err := coordination.NewMutex(backend, "billing/close", "worker-a", 30*time.Second)
if err != nil {
fmt.Println(err)
return
}
token, err := mutex.Lock(ctx)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("locked with token", token)
if err := mutex.Unlock(ctx); err != nil {
fmt.Println(err)
}
}
Output: locked with token 1
func (*Mutex) Lock ¶
func (m *Mutex) Lock(ctx context.Context) (FencingToken, error)
Lock waits until the lease for the mutex key is acquired and returns its fencing token, which callers pass to the protected resource. It returns ErrNotOwner promptly if this Mutex already holds or is acquiring a lease, and the context's error if ctx is done while waiting.
func (*Mutex) Unlock ¶
Unlock releases the held lease. It returns ErrNotOwner when no lease is held. If the lease was already lost it returns ErrLeaseLost and the Mutex may be locked again; other release errors keep the lease so Unlock can be retried.
type Registry ¶
type Registry interface {
// Join registers member for ttl. It returns [ErrInvalidRequest] for an
// empty group or ID or a non-positive ttl and [ErrNotAcquired] while the
// same group and ID are already active. After leave or expiry the same
// ID may join again as a fresh membership.
Join(ctx context.Context, member Member, ttl time.Duration) (Membership, error)
// List returns the active members of group sorted by ID. It returns
// [ErrInvalidRequest] for an empty group.
List(ctx context.Context, group string) ([]MemberInfo, error)
}
Registry tracks expiring group membership. Implementations must be safe for concurrent use.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package conformance provides the test suite every coordination.Backend implementation must pass.
|
Package conformance provides the test suite every coordination.Backend implementation must pass. |
|
Package file implements coordination.Backend with cross-process leases on a local filesystem directory.
|
Package file implements coordination.Backend with cross-process leases on a local filesystem directory. |
|
Package memory provides a synchronized, in-process reference implementation of the coordination contracts.
|
Package memory provides a synchronized, in-process reference implementation of the coordination contracts. |