use std::sync::atomic::{AtomicI64, AtomicU64, AtomicUsize, Ordering};
pub static PAUSE_UNTIL_MS: AtomicI64 = AtomicI64::new(0);
const ENDING: i64 = -1;
static HELD: AtomicUsize = AtomicUsize::new(0);
static LETTING_GO: parking_lot::Mutex<Vec<u64>> = parking_lot::const_mutex(Vec::new());
static LETTING_GO_LEN: AtomicUsize = AtomicUsize::new(0);
static PAUSE_MODE_WRITE_ONLY: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
static HANDOFF: AtomicU64 = AtomicU64::new(0);
const HANDOFF_PAUSE: u64 = 1;
const KEYS_MOVING: u64 = 2;
const CLIENT_PAUSE: u64 = 4;
const ROUTES_MOVED: u64 = 8;
const BITS: u64 = ROUTES_MOVED - 1;
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
}
pub fn active() -> Option<bool> {
let until = PAUSE_UNTIL_MS.load(Ordering::Relaxed);
if until <= 0 {
return None;
}
if now_ms() >= until {
if PAUSE_UNTIL_MS
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
end_handoff_flag();
}
return None;
}
Some(PAUSE_MODE_WRITE_ONLY.load(Ordering::Relaxed))
}
#[inline]
pub fn expiry_deferred() -> bool {
#[cfg(test)]
if crate::expiry::undisturbed() {
return false;
}
PAUSE_UNTIL_MS.load(Ordering::Relaxed) != 0 && active().is_some()
}
pub fn set_pause(duration_ms: i64, write_only: bool) {
let end = now_ms().saturating_add(duration_ms);
let (end, write_only) = match active() {
Some(was_write_only) => (
end.max(PAUSE_UNTIL_MS.load(Ordering::Relaxed)),
write_only && was_write_only,
),
None => (end, write_only),
};
PAUSE_MODE_WRITE_ONLY.store(write_only, Ordering::Relaxed);
PAUSE_UNTIL_MS.store(end, Ordering::Relaxed); }
fn in_flight_wait_max() -> std::time::Duration {
#[cfg(debug_assertions)]
{
static SET: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
if let Some(ms) = *SET.get_or_init(|| {
std::env::var("KIVIDB_TEST_IN_FLIGHT_WAIT_MS")
.ok()
.and_then(|ms| ms.parse().ok())
}) {
return std::time::Duration::from_millis(ms);
}
}
std::time::Duration::from_secs(5)
}
static FLAG_LOCK: parking_lot::Mutex<()> = parking_lot::const_mutex(());
pub const PAUSE_DID_NOT_TAKE_HOLD: &str =
"ERR writes in progress did not finish before the pause could take hold";
pub fn pause_clients(duration_ms: i64, write_only: bool) -> Result<(), &'static str> {
pause_clients_within(duration_ms, write_only, in_flight_wait_max())
}
fn pause_clients_within(
duration_ms: i64,
write_only: bool,
limit: std::time::Duration,
) -> Result<(), &'static str> {
let (before, ours) = {
let _flag = FLAG_LOCK.lock();
let before =
active().map(|was_write_only| (PAUSE_UNTIL_MS.load(Ordering::SeqCst), was_write_only));
set_pause(duration_ms, write_only);
HANDOFF.fetch_or(CLIENT_PAUSE, Ordering::SeqCst);
(before, PAUSE_UNTIL_MS.load(Ordering::SeqCst))
};
let deadline = std::time::Instant::now() + limit;
let waited_out = crate::command_gate::alone_on_this_thread()
|| crate::cluster::migration::off_the_runtime(|| {
crate::write_gate::wait_out_writes(deadline, || duration_ms == 0 || active().is_some())
});
if waited_out {
return Ok(());
}
log_warn!(
"CLIENT PAUSE refused: a write in progress when clients were paused had not finished \
after {} ms, or the pause ended first; nothing is paused by it",
limit.as_millis()
);
let _flag = FLAG_LOCK.lock();
if PAUSE_UNTIL_MS.load(Ordering::SeqCst) == ours {
match before {
Some((until, was_write_only)) => {
PAUSE_MODE_WRITE_ONLY.store(was_write_only, Ordering::Relaxed);
PAUSE_UNTIL_MS.store(until, Ordering::SeqCst);
}
None => {
clear_pause();
lower_client_pause_flag();
}
}
}
Err(PAUSE_DID_NOT_TAKE_HOLD)
}
pub const HELD_IN_GATE: &[u8] = b"\0held by CLIENT PAUSE\0";
#[inline]
pub fn is_held(reply: &[u8]) -> bool {
reply.first() == Some(&0) && reply == HELD_IN_GATE
}
#[cold]
#[inline(never)]
pub fn held_in_gate<Q: AsRef<[u8]>>(cmd: &[&[u8]], queued: &[Vec<Q>]) -> bool {
if HANDOFF.load(Ordering::Acquire) & CLIENT_PAUSE == 0 {
return false;
}
if holds(cmd, queued) {
return true;
}
if active().is_none() {
end_client_pause_flag();
}
false
}
#[inline]
pub fn write_held_in_gate(cmd: &[&[u8]]) -> bool {
held_in_gate::<Vec<u8>>(cmd, &[])
}
pub fn exec_held_in_gate(queued: &[Vec<Vec<u8>>]) -> bool {
!handoff() && held_in_gate(&[b"EXEC"], queued)
}
fn end_client_pause_flag() {
if HANDOFF.load(Ordering::Relaxed) & CLIENT_PAUSE == 0 {
return;
}
let Some(_flag) = FLAG_LOCK.try_lock() else {
return;
};
lower_client_pause_flag();
}
fn lower_client_pause_flag() {
if PAUSE_UNTIL_MS.load(Ordering::SeqCst) <= now_ms() {
HANDOFF.fetch_and(!CLIENT_PAUSE, Ordering::SeqCst);
}
}
#[cfg(debug_assertions)]
pub fn test_stall_before_the_gate(cmd: &[&[u8]]) {
static DELAY: std::sync::OnceLock<Option<std::time::Duration>> = std::sync::OnceLock::new();
static TAKEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
let delay = DELAY.get_or_init(|| {
std::env::var("KIVIDB_TEST_PRE_GATE_DELAY_MS")
.ok()
.and_then(|ms| ms.parse().ok())
.map(std::time::Duration::from_millis)
});
if let Some(delay) = *delay
&& cmd.iter().skip(1).any(|arg| arg.starts_with(b"stalled:"))
&& !TAKEN.swap(true, Ordering::Relaxed)
{
crate::cluster::migration::off_the_runtime(|| std::thread::sleep(delay));
}
}
pub fn clear_pause() {
PAUSE_MODE_WRITE_ONLY.store(false, Ordering::Relaxed);
let held = HELD.load(Ordering::SeqCst) > 0;
PAUSE_UNTIL_MS.store(if held { ENDING } else { 0 }, Ordering::SeqCst);
if held && HELD.load(Ordering::SeqCst) == 0 {
let _ = PAUSE_UNTIL_MS.compare_exchange(ENDING, 0, Ordering::SeqCst, Ordering::SeqCst);
}
end_handoff_flag();
CHANGED.notify_waiters();
}
fn end_handoff_flag() {
let mut now = HANDOFF.load(Ordering::Relaxed);
while now & HANDOFF_PAUSE != 0 {
let ended = (now & !HANDOFF_PAUSE).wrapping_add(ROUTES_MOVED);
match HANDOFF.compare_exchange_weak(now, ended, Ordering::SeqCst, Ordering::Relaxed) {
Ok(_) => break,
Err(seen) => now = seen,
}
}
end_client_pause_flag();
}
static CHANGED: tokio::sync::Notify = tokio::sync::Notify::const_new();
pub async fn gate<Q: AsRef<[u8]>, G: std::future::Future<Output = ()>>(
cmd: &[&[u8]],
queued: &[Vec<Q>],
id: u64,
gone: impl FnOnce() -> G,
) -> Option<Option<Ran>> {
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(100);
while PAUSE_UNTIL_MS.load(Ordering::SeqCst) == ENDING {
if std::time::Instant::now() >= deadline {
let _ = PAUSE_UNTIL_MS.compare_exchange(ENDING, 0, Ordering::SeqCst, Ordering::SeqCst);
break;
}
wait_for_change(|| PAUSE_UNTIL_MS.load(Ordering::SeqCst) == ENDING).await;
}
if !holds(cmd, queued) {
return Some(None);
}
let held = Held::new();
HELD.fetch_add(1, Ordering::SeqCst);
let counted = Counted;
let gone = gone();
let mut gone = std::pin::pin!(gone);
while holds(cmd, queued) {
tokio::select! {
biased;
() = wait_for_change(|| holds(cmd, queued)) => {}
() = &mut gone => return None,
}
}
drop(held);
if PAUSE_UNTIL_MS.load(Ordering::SeqCst) == ENDING {
std::mem::forget(counted);
LETTING_GO.lock().push(id);
LETTING_GO_LEN.fetch_add(1, Ordering::SeqCst);
return Some(Some(Ran(id)));
}
Some(None)
}
struct Counted;
impl Drop for Counted {
fn drop(&mut self) {
let_go();
}
}
async fn wait_for_change(still: impl Fn() -> bool) {
let changed = CHANGED.notified();
tokio::pin!(changed);
changed.as_mut().enable();
if still() {
let _ = tokio::time::timeout(std::time::Duration::from_millis(1), changed).await;
}
}
fn let_go() {
if HELD.fetch_sub(1, Ordering::SeqCst) == 1
&& PAUSE_UNTIL_MS
.compare_exchange(ENDING, 0, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
{
CHANGED.notify_waiters();
}
}
pub fn went_on(id: u64) {
if LETTING_GO_LEN.load(Ordering::SeqCst) == 0 {
return;
}
let mut letting_go = LETTING_GO.lock();
if let Some(at) = letting_go.iter().position(|&other| other == id) {
letting_go.swap_remove(at);
LETTING_GO_LEN.fetch_sub(1, Ordering::SeqCst);
drop(letting_go);
let_go();
}
}
pub struct Ran(u64);
impl Drop for Ran {
fn drop(&mut self) {
went_on(self.0);
}
}
pub fn set_handoff_pause(duration_ms: i64) {
HANDOFF.fetch_or(HANDOFF_PAUSE, Ordering::SeqCst);
set_pause(duration_ms, true);
}
const UNTIL_ENDED_MS: i64 = 100 * 365 * 24 * 3600 * 1000;
pub fn hold_writes() {
set_handoff_pause(UNTIL_ENDED_MS);
}
#[inline]
pub fn handoff() -> bool {
HANDOFF.load(Ordering::Acquire) & HANDOFF_PAUSE != 0 && handoff_pause_in_force()
}
#[cold]
#[inline(never)]
fn handoff_pause_in_force() -> bool {
let in_force = active().is_some();
std::sync::atomic::fence(Ordering::Acquire);
in_force
}
#[inline]
pub fn writes_must_check(routed: u64) -> bool {
HANDOFF.load(Ordering::Acquire) != routed
}
#[inline]
pub fn keys_moving() -> bool {
HANDOFF.load(Ordering::Acquire) & KEYS_MOVING != 0
}
#[inline]
pub fn routes_now() -> u64 {
HANDOFF.load(Ordering::Acquire) & !BITS
}
pub fn routes_moved_since(routed: u64) -> bool {
routes_now() != routed
}
pub(crate) fn routes_moved() {
HANDOFF.fetch_add(ROUTES_MOVED, Ordering::SeqCst);
}
pub(crate) fn set_keys_moving(on: bool) {
if on {
HANDOFF.fetch_or(KEYS_MOVING, Ordering::SeqCst);
} else {
HANDOFF.fetch_and(!KEYS_MOVING, Ordering::SeqCst);
}
}
pub fn wait_out_handoff() {
let wait = || {
while handoff() {
std::thread::sleep(std::time::Duration::from_micros(200));
}
};
let on_multi_thread_runtime = tokio::runtime::Handle::try_current().is_ok_and(|runtime| {
runtime.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread
});
if on_multi_thread_runtime {
tokio::task::block_in_place(wait);
} else {
wait();
}
}
pub fn holds<Q: AsRef<[u8]>>(cmd: &[&[u8]], queued: &[Vec<Q>]) -> bool {
let Some(write_only) = active() else {
return false;
};
let name = String::from_utf8_lossy(cmd[0]).to_ascii_uppercase();
if crate::commands::arity::check(&name, cmd).is_some() {
return false;
}
if !write_only {
return !(name == "CLIENT"
&& cmd
.get(1)
.is_some_and(|sub| sub.eq_ignore_ascii_case(b"UNPAUSE")));
}
if name == "EXEC" {
return queued.iter().any(|command| queued_may_replicate(command));
}
may_replicate(&name, cmd)
}
pub fn queued_may_replicate<Q: AsRef<[u8]>>(command: &[Q]) -> bool {
let Some(cmd0) = command.first() else {
return false;
};
let cmd: Vec<&[u8]> = command.iter().map(|arg| arg.as_ref()).collect();
may_replicate(
&String::from_utf8_lossy(cmd0.as_ref()).to_ascii_uppercase(),
&cmd,
)
}
fn may_replicate(name: &str, cmd: &[&[u8]]) -> bool {
#[cfg(feature = "lua")]
let declared_read_only = |name: &str, first: &[u8]| match name {
"EVAL" => crate::commands::script_declares_no_writes(first),
"EVALSHA" => crate::commands::cached_script_declares_no_writes(first),
_ => crate::commands::function_declares_no_writes(first),
};
#[cfg(not(feature = "lua"))]
let declared_read_only = |_: &str, _: &[u8]| false;
match name {
"PFCOUNT" | "PUBLISH" | "SPUBLISH" => true,
"SELECT" | "SCRIPT" => false,
"EVAL" | "EVALSHA" | "FCALL" => !cmd
.get(1)
.copied()
.is_some_and(|first| declared_read_only(name, first)),
"EVAL_RO" | "EVALSHA_RO" | "FCALL_RO" => false,
_ => crate::replication::command_mutates_for_replication(name, cmd),
}
}
pub struct Held;
impl Held {
pub fn new() -> Self {
crate::stats::BLOCKED_CLIENTS.fetch_add(1, Ordering::Relaxed);
Held
}
}
impl Default for Held {
fn default() -> Self {
Self::new()
}
}
impl Drop for Held {
fn drop(&mut self) {
crate::stats::BLOCKED_CLIENTS.fetch_sub(1, Ordering::Relaxed);
}
}
#[cfg(test)]
pub(crate) static TEST_LOCK: parking_lot::Mutex<()> = parking_lot::const_mutex(());
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_longer_and_the_wider_pause_holds() {
let _pause = TEST_LOCK.lock();
clear_pause();
assert_eq!(active(), None);
set_pause(60_000, true);
assert_eq!(active(), Some(true));
let end = PAUSE_UNTIL_MS.load(Ordering::Relaxed);
set_pause(10, true);
assert_eq!(PAUSE_UNTIL_MS.load(Ordering::Relaxed), end);
set_pause(10, false);
assert_eq!(active(), Some(false));
set_pause(10, true);
assert_eq!(active(), Some(false));
let none: &[Vec<Vec<u8>>] = &[];
assert!(holds(&[b"GET", b"k"], none));
assert!(!holds(&[b"CLIENT", b"UNPAUSE"], none));
clear_pause();
set_pause(60_000, true);
assert!(!holds(&[b"GET", b"k"], none));
assert!(holds(&[b"SET", b"k", b"v"], none));
assert!(holds(&[b"PUBLISH", b"c", b"m"], none));
assert!(!holds(&[b"SET", b"k"], none));
let reads = vec![vec![b"GET".to_vec(), b"k".to_vec()]];
let writes = vec![vec![b"SET".to_vec(), b"k".to_vec(), b"v".to_vec()]];
assert!(!holds(&[b"EXEC"], &reads));
assert!(holds(&[b"EXEC"], &writes));
let georadius: &[&[u8]] = &[b"GEORADIUS", b"src", b"15", b"37", b"200", b"km"];
let store: &[&[u8]] = &[
b"GEORADIUS",
b"src",
b"15",
b"37",
b"200",
b"km",
b"STORE",
b"dst",
];
let storedist: &[&[u8]] = &[
b"GEORADIUSBYMEMBER",
b"src",
b"m",
b"10",
b"km",
b"STOREDIST",
b"dst",
];
assert!(!holds(georadius, none));
assert!(holds(store, none));
assert!(holds(storedist, none));
let queue = |cmd: &[&[u8]]| vec![cmd.iter().map(|arg| arg.to_vec()).collect::<Vec<_>>()];
assert!(!holds(&[b"EXEC"], &queue(georadius)));
assert!(holds(&[b"EXEC"], &queue(store)));
assert!(holds(&[b"EXEC"], &queue(storedist)));
assert!(holds(&[b"FUNCTION", b"LOAD", b"code"], none));
assert!(holds(&[b"FUNCTION", b"DELETE", b"lib"], none));
assert!(holds(&[b"FUNCTION", b"FLUSH"], none));
assert!(!holds(&[b"FUNCTION", b"LIST"], none));
assert!(!holds(&[b"SCRIPT", b"LOAD", b"return 1"], none));
assert!(!holds(&[b"SCRIPT", b"FLUSH"], none));
assert!(!holds(&[b"SCRIPT", b"FLUSH", b"ASYNC"], none));
assert!(!holds(&[b"SCRIPT", b"EXISTS", b"0123"], none));
let script_load = vec![vec![
b"SCRIPT".to_vec(),
b"LOAD".to_vec(),
b"return 1".to_vec(),
]];
assert!(!holds(&[b"EXEC"], &script_load));
assert!(!script_load.iter().any(|c| queued_may_replicate(c)));
let script_load_and_write = vec![
script_load[0].clone(),
vec![b"SET".to_vec(), b"k".to_vec(), b"v".to_vec()],
];
assert!(holds(&[b"EXEC"], &script_load_and_write));
assert!(holds(
&[b"MIGRATE", b"127.0.0.1", b"6379", b"k", b"0", b"1000"],
none
));
assert!(!holds(&[b"SELECT", b"1"], none));
let select_and_read = vec![
vec![b"SELECT".to_vec(), b"1".to_vec()],
vec![b"GET".to_vec(), b"k".to_vec()],
];
assert!(!holds(&[b"EXEC"], &select_and_read));
assert!(!select_and_read.iter().any(|c| queued_may_replicate(c)));
let select_and_write = vec![
vec![b"SELECT".to_vec(), b"1".to_vec()],
vec![b"SET".to_vec(), b"k".to_vec(), b"v".to_vec()],
];
assert!(holds(&[b"EXEC"], &select_and_write));
clear_pause();
assert!(!holds(&[b"SET", b"k", b"v"], none));
assert!(!handoff());
set_pause(60_000, true);
assert!(!handoff());
clear_pause();
set_handoff_pause(60_000);
assert!(handoff() && holds(&[b"SET", b"k", b"v"], none));
clear_pause();
assert!(!handoff());
set_handoff_pause(1);
std::thread::sleep(std::time::Duration::from_millis(5));
assert!(!handoff());
set_pause(60_000, true);
assert!(!handoff());
clear_pause();
hold_writes();
assert!(handoff() && holds(&[b"SET", b"k", b"v"], none));
assert!(!holds(&[b"GET", b"k"], none));
clear_pause();
assert!(!handoff());
let client_flag = || HANDOFF.load(Ordering::SeqCst) & CLIENT_PAUSE != 0;
assert!(!client_flag());
pause_clients(60_000, true).unwrap();
assert!(client_flag() && !handoff());
assert!(write_held_in_gate(&[b"SET", b"k", b"v"]));
assert!(!write_held_in_gate(&[b"GET", b"k"]));
assert!(exec_held_in_gate(&writes) && !exec_held_in_gate(&reads));
assert!(client_flag());
clear_pause();
assert!(!client_flag() && !write_held_in_gate(&[b"SET", b"k", b"v"]));
let _ = pause_clients(1, false);
std::thread::sleep(std::time::Duration::from_millis(5));
assert!(!write_held_in_gate(&[b"SET", b"k", b"v"]));
assert!(!client_flag());
pause_clients(60_000, true).unwrap();
set_handoff_pause(60_000);
assert!(handoff() && !exec_held_in_gate(&writes));
clear_pause();
assert!(!handoff() && !client_flag());
let routed = routes_now();
pause_clients(60_000, true).unwrap();
assert!(!routes_moved_since(routed));
clear_pause();
pause_clients(60_000, true).unwrap();
end_client_pause_flag();
assert!(client_flag(), "the flag of a pause in force came down");
clear_pause();
HANDOFF.fetch_or(CLIENT_PAUSE, Ordering::SeqCst);
PAUSE_UNTIL_MS.store(now_ms() - 10, Ordering::SeqCst);
{
let _setting = FLAG_LOCK.lock();
end_client_pause_flag();
assert!(
client_flag(),
"taken down while a CLIENT PAUSE held the lock"
);
}
end_client_pause_flag();
assert!(!client_flag());
PAUSE_UNTIL_MS.store(0, Ordering::SeqCst);
let (in_gate, out) = (
std::sync::Arc::new(std::sync::Barrier::new(2)),
std::sync::Arc::new(std::sync::Barrier::new(2)),
);
let writer = {
let (in_gate, out) = (std::sync::Arc::clone(&in_gate), std::sync::Arc::clone(&out));
std::thread::spawn(move || {
let _gate = crate::write_gate::enter();
in_gate.wait();
out.wait();
})
};
in_gate.wait();
let limit = std::time::Duration::from_millis(30);
assert_eq!(
pause_clients_within(60_000, true, limit),
Err(PAUSE_DID_NOT_TAKE_HOLD)
);
assert_eq!(active(), None, "a failed CLIENT PAUSE left clients paused");
assert!(!client_flag());
set_pause(60_000, false);
let before = PAUSE_UNTIL_MS.load(Ordering::SeqCst);
assert_eq!(
pause_clients_within(120_000, true, limit),
Err(PAUSE_DID_NOT_TAKE_HOLD)
);
assert_eq!(active(), Some(false));
assert_eq!(PAUSE_UNTIL_MS.load(Ordering::SeqCst), before);
clear_pause();
out.wait();
writer.join().unwrap();
let enough = std::time::Duration::from_secs(5);
assert_eq!(pause_clients_within(60_000, true, enough), Ok(()));
clear_pause();
assert!(!client_flag());
set_handoff_pause(20_000);
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let started = std::time::Instant::now();
runtime.block_on(async {
tokio::spawn(async {
let ender = tokio::spawn(async { clear_pause() });
wait_out_handoff();
ender.await.unwrap();
})
.await
.unwrap();
});
assert!(
started.elapsed() < std::time::Duration::from_secs(10),
"the handoff was waited out for {:?}",
started.elapsed()
);
assert!(!handoff());
}
}