use crate::commands::*;
use crate::replication;
use crate::resp::write::{resp_array, resp_error, resp_integer};
use ctx::Ctx;
use std::sync::atomic::Ordering;
fn dispatch_command_handlers_fallback(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
strings::handle(ctx, name)
.or_else(|| acl::handle(ctx, name))
.or_else(|| json::handle(ctx, name))
.or_else(|| lists::handle(ctx, name))
.or_else(|| sets::handle(ctx, name))
.or_else(|| generics::handle(ctx, name))
.or_else(|| server::handle(ctx, name))
.or_else(|| streams::handle(ctx, name))
.or_else(|| connection::handle(ctx, name))
.or_else(|| vector::handle(ctx, name))
.or_else(|| vset::handle(ctx, name))
.or_else(|| hash::handle(ctx, name))
.or_else(|| zset::handle(ctx, name))
.or_else(|| bitmap::handle(ctx, name))
.or_else(|| hyperloglog::handle(ctx, name))
.or_else(|| geo::handle(ctx, name))
.or_else(|| ts::handle(ctx, name))
.or_else(|| pubsub::handle(ctx, name))
.or_else(|| slowlog::handle(ctx, name))
.or_else(|| latency::handle(ctx, name))
.or_else(|| memory::handle(ctx, name))
.or_else(|| cluster::handle(ctx, name))
.or_else(|| cluster::handle_migrate(ctx, name))
.or_else(|| array::handle(ctx, name))
.or_else(|| hotkeys::handle(ctx, name))
.or_else(|| backup::handle(ctx, name))
}
pub(crate) fn unknown_command(cmd: &[&[u8]]) -> Vec<u8> {
let shown = |raw: &[u8]| -> String {
String::from_utf8_lossy(&raw[..raw.len().min(128)]).replace(['\r', '\n'], " ")
};
let mut args = String::new();
for arg in cmd.iter().skip(1) {
if args.len() >= 128 {
break;
}
let room = 128 - args.len();
let arg = shown(arg);
let arg: String = arg.chars().take(room).collect();
args.push_str(&format!("'{arg}' "));
}
resp_error(&format!(
"ERR unknown command '{}', with args beginning with: {}",
shown(cmd.first().copied().unwrap_or_default()),
args
))
}
pub(crate) fn dispatch_command_handlers(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
let first = name.as_bytes().first().copied().unwrap_or(0) | 0x20;
let fast = match first {
b'g' | b's' | b'i' | b'd' | b'a' | b'm' => strings::handle(ctx, name)
.or_else(|| generics::handle(ctx, name))
.or_else(|| sets::handle(ctx, name))
.or_else(|| server::handle(ctx, name))
.or_else(|| {
if first == b'g' {
geo::handle(ctx, name)
} else {
None
}
})
.or_else(|| {
if first == b'a' {
acl::handle(ctx, name)
} else {
None
}
})
.or_else(|| {
if first == b'a' {
array::handle(ctx, name)
} else {
None
}
})
.or_else(|| {
if first == b'm' {
memory::handle(ctx, name)
} else {
None
}
}),
b'l' => lists::handle(ctx, name),
b'h' => hash::handle(ctx, name).or_else(|| hyperloglog::handle(ctx, name)),
b'z' => zset::handle(ctx, name),
b'b' => bitmap::handle(ctx, name),
b'f' => vector::handle(ctx, name),
b'j' => json::handle(ctx, name),
b'x' => streams::handle(ctx, name),
b'v' => vset::handle(ctx, name).or_else(|| vector::handle(ctx, name)),
b'p' => connection::handle(ctx, name)
.or_else(|| generics::handle(ctx, name))
.or_else(|| pubsub::handle(ctx, name)),
b'u' => pubsub::handle(ctx, name).or_else(|| generics::handle(ctx, name)),
b't' => ts::handle(ctx, name)
.or_else(|| generics::handle(ctx, name))
.or_else(|| server::handle(ctx, name)),
b'c' => connection::handle(ctx, name)
.or_else(|| cluster::handle(ctx, name))
.or_else(|| cluster::handle_migrate(ctx, name)),
b'r' | b'e' | b'w' | b'n' | b'o' | b'y' => server::handle(ctx, name)
.or_else(|| generics::handle(ctx, name))
.or_else(|| strings::handle(ctx, name)),
_ => None,
};
fast.or_else(|| dispatch_command_handlers_fallback(ctx, name))
}
struct ReplaceWatch {
before: Vec<(usize, usize, crate::store::EntryRef)>,
holding: bool,
}
#[cold]
#[inline(never)]
fn replace_watch_begin(ctx: &Ctx, name: &str) -> Option<ReplaceWatch> {
let before: Vec<_> = crate::keyspace_events::whole_value_targets(name, &ctx.cmd)
.into_iter()
.filter_map(|(db, pos)| {
let db = db.unwrap_or(*ctx.selected_db);
let key = ctx.cmd[pos];
let held =
crate::read_lock!(crate::store::get_shard(ctx.store.get(db)?, key)).get_ref(key)?;
Some((db, pos, held))
})
.collect();
if before.is_empty() {
return None;
}
let holding = crate::keyspace_events::overwritten_goes_first(name);
if holding {
crate::keyspace_events::hold();
}
Some(ReplaceWatch { before, holding })
}
#[cold]
#[inline(never)]
fn replace_watch_end(ctx: &Ctx, watch: ReplaceWatch) {
let held = if watch.holding {
crate::keyspace_events::release()
} else {
Vec::new()
};
for (db, pos, old) in watch.before {
let key = ctx.cmd[pos];
let replaced = {
let map = crate::read_lock!(crate::store::get_shard(&ctx.store[db], key));
match map.get(key) {
Some(now) if !map.holds(key, &old) => {
Some(now.type_name() != old.value().type_name())
}
_ => None,
}
};
if let Some(type_changed) = replaced {
crate::keyspace_events::notify(
ctx.pubsub,
db,
crate::keyspace_events::KS_OVERWRITTEN,
"overwritten",
key,
);
if type_changed {
crate::keyspace_events::notify(
ctx.pubsub,
db,
crate::keyspace_events::KS_TYPE_CHANGED,
"type_changed",
key,
);
}
}
}
crate::keyspace_events::replay(ctx.pubsub, held);
}
#[cfg_attr(not(feature = "lua"), allow(dead_code))]
pub(crate) fn execute_command_from_script(
ctx: &mut Ctx,
mut parts: Vec<&[u8]>,
read_only_script: bool,
) -> Vec<u8> {
if parts.is_empty() {
return resp_error("ERR wrong number of arguments for redis.call()");
}
let _queued = crate::lazyfree::running_queued();
let mut upper_first = [0u8; 32];
let name_long;
let name: &str = if parts[0].len() <= upper_first.len() {
let upper = &mut upper_first[..parts[0].len()];
upper.copy_from_slice(parts[0]);
upper.make_ascii_uppercase();
std::str::from_utf8(upper).unwrap_or("")
} else {
name_long = String::from_utf8_lossy(parts[0]).to_ascii_uppercase();
name_long.as_str()
};
if not_allowed_from_script(name, parts.get(1).copied()) {
return resp_error("ERR This Redis command is not allowed from script");
}
match name {
"WAIT" => return resp_integer(0),
"WAITAOF" => return resp_array(vec![resp_integer(0), resp_integer(0)]),
"XREAD" | "XREADGROUP" => {
let has_block = parts.iter().any(|a| a.eq_ignore_ascii_case(b"BLOCK"));
if has_block {
let mut i = 1usize;
while i < parts.len() {
if parts[i].eq_ignore_ascii_case(b"BLOCK") {
parts.remove(i);
if i < parts.len() {
parts.remove(i);
}
} else {
i += 1;
}
}
}
}
_ => {}
}
let refs_erased: Vec<&'static [u8]> = unsafe { std::mem::transmute(parts) };
let saved_cmd = std::mem::replace(&mut ctx.cmd, refs_erased);
let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
run_from_script(ctx, read_only_script)
}));
ctx.cmd = saved_cmd;
reply.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
}
fn not_allowed_from_script(name: &str, sub: Option<&[u8]>) -> bool {
let sub_is = |names: &[&str]| {
sub.is_some_and(|sub| names.iter().any(|n| sub.eq_ignore_ascii_case(n.as_bytes())))
};
match name {
"AUTH" | "BGREWRITEAOF" | "BGSAVE" | "DEBUG" | "DISCARD" | "EVAL" | "EVALSHA"
| "EVALSHA_RO" | "EVAL_RO" | "EXEC" | "FAILOVER" | "FCALL" | "FCALL_RO" | "HELLO"
| "MONITOR" | "MULTI" | "PSUBSCRIBE" | "PSYNC" | "PUNSUBSCRIBE" | "QUIT" | "REPLCONF"
| "REPLICAOF" | "RESET" | "ROLE" | "SAVE" | "SHUTDOWN" | "SLAVEOF" | "SSUBSCRIBE"
| "SUBSCRIBE" | "SUNSUBSCRIBE" | "SYNC" | "UNSUBSCRIBE" | "UNWATCH" | "WATCH" => true,
"ACL" => sub_is(&[
"CAT", "DELUSER", "DRYRUN", "GENPASS", "GETUSER", "LIST", "LOAD", "LOG", "SAVE",
"SETUSER", "USERS", "WHOAMI",
]),
"BACKUP" => sub_is(&["ABORT", "CLEANUP", "SEAL", "START"]),
"CLIENT" => sub_is(&[
"CACHING",
"GETNAME",
"GETREDIR",
"ID",
"INFO",
"KILL",
"LIST",
"NO-EVICT",
"NO-TOUCH",
"PAUSE",
"REPLY",
"SETINFO",
"SETNAME",
"TRACKING",
"TRACKINGINFO",
"UNBLOCK",
"UNPAUSE",
]),
"CLUSTER" => !sub_is(&[
"COUNTKEYSINSLOT",
"GETKEYSINSLOT",
"HELP",
"INFO",
"KEYSLOT",
"LINKS",
"MYID",
"MYSHARDID",
"NODES",
"SHARDS",
"SLOT-STATS",
"SLOTS",
]),
"CONFIG" => sub_is(&["GET", "RESETSTAT", "REWRITE", "SET"]),
"FUNCTION" => sub_is(&[
"DELETE", "DUMP", "FLUSH", "KILL", "LIST", "LOAD", "RESTORE", "STATS",
]),
"HOTKEYS" => sub_is(&["GET", "RESET", "START", "STOP"]),
"LATENCY" => sub_is(&["DOCTOR", "GRAPH", "HISTOGRAM", "HISTORY", "LATEST", "RESET"]),
"MODULE" => sub_is(&["LIST", "LOAD", "LOADEX", "UNLOAD"]),
"SCRIPT" => sub_is(&["DEBUG", "EXISTS", "FLUSH", "KILL", "LOAD"]),
_ => false,
}
}
fn busy_reply() -> Vec<u8> {
#[cfg(feature = "lua")]
{
crate::commands::lua::busy_reply()
}
#[cfg(not(feature = "lua"))]
{
resp_error(
"BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.",
)
}
}
#[cfg(feature = "lua")]
fn script_key_refusal(ctx: &Ctx, name: &str) -> Option<Vec<u8>> {
let (script_slot, allow_cross_slot) = crate::commands::lua::script_slot()?;
let keys = crate::keyspec::key_positions(name, &ctx.cmd);
let mut slots = keys
.iter()
.map(|pos| crate::cluster::slot::key_hash_slot(ctx.cmd[pos]));
let first = slots.next()?;
if slots.any(|slot| slot != first) {
return Some(resp_error(
"ERR Script attempted to access keys that do not hash to the same slot",
));
}
if script_slot == Some(first) {
return None;
}
if script_slot.is_some() && !allow_cross_slot {
return Some(resp_error(
"ERR Script attempted to access keys that do not hash to the same slot",
));
}
let store = ctx.store;
let db = *ctx.selected_db;
let registry = ctx.client_registry;
let client_id = ctx.client_id;
let decision = crate::cluster::routing::route_named(
name,
ctx.cmd.as_slice(),
ctx.cluster,
false,
|| registry.get_readonly(client_id),
|key| {
let shard = crate::store::get_shard(&store[db], key);
crate::read_lock!(shard).contains_key(key)
},
);
match decision {
crate::cluster::routing::RouteDecision::OwnedSlot(slot) => {
crate::commands::lua::script_settle_slot(slot);
None
}
crate::cluster::routing::RouteDecision::TryAgain => decision.refusal(),
crate::cluster::routing::RouteDecision::Passthrough => None,
_ => Some(resp_error(
"ERR Script attempted to access a non local key in a cluster node",
)),
}
}
#[inline(never)]
fn keys_of_several_shards(
store: &crate::store::Store,
db: usize,
name: &str,
cmd: &[&[u8]],
) -> bool {
if cmd.len() < 3
|| matches!(name, "MSET" | "MSETNX")
|| one_key_write(name)
|| !replication::command_mutates_for_replication(name, cmd)
{
return false;
}
let keys = crate::keyspec::key_positions(name, cmd);
if keys.iter().nth(1).is_none() {
return false;
}
let Some(db) = store.get(db) else {
return false;
};
let mut shards = keys
.iter()
.map(|pos| crate::store::shard_index_of_bytes(db.len(), cmd[pos]));
let first = shards.next();
first.is_none() || shards.any(|shard| Some(shard) != first)
}
#[inline(always)]
fn takes_the_gate_alone(
store: &crate::store::Store,
db: usize,
name: &str,
cmd: &[&[u8]],
script_alone: bool,
gated: bool,
) -> bool {
script_alone
|| (gated
&& matches!(name, "FLUSHALL" | "FLUSHDB" | "SWAPDB")
&& !crate::expiry::replaying())
|| (crate::tag_locks::enabled() && crate::tag_locks::sees_the_whole_keyspace(name))
|| crate::tag_locks::is_switch(name, cmd)
|| (cmd.len() >= 3 && keys_of_several_shards(store, db, name, cmd))
|| (name == "SORT" && sort_reads_hash_fields(cmd))
}
#[inline(never)]
fn sort_reads_hash_fields(cmd: &[&[u8]]) -> bool {
crate::commands::generics::sort_reads_hash_fields(cmd)
}
#[inline]
fn one_key_write(name: &str) -> bool {
matches!(
name,
"SET"
| "SETEX"
| "PSETEX"
| "SETNX"
| "GETSET"
| "GETDEL"
| "APPEND"
| "INCR"
| "DECR"
| "INCRBY"
| "DECRBY"
| "INCRBYFLOAT"
| "HSET"
| "HMSET"
| "HSETNX"
| "HDEL"
| "HINCRBY"
| "HINCRBYFLOAT"
| "LPUSH"
| "RPUSH"
| "LPOP"
| "RPOP"
| "SADD"
| "SREM"
| "ZADD"
| "ZREM"
| "ZINCRBY"
| "XADD"
| "PFADD"
| "PEXPIREAT"
| "HPEXPIREAT"
| "PERSIST"
)
}
pub(crate) fn applied_takes_the_gate_alone(
store: &crate::store::Store,
db: usize,
cmd: &[&[u8]],
) -> bool {
let Some(&cmd0) = cmd.first() else {
return false;
};
let mut upper = [0u8; 32];
let owned;
let name: &str = if cmd0.len() <= upper.len() {
for (to, from) in upper.iter_mut().zip(cmd0) {
*to = from.to_ascii_uppercase();
}
std::str::from_utf8(&upper[..cmd0.len()]).unwrap_or("")
} else {
owned = String::from_utf8_lossy(cmd0).to_ascii_uppercase();
&owned
};
if one_key_write(name) || crate::command_gate::skips(name, cmd) {
return false;
}
let script = matches!(
name,
"EVAL" | "EVALSHA" | "FCALL" | "EVAL_RO" | "EVALSHA_RO" | "FCALL_RO"
);
takes_the_gate_alone(store, db, name, cmd, script, true)
}
#[inline(never)]
fn order_of_pairs_shared(ctx: &Ctx) -> crate::write_order::OrderGuard {
crate::write_order::lock_keys_shared(*ctx.selected_db, ctx.cmd[1..].iter().step_by(2).copied())
}
#[inline(never)]
fn sort_pattern_outside_the_tag(name: &str, cmd: &[&[u8]]) -> Option<String> {
if !matches!(name, "SORT" | "SORT_RO") {
return None;
}
let pattern =
crate::commands::generics::sort_pattern_outside(cmd, crate::tag_locks::script_may_touch)?;
Some(format!(
"ERR Script attempted to run '{}' with the pattern '{}', which looks at keys it does \
not name outside the hash tag '{}' of its KEYS (lua-parallel-scripts)",
name.to_ascii_lowercase(),
String::from_utf8_lossy(pattern),
crate::tag_locks::script_tag_for_message()
))
}
fn run_from_script(ctx: &mut Ctx, read_only_script: bool) -> Vec<u8> {
let cmd0 = ctx.cmd[0];
let mut upper_buf = [0u8; 32];
let name_owned2;
let name2: &str = if cmd0.len() <= 32 {
for (i, &b) in cmd0.iter().enumerate() {
upper_buf[i] = b.to_ascii_uppercase();
}
std::str::from_utf8(&upper_buf[..cmd0.len()]).unwrap_or("")
} else {
name_owned2 = String::from_utf8_lossy(cmd0).to_ascii_uppercase();
name_owned2.as_str()
};
if crate::tag_locks::in_script() {
let outside = if crate::tag_locks::sees_the_whole_keyspace(name2) {
Some(format!(
"ERR Script attempted to run '{}', which looks at keys it does not name, while \
running under the hash tag '{}' of its KEYS (lua-parallel-scripts)",
name2.to_ascii_lowercase(),
crate::tag_locks::script_tag_for_message()
))
} else {
crate::keyspec::key_positions(name2, &ctx.cmd)
.iter()
.map(|pos| ctx.cmd[pos])
.find(|key| !crate::tag_locks::script_may_touch(key))
.map(|key| {
format!(
"ERR Script attempted to access the key '{}', which is outside the hash \
tag '{}' of its KEYS (lua-parallel-scripts)",
String::from_utf8_lossy(key),
crate::tag_locks::script_tag_for_message()
)
})
.or_else(|| sort_pattern_outside_the_tag(name2, &ctx.cmd))
};
if let Some(outside) = outside {
return resp_error(&outside);
}
if name2 == "SELECT"
&& crate::tag_locks::beside_others()
&& let Some(db) = makes_the_switch(ctx)
{
return resp_error(&format!(
"ERR Script attempted to SELECT {db}, the first database other than 0 \
selected on this server, while running beside other scripts under the hash \
tag '{}' of its KEYS (lua-parallel-scripts)",
crate::tag_locks::script_tag_for_message()
));
}
}
if read_only_script && replication::inner_command_blocked_in_readonly_script(name2, &ctx.cmd) {
return resp_error("ERR Write commands are not allowed from read-only scripts.");
}
#[cfg(feature = "lua")]
if ctx.cluster.enabled
&& !ctx.bypass_cluster_check
&& !ctx.apply_replication
&& let Some(refusal) = script_key_refusal(ctx, name2)
{
return refusal;
}
let repl_is_slave = ctx.repl_state.is_slave();
if repl_is_slave && !ctx.apply_replication {
if replication::is_denied_on_readonly_replica(name2, &ctx.cmd) {
return resp_error("READONLY You can't write against a read only replica.");
}
if ctx
.repl_state
.slave_sync_in_progress
.load(Ordering::Relaxed)
&& !replication::slave_command_allowed_during_loading(name2)
{
return resp_error("LOADING KiviDB is loading the dataset into memory");
}
}
#[cfg(feature = "lua")]
let skip_mem = crate::commands::lua::script_allow_oom();
#[cfg(not(feature = "lua"))]
let skip_mem = false;
if !repl_is_slave
&& check_memory_limit()
&& replication::command_mutates_for_replication(name2, ctx.cmd.as_slice())
&& !crate::eviction::allowed_when_out_of_memory(name2)
&& !skip_mem
{
log_throttled!(
60,
crate::loglevel::WARN,
"maxmemory ({} bytes) reached and nothing more can be evicted under \
maxmemory-policy {}: write commands are refused with OOM. Raise maxmemory, \
use an evicting policy such as allkeys-lru, or delete data",
crate::RUNTIME_MAXMEMORY.load(std::sync::atomic::Ordering::Relaxed),
crate::eviction::policy().name()
);
return resp_error("OOM command not allowed when used memory > 'maxmemory'.");
}
#[cfg(feature = "lua")]
if !repl_is_slave && let Some(rep) = crate::commands::lua::script_min_replicas_gate(ctx, cmd0) {
return rep;
}
if !ctx.apply_replication
&& (crate::acl::RESTRICTED_CMD_CLIENTS.load(std::sync::atomic::Ordering::Relaxed) > 0
|| crate::acl::RESTRICTED_KEY_CLIENTS.load(std::sync::atomic::Ordering::Relaxed) > 0)
{
let denied = ctx
.acl_store
.read()
.get(ctx.authenticated_user)
.and_then(|user| crate::acl::check_permission(user, name2, ctx.cmd.as_slice()).err());
if let Some(denied) = denied {
let _lua = crate::acl::log_context("lua");
ctx.acl_log.record(
denied.reason(),
denied.object(),
ctx.authenticated_user,
&crate::acl::log_client_info(ctx.client_registry, ctx.client_id, ctx.peer_addr),
);
let reply = resp_error(&denied.message(ctx.authenticated_user));
return reply;
}
}
crate::monitor::feed(ctx.monitor_registry, &ctx.cmd, *ctx.selected_db, "lua");
let started = std::time::Instant::now();
if replication::command_mutates_for_replication(name2, ctx.cmd.as_slice()) {
expire_named_keys_first(ctx, name2, None);
}
let script_call = replication::script_feed::ScriptCall::enter();
let result = dispatch_command_handlers(ctx, name2)
.unwrap_or_else(|| resp_error("ERR Unknown Redis command called from script"));
drop(script_call);
crate::cmdstats::record(name2, &ctx.cmd, &result, started.elapsed());
let inner_write = replication::command_mutates_for_replication(name2, ctx.cmd.as_slice());
#[cfg(feature = "lua")]
if !result.starts_with(b"-") && inner_write {
crate::commands::lua::script_note_successful_write();
}
if !result.starts_with(b"-") && inner_write {
settle_written_keys(ctx, name2);
}
{
track(
ctx,
name2,
&result,
inner_write && !result.starts_with(b"-"),
inner_write,
);
}
#[cfg(feature = "lua")]
if !result.starts_with(b"-")
&& !repl_is_slave
&& !ctx.apply_replication
&& !propagates_nothing(name2, ctx.cmd.as_slice(), &result)
&& replication::command_mutates_for_replication(name2, ctx.cmd.as_slice())
{
let feeds = replication::script_feed::commands_for_propagation(
ctx,
name2,
ctx.cmd.as_slice(),
&result,
);
let observed = replication::write_is_observed(ctx);
for parts in feeds {
if observed {
replication::replicate_one_write(ctx, &parts);
}
crate::stats::record_rdb_change();
}
notify_watchers(ctx, name2, &result);
}
crate::watch::clear_unchanged();
rewrite_wrong_arity_error_for_script(result)
}
fn rewrite_wrong_arity_error_for_script(resp: Vec<u8>) -> Vec<u8> {
if resp.starts_with(b"-ERR wrong number of arguments for redis.call") {
return resp;
}
if resp.starts_with(b"-ERR wrong number of arguments") {
return resp_error("ERR Wrong number of args calling Redis command from script");
}
resp
}
#[inline]
pub(crate) fn effective_resp_for_reply(ctx: &Ctx<'_>) -> u8 {
#[cfg(feature = "lua")]
{
if let Some(r) = crate::commands::lua::script_eval_script_resp() {
return r;
}
}
ctx.resp
}
#[allow(dead_code)]
#[inline]
pub(crate) fn client_connection_resp(ctx: &Ctx<'_>) -> u8 {
ctx.client_registry.get_resp(ctx.client_id)
}
pub fn check_memory_limit() -> bool {
let limit = crate::RUNTIME_MAXMEMORY.load(std::sync::atomic::Ordering::Relaxed);
limit != 0 && crate::memory_use::over(limit)
}
pub fn execute_command(mut ctx: Ctx) -> Vec<u8> {
let ctx = &mut ctx;
if ctx.cmd.is_empty() {
return resp_error("ERR empty command");
}
ctx.skip_write_side_effects = false;
crate::stats::record_command_processed();
let cmd0 = &ctx.cmd[0];
let mut upper_buf = [0u8; 32];
let name_owned;
let name: &str = if cmd0.len() <= 32 {
let mut ascii = true;
for (i, &b) in cmd0.iter().enumerate() {
ascii &= b.is_ascii();
upper_buf[i] = b.to_ascii_uppercase();
}
if ascii {
unsafe { std::str::from_utf8_unchecked(&upper_buf[..cmd0.len()]) }
} else {
""
}
} else {
name_owned = String::from_utf8_lossy(cmd0).to_ascii_uppercase();
name_owned.as_str()
};
let started = std::time::Instant::now();
let reply = run_command(ctx, name, started);
if crate::pause::is_held(&reply) {
crate::stats::unrecord_command_processed();
return reply;
}
let elapsed = started.elapsed();
crate::cmdstats::note_last_command(elapsed);
crate::latency::note_command(ctx.latency, name, elapsed);
if !crate::commands::blocking::parked(ctx) {
crate::cmdstats::record(name, &ctx.cmd, &reply, elapsed);
}
if ctx.cluster.enabled && crate::cluster::ddl::is_definition_command(name) {
return crate::cluster::ddl::spread(ctx, reply);
}
reply
}
#[inline]
fn asks_only(name: &str) -> bool {
matches!(
name,
"OBJECT"
| "TYPE"
| "TTL"
| "PTTL"
| "EXPIRETIME"
| "PEXPIRETIME"
| "EXISTS"
| "DEBUG"
| "RESTORE"
| "TS.MGET"
| "TS.MRANGE"
| "TS.MREVRANGE"
| "TS.QUERYINDEX"
) || name.starts_with("FT.")
}
#[inline]
fn is_script(name: &str) -> bool {
matches!(
name,
"EVAL" | "EVALSHA" | "EVAL_RO" | "EVALSHA_RO" | "FCALL" | "FCALL_RO"
)
}
#[cold]
#[inline(never)]
fn access_scope(name: &str, now: std::time::Instant, cmd: &[&[u8]]) -> crate::store::AccessScope {
use crate::store::AccessScope;
if asks_only(name) || is_script(name) {
return AccessScope::none();
}
let stamp = crate::eviction::stamp(now);
if !AccessScope::counts(stamp) || cmd.len() < 3 {
return AccessScope::open(stamp);
}
AccessScope::open_naming(stamp, named_more_than_once(name, cmd))
}
fn named_more_than_once(name: &str, cmd: &[&[u8]]) -> Vec<(Box<[u8]>, u8)> {
let positions = crate::keyspec::key_positions(name, cmd);
let mut keys = positions.iter();
let (Some(first), Some(second)) = (keys.next(), keys.next()) else {
return Vec::new();
};
let mut keys: Vec<&[u8]> = [first, second]
.into_iter()
.chain(keys)
.map(|pos| cmd[pos])
.collect();
keys.sort_unstable();
let mut named = Vec::new();
for run in keys.chunk_by(|a, b| a == b) {
if run.len() > 1 {
named.push((Box::from(run[0]), run.len().min(u8::MAX as usize) as u8));
}
}
named
}
#[cold]
#[inline(never)]
fn used_on_error(ctx: &Ctx, name: &str) {
let db = *ctx.selected_db;
for pos in crate::keyspec::key_positions(name, &ctx.cmd).iter() {
let key = ctx.cmd[pos];
crate::read_lock!(crate::store::get_shard_of_bytes(&ctx.store[db], key)).use_key(key);
}
}
#[cold]
#[inline(never)]
fn routed_again_in_gate(
ctx: &Ctx,
name: &str,
routed: crate::cluster::routing::Routed,
) -> Option<Vec<u8>> {
if !ctx.cluster.enabled
|| ctx.bypass_cluster_check
|| !crate::pause::routes_moved_since(routed.at())
{
return None;
}
let store = ctx.store;
let db = *ctx.selected_db;
let registry = ctx.client_registry;
let client_id = ctx.client_id;
crate::cluster::routing::route_named(
name,
ctx.cmd.as_slice(),
ctx.cluster,
routed.asking(),
|| registry.get_readonly(client_id),
|key| crate::read_lock!(crate::store::get_shard(&store[db], key)).contains_key(key),
)
.refusal()
}
fn run_command(ctx: &mut Ctx, name: &str, started: std::time::Instant) -> Vec<u8> {
if let Some(refusal) = crate::commands::arity::check(name, &ctx.cmd) {
return refusal;
}
let repl_is_slave = ctx.repl_state.is_slave();
let mut routed = crate::cluster::routing::Routed::default();
{
use crate::cluster::routing::route_named;
if ctx.cluster.enabled && !ctx.bypass_cluster_check {
if name == "SELECT" && ctx.cmd.get(1).is_some_and(|db| *db != &b"0"[..]) {
return resp_error("ERR SELECT is not allowed in cluster mode");
}
let asking_flag = ctx.client_registry.get_asking(ctx.client_id);
routed = crate::cluster::routing::Routed::now(asking_flag);
let store_for_check = ctx.store;
let db = *ctx.selected_db;
let has_key_locally = |key: &[u8]| -> bool {
let shard = crate::store::get_shard(&store_for_check[db], key);
crate::read_lock!(shard).contains_key(key)
};
let registry = ctx.client_registry;
let client_id = ctx.client_id;
let decision = route_named(
name,
ctx.cmd.as_slice(),
ctx.cluster,
asking_flag,
|| registry.get_readonly(client_id),
has_key_locally,
);
if asking_flag {
ctx.client_registry.update(ctx.client_id, |info| {
info.asking = false;
});
}
if let Some(refusal) = decision.refusal() {
return refusal;
}
crate::cluster::routing::stall_for_test(name, ctx.cmd.as_slice());
}
}
#[cfg(feature = "lua")]
if crate::commands::lua::lua_server_busy_for_command(ctx.cmd.as_slice()) {
return busy_reply();
}
if repl_is_slave
&& !ctx.apply_replication
&& replication::is_denied_on_readonly_replica(name, &ctx.cmd)
{
return resp_error("READONLY You can't write against a read only replica.");
}
if !ctx.apply_replication
&& ctx.repl_state.min_replicas_to_write.load(Ordering::Relaxed) != 0
&& !matches!(
name,
"EVAL" | "EVALSHA" | "EVAL_RO" | "EVALSHA_RO" | "FCALL" | "FCALL_RO"
)
&& !crate::command_gate::alone_on_this_thread()
&& replication::refused_without_replicas(name, &ctx.cmd)
&& ctx.repl_state.lacks_good_replicas()
{
return resp_error(replication::NOREPLICAS);
}
let loading_replica = repl_is_slave
&& !ctx.apply_replication
&& ctx
.repl_state
.slave_sync_in_progress
.load(Ordering::Relaxed);
let loading_snapshot =
!ctx.apply_replication && crate::vector::SNAPSHOT_INDEX_REBUILD.load(Ordering::Relaxed);
if (loading_replica || loading_snapshot)
&& !replication::slave_command_allowed_during_loading(name)
{
return resp_error("LOADING KiviDB is loading the dataset into memory");
}
if crate::acl::RESTRICTED_CMD_CLIENTS.load(std::sync::atomic::Ordering::Relaxed) > 0
|| crate::acl::RESTRICTED_KEY_CLIENTS.load(std::sync::atomic::Ordering::Relaxed) > 0
{
let denied = ctx
.acl_store
.read()
.get(ctx.authenticated_user)
.and_then(|user| crate::acl::check_permission(user, name, ctx.cmd.as_slice()).err());
if let Some(denied) = denied {
if !crate::commands::server::is_command(name) {
return unknown_command(&ctx.cmd);
}
ctx.acl_log.record(
denied.reason(),
denied.object(),
ctx.authenticated_user,
&crate::acl::log_client_info(ctx.client_registry, ctx.client_id, ctx.peer_addr),
);
return resp_error(&denied.message(ctx.authenticated_user));
}
}
let over_limit = !repl_is_slave && !ctx.apply_replication && check_memory_limit();
let loads_functions = name == "FUNCTION"
&& ctx.cmd.get(1).is_some_and(|sub| {
sub.eq_ignore_ascii_case(b"LOAD") || sub.eq_ignore_ascii_case(b"RESTORE")
});
let needs_room = over_limit
&& (loads_functions
|| (replication::command_mutates_for_replication(name, &ctx.cmd)
&& !crate::eviction::allowed_when_out_of_memory(name)));
let writes_operation = replication::command_mutates_for_replication(name, &ctx.cmd);
let script = matches!(name, "EVAL" | "EVALSHA" | "FCALL");
let gated = (writes_operation && name != "MIGRATE" && name != "FT.DROPINDEX") || script;
if gated && name == "SELECT" {
first_select_of_another_database(ctx);
}
let ordered = gated && !ctx.apply_replication;
let keys_ordered = ordered
|| (gated
&& !crate::expiry::replaying()
&& (crate::field_expiry::any_watched() || tracks_field_ttls(name)));
let any_script = script || matches!(name, "EVAL_RO" | "EVALSHA_RO" | "FCALL_RO");
#[cfg(feature = "lua")]
let overrun = crate::commands::lua::running_script_is_over_its_time_limit;
#[cfg(not(feature = "lua"))]
let overrun = || false;
const SLICE: std::time::Duration = std::time::Duration::from_millis(10);
let tag_locks = crate::tag_locks::enabled();
let allowed_beside = any_script && crate::tag_locks::take_next_script_allowed();
let script_tag: Option<&[u8]> = if tag_locks && any_script {
crate::tag_locks::script_tag(&ctx.cmd)
} else {
None
};
let beside_others =
script_tag.is_some() && allowed_beside && !crate::command_gate::alone_on_this_thread();
#[cfg(debug_assertions)]
if gated && !crate::write_gate::held_by_this_thread() {
crate::pause::test_stall_before_the_gate(ctx.cmd.as_slice());
}
let gates = if crate::command_gate::skips(name, &ctx.cmd) {
Some((None, None))
} else if takes_the_gate_alone(
ctx.store,
*ctx.selected_db,
name,
&ctx.cmd,
any_script && !beside_others,
gated,
) {
crate::command_gate::enter_alone_unless(SLICE, overrun).map(|alone| (None, Some(alone)))
} else {
crate::command_gate::enter_unless(SLICE, overrun).map(|gate| (Some(gate), None))
};
let Some((_command_gate, _alone)) = gates else {
return busy_reply();
};
let nested = crate::write_gate::held_by_this_thread();
let mut _write_gate = gated.then(crate::write_gate::enter);
while gated && !nested && !ctx.apply_replication && crate::pause::writes_must_check(routed.at())
{
let handoff = crate::pause::handoff();
if !handoff
&& crate::pause::write_held_in_gate(ctx.cmd.as_slice())
&& !crate::commands::blocking::client_gone(ctx)
{
drop(_write_gate);
if routed.asking() {
ctx.client_registry
.update(ctx.client_id, |info| info.asking = true);
}
return crate::commands::blocking::hold_for_pause(ctx);
}
if !handoff
&& !(crate::pause::keys_moving()
&& crate::key_moves::names_a_moving_key(*ctx.selected_db, name, ctx.cmd.as_slice()))
{
if let Some(refusal) = routed_again_in_gate(ctx, name, routed) {
return refusal;
}
break;
}
_write_gate = None;
if handoff {
crate::pause::wait_out_handoff();
} else {
crate::key_moves::wait_until_moved(*ctx.selected_db, name, ctx.cmd.as_slice());
}
routed = crate::cluster::routing::Routed::now(false);
if ctx.cluster.enabled {
let store = ctx.store;
let db = *ctx.selected_db;
let decision = crate::cluster::routing::route_named(
name,
ctx.cmd.as_slice(),
ctx.cluster,
false,
|| false,
|key| {
handoff
|| crate::read_lock!(crate::store::get_shard(&store[db], key))
.contains_key(key)
},
);
if let Some(refusal) = decision.refusal() {
return refusal;
}
}
if ctx.repl_state.is_slave() && replication::is_denied_on_readonly_replica(name, &ctx.cmd) {
return resp_error("READONLY You can't write against a read only replica.");
}
_write_gate = Some(crate::write_gate::enter());
}
if over_limit {
let _evicting = crate::write_gate::enter();
let limit = crate::RUNTIME_MAXMEMORY.load(std::sync::atomic::Ordering::Relaxed);
let in_order = ordered || (!gated && !ctx.apply_replication);
if limit != 0 && !crate::eviction::make_room(ctx, limit, in_order) && needs_room {
log_throttled!(
60,
crate::loglevel::WARN,
"maxmemory ({} bytes) reached and nothing more can be evicted under \
maxmemory-policy {}: write commands are refused with OOM. Raise maxmemory, \
use an evicting policy such as allkeys-lru, or delete data",
crate::RUNTIME_MAXMEMORY.load(std::sync::atomic::Ordering::Relaxed),
crate::eviction::policy().name()
);
return crate::tracking::with_what_came_before(resp_error(
"OOM command not allowed when used memory > 'maxmemory'.",
));
}
}
let _script_tag = script_tag.map(|tag| {
if beside_others {
crate::tag_locks::lock_for_script(tag)
} else {
crate::tag_locks::hold_script_to(tag)
}
});
let _key_tags = if tag_locks
&& !any_script
&& !crate::command_gate::alone_on_this_thread()
&& !crate::tag_locks::in_script()
{
let keys = crate::keyspec::key_positions(name, &ctx.cmd);
crate::tag_locks::lock_keys(keys.iter().map(|pos| ctx.cmd[pos]))
} else {
None
};
let mut hash_beside_others = false;
let mut named: Option<crate::keyspec::Keys> = None;
let mut _write_order = if crate::command_gate::alone_on_this_thread() {
Some(crate::write_order::held_exclusively())
} else if keys_ordered
&& !replication::write_is_observed(ctx)
&& atomic_under_its_shard(ctx, name)
{
hash_beside_others = name.as_bytes()[0] == b'H';
Some(crate::write_order::lock_key_shared(
*ctx.selected_db,
ctx.cmd[1],
))
} else if keys_ordered
&& matches!(name, "MSET" | "MSETNX")
&& !replication::write_is_observed(ctx)
{
Some(order_of_pairs_shared(ctx))
} else if keys_ordered {
let keys = named.insert(crate::keyspec::key_positions(name, &ctx.cmd));
let here = *ctx.selected_db;
match database_written_too(ctx, name) {
Some(there) if there != here => Some(crate::write_order::lock_keys_in(
keys.iter()
.flat_map(|pos| [(here, ctx.cmd[pos]), (there, ctx.cmd[pos])]),
)),
_ => Some(crate::write_order::lock_keys(
here,
keys.iter().map(|pos| ctx.cmd[pos]),
)),
}
} else {
None
};
if hash_beside_others && !ctx.index_store.none() {
ask_again_for_an_index(ctx, &mut _write_order);
}
if gated && writes_operation {
expire_named_keys_first(ctx, name, named);
}
let hotkeys_started = hotkeys::active().then(std::time::Instant::now);
if crate::monitor::MONITOR_COUNT.load(std::sync::atomic::Ordering::Relaxed) > 0
&& !crate::commands::blocking::resuming(ctx)
&& !crate::commands::server::is_admin_command(name)
{
crate::monitor::feed(
ctx.monitor_registry,
&ctx.cmd,
*ctx.selected_db,
ctx.peer_addr,
);
}
let announce_new = writes_operation
&& crate::keyspace_events::KS_FLAGS.load(std::sync::atomic::Ordering::Relaxed)
& crate::keyspace_events::KS_NEW
!= 0;
let exists = |ctx: &Ctx, key: &[u8]| {
crate::read_lock!(crate::store::get_shard(&ctx.store[*ctx.selected_db], key))
.contains_key(key)
};
let absent: Vec<usize> = if announce_new {
crate::keyspec::key_positions(name, &ctx.cmd)
.iter()
.filter(|pos| !exists(ctx, ctx.cmd[*pos]))
.collect()
} else {
Vec::new()
};
let missed: Vec<usize> = if !writes_operation
&& crate::keyspace_events::KS_FLAGS.load(std::sync::atomic::Ordering::Relaxed)
& crate::keyspace_events::KS_KEY_MISS
!= 0
&& !matches!(name, "EXISTS" | "TYPE" | "TOUCH" | "OBJECT")
{
crate::keyspec::key_positions(name, &ctx.cmd)
.iter()
.filter(|pos| !exists(ctx, ctx.cmd[*pos]))
.collect()
} else {
Vec::new()
};
let replacing = if writes_operation
&& crate::keyspace_events::KS_FLAGS.load(std::sync::atomic::Ordering::Relaxed)
& (crate::keyspace_events::KS_OVERWRITTEN | crate::keyspace_events::KS_TYPE_CHANGED)
!= 0
{
replace_watch_begin(ctx, name)
} else {
None
};
let access = crate::eviction::recording().then(|| access_scope(name, started, &ctx.cmd));
let result = dispatch_command_handlers(ctx, name)
.or_else(|| lua::handle(ctx, name))
.unwrap_or_else(|| unknown_command(&ctx.cmd));
if access.is_some() && result.starts_with(b"-") {
used_on_error(ctx, name);
}
if access.is_some()
&& let Some(named) = crate::store::AccessScope::named_more_than_once()
{
let db = *ctx.selected_db;
for (key, times) in named {
let map = crate::read_lock!(crate::store::get_shard_of_bytes(&ctx.store[db], &key));
for _ in 0..times {
map.use_key(&key);
}
}
}
drop(access);
if let Some(watch) = replacing {
replace_watch_end(ctx, watch);
}
for pos in absent {
let key = ctx.cmd[pos];
if exists(ctx, key) {
crate::keyspace_events::notify(
ctx.pubsub,
*ctx.selected_db,
crate::keyspace_events::KS_NEW,
"new",
key,
);
}
}
for pos in missed {
crate::keyspace_events::notify(
ctx.pubsub,
*ctx.selected_db,
crate::keyspace_events::KS_KEY_MISS,
"keymiss",
ctx.cmd[pos],
);
}
if writes_operation
&& crate::keyspace_events::KS_FLAGS.load(std::sync::atomic::Ordering::Relaxed) != 0
&& !result.starts_with(b"-")
&& !crate::commands::blocking::parked(ctx)
{
for event in crate::keyspace_events::command_events(name, &ctx.cmd, &result) {
if let Some(key) = ctx.cmd.get(event.key) {
crate::keyspace_events::notify(
ctx.pubsub,
event.db.unwrap_or(*ctx.selected_db),
event.class,
&event.event,
key,
);
}
}
}
if crate::commands::blocking::parked(ctx) {
return result;
}
if let Some(started) = hotkeys_started {
hotkeys::record(ctx, name, result.len(), started.elapsed());
}
if crate::eviction::recording()
&& crate::eviction::used_after(is_script(name))
&& !asks_only(name)
{
let wrote = writes_operation && !result.starts_with(b"-");
for pos in crate::keyspec::key_positions(name, &ctx.cmd).iter() {
crate::eviction::used(ctx.store, *ctx.selected_db, ctx.cmd[pos], wrote);
}
}
write_side_effects(ctx, name, &result, writes_operation);
let result = if ctx.resp == 3 {
crate::resp::write::resp3_normalize_null(result)
} else {
result
};
crate::tracking::with_what_came_before(result)
}
#[inline]
pub(crate) fn apply_write_side_effects(ctx: &Ctx, name: &str, result: &[u8]) {
let writes_operation = replication::command_mutates_for_replication(name, &ctx.cmd);
write_side_effects(ctx, name, result, writes_operation);
}
#[cold]
#[inline(never)]
fn first_select_of_another_database(ctx: &Ctx) {
if let Some(db) = makes_the_switch(ctx) {
ctx.repl_state.note_database_selected(db);
}
}
fn makes_the_switch(ctx: &Ctx) -> Option<usize> {
if ctx.repl_state.several_databases.load(Ordering::Relaxed) || ctx.cmd.len() != 2 {
return None;
}
std::str::from_utf8(ctx.cmd[1])
.ok()
.and_then(|db| db.parse::<usize>().ok())
.filter(|db| *db != 0 && *db < ctx.config.databases)
}
fn changed_nothing(name: &str, cmd: &[&[u8]], result: &[u8]) -> bool {
let nil = result == b"$-1\r\n" || result == b"_\r\n";
let zero = result == b":0\r\n";
match name {
"SET" => nil && !set_wrote_answering_nil(cmd),
"SETNX" | "MSETNX" | "HSETNX" | "RENAMENX" | "PERSIST" | "EXPIRE" | "PEXPIRE"
| "EXPIREAT" | "PEXPIREAT" | "SADD" | "SREM" | "ZREM" | "HDEL" | "LREM" | "DEL"
| "UNLINK" | "COPY" | "MOVE" | "SMOVE" | "LPUSHX" | "RPUSHX" => zero,
"LINSERT" => zero || result == b":-1\r\n",
_ => popped_nothing(name, result),
}
}
fn set_wrote_answering_nil(cmd: &[&[u8]]) -> bool {
let (mut get, mut needs_the_key) = (false, false);
let mut i = 3;
while i < cmd.len() {
let option = cmd[i];
let is = |name: &[u8]| option.eq_ignore_ascii_case(name);
if is(b"GET") {
get = true;
} else if is(b"XX") {
needs_the_key = true;
} else if is(b"IFEQ") || is(b"IFDEQ") {
needs_the_key = true;
i += 1;
} else if is(b"IFNE")
|| is(b"IFDNE")
|| is(b"EX")
|| is(b"PX")
|| is(b"EXAT")
|| is(b"PXAT")
{
i += 1;
}
i += 1;
}
get && !needs_the_key
}
#[inline]
fn expire_named_keys_first(ctx: &Ctx, name: &str, named: Option<crate::keyspec::Keys>) {
if ctx.apply_replication || ctx.repl_state.is_slave() || !replication::write_is_observed(ctx) {
return;
}
if name == "SET" && !set_has_a_condition(&ctx.cmd) {
return;
}
let db = *ctx.selected_db;
let named = named.unwrap_or_else(|| crate::keyspec::key_positions(name, &ctx.cmd));
for pos in named.iter() {
let key = ctx.cmd[pos];
if crate::commands::helpers::is_expired(ctx.store, db, key) {
crate::commands::helpers::delete_key_if_expired(ctx.store, db, key);
}
}
}
fn set_has_a_condition(cmd: &[&[u8]]) -> bool {
cmd.iter().skip(3).any(|arg| {
arg.eq_ignore_ascii_case(b"NX")
|| arg.eq_ignore_ascii_case(b"XX")
|| (arg.len() >= 4 && arg[..2].eq_ignore_ascii_case(b"IF"))
})
}
#[inline]
fn propagates_nothing(name: &str, cmd: &[&[u8]], result: &[u8]) -> bool {
result.len() <= 5
&& matches!(result.first(), Some(b':' | b'$' | b'_' | b'*' | b'~'))
&& changed_nothing(name, cmd, result)
}
#[inline]
fn popped_nothing(name: &str, result: &[u8]) -> bool {
matches!(
result,
b"$-1\r\n" | b"*-1\r\n" | b"_\r\n" | b"*0\r\n" | b"~0\r\n"
) && matches!(
name,
"LPOP"
| "RPOP"
| "LMPOP"
| "LMOVE"
| "RPOPLPUSH"
| "LMOVEM"
| "ZPOPMIN"
| "ZPOPMAX"
| "ZMPOP"
| "SPOP"
| "BLPOP"
| "BRPOP"
| "BLMPOP"
| "BLMOVE"
| "BRPOPLPUSH"
| "BLMOVEM"
| "BZPOPMIN"
| "BZPOPMAX"
| "BZMPOP"
)
}
fn touch_swapped_watches(ctx: &Ctx) {
let db = |i: usize| {
ctx.cmd
.get(i)
.and_then(|arg| std::str::from_utf8(arg).ok())
.and_then(|arg| arg.parse::<usize>().ok())
};
let (Some(db1), Some(db2)) = (db(1), db(2)) else {
return;
};
if db1 == db2 {
return;
}
let present = |db: usize, key: &[u8]| {
ctx.store.get(db).is_some_and(|shards| {
crate::read_lock!(crate::store::get_shard(shards, key)).contains_key(key)
}) && !crate::commands::helpers::is_expired(ctx.store, db, key)
};
for (watched, other) in [(db1, db2), (db2, db1)] {
ctx.watch_registry
.notify_existing(Some(watched), &|_, key| {
present(watched, key) || present(other, key)
});
}
}
fn notify_watchers(ctx: &Ctx, name: &str, result: &[u8]) {
if !ctx.watch_registry.has_watchers() {
return;
}
notify_watchers_of_changed_keys(ctx, name, result);
}
#[cold]
fn notify_watchers_of_changed_keys(ctx: &Ctx, name: &str, result: &[u8]) {
let db = *ctx.selected_db;
match name {
"FLUSHDB" | "FLUSHALL" => return,
"SWAPDB" => return touch_swapped_watches(ctx),
"MOVE" => {
if result == b":1\r\n" {
ctx.watch_registry.notify(db, ctx.cmd[1]);
if let Some(to) = ctx.cmd.get(2).and_then(|to| parse_db(to)) {
ctx.watch_registry.notify(to, ctx.cmd[1]);
}
}
return;
}
"COPY" => {
if let Some(to) = copy_db(&ctx.cmd) {
if result == b":1\r\n" {
ctx.watch_registry.notify(to, ctx.cmd[2]);
}
return;
}
}
_ => {}
}
let known = for_each_changed_key(ctx, name, result, |key| ctx.watch_registry.notify(db, key));
if !known && !changed_nothing(name, &ctx.cmd, result) {
if let Some(key) = ctx.cmd.get(1) {
ctx.watch_registry.notify(db, key);
}
}
}
fn parse_db(arg: &[u8]) -> Option<usize> {
std::str::from_utf8(arg).ok()?.parse().ok()
}
fn copy_db(cmd: &[&[u8]]) -> Option<usize> {
let at = cmd
.iter()
.skip(3)
.position(|arg| arg.eq_ignore_ascii_case(b"DB"))?;
parse_db(cmd.get(3 + at + 1)?)
}
#[cold]
fn for_each_changed_key(
ctx: &Ctx,
name: &str,
result: &[u8],
mut changed: impl FnMut(&[u8]),
) -> bool {
let keys = crate::keyspec::key_positions(name, &ctx.cmd);
let Some(first) = keys.first() else {
return false;
};
if changed_nothing(name, &ctx.cmd, result) || leaves_the_stream_signalled_as_is(name, &ctx.cmd)
{
return true;
}
let db = *ctx.selected_db;
let mut tell = |key: &[u8]| {
if !crate::watch::is_unchanged(db, key) {
changed(key);
}
};
if keys.iter().nth(1).is_none() {
tell(ctx.cmd[first]);
return true;
}
if let Some(popped) = popped_from(name, result)
&& let Some(pos) = keys.iter().find(|&pos| ctx.cmd[pos] == popped)
{
tell(ctx.cmd[pos]);
return true;
}
let read_only = read_only_key_positions(&ctx.cmd);
for pos in keys.iter() {
if !read_only.contains(&pos) {
tell(ctx.cmd[pos]);
}
}
true
}
fn leaves_the_stream_signalled_as_is(name: &str, cmd: &[&[u8]]) -> bool {
match name {
"XREADGROUP" | "XACK" | "XCLAIM" | "XAUTOCLAIM" | "XSETID" => true,
"XGROUP" => {
!(cmd
.get(1)
.is_some_and(|sub| sub.eq_ignore_ascii_case(b"CREATE"))
&& cmd.iter().any(|arg| arg.eq_ignore_ascii_case(b"MKSTREAM")))
}
_ => false,
}
}
fn popped_from<'a>(name: &str, result: &'a [u8]) -> Option<&'a [u8]> {
if !matches!(
name,
"BLPOP" | "BRPOP" | "BZPOPMIN" | "BZPOPMAX" | "LMPOP" | "ZMPOP" | "BLMPOP" | "BZMPOP"
) {
return None;
}
let rest = result.strip_prefix(b"*")?;
let rest = &rest[rest.iter().position(|&b| b == b'\n')? + 1..];
let rest = rest.strip_prefix(b"$")?;
let digits = rest.iter().position(|&b| b == b'\r')?;
let len: usize = std::str::from_utf8(&rest[..digits]).ok()?.parse().ok()?;
rest.get(digits + 2..digits + 2 + len)
}
fn read_only_key_positions(cmd: &[&[u8]]) -> Vec<usize> {
match crate::commands::key_specs::keys_of(cmd) {
Some(Ok(keys)) => keys
.into_iter()
.filter(|(_, flags)| flags.starts_with("RO"))
.map(|(pos, _)| pos)
.collect(),
_ => Vec::new(),
}
}
#[inline]
fn atomic_under_its_shard(ctx: &Ctx, name: &str) -> bool {
if ctx.cmd.len() < 2 {
return false;
}
match name {
"SET" | "INCR" | "DECR" | "INCRBY" | "DECRBY" | "INCRBYFLOAT" | "LPUSH" | "RPUSH"
| "SADD" | "ZADD" | "ZINCRBY" | "PFADD" => true,
"HSET" | "HMSET" | "HSETNX" | "HINCRBY" | "HINCRBYFLOAT" => ctx.index_store.none(),
_ => false,
}
}
#[cold]
#[inline(never)]
fn ask_again_for_an_index(ctx: &Ctx, order: &mut Option<crate::write_order::OrderGuard>) {
*order = None;
*order = Some(crate::write_order::lock_keys(
*ctx.selected_db,
std::iter::once(ctx.cmd[1]),
));
}
fn can_leave_a_key_empty(name: &str) -> bool {
matches!(
name,
"LPOP"
| "RPOP"
| "LMPOP"
| "BLPOP"
| "BRPOP"
| "BLMPOP"
| "LREM"
| "LTRIM"
| "RPOPLPUSH"
| "LMOVE"
| "BLMOVE"
| "BRPOPLPUSH"
| "LMOVEM"
| "BLMOVEM"
| "SPOP"
| "SREM"
| "SMOVE"
| "SDIFFSTORE"
| "SINTERSTORE"
| "SUNIONSTORE"
| "ZADD"
| "ZINCRBY"
| "ZREM"
| "ZPOPMIN"
| "ZPOPMAX"
| "BZPOPMIN"
| "BZPOPMAX"
| "ZMPOP"
| "BZMPOP"
| "ZREMRANGEBYSCORE"
| "ZREMRANGEBYRANK"
| "ZREMRANGEBYLEX"
| "ZRANGESTORE"
| "ZDIFFSTORE"
| "ZINTERSTORE"
| "ZUNIONSTORE"
| "GEOSEARCHSTORE"
| "GEORADIUS"
| "GEORADIUSBYMEMBER"
| "SORT"
| "HDEL"
| "HGETDEL"
| "HGETEX"
| "HSETEX"
| "HEXPIRE"
| "HPEXPIRE"
| "HEXPIREAT"
| "HPEXPIREAT"
| "VREM"
)
}
fn drop_if_empty(ctx: &Ctx, db: usize, key: &[u8]) -> bool {
let shard = crate::store::get_shard(&ctx.store[db], key);
if !crate::read_lock!(shard)
.get(key)
.is_some_and(|value| value.is_empty_collection())
{
return false;
}
let removed = {
let mut map = crate::write_lock!(shard);
let still_empty = map
.get(key)
.is_some_and(|value| value.is_empty_collection());
still_empty && map.remove(key).is_some()
};
if removed {
crate::vector::maybe_unindex(ctx.index_store, db, key);
crate::keyspace_events::notify(
ctx.pubsub,
db,
crate::keyspace_events::KS_GENERIC,
"del",
key,
);
}
removed
}
#[inline]
fn database_written_too(ctx: &Ctx, name: &str) -> Option<usize> {
if !matches!(name, "MOVE" | "COPY") {
return None;
}
let number = |i: usize| {
ctx.cmd
.get(i)
.and_then(|a| std::str::from_utf8(a).ok())
.and_then(|s| s.parse::<usize>().ok())
};
if name == "MOVE" {
return number(2);
}
(3..ctx.cmd.len())
.find(|&i| ctx.cmd[i].eq_ignore_ascii_case(b"DB"))
.and_then(|i| number(i + 1))
}
fn reindex_copied(ctx: &Ctx, name: &str) {
use crate::vector::Write;
let here = *ctx.selected_db;
let number = |i: usize| {
ctx.cmd
.get(i)
.and_then(|a| std::str::from_utf8(a).ok())
.and_then(|s| s.parse::<usize>().ok())
};
if name == "MOVE" {
if let (Some(key), Some(to)) = (ctx.cmd.get(1), number(2)) {
crate::vector::reindex_key(ctx.index_store, ctx.store, here, key, Write::Whole);
crate::vector::reindex_key(ctx.index_store, ctx.store, to, key, Write::Whole);
}
return;
}
let Some(key) = ctx.cmd.get(2) else {
return;
};
let mut to = here;
let mut i = 3;
while i < ctx.cmd.len() {
if ctx.cmd[i].eq_ignore_ascii_case(b"DB") {
to = number(i + 1).unwrap_or(here);
i += 1;
}
i += 1;
}
crate::vector::reindex_key(ctx.index_store, ctx.store, to, key, Write::Whole);
}
#[inline]
fn tracks_field_ttls(name: &str) -> bool {
matches!(name.as_bytes().first(), Some(b'H' | b'R' | b'C' | b'M'))
&& matches!(
name,
"HEXPIRE"
| "HPEXPIRE"
| "HEXPIREAT"
| "HPEXPIREAT"
| "HSETEX"
| "HGETEX"
| "HIMPORT"
| "RENAME"
| "RENAMENX"
| "RESTORE"
| "COPY"
| "MOVE"
)
}
fn settle_written_keys(ctx: &Ctx, name: &str) {
use crate::vector::Write;
let first = name.as_bytes().first().copied().unwrap_or(0);
let named_below = matches!(first, b'H' | b'R' | b'C' | b'M' | b'J') || name == "SWAPDB";
match if named_below { name } else { "" } {
"HEXPIRE" | "HPEXPIRE" | "HEXPIREAT" | "HPEXPIREAT" | "HSETEX" | "HGETEX" | "HIMPORT"
| "RENAME" | "RENAMENX" | "RESTORE" => {
let how = match name {
"RENAME" | "RENAMENX" | "RESTORE" => Some(Write::Whole),
"HIMPORT" => None,
_ => Some(Write::Refresh),
};
let db = *ctx.selected_db;
for pos in crate::keyspec::key_positions(name, &ctx.cmd).iter() {
let key = ctx.cmd[pos];
crate::field_expiry::track_key(ctx.store, db, key);
if let Some(how) = how {
crate::vector::reindex_key(ctx.index_store, ctx.store, db, key, how);
}
}
}
"COPY" | "MOVE" => {
for pos in crate::keyspec::key_positions(name, &ctx.cmd).iter() {
for db in 0..ctx.store.len() {
crate::field_expiry::track_key(ctx.store, db, ctx.cmd[pos]);
}
}
reindex_copied(ctx, name);
}
"HDEL" | "HINCRBY" | "HINCRBYFLOAT" | "HSETNX" | "HGETDEL" => {
for pos in crate::keyspec::key_positions(name, &ctx.cmd).iter() {
let db = *ctx.selected_db;
crate::vector::reindex_key(
ctx.index_store,
ctx.store,
db,
ctx.cmd[pos],
Write::Refresh,
);
}
}
"SWAPDB" => {
crate::field_expiry::rescan(ctx.store);
crate::vector::rebuild_indexes(ctx.index_store, ctx.store);
}
_ if name.starts_with("JSON.") => {
for pos in crate::keyspec::key_positions(name, &ctx.cmd).iter() {
crate::vector::reindex_json_key(
ctx.index_store,
ctx.store,
*ctx.selected_db,
ctx.cmd[pos],
);
}
}
_ => {}
}
let may_be_empty = can_leave_a_key_empty(name);
let waiters = ctx.wait_table.has_signal_waiters();
if waiters && matches!(name, "FLUSHALL" | "FLUSHDB" | "SWAPDB") {
ctx.wait_table.notify_all_signals();
return;
}
if !may_be_empty && !waiters {
return;
}
let db = *ctx.selected_db;
for pos in crate::keyspec::key_positions(name, &ctx.cmd).iter() {
let key = ctx.cmd[pos];
if may_be_empty && drop_if_empty(ctx, db, key) {
continue;
}
if waiters {
ctx.wait_table.notify_signal(key);
}
}
}
#[inline]
fn write_side_effects(ctx: &Ctx, name: &str, result: &[u8], writes_operation: bool) {
side_effects(ctx, name, result, writes_operation);
crate::watch::clear_unchanged();
}
fn side_effects(ctx: &Ctx, name: &str, result: &[u8], writes_operation: bool) {
let is_mutating_ok_write = writes_operation && !result.starts_with(b"-");
if is_mutating_ok_write {
settle_written_keys(ctx, name);
if !ctx.apply_replication {
ctx.repl_state.note_local_write();
}
}
if is_mutating_ok_write && !ctx.skip_write_side_effects {
if replication::write_is_observed(ctx) && !propagates_nothing(name, &ctx.cmd, result) {
for parts in
replication::script_feed::commands_for_propagation(ctx, name, &ctx.cmd, result)
{
replication::replicate_one_write(ctx, &parts);
}
}
notify_watchers(ctx, name, result);
if (name != "XREADGROUP" || replication::script_feed::effects_changed_data())
&& !propagates_nothing(name, &ctx.cmd, result)
{
crate::stats::record_rdb_change();
}
}
if !writes_operation
&& matches!(name, "PUBLISH" | "SPUBLISH")
&& !ctx.cluster.enabled
&& !ctx.apply_replication
&& !ctx.repl_state.is_slave()
&& !result.starts_with(b"-")
&& ctx.repl_state.connected_replicas.load(Ordering::Relaxed) > 0
{
let parts: Vec<Vec<u8>> = ctx.cmd.iter().map(|b| b.to_vec()).collect();
let payload = crate::resp::write::encode_resp_command(&parts);
replication::propagate_in_order(ctx.repl_state, ctx.hub_tx, payload);
}
track(ctx, name, result, is_mutating_ok_write, writes_operation);
}
#[inline(always)]
fn track(ctx: &Ctx, name: &str, result: &[u8], wrote: bool, is_write: bool) {
if crate::tracking::TRACKING_CLIENT_COUNT.load(std::sync::atomic::Ordering::Relaxed) == 0 {
return;
}
track_for_clients(ctx, name, result, wrote, is_write);
}
#[cold]
fn track_for_clients(ctx: &Ctx, name: &str, result: &[u8], wrote: bool, is_write: bool) {
if matches!(
name,
"EVAL" | "EVALSHA" | "EVAL_RO" | "EVALSHA_RO" | "FCALL" | "FCALL_RO" | "CLIENT"
) {
return;
}
if wrote {
if matches!(name, "FLUSHALL" | "FLUSHDB") {
crate::tracking::invalidate_everything(
ctx.tracking_table,
ctx.client_registry,
Some(ctx.client_id),
);
return;
}
for_each_changed_key(ctx, name, result, |key| {
invalidate_tracked_key(ctx, key, true)
});
return;
}
if is_write {
return;
}
let keys = crate::keyspec::key_positions(name, &ctx.cmd);
if keys.is_empty() {
return;
}
let mut should_register = false;
ctx.client_registry.update(ctx.client_id, |info| {
if !info.tracking || info.tracking_bcast {
return;
}
let caching_next = info.tracking_caching_next.take();
should_register = if info.tracking_optin {
caching_next == Some(true)
} else if info.tracking_optout {
caching_next != Some(false)
} else {
true
};
});
if !should_register {
return;
}
for pos in keys.iter() {
let dropped = ctx.tracking_table.register(ctx.cmd[pos], ctx.client_id);
crate::tracking::tell_dropped(ctx.client_registry, dropped, Some(ctx.client_id));
}
}
pub(crate) fn invalidate_tracked_key(ctx: &Ctx, key: &[u8], by_client: bool) {
if crate::tracking::TRACKING_CLIENT_COUNT.load(std::sync::atomic::Ordering::Relaxed) == 0 {
return;
}
let invalidate = || {
crate::tracking::invalidate(
ctx.tracking_table,
ctx.client_registry,
key,
by_client.then_some(ctx.client_id),
Some(ctx.client_id),
);
};
if by_client {
invalidate();
} else {
crate::tracking::before_the_reply(invalidate);
}
}
#[cfg(test)]
mod applied_gate_tests {
use super::applied_takes_the_gate_alone;
fn takes(cmd: &[&str]) -> bool {
let store = crate::store::new_store(2);
let cmd: Vec<&[u8]> = cmd.iter().map(|a| a.as_bytes()).collect();
applied_takes_the_gate_alone(&store, 0, &cmd)
}
#[test]
fn the_applier_takes_the_gate_alone_as_run_command_does() {
assert!(!takes(&["SET", "k", "v"]));
assert!(!takes(&["HSET", "h", "f", "v"]));
assert!(!takes(&["MSET", "a", "1", "b", "2"]));
assert!(!takes(&["PING"]));
assert!(takes(&["EVAL", "return 1", "0"]));
assert!(takes(&["EVAL_RO", "return 1", "0"]));
assert!(takes(&["FLUSHDB"]));
assert!(takes(&["flushall", "async"]));
assert!(takes(&["SWAPDB", "0", "1"]));
let shards = crate::store::new_store(1)[0].len();
let of = |key: &str| crate::store::shard_index(shards, key);
let other = (0..)
.map(|i| format!("b{i}"))
.find(|b| of(b) != of("a"))
.unwrap();
let same = (0..)
.map(|i| format!("c{i}"))
.find(|c| of(c) == of("a"))
.unwrap();
assert!(takes(&["COPY", "a", &other, "REPLACE"]));
assert!(!takes(&["COPY", "a", &same, "REPLACE"]));
}
}
#[cfg(test)]
mod noscript_tests {
use super::not_allowed_from_script;
#[test]
fn the_noscript_commands_are_redis_s() {
let redis: &[(&str, &[&str])] = &[
(
"ACL",
&[
"CAT", "DELUSER", "DRYRUN", "GENPASS", "GETUSER", "LIST", "LOAD", "LOG",
"SAVE", "SETUSER", "USERS", "WHOAMI",
],
),
("BACKUP", &["ABORT", "CLEANUP", "SEAL", "START"]),
(
"CLIENT",
&[
"CACHING",
"GETNAME",
"GETREDIR",
"ID",
"INFO",
"KILL",
"LIST",
"NO-EVICT",
"NO-TOUCH",
"PAUSE",
"REPLY",
"SETINFO",
"SETNAME",
"TRACKING",
"TRACKINGINFO",
"UNBLOCK",
"UNPAUSE",
],
),
("CLUSTER", &["RESET"]),
("CONFIG", &["GET", "RESETSTAT", "REWRITE", "SET"]),
(
"FUNCTION",
&[
"DELETE", "DUMP", "FLUSH", "KILL", "LIST", "LOAD", "RESTORE", "STATS",
],
),
("HOTKEYS", &["GET", "RESET", "START", "STOP"]),
(
"LATENCY",
&["DOCTOR", "GRAPH", "HISTOGRAM", "HISTORY", "LATEST", "RESET"],
),
("MODULE", &["LIST", "LOAD", "LOADEX", "UNLOAD"]),
("SCRIPT", &["DEBUG", "EXISTS", "FLUSH", "KILL", "LOAD"]),
];
for (name, subs) in redis {
for sub in *subs {
assert!(
not_allowed_from_script(name, Some(sub.as_bytes())),
"{name} {sub}"
);
let lower = sub.to_ascii_lowercase();
assert!(not_allowed_from_script(name, Some(lower.as_bytes())));
}
assert!(!not_allowed_from_script(name, Some(b"HELP")), "{name} HELP");
}
for name in [
"AUTH",
"BGREWRITEAOF",
"BGSAVE",
"DEBUG",
"DISCARD",
"EVAL",
"EVALSHA",
"EVALSHA_RO",
"EVAL_RO",
"EXEC",
"FAILOVER",
"FCALL",
"FCALL_RO",
"HELLO",
"MONITOR",
"MULTI",
"PSUBSCRIBE",
"PSYNC",
"PUNSUBSCRIBE",
"QUIT",
"REPLCONF",
"REPLICAOF",
"RESET",
"ROLE",
"SAVE",
"SHUTDOWN",
"SLAVEOF",
"SSUBSCRIBE",
"SUBSCRIBE",
"SUNSUBSCRIBE",
"SYNC",
"UNSUBSCRIBE",
"UNWATCH",
"WATCH",
] {
assert!(not_allowed_from_script(name, None), "{name}");
}
for (name, sub) in [
("GET", None),
("SET", None),
("PUBLISH", None),
("INFO", None),
("BACKUP", Some(&b"LIST"[..])),
("BACKUP", Some(b"STATUS")),
("CLUSTER", Some(b"KEYSLOT")),
("CLUSTER", Some(b"NODES")),
("OBJECT", Some(b"FREQ")),
("MEMORY", Some(b"USAGE")),
] {
assert!(!not_allowed_from_script(name, sub), "{name} {sub:?}");
}
for sub in [
"SETSLOT",
"FAILOVER",
"MEET",
"FORGET",
"ADDSLOTS",
"MIGRATION",
] {
assert!(
not_allowed_from_script("CLUSTER", Some(sub.as_bytes())),
"{sub}"
);
}
}
}
#[cfg(test)]
mod replica_loading_gate_tests {
use super::execute_command;
use crate::commands::ctx::{Ctx, NoopAofSender};
use crate::config::Config;
use crate::replication::ReplState;
use parking_lot::RwLock;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Instant;
fn run_as_slave(repl_state: &Arc<ReplState>, cmd: Vec<Vec<u8>>, apply_stream: bool) -> Vec<u8> {
let store = crate::store::new_store(1);
let lastsave = Arc::new(RwLock::new(0i64));
let (hub_tx, mut hub_rx) =
tokio::sync::mpsc::unbounded_channel::<crate::replication::HubMsg>();
tokio::spawn(async move { while hub_rx.recv().await.is_some() {} });
let config = Arc::new(Config::default_replica());
let started_at = Instant::now();
let index_store = crate::vector::new_index_store();
let dict_store = crate::vector::new_dict_store();
let wait_table = Arc::new(crate::wait_table::WaitTable::new());
let ts_index = crate::store::new_ts_index();
let pubsub = crate::pubsub::PubSubHub::new();
let acl_store = crate::acl::new_acl_store("");
let acl_log = crate::acl::new_acl_log();
let slowlog = crate::slowlog::new_slowlog(u64::MAX, 0);
let latency = crate::latency::new_latency_tracker();
let (compaction_tx, compaction_rx) = crate::vector::new_compaction_channel();
drop(compaction_rx);
let cluster = Arc::new(crate::cluster::ClusterState::new_disabled());
let client_registry = crate::client_registry::new_client_registry();
let monitor_registry = crate::monitor::new_monitor_registry();
let tracking_table = crate::tracking::new_tracking_table();
let mut selected_db = 0usize;
let peer = "127.0.0.1:1".to_string();
execute_command(Ctx {
cmd: cmd.iter().map(|v| v.as_slice()).collect(),
store: &store,
lastsave: &lastsave,
selected_db: &mut selected_db,
aof_tx: &NoopAofSender,
aof_enabled: false,
config: &config,
started_at: &started_at,
index_store: &index_store,
dict_store: &dict_store,
wait_table: &wait_table,
ts_index: &ts_index,
pubsub: &pubsub,
hub_tx: &hub_tx,
repl_state,
watch_registry: &crate::watch::NoopWatchRegistry,
client_id: 0,
client_registry: &client_registry,
resp: 2,
acl_store: &acl_store,
acl_log: &acl_log,
slowlog: &slowlog,
latency: &latency,
compaction_tx: &compaction_tx,
cluster: &cluster,
bypass_cluster_check: false,
apply_replication: apply_stream,
skip_write_side_effects: false,
peer_addr: peer.as_str(),
monitor_registry: &monitor_registry,
authenticated_user: "default",
tracking_table: &tracking_table,
blocking: None,
})
}
#[tokio::test]
async fn slave_get_returns_loading_while_slave_sync_in_progress() {
let repl_state = Arc::new(ReplState::new_master());
repl_state.become_slave();
repl_state
.slave_sync_in_progress
.store(true, Ordering::Relaxed);
let out = run_as_slave(&repl_state, vec![b"GET".to_vec(), b"x".to_vec()], false);
assert!(
String::from_utf8_lossy(&out).starts_with("-LOADING"),
"got {}",
String::from_utf8_lossy(&out)
);
}
#[tokio::test]
async fn slave_ping_allowed_while_slave_sync_in_progress() {
let repl_state = Arc::new(ReplState::new_master());
repl_state.become_slave();
repl_state
.slave_sync_in_progress
.store(true, Ordering::Relaxed);
let out = run_as_slave(&repl_state, vec![b"PING".to_vec()], false);
assert!(
String::from_utf8_lossy(&out).starts_with("+PONG")
|| String::from_utf8_lossy(&out).starts_with('$'),
"expected PONG-compatible reply, got {}",
String::from_utf8_lossy(&out)
);
}
#[tokio::test]
async fn apply_replication_bypasses_loading_gate_for_stream_applier() {
let repl_state = Arc::new(ReplState::new_master());
repl_state.become_slave();
repl_state
.slave_sync_in_progress
.store(true, Ordering::Relaxed);
let out = run_as_slave(
&repl_state,
vec![b"SET".to_vec(), b"stream-key".to_vec(), b"1".to_vec()],
true,
);
assert!(
!String::from_utf8_lossy(&out).starts_with("-LOADING"),
"applier must not hit LOADING gate, got {}",
String::from_utf8_lossy(&out)
);
}
}
#[cfg(test)]
mod changed_nothing_tests {
use super::*;
fn cmd(args: &[&'static str]) -> Vec<&'static [u8]> {
args.iter().map(|&a| a.as_bytes()).collect()
}
#[test]
fn a_set_that_answered_nil_wrote_only_with_get_and_a_condition_a_missing_key_meets() {
let wrote = |args: &[&'static str]| set_wrote_answering_nil(&cmd(args));
assert!(wrote(&["SET", "k", "v", "GET"]));
assert!(wrote(&["SET", "k", "v", "NX", "GET"]));
assert!(wrote(&["SET", "k", "v", "GET", "NX"]));
assert!(wrote(&["SET", "k", "v", "IFNE", "x", "GET"]));
assert!(wrote(&[
"SET",
"k",
"v",
"IFDNE",
"0123456789abcdef",
"GET"
]));
assert!(wrote(&["SET", "k", "v", "EX", "10", "GET"]));
assert!(wrote(&["SET", "k", "v", "IFNE", "XX", "GET"]));
assert!(wrote(&["set", "k", "v", "ifne", "IFEQ", "get"]));
assert!(!wrote(&["SET", "k", "v", "XX", "GET"]));
assert!(!wrote(&["SET", "k", "v", "IFEQ", "x", "GET"]));
assert!(!wrote(&[
"SET",
"k",
"v",
"IFDEQ",
"0123456789abcdef",
"GET"
]));
assert!(!wrote(&["SET", "k", "v", "NX"]));
assert!(!wrote(&["SET", "k", "v", "IFNE", "GET"]));
assert!(!wrote(&["SET", "k", "v", "IFEQ", "GET"]));
assert!(!wrote(&["SET", "k", "v", "PX", "100", "XX"]));
}
#[test]
fn replies_that_change_nothing() {
let nothing = |args: &[&'static str], reply: &[u8]| {
let cmd = cmd(args);
assert_eq!(
changed_nothing(&args[0].to_ascii_uppercase(), &cmd, reply),
propagates_nothing(&args[0].to_ascii_uppercase(), &cmd, reply),
"{args:?}"
);
changed_nothing(&args[0].to_ascii_uppercase(), &cmd, reply)
};
assert!(nothing(&["SMOVE", "a", "b", "m"], b":0\r\n"));
assert!(!nothing(&["SMOVE", "a", "b", "m"], b":1\r\n"));
assert!(nothing(&["LPUSHX", "l", "x"], b":0\r\n"));
assert!(nothing(&["RPUSHX", "l", "x"], b":0\r\n"));
assert!(!nothing(&["RPUSHX", "l", "x"], b":1\r\n"));
assert!(nothing(&["LINSERT", "l", "BEFORE", "p", "x"], b":0\r\n"));
assert!(nothing(&["LINSERT", "l", "BEFORE", "p", "x"], b":-1\r\n"));
assert!(!nothing(&["LINSERT", "l", "BEFORE", "p", "x"], b":3\r\n"));
assert!(nothing(&["PERSIST", "k"], b":0\r\n"));
assert!(nothing(&["SET", "k", "v", "XX"], b"$-1\r\n"));
assert!(nothing(&["SET", "k", "v", "IFEQ", "x"], b"_\r\n"));
assert!(!nothing(&["SET", "k", "v", "NX", "GET"], b"$-1\r\n"));
assert!(!nothing(&["SET", "k", "v"], b"+OK\r\n"));
assert!(nothing(&["LPOP", "l"], b"$-1\r\n"));
assert!(!nothing(&["SADD", "s", "a"], b":1\r\n"));
assert!(!nothing(&["INCRBY", "n", "-1"], b":0\r\n"));
}
#[test]
fn only_a_set_with_a_condition_looks_for_its_key_first() {
let conditional = |args: &[&'static str]| set_has_a_condition(&cmd(args));
assert!(!conditional(&["SET", "k", "v"]));
assert!(!conditional(&["SET", "k", "v", "EX", "10"]));
assert!(!conditional(&["SET", "k", "v", "KEEPTTL", "GET"]));
assert!(!conditional(&["SET", "k", "NX"]));
assert!(conditional(&["SET", "k", "v", "NX"]));
assert!(conditional(&["SET", "k", "v", "xx", "PX", "5"]));
assert!(conditional(&["SET", "k", "v", "IFEQ", "old"]));
assert!(conditional(&["SET", "k", "v", "ifdne", "0123456789abcdef"]));
}
}