package redis

import (
	
	
	
	
	
	
	
	
	
	

	
	
	
	
	
)

var errRingShardsDown = errors.New("redis: all ring shards are down")

// defaultHeartbeatFn is the default function used to check the shard liveness
var defaultHeartbeatFn = func( context.Context,  *Client) bool {
	 := .Ping().Err()
	return  == nil ||  == pool.ErrPoolTimeout
}

//------------------------------------------------------------------------------

type ConsistentHash interface {
	Get(string) string
}

func newRendezvous( []string) ConsistentHash {
	return hashtag.NewRendezvousHash()
}

//------------------------------------------------------------------------------

// RingOptions are used to configure a ring client and should be
// passed to NewRing.
type RingOptions struct {
	// Map of name => host:port addresses of ring shards.
	Addrs map[string]string

	// NewClient creates a shard client with provided options.
	NewClient func(opt *Options) *Client

	// himport is the ring-wide HIMPORT fieldset registry, set by NewRing and
	// shared with every shard client (see himport.go, himport_cluster.go).
	himport *himportRegistry

	// ClientName will execute the `CLIENT SETNAME ClientName` command for each conn.
	ClientName string

	// Frequency of executing HeartbeatFn to check shards availability.
	// Shard is considered down after 3 subsequent failed checks.
	HeartbeatFrequency time.Duration

	// A function used to check the shard liveness
	// if not set, defaults to defaultHeartbeatFn
	HeartbeatFn func(ctx context.Context, client *Client) bool

	// NewConsistentHash returns a consistent hash that is used
	// to distribute keys across the shards.
	//
	// See https://medium.com/@dgryski/consistent-hashing-algorithmic-tradeoffs-ef6b8e2fcae8
	// for consistent hashing algorithmic tradeoffs.
	NewConsistentHash func(shards []string) ConsistentHash

	// Following options are copied from Options struct.

	Dialer    func(ctx context.Context, network, addr string) (net.Conn, error)
	OnConnect func(ctx context.Context, cn *Conn) error

	Protocol int
	Username string
	Password string
	// CredentialsProvider allows the username and password to be updated
	// before reconnecting. It should return the current username and password.
	CredentialsProvider func() (username string, password string)

	// CredentialsProviderContext is an enhanced parameter of CredentialsProvider,
	// done to maintain API compatibility. In the future,
	// there might be a merge between CredentialsProviderContext and CredentialsProvider.
	// There will be a conflict between them; if CredentialsProviderContext exists, we will ignore CredentialsProvider.
	CredentialsProviderContext func(ctx context.Context) (username string, password string, err error)

	// StreamingCredentialsProvider is used to retrieve the credentials
	// for the connection from an external source. Those credentials may change
	// during the connection lifetime. This is useful for managed identity
	// scenarios where the credentials are retrieved from an external source.
	//
	// Currently, this is a placeholder for the future implementation.
	StreamingCredentialsProvider auth.StreamingCredentialsProvider
	DB                           int

	MaxRetries      int
	MinRetryBackoff time.Duration
	MaxRetryBackoff time.Duration

	DialTimeout time.Duration

	// DialerRetries is the maximum number of retry attempts when dialing fails.
	//
	// default: 5
	DialerRetries int

	// DialerRetryTimeout is the backoff duration between retry attempts.
	//
	// default: 100 milliseconds
	DialerRetryTimeout time.Duration

	// DialerRetryBackoff controls the delay between dial retry attempts.
	// See Options.DialerRetryBackoff for details.
	DialerRetryBackoff func(attempt int) time.Duration

	ReadTimeout           time.Duration
	WriteTimeout          time.Duration
	ContextTimeoutEnabled bool

	// PoolFIFO uses FIFO mode for each node connection pool GET/PUT (default LIFO).
	PoolFIFO bool

	PoolSize              int
	PoolTimeout           time.Duration
	MinIdleConns          int
	MaxIdleConns          int
	MaxActiveConns        int
	ConnMaxIdleTime       time.Duration
	ConnMaxLifetime       time.Duration
	ConnMaxLifetimeJitter time.Duration

	// ReadBufferSize is the size of the bufio.Reader buffer for each connection.
	// Larger buffers can improve performance for commands that return large responses.
	// Smaller buffers can improve memory usage for larger pools.
	//
	// default: 32KiB (32768 bytes)
	ReadBufferSize int

	// WriteBufferSize is the size of the bufio.Writer buffer for each connection.
	// Larger buffers can improve performance for large pipelines and commands with many arguments.
	// Smaller buffers can improve memory usage for larger pools.
	//
	// default: 32KiB (32768 bytes)
	WriteBufferSize int

	// PipelineReadBufferSize, PipelineWriteBufferSize and PipelinePoolSize
	// configure the separate connection pool used for pipelining on each shard,
	// with its own (typically larger) buffers. See the same-named fields on
	// Options for details. Each shard client (a NewClient) creates this pool by
	// default; set PipelinePoolSize < 0 to opt out (pipelines run on the main pool).
	PipelineReadBufferSize  int
	PipelineWriteBufferSize int
	PipelinePoolSize        int

	TLSConfig *tls.Config
	Limiter   Limiter

	// DisableIndentity - Disable set-lib on connect.
	//
	// default: false
	//
	// Deprecated: Use DisableIdentity instead.
	DisableIndentity bool

	// DisableIdentity is used to disable CLIENT SETINFO command on connect.
	//
	// default: false
	DisableIdentity bool
	IdentitySuffix  string

	// Deprecated: All RediSearch commands now have stable RESP3 parsing and this
	// flag is a no-op. It is kept for backwards compatibility and will be removed
	// in a future release.
	UnstableResp3 bool
}

func ( *RingOptions) () {
	if .NewClient == nil {
		.NewClient = func( *Options) *Client {
			return NewClient()
		}
	}

	if .HeartbeatFrequency == 0 {
		.HeartbeatFrequency = 500 * time.Millisecond
	}

	if .HeartbeatFn == nil {
		.HeartbeatFn = defaultHeartbeatFn
	}

	if .NewConsistentHash == nil {
		.NewConsistentHash = newRendezvous
	}

	switch .MaxRetries {
	case -1:
		.MaxRetries = 0
	case 0:
		.MaxRetries = 3
	}
	switch .MinRetryBackoff {
	case -1:
		.MinRetryBackoff = 0
	case 0:
		.MinRetryBackoff = 10 * time.Millisecond
	}
	switch .MaxRetryBackoff {
	case -1:
		.MaxRetryBackoff = 0
	case 0:
		.MaxRetryBackoff = time.Second
	}

	if .ReadBufferSize == 0 {
		.ReadBufferSize = proto.DefaultBufferSize
	}
	if .WriteBufferSize == 0 {
		.WriteBufferSize = proto.DefaultBufferSize
	}
}

func ( *RingOptions) () *Options {
	return &Options{
		ClientName: .ClientName,
		Dialer:     .Dialer,
		OnConnect:  .OnConnect,

		Protocol:                     .Protocol,
		Username:                     .Username,
		Password:                     .Password,
		CredentialsProvider:          .CredentialsProvider,
		CredentialsProviderContext:   .CredentialsProviderContext,
		StreamingCredentialsProvider: .StreamingCredentialsProvider,
		DB:                           .DB,

		MaxRetries: -1,

		DialTimeout:           .DialTimeout,
		DialerRetries:         .DialerRetries,
		DialerRetryTimeout:    .DialerRetryTimeout,
		DialerRetryBackoff:    .DialerRetryBackoff,
		ReadTimeout:           .ReadTimeout,
		WriteTimeout:          .WriteTimeout,
		ContextTimeoutEnabled: .ContextTimeoutEnabled,

		PoolFIFO:              .PoolFIFO,
		PoolSize:              .PoolSize,
		PoolTimeout:           .PoolTimeout,
		MinIdleConns:          .MinIdleConns,
		MaxIdleConns:          .MaxIdleConns,
		MaxActiveConns:        .MaxActiveConns,
		ConnMaxIdleTime:       .ConnMaxIdleTime,
		ConnMaxLifetime:       .ConnMaxLifetime,
		ConnMaxLifetimeJitter: .ConnMaxLifetimeJitter,
		ReadBufferSize:        .ReadBufferSize,
		WriteBufferSize:       .WriteBufferSize,

		PipelineReadBufferSize:  .PipelineReadBufferSize,
		PipelineWriteBufferSize: .PipelineWriteBufferSize,
		PipelinePoolSize:        .PipelinePoolSize,

		TLSConfig: .TLSConfig,
		Limiter:   .Limiter,

		DisableIdentity:  .DisableIdentity,
		DisableIndentity: .DisableIndentity,

		IdentitySuffix: .IdentitySuffix,
		UnstableResp3:  .UnstableResp3,
	}
}

//------------------------------------------------------------------------------

type ringShard struct {
	Client *Client
	down   atomic.Int32
	addr   string
}

func newRingShard( *RingOptions,  string) *ringShard {
	 := .clientOptions()
	.Addr = 

	 := &ringShard{
		Client: .NewClient(),
		addr:   ,
	}
	// Share the ring-wide HIMPORT fieldset registry so any shard connection
	// serving an HIMPORT SET can lazily replay the PREPARE.
	if .himport != nil {
		.Client.himport = .himport
	}
	return 
}

func ( *ringShard) () string {
	var  string
	if .IsUp() {
		 = "up"
	} else {
		 = "down"
	}
	return fmt.Sprintf("%s is %s", .Client, )
}

func ( *ringShard) () bool {
	const  = 3
	return .down.Load() >= 
}

func ( *ringShard) () bool {
	return !.IsDown()
}

// Vote votes to set shard state and returns true if state was changed.
func ( *ringShard) ( bool) bool {
	if  {
		 := .IsDown()
		.down.Store(0)
		return 
	}

	if .IsDown() {
		return false
	}

	.down.Add(1)
	return .IsDown()
}

//------------------------------------------------------------------------------

type ringSharding struct {
	opt *RingOptions

	mu        sync.RWMutex
	shards    *ringShards
	closed    bool
	hash      ConsistentHash
	numShard  int
	onNewNode []func(rdb *Client)

	// ensures exclusive access to SetAddrs so there is no need
	// to hold mu for the duration of potentially long shard creation
	setAddrsMu sync.Mutex
}

type ringShards struct {
	m    map[string]*ringShard
	list []*ringShard
}

func newRingSharding( *RingOptions) *ringSharding {
	 := &ringSharding{
		opt: ,
	}
	.SetAddrs(.Addrs)

	return 
}

func ( *ringSharding) ( func( *Client)) {
	.mu.Lock()
	.onNewNode = append(.onNewNode, )
	.mu.Unlock()
}

// SetAddrs replaces the shards in use, such that you can increase and
// decrease number of shards, that you use. It will reuse shards that
// existed before and close the ones that will not be used anymore.
func ( *ringSharding) ( map[string]string) {
	.setAddrsMu.Lock()
	defer .setAddrsMu.Unlock()

	 := func( map[string]*ringShard) {
		for ,  := range  {
			if  := .Client.Close();  != nil {
				internal.Logger.Printf(context.Background(), "shard.Close %s failed: %s", , )
			}
		}
	}

	.mu.RLock()
	if .closed {
		.mu.RUnlock()
		return
	}
	 := .shards
	 := .onNewNode
	.mu.RUnlock()

	, ,  := .newRingShards(, , )

	.mu.Lock()
	if .closed {
		()
		.mu.Unlock()
		return
	}
	.shards = 
	.rebalanceLocked()
	.mu.Unlock()

	()
}

func ( *ringSharding) (
	 map[string]string,  *ringShards,  []func( *Client),
) ( *ringShards, ,  map[string]*ringShard) {
	 = &ringShards{m: make(map[string]*ringShard, len())}
	 = make(map[string]*ringShard) // indexed by addr
	 = make(map[string]*ringShard)  // indexed by addr

	if  != nil {
		for ,  := range .list {
			[.addr] = 
		}
	}

	for ,  := range  {
		if ,  := [];  {
			.m[] = 
			delete(, )
		} else {
			 := newRingShard(.opt, )
			.m[] = 
			[] = 

			for ,  := range  {
				(.Client)
			}
		}
	}

	for ,  := range .m {
		.list = append(.list, )
	}

	return
}

// Warning: External exposure of `c.shards.list` may cause data races.
// So keep internal or implement deep copy if exposed.
func ( *ringSharding) () []*ringShard {
	.mu.RLock()
	defer .mu.RUnlock()

	if .closed {
		return nil
	}
	return .shards.list
}

func ( *ringSharding) ( string) string {
	 = hashtag.Key()

	var  string

	.mu.RLock()
	defer .mu.RUnlock()

	if .numShard > 0 {
		 = .hash.Get()
	}

	return 
}

func ( *ringSharding) ( string) (*ringShard, error) {
	 = hashtag.Key()

	.mu.RLock()
	defer .mu.RUnlock()

	if .closed {
		return nil, pool.ErrClosed
	}

	if .numShard == 0 {
		return nil, errRingShardsDown
	}

	 := .hash.Get()
	if  == "" {
		return nil, errRingShardsDown
	}
	return .shards.m[], nil
}

func ( *ringSharding) ( string) (*ringShard, error) {
	if  == "" {
		return .Random()
	}

	.mu.RLock()
	defer .mu.RUnlock()

	,  := .shards.m[]
	if ! {
		return nil, errors.New("redis: the shard is not in the ring")
	}

	return , nil
}

func ( *ringSharding) () (*ringShard, error) {
	return .GetByKey(strconv.Itoa(rand.Int()))
}

// Heartbeat monitors state of each shard in the ring.
func ( *ringSharding) ( context.Context,  time.Duration) {
	 := time.NewTicker()
	defer .Stop()

	for {
		select {
		case <-.C:
			var  bool

			// note: `c.List()` return a shadow copy of `[]*ringShard`.
			for ,  := range .List() {
				 := .opt.HeartbeatFn(, .Client)
				if .Vote() {
					internal.Logger.Printf(, "ring shard state changed: %s", )
					 = true
				}
			}

			if  {
				.mu.Lock()
				.rebalanceLocked()
				.mu.Unlock()
			}
		case <-.Done():
			return
		}
	}
}

// rebalanceLocked removes dead shards from the Ring.
// Requires c.mu locked.
func ( *ringSharding) () {
	if .closed {
		return
	}
	if .shards == nil {
		return
	}

	 := make([]string, 0, len(.shards.m))

	for ,  := range .shards.m {
		if .IsUp() {
			 = append(, )
		}
	}

	.hash = .opt.NewConsistentHash()
	.numShard = len()
}

func ( *ringSharding) () int {
	.mu.RLock()
	defer .mu.RUnlock()

	return .numShard
}

func ( *ringSharding) () error {
	.mu.Lock()
	defer .mu.Unlock()

	if .closed {
		return nil
	}
	.closed = true

	var  error

	for ,  := range .shards.list {
		if  := .Client.Close();  != nil &&  == nil {
			 = 
		}
	}

	.hash = nil
	.shards = nil
	.numShard = 0

	return 
}

//------------------------------------------------------------------------------

// Ring is a Redis client that uses consistent hashing to distribute
// keys across multiple Redis servers (shards). It's safe for
// concurrent use by multiple goroutines.
//
// Ring monitors the state of each shard and removes dead shards from
// the ring. When a shard comes online it is added back to the ring. This
// gives you maximum availability and partition tolerance, but no
// consistency between different shards or even clients. Each client
// uses shards that are available to the client and does not do any
// coordination when shard state is changed.
//
// Ring should be used when you need multiple Redis servers for caching
// and can tolerate losing data when one of the servers dies.
// Otherwise you should use Redis Cluster.
type Ring struct {
	cmdable
	hooksMixin

	opt               *RingOptions
	sharding          *ringSharding
	cmdsInfoCache     *cmdsInfoCache
	heartbeatCancelFn context.CancelFunc
}

// NewRing returns a Redis Ring client to the Redis Server specified by RingOptions.
// Passing nil RingOptions will cause a panic.
func ( *RingOptions) *Ring {
	if  == nil {
		panic("redis: NewRing nil options")
	}
	// Shallow-copy the options: the ring-wide HIMPORT registry is carried
	// through them to shard construction, and reusing one caller-owned
	// RingOptions across several rings must not make the rings share (or
	// clobber each other's) registry.
	 := *
	 = &
	.init()
	// The registry must exist before the first shard is created; shards
	// adopt it in newRingShard.
	.himport = newHImportRegistry()

	,  := context.WithCancel(context.Background())

	 := Ring{
		opt:               ,
		sharding:          newRingSharding(),
		heartbeatCancelFn: ,
	}

	.cmdsInfoCache = newCmdsInfoCache(.cmdsInfo)
	.cmdable = .Process

	.initHooks(hooks{
		process: .process,
		pipeline: func( context.Context,  []Cmder) error {
			return .generalProcessPipeline(, , false)
		},
		txPipeline: func( context.Context,  []Cmder) error {
			return .generalProcessPipeline(, , true)
		},
	})

	go .sharding.Heartbeat(, .HeartbeatFrequency)

	return &
}

func ( *Ring) ( map[string]string) {
	.sharding.SetAddrs()
}

func ( *Ring) ( context.Context,  Cmder) error {
	 := .processHook(, )
	.SetErr()
	return 
}

// Options returns read-only *RingOptions that were used to create the client.
// Any alteration of the returned *RingOptions may result in undefined behaviour.
func ( *Ring) () *RingOptions {
	return .opt
}

func ( *Ring) ( int) time.Duration {
	return internal.RetryBackoff(, .opt.MinRetryBackoff, .opt.MaxRetryBackoff)
}

// PoolStats returns accumulated connection pool stats.
func ( *Ring) () *PoolStats {
	// note: `c.List()` return a shadow copy of `[]*ringShard`.
	 := .sharding.List()
	var  PoolStats
	var  pool.Stats
	 := false
	for ,  := range  {
		 := .Client.connPool.Stats()
		.Hits += .Hits
		.Misses += .Misses
		.Timeouts += .Timeouts
		.WaitCount += .WaitCount
		.WaitDurationNs += .WaitDurationNs
		.TotalConns += .TotalConns
		.IdleConns += .IdleConns
		.StaleConns += .StaleConns

		// Each shard now creates the dedicated pipeline pool by default; fold its
		// stats into acc.PipelineStats so ring monitoring reflects it too.
		if  := .Client.getPipelinePool();  != nil {
			 := .Stats()
			.Hits += .Hits
			.Misses += .Misses
			.Timeouts += .Timeouts
			.WaitCount += .WaitCount
			.WaitDurationNs += .WaitDurationNs
			.TotalConns += .TotalConns
			.IdleConns += .IdleConns
			.StaleConns += .StaleConns
			 = true
		}
	}
	if  {
		.PipelineStats = &
	}
	return &
}

// Len returns the current number of shards in the ring.
func ( *Ring) () int {
	return .sharding.Len()
}

// Subscribe subscribes the client to the specified channels.
func ( *Ring) ( context.Context,  ...string) *PubSub {
	if len() == 0 {
		panic("at least one channel is required")
	}

	,  := .sharding.GetByKey([0])
	if  != nil {
		// TODO: return PubSub with sticky error
		panic()
	}
	return .Client.Subscribe(, ...)
}

// PSubscribe subscribes the client to the given patterns.
func ( *Ring) ( context.Context,  ...string) *PubSub {
	if len() == 0 {
		panic("at least one channel is required")
	}

	,  := .sharding.GetByKey([0])
	if  != nil {
		// TODO: return PubSub with sticky error
		panic()
	}
	return .Client.PSubscribe(, ...)
}

// SSubscribe Subscribes the client to the specified shard channels.
func ( *Ring) ( context.Context,  ...string) *PubSub {
	if len() == 0 {
		panic("at least one channel is required")
	}
	,  := .sharding.GetByKey([0])
	if  != nil {
		// TODO: return PubSub with sticky error
		panic()
	}
	return .Client.SSubscribe(, ...)
}

// Publish posts the message to the channel
func ( *Ring) ( context.Context,  string,  interface{}) *IntCmd {
	,  := .sharding.GetByKey()
	if  != nil {
		 := NewIntCmd(, "publish", , )
		.SetErr()
		return 
	}
	return .Client.Publish(, , )
}

func ( *Ring) ( func( *Client)) {
	.sharding.OnNewNode()
}

// ForEachShard concurrently calls the fn on each live shard in the ring.
// It returns the first error if any.
func ( *Ring) (
	 context.Context,
	 func( context.Context,  *Client) error,
) error {
	// note: `c.List()` return a shadow copy of `[]*ringShard`.
	 := .sharding.List()
	var  sync.WaitGroup
	 := make(chan error, 1)
	for ,  := range  {
		if .IsDown() {
			continue
		}

		.Add(1)
		go func( *ringShard) {
			defer .Done()
			 := (, .Client)
			if  != nil {
				select {
				case  <- :
				default:
				}
			}
		}()
	}
	.Wait()

	select {
	case  := <-:
		return 
	default:
		return nil
	}
}

func ( *Ring) ( context.Context) (map[string]*CommandInfo, error) {
	// note: `c.List()` return a shadow copy of `[]*ringShard`.
	 := .sharding.List()
	var  error
	for ,  := range  {
		,  := .Client.Command().Result()
		if  == nil {
			return , nil
		}
		if  == nil {
			 = 
		}
	}
	if  == nil {
		return nil, errRingShardsDown
	}
	return nil, 
}

func ( *Ring) ( Cmder) (*ringShard, error) {
	// TODO: populate cmdsInfoCache lazily (via cmdsInfoCache.Get) so that
	// the warm-cache branch in cmdFirstKeyPosWithInfo is reachable for Ring,
	// mirroring how ClusterClient.cmdInfo works. For now pass nil
	 := cmdFirstKeyPosWithInfo(, nil)
	if  == 0 {
		return .sharding.Random()
	}
	 := .stringArg()
	return .sharding.GetByKey()
}

func ( *Ring) ( context.Context,  Cmder) error {
	var  error
	for  := 0;  <= .opt.MaxRetries; ++ {
		if  > 0 {
			if  := internal.Sleep(, .retryBackoff());  != nil {
				return 
			}
		}

		,  := .cmdShard()
		if  != nil {
			return 
		}

		 = .Client.Process(, )
		if  == nil || !shouldRetry(, .readTimeout() == nil) || .NoRetry() {
			return 
		}
	}
	return 
}

func ( *Ring) ( context.Context,  func(Pipeliner) error) ([]Cmder, error) {
	return .Pipeline().Pipelined(, )
}

func ( *Ring) () Pipeliner {
	 := Pipeline{
		exec: pipelineExecer(.processPipelineHook),
	}
	.init()
	return &
}

// ErrRingAutoPipelineUnsupported is returned by Ring's AutoPipeline /
// AsyncAutoPipeline (and their WithOptions forms); check for it with
// errors.Is. Autopipelining is not implemented for Ring; use the per-shard
// clients or a ClusterClient. Ring is part of the UniversalClient
// interface, so these methods exist to satisfy it and fail explicitly rather
// than being silently absent.
var ErrRingAutoPipelineUnsupported = errors.New("redis: AutoPipeline is not supported by Ring")

// AutoPipeline is not supported by Ring; it returns ErrRingAutoPipelineUnsupported.
func ( *Ring) () (*AutoPipeliner, error) {
	return .AutoPipelineWithOptions(nil)
}

// AutoPipelineWithOptions is not supported by Ring; it returns ErrRingAutoPipelineUnsupported.
func ( *Ring) ( *AutoPipelineOptions) (*AutoPipeliner, error) {
	return nil, ErrRingAutoPipelineUnsupported
}

// AsyncAutoPipeline is not supported by Ring; it returns ErrRingAutoPipelineUnsupported.
func ( *Ring) () (*AutoPipeliner, error) {
	return .AsyncAutoPipelineWithOptions(nil)
}

// AsyncAutoPipelineWithOptions is not supported by Ring; it returns ErrRingAutoPipelineUnsupported.
func ( *Ring) ( *AutoPipelineOptions) (*AutoPipeliner, error) {
	return nil, ErrRingAutoPipelineUnsupported
}

func ( *Ring) ( context.Context,  func(Pipeliner) error) ([]Cmder, error) {
	return .TxPipeline().Pipelined(, )
}

func ( *Ring) () Pipeliner {
	 := Pipeline{
		exec: func( context.Context,  []Cmder) error {
			 = wrapMultiExec(, )
			return .processTxPipelineHook(, )
		},
	}
	.init()
	return &
}

func ( *Ring) (
	 context.Context,  []Cmder,  bool,
) error {
	if  {
		// Trim multi .. exec.
		 = [1 : len()-1]
	}

	 := make(map[string][]Cmder)

	for ,  := range  {
		 := .stringArg(cmdFirstKeyPosWithInfo(, nil))
		if  != "" {
			 = .sharding.Hash()
		}
		[] = append([], )
	}

	var  sync.WaitGroup
	 := make(chan error, len())

	for ,  := range  {
		.Add(1)
		go func( string,  []Cmder) {
			defer .Done()

			// TODO: retry?
			,  := .sharding.GetByName()
			if  != nil {
				setCmdsErr(, )
				return
			}

			 := .Client.processPipelineHook
			if  {
				 = wrapMultiExec(, )
				 = .Client.processTxPipelineHook
			}

			if  = (, );  != nil {
				 <- 
			}
		}(, )
	}

	.Wait()
	close()

	if  := <-;  != nil {
		return 
	}
	return cmdsFirstErr()
}

func ( *Ring) ( context.Context,  func(*Tx) error,  ...string) error {
	if len() == 0 {
		return fmt.Errorf("redis: Watch requires at least one key")
	}

	var  []*ringShard

	for ,  := range  {
		if  != "" {
			,  := .sharding.GetByKey()
			if  != nil {
				return 
			}

			 = append(, )
		}
	}

	if len() == 0 {
		return fmt.Errorf("redis: Watch requires at least one shard")
	}

	if len() > 1 {
		for ,  := range [1:] {
			if .Client != [0].Client {
				 := fmt.Errorf("redis: Watch requires all keys to be in the same shard")
				return 
			}
		}
	}

	return [0].Client.Watch(, , ...)
}

// Close closes the ring client, releasing any open resources.
//
// It is rare to Close a Ring, as the Ring is meant to be long-lived
// and shared between many goroutines.
func ( *Ring) () error {
	.heartbeatCancelFn()

	return .sharding.Close()
}

// GetShardClients returns a list of all shard clients in the ring.
// This can be used to create dedicated connections (e.g., PubSub) for each shard.
func ( *Ring) () []*Client {
	 := .sharding.List()
	 := make([]*Client, 0, len())
	for ,  := range  {
		if .IsUp() {
			 = append(, .Client)
		}
	}
	return 
}

// GetShardClientForKey returns the shard client that would handle the given key.
// This can be used to determine which shard a particular key/channel would be routed to.
func ( *Ring) ( string) (*Client, error) {
	,  := .sharding.GetByKey()
	if  != nil {
		return nil, 
	}
	return .Client, nil
}