Skip to content
Open
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ Because ReRu is pre-1.0, minor versions may include breaking changes.

### Added

- Added `MEMORY USAGE key [SAMPLES count]`, which reports ReRu's logical
per-key estimate (key name, value and entry overhead) rather than allocator
memory or process RSS. `SAMPLES` is validated and ignored.

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

Expand Down
15 changes: 14 additions & 1 deletion docs/COMPATIBILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ tests; it does not certify complete compatibility with Redis.
| Bitmaps | `SETBIT`, `GETBIT`, `BITCOUNT`, `BITOP`, `BITPOS`, `BITFIELD`, `BITFIELD_RO` | Bitmaps stored as strings, byte/bit count ranges, AND/OR/XOR/NOT; bitfield GET/SET/INCRBY, signed/unsigned widths, `#` offsets and WRAP/SAT/FAIL overflow modes |
| HyperLogLog | `PFADD`, `PFCOUNT`, `PFMERGE` | Approximate distinct counts, multi-key unions, binary members, Redis dense/sparse interchange, cached cardinality |
| Geospatial | `GEOADD`, `GEOPOS`, `GEOHASH`, `GEODIST`, `GEOSEARCH`, `GEOSEARCHSTORE` | Geo points use sorted-set scores; NX/XX/CH, positions and distances, radius/box search, sort/count, decorated results, and destination storing |
| Keyspace | `TYPE`, `DEL`, `UNLINK`, `EXISTS`, `TOUCH`, `DBSIZE`, `KEYS`, `SCAN`, `RANDOMKEY`, `COPY`, `RENAME`, `RENAMENX`, `TTL`, `PTTL`, `EXPIRE`, `PEXPIRE`, `EXPIREAT`, `PEXPIREAT`, `EXPIRETIME`, `PEXPIRETIME`, `PERSIST`, `OBJECT ENCODING`, `OBJECT REFCOUNT`, `FLUSHDB`, `FLUSHALL` | Multiple keys, glob and type filtered scanning, rename/copy with TTL, relative/absolute expiry conditions with `EXPIRETIME` rounding half up and `PEXPIRETIME` exact for absolute deadlines, advisory encoding labels with Redis 8 thresholds, constant reference counts, whole-database flush |
| Keyspace | `TYPE`, `DEL`, `UNLINK`, `EXISTS`, `TOUCH`, `DBSIZE`, `KEYS`, `SCAN`, `RANDOMKEY`, `COPY`, `RENAME`, `RENAMENX`, `TTL`, `PTTL`, `EXPIRE`, `PEXPIRE`, `EXPIREAT`, `PEXPIREAT`, `EXPIRETIME`, `PEXPIRETIME`, `PERSIST`, `OBJECT ENCODING`, `OBJECT REFCOUNT`, `MEMORY USAGE`, `FLUSHDB`, `FLUSHALL` | Multiple keys, glob and type filtered scanning, rename/copy with TTL, relative/absolute expiry conditions with `EXPIRETIME` rounding half up and `PEXPIRETIME` exact for absolute deadlines, advisory encoding labels with Redis 8 thresholds, constant reference counts, logical per-key memory estimates, whole-database flush |
| Transactions | `MULTI`, `EXEC`, `DISCARD`, `WATCH`, `UNWATCH` | Queuing, atomic execution relative to other commands, runtime errors, optimistic locking |
| Pub/Sub | `PUBLISH`, `SUBSCRIBE`, `UNSUBSCRIBE`, `PSUBSCRIBE`, `PUNSUBSCRIBE`, `PUBSUB` | Binary channels/messages, glob patterns, RESP2 subscribed mode, CHANNELS/NUMSUB/NUMPAT; local process only. Each subscriber has its own output buffer and writer thread; frames are queued whole, a publish never waits for a slow reader or skips a live listener, and a subscriber is dropped only above 32 MiB of buffered output or after staying above 8 MiB for 60 seconds. `UNSUBSCRIBE`/`PUNSUBSCRIBE` without names replies in sorted order where Redis uses hash order |
| Connection close | `QUIT` | Ignores extra arguments, replies OK, and closes the connection |
Expand Down Expand Up @@ -158,6 +158,19 @@ returns to `listpack` when the last deadline is cleared, deleted, or expires.
`OBJECT REFCOUNT` always returns `1` because values are never shared between
keys. `OBJECT FREQ`, `OBJECT IDLETIME`, and `OBJECT HELP` are not implemented.

`MEMORY USAGE key [SAMPLES count]` returns the estimated bytes for one key, or
nil when the key is missing or expired. The number is that key's share of the
logical dataset estimate used for `maxmemory` and `INFO memory`: the key name,
a per-type value estimate, and fixed per-entry overhead. It is **not** Redis
allocator memory or process RSS, and it does not match the number Redis reports
for the same value. `SAMPLES` is accepted but ignored, because the estimate
always covers the whole value; the count must still be a non-negative integer,
and a missing or negative count or any other option returns `ERR syntax error`.
The lookup does not change LRU or LFU state. `MEMORY DOCTOR`, `MEMORY HELP`,
`MEMORY MALLOC-STATS`, `MEMORY PURGE`, and `MEMORY STATS` are not implemented.
Redis documents
[MEMORY USAGE](https://redis.io/docs/latest/commands/memory-usage/).

AOF replay rewrites one key per batch. Collection keys are split by argument
count and a 32 MiB payload budget. String values larger than that budget are
written as a SET followed by APPEND chunks, so a string grown past the 256 MiB
Expand Down
21 changes: 14 additions & 7 deletions src/command_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ const COMMANDS: &[&str] = &[
"lset",
"ltrim",
"lmpop",
"memory|usage",
"mget",
"migrate",
"mset",
Expand Down Expand Up @@ -286,8 +287,8 @@ fn metadata(name: &str) -> Metadata {
"restore" => -4,
"zincrby" => 4,
"client" | "config" | "acl" | "xgroup" | "xinfo" | "cluster" | "latency"
| "latency|reset" | "object" => -2,
"config|get" => -3,
| "latency|reset" | "object" | "memory" => -2,
"config|get" | "memory|usage" => -3,
"config|set" => -4,
"acl|whoami" => 2,
"auth" | "pubsub" | "getex" | "lpop" | "rpop" | "hrandfield" | "spop" | "srandmember"
Expand Down Expand Up @@ -346,9 +347,8 @@ fn metadata(name: &str) -> Metadata {
| "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)
}
| "zmpop" | "bzmpop" | "sintercard" | "zintercard" | "zdiff" | "zinter" | "zunion"
| "memory" => (0, 0, 0),
"copy" | "rename" | "renamenx" | "smove" | "lmove" | "blmove" | "rpoplpush"
| "brpoplpush" | "zrangestore" | "lcs" => (1, 2, 1),
"geosearchstore" => (1, 2, 1),
Expand All @@ -368,7 +368,8 @@ fn metadata(name: &str) -> Metadata {
| "xinfo|consumers"
| "xinfo|stream"
| "object|encoding"
| "object|refcount" => (2, 2, 1),
| "object|refcount"
| "memory|usage" => (2, 2, 1),
_ => (1, 1, 1),
};

Expand Down Expand Up @@ -467,7 +468,10 @@ pub(crate) fn queued_arity(command: &[Vec<u8>]) -> Option<bool> {
/// Commands with dynamic key positions need their own argument parser.
pub(crate) fn key_indices(command: &[Vec<u8>]) -> Option<Vec<usize>> {
let root = String::from_utf8_lossy(command.first()?).to_ascii_lowercase();
let name = if matches!(root.as_str(), "xgroup" | "xinfo" | "cluster" | "object") {
let name = if matches!(
root.as_str(),
"xgroup" | "xinfo" | "cluster" | "object" | "memory"
) {
let subcommand = String::from_utf8_lossy(command.get(1)?).to_ascii_lowercase();
format!("{root}|{subcommand}")
} else {
Expand Down Expand Up @@ -651,6 +655,8 @@ mod tests {
("randomkey", (1, 0, 0, 0)),
("publish", (3, 0, 0, 0)),
("lcs", (-3, 1, 2, 1)),
("memory", (-2, 0, 0, 0)),
("memory|usage", (-3, 2, 2, 1)),
] {
let actual = metadata(name);
assert_eq!(
Expand Down Expand Up @@ -679,6 +685,7 @@ mod tests {
check(&[b"LMPOP", b"2", b"a", b"b", b"LEFT"], &[2, 3]);
check(&[b"ZUNIONSTORE", b"out", b"2", b"a", b"b"], &[1, 3, 4]);
check(&[b"XGROUP", b"CREATE", b"stream", b"group", b"$"], &[2]);
check(&[b"MEMORY", b"USAGE", b"key", b"SAMPLES", b"5"], &[2]);
check(&[b"CLUSTER", b"KEYSLOT", b"a"], &[]);
check(&[b"LCS", b"a", b"b", b"IDX", b"WITHMATCHLEN"], &[1, 2]);
}
Expand Down
5 changes: 3 additions & 2 deletions src/eviction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,8 +465,9 @@ impl Eviction {
|| name.eq_ignore_ascii_case(b"FLUSHDB")
|| name.eq_ignore_ascii_case(b"FLUSHALL")
|| name.eq_ignore_ascii_case(b"CONFIG")
// OBJECT looks keys up without touching LRU or LFU state.
// OBJECT and MEMORY look keys up without touching LRU or LFU state.
|| name.eq_ignore_ascii_case(b"OBJECT")
|| name.eq_ignore_ascii_case(b"MEMORY")
{
Vec::new()
} else {
Expand Down Expand Up @@ -575,7 +576,7 @@ impl Eviction {
}
}

fn entry_bytes(key: &[u8], entry: &Entry) -> usize {
pub(crate) fn entry_bytes(key: &[u8], entry: &Entry) -> usize {
let content = match &entry.value {
Value::String(bytes) => bytes.len(),
Value::List(items) => items.iter().map(|item| item.len() + 16).sum(),
Expand Down
67 changes: 59 additions & 8 deletions src/keyspace.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
use crate::{mark_modified, protocol, pubsub::glob_matches, remove_expired, Store, Value};
use crate::{
eviction, mark_modified, protocol, pubsub::glob_matches, remove_expired, Store, Value,
};
use std::collections::hash_map::RandomState;
use std::collections::VecDeque;
use std::hash::BuildHasher;
Expand All @@ -19,8 +21,8 @@ pub fn valid_arity(command: &[Vec<u8>]) -> Option<bool> {
Some(command.len() == 2)
} else if name.eq_ignore_ascii_case(b"RANDOMKEY") {
Some(command.len() == 1)
} else if name.eq_ignore_ascii_case(b"OBJECT") {
// queue_error and execute validate OBJECT subcommands in full.
} else if name.eq_ignore_ascii_case(b"OBJECT") || name.eq_ignore_ascii_case(b"MEMORY") {
// queue_error and execute validate OBJECT and MEMORY subcommands in full.
Some(true)
} else if name.eq_ignore_ascii_case(b"SCAN") {
Some(command.len() >= 2 && command.len().is_multiple_of(2))
Expand Down Expand Up @@ -205,12 +207,33 @@ fn object_error(command: &[Vec<u8>]) -> Option<Vec<u8>> {
None
}

/// Validate OBJECT when it is queued, so MULTI aborts like Redis does.
fn memory_error(command: &[Vec<u8>]) -> Option<Vec<u8>> {
let Some(subcommand) = command.get(1) else {
return Some(protocol::error(
"wrong number of arguments for 'memory' command",
));
};
if !subcommand.eq_ignore_ascii_case(b"USAGE") {
return Some(protocol::unknown_subcommand("MEMORY", subcommand));
}
if command.len() < 3 {
return Some(protocol::error(
"wrong number of arguments for 'memory|usage' command",
));
}
None
}

/// Validate OBJECT and MEMORY when they are queued, so MULTI aborts like Redis
/// does. Option syntax such as SAMPLES is checked when the command runs.
pub fn queue_error(command: &[Vec<u8>]) -> Option<Vec<u8>> {
command[0]
.eq_ignore_ascii_case(b"OBJECT")
.then(|| object_error(command))
.flatten()
if command[0].eq_ignore_ascii_case(b"OBJECT") {
object_error(command)
} else if command[0].eq_ignore_ascii_case(b"MEMORY") {
memory_error(command)
} else {
None
}
}

fn object(command: &[Vec<u8>], store: &Store) -> Vec<u8> {
Expand All @@ -231,6 +254,31 @@ fn object(command: &[Vec<u8>], store: &Store) -> Vec<u8> {
}
}

fn memory(command: &[Vec<u8>], store: &Store) -> Vec<u8> {
if let Some(error) = memory_error(command) {
return error;
}
// SAMPLES is validated for compatibility and then ignored: the estimator
// always walks the whole value instead of sampling nested elements.
for option in command[3..].chunks(2) {
if option.len() != 2 || !option[0].eq_ignore_ascii_case(b"SAMPLES") {
return protocol::error("syntax error");
}
match protocol::parse_int(&option[1]) {
Some(count) if count >= 0 => {}
Some(_) => return protocol::error("syntax error"),
None => return protocol::error("value is not an integer or out of range"),
}
}
let mut entries = store.entries.lock().unwrap();
remove_expired(&mut entries, &command[2]);
let Some(entry) = entries.get(&command[2]) else {
return b"$-1\r\n".to_vec();
};
// The same per-entry estimate that maxmemory accounting sums for the dataset.
format!(":{}\r\n", eviction::entry_bytes(&command[2], entry)).into_bytes()
}

fn scan(command: &[Vec<u8>], store: &Store) -> Vec<u8> {
let cursor = match protocol::parse_cursor(&command[1]) {
Some(value) => value,
Expand Down Expand Up @@ -362,6 +410,9 @@ pub fn execute(command: &[Vec<u8>], store: &Store) -> Option<Vec<u8>> {
if command[0].eq_ignore_ascii_case(b"OBJECT") {
return Some(object(command, store));
}
if command[0].eq_ignore_ascii_case(b"MEMORY") {
return Some(memory(command, store));
}
let valid = valid_arity(command)?;
let name = &command[0];
if !valid {
Expand Down
9 changes: 9 additions & 0 deletions tests/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,15 @@ fn command_introspection_reports_dispatch_metadata_and_unknown_names_in_place()
],
)])
);
assert_eq!(
c.call(&[b"COMMAND", b"INFO", b"MEMORY"]),
array(vec![command_entry(
b"memory",
-2,
(0, 0, 0),
vec![command_entry(b"memory|usage", -3, (2, 2, 1), vec![])],
)])
);
assert_eq!(
c.call(&[b"COMMAND", b"INFO", b"GET", b"not-a-command", b"PING"]),
array(vec![
Expand Down
Loading