Skip to content

Latest commit

 

History

History
378 lines (302 loc) · 8.64 KB

File metadata and controls

378 lines (302 loc) · 8.64 KB

API Reference

This reference summarizes the complete exported API. For behavioral examples, start with Getting started.

Constants and errors

const DefaultTTL = 300 * time.Second

Sentinel errors suitable for errors.Is:

var ErrLockConflicted error
var ErrLockExpired error
var ErrInvalidTTL error
var ErrUnserializableKey error
var ErrUnsupportedStore error
var ErrTableNotFound error

See Errors and logging.

Key

type Key struct { /* unexported fields */ }

func NewKey(resource string) *Key
func DecodeKey(payload []byte) (*Key, error)
func NormalizeKey(key *Key) ([]byte, error)
func DenormalizeKey(payload []byte) (*Key, error)

Resource and storage state:

func (k *Key) String() string
func (k *Key) State(name string) (any, bool)
func (k *Key) SetState(name string, value any)
func (k *Key) RemoveState(name string)
func (k *Key) MarkUnserializable()

Lifetime:

func (k *Key) ResetLifetime()
func (k *Key) ReduceLifetime(ttl time.Duration)
func (k *Key) RemainingLifetime() (time.Duration, bool)
func (k *Key) Expired() bool

Binary transfer:

func (k *Key) MarshalBinary() ([]byte, error)
func (k *Key) UnmarshalBinary(payload []byte) error

The key carries owner identity. See Ownership and transferable keys.

Lock

type Lock struct { /* unexported fields */ }

func NewLock(
    key *Key,
    store Store,
    ttl time.Duration,
    autoRelease bool,
) *Lock

Methods:

func (l *Lock) Acquire(ctx context.Context, blocking bool) (bool, error)
func (l *Lock) AcquireRead(ctx context.Context, blocking bool) (bool, error)
func (l *Lock) Refresh(ttl time.Duration) error
func (l *Lock) IsAcquired() (bool, error)
func (l *Lock) Release() error
func (l *Lock) Close() error
func (l *Lock) Expired() bool
func (l *Lock) RemainingLifetime() (time.Duration, bool)
func (l *Lock) SetLogger(logger *slog.Logger)

Close performs auto-release only when enabled and the lock is believed to be owned. It must be called explicitly.

Factory

type Factory struct { /* unexported fields */ }

func NewFactory(store Store) *Factory
func (f *Factory) CreateDefault(resource string) *Lock
func (f *Factory) Create(
    resource string,
    ttl time.Duration,
    autoRelease bool,
) *Lock
func (f *Factory) CreateFromKey(
    key *Key,
    ttl time.Duration,
    autoRelease bool,
) *Lock

Locker interfaces and NoLock

type Locker interface {
    Acquire(context.Context, bool) (bool, error)
    Refresh(time.Duration) error
    IsAcquired() (bool, error)
    Release() error
    Expired() bool
    RemainingLifetime() (time.Duration, bool)
}

type SharedLocker interface {
    Locker
    AcquireRead(context.Context, bool) (bool, error)
}

NoLock implements the lock behavior with unconditional success:

type NoLock struct{}

func (NoLock) Acquire(context.Context, bool) (bool, error)
func (NoLock) AcquireRead(context.Context, bool) (bool, error)
func (NoLock) Refresh(time.Duration) error
func (NoLock) IsAcquired() (bool, error)
func (NoLock) Release() error
func (NoLock) Close() error
func (NoLock) Expired() bool
func (NoLock) RemainingLifetime() (time.Duration, bool)

Store interfaces

type Store interface {
    Save(*Key) error
    Delete(*Key) error
    Exists(*Key) (bool, error)
    PutOffExpiration(*Key, time.Duration) error
}

type SharedStore interface {
    Store
    SaveRead(*Key) error
}

type BlockingStore interface {
    Store
    WaitAndSave(context.Context, *Key) error
}

type BlockingSharedStore interface {
    SharedStore
    BlockingStore
    WaitAndSaveRead(context.Context, *Key) error
}

LeaseBackend

type BackendLockMode uint8

const (
    BackendWrite BackendLockMode = iota
    BackendRead
)

type LeaseBackend interface {
    Acquire(context.Context, string, string, BackendLockMode, time.Duration, bool) error
    Delete(context.Context, string, string) error
    Exists(context.Context, string, string) (bool, error)
    Refresh(context.Context, string, string, time.Duration) error
}

See Custom lease backends for the full contract.

Local stores

type InMemoryStore struct { /* unexported fields */ }
func NewInMemoryStore() *InMemoryStore

type FileStore struct { /* unexported fields */ }
func NewFileStore(directory string) (*FileStore, error)

type NullStore struct{}
func NewNullStore() *NullStore

func OpenStore(dsn string) (Store, error)

All implement Store. InMemoryStore, FileStore, and NullStore also implement SharedStore; FileStore implements BlockingSharedStore.

Remote store adapters

func NewRedisStore(LeaseBackend, time.Duration) (*RedisStore, error)
func NewMemcachedStore(LeaseBackend, time.Duration) (*MemcachedStore, error)
func NewMongoDBStore(LeaseBackend, MongoDBOptions) (*MongoDBStore, error)
func NewSQLStore(LeaseBackend, SQLStoreOptions) (*SQLStore, error)
func NewMySQLStore(LeaseBackend, MySQLStoreOptions) (*MySQLStore, error)
func NewPostgreSQLStore(LeaseBackend, PostgreSQLStoreOptions) (*PostgreSQLStore, error)
func NewSemaphoreStore(string, LeaseBackend) (*SemaphoreStore, error)
func NewZooKeeperStore(LeaseBackend, string) (*ZooKeeperStore, error)
func NewDynamoDBStore(LeaseBackend, time.Duration) (*DynamoDBStore, error)

Every returned type implements Store. Additional capabilities:

Type Additional interfaces or methods
RedisStore SharedStore
MongoDBStore CreateTTLIndex(context.Context)
SQLStore ConfigureSchema
MySQLStore BlockingStore
PostgreSQLStore BlockingSharedStore
SemaphoreStore BlockingStore, ProjectID

Configuration structs and parsers:

type MongoDBOptions struct {
    URI        string
    Database   string
    Collection string
    DefaultTTL time.Duration
    Source     MongoSource
}

type MongoSource uint8
const (
    MongoSourceClient MongoSource = iota
    MongoSourceDatabase
    MongoSourceCollection
)

func ParseMongoDBStoreDSN(string, MongoDBOptions) (MongoDBOptions, error)

type SQLStoreOptions struct {
    Dialect       string
    DefaultTTL    time.Duration
    Transactional bool
}
func ParseSQLStoreDSN(string) (SQLStoreOptions, error)

type MySQLStoreOptions struct {
    Driver                   string
    ErrorMode                SQLErrorMode
    ServerVersion            string
    StringifyResults         bool
    NativePreparedStatements bool
}

type SQLErrorMode uint8
const (
    SQLErrorModeException SQLErrorMode = iota
    SQLErrorModeSilent
)
func ParseMySQLStoreDSN(string) (MySQLStoreOptions, error)

type PostgreSQLStoreOptions struct { Driver string }

type ZooKeeperOptions struct {
    Servers []string
    Path    string
}
func ParseZooKeeperDSN(string) (ZooKeeperOptions, error)

SQLSchema

type SQLSchema struct { /* unexported fields */ }

func NewSQLSchema() *SQLSchema
func (s *SQLSchema) AddTable(name string, columns []string)
func (s *SQLSchema) HasTable(name string) bool
func (s *SQLSchema) Columns(name string) []string
func (s *SQLStore) ConfigureSchema(
    schema *SQLSchema,
    sameDatabase func() bool,
)

CombinedStore and strategies

type Strategy interface {
    IsMet(successes, total int) bool
    CanBeMet(failures, total int) bool
}

type ConsensusStrategy struct{}
type UnanimousStrategy struct{}

func NewCombinedStore(
    stores []Store,
    strategy Strategy,
) (*CombinedStore, error)

ConsensusStrategy requires a strict majority. UnanimousStrategy requires every member. CombinedStore implements SharedStore.

StoreFactory

type StoreFactory struct { /* unexported fields */ }
func NewStoreFactory(backend LeaseBackend) *StoreFactory
func (f *StoreFactory) Open(dsn string) (Store, error)
func (f *StoreFactory) FromBackend(
    kind StoreBackendKind,
    advisory bool,
) (Store, error)
func (f *StoreFactory) FromSQLDriver(
    driver string,
    advisory bool,
) (Store, error)
func (f *StoreFactory) FromSQLPlatform(
    platform SQLPlatform,
    version string,
    advisory bool,
) (Store, error)

Enums:

type StoreBackendKind uint8
const (
    StoreBackendRedis StoreBackendKind = iota
    StoreBackendMemcached
    StoreBackendRedisProxy
)

type SQLPlatform uint8
const (
    SQLPlatformSQLite SQLPlatform = iota
    SQLPlatformPostgreSQL
    SQLPlatformMySQL
    SQLPlatformMariaDB
)

Typed errors

type AcquiringError struct {
    Resource string
    Err      error
}
func (e *AcquiringError) Error() string
func (e *AcquiringError) Unwrap() error

type ReleasingError struct {
    Resource string
    Err      error
}
func (e *ReleasingError) Error() string
func (e *ReleasingError) Unwrap() error