package pool

import (
	
	
	
	
)

const (
	stateDefault = 0
	stateInited  = 1
	stateClosed  = 2
)

type BadConnError struct {
	wrapped error
}

var _ error = (*BadConnError)(nil)

func ( BadConnError) () string {
	 := "redis: Conn is in a bad state"
	if .wrapped != nil {
		 += ": " + .wrapped.Error()
	}
	return 
}

func ( BadConnError) () error {
	return .wrapped
}

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

type StickyConnPool struct {
	pool   Pooler
	shared atomic.Int32

	state atomic.Uint32
	ch    chan *Conn

	// onFirstConn runs once when this sticky pool claims a connection from its
	// parent. CSC uses it to revoke cache ownership before the connection leaves
	// the parent's background drainer.
	onFirstConn func(*Conn)

	// discardOnClose makes Close remove the claimed connection from the parent
	// pool instead of returning it. Client.EphemeralConn sets it: the session
	// state a dedicated connection accumulates (AUTH, SELECT, CLIENT SETNAME,
	// CLIENT TRACKING, RESET, ...) cannot be undone, and a pooled caller must
	// never inherit it.
	discardOnClose bool

	_badConnError atomic.Value
}

var _ Pooler = (*StickyConnPool)(nil)

func ( Pooler) *StickyConnPool {
	,  := .(*StickyConnPool)
	if ! {
		 = &StickyConnPool{
			pool: ,
			ch:   make(chan *Conn, 1),
		}
	}
	.shared.Add(1)
	return 
}

func ( *StickyConnPool) ( context.Context) (*Conn, error) {
	return .pool.NewConn()
}

func ( *StickyConnPool) ( context.Context,  *Conn,  string,  string) error {
	return .pool.CloseConn(, , , )
}

func ( *StickyConnPool) ( context.Context) (*Conn, error) {
	// In worst case this races with Close which is not a very common operation.
	for  := 0;  < 1000; ++ {
		switch .state.Load() {
		case stateDefault:
			,  := .pool.Get()
			if  != nil {
				return nil, 
			}
			if .state.CompareAndSwap(stateDefault, stateInited) {
				if .onFirstConn != nil {
					.onFirstConn()
				}
				return , nil
			}
			.pool.Remove(, , ErrClosed)
		case stateInited:
			if  := .badConnError();  != nil {
				return nil, 
			}
			,  := <-.ch
			if ! {
				return nil, ErrClosed
			}
			return , nil
		case stateClosed:
			return nil, ErrClosed
		default:
			panic("not reached")
		}
	}
	return nil, fmt.Errorf("redis: StickyConnPool.Get: infinite loop")
}

// SetOnFirstConn configures a callback that runs when the sticky pool first
// claims a parent connection. It must be called before the pool is used.
func ( *StickyConnPool) ( func(*Conn)) {
	.onFirstConn = 
}

// DiscardOnClose configures the pool to remove the claimed connection from
// the parent pool on Close instead of returning it. It must be called before
// the pool is used.
func ( *StickyConnPool) () {
	.discardOnClose = true
}

func ( *StickyConnPool) ( context.Context,  *Conn) {
	defer func() {
		if recover() != nil {
			.freeConn(, )
		}
	}()
	// A connection marked for removal on release (it may hold unread
	// replies) must not be served to the next Get: record it as a bad
	// connection — exactly like Remove — so Get refuses and the underlying
	// connection is removed from the parent pool when the sticky pool
	// unwinds (the parent's Put honors the same mark).
	if  := .CloseOnPutReason();  != "" {
		._badConnError.Store(BadConnError{wrapped: errors.New()})
	}
	.ch <- 
}

func ( *StickyConnPool) ( context.Context,  *Conn) {
	if  := .badConnError();  != nil {
		.pool.Remove(, , )
	} else if .discardOnClose {
		.pool.Remove(, , ErrClosed)
	} else {
		.pool.Put(, )
	}
}

func ( *StickyConnPool) ( context.Context,  *Conn,  error) {
	defer func() {
		if recover() != nil {
			.pool.Remove(, , ErrClosed)
		}
	}()
	._badConnError.Store(BadConnError{wrapped: })
	.ch <- 
}

// RemoveWithoutTurn has the same behavior as Remove for StickyConnPool
// since StickyConnPool doesn't use a turn-based queue system.
func ( *StickyConnPool) ( context.Context,  *Conn,  error) {
	.Remove(, , )
}

func ( *StickyConnPool) () error {
	if  := .shared.Add(-1);  > 0 {
		return nil
	}

	for  := 0;  < 1000; ++ {
		 := .state.Load()
		if  == stateClosed {
			return ErrClosed
		}
		if .state.CompareAndSwap(, stateClosed) {
			close(.ch)
			,  := <-.ch
			if  {
				.freeConn(context.TODO(), )
			}
			return nil
		}
	}

	return errors.New("redis: StickyConnPool.Close: infinite loop")
}

func ( *StickyConnPool) ( context.Context) error {
	if .badConnError() == nil {
		return nil
	}

	select {
	case ,  := <-.ch:
		if ! {
			return ErrClosed
		}
		.pool.Remove(, , ErrClosed)
		._badConnError.Store(BadConnError{wrapped: nil})
	default:
		return errors.New("redis: StickyConnPool does not have a Conn")
	}

	if !.state.CompareAndSwap(stateInited, stateDefault) {
		 := .state.Load()
		return fmt.Errorf("redis: invalid StickyConnPool state: %d", )
	}

	return nil
}

func ( *StickyConnPool) () error {
	if  := ._badConnError.Load();  != nil {
		if  := .(BadConnError); .wrapped != nil {
			return 
		}
	}
	return nil
}

func ( *StickyConnPool) () int {
	switch .state.Load() {
	case stateDefault:
		return 0
	case stateInited:
		return 1
	case stateClosed:
		return 0
	default:
		panic("not reached")
	}
}

func ( *StickyConnPool) () int {
	return len(.ch)
}

// Size returns the maximum pool size, which is always 1 for StickyConnPool.
func ( *StickyConnPool) () int { return 1 }

func ( *StickyConnPool) () *Stats {
	return &Stats{}
}

func ( *StickyConnPool) ( PoolHook) {}

func ( *StickyConnPool) ( PoolHook) {}