forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/redis/go-redis/v9/ring.go

1321 lines
18 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
package redis
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/cespare/xxhash/v2"
"github.com/dgryski/go-rendezvous" //nolint
"github.com/redis/go-redis/v9/internal"
"github.com/redis/go-redis/v9/internal/hashtag"
"github.com/redis/go-redis/v9/internal/pool"
"github.com/redis/go-redis/v9/internal/rand"
)
var errRingShardsDown = errors.New("redis: all ring shards are down")
//------------------------------------------------------------------------------
type ConsistentHash interface {
Get(string) string
}
type rendezvousWrapper struct {
*rendezvous.Rendezvous
}
func (w rendezvousWrapper) Get(key string) string {
2024-02-18 10:42:21 +00:00
return w.Lookup(key)
2024-02-18 10:42:21 +00:00
}
func newRendezvous(shards []string) ConsistentHash {
2024-02-18 10:42:21 +00:00
return rendezvousWrapper{rendezvous.New(shards, xxhash.Sum64String)}
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
// RingOptions are used to configure a ring client and should be
2024-02-18 10:42:21 +00:00
// passed to NewRing.
2024-02-18 10:42:21 +00:00
type RingOptions struct {
2024-02-18 10:42:21 +00:00
// Map of name => host:port addresses of ring shards.
2024-02-18 10:42:21 +00:00
Addrs map[string]string
// NewClient creates a shard client with provided options.
2024-02-18 10:42:21 +00:00
NewClient func(opt *Options) *Client
// ClientName will execute the `CLIENT SETNAME ClientName` command for each conn.
2024-02-18 10:42:21 +00:00
ClientName string
// Frequency of PING commands sent to check shards availability.
2024-02-18 10:42:21 +00:00
// Shard is considered down after 3 subsequent failed checks.
2024-02-18 10:42:21 +00:00
HeartbeatFrequency time.Duration
// NewConsistentHash returns a consistent hash that is used
2024-02-18 10:42:21 +00:00
// to distribute keys across the shards.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// See https://medium.com/@dgryski/consistent-hashing-algorithmic-tradeoffs-ef6b8e2fcae8
2024-02-18 10:42:21 +00:00
// for consistent hashing algorithmic tradeoffs.
2024-02-18 10:42:21 +00:00
NewConsistentHash func(shards []string) ConsistentHash
// Following options are copied from Options struct.
Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
2024-02-18 10:42:21 +00:00
OnConnect func(ctx context.Context, cn *Conn) error
Protocol int
2024-02-18 10:42:21 +00:00
Username string
2024-02-18 10:42:21 +00:00
Password string
DB int
MaxRetries int
2024-02-18 10:42:21 +00:00
MinRetryBackoff time.Duration
2024-02-18 10:42:21 +00:00
MaxRetryBackoff time.Duration
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
2024-02-18 10:42:21 +00:00
ContextTimeoutEnabled bool
// PoolFIFO uses FIFO mode for each node connection pool GET/PUT (default LIFO).
2024-02-18 10:42:21 +00:00
PoolFIFO bool
PoolSize int
PoolTimeout time.Duration
MinIdleConns int
MaxIdleConns int
MaxActiveConns int
2024-02-18 10:42:21 +00:00
ConnMaxIdleTime time.Duration
2024-02-18 10:42:21 +00:00
ConnMaxLifetime time.Duration
TLSConfig *tls.Config
Limiter Limiter
2024-02-18 10:42:21 +00:00
DisableIndentity bool
IdentitySuffix string
2024-02-18 10:42:21 +00:00
}
func (opt *RingOptions) init() {
2024-02-18 10:42:21 +00:00
if opt.NewClient == nil {
2024-02-18 10:42:21 +00:00
opt.NewClient = func(opt *Options) *Client {
2024-02-18 10:42:21 +00:00
return NewClient(opt)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if opt.HeartbeatFrequency == 0 {
2024-02-18 10:42:21 +00:00
opt.HeartbeatFrequency = 500 * time.Millisecond
2024-02-18 10:42:21 +00:00
}
if opt.NewConsistentHash == nil {
2024-02-18 10:42:21 +00:00
opt.NewConsistentHash = newRendezvous
2024-02-18 10:42:21 +00:00
}
if opt.MaxRetries == -1 {
2024-02-18 10:42:21 +00:00
opt.MaxRetries = 0
2024-02-18 10:42:21 +00:00
} else if opt.MaxRetries == 0 {
2024-02-18 10:42:21 +00:00
opt.MaxRetries = 3
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
switch opt.MinRetryBackoff {
2024-02-18 10:42:21 +00:00
case -1:
2024-02-18 10:42:21 +00:00
opt.MinRetryBackoff = 0
2024-02-18 10:42:21 +00:00
case 0:
2024-02-18 10:42:21 +00:00
opt.MinRetryBackoff = 8 * time.Millisecond
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
switch opt.MaxRetryBackoff {
2024-02-18 10:42:21 +00:00
case -1:
2024-02-18 10:42:21 +00:00
opt.MaxRetryBackoff = 0
2024-02-18 10:42:21 +00:00
case 0:
2024-02-18 10:42:21 +00:00
opt.MaxRetryBackoff = 512 * time.Millisecond
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (opt *RingOptions) clientOptions() *Options {
2024-02-18 10:42:21 +00:00
return &Options{
2024-02-18 10:42:21 +00:00
ClientName: opt.ClientName,
Dialer: opt.Dialer,
OnConnect: opt.OnConnect,
2024-02-18 10:42:21 +00:00
Protocol: opt.Protocol,
2024-02-18 10:42:21 +00:00
Username: opt.Username,
2024-02-18 10:42:21 +00:00
Password: opt.Password,
DB: opt.DB,
2024-02-18 10:42:21 +00:00
MaxRetries: -1,
DialTimeout: opt.DialTimeout,
ReadTimeout: opt.ReadTimeout,
WriteTimeout: opt.WriteTimeout,
2024-02-18 10:42:21 +00:00
ContextTimeoutEnabled: opt.ContextTimeoutEnabled,
PoolFIFO: opt.PoolFIFO,
PoolSize: opt.PoolSize,
PoolTimeout: opt.PoolTimeout,
MinIdleConns: opt.MinIdleConns,
MaxIdleConns: opt.MaxIdleConns,
MaxActiveConns: opt.MaxActiveConns,
2024-02-18 10:42:21 +00:00
ConnMaxIdleTime: opt.ConnMaxIdleTime,
2024-02-18 10:42:21 +00:00
ConnMaxLifetime: opt.ConnMaxLifetime,
TLSConfig: opt.TLSConfig,
Limiter: opt.Limiter,
2024-02-18 10:42:21 +00:00
DisableIndentity: opt.DisableIndentity,
IdentitySuffix: opt.IdentitySuffix,
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
type ringShard struct {
Client *Client
down int32
addr string
2024-02-18 10:42:21 +00:00
}
func newRingShard(opt *RingOptions, addr string) *ringShard {
2024-02-18 10:42:21 +00:00
clopt := opt.clientOptions()
2024-02-18 10:42:21 +00:00
clopt.Addr = addr
return &ringShard{
2024-02-18 10:42:21 +00:00
Client: opt.NewClient(clopt),
addr: addr,
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (shard *ringShard) String() string {
2024-02-18 10:42:21 +00:00
var state string
2024-02-18 10:42:21 +00:00
if shard.IsUp() {
2024-02-18 10:42:21 +00:00
state = "up"
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
state = "down"
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return fmt.Sprintf("%s is %s", shard.Client, state)
2024-02-18 10:42:21 +00:00
}
func (shard *ringShard) IsDown() bool {
2024-02-18 10:42:21 +00:00
const threshold = 3
2024-02-18 10:42:21 +00:00
return atomic.LoadInt32(&shard.down) >= threshold
2024-02-18 10:42:21 +00:00
}
func (shard *ringShard) IsUp() bool {
2024-02-18 10:42:21 +00:00
return !shard.IsDown()
2024-02-18 10:42:21 +00:00
}
// Vote votes to set shard state and returns true if state was changed.
2024-02-18 10:42:21 +00:00
func (shard *ringShard) Vote(up bool) bool {
2024-02-18 10:42:21 +00:00
if up {
2024-02-18 10:42:21 +00:00
changed := shard.IsDown()
2024-02-18 10:42:21 +00:00
atomic.StoreInt32(&shard.down, 0)
2024-02-18 10:42:21 +00:00
return changed
2024-02-18 10:42:21 +00:00
}
if shard.IsDown() {
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
atomic.AddInt32(&shard.down, 1)
2024-02-18 10:42:21 +00:00
return shard.IsDown()
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
type ringSharding struct {
opt *RingOptions
mu sync.RWMutex
shards *ringShards
closed bool
hash ConsistentHash
numShard int
2024-02-18 10:42:21 +00:00
onNewNode []func(rdb *Client)
// ensures exclusive access to SetAddrs so there is no need
2024-02-18 10:42:21 +00:00
// to hold mu for the duration of potentially long shard creation
2024-02-18 10:42:21 +00:00
setAddrsMu sync.Mutex
}
type ringShards struct {
m map[string]*ringShard
2024-02-18 10:42:21 +00:00
list []*ringShard
}
func newRingSharding(opt *RingOptions) *ringSharding {
2024-02-18 10:42:21 +00:00
c := &ringSharding{
2024-02-18 10:42:21 +00:00
opt: opt,
}
2024-02-18 10:42:21 +00:00
c.SetAddrs(opt.Addrs)
return c
2024-02-18 10:42:21 +00:00
}
func (c *ringSharding) OnNewNode(fn func(rdb *Client)) {
2024-02-18 10:42:21 +00:00
c.mu.Lock()
2024-02-18 10:42:21 +00:00
c.onNewNode = append(c.onNewNode, fn)
2024-02-18 10:42:21 +00:00
c.mu.Unlock()
2024-02-18 10:42:21 +00:00
}
// SetAddrs replaces the shards in use, such that you can increase and
2024-02-18 10:42:21 +00:00
// decrease number of shards, that you use. It will reuse shards that
2024-02-18 10:42:21 +00:00
// existed before and close the ones that will not be used anymore.
2024-02-18 10:42:21 +00:00
func (c *ringSharding) SetAddrs(addrs map[string]string) {
2024-02-18 10:42:21 +00:00
c.setAddrsMu.Lock()
2024-02-18 10:42:21 +00:00
defer c.setAddrsMu.Unlock()
cleanup := func(shards map[string]*ringShard) {
2024-02-18 10:42:21 +00:00
for addr, shard := range shards {
2024-02-18 10:42:21 +00:00
if err := shard.Client.Close(); err != nil {
2024-02-18 10:42:21 +00:00
internal.Logger.Printf(context.Background(), "shard.Close %s failed: %s", addr, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
c.mu.RLock()
2024-02-18 10:42:21 +00:00
if c.closed {
2024-02-18 10:42:21 +00:00
c.mu.RUnlock()
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
existing := c.shards
2024-02-18 10:42:21 +00:00
c.mu.RUnlock()
shards, created, unused := c.newRingShards(addrs, existing)
c.mu.Lock()
2024-02-18 10:42:21 +00:00
if c.closed {
2024-02-18 10:42:21 +00:00
cleanup(created)
2024-02-18 10:42:21 +00:00
c.mu.Unlock()
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
c.shards = shards
2024-02-18 10:42:21 +00:00
c.rebalanceLocked()
2024-02-18 10:42:21 +00:00
c.mu.Unlock()
cleanup(unused)
2024-02-18 10:42:21 +00:00
}
func (c *ringSharding) newRingShards(
2024-02-18 10:42:21 +00:00
addrs map[string]string, existing *ringShards,
2024-02-18 10:42:21 +00:00
) (shards *ringShards, created, unused map[string]*ringShard) {
2024-02-18 10:42:21 +00:00
shards = &ringShards{m: make(map[string]*ringShard, len(addrs))}
2024-02-18 10:42:21 +00:00
created = make(map[string]*ringShard) // indexed by addr
unused = make(map[string]*ringShard) // indexed by addr
2024-02-18 10:42:21 +00:00
if existing != nil {
2024-02-18 10:42:21 +00:00
for _, shard := range existing.list {
2024-02-18 10:42:21 +00:00
unused[shard.addr] = shard
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
for name, addr := range addrs {
2024-02-18 10:42:21 +00:00
if shard, ok := unused[addr]; ok {
2024-02-18 10:42:21 +00:00
shards.m[name] = shard
2024-02-18 10:42:21 +00:00
delete(unused, addr)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
shard := newRingShard(c.opt, addr)
2024-02-18 10:42:21 +00:00
shards.m[name] = shard
2024-02-18 10:42:21 +00:00
created[addr] = shard
for _, fn := range c.onNewNode {
2024-02-18 10:42:21 +00:00
fn(shard.Client)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
for _, shard := range shards.m {
2024-02-18 10:42:21 +00:00
shards.list = append(shards.list, shard)
2024-02-18 10:42:21 +00:00
}
return
2024-02-18 10:42:21 +00:00
}
func (c *ringSharding) List() []*ringShard {
2024-02-18 10:42:21 +00:00
var list []*ringShard
c.mu.RLock()
2024-02-18 10:42:21 +00:00
if !c.closed {
2024-02-18 10:42:21 +00:00
list = c.shards.list
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
c.mu.RUnlock()
return list
2024-02-18 10:42:21 +00:00
}
func (c *ringSharding) Hash(key string) string {
2024-02-18 10:42:21 +00:00
key = hashtag.Key(key)
var hash string
c.mu.RLock()
2024-02-18 10:42:21 +00:00
defer c.mu.RUnlock()
if c.numShard > 0 {
2024-02-18 10:42:21 +00:00
hash = c.hash.Get(key)
2024-02-18 10:42:21 +00:00
}
return hash
2024-02-18 10:42:21 +00:00
}
func (c *ringSharding) GetByKey(key string) (*ringShard, error) {
2024-02-18 10:42:21 +00:00
key = hashtag.Key(key)
c.mu.RLock()
2024-02-18 10:42:21 +00:00
defer c.mu.RUnlock()
if c.closed {
2024-02-18 10:42:21 +00:00
return nil, pool.ErrClosed
2024-02-18 10:42:21 +00:00
}
if c.numShard == 0 {
2024-02-18 10:42:21 +00:00
return nil, errRingShardsDown
2024-02-18 10:42:21 +00:00
}
shardName := c.hash.Get(key)
2024-02-18 10:42:21 +00:00
if shardName == "" {
2024-02-18 10:42:21 +00:00
return nil, errRingShardsDown
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return c.shards.m[shardName], nil
2024-02-18 10:42:21 +00:00
}
func (c *ringSharding) GetByName(shardName string) (*ringShard, error) {
2024-02-18 10:42:21 +00:00
if shardName == "" {
2024-02-18 10:42:21 +00:00
return c.Random()
2024-02-18 10:42:21 +00:00
}
c.mu.RLock()
2024-02-18 10:42:21 +00:00
defer c.mu.RUnlock()
return c.shards.m[shardName], nil
2024-02-18 10:42:21 +00:00
}
func (c *ringSharding) Random() (*ringShard, error) {
2024-02-18 10:42:21 +00:00
return c.GetByKey(strconv.Itoa(rand.Int()))
2024-02-18 10:42:21 +00:00
}
// Heartbeat monitors state of each shard in the ring.
2024-02-18 10:42:21 +00:00
func (c *ringSharding) Heartbeat(ctx context.Context, frequency time.Duration) {
2024-02-18 10:42:21 +00:00
ticker := time.NewTicker(frequency)
2024-02-18 10:42:21 +00:00
defer ticker.Stop()
for {
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-ticker.C:
2024-02-18 10:42:21 +00:00
var rebalance bool
for _, shard := range c.List() {
2024-02-18 10:42:21 +00:00
err := shard.Client.Ping(ctx).Err()
2024-02-18 10:42:21 +00:00
isUp := err == nil || err == pool.ErrPoolTimeout
2024-02-18 10:42:21 +00:00
if shard.Vote(isUp) {
2024-02-18 10:42:21 +00:00
internal.Logger.Printf(ctx, "ring shard state changed: %s", shard)
2024-02-18 10:42:21 +00:00
rebalance = true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if rebalance {
2024-02-18 10:42:21 +00:00
c.mu.Lock()
2024-02-18 10:42:21 +00:00
c.rebalanceLocked()
2024-02-18 10:42:21 +00:00
c.mu.Unlock()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// rebalanceLocked removes dead shards from the Ring.
2024-02-18 10:42:21 +00:00
// Requires c.mu locked.
2024-02-18 10:42:21 +00:00
func (c *ringSharding) rebalanceLocked() {
2024-02-18 10:42:21 +00:00
if c.closed {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if c.shards == nil {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
liveShards := make([]string, 0, len(c.shards.m))
for name, shard := range c.shards.m {
2024-02-18 10:42:21 +00:00
if shard.IsUp() {
2024-02-18 10:42:21 +00:00
liveShards = append(liveShards, name)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
c.hash = c.opt.NewConsistentHash(liveShards)
2024-02-18 10:42:21 +00:00
c.numShard = len(liveShards)
2024-02-18 10:42:21 +00:00
}
func (c *ringSharding) Len() int {
2024-02-18 10:42:21 +00:00
c.mu.RLock()
2024-02-18 10:42:21 +00:00
defer c.mu.RUnlock()
return c.numShard
2024-02-18 10:42:21 +00:00
}
func (c *ringSharding) Close() error {
2024-02-18 10:42:21 +00:00
c.mu.Lock()
2024-02-18 10:42:21 +00:00
defer c.mu.Unlock()
if c.closed {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
c.closed = true
var firstErr error
for _, shard := range c.shards.list {
2024-02-18 10:42:21 +00:00
if err := shard.Client.Close(); err != nil && firstErr == nil {
2024-02-18 10:42:21 +00:00
firstErr = err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
c.hash = nil
2024-02-18 10:42:21 +00:00
c.shards = nil
2024-02-18 10:42:21 +00:00
c.numShard = 0
return firstErr
2024-02-18 10:42:21 +00:00
}
//------------------------------------------------------------------------------
// Ring is a Redis client that uses consistent hashing to distribute
2024-02-18 10:42:21 +00:00
// keys across multiple Redis servers (shards). It's safe for
2024-02-18 10:42:21 +00:00
// concurrent use by multiple goroutines.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Ring monitors the state of each shard and removes dead shards from
2024-02-18 10:42:21 +00:00
// the ring. When a shard comes online it is added back to the ring. This
2024-02-18 10:42:21 +00:00
// gives you maximum availability and partition tolerance, but no
2024-02-18 10:42:21 +00:00
// consistency between different shards or even clients. Each client
2024-02-18 10:42:21 +00:00
// uses shards that are available to the client and does not do any
2024-02-18 10:42:21 +00:00
// coordination when shard state is changed.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Ring should be used when you need multiple Redis servers for caching
2024-02-18 10:42:21 +00:00
// and can tolerate losing data when one of the servers dies.
2024-02-18 10:42:21 +00:00
// Otherwise you should use Redis Cluster.
2024-02-18 10:42:21 +00:00
type Ring struct {
cmdable
2024-02-18 10:42:21 +00:00
hooksMixin
opt *RingOptions
sharding *ringSharding
cmdsInfoCache *cmdsInfoCache
2024-02-18 10:42:21 +00:00
heartbeatCancelFn context.CancelFunc
}
func NewRing(opt *RingOptions) *Ring {
2024-02-18 10:42:21 +00:00
opt.init()
hbCtx, hbCancel := context.WithCancel(context.Background())
ring := Ring{
opt: opt,
sharding: newRingSharding(opt),
2024-02-18 10:42:21 +00:00
heartbeatCancelFn: hbCancel,
}
ring.cmdsInfoCache = newCmdsInfoCache(ring.cmdsInfo)
2024-02-18 10:42:21 +00:00
ring.cmdable = ring.Process
ring.initHooks(hooks{
2024-02-18 10:42:21 +00:00
process: ring.process,
2024-02-18 10:42:21 +00:00
pipeline: func(ctx context.Context, cmds []Cmder) error {
2024-02-18 10:42:21 +00:00
return ring.generalProcessPipeline(ctx, cmds, false)
2024-02-18 10:42:21 +00:00
},
2024-02-18 10:42:21 +00:00
txPipeline: func(ctx context.Context, cmds []Cmder) error {
2024-02-18 10:42:21 +00:00
return ring.generalProcessPipeline(ctx, cmds, true)
2024-02-18 10:42:21 +00:00
},
})
go ring.sharding.Heartbeat(hbCtx, opt.HeartbeatFrequency)
return &ring
2024-02-18 10:42:21 +00:00
}
func (c *Ring) SetAddrs(addrs map[string]string) {
2024-02-18 10:42:21 +00:00
c.sharding.SetAddrs(addrs)
2024-02-18 10:42:21 +00:00
}
// Do create a Cmd from the args and processes the cmd.
2024-02-18 10:42:21 +00:00
func (c *Ring) Do(ctx context.Context, args ...interface{}) *Cmd {
2024-02-18 10:42:21 +00:00
cmd := NewCmd(ctx, args...)
2024-02-18 10:42:21 +00:00
_ = c.Process(ctx, cmd)
2024-02-18 10:42:21 +00:00
return cmd
2024-02-18 10:42:21 +00:00
}
func (c *Ring) Process(ctx context.Context, cmd Cmder) error {
2024-02-18 10:42:21 +00:00
err := c.processHook(ctx, cmd)
2024-02-18 10:42:21 +00:00
cmd.SetErr(err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
// Options returns read-only Options that were used to create the client.
2024-02-18 10:42:21 +00:00
func (c *Ring) Options() *RingOptions {
2024-02-18 10:42:21 +00:00
return c.opt
2024-02-18 10:42:21 +00:00
}
func (c *Ring) retryBackoff(attempt int) time.Duration {
2024-02-18 10:42:21 +00:00
return internal.RetryBackoff(attempt, c.opt.MinRetryBackoff, c.opt.MaxRetryBackoff)
2024-02-18 10:42:21 +00:00
}
// PoolStats returns accumulated connection pool stats.
2024-02-18 10:42:21 +00:00
func (c *Ring) PoolStats() *PoolStats {
2024-02-18 10:42:21 +00:00
shards := c.sharding.List()
2024-02-18 10:42:21 +00:00
var acc PoolStats
2024-02-18 10:42:21 +00:00
for _, shard := range shards {
2024-02-18 10:42:21 +00:00
s := shard.Client.connPool.Stats()
2024-02-18 10:42:21 +00:00
acc.Hits += s.Hits
2024-02-18 10:42:21 +00:00
acc.Misses += s.Misses
2024-02-18 10:42:21 +00:00
acc.Timeouts += s.Timeouts
2024-02-18 10:42:21 +00:00
acc.TotalConns += s.TotalConns
2024-02-18 10:42:21 +00:00
acc.IdleConns += s.IdleConns
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return &acc
2024-02-18 10:42:21 +00:00
}
// Len returns the current number of shards in the ring.
2024-02-18 10:42:21 +00:00
func (c *Ring) Len() int {
2024-02-18 10:42:21 +00:00
return c.sharding.Len()
2024-02-18 10:42:21 +00:00
}
// Subscribe subscribes the client to the specified channels.
2024-02-18 10:42:21 +00:00
func (c *Ring) Subscribe(ctx context.Context, channels ...string) *PubSub {
2024-02-18 10:42:21 +00:00
if len(channels) == 0 {
2024-02-18 10:42:21 +00:00
panic("at least one channel is required")
2024-02-18 10:42:21 +00:00
}
shard, err := c.sharding.GetByKey(channels[0])
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
// TODO: return PubSub with sticky error
2024-02-18 10:42:21 +00:00
panic(err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return shard.Client.Subscribe(ctx, channels...)
2024-02-18 10:42:21 +00:00
}
// PSubscribe subscribes the client to the given patterns.
2024-02-18 10:42:21 +00:00
func (c *Ring) PSubscribe(ctx context.Context, channels ...string) *PubSub {
2024-02-18 10:42:21 +00:00
if len(channels) == 0 {
2024-02-18 10:42:21 +00:00
panic("at least one channel is required")
2024-02-18 10:42:21 +00:00
}
shard, err := c.sharding.GetByKey(channels[0])
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
// TODO: return PubSub with sticky error
2024-02-18 10:42:21 +00:00
panic(err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return shard.Client.PSubscribe(ctx, channels...)
2024-02-18 10:42:21 +00:00
}
// SSubscribe Subscribes the client to the specified shard channels.
2024-02-18 10:42:21 +00:00
func (c *Ring) SSubscribe(ctx context.Context, channels ...string) *PubSub {
2024-02-18 10:42:21 +00:00
if len(channels) == 0 {
2024-02-18 10:42:21 +00:00
panic("at least one channel is required")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
shard, err := c.sharding.GetByKey(channels[0])
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
// TODO: return PubSub with sticky error
2024-02-18 10:42:21 +00:00
panic(err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return shard.Client.SSubscribe(ctx, channels...)
2024-02-18 10:42:21 +00:00
}
func (c *Ring) OnNewNode(fn func(rdb *Client)) {
2024-02-18 10:42:21 +00:00
c.sharding.OnNewNode(fn)
2024-02-18 10:42:21 +00:00
}
// ForEachShard concurrently calls the fn on each live shard in the ring.
2024-02-18 10:42:21 +00:00
// It returns the first error if any.
2024-02-18 10:42:21 +00:00
func (c *Ring) ForEachShard(
2024-02-18 10:42:21 +00:00
ctx context.Context,
2024-02-18 10:42:21 +00:00
fn func(ctx context.Context, client *Client) error,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
shards := c.sharding.List()
2024-02-18 10:42:21 +00:00
var wg sync.WaitGroup
2024-02-18 10:42:21 +00:00
errCh := make(chan error, 1)
2024-02-18 10:42:21 +00:00
for _, shard := range shards {
2024-02-18 10:42:21 +00:00
if shard.IsDown() {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
wg.Add(1)
2024-02-18 10:42:21 +00:00
go func(shard *ringShard) {
2024-02-18 10:42:21 +00:00
defer wg.Done()
2024-02-18 10:42:21 +00:00
err := fn(ctx, shard.Client)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case errCh <- err:
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}(shard)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
wg.Wait()
select {
2024-02-18 10:42:21 +00:00
case err := <-errCh:
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (c *Ring) cmdsInfo(ctx context.Context) (map[string]*CommandInfo, error) {
2024-02-18 10:42:21 +00:00
shards := c.sharding.List()
2024-02-18 10:42:21 +00:00
var firstErr error
2024-02-18 10:42:21 +00:00
for _, shard := range shards {
2024-02-18 10:42:21 +00:00
cmdsInfo, err := shard.Client.Command(ctx).Result()
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
return cmdsInfo, nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if firstErr == nil {
2024-02-18 10:42:21 +00:00
firstErr = err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if firstErr == nil {
2024-02-18 10:42:21 +00:00
return nil, errRingShardsDown
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil, firstErr
2024-02-18 10:42:21 +00:00
}
func (c *Ring) cmdShard(ctx context.Context, cmd Cmder) (*ringShard, error) {
2024-02-18 10:42:21 +00:00
pos := cmdFirstKeyPos(cmd)
2024-02-18 10:42:21 +00:00
if pos == 0 {
2024-02-18 10:42:21 +00:00
return c.sharding.Random()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
firstKey := cmd.stringArg(pos)
2024-02-18 10:42:21 +00:00
return c.sharding.GetByKey(firstKey)
2024-02-18 10:42:21 +00:00
}
func (c *Ring) process(ctx context.Context, cmd Cmder) error {
2024-02-18 10:42:21 +00:00
var lastErr error
2024-02-18 10:42:21 +00:00
for attempt := 0; attempt <= c.opt.MaxRetries; attempt++ {
2024-02-18 10:42:21 +00:00
if attempt > 0 {
2024-02-18 10:42:21 +00:00
if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
shard, err := c.cmdShard(ctx, cmd)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
lastErr = shard.Client.Process(ctx, cmd)
2024-02-18 10:42:21 +00:00
if lastErr == nil || !shouldRetry(lastErr, cmd.readTimeout() == nil) {
2024-02-18 10:42:21 +00:00
return lastErr
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return lastErr
2024-02-18 10:42:21 +00:00
}
func (c *Ring) Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) {
2024-02-18 10:42:21 +00:00
return c.Pipeline().Pipelined(ctx, fn)
2024-02-18 10:42:21 +00:00
}
func (c *Ring) Pipeline() Pipeliner {
2024-02-18 10:42:21 +00:00
pipe := Pipeline{
2024-02-18 10:42:21 +00:00
exec: pipelineExecer(c.processPipelineHook),
}
2024-02-18 10:42:21 +00:00
pipe.init()
2024-02-18 10:42:21 +00:00
return &pipe
2024-02-18 10:42:21 +00:00
}
func (c *Ring) TxPipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) {
2024-02-18 10:42:21 +00:00
return c.TxPipeline().Pipelined(ctx, fn)
2024-02-18 10:42:21 +00:00
}
func (c *Ring) TxPipeline() Pipeliner {
2024-02-18 10:42:21 +00:00
pipe := Pipeline{
2024-02-18 10:42:21 +00:00
exec: func(ctx context.Context, cmds []Cmder) error {
2024-02-18 10:42:21 +00:00
cmds = wrapMultiExec(ctx, cmds)
2024-02-18 10:42:21 +00:00
return c.processTxPipelineHook(ctx, cmds)
2024-02-18 10:42:21 +00:00
},
}
2024-02-18 10:42:21 +00:00
pipe.init()
2024-02-18 10:42:21 +00:00
return &pipe
2024-02-18 10:42:21 +00:00
}
func (c *Ring) generalProcessPipeline(
2024-02-18 10:42:21 +00:00
ctx context.Context, cmds []Cmder, tx bool,
2024-02-18 10:42:21 +00:00
) error {
2024-02-18 10:42:21 +00:00
if tx {
2024-02-18 10:42:21 +00:00
// Trim multi .. exec.
2024-02-18 10:42:21 +00:00
cmds = cmds[1 : len(cmds)-1]
2024-02-18 10:42:21 +00:00
}
cmdsMap := make(map[string][]Cmder)
for _, cmd := range cmds {
2024-02-18 10:42:21 +00:00
hash := cmd.stringArg(cmdFirstKeyPos(cmd))
2024-02-18 10:42:21 +00:00
if hash != "" {
2024-02-18 10:42:21 +00:00
hash = c.sharding.Hash(hash)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cmdsMap[hash] = append(cmdsMap[hash], cmd)
2024-02-18 10:42:21 +00:00
}
var wg sync.WaitGroup
2024-02-18 10:42:21 +00:00
for hash, cmds := range cmdsMap {
2024-02-18 10:42:21 +00:00
wg.Add(1)
2024-02-18 10:42:21 +00:00
go func(hash string, cmds []Cmder) {
2024-02-18 10:42:21 +00:00
defer wg.Done()
// TODO: retry?
2024-02-18 10:42:21 +00:00
shard, err := c.sharding.GetByName(hash)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
setCmdsErr(cmds, err)
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
if tx {
2024-02-18 10:42:21 +00:00
cmds = wrapMultiExec(ctx, cmds)
2024-02-18 10:42:21 +00:00
_ = shard.Client.processTxPipelineHook(ctx, cmds)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
_ = shard.Client.processPipelineHook(ctx, cmds)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}(hash, cmds)
2024-02-18 10:42:21 +00:00
}
wg.Wait()
2024-02-18 10:42:21 +00:00
return cmdsFirstErr(cmds)
2024-02-18 10:42:21 +00:00
}
func (c *Ring) Watch(ctx context.Context, fn func(*Tx) error, keys ...string) error {
2024-02-18 10:42:21 +00:00
if len(keys) == 0 {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("redis: Watch requires at least one key")
2024-02-18 10:42:21 +00:00
}
var shards []*ringShard
for _, key := range keys {
2024-02-18 10:42:21 +00:00
if key != "" {
2024-02-18 10:42:21 +00:00
shard, err := c.sharding.GetByKey(hashtag.Key(key))
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
shards = append(shards, shard)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if len(shards) == 0 {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("redis: Watch requires at least one shard")
2024-02-18 10:42:21 +00:00
}
if len(shards) > 1 {
2024-02-18 10:42:21 +00:00
for _, shard := range shards[1:] {
2024-02-18 10:42:21 +00:00
if shard.Client != shards[0].Client {
2024-02-18 10:42:21 +00:00
err := fmt.Errorf("redis: Watch requires all keys to be in the same shard")
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
return shards[0].Client.Watch(ctx, fn, keys...)
2024-02-18 10:42:21 +00:00
}
// Close closes the ring client, releasing any open resources.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// It is rare to Close a Ring, as the Ring is meant to be long-lived
2024-02-18 10:42:21 +00:00
// and shared between many goroutines.
2024-02-18 10:42:21 +00:00
func (c *Ring) Close() error {
2024-02-18 10:42:21 +00:00
c.heartbeatCancelFn()
return c.sharding.Close()
2024-02-18 10:42:21 +00:00
}