Source File
conn_state.go
Belonging Package
github.com/redis/go-redis/v9/internal/pool
package poolimport ()// ConnState represents the connection state in the state machine.// States are designed to be lightweight and fast to check.//// State Transitions://// CREATED → INITIALIZING → IDLE ⇄ IN_USE// ↓// UNUSABLE (handoff/reauth)// ↓// IDLE/CLOSEDtype ConnState uint32const (// StateCreated - Connection just created, not yet initializedStateCreated ConnState = iota// StateInitializing - Connection initialization in progressStateInitializing// StateIdle - Connection initialized and idle in pool, ready to be acquiredStateIdle// StateInUse - Connection actively processing a command (retrieved from pool)StateInUse// StateUnusable - Connection temporarily unusable due to background operation// (handoff, reauth, etc.). Cannot be acquired from pool.StateUnusable// StateClosed - Connection closedStateClosed)// Predefined state slices to avoid allocations in hot pathsvar (validFromInUse = []ConnState{StateInUse}validFromCreatedOrIdle = []ConnState{StateCreated, StateIdle}validFromCreatedInUseOrIdle = []ConnState{StateCreated, StateInUse, StateIdle}// For AwaitAndTransition callsvalidFromCreatedIdleOrUnusable = []ConnState{StateCreated, StateIdle, StateUnusable}validFromIdle = []ConnState{StateIdle}// For CompareAndSwapUsablevalidFromInitializingOrUnusable = []ConnState{StateInitializing, StateUnusable})// Accessor functions for predefined slices to avoid allocations in external packages// These return the same slice instance, so they're zero-allocation// ValidFromIdle returns a predefined slice containing only StateIdle.// Use this to avoid allocations when calling AwaitAndTransition or TryTransition.func () []ConnState {return validFromIdle}// ValidFromCreatedIdleOrUnusable returns a predefined slice for initialization transitions.// Use this to avoid allocations when calling AwaitAndTransition or TryTransition.func () []ConnState {return validFromCreatedIdleOrUnusable}// String returns a human-readable string representation of the state.func ( ConnState) () string {switch {case StateCreated:return "CREATED"case StateInitializing:return "INITIALIZING"case StateIdle:return "IDLE"case StateInUse:return "IN_USE"case StateUnusable:return "UNUSABLE"case StateClosed:return "CLOSED"default:return fmt.Sprintf("UNKNOWN(%d)", )}}var (// ErrInvalidStateTransition is returned when a state transition is not allowedErrInvalidStateTransition = errors.New("invalid state transition")// ErrStateMachineClosed is returned when operating on a closed state machineErrStateMachineClosed = errors.New("state machine is closed")// ErrTimeout is returned when a state transition times outErrTimeout = errors.New("state transition timeout"))// waiter represents a goroutine waiting for a state transition.// Designed for minimal allocations and fast processing.type waiter struct {validStates map[ConnState]struct{} // States we're waiting fortargetState ConnState // State to transition todone chan error // Signaled when transition completes or times out}// ConnStateMachine manages connection state transitions with FIFO waiting queue.// Optimized for:// - Lock-free reads (hot path)// - Minimal allocations// - Fast state transitions// - FIFO fairness for waiters// Note: Handoff metadata (endpoint, seqID, retries) is managed separately in the Conn struct.type ConnStateMachine struct {// Current state - atomic for lock-free readsstate atomic.Uint32// FIFO queue for waiters - only locked during waiter add/remove/notifymu sync.Mutexwaiters *list.List // List of *waiterwaiterCount atomic.Int32 // Fast lock-free check for waiters (avoids mutex in hot path)}// NewConnStateMachine creates a new connection state machine.// Initial state is StateCreated.func () *ConnStateMachine {:= &ConnStateMachine{waiters: list.New(),}.state.Store(uint32(StateCreated))return}// GetState returns the current state (lock-free read).// This is the hot path - optimized for zero allocations and minimal overhead.// Note: Zero allocations applies to state reads; converting the returned state to a string// (via String()) may allocate if the state is unknown.func ( *ConnStateMachine) () ConnState {return ConnState(.state.Load())}// TryTransitionFast is an optimized version for the hot path (Get/Put operations).// It only handles simple state transitions without waiter notification.// This is safe because:// 1. Get/Put don't need to wait for state changes// 2. Background operations (handoff/reauth) use UNUSABLE state, which this won't match// 3. If a background operation is in progress (state is UNUSABLE), this fails fast//// Returns true if transition succeeded, false otherwise.// Use this for performance-critical paths where you don't need error details.//// Performance: Single CAS operation - as fast as the old atomic bool!// For multiple from states, use: sm.TryTransitionFast(State1, Target) || sm.TryTransitionFast(State2, Target)// The || operator short-circuits, so only 1 CAS is executed in the common case.func ( *ConnStateMachine) (, ConnState) bool {return .state.CompareAndSwap(uint32(), uint32())}// TryTransition attempts an immediate state transition without waiting.// Returns the current state after the transition attempt and an error if the transition failed.// The returned state is the CURRENT state (after the attempt), not the previous state.// This is faster than AwaitAndTransition when you don't need to wait.// Uses compare-and-swap to atomically transition, preventing concurrent transitions.// This method does NOT wait - it fails immediately if the transition cannot be performed.//// Performance: Zero allocations on success path (hot path).func ( *ConnStateMachine) ( []ConnState, ConnState) (ConnState, error) {// Try each valid from state with CAS// This ensures only ONE goroutine can successfully transition at a timefor , := range {// Try to atomically swap from fromState to targetState// If successful, we won the race and can proceedif .state.CompareAndSwap(uint32(), uint32()) {// Success! We transitioned atomically// Hot path optimization: only check for waiters if transition succeeded// This avoids atomic load on every Get/Put when no waiters existif .waiterCount.Load() > 0 {.notifyWaiters()}return , nil}}// All CAS attempts failed - state is not valid for this transition// Return the current state so caller can decide what to do// Note: This error path allocates, but it's the exceptional case:= .GetState()return , fmt.Errorf("%w: cannot transition from %s to %s (valid from: %v)",ErrInvalidStateTransition, , , )}// Transition unconditionally transitions to the target state.// Use with caution - prefer AwaitAndTransition or TryTransition for safety.// This is useful for error paths or when you know the transition is valid.func ( *ConnStateMachine) ( ConnState) {.state.Store(uint32()).notifyWaiters()}// AwaitAndTransition waits for the connection to reach one of the valid states,// then atomically transitions to the target state.// Returns the current state after the transition attempt and an error if the operation failed.// The returned state is the CURRENT state (after the attempt), not the previous state.// Returns error if timeout expires or context is cancelled.//// This method implements FIFO fairness - the first caller to wait gets priority// when the state becomes available.//// Performance notes:// - If already in a valid state, this is very fast (no allocation, no waiting)// - If waiting is required, allocates one waiter struct and one channelfunc ( *ConnStateMachine) (context.Context,[]ConnState,ConnState,) (ConnState, error) {// Fast path: try immediate transition with CAS to prevent race conditions// BUT: only if there are no waiters in the queue (to maintain FIFO ordering)if .waiterCount.Load() == 0 {for , := range {// Check if we're already in target stateif == && .GetState() == {return , nil}// Try to atomically swap from fromState to targetStateif .state.CompareAndSwap(uint32(), uint32()) {// Success! We transitioned atomically.notifyWaiters()return , nil}}}// Fast path failed - check if we should wait or fail:= .GetState()// Check if closedif == StateClosed {return , ErrStateMachineClosed}// Slow path: need to wait for state change// Create waiter with valid states map for fast lookup:= make(map[ConnState]struct{}, len())for , := range {[] = struct{}{}}:= &waiter{validStates: ,targetState: ,done: make(chan error, 1), // Buffered to avoid goroutine leak}// Add to FIFO queue.mu.Lock():= .waiters.PushBack().waiterCount.Add(1).mu.Unlock()// Re-check now that the waiter is visible. A transition that happened// between the fast path above and the enqueue found no waiter to notify,// so without this the waiter would sleep until its context expires..notifyWaiters()// Wait for state change or timeoutselect {case <-.Done():// Timeout or cancellation - remove from queue.mu.Lock()// notifyWaiters removes the waiter and sends on w.done under sm.mu, so// a value here means it was served before we got the lock: report the// transition and don't decrement waiterCount again.select {case := <-.done:.mu.Unlock()return .GetState(),default:}.waiters.Remove().waiterCount.Add(-1).mu.Unlock()return .GetState(), .Err()case := <-.done:// Transition completed (or failed)// Note: waiterCount is decremented either in notifyWaiters (when the waiter is notified and removed)// or here (on timeout/cancellation).return .GetState(),}}// notifyWaiters checks if any waiters can proceed and notifies them in FIFO order.// This is called after every state transition.func ( *ConnStateMachine) () {// Fast path: check atomic counter without acquiring lock// This eliminates mutex overhead in the common case (no waiters)if .waiterCount.Load() == 0 {return}.mu.Lock()defer .mu.Unlock()// Double-check after acquiring lock (waiters might have been processed)if .waiters.Len() == 0 {return}// Track state locally so we only consider transitions made within this// call, not concurrent transitions from woken goroutines. Re-reading the// atomic would let a fast goroutine's Transition(StateIdle) leak into our// view, causing us to wake multiple waiters at once and breaking FIFO// execution ordering.:= .GetState()for {:= falsefor := .waiters.Front(); != nil; = .Next() {:= .Value.(*waiter)if , := .validStates[]; {if .state.CompareAndSwap(uint32(), uint32(.targetState)) {.waiters.Remove().waiterCount.Add(-1).done <- nil= .targetState} else {// State changed concurrently. Keep the waiter where it is:// AwaitAndTransition holds elem and removes it on timeout.= .GetState()}= truebreak}}if ! {break}}}
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |