use std::sync::Arc;
use std::sync::atomic::Ordering;
pub static WATCHED_EXEC: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
const BUSY: &str =
"BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.";
fn busy(cmd: &[&[u8]]) -> bool {
#[cfg(feature = "lua")]
{
crate::commands::lua::lua_server_busy_for_command(cmd)
}
#[cfg(not(feature = "lua"))]
{
let _ = cmd;
false
}
}
pub fn queue_refusal(name: &str, cmd: &[&[u8]]) -> Option<Vec<u8>> {
if !crate::commands::server::is_command(name) {
return Some(crate::commands::handler::unknown_command(cmd));
}
if let Some(wrong_number) = crate::commands::arity::check(name, cmd) {
return Some(wrong_number);
}
if not_allowed_in_multi(name) {
return Some(crate::resp::write::resp_error(NOT_IN_MULTI));
}
if busy(cmd) {
return Some(crate::resp::write::resp_error(BUSY));
}
no_room(name, cmd).then(|| crate::resp::write::resp_error(OOM))
}
const OOM: &str = "OOM command not allowed when used memory > 'maxmemory'.";
pub const NOT_IN_MULTI: &str = "ERR Command not allowed inside a transaction";
pub fn not_allowed_in_multi(name: &str) -> bool {
matches!(name, "SAVE" | "SHUTDOWN" | "SYNC" | "PSYNC")
}
pub struct InExec<'a> {
pub acl_store: &'a crate::acl::AclStore,
pub acl_log: &'a crate::acl::SharedAclLog,
pub user: &'a str,
pub peer_addr: &'a str,
pub client_registry: &'a crate::client_registry::ClientRegistry,
pub client_id: u64,
pub repl_state: &'a crate::replication::ReplState,
pub wait_targets: Option<&'a [(Arc<crate::replication::ReplicaProgress>, u64)]>,
}
pub fn queues_wait(queue: &[Vec<Vec<u8>>]) -> bool {
queue.iter().any(|queued| {
queued
.first()
.is_some_and(|name| name.eq_ignore_ascii_case(b"WAIT"))
})
}
pub fn connection_reply_in_exec(name: &str, cmd: &[&[u8]], env: &InExec) -> Option<Vec<u8>> {
if !matches!(name, "UNWATCH" | "MONITOR" | "WAIT" | "WAITAOF") {
return None;
}
if crate::acl::RESTRICTED_CMD_CLIENTS.load(Ordering::Relaxed) > 0
|| crate::acl::RESTRICTED_KEY_CLIENTS.load(Ordering::Relaxed) > 0
{
let denied = env
.acl_store
.read()
.get(env.user)
.and_then(|user| crate::acl::check_permission(user, name, cmd).err());
if let Some(denied) = denied {
env.acl_log.record(
denied.reason(),
denied.object(),
env.user,
&crate::acl::log_client_info(env.client_registry, env.client_id, env.peer_addr),
);
return Some(crate::resp::write::resp_error(&denied.message(env.user)));
}
}
let number = |at: usize| {
cmd.get(at)
.and_then(|arg| std::str::from_utf8(arg).ok())
.and_then(|arg| arg.parse::<i64>().ok())
.unwrap_or(0)
};
Some(match name {
"UNWATCH" => b"+OK\r\n".to_vec(),
"MONITOR" => {
crate::resp::write::resp_error("ERR MONITOR isn't allowed for DENY BLOCKING client")
}
"WAIT" => match crate::replication::wait_args(cmd, env.repl_state.is_slave()) {
Err(refusal) => refusal,
Ok(_) => crate::resp::write::resp_integer(
env.wait_targets
.map_or(0, crate::replication::ReplState::count_reached),
),
},
_ => {
if !crate::aof::AOF_ENABLED.load(Ordering::Relaxed) {
if number(1) != 0 {
crate::resp::write::resp_error(
"ERR WAITAOF cannot be used when numlocal is set but appendonly is disabled.",
)
} else {
b"*2\r\n:0\r\n:0\r\n".to_vec()
}
} else if crate::aof::AOF_FSYNCED.load(Ordering::Relaxed)
>= crate::aof::AOF_WRITTEN.load(Ordering::Relaxed)
{
b"*2\r\n:1\r\n:0\r\n".to_vec()
} else {
b"*2\r\n:0\r\n:0\r\n".to_vec()
}
}
})
}
fn no_room(name: &str, cmd: &[&[u8]]) -> bool {
crate::commands::handler::check_memory_limit()
&& crate::eviction::policy() == crate::eviction::Policy::NoEviction
&& crate::replication::command_mutates_for_replication(name, cmd)
&& !crate::eviction::allowed_when_out_of_memory(name)
}
pub fn exec_refusal(
cmd: &[&[u8]],
queue: &[Vec<Vec<u8>>],
repl_state: &crate::replication::ReplState,
) -> Option<Vec<u8>> {
let writes = || {
queue.iter().any(|queued| {
let Some(cmd0) = queued.first() else {
return false;
};
let parts: Vec<&[u8]> = queued.iter().map(Vec::as_slice).collect();
let name = String::from_utf8_lossy(cmd0).to_ascii_uppercase();
crate::replication::refused_without_replicas(&name, &parts)
})
};
let why = if busy(cmd) {
BUSY
} else if crate::commands::handler::check_memory_limit()
&& queue.iter().any(|queued| {
let Some(cmd0) = queued.first() else {
return false;
};
let parts: Vec<&[u8]> = queued.iter().map(Vec::as_slice).collect();
no_room(&String::from_utf8_lossy(cmd0).to_ascii_uppercase(), &parts)
})
{
OOM
} else if repl_state.lacks_good_replicas() && writes() {
crate::replication::NOREPLICAS
} else {
return None;
};
Some(crate::resp::write::resp_error(&format!(
"EXECABORT Transaction discarded because of: {why}"
)))
}
pub struct TxState {
pub active: bool,
pub queue: Vec<Vec<Vec<u8>>>,
pub watched_keys: Vec<(usize, crate::store::Key)>, pub dirty: bool,
pub aborted: bool,
}
impl TxState {
pub fn new() -> Self {
Self {
active: false,
queue: Vec::new(),
watched_keys: Vec::new(),
dirty: false,
aborted: false,
}
}
pub fn reset(&mut self) {
self.active = false;
self.queue.clear();
self.watched_keys.clear();
self.dirty = false;
self.aborted = false;
}
}
pub struct Monitored<'a> {
pub registry: &'a crate::monitor::SharedMonitorRegistry,
pub db: usize,
pub peer_addr: &'a str,
}
pub fn reject(
tx: &mut TxState,
cmd: &[&[u8]],
watches: &dyn crate::watch::WatchNotifier,
dirty_flag: &Arc<std::sync::atomic::AtomicBool>,
monitor: Monitored<'_>,
refusal: Vec<u8>,
) -> Vec<u8> {
let is_exec = cmd
.first()
.is_some_and(|name| name.eq_ignore_ascii_case(b"EXEC"));
if !is_exec {
if tx.active {
tx.aborted = true;
}
return refusal;
}
watches.unwatch_all(
&tx.watched_keys
.iter()
.map(|_| Arc::clone(dirty_flag))
.collect::<Vec<_>>(),
);
tx.reset();
dirty_flag.store(false, Ordering::Release);
crate::monitor::feed(monitor.registry, cmd, monitor.db, monitor.peer_addr);
let why = String::from_utf8_lossy(&refusal);
crate::resp::write::resp_error(&format!(
"EXECABORT Transaction discarded because of: {}",
why.trim_start_matches('-').trim_end()
))
}
impl Default for TxState {
fn default() -> Self {
Self::new()
}
}