Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 17 additions & 23 deletions src/runtime/valkey_jsc/js_valkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1185,8 +1185,18 @@ impl JSValkeyClient {
.expect("unreachable");
let len = start - cur.len();
let msg = &buf[..len];
// Between reconnect attempts the socket is already detached, so
// `fail()`'s `close()` is a no-op and no close callback will ever
// settle the connection promise or release the poll ref.
let already_detached = self.client.get().socket.is_closed();
let _ = self.client_fail(msg, protocol::RedisError::ConnectionTimeout);
// TODO: properly propagate exception upwards
if already_detached {
// `on_valkey_close()`'s defer runs `update_poll_ref()` and
// releases one ref; balance that release here.
self.ref_();
let _ = self.on_valkey_close();
}
}
}
}
Expand Down Expand Up @@ -1231,16 +1241,13 @@ impl JSValkeyClient {
r.ref_(vm_event_loop_ctx());
});

if let Err(err) = self.connect() {
self.fail_with_js_value(
self.global_object
.err(
jsc::ErrorCode::SOCKET_CLOSED_BEFORE_CONNECTION,
format_args!("{} reconnecting", err.name()),
)
.to_js(),
);
self.poll_ref.with_mut(|r| r.disable());
if self.connect().is_err() {
// Same state machine as an async connect failure (`on_connect_error`):
// retry with backoff, or fail and settle the connection promise.
// `connect()` released its own ref; `on_close()` releases one, so balance.
self.ref_();
let _ = self.client_mut().on_close();
self.update_poll_ref();
return;
}

Expand Down Expand Up @@ -1465,19 +1472,6 @@ impl JSValkeyClient {
narrow_terminated(self.client_mut().fail(message, err))
}

pub fn fail_with_js_value(&self, value: JSValue) {
let Some(this_value) = self.this_value.get().try_get() else {
return;
};
let global_object = self.global_object;
if let Some(on_close) = Js::onclose_get_cached(this_value) {
let _exit = self.vm().enter_event_loop_scope();
if let Err(e) = on_close.call(&global_object, this_value, &[value]) {
global_object.report_active_exception_as_unhandled(e);
}
}
}

fn close_socket_next_tick(&self) {
if self.client.get().socket.is_closed() {
return;
Expand Down
33 changes: 20 additions & 13 deletions src/runtime/valkey_jsc/valkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,10 @@ impl ValkeyClient {
return Ok(());
}
self.flags.failed = true;
// A failed client is terminal until the next explicit `connect()`.
// A stale `is_reconnecting` would keep the event loop referenced via
// `update_poll_ref` and let a pending reconnect timer resurrect it.
self.flags.is_reconnecting = false;
let val = Self::reject_all_pending_commands(
&mut self.in_flight,
&mut self.queue,
Expand Down Expand Up @@ -639,6 +643,12 @@ impl ValkeyClient {
self.unregister_auto_flusher();
self.write_buffer.clear_and_free();

// The socket is gone, so the session can no longer be authenticated.
// Every branch below must observe `connection_ready() == false`, or a
// later `connect()` + `enqueue()` sees a Disconnected-but-"ready" client.
self.flags.is_authenticated = false;
self.flags.is_selecting_db_internal = false;

// If manually closing, don't attempt to reconnect
if self.flags.is_manually_closed {
debug!("skip reconnecting since the connection is manually closed");
Expand Down Expand Up @@ -675,8 +685,6 @@ impl ValkeyClient {
);

self.flags.is_reconnecting = true;
self.flags.is_authenticated = false;
self.flags.is_selecting_db_internal = false;

// Signal reconnect timer should be started
self.on_valkey_reconnect();
Expand Down Expand Up @@ -1344,8 +1352,12 @@ impl ValkeyClient {
&& self.queue.readable_length() > 0;

if
// If there are any pending commands, queue this one
self.queue.readable_length() > 0
// Only an established, authenticated connection may take the
// direct-write path below. `connection_ready()` alone is not enough:
// a disconnected or still-connecting socket must go to the queue.
self.status != Status::Connected
// If there are any pending commands, queue this one
|| self.queue.readable_length() > 0
// With auto pipelining, we can accept commands regardless of in_flight commands
|| (!can_pipeline && self.in_flight.readable_length() > 0)
// We need authentication before processing commands
Expand All @@ -1367,15 +1379,10 @@ impl ValkeyClient {
return Ok(());
}

match self.status {
Status::Connecting | Status::Connected => {
if command.write(self.writer()).is_err() {
let global = self.global_object();
let _ = promise.reject(&global, Ok(global.create_out_of_memory_error()));
return Ok(());
}
}
_ => unreachable!(),
if command.write(self.writer()).is_err() {
let global = self.global_object();
let _ = promise.reject(&global, Ok(global.create_out_of_memory_error()));
return Ok(());
}

let cmd_pair = command::PromisePair {
Expand Down
180 changes: 180 additions & 0 deletions test/js/valkey/valkey-reconnect-failure.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, isWindows, normalizeBunSnapshot, tempDir } from "harness";

// A previously-authenticated client that was closed used to keep
// `is_authenticated` set. If a later connect() then failed synchronously (the
// unix socket is gone, or socket() hits EMFILE), the client ended up
// Disconnected with `failed` cleared but `connection_ready()` still true, and
// the next non-pipelined command fell into `enqueue()`'s `_ => unreachable!()`
// arm and aborted the process.
//
// The fixture uses a unix socket so the reconnect's connect(2) fails
// synchronously (ENOENT) once the socket file is removed.
const FIXTURE = /* ts */ `
import { join } from "node:path";

const mode = process.argv[2];
const sock = join(import.meta.dir, "valkey.sock");

// Minimal RESP mock: +OK to every inbound frame (HELLO handshake + commands).
function listen() {
return Bun.listen({
unix: sock,
socket: {
open() {},
data(s) {
s.write("+OK\\r\\n");
},
error() {},
close() {},
drain() {},
},
});
}

let srv = listen();

const options =
mode === "send"
? { autoReconnect: false }
: mode === "no-pipelining"
? { autoReconnect: false, enableAutoPipelining: false }
: {};

const client = new Bun.RedisClient("redis+unix://" + sock, options);
await client.connect();
await client.set("k", "v");
console.log("connected", client.connected);

client.close();
console.log("closed", client.connected);

// Unlinks the unix socket, so the next connect(2) fails with ENOENT.
srv.stop(true);

const connectPromise = client.connect();

if (mode === "recover") {
// autoReconnect (default) retries with backoff; bring the server back so
// the retry succeeds and the offline queue drains.
srv = listen();
const reply = client.send("INFO", []);
console.log("reply", await reply);
await connectPromise;
console.log("reconnected", client.connected);
srv.stop(true);
} else {
const command = mode === "no-pipelining" ? client.incr("n") : client.send("INFO", []);
const [connectResult, commandResult] = await Promise.allSettled([connectPromise, command]);
console.log("connect", connectResult.status, connectResult.reason?.code);
console.log("command", commandResult.status, commandResult.reason?.code, commandResult.reason?.message);
}
`;

async function runFixture(mode: string) {
using dir = tempDir("valkey-reconn", { "reconnect-fixture.ts": FIXTURE });
await using proc = Bun.spawn({
cmd: [bunExe(), "reconnect-fixture.ts", mode],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
return { stdout: normalizeBunSnapshot(stdout, String(dir)), stderr, exitCode };
}

describe.skipIf(isWindows)("RedisClient after a synchronously failing reconnect", () => {
const rejected = [
"connected true",
"closed false",
"connect rejected ERR_REDIS_CONNECTION_CLOSED",
"command rejected ERR_REDIS_CONNECTION_CLOSED Connection has failed",
].join("\n");

test.concurrent("non-pipelined command rejects instead of aborting the process", async () => {
const { stdout, stderr, exitCode } = await runFixture("send");
expect({ stdout, exitCode }, stderr).toEqual({ stdout: rejected, exitCode: 0 });
});

test.concurrent("enableAutoPipelining: false rejects instead of aborting the process", async () => {
const { stdout, stderr, exitCode } = await runFixture("no-pipelining");
expect({ stdout, exitCode }, stderr).toEqual({ stdout: rejected, exitCode: 0 });
});

test.concurrent("autoReconnect retries with backoff and drains the offline queue", async () => {
const { stdout, stderr, exitCode } = await runFixture("recover");
expect({ stdout, exitCode }, stderr).toEqual({
stdout: ["connected true", "closed false", "reply OK", "reconnected true"].join("\n"),
exitCode: 0,
});
});
});

async function runInline(fixture: string) {
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", fixture],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
return { stdout: normalizeBunSnapshot(stdout), stderr, exitCode, signalCode: proc.signalCode };
}

// After auto-reconnect exhausts maxRetries and the client fails, the stale
// `is_reconnecting` flag used to keep the event loop referenced forever, so
// the process never exited.
test.concurrent("process exits after auto-reconnect exhausts maxRetries", async () => {
const { stdout, stderr, exitCode, signalCode } = await runInline(/* ts */ `
const srv = Bun.listen({
hostname: "127.0.0.1",
port: 0,
socket: {
open() {},
data(s) {
s.write("+OK\\r\\n");
},
error() {},
close() {},
drain() {},
},
});
const client = new Bun.RedisClient("redis://127.0.0.1:" + srv.port, { maxRetries: 1 });
await client.set("k", "v");
console.log("connected", client.connected);
const pending = client.get("k");
srv.stop(true);
const results = await Promise.allSettled([pending, client.get("k")]);
console.log(results.map(r => r.status + " " + r.reason?.code).join("|"));
`);
expect({ stdout, exitCode, signalCode }, stderr).toEqual({
stdout: ["connected true", "rejected ERR_REDIS_CONNECTION_CLOSED|rejected ERR_REDIS_CONNECTION_CLOSED"].join("\n"),
exitCode: 0,
signalCode: null,
});
});

// https://github.com/oven-sh/bun/issues/18895
// When connectionTimeout fired between reconnect attempts the socket was
// already detached, so fail()'s close() was a no-op and no close callback ever
// settled the connect() promise or released the event loop.
test.concurrent("connectionTimeout during a reconnect backoff settles connect() and exits", async () => {
const { stdout, stderr, exitCode, signalCode } = await runInline(/* ts */ `
// Bind and release a port so nothing is listening on it.
const probe = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } });
const port = probe.port;
probe.stop(true);
const client = new Bun.RedisClient("redis://127.0.0.1:" + port, { connectionTimeout: 500 });
const results = await Promise.allSettled([client.connect(), client.get("k")]);
console.log(results.map(r => r.status + " " + r.reason?.code + " " + r.reason?.message).join("|"));
`);
expect({ stdout, exitCode, signalCode }, stderr).toEqual({
stdout: [
"rejected ERR_REDIS_CONNECTION_CLOSED Connection closed",
"rejected ERR_REDIS_CONNECTION_TIMEOUT Connection timeout reached after 500ms",
].join("|"),
exitCode: 0,
signalCode: null,
});
});
Loading