Skip to main content

RedisConnection

Struct RedisConnection 

Source
pub struct RedisConnection { /* private fields */ }
Expand description

A single Redis connection implementing tower::Service<Cmd>.

This is the foundational building block. It owns a framed TCP/TLS/Unix connection and serializes commands one at a time.

RedisConnection requires &mut self for Service::call, which is the correct Tower contract for a non-multiplexed connection. For shared access across tasks, wrap with tower::buffer::Buffer.

Cancelling an in-flight Service::call closes the connection. Once a request may have reached Redis, reusing its transport could let the next call consume the cancelled request’s late response. A subsequent poll_ready therefore returns RedisError::ConnectionClosed.

§Example

Typed command types such as Get live in the redis-tower-commands crate, which depends on this one, so the example below stands in a minimal local Command implementation (hidden) and runs it with execute:

use redis_tower_core::{Command, Frame, RedisConnection, RedisError};
let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
let value = conn.execute(Get("my_key".to_string())).await?;

Implementations§

Source§

impl RedisConnection

Source

pub async fn connect(addr: &str) -> Result<RedisConnection, RedisError>

Connect to a Redis server over TCP.

TCP keepalive is enabled with sensible defaults: 60 s idle, 10 s interval, 3 probes. Use connect_with_keepalive to supply custom keepalive parameters.

Source

pub async fn connect_with_config( addr: &str, config: &ConnectionConfig, ) -> Result<RedisConnection, RedisError>

Connect to a Redis server over TCP with explicit connection settings.

The configured RESP decode limits are installed before any server data is read, including CLIENT SETINFO and protocol-negotiation replies.

Source

pub async fn connect_with_keepalive( addr: &str, keepalive: &KeepaliveConfig, ) -> Result<RedisConnection, RedisError>

Connect to a Redis server over TCP with a custom keepalive configuration.

§Errors

Returns RedisError::Connection if the TCP connection fails or if the keepalive socket options cannot be applied.

Source

pub async fn connect_with_timeout( addr: &str, timeout: Duration, ) -> Result<RedisConnection, RedisError>

Connect to a Redis server over TCP with a connect timeout.

If the TCP handshake is not completed within timeout, returns RedisError::ConnectTimeout instead of waiting for the OS-default timeout (which can be several minutes on unreachable hosts).

TCP keepalive is enabled with sensible defaults after the connection is established. Use connect_with_config to combine a timeout with custom keepalive or RESP decode limits.

§Example
use redis_tower_core::RedisConnection;
use std::time::Duration;

let conn = RedisConnection::connect_with_timeout("127.0.0.1:6379", Duration::from_secs(3)).await;
Source

pub async fn connect_tls( addr: &str, hostname: &str, tls_config: &TlsConfig, ) -> Result<RedisConnection, RedisError>

Available on crate features tls-native-tls or tls-rustls only.

Connect over TLS using the provided configuration.

Requires either the tls-native-tls or tls-rustls feature.

TCP keepalive is enabled with sensible defaults: 60 s idle, 10 s interval, 3 probes. Use connect_tls_with_keepalive to supply custom keepalive parameters.

Source

pub async fn connect_tls_with_config( addr: &str, hostname: &str, tls_config: &TlsConfig, config: &ConnectionConfig, ) -> Result<RedisConnection, RedisError>

Available on crate features tls-native-tls or tls-rustls only.

Connect over TLS with explicit connection settings.

The TCP connect timeout, keepalive policy, protocol negotiation, and RESP decode limits all come from config. The connect timeout covers the TCP handshake only, matching connect_tls_with_timeout.

Source

pub async fn connect_tls_with_keepalive( addr: &str, hostname: &str, tls_config: &TlsConfig, keepalive: &KeepaliveConfig, ) -> Result<RedisConnection, RedisError>

Available on crate features tls-native-tls or tls-rustls only.

Connect over TLS with a custom keepalive configuration.

Requires either the tls-native-tls or tls-rustls feature.

§Errors

Returns RedisError::Connection if the TCP connection or TLS handshake fails, or if the keepalive socket options cannot be applied.

Source

pub async fn connect_tls_with_timeout( addr: &str, hostname: &str, tls_config: &TlsConfig, timeout: Duration, ) -> Result<RedisConnection, RedisError>

Available on crate features tls-native-tls or tls-rustls only.

Connect over TLS with a connect timeout.

Requires either the tls-native-tls or tls-rustls feature.

If the TCP handshake is not completed within timeout, returns RedisError::ConnectTimeout. The timeout covers only the TCP connection phase; the TLS handshake runs outside the timeout window.

§Errors

Returns RedisError::ConnectTimeout if the TCP connect times out, RedisError::Connection if the TCP connection or TLS handshake fails, or RedisError::Connection if keepalive socket options cannot be applied.

Source

pub async fn connect_url(url: &str) -> Result<RedisConnection, RedisError>

Connect using a Redis URL.

Supports redis://, rediss:// (TLS), their Valkey aliases, and unix://, redis+unix://, and valkey+unix:// Unix-socket URLs.

Unix URLs accept user, pass, db, and protocol query parameters:

redis+unix:///run/redis%20server.sock?user=app&pass=secret&db=1&protocol=resp3

For rediss:// URLs, a TLS backend feature must be enabled. The tls-rustls backend is preferred if both are enabled.

Source

pub async fn connect_url_with_config( url: &str, config: &ConnectionConfig, ) -> Result<RedisConnection, RedisError>

Connect using a Redis URL with explicit connection settings.

URL authentication and database selection run before RESP negotiation. ?protocol=2|resp2|3|resp3 selects a protocol when the connection config uses ProtocolVersion::Auto. An explicit protocol in ConnectionConfig takes precedence, which lets RESP3-only clients enforce their invariant. Decode limits are active for every setup response.

Source

pub async fn begin_url_connection_with_config( url: &str, config: &ConnectionConfig, ) -> Result<PendingRedisConnection, RedisError>

Open the transport described by a Redis URL without applying its static credentials, selected database, or RESP protocol yet.

This is the provider-authentication seam used by higher-level connection factories. The returned connection starts in RESP2, while preserving the URL’s TCP, TLS, or Unix transport, database, and protocol settings. Authenticate it through PendingRedisConnection::connection_mut, then call PendingRedisConnection::finish.

The URL’s username and password are intentionally ignored on this path; they remain active on connect_url_with_config.

Source

pub async fn connect_url_with_tls( url: &str, tls_config: &TlsConfig, ) -> Result<RedisConnection, RedisError>

Available on crate features tls-native-tls or tls-rustls only.

Connect from a Redis URL, performing the TLS handshake with an explicit TlsConfig.

Like connect_url but the caller supplies the TLS configuration – a custom root CA, a client certificate for mTLS, or a pre-built backend – instead of the URL’s hardcoded default. The host, port, and any AUTH/SELECT parameters still come from the URL, and the connection always uses TLS (for either a redis:// or rediss:// URL). Unix-socket URLs are rejected.

§Example
use redis_tower_core::RedisConnection;
use redis_tower_core::tls::TlsConfig;

let tls = TlsConfig::default_rustls()
    .with_root_ca_pem(std::fs::read("ca.pem")?)
    .with_client_auth_pem(std::fs::read("client.pem")?, std::fs::read("client.key")?);
let conn = RedisConnection::connect_url_with_tls(
    "rediss://default:secret@redis.internal:6379",
    &tls,
)
.await?;
Source

pub async fn connect_url_with_tls_and_config( url: &str, tls_config: &TlsConfig, config: &ConnectionConfig, ) -> Result<RedisConnection, RedisError>

Available on crate features tls-native-tls or tls-rustls only.

Connect from a Redis URL with explicit TLS and connection settings.

This combines a custom CA or mTLS configuration with keepalive, connection timeout, protocol, and RESP decode-limit settings. Unix socket URLs are rejected because this connector always uses TLS.

Source

pub async fn begin_url_connection_with_tls_and_config( url: &str, tls_config: &TlsConfig, config: &ConnectionConfig, ) -> Result<PendingRedisConnection, RedisError>

Available on crate features tls-native-tls or tls-rustls only.

Open a staged URL connection using explicit TLS configuration.

This is the custom-CA/mTLS counterpart to begin_url_connection_with_config. The URL must describe a TCP endpoint; Unix URLs are rejected. Static URL credentials are ignored so the caller can authenticate through a dynamic provider before database selection and protocol negotiation.

Source

pub async fn connect_resp3(addr: &str) -> Result<RedisConnection, RedisError>

Connect to a Redis server and negotiate RESP3 protocol.

Sends HELLO 3 after connecting. The server will respond with RESP3 frames for all subsequent commands.

Source

pub fn is_resp3(&self) -> bool

Whether this connection has negotiated RESP3 (via HELLO 3).

Returns false for a plain RESP2 connection. Useful for tests and for middleware that behaves differently under the two protocols – push-based features such as client-side caching require RESP3.

Source

pub async fn connect_with_protocol( addr: &str, version: ProtocolVersion, ) -> Result<RedisConnection, RedisError>

Connect and negotiate the protocol explicitly.

§Example
use redis_tower_core::{RedisConnection, ProtocolVersion};
let conn = RedisConnection::connect_with_protocol(
    "127.0.0.1:6379",
    ProtocolVersion::Resp3,
).await?;
assert!(conn.is_resp3());
Source

pub async fn negotiate_protocol( &mut self, version: ProtocolVersion, ) -> Result<(), RedisError>

Negotiate version on an already-connected connection.

This is useful for connection setup that must run before protocol negotiation, such as authenticating a protected Redis Cluster node. Requesting RESP2 only sends HELLO 2 when the connection is currently in RESP3; a fresh RESP2 connection does not pay an extra round trip.

Source

pub async fn hello(&mut self, version: u8) -> Result<Frame, RedisError>

Send HELLO to negotiate protocol version.

HELLO 3 switches to RESP3, HELLO 2 switches back to RESP2.

Source

pub fn from_stream(stream: RedisStream) -> RedisConnection

Wrap an existing stream in a RedisConnection.

Source

pub fn from_stream_with_config( stream: RedisStream, config: &ConnectionConfig, ) -> RedisConnection

Wrap an existing stream using explicit connection settings.

Only the RESP decode limits apply to an already-open stream. Keepalive, connect timeout, and protocol negotiation are connection-establishment settings and are not replayed by this synchronous constructor.

Source

pub fn subscribe_pushes(&mut self) -> UnboundedReceiver<Frame>

Subscribe to RESP3 push messages.

Returns a receiver for out-of-band push frames (e.g., invalidation messages from CLIENT TRACKING). Push frames received during normal command execution are automatically routed to this channel.

If nobody subscribes, push frames are silently discarded.

§Reconnection Warning

Push subscriptions do not survive reconnection. If the underlying TCP connection drops and a new connection is established (e.g., via ResilientConnection or manual reconnection), any server-side state such as CLIENT TRACKING registrations is lost. The push receiver will stop receiving messages until the tracking is re-enabled on the new connection.

To handle this, implement ConnectionFactory yourself and replay setup commands (e.g., CLIENT TRACKING ON) inside connect(). This ensures the setup runs on every fresh connection, including reconnections.

ConnectionFactory lives in the redis-tower crate, which depends on this one, so the setup below is shown as the standalone function that the factory’s connect() body calls:

use redis_tower_core::{Frame, RedisConnection, RedisError};
use redis_tower_protocol::helpers::{array, bulk};
use tokio::sync::mpsc::UnboundedReceiver;

let mut conn = RedisConnection::connect_resp3(addr).await?;
// Replay CLIENT TRACKING and re-subscribe on every new connection.
conn.execute_pipeline(vec![array(vec![bulk("CLIENT"), bulk("TRACKING"), bulk("ON")])])
    .await?;
let pushes = conn.subscribe_pushes();
Ok((conn, pushes))
Source

pub async fn read_idle_push(&mut self) -> Result<(), RedisError>

Wait for one unsolicited RESP3 push frame while the connection is idle.

The frame is routed to the receiver returned by subscribe_pushes, matching the behavior of command-response reads. EOF, decode failures, and non-push frames are returned as errors because a response arriving without an outstanding command means protocol alignment has been lost.

This method is cancellation-safe: it borrows the framed transport in place, so cancelling the wait preserves both the transport and any partially buffered frame. It is intended for an exclusive connection owner, such as an auto-pipeline worker, and must not be called while a Service::call future is in flight.

Source

pub async fn execute<Cmd>( &mut self, cmd: Cmd, ) -> Result<<Cmd as Command>::Response, RedisError>
where Cmd: Command,

Send a command and receive the response.

This is the low-level method. Prefer using the Service trait via tower::ServiceExt::oneshot or Service::call.

§Large values

For values approaching 10MB or larger, the sequential send-then-read pattern can cause TCP backpressure issues on some managed Redis services (e.g., ElastiCache) if the write buffer fills before the response starts being read. Consider using AutoPipelineService for large-value workloads, or splitting large values across multiple keys.

Cancelling this future after dispatch closes the connection. The transport is checked out of self until a complete response has been read, preventing a later command from consuming a cancelled command’s response.

Source

pub async fn execute_pipeline( &mut self, frames: Vec<Frame>, ) -> Result<Vec<Frame>, RedisError>

Send multiple command frames and read all responses in a single roundtrip.

Used by pipeline and transaction implementations. Cancelling before every response has been read closes the connection.

Source

pub async fn execute_transaction( &mut self, watch_frames: Vec<Frame>, command_frames: Vec<Frame>, ) -> Result<Option<Vec<Frame>>, RedisError>

Execute a WATCH/MULTI/EXEC transaction sequence.

Returns Ok(Some(responses)) on commit, Ok(None) if aborted by WATCH.

Source

pub fn into_framed(self) -> Result<Framed<RedisStream, RespCodec>, RedisError>

Consume this connection and extract the underlying framed stream.

Fails if a Service::call future is still in flight.

Trait Implementations§

Source§

impl PipelineExecutor for RedisConnection

Source§

fn execute_pipeline( &mut self, frames: Vec<Frame>, ) -> impl Future<Output = Result<Vec<Frame>, RedisError>> + Send

Send frames as a pipelined batch and return the responses in order.
Source§

impl RedisExecutor for RedisConnection

Source§

fn execute<Cmd: Command>( &mut self, cmd: Cmd, ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send

Execute a Redis command and return its typed response.
Source§

impl<Cmd> Service<Cmd> for RedisConnection
where Cmd: Command,

Source§

type Response = <Cmd as Command>::Response

Responses given by the service.
Source§

type Error = RedisError

Errors produced by the service.
Source§

type Future = Pin<Box<dyn Future<Output = Result<<Cmd as Command>::Response, RedisError>> + Send>>

The future response value.
Source§

fn poll_ready( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), <RedisConnection as Service<Cmd>>::Error>>

Returns Poll::Ready(Ok(())) when the service is able to process requests. Read more
Source§

fn call(&mut self, cmd: Cmd) -> <RedisConnection as Service<Cmd>>::Future

Process the request and return the response asynchronously. Read more
Source§

impl TransactionExecutor for RedisConnection

Source§

fn execute_transaction( &mut self, watch_frames: Vec<Frame>, command_frames: Vec<Frame>, ) -> impl Future<Output = Result<Option<Vec<Frame>>, RedisError>> + Send

Execute a WATCH/MULTI/EXEC transaction. Read more
Source§

const SUPPORTS_TRANSACTION_RETRY: bool = true

Whether the executor can keep a standalone WATCH active on the same physical connection across the read/build window used by transaction and transaction_with_retries. Read more
Source§

fn validate_transaction_retry(&self) -> Result<(), RedisError>

Reject the closure-based transaction helpers before WATCH or any other command is sent when this executor cannot reserve their full window.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, Request> ServiceExt<Request> for T
where T: Service<Request> + ?Sized,

Source§

fn ready(&mut self) -> Ready<'_, Self, Request> ⓘ
where Self: Sized,

Yields a mutable reference to the service when it is ready to accept a request.
Source§

fn ready_oneshot(self) -> ReadyOneshot<Self, Request> ⓘ
where Self: Sized,

Yields the service when it is ready to accept a request.
Source§

fn oneshot(self, req: Request) -> Oneshot<Self, Request> ⓘ
where Self: Sized,

Consume this Service, calling it with the provided request once it is ready.
Source§

fn call_all<S>(self, reqs: S) -> CallAll<Self, S>
where Self: Sized, S: Stream<Item = Request>,

Process all requests from the given Stream, and produce a Stream of their responses. Read more
Source§

fn and_then<F>(self, f: F) -> AndThen<Self, F>
where Self: Sized, F: Clone,

Executes a new future after this service’s future resolves. This does not alter the behaviour of the poll_ready method. Read more
Source§

fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>
where Self: Sized, F: FnOnce(Self::Response) -> Response + Clone,

Maps this service’s response value to a different value. This does not alter the behaviour of the poll_ready method. Read more
Source§

fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>
where Self: Sized, F: FnOnce(Self::Error) -> Error + Clone,

Maps this service’s error value to a different value. This does not alter the behaviour of the poll_ready method. Read more
Source§

fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>
where Self: Sized, Error: From<Self::Error>, F: FnOnce(Result<Self::Response, Self::Error>) -> Result<Response, Error> + Clone,

Maps this service’s result type (Result<Self::Response, Self::Error>) to a different value, regardless of whether the future succeeds or fails. Read more
Source§

fn map_request<F, NewRequest>(self, f: F) -> MapRequest<Self, F>
where Self: Sized, F: FnMut(NewRequest) -> Request,

Composes a function in front of the service. Read more
Source§

fn then<F, Response, Error, Fut>(self, f: F) -> Then<Self, F>
where Self: Sized, Error: From<Self::Error>, F: FnOnce(Result<Self::Response, Self::Error>) -> Fut + Clone, Fut: Future<Output = Result<Response, Error>>,

Composes an asynchronous function after this service. Read more
Source§

fn map_future<F, Fut, Response, Error>(self, f: F) -> MapFuture<Self, F>
where Self: Sized, F: FnMut(Self::Future) -> Fut, Error: From<Self::Error>, Fut: Future<Output = Result<Response, Error>>,

Composes a function that transforms futures produced by the service. Read more
Source§

fn boxed(self) -> BoxService<Request, Self::Response, Self::Error>
where Self: Sized + Send + 'static, Self::Future: Send + 'static,

Convert the service into a Service + Send trait object. Read more
Source§

fn boxed_clone(self) -> BoxCloneService<Request, Self::Response, Self::Error>
where Self: Sized + Clone + Send + 'static, Self::Future: Send + 'static,

Convert the service into a Service + Clone + Send trait object. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more