Skip to main content

redis_tower_core/
connection.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4use std::time::Duration;
5
6use futures::Sink;
7use futures::SinkExt;
8use socket2::{Socket, TcpKeepalive};
9use tokio::net::TcpStream;
10use tokio::sync::oneshot;
11use tokio_stream::StreamExt;
12use tokio_util::codec::Framed;
13
14use redis_tower_protocol::helpers::{array, bulk};
15use redis_tower_protocol::{Frame, RespCodec, RespLimits};
16
17use crate::command::Command;
18use crate::error::RedisError;
19use crate::stream::RedisStream;
20use crate::url::{RedisUrl, parse_connection_url};
21
22/// Configuration for TCP keepalive probes.
23///
24/// Controls `SO_KEEPALIVE` on TCP connections created by
25/// [`RedisConnection::connect`] and `RedisConnection::connect_tls` (TLS features).
26///
27/// When the connection has been idle for `idle` seconds, the OS begins
28/// sending keepalive probes every `interval` seconds. If `probes` consecutive
29/// probes go unanswered the connection is considered dead and a subsequent
30/// read or write will return an error.
31///
32/// # Example
33///
34/// ```
35/// use redis_tower_core::KeepaliveConfig;
36/// use std::time::Duration;
37///
38/// // Aggressive keepalive for cloud environments:
39/// let cfg = KeepaliveConfig::new()
40///     .with_idle(Duration::from_secs(30))
41///     .with_interval(Duration::from_secs(5))
42///     .with_probes(5);
43/// ```
44#[derive(Debug, Clone)]
45pub struct KeepaliveConfig {
46    /// Time the connection must be idle before keepalive probes start.
47    pub idle: Duration,
48    /// Interval between consecutive keepalive probes.
49    pub interval: Duration,
50    /// Number of unanswered probes before the connection is considered dead.
51    /// Note: ignored on Windows, which does not expose this parameter.
52    pub probes: u32,
53}
54
55impl Default for KeepaliveConfig {
56    fn default() -> Self {
57        Self {
58            idle: Duration::from_secs(60),
59            interval: Duration::from_secs(10),
60            probes: 3,
61        }
62    }
63}
64
65impl KeepaliveConfig {
66    /// Create a new `KeepaliveConfig` with default values (60s idle, 10s interval, 3 probes).
67    #[must_use]
68    pub fn new() -> Self {
69        Self::default()
70    }
71
72    /// Set the idle time before keepalive probes start.
73    #[must_use]
74    pub fn with_idle(mut self, idle: Duration) -> Self {
75        self.idle = idle;
76        self
77    }
78
79    /// Set the interval between consecutive keepalive probes.
80    #[must_use]
81    pub fn with_interval(mut self, interval: Duration) -> Self {
82        self.interval = interval;
83        self
84    }
85
86    /// Set the number of unanswered probes before declaring the connection dead.
87    ///
88    /// This setting is ignored on Windows.
89    #[must_use]
90    pub fn with_probes(mut self, probes: u32) -> Self {
91        self.probes = probes;
92        self
93    }
94}
95
96/// Apply TCP keepalive settings to an already-connected `TcpStream`.
97///
98/// Converts through `socket2` to call `setsockopt(SO_KEEPALIVE, ...)`.
99fn apply_keepalive(stream: TcpStream, config: &KeepaliveConfig) -> Result<TcpStream, RedisError> {
100    let std_stream = stream.into_std()?;
101    let socket = Socket::from(std_stream);
102
103    let keepalive = TcpKeepalive::new()
104        .with_time(config.idle)
105        .with_interval(config.interval);
106
107    // `with_retries` is not available on Windows.
108    #[cfg(not(windows))]
109    let keepalive = keepalive.with_retries(config.probes);
110
111    socket.set_tcp_keepalive(&keepalive)?;
112
113    let std_stream: std::net::TcpStream = socket.into();
114    std_stream.set_nonblocking(true)?;
115    Ok(TcpStream::from_std(std_stream)?)
116}
117
118/// Read the next non-push response frame, routing push frames to the channel.
119async fn read_response_from(
120    framed: &mut Framed<RedisStream, RespCodec>,
121    push_tx: &Option<tokio::sync::mpsc::UnboundedSender<Frame>>,
122    received_push_tx: &Option<tokio::sync::broadcast::Sender<ReceivedPushFrame>>,
123) -> Result<Frame, RedisError> {
124    loop {
125        let frame = framed
126            .next()
127            .await
128            .ok_or(RedisError::ConnectionClosed)?
129            .map_err(RedisError::from)?;
130
131        if let Frame::Push(_) = &frame {
132            let received_at = std::time::Instant::now();
133            if let Some(ref tx) = *push_tx {
134                let _ = tx.send(frame.clone());
135            }
136            if let Some(ref tx) = *received_push_tx {
137                let _ = tx.send(ReceivedPushFrame { received_at, frame });
138            }
139            continue;
140        }
141
142        return Ok(frame);
143    }
144}
145
146/// A single Redis connection implementing `tower::Service<Cmd>`.
147///
148/// This is the foundational building block. It owns a framed TCP/TLS/Unix
149/// connection and serializes commands one at a time.
150///
151/// `RedisConnection` requires `&mut self` for `Service::call`, which is the
152/// correct Tower contract for a non-multiplexed connection. For shared access
153/// across tasks, wrap with `tower::buffer::Buffer`.
154///
155/// Cancelling an in-flight `Service::call` closes the connection. Once a
156/// request may have reached Redis, reusing its transport could let the next
157/// call consume the cancelled request's late response. A subsequent
158/// `poll_ready` therefore returns [`RedisError::ConnectionClosed`].
159///
160/// # Example
161///
162/// Typed command types such as `Get` live in the `redis-tower-commands` crate,
163/// which depends on this one, so the example below stands in a minimal local
164/// [`Command`] implementation (hidden) and runs it with
165/// [`execute`](Self::execute):
166///
167/// ```no_run
168/// use redis_tower_core::{Command, Frame, RedisConnection, RedisError};
169/// # use redis_tower_protocol::helpers::{array, bulk};
170/// #
171/// # struct Get(String);
172/// #
173/// # impl Command for Get {
174/// #     type Response = Option<String>;
175/// #
176/// #     fn to_frame(&self) -> Frame {
177/// #         array(vec![bulk("GET"), bulk(&self.0)])
178/// #     }
179/// #
180/// #     fn parse_response(&self, frame: Frame) -> Result<Option<String>, RedisError> {
181/// #         match frame {
182/// #             Frame::BulkString(Some(b)) => Ok(Some(String::from_utf8_lossy(&b).into_owned())),
183/// #             _ => Ok(None),
184/// #         }
185/// #     }
186/// #
187/// #     fn name(&self) -> &str { "GET" }
188/// # }
189/// #
190/// # async fn example() -> Result<(), RedisError> {
191/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
192/// let value = conn.execute(Get("my_key".to_string())).await?;
193/// # let _ = value;
194/// # Ok(())
195/// # }
196/// ```
197pub struct RedisConnection {
198    /// The framed transport. `None` while a `Service::call` future is in flight.
199    framed: Option<Framed<RedisStream, RespCodec>>,
200    /// Optional sender for RESP3 push messages. Set via `subscribe_pushes()`.
201    push_tx: Option<tokio::sync::mpsc::UnboundedSender<Frame>>,
202    /// Optional timestamped push feed for exclusive connection owners.
203    received_push_tx: Option<tokio::sync::broadcast::Sender<ReceivedPushFrame>>,
204    /// Channel to reclaim the framed transport after a `Service::call` completes.
205    inflight: Option<oneshot::Receiver<Framed<RedisStream, RespCodec>>>,
206    /// Whether RESP3 has been negotiated via `HELLO 3`. Defaults to RESP2.
207    resp3: bool,
208}
209
210/// A RESP3 push frame paired with the instant at which it was decoded.
211///
212/// This feed is intended for an exclusive connection owner that must base a
213/// protocol deadline on receipt time rather than on when it later drains a
214/// notification queue. It is independent of [`RedisConnection::subscribe_pushes`],
215/// so installing it does not replace an application's ordinary push receiver.
216#[doc(hidden)]
217#[derive(Debug, Clone)]
218pub struct ReceivedPushFrame {
219    /// Monotonic instant captured immediately after the frame was decoded.
220    pub received_at: std::time::Instant,
221    /// The decoded RESP3 push frame.
222    pub frame: Frame,
223}
224
225/// Which RESP protocol version to negotiate when connecting.
226///
227/// Used with [`RedisConnection::connect_with_protocol`] to control the
228/// handshake explicitly.
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
230pub enum ProtocolVersion {
231    /// Try RESP3 via `HELLO 3`, falling back to RESP2 if the server does not
232    /// support it (Redis < 6.0, or `HELLO` rejected). The default.
233    #[default]
234    Auto,
235    /// Force RESP2 -- do not send `HELLO 3`.
236    Resp2,
237    /// Force RESP3 -- send `HELLO 3` and return an error if it is rejected.
238    Resp3,
239}
240
241/// Configuration shared by Redis connection constructors.
242///
243/// The default matches [`RedisConnection::connect`]: standard TCP keepalive,
244/// no connect timeout, automatic RESP3 negotiation with RESP2 fallback, and
245/// [`RespLimits::default`] decode limits. Builder methods can be combined
246/// without adding a constructor for every possible option matrix.
247///
248/// ```
249/// use redis_tower_core::{ConnectionConfig, ProtocolVersion, RespLimits};
250/// use std::time::Duration;
251///
252/// let config = ConnectionConfig::new()
253///     .with_connect_timeout(Some(Duration::from_secs(3)))
254///     .with_protocol(ProtocolVersion::Resp3)
255///     .with_resp_limits(RespLimits {
256///         max_frame_size: 8 * 1024 * 1024,
257///         max_depth: 32,
258///     });
259/// assert_eq!(config.protocol(), ProtocolVersion::Resp3);
260/// ```
261#[derive(Debug, Clone)]
262pub struct ConnectionConfig {
263    keepalive: KeepaliveConfig,
264    connect_timeout: Option<Duration>,
265    protocol: ProtocolVersion,
266    resp_limits: RespLimits,
267}
268
269impl Default for ConnectionConfig {
270    fn default() -> Self {
271        Self {
272            keepalive: KeepaliveConfig::default(),
273            connect_timeout: None,
274            protocol: ProtocolVersion::Auto,
275            resp_limits: RespLimits::default(),
276        }
277    }
278}
279
280impl ConnectionConfig {
281    /// Create a connection configuration with the default settings.
282    #[must_use]
283    pub fn new() -> Self {
284        Self::default()
285    }
286
287    /// Set the TCP keepalive configuration.
288    #[must_use]
289    pub fn with_keepalive(mut self, keepalive: KeepaliveConfig) -> Self {
290        self.keepalive = keepalive;
291        self
292    }
293
294    /// Set or clear the connection-establishment timeout.
295    ///
296    /// `None` uses the operating system's connection timeout. `Some` applies
297    /// to the TCP or Unix-socket connect operation; a TLS handshake is not
298    /// included in this timeout.
299    #[must_use]
300    pub fn with_connect_timeout(mut self, timeout: Option<Duration>) -> Self {
301        self.connect_timeout = timeout;
302        self
303    }
304
305    /// Set the RESP protocol negotiation policy.
306    #[must_use]
307    pub fn with_protocol(mut self, protocol: ProtocolVersion) -> Self {
308        self.protocol = protocol;
309        self
310    }
311
312    /// Set the resource limits enforced while decoding RESP frames.
313    #[must_use]
314    pub fn with_resp_limits(mut self, limits: RespLimits) -> Self {
315        self.resp_limits = limits;
316        self
317    }
318
319    /// Return the configured TCP keepalive settings.
320    pub fn keepalive(&self) -> &KeepaliveConfig {
321        &self.keepalive
322    }
323
324    /// Return the connection-establishment timeout.
325    pub fn connect_timeout(&self) -> Option<Duration> {
326        self.connect_timeout
327    }
328
329    /// Return the RESP protocol negotiation policy.
330    pub fn protocol(&self) -> ProtocolVersion {
331        self.protocol
332    }
333
334    /// Return the configured RESP decode limits.
335    pub fn resp_limits(&self) -> RespLimits {
336        self.resp_limits
337    }
338}
339
340/// A Redis URL connection whose transport is open but whose caller-defined
341/// authentication and URL session setup are not yet complete.
342///
343/// This staged form exists for credential providers that must authenticate a
344/// fresh socket before Redis applies the URL's selected database and RESP
345/// protocol. Call [`connection_mut`](Self::connection_mut), authenticate the
346/// connection, then call [`finish`](Self::finish). URL-embedded credentials
347/// are deliberately not sent by `finish`; callers that want static URL
348/// authentication should use [`RedisConnection::connect_url_with_config`].
349///
350/// Dropping this value before `finish` closes the partially configured socket.
351#[must_use = "a staged URL connection must be authenticated and finished"]
352pub struct PendingRedisConnection {
353    connection: RedisConnection,
354    url: RedisUrl,
355    protocol: ProtocolVersion,
356}
357
358impl PendingRedisConnection {
359    /// Borrow the fresh RESP2 connection for caller-defined authentication.
360    ///
361    /// Do not issue application commands at this stage. Only connection setup
362    /// such as `AUTH` belongs before [`finish`](Self::finish).
363    pub fn connection_mut(&mut self) -> &mut RedisConnection {
364        &mut self.connection
365    }
366
367    /// Apply URL database selection and negotiate the resolved RESP protocol.
368    ///
369    /// Authentication must already be complete when the server requires it.
370    /// The URL's static username and password are ignored on this staged path.
371    pub async fn finish(mut self) -> Result<RedisConnection, RedisError> {
372        self.connection
373            .post_connect_database(self.url.database)
374            .await?;
375        self.connection.negotiate_protocol(self.protocol).await?;
376        Ok(self.connection)
377    }
378}
379
380fn resolve_url_protocol(
381    url_protocol: Option<ProtocolVersion>,
382    configured: ProtocolVersion,
383) -> ProtocolVersion {
384    match configured {
385        ProtocolVersion::Auto => url_protocol.unwrap_or(ProtocolVersion::Auto),
386        explicit => explicit,
387    }
388}
389
390impl RedisConnection {
391    /// Create a connection from a framed stream.
392    fn from_framed_inner(framed: Framed<RedisStream, RespCodec>) -> Self {
393        Self {
394            framed: Some(framed),
395            push_tx: None,
396            received_push_tx: None,
397            inflight: None,
398            resp3: false,
399        }
400    }
401
402    /// Wrap a transport with the codec configured for this connection.
403    fn from_stream_inner(stream: RedisStream, config: &ConnectionConfig) -> Self {
404        Self::from_framed_inner(Framed::new(
405            stream,
406            RespCodec::with_limits(config.resp_limits),
407        ))
408    }
409
410    /// Open a TCP stream and apply the configured timeout and keepalive.
411    async fn open_tcp(addr: &str, config: &ConnectionConfig) -> Result<TcpStream, RedisError> {
412        let stream = if let Some(timeout) = config.connect_timeout {
413            match tokio::time::timeout(timeout, TcpStream::connect(addr)).await {
414                Ok(Ok(stream)) => stream,
415                Ok(Err(error)) => return Err(RedisError::connection(addr, error)),
416                Err(_elapsed) => return Err(RedisError::ConnectTimeout),
417            }
418        } else {
419            TcpStream::connect(addr)
420                .await
421                .map_err(|error| RedisError::connection(addr, error))?
422        };
423        let stream = apply_keepalive(stream, &config.keepalive)?;
424        stream.set_nodelay(true)?;
425        Ok(stream)
426    }
427
428    /// Connect to a Redis server over TCP.
429    ///
430    /// TCP keepalive is enabled with sensible defaults: 60 s idle, 10 s
431    /// interval, 3 probes. Use [`connect_with_keepalive`](Self::connect_with_keepalive)
432    /// to supply custom keepalive parameters.
433    pub async fn connect(addr: &str) -> Result<Self, RedisError> {
434        Self::connect_with_config(addr, &ConnectionConfig::default()).await
435    }
436
437    /// Connect to a Redis server over TCP with explicit connection settings.
438    ///
439    /// The configured RESP decode limits are installed before any server data
440    /// is read, including `CLIENT SETINFO` and protocol-negotiation replies.
441    pub async fn connect_with_config(
442        addr: &str,
443        config: &ConnectionConfig,
444    ) -> Result<Self, RedisError> {
445        let mut conn = Self::connect_raw(addr, config).await?;
446        conn.negotiate_protocol(config.protocol).await?;
447        Ok(conn)
448    }
449
450    /// Connect to a Redis server over TCP with a custom keepalive configuration.
451    ///
452    /// # Errors
453    ///
454    /// Returns [`RedisError::Connection`] if the TCP connection fails or if
455    /// the keepalive socket options cannot be applied.
456    pub async fn connect_with_keepalive(
457        addr: &str,
458        keepalive: &KeepaliveConfig,
459    ) -> Result<Self, RedisError> {
460        let config = ConnectionConfig::default().with_keepalive(keepalive.clone());
461        Self::connect_with_config(addr, &config).await
462    }
463
464    /// TCP connect + CLIENT SETINFO, WITHOUT protocol negotiation. The building
465    /// block for the public connectors (which add RESP3 negotiation) and for
466    /// `connect_with_protocol` (which negotiates explicitly).
467    ///
468    /// Instrumented with a `redis.connect` span so every plain-TCP connector
469    /// (`connect`, `connect_with_keepalive`, `connect_with_protocol`, and
470    /// `connect_resp3`, which all funnel through here) emits exactly one
471    /// connection-lifecycle span carrying the target address.
472    #[tracing::instrument(
473        name = "redis.connect",
474        skip_all,
475        fields(server.address = %addr, tls = false),
476        err
477    )]
478    async fn connect_raw(addr: &str, config: &ConnectionConfig) -> Result<Self, RedisError> {
479        let stream = Self::open_tcp(addr, config).await?;
480        let mut conn = Self::from_stream_inner(RedisStream::Tcp(stream), config);
481        conn.identify_client().await?;
482        Ok(conn)
483    }
484
485    /// Connect to a Redis server over TCP with a connect timeout.
486    ///
487    /// If the TCP handshake is not completed within `timeout`, returns
488    /// [`RedisError::ConnectTimeout`] instead of waiting for the OS-default
489    /// timeout (which can be several minutes on unreachable hosts).
490    ///
491    /// TCP keepalive is enabled with sensible defaults after the connection is
492    /// established. Use [`connect_with_config`](Self::connect_with_config) to
493    /// combine a timeout with custom keepalive or RESP decode limits.
494    ///
495    /// # Example
496    ///
497    /// ```no_run
498    /// use redis_tower_core::RedisConnection;
499    /// use std::time::Duration;
500    ///
501    /// # tokio_test::block_on(async {
502    /// let conn = RedisConnection::connect_with_timeout("127.0.0.1:6379", Duration::from_secs(3)).await;
503    /// # });
504    /// ```
505    pub async fn connect_with_timeout(addr: &str, timeout: Duration) -> Result<Self, RedisError> {
506        let config = ConnectionConfig::default().with_connect_timeout(Some(timeout));
507        Self::connect_with_config(addr, &config).await
508    }
509
510    /// Connect over TLS using the provided configuration.
511    ///
512    /// Requires either the `tls-native-tls` or `tls-rustls` feature.
513    ///
514    /// TCP keepalive is enabled with sensible defaults: 60 s idle, 10 s
515    /// interval, 3 probes. Use [`connect_tls_with_keepalive`](Self::connect_tls_with_keepalive)
516    /// to supply custom keepalive parameters.
517    #[cfg(any(feature = "tls-native-tls", feature = "tls-rustls"))]
518    #[cfg_attr(
519        docsrs,
520        doc(cfg(any(feature = "tls-native-tls", feature = "tls-rustls")))
521    )]
522    pub async fn connect_tls(
523        addr: &str,
524        hostname: &str,
525        tls_config: &crate::tls::TlsConfig,
526    ) -> Result<Self, RedisError> {
527        Self::connect_tls_with_config(addr, hostname, tls_config, &ConnectionConfig::default())
528            .await
529    }
530
531    /// Connect over TLS with explicit connection settings.
532    ///
533    /// The TCP connect timeout, keepalive policy, protocol negotiation, and
534    /// RESP decode limits all come from `config`. The connect timeout covers
535    /// the TCP handshake only, matching [`connect_tls_with_timeout`](Self::connect_tls_with_timeout).
536    #[cfg(any(feature = "tls-native-tls", feature = "tls-rustls"))]
537    #[cfg_attr(
538        docsrs,
539        doc(cfg(any(feature = "tls-native-tls", feature = "tls-rustls")))
540    )]
541    pub async fn connect_tls_with_config(
542        addr: &str,
543        hostname: &str,
544        tls_config: &crate::tls::TlsConfig,
545        config: &ConnectionConfig,
546    ) -> Result<Self, RedisError> {
547        let mut conn = Self::connect_tls_raw(addr, hostname, tls_config, config).await?;
548        conn.negotiate_protocol(config.protocol).await?;
549        Ok(conn)
550    }
551
552    /// Connect over TLS with a custom keepalive configuration.
553    ///
554    /// Requires either the `tls-native-tls` or `tls-rustls` feature.
555    ///
556    /// # Errors
557    ///
558    /// Returns [`RedisError::Connection`] if the TCP connection or TLS
559    /// handshake fails, or if the keepalive socket options cannot be applied.
560    #[cfg(any(feature = "tls-native-tls", feature = "tls-rustls"))]
561    #[cfg_attr(
562        docsrs,
563        doc(cfg(any(feature = "tls-native-tls", feature = "tls-rustls")))
564    )]
565    pub async fn connect_tls_with_keepalive(
566        addr: &str,
567        hostname: &str,
568        tls_config: &crate::tls::TlsConfig,
569        keepalive: &KeepaliveConfig,
570    ) -> Result<Self, RedisError> {
571        let config = ConnectionConfig::default().with_keepalive(keepalive.clone());
572        Self::connect_tls_with_config(addr, hostname, tls_config, &config).await
573    }
574
575    /// Connect over TLS with a connect timeout.
576    ///
577    /// Requires either the `tls-native-tls` or `tls-rustls` feature.
578    ///
579    /// If the TCP handshake is not completed within `timeout`, returns
580    /// [`RedisError::ConnectTimeout`]. The timeout covers only the TCP
581    /// connection phase; the TLS handshake runs outside the timeout window.
582    ///
583    /// # Errors
584    ///
585    /// Returns [`RedisError::ConnectTimeout`] if the TCP connect times out,
586    /// [`RedisError::Connection`] if the TCP connection or TLS handshake
587    /// fails, or [`RedisError::Connection`] if keepalive socket options
588    /// cannot be applied.
589    #[cfg(any(feature = "tls-native-tls", feature = "tls-rustls"))]
590    #[cfg_attr(
591        docsrs,
592        doc(cfg(any(feature = "tls-native-tls", feature = "tls-rustls")))
593    )]
594    pub async fn connect_tls_with_timeout(
595        addr: &str,
596        hostname: &str,
597        tls_config: &crate::tls::TlsConfig,
598        timeout: Duration,
599    ) -> Result<Self, RedisError> {
600        let config = ConnectionConfig::default().with_connect_timeout(Some(timeout));
601        Self::connect_tls_with_config(addr, hostname, tls_config, &config).await
602    }
603
604    /// Open a TLS transport and install its codec without negotiating RESP.
605    #[cfg(any(feature = "tls-native-tls", feature = "tls-rustls"))]
606    #[tracing::instrument(
607        name = "redis.connect",
608        skip_all,
609        fields(server.address = %addr, server.tls.hostname = %hostname, tls = true),
610        err
611    )]
612    async fn connect_tls_raw(
613        addr: &str,
614        hostname: &str,
615        tls_config: &crate::tls::TlsConfig,
616        config: &ConnectionConfig,
617    ) -> Result<Self, RedisError> {
618        let tcp = Self::open_tcp(addr, config).await?;
619        let stream = tls_config.connect(tcp, hostname).await?;
620        let mut conn = Self::from_stream_inner(stream, config);
621        conn.identify_client().await?;
622        Ok(conn)
623    }
624
625    /// Connect using a Redis URL.
626    ///
627    /// Supports `redis://`, `rediss://` (TLS), their Valkey aliases, and
628    /// `unix://`, `redis+unix://`, and `valkey+unix://` Unix-socket URLs.
629    ///
630    /// Unix URLs accept `user`, `pass`, `db`, and `protocol` query parameters:
631    ///
632    /// ```text
633    /// redis+unix:///run/redis%20server.sock?user=app&pass=secret&db=1&protocol=resp3
634    /// ```
635    ///
636    /// For `rediss://` URLs, a TLS backend feature must be enabled.
637    /// The `tls-rustls` backend is preferred if both are enabled.
638    pub async fn connect_url(url: &str) -> Result<Self, RedisError> {
639        Self::connect_url_with_config(url, &ConnectionConfig::default()).await
640    }
641
642    /// Connect using a Redis URL with explicit connection settings.
643    ///
644    /// URL authentication and database selection run before RESP negotiation.
645    /// `?protocol=2|resp2|3|resp3` selects a protocol when the connection
646    /// config uses [`ProtocolVersion::Auto`]. An explicit protocol in
647    /// [`ConnectionConfig`] takes precedence, which lets RESP3-only clients
648    /// enforce their invariant. Decode limits are active for every setup
649    /// response.
650    pub async fn connect_url_with_config(
651        url: &str,
652        config: &ConnectionConfig,
653    ) -> Result<Self, RedisError> {
654        let mut pending = Self::begin_url_connection_with_config(url, config).await?;
655        pending
656            .connection
657            .post_connect_authentication(&pending.url)
658            .await?;
659        pending.finish().await
660    }
661
662    /// Open the transport described by a Redis URL without applying its static
663    /// credentials, selected database, or RESP protocol yet.
664    ///
665    /// This is the provider-authentication seam used by higher-level
666    /// connection factories. The returned connection starts in RESP2, while
667    /// preserving the URL's TCP, TLS, or Unix transport, database, and
668    /// protocol settings. Authenticate it through
669    /// [`PendingRedisConnection::connection_mut`], then call
670    /// [`PendingRedisConnection::finish`].
671    ///
672    /// The URL's username and password are intentionally ignored on this path;
673    /// they remain active on [`connect_url_with_config`](Self::connect_url_with_config).
674    pub async fn begin_url_connection_with_config(
675        url: &str,
676        config: &ConnectionConfig,
677    ) -> Result<PendingRedisConnection, RedisError> {
678        let parsed = parse_connection_url(url)?;
679
680        let connection = if parsed.url.unix {
681            #[cfg(unix)]
682            {
683                use std::os::unix::ffi::OsStrExt;
684
685                let path_bytes = parsed
686                    .unix_path
687                    .as_deref()
688                    .ok_or_else(|| RedisError::InvalidUrl("unix URL missing path".into()))?;
689                let path = std::path::Path::new(std::ffi::OsStr::from_bytes(path_bytes));
690                let error_address = parsed
691                    .url
692                    .path
693                    .as_deref()
694                    .unwrap_or("<non-UTF-8 Unix socket>");
695                let stream = if let Some(timeout) = config.connect_timeout {
696                    match tokio::time::timeout(timeout, tokio::net::UnixStream::connect(path)).await
697                    {
698                        Ok(Ok(stream)) => stream,
699                        Ok(Err(error)) => {
700                            return Err(RedisError::connection(error_address, error));
701                        }
702                        Err(_elapsed) => return Err(RedisError::ConnectTimeout),
703                    }
704                } else {
705                    tokio::net::UnixStream::connect(path)
706                        .await
707                        .map_err(|error| RedisError::connection(error_address, error))?
708                };
709                let mut conn = Self::from_stream_inner(RedisStream::Unix(stream), config);
710                conn.identify_client().await?;
711                conn
712            }
713            #[cfg(not(unix))]
714            {
715                return Err(RedisError::InvalidUrl(
716                    "unix sockets not supported on this platform".into(),
717                ));
718            }
719        } else if parsed.url.tls {
720            #[cfg(feature = "tls-rustls")]
721            {
722                let tls_config = crate::tls::TlsConfig::default_rustls();
723                let addr = parsed.url.tcp_addr();
724                Self::connect_tls_raw(&addr, parsed.url.tls_server_name(), &tls_config, config)
725                    .await?
726            }
727            #[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
728            {
729                let tls_config = crate::tls::TlsConfig::default_native_tls();
730                let addr = parsed.url.tcp_addr();
731                Self::connect_tls_raw(&addr, parsed.url.tls_server_name(), &tls_config, config)
732                    .await?
733            }
734            #[cfg(not(any(feature = "tls-native-tls", feature = "tls-rustls")))]
735            {
736                return Err(RedisError::InvalidUrl(
737                    "TLS requires the tls-native-tls or tls-rustls feature".into(),
738                ));
739            }
740        } else {
741            Self::connect_raw(&parsed.url.tcp_addr(), config).await?
742        };
743
744        Ok(PendingRedisConnection {
745            connection,
746            url: parsed.url,
747            protocol: resolve_url_protocol(parsed.protocol, config.protocol),
748        })
749    }
750
751    /// Connect from a Redis URL, performing the TLS handshake with an explicit
752    /// [`TlsConfig`](crate::tls::TlsConfig).
753    ///
754    /// Like [`connect_url`](Self::connect_url) but the caller supplies the TLS
755    /// configuration -- a custom root CA, a client certificate for mTLS, or a
756    /// pre-built backend -- instead of the URL's hardcoded default. The host,
757    /// port, and any AUTH/SELECT parameters still come from the URL, and the
758    /// connection always uses TLS (for either a `redis://` or `rediss://` URL).
759    /// Unix-socket URLs are rejected.
760    ///
761    /// # Example
762    ///
763    /// ```no_run
764    /// use redis_tower_core::RedisConnection;
765    /// use redis_tower_core::tls::TlsConfig;
766    ///
767    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
768    /// let tls = TlsConfig::default_rustls()
769    ///     .with_root_ca_pem(std::fs::read("ca.pem")?)
770    ///     .with_client_auth_pem(std::fs::read("client.pem")?, std::fs::read("client.key")?);
771    /// let conn = RedisConnection::connect_url_with_tls(
772    ///     "rediss://default:secret@redis.internal:6379",
773    ///     &tls,
774    /// )
775    /// .await?;
776    /// # let _ = conn;
777    /// # Ok(())
778    /// # }
779    /// ```
780    #[cfg(any(feature = "tls-native-tls", feature = "tls-rustls"))]
781    #[cfg_attr(
782        docsrs,
783        doc(cfg(any(feature = "tls-native-tls", feature = "tls-rustls")))
784    )]
785    pub async fn connect_url_with_tls(
786        url: &str,
787        tls_config: &crate::tls::TlsConfig,
788    ) -> Result<Self, RedisError> {
789        Self::connect_url_with_tls_and_config(url, tls_config, &ConnectionConfig::default()).await
790    }
791
792    /// Connect from a Redis URL with explicit TLS and connection settings.
793    ///
794    /// This combines a custom CA or mTLS configuration with keepalive,
795    /// connection timeout, protocol, and RESP decode-limit settings. Unix
796    /// socket URLs are rejected because this connector always uses TLS.
797    #[cfg(any(feature = "tls-native-tls", feature = "tls-rustls"))]
798    #[cfg_attr(
799        docsrs,
800        doc(cfg(any(feature = "tls-native-tls", feature = "tls-rustls")))
801    )]
802    pub async fn connect_url_with_tls_and_config(
803        url: &str,
804        tls_config: &crate::tls::TlsConfig,
805        config: &ConnectionConfig,
806    ) -> Result<Self, RedisError> {
807        let mut pending =
808            Self::begin_url_connection_with_tls_and_config(url, tls_config, config).await?;
809        pending
810            .connection
811            .post_connect_authentication(&pending.url)
812            .await?;
813        pending.finish().await
814    }
815
816    /// Open a staged URL connection using explicit TLS configuration.
817    ///
818    /// This is the custom-CA/mTLS counterpart to
819    /// [`begin_url_connection_with_config`](Self::begin_url_connection_with_config).
820    /// The URL must describe a TCP endpoint; Unix URLs are rejected. Static
821    /// URL credentials are ignored so the caller can authenticate through a
822    /// dynamic provider before database selection and protocol negotiation.
823    #[cfg(any(feature = "tls-native-tls", feature = "tls-rustls"))]
824    #[cfg_attr(
825        docsrs,
826        doc(cfg(any(feature = "tls-native-tls", feature = "tls-rustls")))
827    )]
828    pub async fn begin_url_connection_with_tls_and_config(
829        url: &str,
830        tls_config: &crate::tls::TlsConfig,
831        config: &ConnectionConfig,
832    ) -> Result<PendingRedisConnection, RedisError> {
833        let parsed = parse_connection_url(url)?;
834        if parsed.url.unix {
835            return Err(RedisError::InvalidUrl(
836                "unix socket URLs cannot use TLS".into(),
837            ));
838        }
839        let addr = parsed.url.tcp_addr();
840        let connection =
841            Self::connect_tls_raw(&addr, parsed.url.tls_server_name(), tls_config, config).await?;
842        Ok(PendingRedisConnection {
843            connection,
844            url: parsed.url,
845            protocol: resolve_url_protocol(parsed.protocol, config.protocol),
846        })
847    }
848
849    /// Connect to a Redis server and negotiate RESP3 protocol.
850    ///
851    /// Sends `HELLO 3` after connecting. The server will respond with
852    /// RESP3 frames for all subsequent commands.
853    pub async fn connect_resp3(addr: &str) -> Result<Self, RedisError> {
854        Self::connect_with_protocol(addr, ProtocolVersion::Resp3).await
855    }
856
857    /// Whether this connection has negotiated RESP3 (via `HELLO 3`).
858    ///
859    /// Returns `false` for a plain RESP2 connection. Useful for tests and for
860    /// middleware that behaves differently under the two protocols -- push-based
861    /// features such as client-side caching require RESP3.
862    pub fn is_resp3(&self) -> bool {
863        self.resp3
864    }
865
866    /// Connect and negotiate the protocol explicitly.
867    ///
868    /// - [`ProtocolVersion::Auto`] tries `HELLO 3` and silently falls back to
869    ///   RESP2 on servers that do not support it (Redis < 6.0).
870    /// - [`ProtocolVersion::Resp3`] forces RESP3 and errors if it is rejected.
871    /// - [`ProtocolVersion::Resp2`] stays on RESP2 without sending `HELLO`.
872    ///
873    /// # Example
874    ///
875    /// ```no_run
876    /// use redis_tower_core::{RedisConnection, ProtocolVersion};
877    /// # tokio_test::block_on(async {
878    /// let conn = RedisConnection::connect_with_protocol(
879    ///     "127.0.0.1:6379",
880    ///     ProtocolVersion::Resp3,
881    /// ).await?;
882    /// assert!(conn.is_resp3());
883    /// # Ok::<(), redis_tower_core::RedisError>(())
884    /// # });
885    /// ```
886    pub async fn connect_with_protocol(
887        addr: &str,
888        version: ProtocolVersion,
889    ) -> Result<Self, RedisError> {
890        let config = ConnectionConfig::default().with_protocol(version);
891        Self::connect_with_config(addr, &config).await
892    }
893
894    /// Negotiate `version` on an already-connected connection.
895    ///
896    /// This is useful for connection setup that must run before protocol
897    /// negotiation, such as authenticating a protected Redis Cluster node.
898    /// Requesting RESP2 only sends `HELLO 2` when the connection is currently
899    /// in RESP3; a fresh RESP2 connection does not pay an extra round trip.
900    pub async fn negotiate_protocol(&mut self, version: ProtocolVersion) -> Result<(), RedisError> {
901        match version {
902            ProtocolVersion::Resp2 => {
903                if self.resp3 {
904                    self.hello(2).await?;
905                }
906                Ok(())
907            }
908            ProtocolVersion::Resp3 => {
909                self.hello(3).await?;
910                Ok(())
911            }
912            ProtocolVersion::Auto => {
913                // An older server that does not understand HELLO leaves us on
914                // RESP2 (`resp3` stays false) -- exactly the desired fallback.
915                // Transport and protocol failures are not a compatibility
916                // signal and must still surface, especially configured decode
917                // limit violations.
918                match self.hello(3).await {
919                    Ok(_) | Err(RedisError::Redis(_)) => Ok(()),
920                    Err(error) => Err(error),
921                }
922            }
923        }
924    }
925
926    /// Send HELLO to negotiate protocol version.
927    ///
928    /// `HELLO 3` switches to RESP3, `HELLO 2` switches back to RESP2.
929    pub async fn hello(&mut self, version: u8) -> Result<Frame, RedisError> {
930        let frame = array(vec![bulk("HELLO"), bulk(version.to_string())]);
931        let response = {
932            let framed = self.framed.as_mut().expect("connection not in flight");
933            framed.send(frame).await.map_err(RedisError::from)?;
934            read_response_from(framed, &self.push_tx, &self.received_push_tx).await?
935        };
936        if let Frame::Error(ref e) = response {
937            return Err(RedisError::Redis(String::from_utf8_lossy(e).into_owned()));
938        }
939        // A successful `HELLO 3` switches the connection to RESP3; `HELLO 2`
940        // switches it back. Track it for introspection and middleware.
941        self.resp3 = version == 3;
942        Ok(response)
943    }
944
945    /// Wrap an existing stream in a `RedisConnection`.
946    pub fn from_stream(stream: RedisStream) -> Self {
947        Self::from_stream_with_config(stream, &ConnectionConfig::default())
948    }
949
950    /// Wrap an existing stream using explicit connection settings.
951    ///
952    /// Only the RESP decode limits apply to an already-open stream. Keepalive,
953    /// connect timeout, and protocol negotiation are connection-establishment
954    /// settings and are not replayed by this synchronous constructor.
955    pub fn from_stream_with_config(stream: RedisStream, config: &ConnectionConfig) -> Self {
956        Self::from_stream_inner(stream, config)
957    }
958
959    /// Subscribe to RESP3 push messages.
960    ///
961    /// Returns a receiver for out-of-band push frames (e.g., invalidation
962    /// messages from CLIENT TRACKING). Push frames received during normal
963    /// command execution are automatically routed to this channel.
964    ///
965    /// If nobody subscribes, push frames are silently discarded.
966    ///
967    /// # Reconnection Warning
968    ///
969    /// Push subscriptions do **not** survive reconnection. If the underlying
970    /// TCP connection drops and a new connection is established (e.g., via
971    /// [`ResilientConnection`](https://docs.rs/redis-tower) or manual
972    /// reconnection), any server-side state such as `CLIENT TRACKING`
973    /// registrations is lost. The push receiver will stop receiving
974    /// messages until the tracking is re-enabled on the new connection.
975    ///
976    /// To handle this, implement [`ConnectionFactory`](https://docs.rs/redis-tower)
977    /// yourself and replay setup commands (e.g., `CLIENT TRACKING ON`) inside
978    /// `connect()`. This ensures the setup runs on every fresh connection,
979    /// including reconnections.
980    ///
981    /// `ConnectionFactory` lives in the `redis-tower` crate, which depends on
982    /// this one, so the setup below is shown as the standalone function that
983    /// the factory's `connect()` body calls:
984    ///
985    /// ```no_run
986    /// use redis_tower_core::{Frame, RedisConnection, RedisError};
987    /// use redis_tower_protocol::helpers::{array, bulk};
988    /// use tokio::sync::mpsc::UnboundedReceiver;
989    ///
990    /// # async fn connect_tracking(
991    /// #     addr: &str,
992    /// # ) -> Result<(RedisConnection, UnboundedReceiver<Frame>), RedisError> {
993    /// let mut conn = RedisConnection::connect_resp3(addr).await?;
994    /// // Replay CLIENT TRACKING and re-subscribe on every new connection.
995    /// conn.execute_pipeline(vec![array(vec![bulk("CLIENT"), bulk("TRACKING"), bulk("ON")])])
996    ///     .await?;
997    /// let pushes = conn.subscribe_pushes();
998    /// Ok((conn, pushes))
999    /// # }
1000    /// ```
1001    pub fn subscribe_pushes(&mut self) -> tokio::sync::mpsc::UnboundedReceiver<Frame> {
1002        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
1003        self.push_tx = Some(tx);
1004        rx
1005    }
1006
1007    /// Subscribe to a timestamped copy of every decoded RESP3 push frame.
1008    ///
1009    /// Unlike [`Self::subscribe_pushes`], this internal feed does not replace
1010    /// the application's ordinary push receiver. Calling it again replaces
1011    /// only the previous timestamped feed.
1012    #[doc(hidden)]
1013    pub fn subscribe_received_pushes(
1014        &mut self,
1015    ) -> tokio::sync::broadcast::Receiver<ReceivedPushFrame> {
1016        // This internal feed must remain bounded even when a long-running
1017        // command delays the exclusive owner's next drain. Receivers observe
1018        // overflow explicitly as `Lagged` and can fail safe by replacing the
1019        // connection rather than silently missing a handoff request.
1020        let (tx, rx) = tokio::sync::broadcast::channel(64);
1021        self.received_push_tx = Some(tx);
1022        rx
1023    }
1024
1025    /// Wait for one unsolicited RESP3 push frame while the connection is idle.
1026    ///
1027    /// The frame is routed to the receiver returned by [`subscribe_pushes`](Self::subscribe_pushes),
1028    /// matching the behavior of command-response reads. EOF, decode failures,
1029    /// and non-push frames are returned as errors because a response arriving
1030    /// without an outstanding command means protocol alignment has been lost.
1031    ///
1032    /// This method is cancellation-safe: it borrows the framed transport in
1033    /// place, so cancelling the wait preserves both the transport and any
1034    /// partially buffered frame. It is intended for an exclusive connection
1035    /// owner, such as an auto-pipeline worker, and must not be called while a
1036    /// [`Service::call`](tower_service::Service::call) future is in flight.
1037    pub async fn read_idle_push(&mut self) -> Result<(), RedisError> {
1038        if self.framed.is_none() {
1039            return if self.inflight.is_some() {
1040                Err(RedisError::ConnectionInUse)
1041            } else {
1042                Err(RedisError::ConnectionClosed)
1043            };
1044        }
1045        let next = self.framed.as_mut().unwrap().next().await;
1046        let frame = match next {
1047            Some(Ok(frame)) => frame,
1048            Some(Err(error)) => {
1049                // A decode/I/O failure leaves the transport unusable. Drop it
1050                // at this completed read boundary while keeping cancellation
1051                // before the boundary non-destructive.
1052                self.framed.take();
1053                return Err(RedisError::from(error));
1054            }
1055            None => {
1056                self.framed.take();
1057                return Err(RedisError::ConnectionClosed);
1058            }
1059        };
1060
1061        match frame {
1062            Frame::Push(_) => {
1063                let received_at = std::time::Instant::now();
1064                if let Some(push_tx) = &self.push_tx {
1065                    let _ = push_tx.send(frame.clone());
1066                }
1067                if let Some(received_push_tx) = &self.received_push_tx {
1068                    let _ = received_push_tx.send(ReceivedPushFrame { received_at, frame });
1069                }
1070                Ok(())
1071            }
1072            other => {
1073                // There is no outstanding request that could own this reply.
1074                // Quarantine the now-misaligned transport.
1075                self.framed.take();
1076                Err(RedisError::UnexpectedResponse {
1077                    expected: "RESP3 push frame while connection is idle",
1078                    actual: format!("{other:?}"),
1079                })
1080            }
1081        }
1082    }
1083
1084    /// Ensure the framed transport is available, reclaiming it from an
1085    /// in-flight `Service::call` future if necessary.
1086    async fn ensure_framed(&mut self) -> Result<(), RedisError> {
1087        if self.framed.is_none() {
1088            if let Some(rx) = self.inflight.take() {
1089                let framed = rx.await.map_err(|_| RedisError::ConnectionClosed)?;
1090                self.framed = Some(framed);
1091            } else {
1092                return Err(RedisError::ConnectionClosed);
1093            }
1094        }
1095        Ok(())
1096    }
1097
1098    /// Send a command and receive the response.
1099    ///
1100    /// This is the low-level method. Prefer using the `Service` trait via
1101    /// `tower::ServiceExt::oneshot` or `Service::call`.
1102    ///
1103    /// # Large values
1104    ///
1105    /// For values approaching 10MB or larger, the sequential send-then-read
1106    /// pattern can cause TCP backpressure issues on some managed Redis
1107    /// services (e.g., ElastiCache) if the write buffer fills before the
1108    /// response starts being read. Consider using `AutoPipelineService`
1109    /// for large-value workloads, or splitting large values across
1110    /// multiple keys.
1111    ///
1112    /// Cancelling this future after dispatch closes the connection. The
1113    /// transport is checked out of `self` until a complete response has been
1114    /// read, preventing a later command from consuming a cancelled command's
1115    /// response.
1116    pub async fn execute<Cmd: Command>(&mut self, cmd: Cmd) -> Result<Cmd::Response, RedisError> {
1117        self.ensure_framed().await?;
1118        let frame = cmd.to_frame();
1119        let push_tx = self.push_tx.clone();
1120        let received_push_tx = self.received_push_tx.clone();
1121        let mut framed = self.framed.take().expect("framed transport was ensured");
1122        framed.send(frame).await.map_err(RedisError::from)?;
1123        let response = read_response_from(&mut framed, &push_tx, &received_push_tx).await?;
1124
1125        // A complete response restores protocol alignment. Return the
1126        // transport before mapping Redis/application parse errors.
1127        self.framed = Some(framed);
1128
1129        if let Frame::Error(ref e) = response {
1130            return Err(RedisError::Redis(String::from_utf8_lossy(e).into_owned()));
1131        }
1132
1133        cmd.parse_response(response)
1134    }
1135
1136    /// Send multiple command frames and read all responses in a single roundtrip.
1137    ///
1138    /// Used by pipeline and transaction implementations.
1139    /// Cancelling before every response has been read closes the connection.
1140    pub async fn execute_pipeline(&mut self, frames: Vec<Frame>) -> Result<Vec<Frame>, RedisError> {
1141        self.ensure_framed().await?;
1142        let count = frames.len();
1143        let push_tx = self.push_tx.clone();
1144        let received_push_tx = self.received_push_tx.clone();
1145        let mut framed = self.framed.take().expect("framed transport was ensured");
1146
1147        // Send all frames, buffering writes.
1148        for (i, frame) in frames.into_iter().enumerate() {
1149            if i < count - 1 {
1150                framed.feed(frame).await.map_err(RedisError::from)?;
1151            } else {
1152                framed.send(frame).await.map_err(RedisError::from)?;
1153            }
1154        }
1155
1156        // Read all responses, routing push frames to the channel.
1157        let mut responses = Vec::with_capacity(count);
1158        for _ in 0..count {
1159            let response = read_response_from(&mut framed, &push_tx, &received_push_tx).await?;
1160            responses.push(response);
1161        }
1162
1163        self.framed = Some(framed);
1164        Ok(responses)
1165    }
1166
1167    /// Execute a WATCH/MULTI/EXEC transaction sequence.
1168    ///
1169    /// Returns `Ok(Some(responses))` on commit, `Ok(None)` if aborted by WATCH.
1170    pub async fn execute_transaction(
1171        &mut self,
1172        watch_frames: Vec<Frame>,
1173        command_frames: Vec<Frame>,
1174    ) -> Result<Option<Vec<Frame>>, RedisError> {
1175        self.ensure_framed().await?;
1176        let push_tx = self.push_tx.clone();
1177        let received_push_tx = self.received_push_tx.clone();
1178        let mut framed = self.framed.take().expect("framed transport was ensured");
1179
1180        // Send WATCH keys if any.
1181        for frame in watch_frames {
1182            framed.send(frame).await.map_err(RedisError::from)?;
1183            let response = read_response_from(&mut framed, &push_tx, &received_push_tx).await?;
1184            if let Frame::Error(e) = response {
1185                self.framed = Some(framed);
1186                return Err(RedisError::Redis(String::from_utf8_lossy(&e).into_owned()));
1187            }
1188        }
1189
1190        // Send MULTI.
1191        framed
1192            .send(array(vec![bulk("MULTI")]))
1193            .await
1194            .map_err(RedisError::from)?;
1195        let multi_resp = read_response_from(&mut framed, &push_tx, &received_push_tx).await?;
1196        if let Frame::Error(e) = multi_resp {
1197            self.framed = Some(framed);
1198            return Err(RedisError::Redis(String::from_utf8_lossy(&e).into_owned()));
1199        }
1200
1201        // Send each command, expect QUEUED for each.
1202        for frame in &command_frames {
1203            framed.send(frame.clone()).await.map_err(RedisError::from)?;
1204            let queued_resp = read_response_from(&mut framed, &push_tx, &received_push_tx).await?;
1205            match queued_resp {
1206                Frame::SimpleString(ref s) if &s[..] == b"QUEUED" => {}
1207                Frame::Error(e) => {
1208                    let error = RedisError::Redis(String::from_utf8_lossy(&e).into_owned());
1209                    // Abort the transaction on error.
1210                    let aligned = if framed.send(array(vec![bulk("DISCARD")])).await.is_ok() {
1211                        read_response_from(&mut framed, &push_tx, &received_push_tx)
1212                            .await
1213                            .is_ok()
1214                    } else {
1215                        false
1216                    };
1217                    if aligned {
1218                        self.framed = Some(framed);
1219                    }
1220                    return Err(error);
1221                }
1222                _ => {
1223                    let error = RedisError::UnexpectedResponse {
1224                        expected: "QUEUED",
1225                        actual: format!("{queued_resp:?}"),
1226                    };
1227                    let aligned = if framed.send(array(vec![bulk("DISCARD")])).await.is_ok() {
1228                        read_response_from(&mut framed, &push_tx, &received_push_tx)
1229                            .await
1230                            .is_ok()
1231                    } else {
1232                        false
1233                    };
1234                    if aligned {
1235                        self.framed = Some(framed);
1236                    }
1237                    return Err(error);
1238                }
1239            }
1240        }
1241
1242        // Send EXEC.
1243        framed
1244            .send(array(vec![bulk("EXEC")]))
1245            .await
1246            .map_err(RedisError::from)?;
1247        let exec_resp = read_response_from(&mut framed, &push_tx, &received_push_tx).await?;
1248
1249        // EXEC produced a complete response, so the transaction exchange is
1250        // aligned even when Redis reports an application-level error.
1251        self.framed = Some(framed);
1252
1253        match exec_resp {
1254            Frame::Array(Some(results)) => Ok(Some(results)),
1255            Frame::Array(None) | Frame::Null => Ok(None), // WATCH violation
1256            Frame::Error(e) => Err(RedisError::Redis(String::from_utf8_lossy(&e).into_owned())),
1257            other => Err(RedisError::UnexpectedResponse {
1258                expected: "array or null",
1259                actual: format!("{other:?}"),
1260            }),
1261        }
1262    }
1263
1264    /// Consume this connection and extract the underlying framed stream.
1265    ///
1266    /// Fails if a `Service::call` future is still in flight.
1267    pub fn into_framed(mut self) -> Result<Framed<RedisStream, RespCodec>, RedisError> {
1268        self.framed.take().ok_or(RedisError::ConnectionInUse)
1269    }
1270
1271    /// Send CLIENT SETINFO to identify the client library.
1272    ///
1273    /// Redis command-error replies are ignored because older versions do not
1274    /// support `CLIENT SETINFO`. Transport and decode errors still propagate:
1275    /// they mean the connection is unusable or its configured limits were
1276    /// violated, rather than that the optional command was rejected.
1277    async fn identify_client(&mut self) -> Result<(), RedisError> {
1278        let framed = self.framed.as_mut().unwrap();
1279        // CLIENT SETINFO LIB-NAME redis-tower
1280        framed
1281            .send(array(vec![
1282                bulk("CLIENT"),
1283                bulk("SETINFO"),
1284                bulk("LIB-NAME"),
1285                bulk("redis-tower"),
1286            ]))
1287            .await
1288            .map_err(RedisError::from)?;
1289        let _response = read_response_from(framed, &self.push_tx, &self.received_push_tx).await?;
1290        // CLIENT SETINFO LIB-VER <version>
1291        framed
1292            .send(array(vec![
1293                bulk("CLIENT"),
1294                bulk("SETINFO"),
1295                bulk("LIB-VER"),
1296                bulk(env!("CARGO_PKG_VERSION")),
1297            ]))
1298            .await
1299            .map_err(RedisError::from)?;
1300        let _response = read_response_from(framed, &self.push_tx, &self.received_push_tx).await?;
1301        Ok(())
1302    }
1303
1304    /// Apply static URL authentication before the remaining URL setup.
1305    async fn post_connect_authentication(&mut self, url: &RedisUrl) -> Result<(), RedisError> {
1306        let framed = self.framed.as_mut().expect("connection not in flight");
1307
1308        if let Some(ref password) = url.password {
1309            let mut auth_args = vec![bulk("AUTH")];
1310            if let Some(ref username) = url.username {
1311                auth_args.push(bulk(username.clone()));
1312            }
1313            auth_args.push(bulk(password.clone()));
1314
1315            framed
1316                .send(array(auth_args))
1317                .await
1318                .map_err(RedisError::from)?;
1319            let response =
1320                read_response_from(framed, &self.push_tx, &self.received_push_tx).await?;
1321
1322            if let Frame::Error(e) = response {
1323                return Err(RedisError::Redis(String::from_utf8_lossy(&e).into_owned()));
1324            }
1325        }
1326
1327        Ok(())
1328    }
1329
1330    /// Select the URL database after authentication and before negotiation.
1331    async fn post_connect_database(&mut self, database: Option<u16>) -> Result<(), RedisError> {
1332        if let Some(db) = database {
1333            let framed = self.framed.as_mut().expect("connection not in flight");
1334            framed
1335                .send(array(vec![bulk("SELECT"), bulk(db.to_string())]))
1336                .await
1337                .map_err(RedisError::from)?;
1338            let response =
1339                read_response_from(framed, &self.push_tx, &self.received_push_tx).await?;
1340
1341            if let Frame::Error(e) = response {
1342                return Err(RedisError::Redis(String::from_utf8_lossy(&e).into_owned()));
1343            }
1344        }
1345
1346        Ok(())
1347    }
1348}
1349
1350/// Owns the framed transport while a `Service::call` future is in flight.
1351///
1352/// The transport is returned through `return_tx` only after a complete
1353/// response frame has been read. Dropping the future, or encountering a
1354/// transport/protocol error before that boundary, drops both fields and closes
1355/// the connection rather than leaving a late response for the next request.
1356struct FrameGuard {
1357    framed: Option<Framed<RedisStream, RespCodec>>,
1358    return_tx: Option<oneshot::Sender<Framed<RedisStream, RespCodec>>>,
1359}
1360
1361impl<Cmd: Command> tower_service::Service<Cmd> for RedisConnection {
1362    type Response = Cmd::Response;
1363    type Error = RedisError;
1364    type Future = Pin<Box<dyn Future<Output = Result<Cmd::Response, RedisError>> + Send>>;
1365
1366    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1367        // If the framed transport was taken by a previous call(), try to reclaim it.
1368        if self.framed.is_none() {
1369            if let Some(ref mut rx) = self.inflight {
1370                match Pin::new(rx).poll(cx) {
1371                    Poll::Ready(Ok(framed)) => {
1372                        self.framed = Some(framed);
1373                        self.inflight = None;
1374                    }
1375                    Poll::Ready(Err(_)) => {
1376                        self.inflight = None;
1377                        return Poll::Ready(Err(RedisError::ConnectionClosed));
1378                    }
1379                    Poll::Pending => return Poll::Pending,
1380                }
1381            } else {
1382                return Poll::Ready(Err(RedisError::ConnectionClosed));
1383            }
1384        }
1385
1386        // Check that the underlying sink can accept a write.
1387        let framed = self.framed.as_mut().unwrap();
1388        Pin::new(framed).poll_ready(cx).map_err(RedisError::from)
1389    }
1390
1391    fn call(&mut self, cmd: Cmd) -> Self::Future {
1392        // Take the framed transport out of self so the future can own it.
1393        let mut framed = self
1394            .framed
1395            .take()
1396            .expect("call() invoked without successful poll_ready()");
1397        let push_tx = self.push_tx.clone();
1398        let received_push_tx = self.received_push_tx.clone();
1399
1400        // Enqueue the frame synchronously (valid after poll_ready returned Ready).
1401        let frame = cmd.to_frame();
1402        if let Err(e) = Pin::new(&mut framed).start_send(frame) {
1403            // A sink error leaves the connection state uncertain. Quarantine
1404            // it rather than allowing a later call to reuse the transport.
1405            return Box::pin(async move { Err(RedisError::from(e)) });
1406        }
1407
1408        // Create the return channel so poll_ready can reclaim the transport.
1409        let (return_tx, return_rx) = oneshot::channel();
1410        self.inflight = Some(return_rx);
1411
1412        // Keep the transport owned by the call future. Cancellation or an I/O
1413        // error before a complete response drops it; reading a complete frame
1414        // restores protocol alignment even if command parsing later fails.
1415        let mut guard = FrameGuard {
1416            framed: Some(framed),
1417            return_tx: Some(return_tx),
1418        };
1419
1420        Box::pin(async move {
1421            let framed = guard.framed.as_mut().unwrap();
1422
1423            // Flush the buffered write.
1424            framed.flush().await.map_err(RedisError::from)?;
1425
1426            // Read response, routing push frames.
1427            let response = read_response_from(framed, &push_tx, &received_push_tx).await?;
1428
1429            // A complete response restores protocol alignment. Return the
1430            // transport before interpreting application or parsing errors so
1431            // a healthy connection survives WRONGTYPE and similar responses.
1432            let _ = guard
1433                .return_tx
1434                .take()
1435                .unwrap()
1436                .send(guard.framed.take().unwrap());
1437
1438            if let Frame::Error(ref e) = response {
1439                return Err(RedisError::Redis(String::from_utf8_lossy(e).into_owned()));
1440            }
1441
1442            cmd.parse_response(response)
1443        })
1444    }
1445}
1446
1447#[cfg(test)]
1448mod tests {
1449    use super::*;
1450    use crate::command::Command;
1451    use redis_tower_protocol::ProtocolError;
1452
1453    /// Minimal command type used only in unit tests.
1454    struct DummyCmd;
1455    impl Command for DummyCmd {
1456        type Response = ();
1457        fn to_frame(&self) -> Frame {
1458            Frame::SimpleString(b"PING"[..].into())
1459        }
1460        fn parse_response(&self, _frame: Frame) -> Result<(), RedisError> {
1461            Ok(())
1462        }
1463        fn name(&self) -> &str {
1464            "DUMMY"
1465        }
1466    }
1467
1468    async fn stream_pair() -> (RedisStream, RedisStream) {
1469        #[cfg(unix)]
1470        {
1471            let (client, server) = tokio::net::UnixStream::pair().unwrap();
1472            (RedisStream::Unix(client), RedisStream::Unix(server))
1473        }
1474        #[cfg(not(unix))]
1475        {
1476            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1477            let addr = listener.local_addr().unwrap();
1478            let client = TcpStream::connect(addr).await.unwrap();
1479            let (server, _) = listener.accept().await.unwrap();
1480            (RedisStream::Tcp(client), RedisStream::Tcp(server))
1481        }
1482    }
1483
1484    async fn write_all(stream: &mut RedisStream, mut bytes: &[u8]) {
1485        while !bytes.is_empty() {
1486            let written = futures::future::poll_fn(|cx| {
1487                tokio::io::AsyncWrite::poll_write(Pin::new(&mut *stream), cx, bytes)
1488            })
1489            .await
1490            .unwrap();
1491            assert!(written > 0, "server socket closed while writing response");
1492            bytes = &bytes[written..];
1493        }
1494    }
1495
1496    async fn execute_against_response(
1497        config: &ConnectionConfig,
1498        response: &'static [u8],
1499    ) -> Result<(), RedisError> {
1500        let (client, server) = stream_pair().await;
1501        let server_task = tokio::spawn(async move {
1502            let mut framed = Framed::new(server, RespCodec::new());
1503            framed
1504                .next()
1505                .await
1506                .expect("client closed before sending its command")
1507                .expect("client sent an invalid command frame");
1508            let mut server = framed.into_inner();
1509            write_all(&mut server, response).await;
1510        });
1511
1512        let mut conn = RedisConnection::from_stream_with_config(client, config);
1513        let result = conn.execute(DummyCmd).await;
1514        server_task.await.unwrap();
1515        result
1516    }
1517
1518    async fn connect_against_hello_response(
1519        config: &ConnectionConfig,
1520        response: &'static [u8],
1521    ) -> Result<RedisConnection, RedisError> {
1522        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1523        let addr = listener.local_addr().unwrap();
1524        let server_task = tokio::spawn(async move {
1525            let (server, _) = listener.accept().await.unwrap();
1526            let mut framed = Framed::new(RedisStream::Tcp(server), RespCodec::new());
1527
1528            for _ in 0..2 {
1529                framed
1530                    .next()
1531                    .await
1532                    .expect("client closed during CLIENT SETINFO")
1533                    .expect("client sent an invalid CLIENT SETINFO frame");
1534                framed
1535                    .send(Frame::SimpleString(b"OK"[..].into()))
1536                    .await
1537                    .unwrap();
1538            }
1539
1540            framed
1541                .next()
1542                .await
1543                .expect("client closed before HELLO")
1544                .expect("client sent an invalid HELLO frame");
1545            let mut server = framed.into_inner();
1546            write_all(&mut server, response).await;
1547        });
1548
1549        let result = RedisConnection::connect_with_config(&addr.to_string(), config).await;
1550        server_task.await.unwrap();
1551        result
1552    }
1553
1554    async fn connect_against_setinfo_response(
1555        config: &ConnectionConfig,
1556        response: &'static [u8],
1557    ) -> Result<RedisConnection, RedisError> {
1558        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1559        let addr = listener.local_addr().unwrap();
1560        let server_task = tokio::spawn(async move {
1561            let (server, _) = listener.accept().await.unwrap();
1562            let mut framed = Framed::new(RedisStream::Tcp(server), RespCodec::new());
1563            framed
1564                .next()
1565                .await
1566                .expect("client closed before CLIENT SETINFO")
1567                .expect("client sent an invalid CLIENT SETINFO frame");
1568
1569            let mut server = framed.into_inner();
1570            write_all(&mut server, response).await;
1571
1572            // A default connection accepts the first response and sends the
1573            // LIB-VER command. A tight connection closes as soon as decoding
1574            // the first response violates its configured limit.
1575            let mut framed = Framed::new(server, RespCodec::new());
1576            if let Some(Ok(_command)) = framed.next().await {
1577                framed
1578                    .send(Frame::SimpleString(b"OK"[..].into()))
1579                    .await
1580                    .unwrap();
1581            }
1582        });
1583
1584        let result = RedisConnection::connect_with_config(&addr.to_string(), config).await;
1585        server_task.await.unwrap();
1586        result
1587    }
1588
1589    #[test]
1590    fn connection_config_defaults_and_builders() {
1591        let defaults = ConnectionConfig::new();
1592        let default_keepalive = KeepaliveConfig::default();
1593        assert_eq!(defaults.keepalive().idle, default_keepalive.idle);
1594        assert_eq!(defaults.keepalive().interval, default_keepalive.interval);
1595        assert_eq!(defaults.keepalive().probes, default_keepalive.probes);
1596        assert_eq!(defaults.connect_timeout(), None);
1597        assert_eq!(defaults.protocol(), ProtocolVersion::Auto);
1598        assert_eq!(defaults.resp_limits(), RespLimits::default());
1599
1600        let keepalive = KeepaliveConfig::new()
1601            .with_idle(Duration::from_secs(20))
1602            .with_interval(Duration::from_secs(4))
1603            .with_probes(7);
1604        let limits = RespLimits {
1605            max_frame_size: 4096,
1606            max_depth: 12,
1607        };
1608        let config = ConnectionConfig::new()
1609            .with_keepalive(keepalive)
1610            .with_connect_timeout(Some(Duration::from_secs(2)))
1611            .with_protocol(ProtocolVersion::Resp2)
1612            .with_resp_limits(limits);
1613
1614        assert_eq!(config.keepalive().idle, Duration::from_secs(20));
1615        assert_eq!(config.keepalive().interval, Duration::from_secs(4));
1616        assert_eq!(config.keepalive().probes, 7);
1617        assert_eq!(config.connect_timeout(), Some(Duration::from_secs(2)));
1618        assert_eq!(config.protocol(), ProtocolVersion::Resp2);
1619        assert_eq!(config.resp_limits(), limits);
1620        assert_eq!(
1621            config.clone().with_connect_timeout(None).connect_timeout(),
1622            None
1623        );
1624
1625        assert_eq!(
1626            resolve_url_protocol(Some(ProtocolVersion::Resp3), ProtocolVersion::Auto),
1627            ProtocolVersion::Resp3
1628        );
1629        assert_eq!(
1630            resolve_url_protocol(Some(ProtocolVersion::Resp2), ProtocolVersion::Resp3),
1631            ProtocolVersion::Resp3,
1632            "an explicit connection config must preserve RESP3-only client invariants"
1633        );
1634    }
1635
1636    #[tokio::test]
1637    async fn from_stream_with_config_installs_decode_limits() {
1638        let (client, _server) = stream_pair().await;
1639        let limits = RespLimits {
1640            max_frame_size: 2048,
1641            max_depth: 9,
1642        };
1643        let config = ConnectionConfig::new().with_resp_limits(limits);
1644        let conn = RedisConnection::from_stream_with_config(client, &config);
1645
1646        let framed = conn.into_framed().unwrap();
1647        assert_eq!(framed.codec().limits(), limits);
1648    }
1649
1650    #[tokio::test]
1651    async fn explicit_resp2_switches_an_existing_resp3_connection() {
1652        let (client, server) = stream_pair().await;
1653        let server_task = tokio::spawn(async move {
1654            let mut framed = Framed::new(server, RespCodec::new());
1655            let hello3 = framed.next().await.unwrap().unwrap();
1656            assert_eq!(hello3, array(vec![bulk("HELLO"), bulk("3")]));
1657            framed
1658                .send(Frame::SimpleString(b"OK"[..].into()))
1659                .await
1660                .unwrap();
1661
1662            let hello2 = framed.next().await.unwrap().unwrap();
1663            assert_eq!(hello2, array(vec![bulk("HELLO"), bulk("2")]));
1664            framed
1665                .send(Frame::SimpleString(b"OK"[..].into()))
1666                .await
1667                .unwrap();
1668        });
1669
1670        let mut conn = RedisConnection::from_stream(client);
1671        conn.negotiate_protocol(ProtocolVersion::Resp3)
1672            .await
1673            .unwrap();
1674        assert!(conn.is_resp3());
1675        conn.negotiate_protocol(ProtocolVersion::Resp2)
1676            .await
1677            .unwrap();
1678        assert!(!conn.is_resp3());
1679        server_task.await.unwrap();
1680    }
1681
1682    #[tokio::test]
1683    async fn configured_depth_limit_rejects_response_accepted_by_default() {
1684        const DEPTH_THREE: &[u8] = b"*1\r\n*1\r\n*1\r\n+OK\r\n";
1685
1686        execute_against_response(&ConnectionConfig::default(), DEPTH_THREE)
1687            .await
1688            .expect("the default nesting limit should accept this response");
1689
1690        let tight = ConnectionConfig::new().with_resp_limits(RespLimits {
1691            max_depth: 2,
1692            ..RespLimits::default()
1693        });
1694        let error = execute_against_response(&tight, DEPTH_THREE)
1695            .await
1696            .expect_err("the configured nesting limit should reject this response");
1697        assert!(matches!(
1698            error,
1699            RedisError::Protocol(ProtocolError::NestingTooDeep { max: 2 })
1700        ));
1701    }
1702
1703    #[tokio::test]
1704    async fn connect_with_config_applies_limits_before_hello_response() {
1705        const DEPTH_THREE: &[u8] = b"*1\r\n*1\r\n*1\r\n+OK\r\n";
1706
1707        let default_conn =
1708            connect_against_hello_response(&ConnectionConfig::default(), DEPTH_THREE)
1709                .await
1710                .expect("the default nesting limit should accept the HELLO response");
1711        assert!(default_conn.is_resp3());
1712
1713        let tight = ConnectionConfig::new().with_resp_limits(RespLimits {
1714            max_depth: 2,
1715            ..RespLimits::default()
1716        });
1717        let error = match connect_against_hello_response(&tight, DEPTH_THREE).await {
1718            Err(error) => error,
1719            Ok(_) => panic!("the configured nesting limit should reject the HELLO response"),
1720        };
1721        assert!(matches!(
1722            error,
1723            RedisError::Protocol(ProtocolError::NestingTooDeep { max: 2 })
1724        ));
1725    }
1726
1727    #[tokio::test]
1728    async fn connect_with_config_surfaces_limits_during_setinfo() {
1729        const DEPTH_THREE: &[u8] = b"*1\r\n*1\r\n*1\r\n+OK\r\n";
1730
1731        let defaults = ConnectionConfig::new().with_protocol(ProtocolVersion::Resp2);
1732        connect_against_setinfo_response(&defaults, DEPTH_THREE)
1733            .await
1734            .expect("the default nesting limit should accept the SETINFO response");
1735
1736        let tight = ConnectionConfig::new()
1737            .with_protocol(ProtocolVersion::Resp2)
1738            .with_resp_limits(RespLimits {
1739                max_depth: 2,
1740                ..RespLimits::default()
1741            });
1742        let error = match connect_against_setinfo_response(&tight, DEPTH_THREE).await {
1743            Err(error) => error,
1744            Ok(_) => panic!("the configured nesting limit should reject the SETINFO response"),
1745        };
1746        assert!(matches!(
1747            error,
1748            RedisError::Protocol(ProtocolError::NestingTooDeep { max: 2 })
1749        ));
1750    }
1751
1752    #[test]
1753    fn into_framed_returns_error_when_none() {
1754        let conn = RedisConnection {
1755            framed: None,
1756            push_tx: None,
1757            received_push_tx: None,
1758            inflight: None,
1759            resp3: false,
1760        };
1761        match conn.into_framed() {
1762            Err(RedisError::ConnectionInUse) => {}
1763            Err(other) => panic!("expected ConnectionInUse, got: {other}"),
1764            Ok(_) => panic!("expected Err(ConnectionInUse), got Ok"),
1765        }
1766    }
1767
1768    #[tokio::test]
1769    async fn ensure_framed_returns_error_when_no_framed_and_no_inflight() {
1770        let mut conn = RedisConnection {
1771            framed: None,
1772            push_tx: None,
1773            received_push_tx: None,
1774            inflight: None,
1775            resp3: false,
1776        };
1777        match conn.ensure_framed().await {
1778            Err(RedisError::ConnectionClosed) => {}
1779            other => panic!("expected ConnectionClosed, got: {other:?}"),
1780        }
1781    }
1782
1783    #[tokio::test]
1784    async fn ensure_framed_returns_error_when_inflight_sender_dropped() {
1785        let (tx, rx) = oneshot::channel::<Framed<RedisStream, RespCodec>>();
1786        drop(tx);
1787
1788        let mut conn = RedisConnection {
1789            framed: None,
1790            push_tx: None,
1791            received_push_tx: None,
1792            inflight: Some(rx),
1793            resp3: false,
1794        };
1795        match conn.ensure_framed().await {
1796            Err(RedisError::ConnectionClosed) => {}
1797            other => panic!("expected ConnectionClosed, got: {other:?}"),
1798        }
1799    }
1800
1801    #[tokio::test]
1802    async fn poll_ready_returns_connection_closed_after_cancelled_future() {
1803        use tower_service::Service;
1804
1805        // Simulate a cancelled Service::call future: the sender side of the
1806        // oneshot is dropped without sending the framed transport back.
1807        let (tx, rx) = oneshot::channel::<Framed<RedisStream, RespCodec>>();
1808        drop(tx); // Simulates the future being dropped before completion.
1809
1810        let mut conn = RedisConnection {
1811            framed: None,
1812            push_tx: None,
1813            received_push_tx: None,
1814            inflight: Some(rx),
1815            resp3: false,
1816        };
1817
1818        // poll_ready should detect the cancelled sender and return an error
1819        // rather than hanging forever.
1820        let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
1821        match Service::<DummyCmd>::poll_ready(&mut conn, &mut cx) {
1822            Poll::Ready(Err(RedisError::ConnectionClosed)) => {}
1823            other => panic!("expected Ready(Err(ConnectionClosed)), got: {other:?}"),
1824        }
1825    }
1826
1827    #[tokio::test]
1828    async fn connect_failure_carries_target_address() {
1829        // Port 1 is reserved and effectively never accepts connections, so the
1830        // connect attempt fails. Whatever the underlying io error, the address
1831        // it failed against must be attached (#464). `RedisConnection` is not
1832        // `Debug`, so match rather than use `expect_err`.
1833        let addr = "127.0.0.1:1";
1834        match RedisConnection::connect(addr).await {
1835            Err(err) => {
1836                assert!(err.is_connection_error(), "got: {err:?}");
1837                assert_eq!(err.connection_addr(), Some(addr));
1838                assert!(err.to_string().contains(addr), "missing addr in: {err}");
1839            }
1840            Ok(_) => panic!("connecting to a reserved port should fail"),
1841        }
1842    }
1843
1844    #[tokio::test]
1845    async fn connect_with_timeout_failure_carries_target_address() {
1846        let addr = "127.0.0.1:1";
1847        match RedisConnection::connect_with_timeout(addr, Duration::from_secs(5)).await {
1848            // Either a refused connection (addr attached) or, on a slow host, a
1849            // ConnectTimeout. The refused path is what we exercise here.
1850            Err(RedisError::ConnectTimeout) => {}
1851            Err(err) => assert_eq!(err.connection_addr(), Some(addr), "got: {err:?}"),
1852            Ok(_) => panic!("connecting to a reserved port should fail"),
1853        }
1854    }
1855
1856    #[tokio::test]
1857    async fn plaintext_url_preserves_an_ipv6_scope_id() {
1858        let listener = match tokio::net::TcpListener::bind("[::1]:0").await {
1859            Ok(listener) => listener,
1860            Err(error) if error.kind() == std::io::ErrorKind::AddrNotAvailable => {
1861                eprintln!("skipping scoped IPv6 URL test: IPv6 loopback is unavailable");
1862                return;
1863            }
1864            Err(error) => panic!("bind IPv6 loopback: {error}"),
1865        };
1866        let address = listener.local_addr().expect("read listener address");
1867        let server = tokio::spawn(async move {
1868            let (stream, _) = listener.accept().await.expect("accept client");
1869            let mut framed = Framed::new(stream, RespCodec::new());
1870            for _ in 0..2 {
1871                framed
1872                    .next()
1873                    .await
1874                    .expect("client closed during setup")
1875                    .expect("decode CLIENT SETINFO");
1876                framed
1877                    .send(Frame::SimpleString(b"OK"[..].into()))
1878                    .await
1879                    .expect("reply to CLIENT SETINFO");
1880            }
1881        });
1882
1883        let url = format!("redis://[::1%0]:{}/", address.port());
1884        let connection = RedisConnection::connect_url_with_config(
1885            &url,
1886            &ConnectionConfig::new().with_protocol(ProtocolVersion::Resp2),
1887        )
1888        .await
1889        .unwrap_or_else(|error| panic!("connect to {url}: {error}"));
1890        drop(connection);
1891        server.await.expect("join test server");
1892    }
1893
1894    #[tokio::test]
1895    async fn staged_url_connection_orders_provider_auth_before_database_and_protocol() {
1896        struct ProviderAuth;
1897        impl Command for ProviderAuth {
1898            type Response = ();
1899
1900            fn to_frame(&self) -> Frame {
1901                array(vec![bulk("AUTH"), bulk("provider-secret")])
1902            }
1903
1904            fn parse_response(&self, frame: Frame) -> Result<(), RedisError> {
1905                match frame {
1906                    Frame::SimpleString(value) if value == b"OK"[..] => Ok(()),
1907                    other => Err(RedisError::UnexpectedResponse {
1908                        expected: "OK",
1909                        actual: format!("{other:?}"),
1910                    }),
1911                }
1912            }
1913
1914            fn name(&self) -> &str {
1915                "AUTH"
1916            }
1917        }
1918
1919        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
1920            .await
1921            .expect("bind staged URL test listener");
1922        let address = listener.local_addr().expect("read staged URL address");
1923        let server = tokio::spawn(async move {
1924            let (stream, _) = listener.accept().await.expect("accept staged URL client");
1925            let mut framed = Framed::new(stream, RespCodec::new());
1926            let expected = [
1927                array(vec![
1928                    bulk("CLIENT"),
1929                    bulk("SETINFO"),
1930                    bulk("LIB-NAME"),
1931                    bulk("redis-tower"),
1932                ]),
1933                array(vec![
1934                    bulk("CLIENT"),
1935                    bulk("SETINFO"),
1936                    bulk("LIB-VER"),
1937                    bulk(env!("CARGO_PKG_VERSION")),
1938                ]),
1939                array(vec![bulk("AUTH"), bulk("provider-secret")]),
1940                array(vec![bulk("SELECT"), bulk("2")]),
1941                array(vec![bulk("HELLO"), bulk("3")]),
1942            ];
1943            for expected_command in expected {
1944                let actual = framed
1945                    .next()
1946                    .await
1947                    .expect("client closed during staged URL setup")
1948                    .expect("decode staged URL setup command");
1949                assert_eq!(actual, expected_command);
1950                framed
1951                    .send(Frame::SimpleString(b"OK"[..].into()))
1952                    .await
1953                    .expect("reply to staged URL setup command");
1954            }
1955        });
1956
1957        let url = format!(
1958            "redis://static:ignored@127.0.0.1:{}/2?protocol=resp3",
1959            address.port()
1960        );
1961        let mut pending =
1962            RedisConnection::begin_url_connection_with_config(&url, &ConnectionConfig::default())
1963                .await
1964                .expect("open staged URL transport");
1965        pending
1966            .connection_mut()
1967            .execute(ProviderAuth)
1968            .await
1969            .expect("authenticate staged URL connection");
1970        let connection = pending.finish().await.expect("finish staged URL setup");
1971        assert!(connection.is_resp3());
1972        drop(connection);
1973        server.await.expect("join staged URL server");
1974    }
1975
1976    #[cfg(unix)]
1977    #[tokio::test]
1978    async fn unix_url_runs_the_complete_connection_setup_in_order() {
1979        let nonce = std::time::SystemTime::now()
1980            .duration_since(std::time::UNIX_EPOCH)
1981            .unwrap()
1982            .as_nanos();
1983        let path = std::path::PathBuf::from(format!(
1984            "/tmp/redis tower setup-{}-{nonce}.sock",
1985            std::process::id()
1986        ));
1987        let listener = tokio::net::UnixListener::bind(&path).expect("bind Unix setup socket");
1988        let server = tokio::spawn(async move {
1989            let (stream, _) = listener.accept().await.expect("accept Unix client");
1990            let mut framed = Framed::new(stream, RespCodec::new());
1991            let expected = [
1992                array(vec![
1993                    bulk("CLIENT"),
1994                    bulk("SETINFO"),
1995                    bulk("LIB-NAME"),
1996                    bulk("redis-tower"),
1997                ]),
1998                array(vec![
1999                    bulk("CLIENT"),
2000                    bulk("SETINFO"),
2001                    bulk("LIB-VER"),
2002                    bulk(env!("CARGO_PKG_VERSION")),
2003                ]),
2004                array(vec![bulk("AUTH"), bulk("agent"), bulk("secret+value")]),
2005                array(vec![bulk("SELECT"), bulk("1")]),
2006                array(vec![bulk("HELLO"), bulk("3")]),
2007            ];
2008            for expected_command in expected {
2009                let actual = framed
2010                    .next()
2011                    .await
2012                    .expect("client closed during Unix setup")
2013                    .expect("decode Unix setup command");
2014                assert_eq!(actual, expected_command);
2015                framed
2016                    .send(Frame::SimpleString(b"OK"[..].into()))
2017                    .await
2018                    .expect("reply to Unix setup command");
2019            }
2020        });
2021
2022        let encoded_path = path.to_str().unwrap().replace(' ', "%20");
2023        let url = format!(
2024            "redis+unix://{encoded_path}?user=agent&pass=secret%2Bvalue&db=1&protocol=resp3"
2025        );
2026        let connection = RedisConnection::connect_url(&url)
2027            .await
2028            .unwrap_or_else(|error| panic!("complete Unix URL setup: {error}"));
2029        assert!(connection.is_resp3());
2030        drop(connection);
2031        server.await.expect("join Unix setup server");
2032        std::fs::remove_file(path).expect("remove Unix setup socket");
2033    }
2034
2035    // Linux permits arbitrary non-NUL bytes in a Unix socket pathname. macOS
2036    // rejects non-UTF-8 socket names with EILSEQ, so the byte-preserving
2037    // connector path is exercised where such a path can actually be bound.
2038    #[cfg(target_os = "linux")]
2039    #[tokio::test]
2040    async fn unix_url_connects_without_lossy_path_conversion() {
2041        use std::ffi::OsString;
2042        use std::os::unix::ffi::OsStringExt;
2043
2044        let nonce = std::time::SystemTime::now()
2045            .duration_since(std::time::UNIX_EPOCH)
2046            .unwrap()
2047            .as_nanos();
2048        let stem = format!("/tmp/redis-tower-{}-{nonce}", std::process::id());
2049        let mut path_bytes = format!("{stem}-").into_bytes();
2050        path_bytes.push(0xff);
2051        path_bytes.extend_from_slice(b".sock");
2052        let path = std::path::PathBuf::from(OsString::from_vec(path_bytes));
2053        let listener = tokio::net::UnixListener::bind(&path).expect("bind non-UTF-8 Unix path");
2054        let server = tokio::spawn(async move {
2055            let (stream, _) = listener.accept().await.expect("accept Unix client");
2056            let mut framed = Framed::new(stream, RespCodec::new());
2057            for _ in 0..2 {
2058                framed
2059                    .next()
2060                    .await
2061                    .expect("client closed during setup")
2062                    .expect("decode CLIENT SETINFO");
2063                framed
2064                    .send(Frame::SimpleString(b"OK"[..].into()))
2065                    .await
2066                    .expect("reply to CLIENT SETINFO");
2067            }
2068        });
2069
2070        let url = format!("unix://{stem}-%FF.sock?protocol=resp2");
2071        let connection = RedisConnection::connect_url(&url)
2072            .await
2073            .unwrap_or_else(|error| panic!("connect to non-UTF-8 Unix path: {error}"));
2074        assert!(!connection.is_resp3());
2075        drop(connection);
2076        server.await.expect("join Unix test server");
2077        std::fs::remove_file(path).expect("remove Unix test socket");
2078    }
2079
2080    #[cfg(feature = "tls-rustls")]
2081    #[tokio::test]
2082    async fn tls_urls_complete_an_ipv6_connection() {
2083        let rustls = (
2084            "rustls",
2085            crate::tls::TlsConfig::default_rustls()
2086                .danger_accept_invalid_certs(true)
2087                .danger_accept_invalid_hostnames(true),
2088        );
2089        #[cfg(feature = "tls-native-tls")]
2090        let backends = [
2091            rustls,
2092            (
2093                "native-tls",
2094                crate::tls::TlsConfig::default_native_tls()
2095                    .danger_accept_invalid_certs(true)
2096                    .danger_accept_invalid_hostnames(true),
2097            ),
2098        ];
2099        #[cfg(not(feature = "tls-native-tls"))]
2100        let backends = [rustls];
2101
2102        for (backend, tls) in backends {
2103            for scheme in ["rediss", "valkeys"] {
2104                let listener = match tokio::net::TcpListener::bind("[::1]:0").await {
2105                    Ok(listener) => listener,
2106                    Err(error) if error.kind() == std::io::ErrorKind::AddrNotAvailable => {
2107                        if std::env::var_os("REDIS_TEST_REQUIRE_IPV6").is_some() {
2108                            panic!("required IPv6 loopback is unavailable: {error}");
2109                        }
2110                        eprintln!("skipping TLS URL IPv6 test: IPv6 loopback is unavailable");
2111                        return;
2112                    }
2113                    Err(error) => panic!("bind IPv6 loopback: {error}"),
2114                };
2115                let address = listener.local_addr().expect("read listener address");
2116                let acceptor = tokio_rustls::TlsAcceptor::from(crate::tls::tests::server_config());
2117                let server = tokio::spawn(async move {
2118                    let (stream, _) = listener.accept().await.expect("accept TLS client");
2119                    let stream = acceptor.accept(stream).await.expect("accept TLS handshake");
2120                    let mut framed = Framed::new(stream, RespCodec::new());
2121                    for _ in 0..2 {
2122                        framed
2123                            .next()
2124                            .await
2125                            .expect("client closed during setup")
2126                            .expect("decode CLIENT SETINFO");
2127                        framed
2128                            .send(Frame::SimpleString(b"OK"[..].into()))
2129                            .await
2130                            .expect("reply to CLIENT SETINFO");
2131                    }
2132                });
2133
2134                let url = format!("{scheme}://[::1]:{}/", address.port());
2135                let connection = RedisConnection::connect_url_with_tls_and_config(
2136                    &url,
2137                    &tls,
2138                    &ConnectionConfig::new().with_protocol(ProtocolVersion::Resp2),
2139                )
2140                .await
2141                .unwrap_or_else(|error| panic!("connect to {url} with {backend}: {error}"));
2142                drop(connection);
2143                server.await.expect("join test TLS server");
2144            }
2145        }
2146    }
2147
2148    #[test]
2149    fn frame_guard_cancels_transport_return_on_drop() {
2150        let (return_tx, mut return_rx) = oneshot::channel::<Framed<RedisStream, RespCodec>>();
2151
2152        let guard = FrameGuard {
2153            framed: None,
2154            return_tx: Some(return_tx),
2155        };
2156        drop(guard);
2157
2158        // Cancellation drops the sender instead of returning a transport.
2159        assert!(return_rx.try_recv().is_err());
2160    }
2161
2162    #[tokio::test]
2163    async fn cancelling_typed_call_after_wire_quarantines_transport() {
2164        use tower_service::Service;
2165
2166        let (client, server) = stream_pair().await;
2167        let (wire_tx, mut wire_rx) = oneshot::channel();
2168        let (release_tx, release_rx) = oneshot::channel();
2169        let (late_attempt_tx, late_attempt_rx) = oneshot::channel();
2170
2171        let server_task = tokio::spawn(async move {
2172            let mut framed = Framed::new(server, RespCodec::new());
2173            framed
2174                .next()
2175                .await
2176                .expect("client closed before sending its command")
2177                .expect("client sent an invalid command frame");
2178            wire_tx.send(()).unwrap();
2179
2180            release_rx.await.unwrap();
2181            let late_result = framed.send(Frame::SimpleString(b"LATE"[..].into())).await;
2182            late_attempt_tx.send(()).unwrap();
2183
2184            // A small response can reach the kernel even after the peer has
2185            // closed. Either way, the quarantined socket must not carry a
2186            // second request.
2187            if late_result.is_ok() {
2188                match tokio::time::timeout(Duration::from_secs(1), framed.next()).await {
2189                    Ok(None) | Ok(Some(Err(_))) => {}
2190                    Ok(Some(Ok(frame))) => panic!("cancelled socket was reused: {frame:?}"),
2191                    Err(_) => panic!("cancelled socket remained open"),
2192                }
2193            }
2194        });
2195
2196        let mut conn = RedisConnection::from_stream(client);
2197        futures::future::poll_fn(|cx| Service::<DummyCmd>::poll_ready(&mut conn, cx))
2198            .await
2199            .unwrap();
2200        let mut call = Service::<DummyCmd>::call(&mut conn, DummyCmd);
2201
2202        // Drive the call until the server has decoded the request, then cancel
2203        // it while the response is deliberately withheld.
2204        tokio::select! {
2205            result = &mut call => panic!("call completed before cancellation: {result:?}"),
2206            observed = &mut wire_rx => observed.unwrap(),
2207        }
2208        drop(call);
2209
2210        release_tx.send(()).unwrap();
2211        late_attempt_rx.await.unwrap();
2212
2213        let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
2214        let readiness = Service::<DummyCmd>::poll_ready(&mut conn, &mut cx);
2215        let is_closed = matches!(readiness, Poll::Ready(Err(RedisError::ConnectionClosed)));
2216        drop(conn);
2217        server_task.await.unwrap();
2218
2219        assert!(
2220            is_closed,
2221            "cancelled connection was reusable: {readiness:?}"
2222        );
2223    }
2224
2225    #[tokio::test]
2226    async fn redis_error_response_keeps_typed_connection_reusable() {
2227        use tower_service::Service;
2228
2229        let (client, server) = stream_pair().await;
2230        let server_task = tokio::spawn(async move {
2231            let mut framed = Framed::new(server, RespCodec::new());
2232
2233            framed
2234                .next()
2235                .await
2236                .expect("client closed before first command")
2237                .expect("client sent an invalid first command");
2238            framed
2239                .send(Frame::Error(b"WRONGTYPE test error"[..].into()))
2240                .await
2241                .unwrap();
2242
2243            framed
2244                .next()
2245                .await
2246                .expect("connection closed after Redis error")
2247                .expect("client sent an invalid second command");
2248            framed
2249                .send(Frame::SimpleString(b"OK"[..].into()))
2250                .await
2251                .unwrap();
2252        });
2253
2254        let mut conn = RedisConnection::from_stream(client);
2255        futures::future::poll_fn(|cx| Service::<DummyCmd>::poll_ready(&mut conn, cx))
2256            .await
2257            .unwrap();
2258        let error = Service::<DummyCmd>::call(&mut conn, DummyCmd)
2259            .await
2260            .unwrap_err();
2261        assert!(matches!(
2262            error,
2263            RedisError::Redis(ref message) if message.starts_with("WRONGTYPE")
2264        ));
2265
2266        futures::future::poll_fn(|cx| Service::<DummyCmd>::poll_ready(&mut conn, cx))
2267            .await
2268            .expect("complete Redis error response should preserve readiness");
2269        Service::<DummyCmd>::call(&mut conn, DummyCmd)
2270            .await
2271            .expect("connection should remain usable after Redis error");
2272
2273        server_task.await.unwrap();
2274    }
2275
2276    #[cfg(unix)]
2277    #[tokio::test]
2278    async fn idle_push_read_is_cancellation_safe_and_routes_the_complete_frame() {
2279        let (client, mut server) = stream_pair().await;
2280        let mut conn = RedisConnection::from_stream(client);
2281        let mut pushes = conn.subscribe_pushes();
2282        let expected = Frame::Push(vec![
2283            Frame::SimpleString(b"invalidate"[..].into()),
2284            Frame::Array(Some(vec![Frame::SimpleString(b"key"[..].into())])),
2285        ]);
2286        let wire = redis_tower_protocol::frame_to_bytes(&expected);
2287
2288        // Leave the final LF outstanding so the first idle read buffers a
2289        // partial frame, then cancel that read at a deterministic boundary.
2290        let split = wire.len() - 1;
2291        write_all(&mut server, &wire[..split]).await;
2292        assert!(
2293            tokio::time::timeout(Duration::from_millis(10), conn.read_idle_push())
2294                .await
2295                .is_err(),
2296            "an incomplete push unexpectedly decoded"
2297        );
2298
2299        write_all(&mut server, &wire[split..]).await;
2300        conn.read_idle_push()
2301            .await
2302            .expect("the cancelled read must preserve its buffered prefix");
2303        assert_eq!(pushes.recv().await.unwrap(), expected);
2304    }
2305
2306    #[cfg(unix)]
2307    #[tokio::test]
2308    async fn timestamped_push_feed_coexists_with_the_application_receiver() {
2309        let (client, mut server) = stream_pair().await;
2310        let mut conn = RedisConnection::from_stream(client);
2311        let mut application_pushes = conn.subscribe_pushes();
2312        let mut received_pushes = conn.subscribe_received_pushes();
2313        let expected = Frame::Push(vec![
2314            Frame::SimpleString(b"maintenance"[..].into()),
2315            Frame::Integer(7),
2316        ]);
2317        let before = std::time::Instant::now();
2318
2319        write_all(
2320            &mut server,
2321            &redis_tower_protocol::frame_to_bytes(&expected),
2322        )
2323        .await;
2324        conn.read_idle_push().await.unwrap();
2325
2326        assert_eq!(application_pushes.recv().await.unwrap(), expected);
2327        let received = received_pushes.recv().await.unwrap();
2328        assert_eq!(received.frame, expected);
2329        assert!(received.received_at >= before);
2330    }
2331
2332    #[cfg(unix)]
2333    #[tokio::test]
2334    async fn idle_push_read_reports_eof_and_unsolicited_responses() {
2335        let (client, server) = stream_pair().await;
2336        let mut conn = RedisConnection::from_stream(client);
2337        drop(server);
2338        assert!(matches!(
2339            conn.read_idle_push().await,
2340            Err(RedisError::ConnectionClosed)
2341        ));
2342        assert!(conn.framed.is_none(), "EOF transport was not quarantined");
2343
2344        let (client, mut server) = stream_pair().await;
2345        let mut conn = RedisConnection::from_stream(client);
2346        let server_task = tokio::spawn(async move {
2347            write_all(&mut server, b"+PONG\r\n").await;
2348        });
2349        assert!(matches!(
2350            conn.read_idle_push().await,
2351            Err(RedisError::UnexpectedResponse { .. })
2352        ));
2353        assert!(
2354            conn.framed.is_none(),
2355            "unsolicited response transport was not quarantined"
2356        );
2357        server_task.await.unwrap();
2358    }
2359
2360    #[test]
2361    fn subscribe_pushes_returns_receiver() {
2362        let mut conn = RedisConnection {
2363            framed: None,
2364            push_tx: None,
2365            received_push_tx: None,
2366            inflight: None,
2367            resp3: false,
2368        };
2369        let _rx = conn.subscribe_pushes();
2370        assert!(conn.push_tx.is_some());
2371    }
2372
2373    // -- redis.connect span --
2374
2375    use std::sync::{Arc, Mutex};
2376    use tracing_subscriber::layer::{Context, Layer};
2377    use tracing_subscriber::prelude::*;
2378
2379    /// A tracing layer that records each new span as `"<name> field=value ..."`.
2380    #[derive(Clone, Default)]
2381    struct SpanCapture {
2382        spans: Arc<Mutex<Vec<String>>>,
2383    }
2384
2385    struct FieldCollector(String);
2386
2387    impl tracing::field::Visit for FieldCollector {
2388        fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
2389            self.0.push_str(&format!(" {}={:?}", field.name(), value));
2390        }
2391    }
2392
2393    impl<S> Layer<S> for SpanCapture
2394    where
2395        S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
2396    {
2397        fn on_new_span(
2398            &self,
2399            attrs: &tracing::span::Attributes<'_>,
2400            _id: &tracing::span::Id,
2401            _ctx: Context<'_, S>,
2402        ) {
2403            let mut collector = FieldCollector(String::new());
2404            attrs.record(&mut collector);
2405            self.spans
2406                .lock()
2407                .unwrap()
2408                .push(format!("{}{}", attrs.metadata().name(), collector.0));
2409        }
2410    }
2411
2412    #[tokio::test]
2413    async fn connect_emits_redis_connect_span() {
2414        let capture = SpanCapture::default();
2415        let subscriber = tracing_subscriber::registry().with(capture.clone());
2416        let _guard = tracing::subscriber::set_default(subscriber);
2417
2418        // Port 1 is closed, so the connect fails fast. The `redis.connect` span
2419        // is still created around the attempt, which is what we assert on.
2420        let _ = RedisConnection::connect("127.0.0.1:1").await;
2421
2422        let spans = capture.spans.lock().unwrap();
2423        assert!(
2424            spans.iter().any(|s| {
2425                s.starts_with("redis.connect")
2426                    && s.contains("server.address")
2427                    && s.contains("127.0.0.1:1")
2428                    && s.contains("tls=false")
2429            }),
2430            "expected a redis.connect span with server.address and tls=false, got: {spans:?}"
2431        );
2432    }
2433}