Skip to content
Source on GitHub (opens in a new tab)
import filelease "github.com/barevoidco/zelk/core/lease/file"

Package filelease is a lease.Lease for processes on one machine, kept in files in a directory the host owns (docs/design/durability.md, L12).

Each session has a lock file, created once and never replaced, and a data file holding the newest fence, whether it is held, and when its grant expires. Every operation runs under the lock file’s lock and persists any change, synced and renamed into place, before it answers, so fences survive restarts and crashes, and two processes never hold one session at once. Expiry is compared on the wall clock, which every process on the machine shares; see L7 for what a clock jump does.

See docs/design/durability.md for the Windows NTFS process-crash contract.

Example

dir, err := os.MkdirTemp("", "leases")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
ctx := context.Background()
// Two processes would each open their own Lease on the same directory.
a, _ := filelease.New(dir, filelease.WithTTL(time.Minute))
b, _ := filelease.New(dir, filelease.WithTTL(time.Minute))
g, _ := a.Acquire(ctx, "session-1")
_, err = b.Acquire(ctx, "session-1")
fmt.Println(errors.Is(err, lease.ErrHeld))
_ = a.Release(ctx, g.Token)
next, _ := b.Acquire(ctx, "session-1")
fmt.Println(next.Token.Fence > g.Token.Fence)
// Output:
// true
// true

Output:

true
true
var ErrCorrupt = errors.New("lease data is damaged")

ErrCorrupt is returned for a session whose lease data is damaged. The lease is never reset to recover, since that could hand out a fence again; an operator decides.

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

Lease is a lease.Lease kept in files in one directory, shared by every process on the machine that opens a Lease on it. It is safe for concurrent use.

func New(dir string, opts ...Option) (*Lease, error)

New returns a lease kept in dir, which must be an absolute path to an existing directory the host owns and makes durable, used for nothing else.

func (l *Lease) Acquire(ctx context.Context, session string) (lease.Grant, error)

Acquire takes the session’s lease, or returns a *lease.HeldError.

func (*Lease) Durable() bool

Durable reports true: fences are kept in files, so they keep growing across processes and restarts.

func (l *Lease) Release(ctx context.Context, t lease.Token) error

Release gives up the lease held by t.

func (l *Lease) Renew(ctx context.Context, t lease.Token) (lease.Grant, error)

Renew extends the grant t holds.

type Option func(*Lease)

Option configures a Lease.

func WithClock(now func() time.Time) Option

WithClock sets the wall clock that times grants. The default is time.Now.

func WithTTL(d time.Duration) Option

WithTTL sets how long a grant lasts. The default is lease.DefaultTTL. Every process sharing the directory should use the same WithTTL.