package redis

import (
	
	
	
	
	
	
	

	
	
	
	
	
)

// PubSub implements Pub/Sub commands as described in
// https://redis.io/docs/latest/develop/pubsub. Message receiving is NOT safe
// for concurrent use by multiple goroutines.
//
// PubSub automatically reconnects to Redis Server and resubscribes
// to the channels in case of network errors.
type PubSub struct {
	opt *Options

	newConn   func(ctx context.Context, addr string, channels []string) (*pool.Conn, error)
	closeConn func(*pool.Conn) error

	mu        sync.Mutex
	cn        *pool.Conn
	channels  map[string]struct{}
	patterns  map[string]struct{}
	schannels map[string]struct{}

	closed bool
	exit   chan struct{}

	cmd *Cmd

	chOnce sync.Once
	msgCh  *channel
	allCh  *channel

	// Push notification processor for handling generic push notifications
	pushProcessor push.NotificationProcessor

	// Cleanup callback for maintenanceNotifications upgrade tracking
	onClose func()
}

func ( *PubSub) () {
	.exit = make(chan struct{})
}

func ( *PubSub) () string {
	.mu.Lock()
	defer .mu.Unlock()

	 := slices.Collect(maps.Keys(.channels))
	 = append(, slices.Collect(maps.Keys(.patterns))...)
	 = append(, slices.Collect(maps.Keys(.schannels))...)
	return fmt.Sprintf("PubSub(%s)", strings.Join(, ", "))
}

func ( *PubSub) ( context.Context) (*pool.Conn, error) {
	.mu.Lock()
	,  := .conn(, nil)
	.mu.Unlock()
	return , 
}

func ( *PubSub) ( context.Context,  []string) (*pool.Conn, error) {
	if .closed {
		return nil, pool.ErrClosed
	}
	if .cn != nil {
		return .cn, nil
	}

	if .opt.Addr == "" {
		// TODO(maintenanceNotifications):
		// this is probably cluster client
		// c.newConn will ignore the addr argument
		// will be changed when we have maintenanceNotifications upgrades for cluster clients
		.opt.Addr = internal.RedisNull
	}

	// Include c.schannels so reconnect-time routing of an SSubscribe-only
	// PubSub picks the slot owner (channels[0] in ClusterClient.pubSub()'s
	// newConn closure) instead of a random node.
	// See https://github.com/redis/go-redis/issues/3806.
	// c.patterns is intentionally NOT included: patterns are not slot-
	// addressable, and adding them would force PSubscribe-only PubSubs to
	// pin to a single node based on pattern-string hash, regressing the
	// existing random-node behaviour.
	 := slices.Collect(maps.Keys(.channels))
	 = append(, slices.Collect(maps.Keys(.schannels))...)
	 = append(, ...)

	,  := .newConn(, .opt.Addr, )
	if  != nil {
		return nil, 
	}

	if  := .resubscribe(, );  != nil {
		_ = .closeConn()
		return nil, 
	}

	.cn = 
	return , nil
}

func ( *PubSub) ( context.Context,  *pool.Conn,  Cmder) error {
	return .WithWriter(, .opt.WriteTimeout, func( *proto.Writer) error {
		return writeCmd(, )
	})
}

func ( *PubSub) ( context.Context,  *pool.Conn) error {
	var  error

	if len(.channels) > 0 {
		 = ._subscribe(, , "subscribe", slices.Collect(maps.Keys(.channels)))
	}

	if len(.patterns) > 0 {
		 := ._subscribe(, , "psubscribe", slices.Collect(maps.Keys(.patterns)))
		if  != nil &&  == nil {
			 = 
		}
	}

	if len(.schannels) > 0 {
		 := ._subscribe(, , "ssubscribe", slices.Collect(maps.Keys(.schannels)))
		if  != nil &&  == nil {
			 = 
		}
	}

	return 
}

func ( *PubSub) (
	 context.Context,  *pool.Conn,  string,  []string,
) error {
	 := make([]interface{}, 0, 1+len())
	 = append(, )
	for ,  := range  {
		 = append(, )
	}
	 := NewSliceCmd(, ...)
	return .writeCmd(, , )
}

func ( *PubSub) (
	 context.Context,
	 *pool.Conn,
	 error,
	 bool,
) {
	.mu.Lock()
	.releaseConn(, , , )
	.mu.Unlock()
}

func ( *PubSub) ( context.Context,  *pool.Conn,  error,  bool) {
	if .cn !=  {
		return
	}

	if !.IsUsable() || .ShouldHandoff() {
		.reconnect(, fmt.Errorf("pubsub: connection is not usable"))
		return
	}

	if isBadConn(, , .opt.Addr) {
		.reconnect(, )
	}
}

func ( *PubSub) ( context.Context,  error) {
	if .cn != nil && .cn.ShouldHandoff() {
		 := .cn.GetHandoffEndpoint()
		// If new endpoint is NULL, use the original address
		if  == internal.RedisNull {
			 = .opt.Addr
		}

		if  != "" {
			// Update the address in the options
			 := .cn.RemoteAddr().String()
			.opt.Addr = 
			internal.Logger.Printf(, "pubsub: reconnecting to new endpoint %s (was %s)", , )
		}
	}
	_ = .closeTheCn()
	_, _ = .conn(, nil)
}

func ( *PubSub) ( error) error {
	if .cn == nil {
		return nil
	}
	 := .closeConn(.cn)
	.cn = nil
	return 
}

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

	if .closed {
		return pool.ErrClosed
	}
	.closed = true
	close(.exit)

	// Call cleanup callback if set
	if .onClose != nil {
		.onClose()
	}

	return .closeTheCn(pool.ErrClosed)
}

// Subscribe the client to the specified channels. It returns
// empty subscription if there are no channels.
func ( *PubSub) ( context.Context,  ...string) error {
	.mu.Lock()
	defer .mu.Unlock()

	 := .subscribe(, "subscribe", ...)
	if .channels == nil {
		.channels = make(map[string]struct{})
	}
	for ,  := range  {
		.channels[] = struct{}{}
	}
	return 
}

// PSubscribe the client to the given patterns. It returns
// empty subscription if there are no patterns.
func ( *PubSub) ( context.Context,  ...string) error {
	.mu.Lock()
	defer .mu.Unlock()

	 := .subscribe(, "psubscribe", ...)
	if .patterns == nil {
		.patterns = make(map[string]struct{})
	}
	for ,  := range  {
		.patterns[] = struct{}{}
	}
	return 
}

// SSubscribe Subscribes the client to the specified shard channels.
func ( *PubSub) ( context.Context,  ...string) error {
	.mu.Lock()
	defer .mu.Unlock()

	 := .subscribe(, "ssubscribe", ...)
	if .schannels == nil {
		.schannels = make(map[string]struct{})
	}
	for ,  := range  {
		.schannels[] = struct{}{}
	}
	return 
}

// Unsubscribe the client from the given channels, or from all of
// them if none is given.
func ( *PubSub) ( context.Context,  ...string) error {
	.mu.Lock()
	defer .mu.Unlock()

	if len() > 0 {
		for ,  := range  {
			delete(.channels, )
		}
	} else {
		// Unsubscribe from all channels.
		clear(.channels)
	}

	 := .subscribe(, "unsubscribe", ...)
	return 
}

// PUnsubscribe the client from the given patterns, or from all of
// them if none is given.
func ( *PubSub) ( context.Context,  ...string) error {
	.mu.Lock()
	defer .mu.Unlock()

	if len() > 0 {
		for ,  := range  {
			delete(.patterns, )
		}
	} else {
		// Unsubscribe from all patterns.
		clear(.patterns)
	}

	 := .subscribe(, "punsubscribe", ...)
	return 
}

// SUnsubscribe unsubscribes the client from the given shard channels,
// or from all of them if none is given.
func ( *PubSub) ( context.Context,  ...string) error {
	.mu.Lock()
	defer .mu.Unlock()

	if len() > 0 {
		for ,  := range  {
			delete(.schannels, )
		}
	} else {
		// Unsubscribe from all channels.
		clear(.schannels)
	}

	 := .subscribe(, "sunsubscribe", ...)
	return 
}

func ( *PubSub) ( context.Context,  string,  ...string) error {
	,  := .conn(, )
	if  != nil {
		return 
	}

	 = ._subscribe(, , , )
	.releaseConn(, , , false)
	return 
}

func ( *PubSub) ( context.Context,  ...string) error {
	 := []interface{}{"ping"}
	if len() == 1 {
		 = append(, [0])
	}
	 := NewCmd(, ...)

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

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

	 = .writeCmd(, , )
	.releaseConn(, , , false)
	return 
}

// ClientSetName assigns  a namee to the PubSub connection using  CLIENT SETNAME,
// The name is visible in CLIENT LIST output and is useful for debugging
// and identifying connections in a redis instance.
func ( *PubSub) ( context.Context,  string) error {
	 := NewStatusCmd(, "client", "setname", )

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

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

	 = .writeCmd(, , )
	.releaseConn(, , , false)
	return 
}

// Subscription received after a successful subscription to channel.
type Subscription struct {
	// Can be "subscribe", "unsubscribe", "psubscribe" or "punsubscribe".
	Kind string
	// Channel name we have subscribed to.
	Channel string
	// Number of channels we are currently subscribed to.
	Count int
}

func ( *Subscription) () string {
	return fmt.Sprintf("%s: %s", .Kind, .Channel)
}

// Message received as result of a PUBLISH command issued by another client.
type Message struct {
	Channel      string
	Pattern      string
	Payload      string
	PayloadSlice []string
}

func ( *Message) () string {
	return fmt.Sprintf("Message<%s: %s>", .Channel, .Payload)
}

// Pong received as result of a PING command issued by another client.
type Pong struct {
	Payload string
}

func ( *Pong) () string {
	if .Payload != "" {
		return fmt.Sprintf("Pong<%s>", .Payload)
	}
	return "Pong"
}

func ( *PubSub) ( context.Context,  *pool.Conn,  interface{}) (interface{}, error) {
	switch reply := .(type) {
	case string:
		return &Pong{
			Payload: ,
		}, nil
	case []interface{}:
		switch  := [0].(string);  {
		case "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "ssubscribe", "sunsubscribe":
			// Can be nil in case of "unsubscribe".
			,  := [1].(string)
			return &Subscription{
				Kind:    ,
				Channel: ,
				Count:   int([2].(int64)),
			}, nil
		case "message", "smessage":
			 := [1].(string)
			 :=  == "smessage"
			switch payload := [2].(type) {
			case string:
				 := &Message{
					Channel: ,
					Payload: ,
				}
				// Record PubSub message received
				otel.RecordPubSubMessage(, , "received", , )
				return , nil
			case []interface{}:
				 := make([]string, len())
				for ,  := range  {
					[] = .(string)
				}
				 := &Message{
					Channel:      ,
					PayloadSlice: ,
				}
				// Record PubSub message received
				otel.RecordPubSubMessage(, , "received", , )
				return , nil
			default:
				return nil, fmt.Errorf("redis: unsupported pubsub message payload: %T", )
			}
		case "pmessage":
			 := [2].(string)
			 := &Message{
				Pattern: [1].(string),
				Channel: ,
				Payload: [3].(string),
			}
			// Record PubSub message received (pattern message, not sharded)
			otel.RecordPubSubMessage(, , "received", , false)
			return , nil
		case "pong":
			return &Pong{
				Payload: [1].(string),
			}, nil
		default:
			return nil, fmt.Errorf("redis: unsupported pubsub message: %q", )
		}
	default:
		return nil, fmt.Errorf("redis: unsupported pubsub message: %#v", )
	}
}

// ReceiveTimeout acts like Receive but returns an error if message
// is not received in time. This is low-level API and in most cases
// Channel should be used instead.
func ( *PubSub) ( context.Context,  time.Duration) (interface{}, error) {
	if .cmd == nil {
		.cmd = NewCmd()
	}

	// Don't hold the lock to allow subscriptions and pings.
	,  := .connWithLock()
	if  != nil {
		return nil, 
	}

	 = .WithReader(, , func( *proto.Reader) error {
		// To be sure there are no buffered push notifications, we process them before reading the reply
		if  := .processPendingPushNotificationWithReader(, , );  != nil {
			// Log the error but don't fail the command execution
			// Push notification processing errors shouldn't break normal Redis operations
			internal.Logger.Printf(, "push: conn[%d] error processing pending notifications before reading reply: %v", .GetID(), )
		}
		return .cmd.readReply()
	})
	.releaseConnWithLock(, , ,  > 0)

	if  != nil {
		return nil, 
	}

	return .newMessage(, , .cmd.Val())
}

// Receive returns a message as a Subscription, Message, Pong or error.
// See PubSub example for details. This is low-level API and in most cases
// Channel should be used instead.
// Receive returns a message as a Subscription, Message, Pong, or an error.
// See PubSub example for details. This is a low-level API and in most cases
// Channel should be used instead.
// This method blocks until a message is received or an error occurs.
// It may return early with an error if the context is canceled, the connection fails,
// or other internal errors occur.
func ( *PubSub) ( context.Context) (interface{}, error) {
	return .ReceiveTimeout(, 0)
}

// ReceiveMessage returns a Message or error ignoring Subscription and Pong
// messages. This is low-level API and in most cases Channel should be used
// instead.
func ( *PubSub) ( context.Context) (*Message, error) {
	for {
		,  := .Receive()
		if  != nil {
			return nil, 
		}

		switch msg := .(type) {
		case *Subscription:
			// Ignore.
		case *Pong:
			// Ignore.
		case *Message:
			return , nil
		default:
			 := fmt.Errorf("redis: unknown message: %T", )
			return nil, 
		}
	}
}

func ( *PubSub) () context.Context {
	if .cmd != nil {
		return .cmd.ctx
	}
	return context.Background()
}

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

// Channel returns a Go channel for concurrently receiving messages.
// The channel is closed together with the PubSub. If the Go channel
// is blocked full for 1 minute the message is dropped.
// Receive* APIs can not be used after channel is created.
//
// go-redis periodically sends ping messages to test connection health
// and re-subscribes if ping can not received for 1 minute.
func ( *PubSub) ( ...ChannelOption) <-chan *Message {
	.chOnce.Do(func() {
		.msgCh = newChannel(, ...)
		.msgCh.initMsgChan()
	})
	if .msgCh == nil {
		 := fmt.Errorf("redis: Channel can't be called after ChannelWithSubscriptions")
		panic()
	}
	return .msgCh.msgCh
}

// ChannelSize is like Channel, but creates a Go channel
// with specified buffer size.
//
// Deprecated: use Channel(WithChannelSize(size)), remove in v9.
func ( *PubSub) ( int) <-chan *Message {
	return .Channel(WithChannelSize())
}

// ChannelWithSubscriptions is like Channel, but message type can be either
// *Subscription or *Message. Subscription messages can be used to detect
// reconnections.
//
// ChannelWithSubscriptions can not be used together with Channel or ChannelSize.
func ( *PubSub) ( ...ChannelOption) <-chan interface{} {
	.chOnce.Do(func() {
		.allCh = newChannel(, ...)
		.allCh.initAllChan()
	})
	if .allCh == nil {
		 := fmt.Errorf("redis: ChannelWithSubscriptions can't be called after Channel")
		panic()
	}
	return .allCh.allCh
}

func ( *PubSub) ( context.Context,  *pool.Conn,  *proto.Reader) error {
	// Only process push notifications for RESP3 connections with a processor
	if .opt.Protocol != 3 || .pushProcessor == nil {
		return nil
	}

	// Create handler context with client, connection pool, and connection information
	 := .pushNotificationHandlerContext()
	return .pushProcessor.ProcessPendingNotifications(, , )
}

func ( *PubSub) ( *pool.Conn) push.NotificationHandlerContext {
	// PubSub doesn't have a client or connection pool, so we pass nil for those
	// PubSub connections are blocking
	return push.NotificationHandlerContext{
		PubSub:     ,
		Conn:       ,
		IsBlocking: true,
	}
}

type ChannelOption func(c *channel)

// WithChannelSize specifies the Go chan size that is used to buffer incoming messages.
//
// The default is 100 messages.
func ( int) ChannelOption {
	return func( *channel) {
		.chanSize = 
	}
}

// WithChannelHealthCheckInterval specifies the health check interval.
// PubSub will ping Redis Server if it does not receive any messages within the interval.
// To disable health check, use zero interval.
//
// The default is 3 seconds.
func ( time.Duration) ChannelOption {
	return func( *channel) {
		.checkInterval = 
	}
}

// WithChannelSendTimeout specifies the channel send timeout after which
// the message is dropped.
//
// The default is 60 seconds.
func ( time.Duration) ChannelOption {
	return func( *channel) {
		.chanSendTimeout = 
	}
}

// WithChannelPingTimeout specifies the timeout for the health-check ping.
//
// The default is 5 seconds.
func ( time.Duration) ChannelOption {
	return func( *channel) {
		.pingTimeout = 
	}
}

// WithChannelReconnectTimeout specifies the timeout for reconnecting after
// a failed health-check ping.
//
// The default is 10 seconds.
func ( time.Duration) ChannelOption {
	return func( *channel) {
		.reconnectTimeout = 
	}
}

type channel struct {
	pubSub *PubSub

	msgCh chan *Message
	allCh chan interface{}
	ping  chan struct{}

	chanSize         int
	chanSendTimeout  time.Duration
	checkInterval    time.Duration
	pingTimeout      time.Duration
	reconnectTimeout time.Duration
}

func newChannel( *PubSub,  ...ChannelOption) *channel {
	 := &channel{
		pubSub: ,

		chanSize:         100,
		chanSendTimeout:  time.Minute,
		checkInterval:    3 * time.Second,
		pingTimeout:      5 * time.Second,
		reconnectTimeout: 10 * time.Second,
	}
	for ,  := range  {
		()
	}
	if .checkInterval > 0 {
		.initHealthCheck()
	}
	return 
}

func ( *channel) () {
	.ping = make(chan struct{}, 1)

	go func() {
		 := time.NewTimer(time.Minute)
		.Stop()

		for {
			.Reset(.checkInterval)
			select {
			case <-.ping:
				select {
				case <-.C:
				default:
				}
			case <-.C:
				,  := context.WithTimeout(context.Background(), .pingTimeout)
				 := .pubSub.Ping()
				()

				if  != nil {
					.pubSub.mu.Lock()
					,  := context.WithTimeout(context.Background(), .reconnectTimeout)
					.pubSub.reconnect(, )
					()
					.pubSub.mu.Unlock()
				}
			case <-.pubSub.exit:
				return
			}
		}
	}()
}

// initMsgChan must be in sync with initAllChan.
func ( *channel) () {
	 := context.TODO()
	.msgCh = make(chan *Message, .chanSize)

	go func() {
		 := time.NewTimer(time.Minute)
		.Stop()

		var  int
		for {
			,  := .pubSub.Receive()
			if  != nil {
				if  == pool.ErrClosed {
					close(.msgCh)
					return
				}
				if  > 0 {
					time.Sleep(100 * time.Millisecond)
				}
				++
				continue
			}

			 = 0

			// Any message is as good as a ping.
			select {
			case .ping <- struct{}{}:
			default:
			}

			switch msg := .(type) {
			case *Subscription:
				// Ignore.
			case *Pong:
				// Ignore.
			case *Message:
				.Reset(.chanSendTimeout)
				select {
				case .msgCh <- :
					if !.Stop() {
						<-.C
					}
				case <-.C:
					internal.Logger.Printf(
						, "redis: %v channel is full for %s (message is dropped)",
						, .chanSendTimeout)
				}
			default:
				internal.Logger.Printf(, "redis: unknown message type: %T", )
			}
		}
	}()
}

// initAllChan must be in sync with initMsgChan.
func ( *channel) () {
	 := context.TODO()
	.allCh = make(chan interface{}, .chanSize)

	go func() {
		 := time.NewTimer(time.Minute)
		.Stop()

		var  int
		for {
			,  := .pubSub.Receive()
			if  != nil {
				if  == pool.ErrClosed {
					close(.allCh)
					return
				}
				if  > 0 {
					time.Sleep(100 * time.Millisecond)
				}
				++
				continue
			}

			 = 0

			// Any message is as good as a ping.
			select {
			case .ping <- struct{}{}:
			default:
			}

			switch msg := .(type) {
			case *Pong:
				// Ignore.
			case *Subscription, *Message:
				.Reset(.chanSendTimeout)
				select {
				case .allCh <- :
					if !.Stop() {
						<-.C
					}
				case <-.C:
					internal.Logger.Printf(
						, "redis: %v channel is full for %s (message is dropped)",
						, .chanSendTimeout)
				}
			default:
				internal.Logger.Printf(, "redis: unknown message type: %T", )
			}
		}
	}()
}