pool
v9.24.1
Documentation
pkg.go.dev ↗Package pool implements the pool management
Constants
CloseReasonStale (6 declarations)
const ( // CloseReasonStale indicates the connection was closed because it exceeded // the idle timeout or max lifetime. CloseReasonStale = "stale" // CloseReasonHookError indicates the connection was closed due to an error // in a pool hook (OnGet or OnPut). CloseReasonHookError = "hook_error" // CloseReasonAuthError indicates the connection was closed due to an // authentication error during re-authentication. CloseReasonAuthError = "auth_error" // CloseReasonTest is used in tests when closing connections. CloseReasonTest = "test" // CloseReasonFailover indicates the connection was closed due to a failover event. CloseReasonFailover = "failover" // CloseReasonMaintNotificationsDisabled indicates the connection enabled // maintenance notifications, but the client later downgraded and disabled // maintenance notification handling for the pool. CloseReasonMaintNotificationsDisabled = "maintnotifications_disabled" )
Connection close reason constants for metrics. These are used as the "reason" parameter in CloseConn() calls.
MetricStateIdle (2 declarations)
const ( // MetricStateIdle indicates the connection is idle in the pool, // ready to be acquired. MetricStateIdle = "idle" // MetricStateUsed indicates the connection is currently being used // by a client operation. MetricStateUsed = "used" )
Metric state constants for connection state tracking. These represent the logical state of a connection from a metrics perspective, not the internal state machine state (ConnState).
Variables
ErrInvalidStateTransition (3 declarations)
var (
// ErrInvalidStateTransition is returned when a state transition is not allowed
ErrInvalidStateTransition = errors.New("invalid state transition")
// ErrStateMachineClosed is returned when operating on a closed state machine
ErrStateMachineClosed = errors.New("state machine is closed")
// ErrTimeout is returned when a state transition times out
ErrTimeout = errors.New("state transition timeout")
)
ErrClosed (5 declarations)
var (
// ErrClosed performs any operation on the closed client will return this error.
ErrClosed = errors.New("redis: client is closed")
// ErrPoolExhausted is returned from a pool connection method
// when the maximum number of database connections in the pool has been reached.
ErrPoolExhausted = errors.New("redis: connection pool exhausted")
// ErrPoolTimeout timed out waiting to get a connection from the connection pool.
ErrPoolTimeout = errors.New("redis: connection pool timeout")
// ErrPoolTryFull is the result of TryGet (the non-waiting acquire) when the
// pool has no free turn now. It is not a timeout, because nothing waited. A
// caller with a fallback uses it to spill at once. The pipeline pool spills to
// the main pool this way. ErrPoolTryFull is different from ErrPoolTimeout on
// purpose. Thus getConn does not record a false pool timeout (Stats.Timeouts or
// POOL_TIMEOUT) for a non-wait. A real wait still returns ErrPoolTimeout.
ErrPoolTryFull = errors.New("redis: connection pool has no free turn")
// ErrConnUnusableTimeout is returned when a connection is not usable and we timed out trying to mark it as unusable.
ErrConnUnusableTimeout = errors.New("redis: timed out trying to mark connection as unusable")
)
Functions
GetCachedTimeNs
func GetCachedTimeNs() int64
GetCachedTimeNs returns the current time in nanoseconds. Exported for use by other packages that need fast time access.
GlobalPools
func GlobalPools() ([]*ConnPool, []*PubSubPool)
GlobalPools returns the live pools that use the global metric table, so a recorder installed after they were created can still observe them.
SetAllMetricCallbacks
func SetAllMetricCallbacks(callbacks *MetricCallbacks)
SetAllMetricCallbacks sets the global metric callbacks atomically. Pools built with their own Options.Metrics are not affected. Pass nil to clear all callbacks (disable metrics).
Note on thread safety: After returning, there is a small window where a concurrent caller may still use the old callback table. This is acceptable for metrics - at most one event may go to the old recorder or be missed during the transition. The callbacks themselves are immutable function pointers, so calling an "old" callback is safe.
Types
BadConnError
type BadConnError struct {
// contains filtered or unexported fields
}
BadConnError.Error
func (e BadConnError) Error() string
BadConnError.Unwrap
func (e BadConnError) Unwrap() error
Conn
type Conn struct {
// contains filtered or unexported fields
}
NewConn
func NewConn(netConn net.Conn) *Conn
NewConnWithBufferSize
func NewConnWithBufferSize(netConn net.Conn, readBufSize, writeBufSize int) *Conn
Conn.CheckForData
func (cn *Conn) CheckForData() (bool, error)
CheckForData reports whether the socket has data ready and surfaces a detected closed or failed socket.
Conn.ClaimIdleForHandoff
func (cn *Conn) ClaimIdleForHandoff() (*HandoffState, bool)
ClaimIdleForHandoff takes an IDLE connection out of circulation for a handoff (IDLE -> UNUSABLE) and keeps its handoff mark, so the handoff can then be queued. It is for a connection nobody holds, which would never reach OnPut. It returns the claimed handoff state, to pass to MarkHandoffQueued, and false when the connection is not IDLE: a Get acquired it, and OnPut queues the handoff when the holder returns it.
Conn.ClearHandoffState
func (cn *Conn) ClearHandoffState()
ClearHandoffState clears the handoff state after successful handoff. Makes the connection usable again.
Conn.ClearPreparedFieldsets
func (cn *Conn) ClearPreparedFieldsets(epoch uint64)
ClearPreparedFieldsets forgets all HIMPORT fieldsets prepared on this connection and records the discard-all epoch the wipe corresponds to.
Conn.ClearRelaxedTimeout
func (cn *Conn) ClearRelaxedTimeout()
ClearRelaxedTimeout removes one holder that SetRelaxedTimeout added. When the last holder is gone and no unexpired deadline remains, it drops the whole window. The count has a lower bound of zero. So a second clear, or a clear after a deadline expiry already emptied the window, does nothing and cannot block a later relaxation. This method is lock-free.
Conn.Close
func (cn *Conn) Close() error
Conn.CloseOnPutReason
func (cn *Conn) CloseOnPutReason() string
CloseOnPutReason returns a non-empty reason when the connection should be removed instead of pooled on Put.
Conn.CompareAndSwapUsable
func (cn *Conn) CompareAndSwapUsable(old, new bool) bool
CompareAndSwapUsable atomically compares and swaps the usable flag (lock-free).
This is used by background operations (handoff, re-auth) to acquire exclusive access to a connection. The operation sets usable to false, preventing the pool from returning the connection to clients.
Returns true if the swap was successful (old value matched), false otherwise.
Implementation note: This is a compatibility wrapper around the state machine. It checks if the current state is "usable" (IDLE or IN_USE) and transitions accordingly. Deprecated: Use GetStateMachine().TryTransition() directly for better state management.
Conn.CompareAndSwapUsed
func (cn *Conn) CompareAndSwapUsed(old, new bool) bool
CompareAndSwapUsed atomically compares and swaps the used flag (lock-free). This method is kept for backwards compatibility.
This is the preferred method for acquiring a connection from the pool, as it ensures that only one goroutine marks the connection as used.
Implementation: Uses state machine transitions IDLE ⇄ IN_USE
Returns true if the swap was successful (old value matched), false otherwise. Deprecated: Use GetStateMachine().TryTransition() directly for better state management.
Conn.EffectiveReadTimeout
func (cn *Conn) EffectiveReadTimeout(normalTimeout time.Duration) time.Duration
EffectiveReadTimeout reports the read timeout that a read on this connection uses now. It returns the active relaxed timeout when the window is set and unexpired. Otherwise it returns normalTimeout. A caller that bounds how long a blocked read may take (for example, the CSC full-duplex drain backstop) must use this method, not the configured ReadTimeout. With ReadTimeout, a relaxed read ends too soon.
It is safe to call from several goroutines at once (the reader, the writer, and the drain backstop of a full-duplex connection). It reads one atomic snapshot. The only change it makes is the deadline safety net: when the deadline has passed, it removes the deadline holder once (see expireRelaxedTimeout). It never removes an active, unexpired window. If a notification holder survives that expiry, it returns that holder's relaxed timeout, not normalTimeout.
Conn.EffectiveWriteTimeout
func (cn *Conn) EffectiveWriteTimeout(normalTimeout time.Duration) time.Duration
EffectiveWriteTimeout is the write side of EffectiveReadTimeout. Use it to bound how long a blocked write may take. It has the same snapshot behavior.
Conn.ExecuteInitConn
func (cn *Conn) ExecuteInitConn(ctx context.Context) error
ExecuteInitConn runs the stored connection initialization function if available.
Conn.ExpiresAt
func (cn *Conn) ExpiresAt() time.Time
ExpiresAt returns the connection's absolute lifetime expiry (zero when no ConnMaxLifetime applies; jitter included). Set once at dial, so a plain read is safe. Long-holding callers bound their hold by the REMAINING lifetime.
Conn.FieldsetEpoch
func (cn *Conn) FieldsetEpoch() uint64
FieldsetEpoch returns the discard-all epoch this connection's prepared fieldsets belong to (0 when none were ever prepared on the session).
Conn.FieldsetPreparedVersion
func (cn *Conn) FieldsetPreparedVersion(name string) uint64
FieldsetPreparedVersion returns the client-side registry version at which the named HIMPORT fieldset was prepared on this connection's current server session, or 0 if it was not prepared on it (registry versions start at 1).
Conn.GetDialStartNs
func (cn *Conn) GetDialStartNs() int64
GetDialStartNs returns the time when the dial started (in nanoseconds since epoch). This is used to calculate the full connection creation time (TCP + handshake).
Conn.GetHandoffEndpoint
func (cn *Conn) GetHandoffEndpoint() string
GetHandoffEndpoint returns the new endpoint for handoff (lock-free).
Conn.GetHandoffInfo
func (cn *Conn) GetHandoffInfo() (bool, string, int64)
GetHandoffInfo returns all handoff information atomically (lock-free). This method prevents race conditions by returning all handoff state in a single atomic operation. Returns (shouldHandoff, endpoint, seqID).
Conn.GetID
func (cn *Conn) GetID() uint64
GetID returns the unique identifier for this connection.
Conn.GetMovingSeqID
func (cn *Conn) GetMovingSeqID() int64
GetMovingSeqID returns the sequence ID from the MOVING notification (lock-free).
Conn.GetNetConn
func (cn *Conn) GetNetConn() net.Conn
GetNetConn safely returns the current network connection using atomic load (lock-free). This method is used by the pool for health checks and provides better performance.
Conn.GetPubSubReAuth
func (cn *Conn) GetPubSubReAuth() func(username, password string) error
GetPubSubReAuth returns the currently installed Pub/Sub re-authentication callback, if any.
Conn.GetStateMachine
func (cn *Conn) GetStateMachine() *ConnStateMachine
GetStateMachine returns the connection's state machine for advanced state management. This is primarily used by internal packages like maintnotifications for handoff processing.
Conn.HandedOffSince
func (cn *Conn) HandedOffSince(gen uint32) bool
HandedOffSince reports whether a handoff took the connection over since gen was read. The state alone cannot tell: the handoff worker can take the connection back through IN_USE (its init commands run on it), so an IN_USE seen after the takeover is the worker's, not the previous holder's.
Conn.HandoffOwnerGen
func (cn *Conn) HandoffOwnerGen() uint32
HandoffOwnerGen returns the current handoff takeover count; pass it to HandedOffSince.
Conn.HandoffPending
func (cn *Conn) HandoffPending() bool
HandoffPending reports whether a handoff owns, or is about to own, the connection: it is marked (ShouldHandoff) or queued/running (an endpoint is set until ClearHandoffState). During a handoff the worker re-initializes the connection while it is still in the pool, and initConn leaves it IDLE before OnConnect has finished, so a state check alone cannot tell it is in use. Lock-free.
Conn.HandoffRetries
func (cn *Conn) HandoffRetries() int
HandoffRetries returns the current handoff retry count (lock-free).
Conn.HasBufferedData
func (cn *Conn) HasBufferedData() bool
HasBufferedData safely checks if the connection has buffered data. This method is used to avoid data races when checking for push notifications.
Conn.HasPreparedFieldsets
func (cn *Conn) HasPreparedFieldsets() bool
HasPreparedFieldsets reports whether any HIMPORT fieldset is prepared on this connection's current server session.
Conn.HasRelaxedTimeout
func (cn *Conn) HasRelaxedTimeout() bool
HasRelaxedTimeout returns true when the relaxed timeouts are active on this connection. Active means a holder is present, a timeout is set, and any deadline is still in the future. When the deadline has passed it removes the deadline holder once (like getEffective*) and re-reads the snapshot: a surviving non-deadline holder keeps the window active. Before this, an expired deadline made it report false even while another holder was still active, contradicting the surviving-holder semantics. This reports the boolean only; the timeout VALUE it would relax to may still be the expired holder's, since all holders share one (readNs, writeNs) pair — see the per-holder timeout follow-up.
Conn.IncrementAndGetHandoffRetries
func (cn *Conn) IncrementAndGetHandoffRetries(n int) int
IncrementAndGetHandoffRetries atomically increments and returns handoff retries (lock-free).
Conn.IsClosed
func (cn *Conn) IsClosed() bool
Conn.IsInited
func (cn *Conn) IsInited() bool
IsInited returns true if the connection has been initialized. This is a backward-compatible wrapper around the state machine.
Conn.IsPooled
func (cn *Conn) IsPooled() bool
IsPooled returns true if the connection is managed by a pool and will be pooled on Put.
Conn.IsPubSub
func (cn *Conn) IsPubSub() bool
IsPubSub returns true if the connection is used for PubSub.
Conn.IsResp3
func (cn *Conn) IsResp3() bool
IsResp3 reports whether the connection successfully negotiated RESP3.
Conn.IsUsable
func (cn *Conn) IsUsable() bool
IsUsable returns true if the connection is safe to use for new commands (lock-free).
A connection is "usable" when it's in a stable state and can be returned to clients. It becomes unusable during:
- Handoff operations (network connection replacement)
- Re-authentication (credential updates)
- Other background operations that need exclusive access
Note: CREATED state is considered usable because new connections need to pass OnGet() hook before initialization. The initialization happens after OnGet() in the client code.
Conn.IsUsed
func (cn *Conn) IsUsed() bool
IsUsed returns true if the connection is currently in use (lock-free).
Deprecated: Use GetStateMachine().GetState() == StateInUse directly for better clarity. This method is kept for backwards compatibility.
A connection is "used" when it has been retrieved from the pool and is actively processing a command. Background operations (like re-auth) should wait until the connection is not used before executing commands.
Conn.LastPutAtNs
func (cn *Conn) LastPutAtNs() int64
Conn.MarkCloseOnPut
func (cn *Conn) MarkCloseOnPut(reason string)
MarkCloseOnPut marks the connection for removal when it is returned to the pool.
Conn.MarkCscReadPending
func (cn *Conn) MarkCscReadPending()
MarkCscReadPending requests one conservative CSC drain after a command read when the transport may retain data that MaybeHasData cannot observe.
Conn.MarkFieldsetPrepared
func (cn *Conn) MarkFieldsetPrepared(name string, version, epoch uint64)
MarkFieldsetPrepared records that the named HIMPORT fieldset was prepared on this connection's current server session at the given registry version. A session acquiring its first fieldset adopts the given discard-all epoch (fieldsets prepared after an HIMPORT DISCARDALL are not subject to it); the epoch never moves backwards, so a mark carrying an older snapshot cannot regress a session already wiped at a newer epoch.
Conn.MarkForHandoff
func (cn *Conn) MarkForHandoff(newEndpoint string, seqID int64) error
MarkForHandoff marks the connection for handoff due to MOVING notification. Returns an error if the connection is already marked for handoff. Note: This only sets metadata - the connection state is not changed until OnPut. This allows the current user to finish using the connection before handoff.
Conn.MarkHandoffQueued
func (cn *Conn) MarkHandoffQueued(claimed *HandoffState)
MarkHandoffQueued clears the ShouldHandoff mark of a connection whose handoff was claimed (ClaimIdleForHandoff) and queued, so it is not queued again. Endpoint and seqID stay for the worker. It does not touch the connection state: the worker may already own it.
It changes only the claimed state. Once queued, the worker can finish the handoff (ClearHandoffState) and a later MOVING can mark the connection again before this runs; that new mark is a new state and is kept.
Conn.MarkQueuedForHandoff
func (cn *Conn) MarkQueuedForHandoff() error
MarkQueuedForHandoff marks the connection as queued for handoff processing. This makes the connection unusable until handoff completes. This is called from OnPut hook, where the connection is typically in IN_USE state. The pool will preserve the UNUSABLE state and not overwrite it with IDLE.
Conn.MaybeHasData
func (cn *Conn) MaybeHasData() bool
MaybeHasData tries to peek at the next byte in the socket without consuming it This is used to check if there are push notifications available Important: This will work on Linux, but not on Windows
Conn.PeekReplyTypeForCheck
func (cn *Conn) PeekReplyTypeForCheck() (byte, error)
PeekReplyTypeForCheck peeks at the reply type while holding readerMu, so it is safe against a concurrent SetNetConn resetting the reader during handoff. Unlike PeekReplyTypeSafe it does not require the data to already be buffered: the pool health check calls it after connCheck reports unexpected socket data, and connCheck only MSG_PEEKs, so the byte still has to be pulled from the socket into the reader here.
Conn.PeekReplyTypeSafe
func (cn *Conn) PeekReplyTypeSafe() (byte, error)
PeekReplyTypeSafe safely peeks at the reply type. This method is used to avoid data races when checking for push notifications.
Conn.PoolName
func (cn *Conn) PoolName() string
PoolName returns the name of the pool this connection belongs to. This is used for metrics to identify which pool a connection is from.
Conn.PreparedFieldsetNames
func (cn *Conn) PreparedFieldsetNames() []string
PreparedFieldsetNames returns the names of the HIMPORT fieldsets prepared on this connection's current server session.
Conn.Release
func (cn *Conn) Release() bool
Release releases the connection back to the pool. This is an optimized inline method for the hot path (Put operation).
It tries to transition from IN_USE -> IDLE. Returns true if the connection was successfully released, false otherwise.
Performance: This is faster than calling GetStateMachine() + TryTransitionFast().
NOTE: We directly access cn.stateMachine.state here instead of using the state machine's methods. This breaks encapsulation but is necessary for performance. Waiters parked in AwaitAndTransition for IDLE (re-auth, handoff) are notified after a successful transition; notifyWaiters costs one atomic load when nobody waits.
Conn.RemoteAddr
func (cn *Conn) RemoteAddr() net.Addr
Conn.ServingEndpoint
func (cn *Conn) ServingEndpoint() string
ServingEndpoint returns the logical dial/handoff endpoint, or empty when none has been recorded (callers fall back to Options.Addr).
Conn.SetInitConnFunc
func (cn *Conn) SetInitConnFunc(fn func(context.Context, *Conn) error)
SetInitConnFunc sets the connection initialization function to be called on reconnections.
Conn.SetLastPutAtNs
func (cn *Conn) SetLastPutAtNs(ns int64)
Conn.SetNetConn
func (cn *Conn) SetNetConn(netConn net.Conn)
Conn.SetNetConnAndInitConn
func (cn *Conn) SetNetConnAndInitConn(ctx context.Context, netConn net.Conn) error
SetNetConnAndInitConn replaces the underlying connection and executes the initialization. This method ensures only one initialization can happen at a time by using atomic state transitions. If another goroutine is currently initializing, this will wait for it to complete.
Conn.SetOnClose
func (cn *Conn) SetOnClose(fn func() error)
SetOnClose installs fn as the callback invoked exactly once when this connection is closed (via Conn.Close).
IMPORTANT: SetOnClose OVERWRITES any previously installed callback — it does not compose, chain, or deduplicate. A Conn has room for a single onClose hook by design, because its lifecycle is bounded (a Conn is created, optionally re-initialized on its own net.Conn, and then closed once) and the pool's OnRemove hooks handle any registry-level cleanup that must survive the net.Conn being swapped.
This has a subtle implication for per-connection subscriptions such as the unsubscribe function returned by StreamingCredentialsProvider (e.g. EntraID token rotation): if SetOnClose is called twice on the same Conn with DIFFERENT unsubscribe closures — for example because initConn ran a second time and obtained a fresh Subscribe() — the previous unsubscribe is dropped and will NEVER run, leaking a subscription on the provider. Callers must therefore ensure either:
- the provider's Subscribe is idempotent for the same listener (the streaming credentials Manager deduplicates listeners by connection id, so re-Subscribe returns an equivalent unsubscribe), OR
- the previous callback has already been invoked before SetOnClose is called again.
Design note: unlike the client-level onCloseHooks registry (see redis.baseClient), there is intentionally NO named-hook dedup or multi-callback support on Conn. This is a deliberate trade-off to keep the Conn object slim — a pool can hold thousands of Conn values and each one is a hot allocation, so paying for a sync.Mutex plus a map[string]func() error per connection to support a feature that would only be used by at most one subsystem today (streaming credentials) is not worth the per-connection memory and allocation cost. For a single Conn there is at most one meaningful close callback at any point in time, and a richer registry here would not even solve the "stale closure" hazard described above.
Conn.SetOnCscClose
func (cn *Conn) SetOnCscClose(fn func() error)
SetOnCscClose sets the client-side-caching close hook, overwriting any previous one. It runs on Close in addition to the SetOnClose callback.
Conn.SetOnCscReinit
func (cn *Conn) SetOnCscReinit(fn func())
SetOnCscReinit sets the client-side-caching pre-reinitialization hook, overwriting any previous one.
Conn.SetPoolName
func (cn *Conn) SetPoolName(name string)
SetPoolName sets the name of the pool this connection belongs to. This should be called when the connection is added to a pool.
Conn.SetPubSubReAuth
func (cn *Conn) SetPubSubReAuth(fn func(username, password string) error)
SetPubSubReAuth installs fn as the re-authentication callback for a Pub/Sub connection.
Conn.SetRelaxedTimeout
func (cn *Conn) SetRelaxedTimeout(readTimeout, writeTimeout time.Duration)
SetRelaxedTimeout sets the relaxed timeouts for this connection during a maintenance-notification upgrade. They apply to every later command until an equal number of ClearRelaxedTimeout calls remove this holder. This method is lock-free. It installs a new snapshot with a compare-and-swap and keeps any deadline that is already in effect. Note: the caller (the notification handler) records the metrics, because it knows the notification type and the pool name.
Conn.SetRelaxedTimeoutWithDeadline
func (cn *Conn) SetRelaxedTimeoutWithDeadline(readTimeout, writeTimeout time.Duration, deadline time.Time)
SetRelaxedTimeoutWithDeadline sets the relaxed timeouts and a deadline. After the deadline the window reverts on its own, because handoff never calls Clear. Only the first deadline window takes a holder slot. An overlapping handoff re-arms the window: it replaces the deadline in place and does not add a holder. So the later expiry removes exactly one holder and the window clears. The connection does not stay relaxed forever. This method is lock-free.
Conn.SetResp3
func (cn *Conn) SetResp3(v bool)
SetResp3 records whether the connection successfully negotiated RESP3.
Conn.SetServingEndpoint
func (cn *Conn) SetServingEndpoint(endpoint string)
SetServingEndpoint records the logical endpoint this connection was dialed or handed off to. Empty values are ignored. Call after a successful dial or SetNetConnAndInitConn so hostless redirects reuse the hostname, not RemoteAddr.
Conn.SetUsable
func (cn *Conn) SetUsable(usable bool)
SetUsable sets the usable flag for the connection (lock-free).
Deprecated: Use GetStateMachine().Transition() directly for better state management. This method is kept for backwards compatibility.
This should be called to mark a connection as usable after initialization or to release it after a background operation completes.
Prefer CompareAndSwapUsable() when acquiring exclusive access to avoid race conditions. Deprecated: Use GetStateMachine().Transition() directly for better state management.
Conn.SetUsed
func (cn *Conn) SetUsed(val bool)
SetUsed sets the used flag for the connection (lock-free).
This should be called when returning a connection to the pool (set to false) or when a single-connection pool retrieves its connection (set to true).
Prefer CompareAndSwapUsed() when acquiring from a multi-connection pool to avoid race conditions. Deprecated: Use GetStateMachine().Transition() directly for better state management.
Conn.SetUsedAt
func (cn *Conn) SetUsedAt(tm time.Time)
Conn.SetUsedAtNs
func (cn *Conn) SetUsedAtNs(ns int64)
Conn.ShouldHandoff
func (cn *Conn) ShouldHandoff() bool
ShouldHandoff returns true if connection needs handoff (lock-free).
Conn.TakeCscPeriodicReadPending
func (cn *Conn) TakeCscPeriodicReadPending(interval time.Duration) bool
TakeCscPeriodicReadPending schedules a throttled conservative read for transports with no readiness mechanism. It returns true at most once per interval, including when several drainer passes race.
Conn.TakeCscReadPending
func (cn *Conn) TakeCscReadPending() bool
TakeCscReadPending consumes the post-command conservative-drain request.
Conn.TryAcquire
func (cn *Conn) TryAcquire() bool
TryAcquire attempts to acquire the connection for use. This is an optimized inline method for the hot path (Get operation).
It tries to transition from IDLE -> IN_USE or CREATED -> CREATED. Returns true if the connection was successfully acquired, false otherwise. The CREATED->CREATED is done so we can keep the state correct for later initialization of the connection in initConn.
Performance: This is faster than calling GetStateMachine() + TryTransitionFast()
NOTE: We directly access cn.stateMachine.state here instead of using the state machine's methods. This breaks encapsulation but is necessary for performance. The IDLE->IN_USE and CREATED->CREATED transitions don't need waiter notification, and benchmarks show 1-3% improvement. If the state machine ever needs to notify waiters on these transitions, update this to use TryTransitionFast().
Conn.UnmarkFieldsetPrepared
func (cn *Conn) UnmarkFieldsetPrepared(name string)
UnmarkFieldsetPrepared forgets that the named HIMPORT fieldset was prepared on this connection, forcing a replay before the next HIMPORT SET using it.
Conn.UsedAt
func (cn *Conn) UsedAt() time.Time
Conn.UsedAtNs
func (cn *Conn) UsedAtNs() int64
Conn.WithReader
func (cn *Conn) WithReader( ctx context.Context, timeout time.Duration, fn func(rd *proto.Reader) error, ) error
Conn.WithReaderHardDeadline
func (cn *Conn) WithReaderHardDeadline( timeout time.Duration, fn func(rd *proto.Reader) error, ) (err error)
WithReaderHardDeadline runs fn under a HARD read deadline of now+timeout, bypassing getEffectiveReadTimeout so a relaxed maintenance timeout can't extend it (used by the CSC drainer). Takes no context: an expired cycle ctx must not become the socket deadline, or the read surfaces context.DeadlineExceeded, which isBadConn treats as fatal.
Conn.WithWriter
func (cn *Conn) WithWriter( ctx context.Context, timeout time.Duration, fn func(wr *proto.Writer) error, ) error
Conn.Write
func (cn *Conn) Write(b []byte) (int, error)
ConnPool
type ConnPool struct {
// contains filtered or unexported fields
}
NewConnPool
func NewConnPool(opt *Options) *ConnPool
ConnPool.AddPoolHook
func (p *ConnPool) AddPoolHook(hook PoolHook)
AddPoolHook adds a pool hook to the pool.
ConnPool.Close
func (p *ConnPool) Close() error
ConnPool.CloseConn
func (p *ConnPool) CloseConn(ctx context.Context, cn *Conn, reason string, fromState string) error
CloseConn closes a connection and records metrics. Parameters:
- ctx: context for metric callbacks (enables trace-to-metric correlation)
- cn: the connection to close
- reason: why the connection is being closed (use CloseReason* constants)
- fromState: unused; db.client.connection.count is read from Stats at collection time
ConnPool.DialExhaustion
func (p *ConnPool) DialExhaustion(ctx context.Context) *atomic.Bool
DialExhaustion retrieves the marker for this pool, if the caller set one.
ConnPool.DrainIdleConns
func (p *ConnPool) DrainIdleConns(ctx context.Context, st *DrainState, fn func(cn *Conn) error)
DrainIdleConns runs one pass of the CSC invalidation drainer over the current round, holding AT MOST ONE connection and its pool turn at a time (ctx is the per-cycle deadline). A round = idle conn ids snapshotted at start; mid-round arrivals are deferred. Each member is drainerPop'd and drained by fn, or — if no longer a claimable idle conn — reconciled (marked visited) so it can't hang the round. The drainer yields when no turn is immediately available, giving command traffic priority. Handles at least one member before honoring ctx (so a tiny DrainInterval can't stall it). No-ops if the pool is closed.
ConnPool.Filter
func (p *ConnPool) Filter(fn func(*Conn) bool) error
ConnPool.Get
func (p *ConnPool) Get(ctx context.Context) (*Conn, error)
Get returns existed connection from the pool or creates a new one.
ConnPool.HasFreeCapacity
func (p *ConnPool) HasFreeCapacity() bool
HasFreeCapacity reports whether the pool can likely serve another Get without blocking — a best-effort probe for the autopipeline straggler-hold gate (a false positive only costs a spill / short hold, never correctness). Checks, in order: a truly servable idle conn (usableIdleLen — plain IdleLen counts not-usable and handoff-marked entries an OnGet hook would divert); a free pool turn (accounts for in-use conns AND in-flight dials); room under PoolSize and MaxActiveConns (newConn's hard dial gate); a free dial slot (MaxConcurrentDials below PoolSize can saturate slots while a turn is free); and the dial circuit breaker not being open (a saturated dialErrorsNum makes the Get fail fast rather than serve).
ConnPool.IdleLen
func (p *ConnPool) IdleLen() int
IdleLen returns number of idle connections.
ConnPool.Len
func (p *ConnPool) Len() int
Len returns total number of connections.
ConnPool.Name
func (p *ConnPool) Name() string
Name returns the pool's configured name, which is stamped on every connection it creates (Conn.PoolName). Callers holding a Pooler can type assert to interface{ Name() string } to find which pool owns a connection — used by maintnotifications to route a handoff to the hook that owns the conn's pool rather than always the primary one.
ConnPool.NewConn
func (p *ConnPool) NewConn(ctx context.Context) (*Conn, error)
NewConn creates a dedicated connection outside the idle pool. It counts against MaxActiveConns and shares the MaxConcurrentDials gate with pooled connections, but does not acquire a PoolSize turn. Remove it with RemoveWithoutTurn when its owner is finished.
NOTE: If you directly get a connection from the pool, it won't be pooled and won't support maintnotifications upgrades.
ConnPool.PendingRequests
func (p *ConnPool) PendingRequests() (pending, started uint32)
PendingRequests returns the Gets waiting for a connection now and the Gets started since the pool was created (wraps at 2^32), from one atomic load.
ConnPool.Put
func (p *ConnPool) Put(ctx context.Context, cn *Conn)
ConnPool.RaiseMinIdleConns
func (p *ConnPool) RaiseMinIdleConns(n int32)
RaiseMinIdleConns raises the pool's minimum idle connections to at least n and starts filling it in the background. It never lowers the configured MinIdleConns or an earlier raise. Like MinIdleConns, the idle connections count against PoolSize and are dialed but not initialized: init runs on first Get. A raised pool also keeps its spare fresh: see refreshStaleSpare.
ConnPool.Remove
func (p *ConnPool) Remove(ctx context.Context, cn *Conn, reason error)
ConnPool.RemovePoolHook
func (p *ConnPool) RemovePoolHook(hook PoolHook)
RemovePoolHook removes a pool hook from the pool.
ConnPool.RemoveWithoutTurn
func (p *ConnPool) RemoveWithoutTurn(ctx context.Context, cn *Conn, reason error)
RemoveWithoutTurn removes a connection from the pool without freeing a turn. This should be used when removing a connection from a context that didn't acquire a turn via Get() (e.g., background workers, cleanup tasks). For normal removal after Get(), use Remove() instead.
ConnPool.RetireConns
func (p *ConnPool) RetireConns(ctx context.Context, conns []*Conn, reason string)
ConnPool.Size
func (p *ConnPool) Size() int
Size returns the maximum pool size (capacity).
This is used by the streaming credentials manager to size the re-auth worker pool, ensuring that re-auth operations don't exhaust the connection pool.
ConnPool.Stats
func (p *ConnPool) Stats() *Stats
ConnPool.SupportsPoolHooks
func (p *ConnPool) SupportsPoolHooks() bool
SupportsPoolHooks reports that AddPoolHook and RemovePoolHook are functional. Pooler adapters with no-op hook methods intentionally do not expose this optional capability.
ConnPool.TryGet
func (p *ConnPool) TryGet(ctx context.Context) (*Conn, error)
TryGet returns a connection only if a pool turn is free now. A free turn is an open slot or room to dial a new connection. TryGet never waits out PoolTimeout for a full pool. It returns ErrPoolTryFull at once instead. This lets a caller with a fallback (the pipeline pool) spill without a stall. ErrPoolTryFull is different from ErrPoolTimeout: no wait happened, so getConn does not count the spill as a pool timeout. Re-authentication at the hard MaxActiveConns limit returns ErrPoolTryFull, while exhaustion without re-auth returns ErrPoolExhausted. TryGet dials under an acquired turn when capacity remains.
ConnPool.WithDialExhaustion
func (p *ConnPool) WithDialExhaustion(ctx context.Context, exhausted *atomic.Bool) context.Context
WithDialExhaustion tracks a failed pool dial sequence without wrapping its error. The returned marker belongs to this connection acquisition only.
ConnRetirer
type ConnRetirer interface {
RetireConns(ctx context.Context, conns []*Conn, reason string)
}
ConnState
type ConnState uint32
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/CLOSED
StateCreated (6 declarations)
const ( // StateCreated - Connection just created, not yet initialized StateCreated ConnState = iota // StateInitializing - Connection initialization in progress StateInitializing // StateIdle - Connection initialized and idle in pool, ready to be acquired StateIdle // 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 closed StateClosed )
ValidFromCreatedIdleOrUnusable
func ValidFromCreatedIdleOrUnusable() []ConnState
ValidFromCreatedIdleOrUnusable returns a predefined slice for initialization transitions. Use this to avoid allocations when calling AwaitAndTransition or TryTransition.
ValidFromIdle
func ValidFromIdle() []ConnState
ValidFromIdle returns a predefined slice containing only StateIdle. Use this to avoid allocations when calling AwaitAndTransition or TryTransition.
ConnState.String
func (s ConnState) String() string
String returns a human-readable string representation of the state.
ConnStateMachine
type ConnStateMachine struct {
// contains filtered or unexported fields
}
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.
NewConnStateMachine
func NewConnStateMachine() *ConnStateMachine
NewConnStateMachine creates a new connection state machine. Initial state is StateCreated.
ConnStateMachine.AwaitAndTransition
func (sm *ConnStateMachine) AwaitAndTransition( ctx context.Context, validFromStates []ConnState, targetState ConnState, ) (ConnState, error)
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 channel
ConnStateMachine.GetState
func (sm *ConnStateMachine) GetState() ConnState
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.
ConnStateMachine.Transition
func (sm *ConnStateMachine) Transition(targetState ConnState)
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.
ConnStateMachine.TryTransition
func (sm *ConnStateMachine) TryTransition(validFromStates []ConnState, targetState ConnState) (ConnState, error)
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).
ConnStateMachine.TryTransitionFast
func (sm *ConnStateMachine) TryTransitionFast(fromState, targetState ConnState) bool
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.
ContextDeadlineError
type ContextDeadlineError struct {
// contains filtered or unexported fields
}
ContextDeadlineError preserves the socket timeout for connection lifecycle decisions.
ContextDeadlineError.Error
func (e *ContextDeadlineError) Error() string
ContextDeadlineError.Is
func (e *ContextDeadlineError) Is(target error) bool
ContextDeadlineError.Temporary
func (e *ContextDeadlineError) Temporary() bool
Temporary is declared so the error still satisfies net.Error.
ContextDeadlineError.Timeout
func (e *ContextDeadlineError) Timeout() bool
ContextDeadlineError.Unwrap
func (e *ContextDeadlineError) Unwrap() error
DrainState
type DrainState struct {
// contains filtered or unexported fields
}
DrainState carries the cross-pass round bookkeeping for the CSC drainer. It is owned by one drainer goroutine, so no synchronization is needed.
HandoffState
type HandoffState struct {
ShouldHandoff bool // Whether connection should be handed off
Endpoint string // New endpoint for handoff
SeqID int64 // Sequence ID from MOVING notification
}
HandoffState represents the atomic state for connection handoffs This struct is stored atomically to prevent race conditions between checking handoff status and reading handoff parameters
MetricCallbacks
type MetricCallbacks struct {
// ConnectionCreateTime is called when a new connection is created
ConnectionCreateTime func(ctx context.Context, duration time.Duration, cn *Conn)
// ConnectionRelaxedTimeout is called when connection timeout is relaxed/unrelaxed
// delta: +1 for relaxed, -1 for unrelaxed
ConnectionRelaxedTimeout func(ctx context.Context, delta int, cn *Conn, poolName, notificationType string)
// ConnectionHandoff is called when a connection is handed off to another node
ConnectionHandoff func(ctx context.Context, cn *Conn, poolName string)
// Error is called when an error occurs
Error func(ctx context.Context, errorType string, cn *Conn, statusCode string, isInternal bool, retryAttempts int)
// MaintenanceNotification is called when a maintenance notification is received
MaintenanceNotification func(ctx context.Context, cn *Conn, notificationType string)
// ConnectionWaitTime is called to record time spent waiting for a connection
ConnectionWaitTime func(ctx context.Context, duration time.Duration, cn *Conn)
// ConnectionClosed is called when a connection is closed
ConnectionClosed func(ctx context.Context, cn *Conn, reason string, err error)
// PendingRequests is called when pending requests count changes (UpDownCounter)
// delta: +1 when request starts waiting, -1 when request stops waiting
// poolName is passed explicitly because we may not have a connection yet when request starts
PendingRequests func(ctx context.Context, delta int, cn *Conn, poolName string)
}
MetricCallbacks holds all metric callback functions. Use SetAllMetricCallbacks to register all callbacks atomically.
MetricsOf
func MetricsOf(cn *Conn) *MetricCallbacks
MetricsOf returns the metric callbacks of the pool cn was dialed by: the pool's own Options.Metrics, or the global table. Never nil.
Options
type Options struct {
Dialer func(context.Context) (net.Conn, error)
ReadBufferSize int
WriteBufferSize int
PoolFIFO bool
PoolSize int32
MaxConcurrentDials int
DialTimeout time.Duration
PoolTimeout time.Duration
MinIdleConns int32
MaxIdleConns int32
MaxActiveConns int32
ConnMaxIdleTime time.Duration
ConnMaxLifetime time.Duration
ConnMaxLifetimeJitter time.Duration
ConnMaxLifetimeReapInterval time.Duration
PushNotificationsEnabled bool
// DialerRetries is the maximum number of retry attempts when dialing fails.
// Default: 5
DialerRetries int
// DialerRetryTimeout is the backoff duration between retry attempts.
// Default: 100ms
DialerRetryTimeout time.Duration
// DialerRetryBackoff controls the delay between dial retry attempts.
// If nil, dial retry backoff is constant and equals DialerRetryTimeout (default: 100ms).
DialerRetryBackoff func(attempt int) time.Duration
// Name is a unique identifier for this pool, used in metrics.
// Format: addr_uniqueID (e.g., "localhost:6379_a1b2c3d4")
Name string
// Metrics is this pool's metric callback table. nil means the global table
// set by SetAllMetricCallbacks. A pool with its own table is bound to it
// for life and is not recounted when the global table changes.
Metrics *MetricCallbacks
}
PoolHook
type PoolHook interface {
// OnGet is called when a connection is retrieved from the pool.
// It can modify the connection or return an error to prevent its use.
// The accept flag can be used to prevent the connection from being used.
// On Accept = false the connection is rejected and returned to the pool.
// The error can be used to prevent the connection from being used and returned to the pool.
// On Errors, the connection is removed from the pool.
// It has isNewConn flag to indicate if this is a new connection (rather than idle from the pool)
// The flag can be used for gathering metrics on pool hit/miss ratio.
OnGet(ctx context.Context, conn *Conn, isNewConn bool) (accept bool, err error)
// OnPut is called when a connection is returned to the pool.
// It returns whether the connection should be pooled and whether it should be removed.
OnPut(ctx context.Context, conn *Conn) (shouldPool bool, shouldRemove bool, err error)
// OnRemove is called when a connection is removed from the pool.
// This happens when:
// - Connection fails health check
// - Connection exceeds max lifetime
// - Pool is being closed
// - Connection encounters an error
// Implementations should clean up any per-connection state.
// The reason parameter indicates why the connection was removed.
OnRemove(ctx context.Context, conn *Conn, reason error)
}
PoolHook defines the interface for connection lifecycle hooks.
PoolHookManager
type PoolHookManager struct {
// contains filtered or unexported fields
}
PoolHookManager manages multiple pool hooks.
NewPoolHookManager
func NewPoolHookManager() *PoolHookManager
NewPoolHookManager creates a new pool hook manager.
PoolHookManager.AddHook
func (phm *PoolHookManager) AddHook(hook PoolHook)
AddHook adds a pool hook to the manager. Hooks are called in the order they were added.
PoolHookManager.Clone
func (phm *PoolHookManager) Clone() *PoolHookManager
Clone creates a copy of the hook manager with the same hooks. This is used for lock-free atomic updates of the hook manager.
PoolHookManager.GetHookCount
func (phm *PoolHookManager) GetHookCount() int
GetHookCount returns the number of registered hooks (for testing).
PoolHookManager.GetHooks
func (phm *PoolHookManager) GetHooks() []PoolHook
GetHooks returns a copy of all registered hooks.
PoolHookManager.ProcessOnGet
func (phm *PoolHookManager) ProcessOnGet(ctx context.Context, conn *Conn, isNewConn bool) (acceptConn bool, err error)
ProcessOnGet calls all OnGet hooks in order. If any hook returns an error, processing stops and the error is returned.
PoolHookManager.ProcessOnPut
func (phm *PoolHookManager) ProcessOnPut(ctx context.Context, conn *Conn) (shouldPool bool, shouldRemove bool, err error)
ProcessOnPut calls all OnPut hooks in order. The first hook that returns shouldRemove=true or shouldPool=false will stop processing.
PoolHookManager.ProcessOnRemove
func (phm *PoolHookManager) ProcessOnRemove(ctx context.Context, conn *Conn, reason error)
ProcessOnRemove calls all OnRemove hooks in order.
PoolHookManager.RemoveHook
func (phm *PoolHookManager) RemoveHook(hook PoolHook)
RemoveHook removes a pool hook from the manager.
Pooler
type Pooler interface {
NewConn(context.Context) (*Conn, error)
CloseConn(ctx context.Context, cn *Conn, reason string, fromState string) error
Get(context.Context) (*Conn, error)
Put(context.Context, *Conn)
Remove(context.Context, *Conn, error)
Len() int
IdleLen() int
Stats() *Stats
// Size returns the maximum pool size (capacity).
// This is used by the streaming credentials manager to size the re-auth worker pool.
Size() int
AddPoolHook(hook PoolHook)
RemovePoolHook(hook PoolHook)
// RemoveWithoutTurn removes a connection from the pool without freeing a turn.
// This should be used when removing a connection from a context that didn't acquire
// a turn via Get() (e.g., background workers, cleanup tasks).
// For normal removal after Get(), use Remove() instead.
RemoveWithoutTurn(context.Context, *Conn, error)
Close() error
}
PubSubPool
type PubSubPool struct {
// contains filtered or unexported fields
}
PubSubPool manages a pool of PubSub connections.
NewPubSubPool
func NewPubSubPool(opt *Options, netDialer func(ctx context.Context, network, addr string) (net.Conn, error)) *PubSubPool
NewPubSubPool implements a pool for PubSub connections. It intentionally does not implement the Pooler interface
PubSubPool.Close
func (p *PubSubPool) Close() error
PubSubPool.Name
func (p *PubSubPool) Name() string
Name returns the pool's configured name, the one its connections carry (Conn.PoolName).
PubSubPool.NewConn
func (p *PubSubPool) NewConn(ctx context.Context, network string, addr string, channels []string) (*Conn, error)
PubSubPool.Stats
func (p *PubSubPool) Stats() *PubSubStats
PubSubPool.TrackConn
func (p *PubSubPool) TrackConn(cn *Conn) error
TrackConn registers an initialized connection. If Close has already started, it closes the connection (including its initialization cleanup) and rejects it.
PubSubPool.UntrackConn
func (p *PubSubPool) UntrackConn(cn *Conn)
PubSubStats
type PubSubStats struct {
Created uint32
Untracked uint32
Active uint32
}
PubSubStats contains pub/sub connection pool stats.
TODO(cxl): the uint32 fields below will be changed to atomic.Uint32 in v10, which is a breaking API change.
SingleConnPool
type SingleConnPool struct {
// contains filtered or unexported fields
}
SingleConnPool is a pool that always returns the same connection. Note: This pool is not thread-safe. It is intended to be used by clients that need a single connection.
NewSingleConnPool
func NewSingleConnPool(pool Pooler, cn *Conn) *SingleConnPool
NewSingleConnPool creates a new single connection pool. The pool will always return the same connection. The pool will not: - Close the connection - Reconnect the connection - Track the connection in any way
SingleConnPool.AddPoolHook
func (p *SingleConnPool) AddPoolHook(_ PoolHook)
SingleConnPool.Close
func (p *SingleConnPool) Close() error
SingleConnPool.CloseConn
func (p *SingleConnPool) CloseConn(ctx context.Context, cn *Conn, reason string, fromState string) error
SingleConnPool.Get
func (p *SingleConnPool) Get(_ context.Context) (*Conn, error)
SingleConnPool.IdleLen
func (p *SingleConnPool) IdleLen() int
SingleConnPool.Len
func (p *SingleConnPool) Len() int
SingleConnPool.NewConn
func (p *SingleConnPool) NewConn(ctx context.Context) (*Conn, error)
SingleConnPool.Put
func (p *SingleConnPool) Put(_ context.Context, cn *Conn)
SingleConnPool.Remove
func (p *SingleConnPool) Remove(_ context.Context, cn *Conn, reason error)
SingleConnPool.RemovePoolHook
func (p *SingleConnPool) RemovePoolHook(_ PoolHook)
SingleConnPool.RemoveWithoutTurn
func (p *SingleConnPool) RemoveWithoutTurn(ctx context.Context, cn *Conn, reason error)
RemoveWithoutTurn has the same behavior as Remove for SingleConnPool since SingleConnPool doesn't use a turn-based queue system.
SingleConnPool.Size
func (p *SingleConnPool) Size() int
Size returns the maximum pool size, which is always 1 for SingleConnPool.
SingleConnPool.Stats
func (p *SingleConnPool) Stats() *Stats
Stats
type Stats struct {
Hits uint32 // number of times free connection was found in the pool
Misses uint32 // number of times free connection was NOT found in the pool
Timeouts uint32 // number of times a wait timeout occurred
WaitCount uint32 // number of times a connection was waited
Unusable uint32 // number of times a connection was found to be unusable
WaitDurationNs int64 // total time spent for waiting a connection in nanoseconds
TotalConns uint32 // number of total connections in the pool
IdleConns uint32 // number of idle connections in the pool
StaleConns uint32 // number of stale connections removed from the pool
PendingRequests uint32 // number of pending requests waiting for a connection
PubSubStats PubSubStats
// PipelineStats holds the stats of the separate pipeline connection pool
// when one is configured (PipelineReadBufferSize/PipelineWriteBufferSize).
// nil when pipelines share the main pool.
PipelineStats *Stats
}
Stats contains pool state information and accumulated stats.
TODO(cxl): the uint32/int64 fields below will be changed to atomic value types (atomic.Uint32/atomic.Int64) in v10, which is a breaking API change.
StickyConnPool
type StickyConnPool struct {
// contains filtered or unexported fields
}
NewStickyConnPool
func NewStickyConnPool(pool Pooler) *StickyConnPool
StickyConnPool.AddPoolHook
func (p *StickyConnPool) AddPoolHook(hook PoolHook)
StickyConnPool.Close
func (p *StickyConnPool) Close() error
StickyConnPool.CloseConn
func (p *StickyConnPool) CloseConn(ctx context.Context, cn *Conn, reason string, fromState string) error
StickyConnPool.DiscardOnClose
func (p *StickyConnPool) DiscardOnClose()
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.
StickyConnPool.Get
func (p *StickyConnPool) Get(ctx context.Context) (*Conn, error)
StickyConnPool.IdleLen
func (p *StickyConnPool) IdleLen() int
StickyConnPool.Len
func (p *StickyConnPool) Len() int
StickyConnPool.NewConn
func (p *StickyConnPool) NewConn(ctx context.Context) (*Conn, error)
StickyConnPool.NewConnOnGet
func (p *StickyConnPool) NewConnOnGet()
NewConnOnGet makes the first Get (and the first Get after Reset) dial a new, non-pooled connection instead of borrowing an idle one. Such connections do not acquire a pool turn and are always removed on Close, without freeing one. It must be called before the pool is used.
StickyConnPool.Put
func (p *StickyConnPool) Put(ctx context.Context, cn *Conn)
StickyConnPool.Remove
func (p *StickyConnPool) Remove(ctx context.Context, cn *Conn, reason error)
StickyConnPool.RemovePoolHook
func (p *StickyConnPool) RemovePoolHook(hook PoolHook)
StickyConnPool.RemoveWithoutTurn
func (p *StickyConnPool) RemoveWithoutTurn(ctx context.Context, cn *Conn, reason error)
RemoveWithoutTurn has the same behavior as Remove for StickyConnPool since StickyConnPool doesn't use a turn-based queue system.
StickyConnPool.Reset
func (p *StickyConnPool) Reset(ctx context.Context) error
StickyConnPool.SetOnFirstConn
func (p *StickyConnPool) SetOnFirstConn(fn func(*Conn))
SetOnFirstConn configures a callback that runs when the sticky pool first claims a parent connection. It must be called before the pool is used.
StickyConnPool.Size
func (p *StickyConnPool) Size() int
Size returns the maximum pool size, which is always 1 for StickyConnPool.
StickyConnPool.Stats
func (p *StickyConnPool) Stats() *Stats