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
	// RouteByLatencyTolerance is passed through to ClusterOptions; see its documentation.
	RouteByLatencyTolerance time.Duration
	// 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

	Protocol int
	Username string
	Password string

	// Push notifications are always enabled for RESP3 connections
	// 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

	// 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, with its own
	// (typically larger) buffers. See the same-named fields on Options for
	// details. NewFailoverClient creates this pool by default; set
	// PipelinePoolSize < 0 to opt out (pipelines then run on the main pool).
	PipelineReadBufferSize  int
	PipelineWriteBufferSize int
	PipelinePoolSize        int

	// AutoPipelineOptions is the default config for the client's autopipeliner
	// faces. See Options.AutoPipelineOptions.
	AutoPipelineOptions *AutoPipelineOptions

	PoolFIFO bool

	PoolSize int

	// MaxConcurrentDials is the maximum number of concurrent connection creation goroutines.
	// If <= 0, defaults to PoolSize. If > PoolSize, it will be capped at PoolSize.
	MaxConcurrentDials int

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

	TLSConfig *tls.Config

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

	// FailingTimeoutSeconds is the timeout in seconds for marking a cluster node as failing.
	// When a node is marked as failing, it will be avoided for this duration.
	// Only applies to failover cluster clients. Default is 15 seconds.
	FailingTimeoutSeconds int

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

	// PushNotificationProcessor is the processor for handling push notifications.
	// If nil, a default processor will be created for RESP3 connections.
	PushNotificationProcessor push.NotificationProcessor

	// MaintNotificationsConfig is not supported for FailoverClients at the moment
	// MaintNotificationsConfig provides custom configuration for maintnotifications upgrades.
	// When MaintNotificationsConfig.Mode is not "disabled", the client will handle
	// upgrade notifications gracefully and manage connection/pool state transitions
	// seamlessly. Requires Protocol: 3 (RESP3) for push notifications.
	// If nil, maintnotifications upgrades are disabled.
	// (however if Mode is nil, it defaults to "auto" - enable if server supports it)
	// MaintNotificationsConfig *maintnotifications.Config
}

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

		Dialer:    .Dialer,
		OnConnect: .OnConnect,

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

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

		ReadBufferSize:  .ReadBufferSize,
		WriteBufferSize: .WriteBufferSize,

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

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

		ContextTimeoutEnabled: .ContextTimeoutEnabled,

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

		TLSConfig: .TLSConfig,

		DisableIdentity:  .DisableIdentity,
		DisableIndentity: .DisableIndentity,

		IdentitySuffix:            .IdentitySuffix,
		UnstableResp3:             .UnstableResp3,
		PushNotificationProcessor: .PushNotificationProcessor,

		MaintNotificationsConfig: &maintnotifications.Config{
			Mode: maintnotifications.ModeDisabled,
		},
	}
}

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,

		// The sentinel client uses a 4KiB read/write buffer size.
		ReadBufferSize:  4096,
		WriteBufferSize: 4096,

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

		ContextTimeoutEnabled: .ContextTimeoutEnabled,

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

		TLSConfig: .TLSConfig,

		DisableIdentity:  .DisableIdentity,
		DisableIndentity: .DisableIndentity,

		IdentitySuffix:            .IdentitySuffix,
		UnstableResp3:             .UnstableResp3,
		PushNotificationProcessor: .PushNotificationProcessor,

		MaintNotificationsConfig: &maintnotifications.Config{
			Mode: maintnotifications.ModeDisabled,
		},
	}
}

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

		Dialer:    .Dialer,
		OnConnect: .OnConnect,

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

		MaxRedirects: .MaxRetries,

		ReadOnly:                .ReplicaOnly,
		RouteByLatency:          .RouteByLatency,
		RouteByLatencyTolerance: .RouteByLatencyTolerance,
		RouteRandomly:           .RouteRandomly,

		MinRetryBackoff: .MinRetryBackoff,
		MaxRetryBackoff: .MaxRetryBackoff,

		ReadBufferSize:  .ReadBufferSize,
		WriteBufferSize: .WriteBufferSize,

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

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

		ContextTimeoutEnabled: .ContextTimeoutEnabled,

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

		TLSConfig: .TLSConfig,

		DisableIdentity:           .DisableIdentity,
		DisableIndentity:          .DisableIndentity,
		IdentitySuffix:            .IdentitySuffix,
		FailingTimeoutSeconds:     .FailingTimeoutSeconds,
		PushNotificationProcessor: .PushNotificationProcessor,

		MaintNotificationsConfig: &maintnotifications.Config{
			Mode: maintnotifications.ModeDisabled,
		},
	}
}

// ParseFailoverURL parses a URL into FailoverOptions that can be used to connect to Redis.
// The URL must be in the form:
//
//	redis://<user>:<password>@<host>:<port>/<db_number>
//	or
//	rediss://<user>:<password>@<host>:<port>/<db_number>
//
// To add additional addresses, specify the query parameter, "addr" one or more times. e.g:
//
//	redis://<user>:<password>@<host>:<port>/<db_number>?addr=<host2>:<port2>&addr=<host3>:<port3>
//	or
//	rediss://<user>:<password>@<host>:<port>/<db_number>?addr=<host2>:<port2>&addr=<host3>:<port3>
//
// Most Option fields can be set using query parameters, with the following restrictions:
//   - field names are mapped using snake-case conversion: to set MaxRetries, use max_retries
//   - only scalar type fields are supported (bool, int, time.Duration)
//   - for time.Duration fields, values must be a valid input for time.ParseDuration();
//     additionally a plain integer as value (i.e. without unit) is interpreted as seconds
//   - to disable a duration field, use value less than or equal to 0; to use the default
//     value, leave the value blank or remove the parameter
//   - only the last value is interpreted if a parameter is given multiple times
//   - fields "network", "addr", "sentinel_username" and "sentinel_password" can only be set using other
//     URL attributes (scheme, host, userinfo, resp.), query parameters using these
//     names will be treated as unknown parameters
//   - unknown parameter names will result in an error
//   - use "skip_verify=true" to ignore TLS certificate validation
//
// Example:
//
//	redis://user:password@localhost:6789?master_name=mymaster&dial_timeout=3&read_timeout=6s&addr=localhost:6790&addr=localhost:6791
//	is equivalent to:
//	&FailoverOptions{
//		MasterName:  "mymaster",
//		Addr:        ["localhost:6789", "localhost:6790", "localhost:6791"]
//		DialTimeout: 3 * time.Second, // no time unit = seconds
//		ReadTimeout: 6 * time.Second,
//	}
func ( string) (*FailoverOptions, error) {
	,  := url.Parse()
	if  != nil {
		return nil, 
	}
	return setupFailoverConn()
}

func setupFailoverConn( *url.URL) (*FailoverOptions, error) {
	 := &FailoverOptions{}

	.SentinelUsername, .SentinelPassword = getUserPassword()

	,  := getHostPortWithDefaults()
	.SentinelAddrs = append(.SentinelAddrs, net.JoinHostPort(, ))

	switch .Scheme {
	case "rediss":
		.TLSConfig = &tls.Config{ServerName: , MinVersion: tls.VersionTLS12}
	case "redis":
		.TLSConfig = nil
	default:
		return nil, fmt.Errorf("redis: invalid URL scheme: %s", .Scheme)
	}

	 := strings.FieldsFunc(.Path, func( rune) bool {
		return  == '/'
	})
	switch len() {
	case 0:
		.DB = 0
	case 1:
		var  error
		if .DB,  = strconv.Atoi([0]);  != nil {
			return nil, fmt.Errorf("redis: invalid database number: %q", [0])
		}
	default:
		return nil, fmt.Errorf("redis: invalid URL path: %s", .Path)
	}

	return setupFailoverConnParams(, )
}

func setupFailoverConnParams( *url.URL,  *FailoverOptions) (*FailoverOptions, error) {
	 := queryOptions{q: .Query()}

	.MasterName = .string("master_name")
	.ClientName = .string("client_name")
	.RouteByLatency = .bool("route_by_latency")
	.RouteByLatencyTolerance = .duration("route_by_latency_tolerance")
	.RouteRandomly = .bool("route_randomly")
	.ReplicaOnly = .bool("replica_only")
	.UseDisconnectedReplicas = .bool("use_disconnected_replicas")
	.Protocol = .int("protocol")
	.Username = .string("username")
	.Password = .string("password")
	.MaxRetries = .int("max_retries")
	.MinRetryBackoff = .duration("min_retry_backoff")
	.MaxRetryBackoff = .duration("max_retry_backoff")
	.DialTimeout = .duration("dial_timeout")
	.DialerRetries = .int("dialer_retries")
	.DialerRetryTimeout = .duration("dialer_retry_timeout")
	.ReadTimeout = .duration("read_timeout")
	.WriteTimeout = .duration("write_timeout")
	.ContextTimeoutEnabled = .bool("context_timeout_enabled")
	.PoolFIFO = .bool("pool_fifo")
	.PoolSize = .int("pool_size")
	.MaxConcurrentDials = .int("max_concurrent_dials")
	.MinIdleConns = .int("min_idle_conns")
	.MaxIdleConns = .int("max_idle_conns")
	.MaxActiveConns = .int("max_active_conns")
	// Pipeline pool (created by default): allow URL opt-out
	// (pipeline_pool_size=-1) / tuning, else rejected as unexpected options.
	.PipelinePoolSize = .int("pipeline_pool_size")
	.PipelineReadBufferSize = .int("pipeline_read_buffer_size")
	.PipelineWriteBufferSize = .int("pipeline_write_buffer_size")
	.ConnMaxLifetime = .duration("conn_max_lifetime")
	if .has("conn_max_lifetime_jitter") {
		.ConnMaxLifetimeJitter = min(.duration("conn_max_lifetime_jitter"), .ConnMaxLifetime)
	}
	.ConnMaxIdleTime = .duration("conn_max_idle_time")
	.PoolTimeout = .duration("pool_timeout")
	.DisableIdentity = .bool("disableIdentity")
	.IdentitySuffix = .string("identitySuffix")
	.UnstableResp3 = .bool("unstable_resp3")

	if .err != nil {
		return nil, .err
	}

	if  := .string("db");  != "" {
		,  := strconv.Atoi()
		if  != nil {
			return nil, fmt.Errorf("redis: invalid database number: %w", )
		}
		.DB = 
	}

	 := .strings("addr")
	for ,  := range  {
		, ,  := net.SplitHostPort()
		if  != nil ||  == "" ||  == "" {
			return nil, fmt.Errorf("redis: unable to parse addr param: %s", )
		}

		.SentinelAddrs = append(.SentinelAddrs, net.JoinHostPort(, ))
	}

	if .TLSConfig != nil && .has("skip_verify") {
		.TLSConfig.InsecureSkipVerify = .bool("skip_verify")
	}
	if .err != nil {
		return nil, .err
	}

	// any parameters left?
	if  := .remaining(); len() > 0 {
		return nil, fmt.Errorf("redis: unexpected option: %s", strings.Join(, ", "))
	}

	return , nil
}

// NewFailoverClient returns a Redis client that uses Redis Sentinel
// for automatic failover. It's safe for concurrent use by multiple
// goroutines.
// Passing nil FailoverOptions will cause a panic.
func ( *FailoverOptions) *Client {
	if  == nil {
		panic("redis: NewFailoverClient nil options")
	}

	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()

	 := &Client{
		baseClient: &baseClient{
			apClosed: &atomic.Bool{},
			opt:      ,
			onClose:  &onCloseHooks{},
			himport:  newHImportRegistry(),
		},
	}
	.init()

	// Registered first (at construction), so onClose.run's LIFO order invokes it LAST —
	// after any lazily-registered autopipeliner drain hook. The drain needs MasterAddr
	// (hence a live failover client) to dial a replacement conn for accepted-but-unsent
	// work; tearing the failover client down here first would make MasterAddr return
	// pool.ErrClosed and fail those replayable commands. See onCloseHooks.run.
	//
	// Registered BEFORE the pools exist, not after: with MinIdleConns > 0 the main
	// pool starts dialing as soon as it is created, and masterReplicaDialer then
	// builds the failover's Sentinel client and pubsub. If a later construction
	// step panics, the panic-cleanup defer below closes rdb, whose onClose hooks
	// must already include this one — otherwise those discovery resources outlive
	// the client nobody will ever hold (Copilot on #4002).
	.onClose.register(onCloseHookIDSentinelFailover, .Close)

	// Close a partially-built client if any construction step below panics before
	// this constructor returns. Mirrors NewClient: the pools (and their MinIdleConns
	// dialing goroutines) are created below, and a later step can panic — a pipeline
	// pool whose PipelinePoolSize overflows int32, otel registration, or a push
	// processor rejecting handler registration. The panic propagates to the caller
	// (which may recover it), but rdb is never returned, so without this its pools
	// would leak with no reference left to Close them. Close is nil-safe for a
	// partially-built client and this defer does not recover, so the panic still
	// surfaces.
	 := false
	defer func() {
		if ! {
			_ = .Close()
		}
	}()

	// Initialize push notification processor using shared helper
	// Use void processor by default for RESP2 connections
	.pushProcessor = initializePushProcessor()

	// Generate unique pool names for metrics
	 := generateUniqueID()
	 := .Addr + "_" + 
	 := .Addr + "_" +  + "_pubsub"

	// Assign the pool fields only AFTER the error check, mirroring NewClient.
	// newConnPool returns a nil *pool.ConnPool on error, and assigning that
	// straight to the pool.Pooler interface field would leave a typed-nil
	// interface that closeResources treats as present (its != nil check passes),
	// so the panic-cleanup defer above would nil-deref inside ConnPool.Close and
	// replace the intended "failed to create connection pool" panic. A local var
	// keeps the field nil on failure. (pubSubPool is a concrete *pool.PubSubPool
	// whose nil is caught correctly by the != nil check, but assign it the same
	// way to keep this constructor identical to NewClient.)
	,  := newConnPool(, .dialHook, )
	if  != nil {
		panic(fmt.Errorf("redis: failed to create connection pool: %w", ))
	}
	.connPool = 
	,  := newPubSubPool(, .dialHook, )
	if  != nil {
		panic(fmt.Errorf("redis: failed to create pubsub pool: %w", ))
	}
	.pubSubPool = 

	// Create the dedicated pipeline pool unconditionally, mirroring NewClient
	// via the shared buildPipelinePool helper. PipelinePoolSize < 0 opts out.
	if .PipelinePoolSize >= 0 {
		,  := .buildPipelinePool( + "_pipeline")
		if  != nil {
			panic(fmt.Errorf("redis: failed to create pipeline connection pool: %w", ))
		}
		.pipelinePool = 
	}

	// Register pools for OTel async gauge metrics, matching NewClient (the
	// failover client previously registered none, so pool gauges were silent
	// for the identical standalone setup). The pipeline pool is nil when not
	// configured.
	otel.RegisterPools(.connPool, .pubSubPool, .getPipelinePool(), .Addr)

	.mu.Lock()
	.onFailover = func( context.Context,  string) {
		if ,  := .connPool.(*pool.ConnPool);  {
			_ = .Filter(func( *pool.Conn) bool {
				return .RemoteAddr().String() != 
			})
		}
		// Drop stale pipeline-pool connections dialed to the demoted master too;
		// otherwise pipelined traffic keeps using the old address after failover.
		// The pipeline pool is created at construction (before this callback can
		// fire), so the ref is simply read here.
		if  := .loadPipelinePool();  != nil {
			_ = .pool.Filter(func( *pool.Conn) bool {
				return .RemoteAddr().String() != 
			})
		}
	}
	.mu.Unlock()

	 = true
	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,
			KeepAliveConfig: defaultKeepAliveConfig,
		}
		if .opt.TLSConfig == nil {
			return .DialContext(, , )
		}
		return tls.DialWithDialer(, , , .opt.TLSConfig)
	}
}

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

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

// NewSentinelClient returns a Redis Sentinel client.
// Passing nil Options will cause a panic.
func ( *Options) *SentinelClient {
	if  == nil {
		panic("redis: NewSentinelClient nil options")
	}
	.init()
	 := &SentinelClient{
		baseClient: &baseClient{
			apClosed: &atomic.Bool{},
			opt:      ,
			onClose:  &onCloseHooks{},
		},
	}

	// Initialize push notification processor using shared helper
	// Use void processor for Sentinel clients
	.pushProcessor = NewVoidPushNotificationProcessor()

	.initHooks(hooks{
		dial:    .baseClient.dial,
		process: .baseClient.process,
	})

	// Generate unique pool names for metrics
	 := generateUniqueID()
	 := .Addr + "_" + 
	 := .Addr + "_" +  + "_pubsub"

	var  error
	.connPool,  = newConnPool(, .dialHook, )
	if  != nil {
		panic(fmt.Errorf("redis: failed to create connection pool: %w", ))
	}
	.pubSubPool,  = newPubSubPool(, .dialHook, )
	if  != nil {
		panic(fmt.Errorf("redis: failed to create pubsub pool: %w", ))
	}

	return 
}

// GetPushNotificationHandler returns the handler for a specific push notification name.
// Returns nil if no handler is registered for the given name.
func ( *SentinelClient) ( string) push.NotificationHandler {
	return .pushProcessor.GetHandler()
}

// RegisterPushNotificationHandler registers a handler for a specific push notification name.
// Returns an error if a handler is already registered for this push notification name.
// If protected is true, the handler cannot be unregistered.
func ( *SentinelClient) ( string,  push.NotificationHandler,  bool) error {
	return .pushProcessor.RegisterHandler(, , )
}

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

func ( *SentinelClient) () *PubSub {
	 := &PubSub{
		opt: .cloneOpt(),
		newConn: func( context.Context,  string,  []string) (*pool.Conn, error) {
			,  := .pubSubPool.NewConn(, .opt.Network, , )
			if  != nil {
				return nil, 
			}
			// will return nil if already initialized
			 = .initConn(, )
			if  != nil {
				_ = .Close()
				return nil, 
			}
			// Track connection in PubSubPool
			.pubSubPool.TrackConn()
			return , nil
		},
		closeConn: func( *pool.Conn) error {
			// Untrack connection from PubSubPool
			.pubSubPool.UntrackConn()
			_ = .Close()
			return nil
		},
		pushProcessor: .pushProcessor,
	}
	.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
	// closed is set by Close (under mu). Once set, MasterAddr and replicaAddrs
	// refuse to create a new SentinelClient/pubsub and return pool.ErrClosed.
	// Close runs as an onClose hook, which fires BEFORE a pool-sharing wrapper's
	// autopipeliner drain hook (registration order); that drain may dial through
	// masterReplicaDialer, and without this flag the dial would rebuild the
	// sentinel client + pubsub after the only cleanup had already run, leaking
	// them past the pool teardown.
	closed bool
}

func ( *sentinelFailover) () error {
	.mu.Lock()
	defer .mu.Unlock()
	.closed = true
	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 isContextError(.Err()) {
				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 isContextError(.Err()) {
				return "", 
			}
			// Continue on other errors
			internal.Logger.Printf(, "sentinel: GetMasterAddrByName name=%q failed: %s",
				.opt.MasterName, )
		} else {
			return , nil
		}
	}

	// Closed: do not rebuild the sentinel client (see sentinelFailover.closed).
	if .closed {
		return "", pool.ErrClosed
	}

	// short circuit if no sentinels configured
	if len(.sentinelAddrs) == 0 {
		return "", errors.New("redis: no sentinels configured")
	}

	var (
		 string
		         sync.WaitGroup
		       sync.Once
		      = make(chan error, len(.sentinelAddrs))
	)

	,  := context.WithCancel()
	defer ()

	for ,  := range .sentinelAddrs {
		.Add(1)
		go func( int,  string) {
			defer .Done()
			 := NewSentinelClient(.opt.sentinelOptions())
			,  := .GetMasterAddrByName(, .opt.MasterName).Result()
			if  != nil {
				internal.Logger.Printf(, "sentinel: GetMasterAddrByName addr=%s, master=%q failed: %s",
					, .opt.MasterName, )
				_ = .Close()
				 <- 
				return
			}

			.Do(func() {
				 = net.JoinHostPort([0], [1])
				// Push working sentinel to the top
				.sentinelAddrs[0], .sentinelAddrs[] = .sentinelAddrs[], .sentinelAddrs[0]
				.setSentinel(, )
				internal.Logger.Printf(, "sentinel: selected addr=%s masterAddr=%s", , )
				()
			})

			if  != .sentinel {
				_ = .Close()
			}
		}(, )
	}

	.Wait()
	close()
	if  != "" {
		return , nil
	}
	 := make([]error, 0, len())
	for  := range  {
		 = append(, )
	}
	return "", fmt.Errorf("redis: all sentinels specified in configuration are unreachable: %w", errors.Join(...))
}

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

	if  != nil {
		,  := .getReplicaAddrs(, )
		if  != nil {
			if isContextError(.Err()) {
				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 isContextError(.Err()) {
				return nil, 
			}
			// Continue on other errors
			internal.Logger.Printf(, "sentinel: Replicas name=%q failed: %s",
				.opt.MasterName, )
		} else if len() > 0 {
			return , nil
		} else if ! {
			// No error and no replicas — valid steady state for master-only setups.
			// Preserve the sentinel connection for master discovery and failover
			// pub/sub monitoring. Only return early when useDisconnected is false;
			// when true, fall through to the discovery loop which passes
			// useDisconnected to parseReplicaAddrs (getReplicaAddrs hardcodes false).
			return []string{}, nil
		} else {
			// useDisconnected=true: close sentinel so the discovery loop can call
			// setSentinel if it finds disconnected replicas.
			_ = .closeSentinel()
		}
	}

	// Closed: do not rebuild the sentinel client (see sentinelFailover.closed).
	if .closed {
		return nil, pool.ErrClosed
	}

	var  bool

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

		,  := .Replicas(, .opt.MasterName).Result()
		if  != nil {
			_ = .Close()
			if isContextError(.Err()) {
				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 nil, nil
	}
	return nil, 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 !slices.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()
		}
	}
}

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

// NewFailoverClusterClient returns a client that supports routing read-only commands
// to a replica node.
// Passing nil FailoverOptions will cause a panic.
func ( *FailoverOptions) *ClusterClient {
	if  == nil {
		panic("redis: NewFailoverClusterClient nil options")
	}

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

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

	 := .clusterOptions()
	if .DB != 0 {
		 := .OnConnect

		.OnConnect = func( context.Context,  *Conn) error {
			if  := .Select(, .DB).Err();  != nil {
				return 
			}

			if  != nil {
				return (, )
			}

			return nil
		}
	}

	.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 
}