Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
72 changes: 35 additions & 37 deletions src/runtime/valkey_jsc/valkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -654,53 +654,51 @@ impl ValkeyClient {
}

/// Handle connection closed event
///
/// Always ends in `on_valkey_close()` or `on_valkey_reconnect()`: they release the ref
/// the socket held on the client and arm the retry, so they run even when rejecting the
/// pending commands returns `Err` (a promise cannot be settled once the VM's termination
/// is pending, e.g. a worker stopped while commands were in flight). That `Err` is still
/// the one returned, as in `fail_with_js_value`.
pub fn on_close(&mut self) -> JsResult<()> {
self.unregister_auto_flusher();
self.write_buffer.clear_and_free();

// If manually closing, don't attempt to reconnect
if self.flags.is_manually_closed {
let reason: &[u8] = if self.flags.is_manually_closed {
debug!("skip reconnecting since the connection is manually closed");
self.fail(b"Connection closed", RedisError::ConnectionClosed)?;
self.on_valkey_close()?;
return Ok(());
}

// If auto reconnect is disabled, just fail
if !self.flags.enable_auto_reconnect {
b"Connection closed"
} else if !self.flags.enable_auto_reconnect {
debug!("skip reconnecting since auto reconnect is disabled");
self.fail(b"Connection closed", RedisError::ConnectionClosed)?;
self.on_valkey_close()?;
return Ok(());
}

// Calculate reconnection delay with exponential backoff
self.retry_attempts += 1;
let delay_ms = self.get_reconnect_delay();
b"Connection closed"
} else {
// Calculate reconnection delay with exponential backoff
self.retry_attempts += 1;
let delay_ms = self.get_reconnect_delay();

if delay_ms != 0 && self.retry_attempts <= self.max_retries {
debug!(
"reconnect in {}ms (attempt {}/{})",
delay_ms, self.retry_attempts, self.max_retries
);

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

let rejected = self
.reject_in_flight_commands(b"Connection closed", RedisError::ConnectionClosed);
// Signal reconnect timer should be started, whatever `rejected` is
self.on_valkey_reconnect();
return rejected;
}

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,
)?;
self.on_valkey_close()?;
return Ok(());
}

debug!(
"reconnect in {}ms (attempt {}/{})",
delay_ms, self.retry_attempts, self.max_retries
);

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

self.reject_in_flight_commands(b"Connection closed", RedisError::ConnectionClosed)?;
b"Max reconnection attempts reached"
};

// Signal reconnect timer should be started
self.on_valkey_reconnect();
Ok(())
let failed = self.fail(reason, RedisError::ConnectionClosed);
let closed = self.on_valkey_close(); // unconditionally, whatever `failed` is
failed.and(closed)
}

pub(crate) fn send_next_command(&mut self) {
Expand Down
82 changes: 81 additions & 1 deletion test/js/valkey/valkey-gc.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { expect, test } from "bun:test";
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, isASAN } from "harness";
import net from "node:net";
import { join } from "node:path";

// Fuzzer found a heap-use-after-free: connect()'s tls_ctx_failed branch
// called on_valkey_close() before the socket keep-alive ref was taken, so
Expand Down Expand Up @@ -42,6 +43,85 @@ test.concurrent("RedisClient survives a failed custom-TLS context without freein
expect(exitCode).toBe(0);
});

// The socket's close event (ValkeyClient::on_close) rejects the commands the
// connection still owed replies for, then releases the ref the socket held on
// the client and settles connect()/onclose or arms the retry. Rejecting a
// promise fails once the VM's termination is pending, which is the state a
// terminated worker's teardown closes its sockets in, and on_close() used to
// return at that point, so every RedisClient terminated with commands in flight
// leaked its Box<JSValkeyClient>. One case per branch of on_close(): retry
// scheduled, autoReconnect off, retries exhausted. LSan sees the box only when
// the worker's VM has been torn down, hence the worker; the parent's own VM is
// torn down too (BUN_DESTRUCT_VM_ON_EXIT) so its server socket is not reported.
describe.skipIf(!isASAN)("worker.terminate() with commands in flight does not leak the RedisClient", () => {
async function terminateWorkerWithCommandsInFlight(options: object) {
const src = `
const { Worker } = require("node:worker_threads");
const HELLO = "%1\\r\\n$5\\r\\nproto\\r\\n:3\\r\\n";
// Answers HELLO, then never replies: every command sent stays in flight.
// Resolves once the commands have reached the server, so they are in the
// client's in-flight queue (not merely queued) when the worker is stopped.
const { promise: commandsInFlight, resolve: onCommands } = Promise.withResolvers();
const server = Bun.listen({
hostname: "127.0.0.1",
port: 0,
socket: {
open(s) { s.data = { hello: false }; },
data(s, chunk) {
const text = chunk.toString("latin1");
if (!s.data.hello && text.includes("HELLO")) { s.data.hello = true; s.write(HELLO); }
if (text.includes("INCR")) onCommands();
},
Comment thread
robobun marked this conversation as resolved.
Resolved
close() {},
error() {},
},
});
// The client is created from a macrotask on purpose: allocations made
// while the worker's module body is still on the stack match the
// module-evaluation entries of leaksan.supp, and a leaked client would
// then go unreported.
const worker = new Worker(
\`const { workerData } = require("node:worker_threads");
setImmediate(() => {
const client = new Bun.RedisClient(workerData.url, workerData.options);
globalThis.client = client;
client.connect().then(() => {
for (let i = 0; i < 4; i++) client.incr("k").catch(() => {});
});
});\`,
{ eval: true, workerData: { url: "redis://127.0.0.1:" + server.port, options: ${JSON.stringify(options)} } },
);
worker.on("error", (err) => { console.error(err); process.exit(2); });
worker.on("exit", (code) => { console.error("worker exited on its own with " + code); process.exit(3); });
await commandsInFlight;
worker.removeAllListeners("exit");
console.log("terminated", await worker.terminate());
server.stop(true);
`;

await using proc = Bun.spawn({
cmd: [bunExe(), "-e", src],
env: {
...bunEnv,
BUN_DESTRUCT_VM_ON_EXIT: "1",
ASAN_OPTIONS: [bunEnv.ASAN_OPTIONS, "detect_leaks=1"].filter(Boolean).join(":"),
LSAN_OPTIONS: `print_suppressions=0:suppressions=${join(import.meta.dirname, "../../leaksan.supp")}`,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stdout, stderr, exitCode }).toEqual({ stdout: "terminated 1\n", stderr: "", exitCode: 0 });
}

// Symbolizing a leak report takes LSan several seconds on a debug binary.
const timeout = 60_000;
test.concurrent("retry scheduled", () => terminateWorkerWithCommandsInFlight({}), timeout);
test.concurrent("autoReconnect off", () => terminateWorkerWithCommandsInFlight({ autoReconnect: false }), timeout);
test.concurrent("retries exhausted", () => terminateWorkerWithCommandsInFlight({ maxRetries: 0 }), timeout);
});

// Fuzzer found a heap-use-after-free that survived the ScopedRef refactor:
// on_connection_timeout's unconditional `ScopedRef::adopt` released a ref the
// timer no longer held, so the ScopedRef drop at scope end brought the
Expand Down
Loading