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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ Because ReRu is pre-1.0, minor versions may include breaking changes.
- `GETEX` validates option syntax first, then the key and type, and only then
the expiry value, so a missing key replies nil and a wrong type replies
WRONGTYPE without value errors.
- Hash field deadlines are capped at the 46-bit millisecond range Redis uses:
larger `HEXPIRE`/`HPEXPIRE`/`HEXPIREAT`/`HPEXPIREAT`/`HSETEX`/`HGETEX` values
report `invalid expire time in '<cmd>' command`. `HTTL` rounds the remaining
time up to the next second. A legacy AOF with a larger stored deadline is
clamped during replay so the server still starts.
- `PUBSUB NUMPAT` reads a reference-counted pattern map instead of rebuilding a
set of every listener's patterns on each call.
- `BZPOPMIN`, `BZPOPMAX`, and `BZMPOP` stay blocked when a watched key only
Expand Down
2 changes: 1 addition & 1 deletion docs/COMPATIBILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ tests; it does not certify complete compatibility with Redis.
| 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 |
| Hashes | `HSET`, `HMSET`, `HSETNX`, `HGET`, `HMGET`, `HGETALL`, `HDEL`, `HEXISTS`, `HLEN`, `HKEYS`, `HVALS`, `HINCRBY`, `HINCRBYFLOAT`, `HSTRLEN`, `HRANDFIELD`, `HSCAN`, `HEXPIRE`, `HPEXPIRE`, `HEXPIREAT`, `HPEXPIREAT`, `HTTL`, `HPTTL`, `HEXPIRETIME`, `HPEXPIRETIME`, `HPERSIST`, `HGETEX`, `HSETEX` | Binary fields/values, multiple field updates, missing-field nil replies, increments, cursor iteration, per-field expiry and conditional TTL changes; HSETEX/HGETEX/HEXPIRE accept options before or after FIELDS |
| Hashes | `HSET`, `HMSET`, `HSETNX`, `HGET`, `HMGET`, `HGETALL`, `HDEL`, `HEXISTS`, `HLEN`, `HKEYS`, `HVALS`, `HINCRBY`, `HINCRBYFLOAT`, `HSTRLEN`, `HRANDFIELD`, `HSCAN`, `HEXPIRE`, `HPEXPIRE`, `HEXPIREAT`, `HPEXPIREAT`, `HTTL`, `HPTTL`, `HEXPIRETIME`, `HPEXPIRETIME`, `HPERSIST`, `HGETEX`, `HSETEX` | Binary fields/values, multiple field updates, missing-field nil replies, increments, cursor iteration, per-field expiry and conditional TTL changes; HSETEX/HGETEX/HEXPIRE accept options before or after FIELDS, field deadlines use Redis's 46-bit millisecond cap, and HTTL rounds up |
| Sets | `SADD`, `SREM`, `SISMEMBER`, `SMISMEMBER`, `SMEMBERS`, `SCARD`, `SMOVE`, `SPOP`, `SRANDMEMBER`, `SUNION`, `SINTER`, `SINTERCARD`, `SDIFF`, `SUNIONSTORE`, `SINTERSTORE`, `SDIFFSTORE`, `SSCAN` | Binary members, deduplication, membership, cardinality, random selection, atomic moves, set algebra and cursor iteration; SINTERCARD LIMIT |
| Sorted sets | `ZADD`, `ZINCRBY`, `ZCARD`, `ZSCORE`, `ZRANK`, `ZREVRANK`, `ZRANGE`, `ZREVRANGE`, `ZRANGESTORE`, `ZRANGEBYSCORE`, `ZREVRANGEBYSCORE`, `ZRANGEBYLEX`, `ZREVRANGEBYLEX`, `ZCOUNT`, `ZLEXCOUNT`, `ZREM`, `ZREMRANGEBYSCORE`, `ZREMRANGEBYRANK`, `ZREMRANGEBYLEX`, `ZMSCORE`, `ZSCAN`, `ZPOPMIN`, `ZPOPMAX`, `ZMPOP`, `BZMPOP`, `BZPOPMIN`, `BZPOPMAX`, `ZUNION`, `ZUNIONSTORE`, `ZINTER`, `ZINTERSTORE`, `ZDIFF`, `ZDIFFSTORE`, `ZINTERCARD` | Score-ordered members, rank, score and lex ranges, ZADD NX/XX/GT/LT/CH/INCR, cursor iteration, range removal, ordered and multi-key blocking pops, weighted algebra and destination storing |
| Vector sets | `VADD`, `VCARD`, `VDIM`, `VEMB`, `VREM`, `VSIM` | Bounded VALUES/FP32 inserts, Q8 or NOQUANT storage, binary members, exact `VSIM ... TRUTH` with COUNT and WITHSCORES |
Expand Down
23 changes: 23 additions & 0 deletions src/aof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,27 @@ pub fn append(
Ok(())
}

/// Older builds accepted field deadlines beyond Redis's 46-bit range. Clamp
/// them during replay so a legacy AOF still loads.
fn clamp_field_deadline(command: &mut [Vec<u8>]) {
if command.len() < 3 {
return;
}
let millis = command[0].eq_ignore_ascii_case(b"HPEXPIREAT");
let seconds = command[0].eq_ignore_ascii_case(b"HEXPIREAT");
if !millis && !seconds {
return;
}
let Some(value) = protocol::parse_int(&command[2]) else {
return;
};
let max = crate::collections::MAX_FIELD_DEADLINE_MS;
let limit = if millis { max } else { max / 1000 };
if i128::from(value) > limit {
command[2] = limit.to_string().into_bytes();
}
}

pub fn replay(path: &Path, store: &Store) -> io::Result<()> {
let file = OpenOptions::new()
.create(true)
Expand Down Expand Up @@ -500,6 +521,8 @@ pub fn replay(path: &Path, store: &Store) -> io::Result<()> {
}
committed = reader.stream_position()?;
} else if let Some(batch) = transaction.as_mut() {
let mut command = command;
clamp_field_deadline(&mut command);
batch.push(command);
} else {
return Err(invalid("AOF command outside transaction"));
Expand Down
2 changes: 1 addition & 1 deletion src/collections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::collections::HashSet;
use std::hash::BuildHasher;

mod hash_expiry;
pub(crate) use hash_expiry::{FieldDeadline, HashValue};
pub(crate) use hash_expiry::{FieldDeadline, HashValue, MAX_FIELD_DEADLINE_MS};

#[derive(Clone, Copy)]
enum Command {
Expand Down
46 changes: 41 additions & 5 deletions src/collections/hash_expiry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,30 @@ fn parse_number(bytes: &[u8]) -> Result<i64, Vec<u8>> {
.ok_or_else(|| protocol::error("value is not an integer or out of range"))
}

fn deadline(raw: &[u8], millis: bool, absolute: bool) -> Result<FieldDeadline, Vec<u8>> {
pub(crate) const MAX_FIELD_DEADLINE_MS: i128 = (1 << 46) - 1;

fn command_name(kind: Kind) -> &'static str {
match kind {
Kind::Expire => "hexpire",
Kind::Pexpire => "hpexpire",
Kind::Expireat => "hexpireat",
Kind::Pexpireat => "hpexpireat",
Kind::Ttl => "httl",
Kind::Pttl => "hpttl",
Kind::Expiretime => "hexpiretime",
Kind::Pexpiretime => "hpexpiretime",
Kind::Persist => "hpersist",
Kind::Getex => "hgetex",
Kind::Setex => "hsetex",
}
}

fn deadline(
raw: &[u8],
millis: bool,
absolute: bool,
command: &str,
) -> Result<FieldDeadline, Vec<u8>> {
let amount = parse_number(raw)?;
if amount < 0 {
return Err(protocol::error("invalid expire time, must be >= 0"));
Expand All @@ -190,6 +213,12 @@ fn deadline(raw: &[u8], millis: bool, absolute: bool) -> Result<FieldDeadline, V
} else {
current + delta_or_absolute
};
// Field deadlines are stored with a 46-bit millisecond timestamp.
if !(0..=MAX_FIELD_DEADLINE_MS).contains(&unix_ms) {
return Err(protocol::error(&format!(
"invalid expire time in '{command}' command"
)));
}
let unix_ms = i64::try_from(unix_ms).map_err(|_| protocol::error("invalid expire time"))?;
let remaining = i128::from(unix_ms) - current;
let at = if remaining <= 0 {
Expand Down Expand Up @@ -247,6 +276,7 @@ fn parse_arguments<'a>(kind: Kind, command: &'a [Vec<u8>]) -> Result<HashArgumen
&command[2],
matches!(kind, Kind::Pexpire | Kind::Pexpireat),
matches!(kind, Kind::Expireat | Kind::Pexpireat),
command_name(kind),
)?));
at += 1;
continue;
Expand Down Expand Up @@ -287,7 +317,7 @@ fn parse_arguments<'a>(kind: Kind, command: &'a [Vec<u8>]) -> Result<HashArgumen
if expiration.is_some() {
return Err(expiry_conflict(kind));
}
expiration = Some(parse_expiry_token(command, &mut at)?);
expiration = Some(parse_expiry_token(kind, command, &mut at)?);
continue;
}
return Err(unknown_argument(token));
Expand Down Expand Up @@ -341,7 +371,11 @@ fn is_expiry_token(kind: Kind, token: &[u8]) -> bool {
}
}

fn parse_expiry_token(command: &[Vec<u8>], at: &mut usize) -> Result<Expiration, Vec<u8>> {
fn parse_expiry_token(
kind: Kind,
command: &[Vec<u8>],
at: &mut usize,
) -> Result<Expiration, Vec<u8>> {
let token = command[*at].as_slice();
if token.eq_ignore_ascii_case(b"PERSIST") {
*at += 1;
Expand All @@ -356,7 +390,7 @@ fn parse_expiry_token(command: &[Vec<u8>], at: &mut usize) -> Result<Expiration,
let raw = command
.get(*at + 1)
.ok_or_else(|| protocol::error("missing expire time"))?;
let expiry = deadline(raw, millis, absolute)?;
let expiry = deadline(raw, millis, absolute, command_name(kind))?;
*at += 2;
Ok(Expiration::Deadline(expiry))
}
Expand Down Expand Up @@ -585,7 +619,9 @@ fn execute_inner(kind: Kind, command: &[Vec<u8>], store: &Store) -> Result<Vec<u
let remaining = at.at.saturating_duration_since(Instant::now());
let millis = i64::try_from(remaining.as_millis()).unwrap_or(i64::MAX);
if matches!(kind, Kind::Ttl) {
millis / 1000
// HTTL rounds the remaining time up to the next second.
i64::try_from(remaining.as_nanos().div_ceil(1_000_000_000))
.unwrap_or(i64::MAX)
} else {
millis
}
Expand Down
36 changes: 36 additions & 0 deletions tests/aof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,39 @@ fn hgetex_options_after_fields_survive_a_restart() {
}
let _ = std::fs::remove_file(path);
}

#[test]
fn aof_clamps_legacy_out_of_range_field_deadlines() {
let path = path();
let filename = path.to_str().unwrap();
{
let server = Server::start_with(&["--appendonly", filename]);
let mut client = Client::new(&server);
assert_eq!(client.call(&[b"HSET", b"h", b"f", b"v"]), integer(1));
}
// A build that predates the deadline cap could append this value.
use std::io::Write;
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(&path)
.unwrap();
file.write_all(
b"*1\r\n$5\r\nMULTI\r\n*6\r\n$10\r\nHPEXPIREAT\r\n$1\r\nh\r\n$15\r\n101795017799627\r\n$6\r\nFIELDS\r\n$1\r\n1\r\n$1\r\nf\r\n*1\r\n$4\r\nEXEC\r\n",
)
.unwrap();
file.write_all(
b"*1\r\n$5\r\nMULTI\r\n*6\r\n$9\r\nHEXPIREAT\r\n$1\r\nh\r\n$15\r\n101795017799627\r\n$6\r\nFIELDS\r\n$1\r\n1\r\n$1\r\nf\r\n*1\r\n$4\r\nEXEC\r\n",
)
.unwrap();
drop(file);
{
let server = Server::start_with(&["--appendonly", filename]);
let mut client = Client::new(&server);
assert_eq!(client.call(&[b"HEXISTS", b"h", b"f"]), integer(1));
assert!(matches!(
client.call(&[b"HTTL", b"h", b"FIELDS", b"1", b"f"]),
Reply::Array(Some(rows)) if matches!(rows[0], Reply::Integer(ttl) if ttl > 0)
));
}
let _ = std::fs::remove_file(path);
}
Loading
Loading