diff --git a/CHANGELOG.md b/CHANGELOG.md index 14c8824..faf294f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 '' 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 diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md index b7bccef..a793487 100644 --- a/docs/COMPATIBILITY.md +++ b/docs/COMPATIBILITY.md @@ -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 | diff --git a/src/aof.rs b/src/aof.rs index 6f2d454..f9f51de 100644 --- a/src/aof.rs +++ b/src/aof.rs @@ -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]) { + 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) @@ -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")); diff --git a/src/collections.rs b/src/collections.rs index 64501f5..58c0532 100644 --- a/src/collections.rs +++ b/src/collections.rs @@ -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 { diff --git a/src/collections/hash_expiry.rs b/src/collections/hash_expiry.rs index 4037450..d00ada1 100644 --- a/src/collections/hash_expiry.rs +++ b/src/collections/hash_expiry.rs @@ -174,7 +174,30 @@ fn parse_number(bytes: &[u8]) -> Result> { .ok_or_else(|| protocol::error("value is not an integer or out of range")) } -fn deadline(raw: &[u8], millis: bool, absolute: bool) -> Result> { +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> { let amount = parse_number(raw)?; if amount < 0 { return Err(protocol::error("invalid expire time, must be >= 0")); @@ -190,6 +213,12 @@ fn deadline(raw: &[u8], millis: bool, absolute: bool) -> Result(kind: Kind, command: &'a [Vec]) -> Result(kind: Kind, command: &'a [Vec]) -> Result bool { } } -fn parse_expiry_token(command: &[Vec], at: &mut usize) -> Result> { +fn parse_expiry_token( + kind: Kind, + command: &[Vec], + at: &mut usize, +) -> Result> { let token = command[*at].as_slice(); if token.eq_ignore_ascii_case(b"PERSIST") { *at += 1; @@ -356,7 +390,7 @@ fn parse_expiry_token(command: &[Vec], at: &mut usize) -> Result], store: &Store) -> Result 0) + )); + } + let _ = std::fs::remove_file(path); +} diff --git a/tests/collections.rs b/tests/collections.rs index 7627da9..dc3ae40 100644 --- a/tests/collections.rs +++ b/tests/collections.rs @@ -1008,3 +1008,210 @@ fn hash_expiry_options_are_accepted_around_fields() { Reply::Error(b"WRONGTYPE Operation against a key holding the wrong kind of value".to_vec()) ); } + +#[test] +fn hash_expiry_deadline_range_and_ttl_rounding() { + let server = common::Server::start(); + let mut c = Client::new(&server); + assert_eq!(c.call(&[b"HSET", b"h", b"f", b"v"]), integer(1)); + let invalid = |name: &str| { + Reply::Error(format!("ERR invalid expire time in '{name}' command").into_bytes()) + }; + + assert_eq!( + c.call(&[b"HEXPIRE", b"h", b"100000000000", b"FIELDS", b"1", b"f"]), + invalid("hexpire") + ); + assert_eq!( + c.call(&[ + b"HPEXPIRE", + b"h", + b"9223372036854775", + b"FIELDS", + b"1", + b"f" + ]), + invalid("hpexpire") + ); + assert_eq!( + c.call(&[b"HEXPIREAT", b"h", b"70368744178", b"FIELDS", b"1", b"f"]), + invalid("hexpireat") + ); + assert_eq!( + c.call(&[ + b"HPEXPIREAT", + b"h", + b"70368744177664", + b"FIELDS", + b"1", + b"f" + ]), + invalid("hpexpireat") + ); + assert_eq!( + c.call(&[ + b"HSETEX", + b"h", + b"EX", + b"100000000000", + b"FIELDS", + b"1", + b"f", + b"v" + ]), + invalid("hsetex") + ); + assert_eq!( + c.call(&[ + b"HGETEX", + b"h", + b"EX", + b"100000000000", + b"FIELDS", + b"1", + b"f" + ]), + invalid("hgetex") + ); + assert_eq!( + c.call(&[b"HEXPIRE", b"h", b"-1", b"FIELDS", b"1", b"f"]), + Reply::Error(b"ERR invalid expire time, must be >= 0".to_vec()) + ); + + // The 46-bit boundary itself is accepted and readable. + assert_eq!( + c.call(&[ + b"HPEXPIREAT", + b"h", + b"70368744177663", + b"FIELDS", + b"1", + b"f" + ]), + array(vec![integer(1)]) + ); + assert_eq!( + c.call(&[b"HPEXPIRETIME", b"h", b"FIELDS", b"1", b"f"]), + array(vec![integer(70_368_744_177_663)]) + ); + assert_eq!( + c.call(&[ + b"HPEXPIREAT", + b"h", + b"70368744177664", + b"FIELDS", + b"1", + b"f" + ]), + invalid("hpexpireat") + ); + assert_eq!( + c.call(&[ + b"HPEXPIRE", + b"h", + b"9223372036854775807", + b"FIELDS", + b"1", + b"f" + ]), + invalid("hpexpire") + ); + assert_eq!( + c.call(&[ + b"HPEXPIRE", + b"h", + b"99999999999999999999", + b"FIELDS", + b"1", + b"f" + ]), + Reply::Error(b"ERR value is not an integer or out of range".to_vec()) + ); + assert_eq!( + c.call(&[ + b"HSETEX", + b"h", + b"PX", + b"9223372036854775", + b"FIELDS", + b"1", + b"f", + b"v" + ]), + invalid("hsetex") + ); + assert_eq!( + c.call(&[ + b"HSETEX", + b"h", + b"PXAT", + b"70368744177664", + b"FIELDS", + b"1", + b"f", + b"v" + ]), + invalid("hsetex") + ); + assert_eq!( + c.call(&[ + b"HGETEX", + b"h", + b"PX", + b"9223372036854775", + b"FIELDS", + b"1", + b"f" + ]), + invalid("hgetex") + ); + assert_eq!( + c.call(&[ + b"HGETEX", + b"h", + b"PXAT", + b"70368744177664", + b"FIELDS", + b"1", + b"f" + ]), + invalid("hgetex") + ); + + // A rejected value leaves the existing TTL and field untouched. + assert_eq!( + c.call(&[b"HPEXPIRE", b"h", b"100000", b"FIELDS", b"1", b"f"]), + array(vec![integer(1)]) + ); + assert_eq!( + c.call(&[b"HPEXPIRE", b"h", b"100000000000000", b"FIELDS", b"1", b"f"]), + invalid("hpexpire") + ); + assert_eq!(c.call(&[b"HEXISTS", b"h", b"f"]), integer(1)); + assert!(matches!( + c.call(&[b"HPTTL", b"h", b"FIELDS", b"1", b"f"]), + Reply::Array(Some(ref rows)) if matches!(rows[0], Reply::Integer(ttl) if ttl > 50_000) + )); + + // HTTL rounds the remaining time up to the next second. + for (millis, seconds) in [ + ("100", 1), + ("999", 1), + ("1000", 1), + ("1001", 2), + ("1499", 2), + ("2001", 3), + ("2500", 3), + ("9999", 10), + ] { + assert_eq!( + c.call(&[b"HPEXPIRE", b"h", millis.as_bytes(), b"FIELDS", b"1", b"f"]), + array(vec![integer(1)]) + ); + assert_eq!( + c.call(&[b"HTTL", b"h", b"FIELDS", b"1", b"f"]), + array(vec![integer(seconds)]), + "{millis}" + ); + } +}