package redsync
import (
"math/rand"
"slices"
"time"
"github.com/go-redsync/redsync/v4/redis"
)
const (
minRetryDelayMilliSec = 50
maxRetryDelayMilliSec = 250
)
type Redsync struct {
pools []redis.Pool
}
func New(pools ...redis.Pool) *Redsync {
return &Redsync{
pools: pools,
}
}
func (r *Redsync) NewMutex(name string, options ...Option) *Mutex {
m := &Mutex{
name: name,
expiry: 8 * time.Second,
tries: 32,
delayFunc: func(tries int) time.Duration {
return time.Duration(rand.Intn(maxRetryDelayMilliSec-minRetryDelayMilliSec)+minRetryDelayMilliSec) * time.Millisecond
},
genValueFunc: genValue,
driftFactor: 0.01,
timeoutFactor: 0.05,
quorum: len(r.pools)/2 + 1,
pools: r.pools,
}
for _, o := range options {
o.Apply(m)
}
if m.shuffle {
m.pools = slices.Clone(m.pools)
randomPools(m.pools)
}
return m
}
type Option interface {
Apply(*Mutex)
}
type OptionFunc func(*Mutex)
func (f OptionFunc) Apply(mutex *Mutex) {
f(mutex)
}
func WithExpiry(expiry time.Duration) Option {
return OptionFunc(func(m *Mutex) {
m.expiry = expiry
})
}
func WithTries(tries int) Option {
return OptionFunc(func(m *Mutex) {
m.tries = tries
})
}
func WithRetryDelay(delay time.Duration) Option {
return OptionFunc(func(m *Mutex) {
m.delayFunc = func(tries int) time.Duration {
return delay
}
})
}
func WithSetNXOnExtend() Option {
return OptionFunc(func(m *Mutex) {
m.setNXOnExtend = true
})
}
func WithRetryDelayFunc(delayFunc DelayFunc) Option {
return OptionFunc(func(m *Mutex) {
m.delayFunc = delayFunc
})
}
func WithDriftFactor(factor float64) Option {
return OptionFunc(func(m *Mutex) {
m.driftFactor = factor
})
}
func WithTimeoutFactor(factor float64) Option {
return OptionFunc(func(m *Mutex) {
m.timeoutFactor = factor
})
}
func WithGenValueFunc(genValueFunc func() (string, error)) Option {
return OptionFunc(func(m *Mutex) {
m.genValueFunc = genValueFunc
})
}
func WithValue(v string) Option {
return OptionFunc(func(m *Mutex) {
m.value = v
})
}
func WithFailFast(b bool) Option {
return OptionFunc(func(m *Mutex) {
m.failFast = b
})
}
func WithShufflePools(b bool) Option {
return OptionFunc(func(m *Mutex) {
m.shuffle = b
})
}
func randomPools(pools []redis.Pool) {
rand.Shuffle(len(pools), func(i, j int) {
pools[i], pools[j] = pools[j], pools[i]
})
}