package redis

import (
	
	
	
	
	
	
	

	
	
	
)

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

// FailoverOptions are used to configure a failover client and should
// be passed to NewFailoverClient.
type FailoverOptions struct {
	// The master name.
	MasterName string
	// A seed list of host:port addresses of sentinel nodes.
	SentinelAddrs []string

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

	// If specified with SentinelPassword, enables ACL-based authentication (via
	// AUTH <user> <pass>).
	SentinelUsername string
	// Sentinel password from "requirepass <password>" (if enabled) in Sentinel
	// configuration, or, if SentinelUsername is also supplied, used for ACL-based
	// authentication.
	SentinelPassword string

	// Allows routing read-only commands to the closest master or replica node.
	// This option only works with NewFailoverClusterClient.
	RouteByLatency bool
	// Allows routing read-only commands to the random master or replica node.
	// This option only works with NewFailoverClusterClient.
	RouteRandomly bool

	// Route all commands to replica read-only nodes.
	ReplicaOnly bool

	// Use replicas disconnected with master when cannot get connected replicas
	// Now, this option only works in RandomReplicaAddr function.
	UseDisconnectedReplicas bool

	// 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

	Username string
	Password string
	DB       int

	MaxRetries      int
	MinRetryBackoff time.Duration
	MaxRetryBackoff time.Duration

	DialTimeout           time.Duration
	ReadTimeout           time.Duration
	WriteTimeout          time.Duration
	ContextTimeoutEnabled bool

	PoolFIFO bool

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

	TLSConfig *tls.Config
}

func ( *FailoverOptions) () *Options {
	return &Options{
		Addr:       "FailoverClient",
		ClientName: .ClientName,

		Dialer:    .Dialer,
		OnConnect: .OnConnect,

		DB:       .DB,
		Username: .Username,
		Password: .Password,

		MaxRetries:      .MaxRetries,
		MinRetryBackoff: .MinRetryBackoff,
		MaxRetryBackoff: .MaxRetryBackoff,

		DialTimeout:           .DialTimeout,
		ReadTimeout:           .ReadTimeout,
		WriteTimeout:          .WriteTimeout,
		ContextTimeoutEnabled: .ContextTimeoutEnabled,

		PoolFIFO:        .PoolFIFO,
		PoolSize:        .PoolSize,
		PoolTimeout:     .PoolTimeout,
		MinIdleConns:    .MinIdleConns,
		MaxIdleConns:    .MaxIdleConns,
		ConnMaxIdleTime: .ConnMaxIdleTime,
		ConnMaxLifetime: .ConnMaxLifetime,

		TLSConfig: .TLSConfig,
	}
}

func ( *FailoverOptions) ( string) *Options {
	return &Options{
		Addr:       ,
		ClientName: .ClientName,

		Dialer:    .Dialer,
		OnConnect: .OnConnect,

		DB:       0,
		Username: .SentinelUsername,
		Password: .SentinelPassword,

		MaxRetries:      .MaxRetries,
		MinRetryBackoff: .MinRetryBackoff,
		MaxRetryBackoff: .MaxRetryBackoff,

		DialTimeout:  .DialTimeout,
		ReadTimeout:  .ReadTimeout,
		WriteTimeout: .WriteTimeout,

		PoolFIFO:        .PoolFIFO,
		PoolSize:        .PoolSize,
		PoolTimeout:     .PoolTimeout,
		MinIdleConns:    .MinIdleConns,
		MaxIdleConns:    .MaxIdleConns,
		ConnMaxIdleTime: .ConnMaxIdleTime,
		ConnMaxLifetime: .ConnMaxLifetime,

		TLSConfig: .TLSConfig,
	}
}

func ( *FailoverOptions) () *ClusterOptions {
	return &ClusterOptions{
		ClientName: .ClientName,

		Dialer:    .Dialer,
		OnConnect: .OnConnect,

		Username: .Username,
		Password: .Password,

		MaxRedirects: .MaxRetries,

		RouteByLatency: .RouteByLatency,
		RouteRandomly:  .RouteRandomly,

		MinRetryBackoff: .MinRetryBackoff,
		MaxRetryBackoff: .MaxRetryBackoff,

		DialTimeout:  .DialTimeout,
		ReadTimeout:  .ReadTimeout,
		WriteTimeout: .WriteTimeout,

		PoolFIFO:        .PoolFIFO,
		PoolSize:        .PoolSize,
		PoolTimeout:     .PoolTimeout,
		MinIdleConns:    .MinIdleConns,
		MaxIdleConns:    .MaxIdleConns,
		ConnMaxIdleTime: .ConnMaxIdleTime,
		ConnMaxLifetime: .ConnMaxLifetime,

		TLSConfig: .TLSConfig,
	}
}

// NewFailoverClient returns a Redis client that uses Redis Sentinel
// for automatic failover. It's safe for concurrent use by multiple
// goroutines.
func ( *FailoverOptions) *Client {
	if .RouteByLatency {
		panic("to route commands by latency, use NewFailoverClusterClient")
	}
	if .RouteRandomly {
		panic("to route commands randomly, use NewFailoverClusterClient")
	}

	 := make([]string, len(.SentinelAddrs))
	copy(, .SentinelAddrs)

	rand.Shuffle(len(), func(,  int) {
		[], [] = [], []
	})

	 := &sentinelFailover{
		opt:           ,
		sentinelAddrs: ,
	}

	 := .clientOptions()
	.Dialer = masterReplicaDialer()
	.init()

	var  *pool.ConnPool

	 := &Client{
		baseClient: &baseClient{
			opt: ,
		},
	}
	.init()

	 = newConnPool(, .dialHook)
	.connPool = 
	.onClose = .Close

	.mu.Lock()
	.onFailover = func( context.Context,  string) {
		_ = .Filter(func( *pool.Conn) bool {
			return .RemoteAddr().String() != 
		})
	}
	.mu.Unlock()

	return 
}

func masterReplicaDialer(
	 *sentinelFailover,
) func( context.Context, ,  string) (net.Conn, error) {
	return func( context.Context, ,  string) (net.Conn, error) {
		var  string
		var  error

		if .opt.ReplicaOnly {
			,  = .RandomReplicaAddr()
		} else {
			,  = .MasterAddr()
			if  == nil {
				.trySwitchMaster(, )
			}
		}
		if  != nil {
			return nil, 
		}
		if .opt.Dialer != nil {
			return .opt.Dialer(, , )
		}

		 := &net.Dialer{
			Timeout:   .opt.DialTimeout,
			KeepAlive: 5 * time.Minute,
		}
		if .opt.TLSConfig == nil {
			return .DialContext(, , )
		}
		return tls.DialWithDialer(, , , .opt.TLSConfig)
	}
}

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

// SentinelClient is a client for a Redis Sentinel.
type SentinelClient struct {
	*baseClient
	hooksMixin
}

func ( *Options) *SentinelClient {
	.init()
	 := &SentinelClient{
		baseClient: &baseClient{
			opt: ,
		},
	}

	.initHooks(hooks{
		dial:    .baseClient.dial,
		process: .baseClient.process,
	})
	.connPool = newConnPool(, .dialHook)

	return 
}

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

func ( *SentinelClient) () *PubSub {
	 := &PubSub{
		opt: .opt,

		newConn: func( context.Context,  []string) (*pool.Conn, error) {
			return .newConn()
		},
		closeConn: .connPool.CloseConn,
	}
	.init()
	return 
}

// Ping is used to test if a connection is still alive, or to
// measure latency.
func ( *SentinelClient) ( context.Context) *StringCmd {
	 := NewStringCmd(, "ping")
	_ = .Process(, )
	return 
}

// Subscribe subscribes the client to the specified channels.
// Channels can be omitted to create empty subscription.
func ( *SentinelClient) ( context.Context,  ...string) *PubSub {
	 := .pubSub()
	if len() > 0 {
		_ = .Subscribe(, ...)
	}
	return 
}

// PSubscribe subscribes the client to the given patterns.
// Patterns can be omitted to create empty subscription.
func ( *SentinelClient) ( context.Context,  ...string) *PubSub {
	 := .pubSub()
	if len() > 0 {
		_ = .PSubscribe(, ...)
	}
	return 
}

func ( *SentinelClient) ( context.Context,  string) *StringSliceCmd {
	 := NewStringSliceCmd(, "sentinel", "get-master-addr-by-name", )
	_ = .Process(, )
	return 
}

func ( *SentinelClient) ( context.Context,  string) *MapStringStringSliceCmd {
	 := NewMapStringStringSliceCmd(, "sentinel", "sentinels", )
	_ = .Process(, )
	return 
}

// Failover forces a failover as if the master was not reachable, and without
// asking for agreement to other Sentinels.
func ( *SentinelClient) ( context.Context,  string) *StatusCmd {
	 := NewStatusCmd(, "sentinel", "failover", )
	_ = .Process(, )
	return 
}

// Reset resets all the masters with matching name. The pattern argument is a
// glob-style pattern. The reset process clears any previous state in a master
// (including a failover in progress), and removes every replica and sentinel
// already discovered and associated with the master.
func ( *SentinelClient) ( context.Context,  string) *IntCmd {
	 := NewIntCmd(, "sentinel", "reset", )
	_ = .Process(, )
	return 
}

// FlushConfig forces Sentinel to rewrite its configuration on disk, including
// the current Sentinel state.
func ( *SentinelClient) ( context.Context) *StatusCmd {
	 := NewStatusCmd(, "sentinel", "flushconfig")
	_ = .Process(, )
	return 
}

// Master shows the state and info of the specified master.
func ( *SentinelClient) ( context.Context,  string) *MapStringStringCmd {
	 := NewMapStringStringCmd(, "sentinel", "master", )
	_ = .Process(, )
	return 
}

// Masters shows a list of monitored masters and their state.
func ( *SentinelClient) ( context.Context) *SliceCmd {
	 := NewSliceCmd(, "sentinel", "masters")
	_ = .Process(, )
	return 
}

// Replicas shows a list of replicas for the specified master and their state.
func ( *SentinelClient) ( context.Context,  string) *MapStringStringSliceCmd {
	 := NewMapStringStringSliceCmd(, "sentinel", "replicas", )
	_ = .Process(, )
	return 
}

// CkQuorum checks if the current Sentinel configuration is able to reach the
// quorum needed to failover a master, and the majority needed to authorize the
// failover. This command should be used in monitoring systems to check if a
// Sentinel deployment is ok.
func ( *SentinelClient) ( context.Context,  string) *StringCmd {
	 := NewStringCmd(, "sentinel", "ckquorum", )
	_ = .Process(, )
	return 
}

// Monitor tells the Sentinel to start monitoring a new master with the specified
// name, ip, port, and quorum.
func ( *SentinelClient) ( context.Context, , , ,  string) *StringCmd {
	 := NewStringCmd(, "sentinel", "monitor", , , , )
	_ = .Process(, )
	return 
}

// Set is used in order to change configuration parameters of a specific master.
func ( *SentinelClient) ( context.Context, , ,  string) *StringCmd {
	 := NewStringCmd(, "sentinel", "set", , , )
	_ = .Process(, )
	return 
}

// Remove is used in order to remove the specified master: the master will no
// longer be monitored, and will totally be removed from the internal state of
// the Sentinel.
func ( *SentinelClient) ( context.Context,  string) *StringCmd {
	 := NewStringCmd(, "sentinel", "remove", )
	_ = .Process(, )
	return 
}

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

type sentinelFailover struct {
	opt *FailoverOptions

	sentinelAddrs []string

	onFailover func(ctx context.Context, addr string)
	onUpdate   func(ctx context.Context)

	mu          sync.RWMutex
	_masterAddr string
	sentinel    *SentinelClient
	pubsub      *PubSub
}

func ( *sentinelFailover) () error {
	.mu.Lock()
	defer .mu.Unlock()
	if .sentinel != nil {
		return .closeSentinel()
	}
	return nil
}

func ( *sentinelFailover) () error {
	 := .pubsub.Close()
	.pubsub = nil

	 := .sentinel.Close()
	if  != nil &&  == nil {
		 = 
	}
	.sentinel = nil

	return 
}

func ( *sentinelFailover) ( context.Context) (string, error) {
	if .opt == nil {
		return "", errors.New("opt is nil")
	}

	,  := .replicaAddrs(, false)
	if  != nil {
		return "", 
	}

	if len() == 0 && .opt.UseDisconnectedReplicas {
		,  = .replicaAddrs(, true)
		if  != nil {
			return "", 
		}
	}

	if len() == 0 {
		return .MasterAddr()
	}
	return [rand.Intn(len())], nil
}

func ( *sentinelFailover) ( context.Context) (string, error) {
	.mu.RLock()
	 := .sentinel
	.mu.RUnlock()

	if  != nil {
		,  := .getMasterAddr(, )
		if  != nil {
			if errors.Is(, context.Canceled) || errors.Is(, context.DeadlineExceeded) {
				return "", 
			}
			// Continue on other errors
			internal.Logger.Printf(, "sentinel: GetMasterAddrByName name=%q failed: %s",
				.opt.MasterName, )
		} else {
			return , nil
		}
	}

	.mu.Lock()
	defer .mu.Unlock()

	if .sentinel != nil {
		,  := .getMasterAddr(, .sentinel)
		if  != nil {
			_ = .closeSentinel()
			if errors.Is(, context.Canceled) || errors.Is(, context.DeadlineExceeded) {
				return "", 
			}
			// Continue on other errors
			internal.Logger.Printf(, "sentinel: GetMasterAddrByName name=%q failed: %s",
				.opt.MasterName, )
		} else {
			return , nil
		}
	}

	for ,  := range .sentinelAddrs {
		 := NewSentinelClient(.opt.sentinelOptions())

		,  := .GetMasterAddrByName(, .opt.MasterName).Result()
		if  != nil {
			_ = .Close()
			if errors.Is(, context.Canceled) || errors.Is(, context.DeadlineExceeded) {
				return "", 
			}
			internal.Logger.Printf(, "sentinel: GetMasterAddrByName master=%q failed: %s",
				.opt.MasterName, )
			continue
		}

		// Push working sentinel to the top.
		.sentinelAddrs[0], .sentinelAddrs[] = .sentinelAddrs[], .sentinelAddrs[0]
		.setSentinel(, )

		 := net.JoinHostPort([0], [1])
		return , nil
	}

	return "", errors.New("redis: all sentinels specified in configuration are unreachable")
}

func ( *sentinelFailover) ( context.Context,  bool) ([]string, error) {
	.mu.RLock()
	 := .sentinel
	.mu.RUnlock()

	if  != nil {
		,  := .getReplicaAddrs(, )
		if  != nil {
			if errors.Is(, context.Canceled) || errors.Is(, context.DeadlineExceeded) {
				return nil, 
			}
			// Continue on other errors
			internal.Logger.Printf(, "sentinel: Replicas name=%q failed: %s",
				.opt.MasterName, )
		} else if len() > 0 {
			return , nil
		}
	}

	.mu.Lock()
	defer .mu.Unlock()

	if .sentinel != nil {
		,  := .getReplicaAddrs(, .sentinel)
		if  != nil {
			_ = .closeSentinel()
			if errors.Is(, context.Canceled) || errors.Is(, context.DeadlineExceeded) {
				return nil, 
			}
			// Continue on other errors
			internal.Logger.Printf(, "sentinel: Replicas name=%q failed: %s",
				.opt.MasterName, )
		} else if len() > 0 {
			return , nil
		} else {
			// No error and no replicas.
			_ = .closeSentinel()
		}
	}

	var  bool

	for ,  := range .sentinelAddrs {
		 := NewSentinelClient(.opt.sentinelOptions())

		,  := .Replicas(, .opt.MasterName).Result()
		if  != nil {
			_ = .Close()
			if errors.Is(, context.Canceled) || errors.Is(, context.DeadlineExceeded) {
				return nil, 
			}
			internal.Logger.Printf(, "sentinel: Replicas master=%q failed: %s",
				.opt.MasterName, )
			continue
		}
		 = true
		 := parseReplicaAddrs(, )
		if len() == 0 {
			continue
		}
		// Push working sentinel to the top.
		.sentinelAddrs[0], .sentinelAddrs[] = .sentinelAddrs[], .sentinelAddrs[0]
		.setSentinel(, )

		return , nil
	}

	if  {
		return []string{}, nil
	}
	return []string{}, errors.New("redis: all sentinels specified in configuration are unreachable")
}

func ( *sentinelFailover) ( context.Context,  *SentinelClient) (string, error) {
	,  := .GetMasterAddrByName(, .opt.MasterName).Result()
	if  != nil {
		return "", 
	}
	return net.JoinHostPort([0], [1]), nil
}

func ( *sentinelFailover) ( context.Context,  *SentinelClient) ([]string, error) {
	,  := .Replicas(, .opt.MasterName).Result()
	if  != nil {
		internal.Logger.Printf(, "sentinel: Replicas name=%q failed: %s",
			.opt.MasterName, )
		return nil, 
	}
	return parseReplicaAddrs(, false), nil
}

func parseReplicaAddrs( []map[string]string,  bool) []string {
	 := make([]string, 0, len())
	for ,  := range  {
		 := false
		if ,  := ["flags"];  {
			for ,  := range strings.Split(, ",") {
				switch  {
				case "s_down", "o_down":
					 = true
				case "disconnected":
					if ! {
						 = true
					}
				}
			}
		}
		if ! && ["ip"] != "" && ["port"] != "" {
			 = append(, net.JoinHostPort(["ip"], ["port"]))
		}
	}

	return 
}

func ( *sentinelFailover) ( context.Context,  string) {
	.mu.RLock()
	 := ._masterAddr //nolint:ifshort
	.mu.RUnlock()

	if  ==  {
		return
	}

	.mu.Lock()
	defer .mu.Unlock()

	if  == ._masterAddr {
		return
	}
	._masterAddr = 

	internal.Logger.Printf(, "sentinel: new master=%q addr=%q",
		.opt.MasterName, )
	if .onFailover != nil {
		.onFailover(, )
	}
}

func ( *sentinelFailover) ( context.Context,  *SentinelClient) {
	if .sentinel != nil {
		panic("not reached")
	}
	.sentinel = 
	.discoverSentinels()

	.pubsub = .Subscribe(, "+switch-master", "+replica-reconf-done")
	go .listen(.pubsub)
}

func ( *sentinelFailover) ( context.Context) {
	,  := .sentinel.Sentinels(, .opt.MasterName).Result()
	if  != nil {
		internal.Logger.Printf(, "sentinel: Sentinels master=%q failed: %s", .opt.MasterName, )
		return
	}
	for ,  := range  {
		,  := ["ip"]
		if ! {
			continue
		}
		,  := ["port"]
		if ! {
			continue
		}
		if  != "" &&  != "" {
			 := net.JoinHostPort(, )
			if !contains(.sentinelAddrs, ) {
				internal.Logger.Printf(, "sentinel: discovered new sentinel=%q for master=%q",
					, .opt.MasterName)
				.sentinelAddrs = append(.sentinelAddrs, )
			}
		}
	}
}

func ( *sentinelFailover) ( *PubSub) {
	 := context.TODO()

	if .onUpdate != nil {
		.onUpdate()
	}

	 := .Channel()
	for  := range  {
		if .Channel == "+switch-master" {
			 := strings.Split(.Payload, " ")
			if [0] != .opt.MasterName {
				internal.Logger.Printf(.getContext(), "sentinel: ignore addr for master=%q", [0])
				continue
			}
			 := net.JoinHostPort([3], [4])
			.trySwitchMaster(.getContext(), )
		}

		if .onUpdate != nil {
			.onUpdate()
		}
	}
}

func contains( []string,  string) bool {
	for ,  := range  {
		if  ==  {
			return true
		}
	}
	return false
}

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

// NewFailoverClusterClient returns a client that supports routing read-only commands
// to a replica node.
func ( *FailoverOptions) *ClusterClient {
	 := make([]string, len(.SentinelAddrs))
	copy(, .SentinelAddrs)

	 := &sentinelFailover{
		opt:           ,
		sentinelAddrs: ,
	}

	 := .clusterOptions()
	.ClusterSlots = func( context.Context) ([]ClusterSlot, error) {
		,  := .MasterAddr()
		if  != nil {
			return nil, 
		}

		 := []ClusterNode{{
			Addr: ,
		}}

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

		for ,  := range  {
			 = append(, ClusterNode{
				Addr: ,
			})
		}

		 := []ClusterSlot{
			{
				Start: 0,
				End:   16383,
				Nodes: ,
			},
		}
		return , nil
	}

	 := NewClusterClient()

	.mu.Lock()
	.onUpdate = func( context.Context) {
		.ReloadState()
	}
	.mu.Unlock()

	return 
}