diff --git a/src/runtime/valkey_jsc/js_valkey.rs b/src/runtime/valkey_jsc/js_valkey.rs index 92dd5cd0da3b..c8f0d1567550 100644 --- a/src/runtime/valkey_jsc/js_valkey.rs +++ b/src/runtime/valkey_jsc/js_valkey.rs @@ -761,6 +761,7 @@ impl JSValkeyClient { read_buffer: Default::default(), reply_scanner: Default::default(), retry_attempts: 0, + failure: None, auto_flusher: Default::default(), }), global_object, @@ -873,6 +874,7 @@ impl JSValkeyClient { read_buffer: Default::default(), reply_scanner: Default::default(), retry_attempts: 0, + failure: None, auto_flusher: Default::default(), }), global_object, @@ -974,13 +976,17 @@ impl JSValkeyClient { let promise = promise_ptr.to_js(); Js::connection_promise_set_cached(this_value, global_object, promise); - // If was manually closed, reset that flag + // If was manually closed, reset that flag. A close() that interrupted + // a dial in this same tick is taken back with it: the deferred close + // of that dial now settles this connect(), and reports the dial's own + // outcome rather than the close. self.client_mut().flags.is_manually_closed = false; - // Explicit connect() should also clear the sticky `failed` flag so the + self.client_mut().flags.close_aborted_dial = false; + // Explicit connect() should also clear the sticky failure so the // client can recover after prior connection attempts exhausted retries. // Without this, every subsequent command rejects with "Connection has // failed" forever — see https://github.com/oven-sh/bun/issues/29925. - self.client_mut().flags.failed = false; + self.client_mut().failure = None; let self_br = BackRef::new(self); let _update = scopeguard::guard(self_br, |p| p.update_poll_ref()); @@ -988,13 +994,10 @@ impl JSValkeyClient { self.poll_ref.with_mut(|r| r.ref_(vm_event_loop_ctx())); if let Err(err) = self.connect() { - debug!( - "first dial failed before a socket was opened: {}", - err.name() - ); + debug!("first dial failed before a socket was opened: {:?}", err); // Settled by the deferred close like a refused dial: the // promise, onclose and the retry policy all go through on_close(). - self.close_without_socket_next_tick(); + self.close_without_socket_next_tick(self.dial_error_message(&err), false); return Ok(promise); } @@ -1053,7 +1056,8 @@ impl JSValkeyClient { // `on_valkey_close` adopts none. The caller's scoped ref covers the // call. self.reconnect_timer.disarm(self); - self.client_mut().on_close() + self.client_mut() + .on_close(valkey::CloseReason::SocketClosed) } // `onconnect`/`onclose` are declared with `this: true` in @@ -1078,7 +1082,7 @@ impl JSValkeyClient { let _guard = self.ref_guard(); let _timer_ref = self.timer.take_fire_ref(self); - if self.client.get().flags.failed { + if self.client.get().failure.is_some() { return Ok(()); } @@ -1135,10 +1139,43 @@ impl JSValkeyClient { /// commands queued for the retry or the rejection, and a disconnect() /// marks the close as manual for the task to honour. `update_poll_ref` /// keeps the wrapper and the event loop alive for it like a dial would. - fn close_without_socket_next_tick(&self) { + fn close_without_socket_next_tick(&self, reason: Box<[u8]>, terminal: bool) { self.client_mut().status = valkey::Status::Connecting; self.update_poll_ref(); - self.enqueue_deferred_close(DeferredClose::WithoutSocket); + self.enqueue_deferred_close(DeferredClose::WithoutSocket { reason, terminal }); + } + + /// The `CloseReason::DialFailed` text for a dial uSockets turned down + /// before it had a socket, in the shape of `node:net`'s: `connect ENOENT + /// /run/redis.sock`. + fn dial_error_message(&self, err: &uws::ConnectError) -> Box<[u8]> { + let &uws::ConnectError::FailedToOpenSocket { mut errno } = err; + let address = &self.client.get().address; + if let valkey::Address::Unix(path) = address { + errno = bun_errno::from_errno(bun_sys::unix_connect_errno(errno as i32, path)); + } + Self::connect_error_message(address, errno) + } + + fn connect_error_message( + address: &valkey::Address, + errno: bun_errno::SystemErrno, + ) -> Box<[u8]> { + use std::io::Write; + let mut message = Vec::new(); + let _ = write!(message, "connect {} ", errno); + match address { + valkey::Address::Unix(path) => message.extend_from_slice(path), + valkey::Address::Host { host, port } => { + // `URL.host()` keeps an IPv6 literal's brackets; node prints `::1:6379`. + let host = host + .strip_prefix(b"[") + .and_then(|h| h.strip_suffix(b"]")) + .unwrap_or(host); + let _ = write!(message, "{}:{}", bstr::BStr::new(host), port); + } + } + message.into_boxed_slice() } fn enqueue_deferred_close(&self, what: DeferredClose) { @@ -1197,13 +1234,10 @@ impl JSValkeyClient { }); if let Err(err) = self.connect() { - debug!( - "reconnect failed before a socket was opened: {}", - err.name() - ); + debug!("reconnect failed before a socket was opened: {:?}", err); // Same outcome as a dial that fails asynchronously: another retry, // or fail() and a settled connect() promise once retries are used up. - self.close_without_socket_next_tick(); + self.close_without_socket_next_tick(self.dial_error_message(&err), false); return Ok(()); } @@ -1397,12 +1431,17 @@ impl JSValkeyClient { return Err(bun_jsc::JsError::Thrown); } - // Create an error value - let error_value = protocol_jsc::valkey_error_to_js( - &global_object, - b"Connection closed", - protocol::RedisError::ConnectionClosed, - ); + // The error the commands were rejected with. Every arm of `on_close()` + // calls `fail()` first, and the one `fail()` that cannot record (a + // finalized client) never gets past the `this_value` guard above. + let Some(failure) = &self.client.get().failure else { + debug_assert!( + false, + "on_close() records a failure before on_valkey_close()" + ); + return Ok(()); + }; + let error_value = failure.get(); let _exit = self.vm().enter_event_loop_scope(); @@ -1462,7 +1501,7 @@ impl JSValkeyClient { self.reconnect_timer.disarm(self); } - fn connect(&self) -> Result<(), crate::Error> { + fn connect(&self) -> Result<(), uws::ConnectError> { // Overwriting a live socket below would leave its callbacks driving // this client alongside the new one's. debug_assert!(self.client.get().socket.is_closed()); @@ -1503,12 +1542,11 @@ impl JSValkeyClient { false }; if tls_ctx_failed { - self.client_mut().flags.enable_auto_reconnect = false; - self.client_fail( - b"Failed to create TLS context", - protocol::RedisError::ConnectionClosed, - )?; - self.close_without_socket_next_tick(); + // Terminal: no retry could build the context either. + self.close_without_socket_next_tick( + Box::from(&b"Failed to create TLS context"[..]), + true, + ); return Ok(()); } let ssl_ctx: Option<*mut uws::SslCtx> = match &self.client.get().tls { @@ -1586,11 +1624,8 @@ impl JSValkeyClient { // The command is queued as for a dial in flight; the deferred // close then rejects it or a retry sends it, like a refused dial. Err(err) => { - debug!( - "first dial failed before a socket was opened: {}", - err.name() - ); - self.close_without_socket_next_tick(); + debug!("first dial failed before a socket was opened: {:?}", err); + self.close_without_socket_next_tick(self.dial_error_message(&err), false); } Ok(()) => self.reset_connection_timeout(), } @@ -1878,7 +1913,8 @@ impl SocketHandler { this.client_mut().status = valkey::Status::Disconnected; let _defer = scopeguard::guard(BackRef::new(this), |p| p.update_poll_ref()); - this.client_mut().on_close() + this.client_mut() + .on_close(valkey::CloseReason::SocketClosed) } pub(crate) fn on_end(this: &JSValkeyClient, socket: SocketType) { @@ -1890,11 +1926,17 @@ impl SocketHandler { // anything here } + /// `errno` is the connect's error in `SystemErrno` numbering (the uSockets + /// trampoline maps the OS code), or, when `dns_error` is set, the + /// `getaddrinfo(3)` code of the lookup that failed instead. pub(crate) fn on_connect_error( this: &JSValkeyClient, - _socket: SocketType, - _code: i32, + socket: SocketType, + errno: i32, ) -> JsResult<()> { + // Read before the socket is detached: uSockets keeps the connecting + // socket alive for the whole dispatch. + let dns_error = socket.dns_error(); // Ensure the socket pointer is updated. this.client_mut().socket = Socket::SocketTcp(uws::SocketTCP::detached()); let _guard = this.ref_guard(); @@ -1903,7 +1945,29 @@ impl SocketHandler { this.client_mut().status = valkey::Status::Disconnected; let _defer = scopeguard::guard(BackRef::new(this), |p| p.update_poll_ref()); - this.client_mut().on_close() + let address = &this.client.get().address; + let message = match bun_cares_sys::c_ares::Error::init_eai(dns_error) + .filter(|_| dns_error != 0) + { + Some(dns_err) => { + use std::io::Write; + let mut message = Vec::new(); + // `code()` is `DNS_ENOTFOUND`; `node:dns` and `Bun.connect` + // report it as `getaddrinfo ENOTFOUND host`. + let _ = write!( + message, + "getaddrinfo {} {}", + &dns_err.code()[4..], + bstr::BStr::new(address.hostname()) + ); + message.into_boxed_slice() + } + None => JSValkeyClient::connect_error_message(address, bun_errno::from_errno(errno)), + }; + this.client_mut().on_close(valkey::CloseReason::DialFailed { + message: &message, + terminal: false, + }) } pub(crate) fn on_timeout(this: &JSValkeyClient, socket: SocketType) { @@ -2020,13 +2084,13 @@ impl Options { } } -#[derive(Clone, Copy)] enum DeferredClose { /// Close the socket the finalized wrapper left behind. Socket, /// Run the close path for a dial that never produced a socket - /// (`close_without_socket_next_tick`). - WithoutSocket, + /// (`close_without_socket_next_tick`); `reason` and `terminal` are the + /// `CloseReason::DialFailed` it runs with. + WithoutSocket { reason: Box<[u8]>, terminal: bool }, } pub(crate) struct ValkeyDeferredClose { @@ -2042,18 +2106,21 @@ impl ValkeyDeferredClose { let _enqueue_ref = unsafe { RefPtr::from_raw(self.ctx) }; // SAFETY: live per the ref above; tasks run on the JS thread. let this = unsafe { &*self.ctx }; - match self.what { + match &self.what { DeferredClose::Socket => { crate::dispatch::fold(this.client_mut().close(uws::CloseCode::FastShutdown)) } - DeferredClose::WithoutSocket => { + DeferredClose::WithoutSocket { reason, terminal } => { // Holding Connecting (see `close_without_socket_next_tick`) // and the gate in `reconnect()` keep every dial entry out. debug_assert!(this.client.get().socket.is_closed()); // No socket ref to give back: `connect()` forgets it only once // it has a socket, and this task exists because it never did. this.client_mut().status = valkey::Status::Disconnected; - let closed = this.client_mut().on_close(); + let closed = this.client_mut().on_close(valkey::CloseReason::DialFailed { + message: reason, + terminal: *terminal, + }); this.update_poll_ref(); crate::dispatch::fold(closed); } @@ -2071,7 +2138,7 @@ impl bun_event_loop::Taskable for ValkeyDeferredClose { DeferredClose::Socket => task.run(), // The VM is going away: `on_close()` would run `onclose`, so only // give back what `close_without_socket_next_tick` took. - DeferredClose::WithoutSocket => { + DeferredClose::WithoutSocket { .. } => { // SAFETY: as in `run`. let _enqueue_ref = unsafe { RefPtr::from_raw(task.ctx) }; // SAFETY: live per the ref above. diff --git a/src/runtime/valkey_jsc/valkey.rs b/src/runtime/valkey_jsc/valkey.rs index 6a8875b5e12a..75cfe5b59632 100644 --- a/src/runtime/valkey_jsc/valkey.rs +++ b/src/runtime/valkey_jsc/valkey.rs @@ -30,6 +30,11 @@ bun_output::define_scoped_log!(debug, Redis, visible); /// Connection flags to track Valkey client state pub struct ConnectionFlags { pub(crate) is_manually_closed: bool, + /// Set by `disconnect()` while a dial is in flight and taken by that + /// dial's `on_close`: uSockets reports the aborted dial as a connect + /// error (`ECONNABORTED`), and the user asked for that close. A + /// `connect()` before that `on_close` clears it with `is_manually_closed`. + pub(crate) close_aborted_dial: bool, pub(crate) is_selecting_db_internal: bool, pub(crate) enable_offline_queue: bool, pub(crate) enable_auto_reconnect: bool, @@ -37,11 +42,6 @@ pub struct ConnectionFlags { /// or `fail()`, so it overlaps `Disconnected` and `Connecting`; that is why /// it is not a `Status` variant. pub(crate) is_reconnecting: bool, - /// Sticky until `on_open`/`connect()`. `fail()` closes the socket outright - /// (see `close()`), so by the time it returns the close callback has run - /// (`on_close` reads this to skip the retry policy) and this overlaps - /// `Disconnected`. - pub(crate) failed: bool, pub(crate) enable_auto_pipelining: bool, pub(crate) finalized: bool, // This flag is a slight hack to allow returning the client instance in the @@ -60,11 +60,11 @@ impl Default for ConnectionFlags { fn default() -> Self { Self { is_manually_closed: false, + close_aborted_dial: false, is_selecting_db_internal: false, enable_offline_queue: true, enable_auto_reconnect: true, is_reconnecting: false, - failed: false, enable_auto_pipelining: true, finalized: false, connection_promise_returns_client: false, @@ -197,7 +197,7 @@ impl Address { group: &mut SocketGroup, ssl_ctx: Option<*mut SslCtx>, is_tls: bool, - ) -> Result { + ) -> Result { if is_tls { let kind = SocketKind::ValkeyTls; let sock = match self { @@ -236,6 +236,34 @@ impl Address { } } +/// Why `on_close` runs. Its message rejects the commands the close leaves +/// unanswered, and is the failure the connect() promise and `onclose` get +/// unless `fail()` recorded one first or the retries are used up. +#[derive(Clone, Copy)] +pub(crate) enum CloseReason<'a> { + /// The socket of a connection went away: closed by the peer, `close()` + /// or `fail()`. + SocketClosed, + /// The dial never produced a connection; `message` is the errno/resolver + /// text, e.g. `connect ECONNREFUSED 127.0.0.1:6379`. A `terminal` dial is + /// one no retry can make succeed (the TLS context cannot be built), so + /// the retry policy is skipped whatever `autoReconnect` says. + DialFailed { message: &'a [u8], terminal: bool }, +} + +impl<'a> CloseReason<'a> { + pub(crate) fn message(self) -> &'a [u8] { + match self { + Self::SocketClosed => b"Connection closed", + Self::DialFailed { message, .. } => message, + } + } + + fn is_terminal(self) -> bool { + matches!(self, Self::DialFailed { terminal: true, .. }) + } +} + /// Core Valkey client implementation pub struct ValkeyClient { pub(crate) socket: AnySocket, @@ -275,6 +303,21 @@ pub struct ValkeyClient { pub(crate) flags: ConnectionFlags, + /// The error of the failure that closed this connection, `Some` from + /// `fail_with_js_value` until the next `connect()`/`on_open`. It is the + /// one value the rejected commands, the connect() promise and `onclose` + /// all get. `fail()` closes the socket outright (see `close()`), so by the + /// time it returns the close callback has run (`on_close` reads this to + /// skip the retry policy) and this overlaps `Disconnected`. + /// + /// A `Strong` because the value has to live from `fail_with_js_value` + /// through the socket close dispatch to `on_valkey_close`, a chain that + /// allocates and can collect, while it may have no other referent (no + /// command was queued) and a `JSValue` in this boxed client is not + /// scanned. Dropped with the client; cleared on the next dial so a + /// client that failed once does not root its error for good. + pub(crate) failure: Option, + // Auto-pipelining pub(crate) auto_flusher: AutoFlusher, @@ -438,7 +481,7 @@ impl ValkeyClient { /// Get the appropriate timeout interval based on connection state pub(crate) fn get_timeout_interval(&self) -> u32 { - if self.flags.failed { + if self.failure.is_some() { return 0; } match self.status { @@ -548,7 +591,7 @@ impl ValkeyClient { /// Mark the connection as failed with error message pub(crate) fn fail(&mut self, message: &[u8], err: RedisError) -> JsResult<()> { debug!("failed: {}: {:?}", bstr::BStr::new(message), err); - if self.flags.failed { + if self.failure.is_some() { return Ok(()); } @@ -581,10 +624,10 @@ impl ValkeyClient { global_this: &JSGlobalObject, jsvalue: JSValue, ) -> JsResult<()> { - if self.flags.failed { + if self.failure.is_some() { return Ok(()); } - self.flags.failed = true; + self.failure = Some(bun_jsc::Strong::create(jsvalue, global_this)); self.flags.is_reconnecting = false; let val = Self::reject_all_pending_commands( &mut self.in_flight, @@ -595,7 +638,7 @@ impl ValkeyClient { // A failure the client detected itself (idle timeout, protocol or // handshake error) has always been a deliberate close; `on_close` reads - // `failed` and skips the retry policy. + // `failure` and skips the retry policy. let closed = self.close(uws::CloseCode::Failure); // unconditionally, whatever `val` is val.and(closed) } @@ -655,12 +698,12 @@ impl ValkeyClient { // client outlives this scope. let _socket_ref = unsafe { RefPtr::from_raw(self.parent_ptr()) }; self.status = Status::Disconnected; - let closed = self.on_close(); + let closed = self.on_close(CloseReason::SocketClosed); thrown.and(closed) } /// Handle connection closed event - pub fn on_close(&mut self) -> JsResult<()> { + pub(crate) fn on_close(&mut self, reason: CloseReason<'_>) -> JsResult<()> { self.unregister_auto_flusher(); self.write_buffer.clear_and_free(); // A partial reply can never complete now; left in place it counts as @@ -668,10 +711,19 @@ impl ValkeyClient { self.read_buffer.clear_and_free(); self.reply_scanner.reset(); - // A manual close or a failure the client detected itself: no retry. - if self.flags.is_manually_closed || self.flags.failed { + // A dial `close()` aborted did not fail; see `close_aborted_dial`. + let message = if core::mem::take(&mut self.flags.close_aborted_dial) { + CloseReason::SocketClosed.message() + } else { + reason.message() + }; + + // A manual close, a failure the client detected itself or a dial no + // retry can fix: no retry. After `fail()` this `fail` is a no-op and + // `on_valkey_close` reports the recorded failure. + if self.flags.is_manually_closed || self.failure.is_some() || reason.is_terminal() { debug!("skip reconnecting since the connection is manually closed or failed"); - self.fail(b"Connection closed", RedisError::ConnectionClosed)?; + self.fail(message, RedisError::ConnectionClosed)?; self.on_valkey_close()?; return Ok(()); } @@ -679,7 +731,7 @@ impl ValkeyClient { // If auto reconnect is disabled, just fail if !self.flags.enable_auto_reconnect { debug!("skip reconnecting since auto reconnect is disabled"); - self.fail(b"Connection closed", RedisError::ConnectionClosed)?; + self.fail(message, RedisError::ConnectionClosed)?; self.on_valkey_close()?; return Ok(()); } @@ -690,10 +742,23 @@ impl ValkeyClient { if delay_ms == 0 || self.retry_attempts > self.max_retries { debug!("Max retries reached or retry strategy returned 0, giving up reconnection"); - self.fail( - b"Max reconnection attempts reached", - RedisError::ConnectionClosed, - )?; + // Giving up is the outcome, so it is the message; the last attempt's + // reason, the only one anybody could still ask about, is its `cause`. + const GAVE_UP: &[u8] = b"Max reconnection attempts reached"; + if self.flags.finalized { + // `fail()` cannot make JS values here and defers the rejections. + self.fail(GAVE_UP, RedisError::ConnectionClosed)?; + } else { + let global_this = self.global_object(); + let err = valkey_error_to_js(&global_this, GAVE_UP, RedisError::ConnectionClosed); + // Non-enumerable, as `new Error(message, { cause })` makes it. + err.put_non_enumerable( + &global_this, + b"cause", + valkey_error_to_js(&global_this, message, RedisError::ConnectionClosed), + ); + self.fail_with_js_value(&global_this, err)?; + } self.on_valkey_close()?; return Ok(()); } @@ -706,7 +771,7 @@ impl ValkeyClient { self.flags.is_reconnecting = true; self.flags.is_selecting_db_internal = false; - self.reject_in_flight_commands(b"Connection closed", RedisError::ConnectionClosed)?; + self.reject_in_flight_commands(message, RedisError::ConnectionClosed)?; // Signal reconnect timer should be started self.on_valkey_reconnect(); @@ -1298,7 +1363,7 @@ impl ValkeyClient { // A fresh socket has opened, so reset per-connection state. Without // this, `send()` would permanently reject with "Connection has failed" // after a previous connection exhausted retries (#29925). - self.flags.failed = false; + self.failure = None; self.flags.is_selecting_db_internal = false; if matches!(self.socket, AnySocket::SocketTcp(_)) { // if is tcp, we need to start the connection process @@ -1473,7 +1538,7 @@ impl ValkeyClient { /// Why `send()` would reject a command outright instead of sending or /// queueing it in the current state, or `None` when it would be accepted. pub(crate) fn send_rejection(&self) -> Option<&'static str> { - if self.flags.failed { + if self.failure.is_some() { return Some("Connection has failed"); } if self.status != Status::Connected && !self.flags.enable_offline_queue { @@ -1498,6 +1563,9 @@ impl ValkeyClient { pub(crate) fn disconnect(&mut self) -> JsResult<()> { self.flags.is_manually_closed = true; self.unregister_auto_flusher(); + if self.status == Status::Connecting { + self.flags.close_aborted_dial = true; + } match self.status { Status::Connected | Status::Connecting => self.close(uws::CloseCode::FastShutdown), // Between retries: the manual flag makes the close terminal. diff --git a/test/js/valkey/reliability/connection-failures.test.ts b/test/js/valkey/reliability/connection-failures.test.ts index c9f70240d8a8..f811f7489aa8 100644 --- a/test/js/valkey/reliability/connection-failures.test.ts +++ b/test/js/valkey/reliability/connection-failures.test.ts @@ -3,7 +3,7 @@ import { estimateShallowMemoryUsageOf } from "bun:jsc"; import { describe, expect, mock, test } from "bun:test"; import { once } from "events"; import { existsSync, readFileSync, writeFileSync } from "fs"; -import { bunEnv, bunExe, isASAN, isDebug, isWindows, nodeExe, tempDir, tls as tlsCert } from "harness"; +import { bunEnv, bunExe, isASAN, isDebug, isIPv6, isWindows, nodeExe, tempDir, tls as tlsCert } from "harness"; import net from "net"; import path from "path"; import tls from "tls"; @@ -34,7 +34,7 @@ describe.skipIf(!isEnabled)("Valkey: Connection Failures", () => { expect(false).toBe(true); // Should not reach here } catch (error) { // Expect an error with connection closed message - expect(error.message).toMatch(/connection closed|socket closed|failed to connect/i); + expect(error.message).toMatch(/connection closed|socket closed|failed to connect|connect E[A-Z]+/i); } finally { // Cleanup await client.close(); @@ -58,7 +58,9 @@ describe.skipIf(!isEnabled)("Valkey: Connection Failures", () => { expect(false).toBe(true); // Should not reach here } catch (error) { // Should fail with connection error - expect(error.message).toMatch(/connection closed|socket closed|failed to connect|offline queue is disabled/i); + expect(error.message).toMatch( + /connection closed|socket closed|failed to connect|connect E[A-Z]+|offline queue is disabled/i, + ); } try { @@ -66,7 +68,9 @@ describe.skipIf(!isEnabled)("Valkey: Connection Failures", () => { expect(false).toBe(true); // Should not reach here } catch (error) { // Should fail with connection error - expect(error.message).toMatch(/connection closed|socket closed|failed to connect|offline queue is disabled/i); + expect(error.message).toMatch( + /connection closed|socket closed|failed to connect|connect E[A-Z]+|offline queue is disabled/i, + ); } try { @@ -74,7 +78,9 @@ describe.skipIf(!isEnabled)("Valkey: Connection Failures", () => { expect(false).toBe(true); // Should not reach here } catch (error) { // Should fail with connection error - expect(error.message).toMatch(/connection closed|socket closed|failed to connect|offline queue is disabled/i); + expect(error.message).toMatch( + /connection closed|socket closed|failed to connect|connect E[A-Z]+|offline queue is disabled/i, + ); } try { @@ -82,7 +88,9 @@ describe.skipIf(!isEnabled)("Valkey: Connection Failures", () => { expect(false).toBe(true); // Should not reach here } catch (error) { // Should fail with connection error - expect(error.message).toMatch(/connection closed|socket closed|failed to connect|offline queue is disabled/i); + expect(error.message).toMatch( + /connection closed|socket closed|failed to connect|connect E[A-Z]+|offline queue is disabled/i, + ); } }); @@ -140,7 +148,7 @@ describe.skipIf(!isEnabled)("Valkey: Connection Failures", () => { expect(false).toBe(true); // Should not reach here } catch (error) { // Should fail with a connection error - expect(error.message).toMatch(/connection closed|socket closed|failed to connect/i); + expect(error.message).toMatch(/connection closed|socket closed|failed to connect|connect E[A-Z]+/i); } await client.close(); @@ -283,9 +291,11 @@ describe.skipIf(!isEnabled)("Valkey: Connection Failures", () => { await client.close(); expect(client.connected).toBe(false); + // close() on a client that never dialed is a no-op; the command dials + // once and gets that dial's errno. expect(async () => { await client.get("any-key"); - }).toThrowErrorMatchingInlineSnapshot(`"Connection closed"`); + }).toThrow("connect ECONNREFUSED localhost:12345"); // Multiple disconnects should not cause issues await client.close(); await client.close(); @@ -328,7 +338,7 @@ describe.skipIf(!isEnabled)("Valkey: Connection Failures", () => { const promises = clients.map(client => client.get("key").catch(err => { // We expect errors, but want to make sure they're the right kind - expect(err.message).toMatch(/connection closed|socket closed|failed to connect/i); + expect(err.message).toMatch(/connection closed|socket closed|failed to connect|connect E[A-Z]+/i); }), ); @@ -343,6 +353,325 @@ describe.skipIf(!isEnabled)("Valkey: Connection Failures", () => { }); }); +describe("Valkey: connect() error identity", () => { + // One failure, one error object: the commands queued behind the dial, the + // connect() promise and onclose all get it. Before, connect() and onclose + // got ERR_REDIS_CONNECTION_CLOSED "Connection closed" whatever the cause. + const CRLF = "\r\n"; + + async function stubServer(helloReply: string | null) { + const server = net.createServer(sock => { + let received = ""; + let replied = false; + sock.on("error", () => {}); + sock.on("data", d => { + if (replied || helloReply === null) return; + received += d.toString().toUpperCase(); + if (received.includes("HELLO") && received.endsWith(CRLF)) { + replied = true; + sock.write(helloReply); + } + }); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as net.AddressInfo; + return { port, close: () => server.close() }; + } + + async function closedPort() { + const listener = net.createServer(); + await new Promise(resolve => listener.listen(0, "127.0.0.1", resolve)); + const { port } = listener.address() as net.AddressInfo; + await new Promise(resolve => listener.close(() => resolve())); + return port; + } + + // `redis+unix://` takes the path from the URL's pathname. A Windows path + // cannot be spelled that way: `redis+unix:///C:/dir/r.sock` reaches + // connect(2) as `/C:/dir/r.sock`, which Winsock rejects with EINVAL. + function missingUnixSocket(dir: string) { + const socketPath = path.join(dir, "missing.sock"); + return { url: `redis+unix://${socketPath}`, seen: socketPath }; + } + + // Dials with a GET queued behind connect() and returns the error connect() + // rejected with, after checking the GET and onclose got the same object. + async function failure(url: string, options: any) { + const client = new RedisClient(url, options); + const closed = Promise.withResolvers(); + let closes = 0; + client.onclose = err => { + closes++; + closed.resolve(err); + }; + try { + const get = client.get("k").then( + () => "", + e => e, + ); + const err = await client.connect().then( + () => "", + e => e, + ); + expect(err).toBeInstanceOf(Error); + expect(await get).toBe(err); + expect(await closed.promise).toBe(err); + expect(closes).toBe(1); + if (!("cause" in err)) return { code: err.code, message: err.message }; + // The same shape as `new Error(message, { cause })`. + expect(Object.getOwnPropertyDescriptor(err, "cause")!.enumerable).toBe(false); + return { code: err.code, message: err.message, cause: err.cause.message }; + } finally { + client.close(); + } + } + + test("-WRONGPASS reply to HELLO rejects connect() with the server's error text", async () => { + const srv = await stubServer(`-WRONGPASS invalid username-password pair or user is disabled.${CRLF}`); + try { + expect(await failure(`redis://:bad@127.0.0.1:${srv.port}`, { autoReconnect: false })).toEqual({ + code: "ERR_REDIS_AUTHENTICATION_FAILED", + message: "WRONGPASS invalid username-password pair or user is disabled.", + }); + } finally { + srv.close(); + } + }); + + test("-NOAUTH reply to HELLO rejects connect() with the server's error text", async () => { + const srv = await stubServer(`-NOAUTH HELLO must be called with the client already authenticated${CRLF}`); + try { + expect(await failure(`redis://127.0.0.1:${srv.port}`, { autoReconnect: false })).toEqual({ + code: "ERR_REDIS_AUTHENTICATION_FAILED", + message: "NOAUTH HELLO must be called with the client already authenticated", + }); + } finally { + srv.close(); + } + }); + + test("connectionTimeout expiry rejects connect() with ERR_REDIS_CONNECTION_TIMEOUT", async () => { + const srv = await stubServer(null); + try { + expect(await failure(`redis://127.0.0.1:${srv.port}`, { autoReconnect: false, connectionTimeout: 200 })).toEqual({ + code: "ERR_REDIS_CONNECTION_TIMEOUT", + message: "Connection timeout reached after 200ms", + }); + } finally { + srv.close(); + } + }); + + test("a refused TCP connect rejects connect() with the errno", async () => { + const port = await closedPort(); + expect(await failure(`redis://127.0.0.1:${port}`, { autoReconnect: false, connectionTimeout: 2000 })).toEqual({ + code: "ERR_REDIS_CONNECTION_CLOSED", + message: `connect ECONNREFUSED 127.0.0.1:${port}`, + }); + }); + + test.skipIf(isWindows)("a unix socket path that does not exist rejects connect() with ENOENT", async () => { + using dir = tempDir("valkey-unix", {}); + const { url, seen } = missingUnixSocket(String(dir)); + // Fails inside the dial itself, before uSockets has a socket to report on. + expect(await failure(url, { autoReconnect: false })).toEqual({ + code: "ERR_REDIS_CONNECTION_CLOSED", + message: `connect ENOENT ${seen}`, + }); + }); + + test("a hostname that does not resolve rejects connect() with the resolver error", async () => { + // A 64 byte DNS label is illegal (RFC 1035 section 2.3.4), so the lookup + // fails locally without a query leaving the machine. + const host = Buffer.alloc(64, "a").toString() + ".com"; + expect(await failure(`redis://${host}:6379`, { autoReconnect: false })).toEqual({ + code: "ERR_REDIS_CONNECTION_CLOSED", + message: `getaddrinfo ENOTFOUND ${host}`, + }); + }); + + test("a certificate the client does not trust rejects connect() with the verify error", async () => { + const server = tls.createServer({ key: tlsCert.key, cert: tlsCert.cert }, socket => { + socket.on("error", () => {}); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as net.AddressInfo; + try { + // No `ca`, so the harness cert is self-signed as far as the client knows. + const err = await failure(`rediss://localhost:${port}`, { + autoReconnect: false, + tls: { rejectUnauthorized: true }, + }); + expect(err.code).toBe("DEPTH_ZERO_SELF_SIGNED_CERT"); + expect(err.message).toContain("self signed certificate"); + } finally { + server.close(); + } + }); + + // Giving up is the outcome, so the terminal message replaces the last + // attempt's own reason, whether that attempt failed inside the dial (a + // missing unix socket path) or from the event loop (a refused port); that + // reason is kept as the error's cause. + test("exhausted retries report the terminal reason with the last refused dial's as cause", async () => { + const port = await closedPort(); + expect(await failure(`redis://127.0.0.1:${port}`, { autoReconnect: true, maxRetries: 1 })).toEqual({ + code: "ERR_REDIS_CONNECTION_CLOSED", + message: "Max reconnection attempts reached", + cause: `connect ECONNREFUSED 127.0.0.1:${port}`, + }); + }); + + test.skipIf(isWindows)( + "exhausted retries report the terminal reason with the last failed dial's as cause", + async () => { + using dir = tempDir("valkey-unix", {}); + const { url, seen } = missingUnixSocket(String(dir)); + expect(await failure(url, { autoReconnect: true, maxRetries: 1 })).toEqual({ + code: "ERR_REDIS_CONNECTION_CLOSED", + message: "Max reconnection attempts reached", + cause: `connect ENOENT ${seen}`, + }); + }, + ); + + test.skipIf(isWindows)( + "a connect() that follows a close() in the tick of a failed first dial reports the dial's errno", + async () => { + using dir = tempDir("valkey-unix", {}); + const { url, seen } = missingUnixSocket(String(dir)); + const client = new RedisClient(url, { autoReconnect: false }); + const closed = Promise.withResolvers(); + let closes = 0; + client.onclose = err => { + closes++; + closed.resolve(err); + }; + try { + // The command's dial fails inside connect() and its close is deferred. + // close() marks that dial as aborted by the user; the connect() in the + // same tick takes the close back, so the dial's own outcome is what + // the deferred close reports. + const get = client.get("k").then( + () => "", + e => e, + ); + client.close(); + const err = await client.connect().then( + () => "", + e => e, + ); + expect(err).toMatchObject({ code: "ERR_REDIS_CONNECTION_CLOSED", message: `connect ENOENT ${seen}` }); + expect(await get).toBe(err); + expect(await closed.promise).toBe(err); + expect(closes).toBe(1); + } finally { + client.close(); + } + }, + ); + + test("a connect() after an authentication failure gets its own outcome", async () => { + let helloReply = `-WRONGPASS invalid username-password pair or user is disabled.${CRLF}`; + const server = net.createServer(sock => { + sock.on("error", () => {}); + sock.on("data", () => sock.write(helloReply)); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as net.AddressInfo; + const client = new RedisClient(`redis://:bad@127.0.0.1:${port}`, { autoReconnect: false }); + try { + const rejection = (p: Promise) => + p.then( + () => "", + e => e, + ); + const first = await rejection(client.connect()); + const second = await rejection(client.connect()); + expect(second).toMatchObject({ code: "ERR_REDIS_AUTHENTICATION_FAILED" }); + // The recorded failure is cleared by the dial; the second attempt's + // rejection is its own, not the first one's replayed. + expect(second).not.toBe(first); + helloReply = `+OK${CRLF}`; + await client.connect(); + expect(client.connected).toBe(true); + } finally { + client.close(); + server.close(); + } + }); + + test.skipIf(!isIPv6())("a refused IPv6 literal is reported without its URL brackets", async () => { + const listener = net.createServer(); + await new Promise(resolve => listener.listen(0, "::1", resolve)); + const { port } = listener.address() as net.AddressInfo; + await new Promise(resolve => listener.close(() => resolve())); + expect(await failure(`redis://[::1]:${port}`, { autoReconnect: false })).toEqual({ + code: "ERR_REDIS_CONNECTION_CLOSED", + message: `connect ECONNREFUSED ::1:${port}`, + }); + }); + + test("a TLS context that cannot be built is terminal even with autoReconnect on", async () => { + // Neither key nor cert parses, so no attempt gets as far as a socket, and + // no retry could do better: one onclose, whatever autoReconnect says. + expect(await failure("rediss://127.0.0.1:1", { tls: { key: "not a key", cert: "not a cert" } })).toEqual({ + code: "ERR_REDIS_CONNECTION_CLOSED", + message: "Failed to create TLS context", + }); + }); + + // close() while the dial is pending. A hostname in a fresh process is + // resolved from the event loop, so its dial is a connecting socket that + // uSockets aborts with a connect error (ECONNABORTED); a literal IP is a + // half-open socket the client closes by hand. Both are the user's close. + test.each([ + ["a hostname", "localhost"], + ["a literal IP", "127.0.0.1"], + ])("close() during a dial to %s reports the close, not a connect error", async (_kind, host) => { + const srv = await stubServer(`+OK${CRLF}`); + try { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const client = new Bun.RedisClient("redis://${host}:${srv.port}", { autoReconnect: false }); + let closes = 0; + const closed = Promise.withResolvers(); + client.onclose = err => { closes++; closed.resolve(err); }; + const get = client.get("k").then(() => "", e => e); + const connect = client.connect().then(() => "", e => e); + client.close(); + const err = await connect; + console.log(JSON.stringify({ + code: err.code, message: err.message, closes, + sameForGet: (await get) === err, sameForOnclose: (await closed.promise) === err, + })); + `, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ stdout: stdout.trim(), stderr, exitCode }).toEqual({ + stdout: JSON.stringify({ + code: "ERR_REDIS_CONNECTION_CLOSED", + message: "Connection closed", + closes: 1, + sameForGet: true, + sameForOnclose: true, + }), + stderr: "", + exitCode: 0, + }); + } finally { + srv.close(); + } + }); +}); + // Takes the complete RESP commands off the front of `state.buffer` and leaves // any partial command in it for the next chunk. function readCommands(state: { buffer: Buffer }): string[][] { @@ -642,7 +971,7 @@ describe("Valkey: Recovering After fail()", () => { inFlight: await inFlight, connections: fake.connections, }).toEqual({ - onclose: "ERR_REDIS_CONNECTION_CLOSED", + onclose: "ERR_REDIS_IDLE_TIMEOUT", connectedInsideOnclose: false, connectedAfter: false, inFlight: "ERR_REDIS_IDLE_TIMEOUT", @@ -676,7 +1005,7 @@ describe("Valkey: Recovering After fail()", () => { client.onclose = err => closed.resolve(err); await client.connect(); expect(client.connected).toBe(true); - expect(await closed.promise).toMatchObject({ code: "ERR_REDIS_CONNECTION_CLOSED" }); + expect(await closed.promise).toMatchObject({ code: "ERR_REDIS_IDLE_TIMEOUT" }); expect(client.connected).toBe(false); expect(fake.connections).toBe(connection); } @@ -717,6 +1046,105 @@ describe("Valkey: Recovering After fail()", () => { } }); + test("the peer dropping an established connection reports the close to onclose and the in-flight command", async () => { + // PING is left unanswered and the socket is dropped instead. + const fake = helloServer({ + PING: (_, socket) => { + socket.destroy(); + return null; + }, + }); + const port = await fake.listen(); + const client = new RedisClient(`redis://127.0.0.1:${port}`, { autoReconnect: false }); + try { + const closed = Promise.withResolvers(); + client.onclose = err => closed.resolve(err); + await client.connect(); + const err = await client.ping().then( + () => "", + e => e, + ); + expect(err).toMatchObject({ code: "ERR_REDIS_CONNECTION_CLOSED", message: "Connection closed" }); + expect(await closed.promise).toBe(err); + } finally { + client.close(); + fake.server.close(); + } + }); + + test("close() on a connected client reports the close to onclose and the in-flight command", async () => { + const fake = helloServer({ PING: () => null }); + const port = await fake.listen(); + const client = new RedisClient(`redis://127.0.0.1:${port}`); + try { + const closed = Promise.withResolvers(); + client.onclose = err => closed.resolve(err); + await client.connect(); + const ping = client.ping().then( + () => "", + e => e, + ); + client.close(); + const err = await ping; + expect(err).toMatchObject({ code: "ERR_REDIS_CONNECTION_CLOSED", message: "Connection closed" }); + expect(await closed.promise).toBe(err); + } finally { + client.close(); + fake.server.close(); + } + }); + + test("a TLS context that could not be built does not turn off autoReconnect for later connections", async () => { + // Connection 1 is dropped by the server right after it answers PING. + const fake = helloServer( + { + PING: (connection, socket) => { + if (connection === 1) { + socket.end("+PONG\r\n"); + return null; + } + return "+PONG\r\n"; + }, + }, + { secure: true }, + ); + const port = await fake.listen(); + // The files exist, so the constructor accepts them; their content is read + // when a connection is dialed, and neither parses. + using dir = tempDir("valkey-tls", { "key.pem": "not a key", "cert.pem": "not a cert" }); + const client = new RedisClient(`rediss://127.0.0.1:${port}`, { + tls: { + ca: tlsCert.cert, + keyFile: path.join(String(dir), "key.pem"), + certFile: path.join(String(dir), "cert.pem"), + }, + autoReconnect: true, + }); + try { + let closes = 0; + client.onclose = () => closes++; + await expect(client.connect()).rejects.toMatchObject({ code: "ERR_REDIS_CONNECTION_CLOSED" }); + expect({ closes, connections: fake.connections }).toEqual({ closes: 1, connections: 0 }); + + await Bun.write(path.join(String(dir), "key.pem"), tlsCert.key); + await Bun.write(path.join(String(dir), "cert.pem"), tlsCert.cert); + const reconnected = Promise.withResolvers(); + let connects = 0; + client.onconnect = () => { + if (++connects === 2) reconnected.resolve(); + }; + client.onclose = err => reconnected.reject(err); + await client.connect(); + expect(await client.ping()).toBe("PONG"); + await reconnected.promise; + expect(await client.ping()).toBe("PONG"); + expect(fake.connections).toBe(2); + } finally { + client.close(); + fake.server.close(); + } + }); + test("connected reads false inside onclose when the server drops an established connection", async () => { // Connection 1 is dropped by the server right after it answers PING. const fake = helloServer({ @@ -810,8 +1238,11 @@ describe("Valkey: Recovering After fail()", () => { const client = new RedisClient(`redis://127.0.0.1:${port}`, { autoReconnect: false }); try { const secondConnect = connectFromOnclose(client); - await expect(client.connect()).rejects.toMatchObject({ code: "ERR_REDIS_CONNECTION_CLOSED" }); - expect(await secondConnect).toBe("rejected: Connection closed"); + await expect(client.connect()).rejects.toMatchObject({ + code: "ERR_REDIS_CONNECTION_CLOSED", + message: `connect ECONNREFUSED 127.0.0.1:${port}`, + }); + expect(await secondConnect).toBe(`rejected: connect ECONNREFUSED 127.0.0.1:${port}`); } finally { client.close(); } @@ -869,7 +1300,10 @@ describe("Valkey: Recovering After fail()", () => { const client = new RedisClient(`redis://127.0.0.1:${port}/1`, { autoReconnect: false }); try { const secondConnect = connectFromOnclose(client); - await expect(client.connect()).rejects.toMatchObject({ code: "ERR_REDIS_CONNECTION_CLOSED" }); + await expect(client.connect()).rejects.toMatchObject({ + code: "ERR_REDIS_AUTHENTICATION_FAILED", + message: "WRONGPASS invalid password", + }); expect(await secondConnect).toBe("connected"); expect(await client.ping()).toBe("PONG"); expect(fake.connections).toBe(2); @@ -909,7 +1343,7 @@ describe("Valkey: Recovering After fail()", () => { // The rejection is a failure the client detected, so there is no retry // even with autoReconnect on: onclose fires once and the only second // connection is the one dialed from it. - expect(closes).toEqual([{ message: "Connection closed", connected: false, connections: 1 }]); + expect(closes).toEqual([{ message: "ERR DB index is out of range", connected: false, connections: 1 }]); expect(await secondConnect).toBe("connected"); expect(await client.ping()).toBe("PONG"); expect(fake.connections).toBe(2); @@ -1061,9 +1495,12 @@ describe("Valkey: Recovering After fail()", () => { const client = new RedisClient(`rediss://127.0.0.1:${port}`, { autoReconnect: false }); try { const secondConnect = connectFromOnclose(client); - await expect(client.connect()).rejects.toMatchObject({ code: "ERR_REDIS_CONNECTION_CLOSED" }); + // The handshake failure is the TLS error the queued commands are + // rejected with, not the generic close. + const disconnected = "Client network socket disconnected before secure TLS connection was established"; + await expect(client.connect()).rejects.toMatchObject({ code: "ECONNRESET", message: disconnected }); expect({ secondConnect: await secondConnect, handshakes }).toEqual({ - secondConnect: "rejected: Connection closed", + secondConnect: `rejected: ${disconnected}`, handshakes: 2, }); } finally { @@ -1114,19 +1551,31 @@ describe("Valkey: Recovering After fail()", () => { client.close(); await first.close(); let closes = 0; - client.onclose = () => closes++; + const closed = Promise.withResolvers(); + client.onclose = err => { + closes++; + closed.resolve(err); + }; const outcome = client.connect().then( () => "connected", - (err: Error & { code: string }) => err.code, + (err: Error) => err, + ); + const get = client.get("k").then( + () => "resolved", + (err: Error) => err, ); client.close(); await second.listenUnix(socketPath); - expect({ outcome: await outcome, closes, connected: client.connected, redialled: second.connections }).toEqual({ - outcome: "ERR_REDIS_CONNECTION_CLOSED", + const err = await outcome; + // The close is what is reported, not the ENOENT the dial hit. + expect(err).toMatchObject({ code: "ERR_REDIS_CONNECTION_CLOSED", message: "Connection closed" }); + expect({ closes, connected: client.connected, redialled: second.connections }).toEqual({ closes: 1, connected: false, redialled: 0, }); + expect(await get).toBe(err); + expect(await closed.promise).toBe(err); } finally { client.close(); await first.close(); diff --git a/test/js/valkey/valkey-gc.test.ts b/test/js/valkey/valkey-gc.test.ts index 73e0a5762f8c..9b306f3db401 100644 --- a/test/js/valkey/valkey-gc.test.ts +++ b/test/js/valkey/valkey-gc.test.ts @@ -265,8 +265,8 @@ describe.skipIf(!isASAN)("VM teardown with commands owed to a RedisClient leaks // ValkeyClient::close() releases connect()'s keep-alive ref and runs the // close event by hand. One case per entry into that branch: close() while // the dial is pending, and the connection timeout firing during it. The - // command in the offline queue tells the two apart: connect() itself is - // always rejected as connection-closed. The client is created from a + // connect() promise and the command in the offline queue are rejected with + // the same error, which tells the two apart. The client is created from a // macrotask for the same reason as the workers'. function closePendingDial(options: object, body: string, stdout: string) { return expectCleanExit( @@ -308,7 +308,7 @@ describe.skipIf(!isASAN)("VM teardown with commands owed to a RedisClient leaks closePendingDial( { connectionTimeout: 1 }, "", - "ERR_REDIS_CONNECTION_CLOSED ERR_REDIS_CONNECTION_TIMEOUT 1 false", + "ERR_REDIS_CONNECTION_TIMEOUT ERR_REDIS_CONNECTION_TIMEOUT 1 false", ), timeout, ); diff --git a/test/js/valkey/valkey-incremental-scan.test.ts b/test/js/valkey/valkey-incremental-scan.test.ts index 0df4fb497d90..d0f4c4fab463 100644 --- a/test/js/valkey/valkey-incremental-scan.test.ts +++ b/test/js/valkey/valkey-incremental-scan.test.ts @@ -193,13 +193,17 @@ describe.concurrent("Valkey reply decoding", () => { client.onconnect = client.onclose = () => {}; try { // Queued before the handshake finishes, so the rejection carries the - // HELLO error. connect() itself rejects with a generic "Connection closed". + // HELLO error; connect() rejects with the same error object. const queued = client.get("k").then( () => null, e => e, ); - await client.connect().catch(() => {}); + const connected = await client.connect().then( + () => null, + e => e, + ); const err = await queued; + expect(connected).toBe(err); expect(err).toBeInstanceOf(Error); expect(err.code).toBe("ERR_REDIS_AUTHENTICATION_FAILED"); expect(err.message).toBe("NOAUTH nope!");