Skip to content
Merged
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ Because ReRu is pre-1.0, minor versions may include breaking changes.

### Added

- Added connection-local `CLIENT REPLY ON|OFF|SKIP` with raw RESP reply
suppression, pipeline and transaction handling, and RESET recovery.

- Added manual two-node Cluster slot migration with persistent ownership,
`CLUSTER SETSLOT`, connection-local `ASKING`, `ASK`/`TRYAGAIN` routing and
acknowledged ReRu-to-ReRu `MIGRATE` with binary values and TTLs.
Expand Down
15 changes: 13 additions & 2 deletions docs/COMPATIBILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ tests; it does not certify complete compatibility with Redis.

| Area | Commands | Current scope |
| --- | --- | --- |
| Connection | `PING`, `ECHO`, `HELLO`, `SELECT`, `RESET`, `CLIENT ID`, `CLIENT SETNAME`, `CLIENT GETNAME`, `CLIENT SETINFO`, `CLIENT INFO` | RESP2 handshake, optional inline authentication/name, database 0 selection, socket metadata and context reset |
| Connection | `PING`, `ECHO`, `HELLO`, `SELECT`, `RESET`, `CLIENT ID`, `CLIENT SETNAME`, `CLIENT GETNAME`, `CLIENT SETINFO`, `CLIENT INFO`, `CLIENT REPLY` | RESP2 handshake, optional inline authentication/name, database 0 selection, socket metadata, reply suppression and context reset |
| Strings/cache | `SET`, `GET`, `INCR`, `GETEX`, `GETDEL`, `MGET`, `MSET`, `MSETNX`, `APPEND`, `STRLEN`, `SETNX`, `SETEX`, `PSETEX`, `GETSET`, `INCRBY`, `INCRBYFLOAT`, `DECR`, `DECRBY`, `GETRANGE`, `SUBSTR`, `SETRANGE`, `LCS` | Binary values; SET NX/XX/GET/EX/PX/EXAT/PXAT/KEEPTTL; GETEX expiry/PERSIST; multi-key access, numeric arithmetic and byte ranges; longest common subsequence with LEN/IDX/MINMATCHLEN/WITHMATCHLEN |
| Lists | `RPUSH`, `LPUSH`, `LPUSHX`, `RPUSHX`, `LRANGE`, `LLEN`, `LINDEX`, `LSET`, `LINSERT`, `LTRIM`, `LREM`, `LPOS`, `LPOP`, `RPOP`, `RPOPLPUSH`, `LMOVE`, `BLPOP`, `BRPOP`, `BLMOVE`, `BRPOPLPUSH`, `LMPOP`, `BLMPOP` | Multiple elements, negative indexes, edits, moves, position search, single/multi-key blocking pops and moves with timeout |
| Streams | `XADD`, `XRANGE`, `XREVRANGE`, `XREAD`, `XLEN`, `XDEL`, `XTRIM`, `XGROUP CREATE`, `XGROUP SETID`, `XGROUP DESTROY`, `XGROUP CREATECONSUMER`, `XGROUP DELCONSUMER`, `XREADGROUP`, `XACK`, `XPENDING`, `XCLAIM`, `XAUTOCLAIM`, `XINFO GROUPS`, `XINFO CONSUMERS`, `XINFO STREAM`, `XSETID` | IDs, ranges, deletion, exact trimming, blocking reads, consumer groups, pending entries, acknowledgement, claiming and diagnostics; XADD NOMKSTREAM/MAXLEN/MINID. XRANGE with COUNT 0 or a negative count returns a null array for an existing stream and an empty array for a missing key; XREAD/XREADGROUP treat COUNT 0 or a negative count as unlimited |
Expand Down Expand Up @@ -551,6 +551,16 @@ name, age, database, default user, RESP version and library metadata. CLIENT LIS
KILL, UNBLOCK, TRACKING, detailed buffer metrics and other client operations
remain pending. Metadata is local to the connection and is never persisted.

`CLIENT REPLY ON|OFF|SKIP` controls command replies per connection. `OFF` and
`SKIP` produce no reply themselves; `ON` replies `+OK`. `SKIP` suppresses the
next command reply, including an error; `ON` can restore replies immediately.
`SKIP` has no effect while replies are `OFF`.
`RESET` restores reply mode while respecting a pending `SKIP`. Subscription
acknowledgements and published messages remain visible in subscribed mode,
matching Redis even when ordinary command replies are disabled.
Within `EXEC`, an embedded reply-mode change can suppress later element bytes
while the declared array length remains unchanged, as observed in Redis 8.10.2.

`SELECT 0` supports clients that explicitly select the default database. Nonzero
databases fail explicitly; multiple logical databases remain unimplemented.
With static Cluster enabled, `SELECT 0` is accepted, other valid database indexes
Expand All @@ -572,7 +582,8 @@ specified behavior; its reference-server comparison remains pending.

References: [HELLO](https://redis.io/docs/latest/commands/hello/),
[RESET](https://redis.io/docs/latest/commands/reset/),
[CLIENT SETINFO](https://redis.io/docs/latest/commands/client-setinfo/).
[CLIENT SETINFO](https://redis.io/docs/latest/commands/client-setinfo/),
[CLIENT REPLY](https://redis.io/docs/latest/commands/client-reply/).

## Authentication

Expand Down
20 changes: 11 additions & 9 deletions src/command_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const COMMANDS: &[&str] = &[
"client|getname",
"client|id",
"client|info",
"client|reply",
"client|setinfo",
"client|setname",
"cluster|keyslot",
Expand Down Expand Up @@ -270,9 +271,10 @@ fn metadata(name: &str) -> Metadata {
"vemb" => -3,
"vadd" => -5,
"vsim" => -4,
"client|setname" | "append" | "setnx" | "getset" | "decrby" | "incrby" | "incrbyfloat"
| "latency|history" | "hget" | "hstrlen" | "sismember" | "zscore" | "rpoplpush"
| "rename" | "renamenx" | "lindex" | "hexists" | "object|encoding" | "object|refcount" => 3,
"client|reply" | "client|setname" | "append" | "setnx" | "getset" | "decrby" | "incrby"
| "incrbyfloat" | "latency|history" | "hget" | "hstrlen" | "sismember" | "zscore"
| "rpoplpush" | "rename" | "renamenx" | "lindex" | "hexists" | "object|encoding"
| "object|refcount" => 3,
"httl" | "hpttl" | "hexpiretime" | "hpexpiretime" | "hpersist" | "hgetex" => -5,
"config|resetstat" => 2,
"client|setinfo" | "hincrby" | "hincrbyfloat" | "hsetnx" | "smove" | "lset" | "lrem"
Expand Down Expand Up @@ -337,12 +339,12 @@ fn metadata(name: &str) -> Metadata {
"command" | "command|count" | "command|info" | "acl" | "acl|whoami" | "auth" | "asking"
| "migrate" | "cluster|setslot" | "cluster" | "cluster|keyslot" | "cluster|shards"
| "cluster|slots" | "bgrewriteaof" | "bgsave" | "client" | "client|getname"
| "client|id" | "client|info" | "client|setinfo" | "client|setname" | "config"
| "config|get" | "config|resetstat" | "config|set" | "discard" | "dbsize" | "echo"
| "exec" | "flushall" | "flushdb" | "hello" | "info" | "keys" | "lastsave" | "multi"
| "object" | "ping" | "pubsub" | "punsubscribe" | "psubscribe" | "publish" | "quit"
| "randomkey" | "reset" | "save" | "scan" | "select" | "subscribe" | "time" | "unwatch"
| "unsubscribe" | "xread" | "xreadgroup" | "latency" | "latency|history"
| "client|id" | "client|info" | "client|reply" | "client|setinfo" | "client|setname"
| "config" | "config|get" | "config|resetstat" | "config|set" | "discard" | "dbsize"
| "echo" | "exec" | "flushall" | "flushdb" | "hello" | "info" | "keys" | "lastsave"
| "multi" | "object" | "ping" | "pubsub" | "punsubscribe" | "psubscribe" | "publish"
| "quit" | "randomkey" | "reset" | "save" | "scan" | "select" | "subscribe" | "time"
| "unwatch" | "unsubscribe" | "xread" | "xreadgroup" | "latency" | "latency|history"
| "latency|latest" | "latency|reset" | "xgroup" | "xinfo" | "lmpop" | "blmpop"
| "zmpop" | "bzmpop" | "sintercard" | "zintercard" | "zdiff" | "zinter" | "zunion" => {
(0, 0, 0)
Expand Down
64 changes: 64 additions & 0 deletions src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ pub struct Session {
peer: SocketAddr,
local: SocketAddr,
created: Instant,
reply_mode: ReplyMode,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ReplyMode {
On,
Off,
Skip,
}

pub fn valid_arity(command: &[Vec<u8>]) -> Option<bool> {
Expand All @@ -27,6 +35,7 @@ pub fn valid_arity(command: &[Vec<u8>]) -> Option<bool> {
Some(b"ID" | b"GETNAME" | b"INFO") => command.len() == 2,
Some(b"SETNAME") => command.len() == 3,
Some(b"SETINFO") => command.len() == 4,
Some(b"REPLY") => command.len() == 3,
_ => false,
},
_ => return None,
Expand All @@ -50,12 +59,49 @@ impl Session {
peer: stream.peer_addr()?,
local: stream.local_addr()?,
created: Instant::now(),
reply_mode: ReplyMode::On,
})
}

pub fn reset(&mut self) {
// The socket ID and library identity survive RESET, as in Redis.
self.name.clear();
self.reply_mode = ReplyMode::On;
}

/// Consume a pending SKIP before dispatch. A valid CLIENT REPLY action can
/// override this decision for its own reply (notably SKIP followed by ON).
pub fn begin_command(&mut self) -> bool {
match self.reply_mode {
ReplyMode::On => true,
ReplyMode::Off => false,
ReplyMode::Skip => {
self.reply_mode = ReplyMode::On;
false
}
}
}

pub fn replies_off(&self) -> bool {
self.reply_mode == ReplyMode::Off
}

pub fn is_reply_action(command: &[Vec<u8>]) -> bool {
command.len() == 3
&& command[0].eq_ignore_ascii_case(b"CLIENT")
&& command[1].eq_ignore_ascii_case(b"REPLY")
&& matches!(
command[2].to_ascii_uppercase().as_slice(),
b"ON" | b"OFF" | b"SKIP"
)
}

pub fn reply_for(&self, is_reply_action: bool, initially_enabled: bool) -> bool {
if is_reply_action {
self.reply_mode == ReplyMode::On
} else {
initially_enabled
}
}

pub fn execute(
Expand All @@ -66,6 +112,14 @@ impl Session {
) -> Option<Vec<u8>> {
let valid = valid_arity(c)?;
if !valid {
if c[0].eq_ignore_ascii_case(b"CLIENT")
&& c.get(1)
.is_some_and(|sub| sub.eq_ignore_ascii_case(b"REPLY"))
{
return Some(protocol::error(
"wrong number of arguments for 'client|reply' command",
));
}
return Some(protocol::error(
"wrong number of arguments or unsupported connection subcommand",
));
Expand Down Expand Up @@ -98,6 +152,16 @@ impl Session {
Some(field) => { field.clone_from(&c[3]); b"+OK\r\n".to_vec() }
}
}
b"REPLY" => match c[2].to_ascii_uppercase().as_slice() {
b"ON" => { self.reply_mode = ReplyMode::On; b"+OK\r\n".to_vec() }
b"OFF" => { self.reply_mode = ReplyMode::Off; b"+OK\r\n".to_vec() }
b"SKIP" => {
// Redis ignores SKIP while replies are OFF.
if self.reply_mode != ReplyMode::Off { self.reply_mode = ReplyMode::Skip; }
b"+OK\r\n".to_vec()
}
_ => protocol::error("syntax error"),
},
b"INFO" => protocol::bulk(format!(
"id={} addr={} laddr={} name={} age={} db=0 user=default resp=2 lib-name={} lib-ver={}\n",
self.id, self.peer, self.local, String::from_utf8_lossy(&self.name),
Expand Down
85 changes: 67 additions & 18 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1795,7 +1795,15 @@ fn validate_queued(command: &[Vec<u8>]) -> Result<(), Vec<u8>> {
if valid {
Ok(())
} else {
let lower = String::from_utf8_lossy(name).to_ascii_lowercase();
let lower = if name.eq_ignore_ascii_case(b"CLIENT")
&& command
.get(1)
.is_some_and(|sub| sub.eq_ignore_ascii_case(b"REPLY"))
{
"client|reply".to_string()
} else {
String::from_utf8_lossy(name).to_ascii_lowercase()
};
Err(protocol::error(&format!(
"wrong number of arguments for '{lower}' command"
)))
Expand Down Expand Up @@ -1829,6 +1837,9 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
if command.is_empty() {
continue;
}
let replies_were_off = session.replies_off();
let reply_enabled = session.begin_command();
let is_reply_action = connection::Session::is_reply_action(&command);
let allow_asking = asking;
let ends_transaction =
command[0].eq_ignore_ascii_case(b"EXEC") || command[0].eq_ignore_ascii_case(b"DISCARD");
Expand All @@ -1843,15 +1854,19 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
&& !command[0].eq_ignore_ascii_case(b"HELLO")
&& !command[0].eq_ignore_ascii_case(b"RESET")
{
subscription.write(b"-NOAUTH Authentication required.\r\n")?;
if reply_enabled {
subscription.write(b"-NOAUTH Authentication required.\r\n")?;
}
continue;
}
if command[0].eq_ignore_ascii_case(b"RESET") {
if command.len() != 1 {
transaction_error |= transaction.is_some();
subscription.write(&protocol::error(
"wrong number of arguments for 'reset' command",
))?;
if reply_enabled {
subscription.write(&protocol::error(
"wrong number of arguments for 'reset' command",
))?;
}
continue;
}
let _gate = store.command_gate.lock().unwrap();
Expand All @@ -1862,7 +1877,9 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
subscription.reset();
session.reset();
authenticated = !store.auth.required();
subscription.write(b"+RESET\r\n")?;
if reply_enabled || replies_were_off {
subscription.write(b"+RESET\r\n")?;
}
continue;
}
if command[0].eq_ignore_ascii_case(b"REPLSYNC") && !store.read_only {
Expand All @@ -1876,7 +1893,9 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
}
if command[0].eq_ignore_ascii_case(b"QUIT") {
// QUIT has arity -1 in Redis: extra arguments are ignored.
subscription.write(b"+OK\r\n")?;
if reply_enabled {
subscription.write(b"+OK\r\n")?;
}
return Ok(());
}
if pubsub::is_subscription_command(&command) && transaction.is_none() {
Expand All @@ -1896,19 +1915,33 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
reply
};
let _gate = store.command_gate.lock().unwrap();
subscription.write(&reply)?;
if reply_enabled {
subscription.write(&reply)?;
}
} else {
let name = String::from_utf8_lossy(&command[0]).to_ascii_lowercase();
let name = if command[0].eq_ignore_ascii_case(b"CLIENT")
&& command
.get(1)
.is_some_and(|sub| sub.eq_ignore_ascii_case(b"REPLY"))
{
"client|reply".to_string()
} else {
String::from_utf8_lossy(&command[0]).to_ascii_lowercase()
};
let reason = format!(
"Can't execute '{name}': only (P|S)SUBSCRIBE / (P|S)UNSUBSCRIBE / PING / QUIT / RESET are allowed in this context"
);
if name == "exec" {
subscription.write(
format!("-EXECABORT Transaction discarded because of: {reason}\r\n")
.as_bytes(),
)?;
if reply_enabled {
subscription.write(
format!("-EXECABORT Transaction discarded because of: {reason}\r\n")
.as_bytes(),
)?;
}
} else {
subscription.write(&protocol::error(&reason))?;
if reply_enabled {
subscription.write(&protocol::error(&reason))?;
}
}
}
continue;
Expand All @@ -1929,6 +1962,7 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
store.latency.start(&command)
};
let mut replied_early = false;
let mut transaction_reply = false;
let mut release_subscriptions = false;
let response = if command[0].eq_ignore_ascii_case(b"AUTH") && transaction.is_none() {
store.auth.authenticate(&command, &mut authenticated)
Expand Down Expand Up @@ -2021,7 +2055,12 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
} else if changed {
b"*-1\r\n".to_vec()
} else {
let mut response = format!("*{}\r\n", queued.len()).into_bytes();
let mut response = if reply_enabled {
format!("*{}\r\n", queued.len()).into_bytes()
} else {
Vec::new()
};
transaction_reply = true;
let writes = queued.iter().any(|command| {
is_mutating(command) || hyperloglog::may_update_cache(command)
});
Expand Down Expand Up @@ -2057,7 +2096,12 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
} else {
execute_checked(&queued_command, &store, false)
};
response.extend(result);
if session.reply_for(
connection::Session::is_reply_action(&queued_command),
!session.replies_off(),
) {
response.extend(result);
}
}
if writes {
if let Err(error) = save_and_publish(&store) {
Expand All @@ -2068,7 +2112,9 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
// Write the reply while the gate is held so a
// delivery cannot overtake it; the budget drops a
// stalled client instead of freezing the server.
subscription.write_transaction(&response)?;
if !response.is_empty() {
subscription.write_transaction(&response)?;
}
replied_early = true;
}
release_subscriptions = holds;
Expand Down Expand Up @@ -2144,7 +2190,10 @@ fn handle_client(mut stream: TcpStream, store: Store) -> io::Result<()> {
asking = false;
}
store.latency.record(latency_started);
if !replied_early {
if !replied_early
&& !response.is_empty()
&& (transaction_reply || session.reply_for(is_reply_action, reply_enabled))
{
subscription.write(&response)?;
}
if release_subscriptions {
Expand Down
Loading
Loading