Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrLockAlreadyAcquired = errors.New("lock already acquired") ErrLockReleaseFailed = errors.New("lock release failed") )
Functions ¶
This section is empty.
Types ¶
type Dialect ¶
type Dialect interface {
TryLock(ctx context.Context, querier Querier, key any) error
ReleaseLock(ctx context.Context, querier Querier, key any) error
}
Dialect is the interface for specific database implementations
type LockOption ¶
type LockOption func(*lockOptions)
func WithKeyFunc ¶
func WithKeyFunc(keyFunc func(string) (any, error)) LockOption
type Locker ¶
type Locker struct {
// contains filtered or unexported fields
}
func New ¶
func New(querier Querier, dialect Dialect, opts ...LockerOption) *Locker
New Create a new locker with provided database connection and dialect. The Locker is build with simplicity and proficient in mind, it is designed to be used when you have well established persistent database which you want to leverage for simple locking use cases.
For more complex use cases, consider using a dedicated distributed system with proper consensus mechanism like zookeeper, etcd...
A locker should be shared across the application with a single database connection for it to work correctly.
Available options: WithLogger, WithDefaultTtl
func (*Locker) TryLock ¶
func (l *Locker) TryLock(ctx context.Context, key string, ttl time.Duration, opts ...LockOption) (releaseFunc ReleaseFunc, err error)
TryLock tries to acquire a lock on the key. If the lock is already acquired, it returns ErrLockAlreadyAcquired.
If ttl equals 0 and the locker's default ttl is 0, the lock is not released automatically unless the database session ends, and the caller is responsible for releasing the lock.
Due to the limitation of popular databases lock functions, bigint with postgres and 64 characters with mysql, the provided key is hashed using FNV-1a before persisting, this behavior can be overridden by providing a custom keyFunc.
Available options: WithKeyFunc
type LockerOption ¶
type LockerOption func(*Locker)
func WithDefaultTtl ¶
func WithDefaultTtl(ttl time.Duration) LockerOption
WithDefaultTtl sets the default ttl for the locker.
func WithLogger ¶
func WithLogger(logger Logger) LockerOption
WithLogger sets the logger for the locker.
type Logger ¶
type Logger interface {
Debug(msg string, args ...any)
Error(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
}
Logger is the interface that wraps the basic logging methods used by dblock. The methods are modeled after the standard library slog package. The default logger is a slog logger
type Querier ¶
type Querier interface {
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
}
Querier is the common interface to execute queries on a DB, Tx, or Conn.
type ReleaseFunc ¶
type ReleaseFunc func() error