use parking_lot::{Mutex, MutexGuard};
use std::cell::{Cell, RefCell};
use std::marker::PhantomData;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
static ENABLED: AtomicBool = AtomicBool::new(false);
#[inline]
pub fn enabled() -> bool {
ENABLED.load(Ordering::Relaxed)
}
pub fn set_enabled(on: bool) {
ENABLED.store(on, Ordering::Relaxed);
}
const STRIPES: usize = 1024;
#[repr(align(64))]
struct Stripe(Mutex<()>);
static STRIPE: [Stripe; STRIPES] = [const { Stripe(parking_lot::const_mutex(())) }; STRIPES];
#[inline]
pub fn tag_of(key: &[u8]) -> Option<&[u8]> {
let open = memchr::memchr(b'{', key)?;
let rest = &key[open + 1..];
let close = memchr::memchr(b'}', rest)?;
(close > 0).then(|| &rest[..close])
}
#[inline]
fn stripe_of(tag: &[u8]) -> usize {
let mut hash: u64 = 0xcbf29ce484222325;
for byte in tag {
hash ^= *byte as u64;
hash = hash.wrapping_mul(0x100000001b3);
}
((hash ^ (hash >> 32)) as usize) & (STRIPES - 1)
}
thread_local! {
static SCRIPT_TAG: RefCell<Option<Vec<u8>>> = const { RefCell::new(None) };
static BESIDE_OTHERS: Cell<bool> = const { Cell::new(false) };
static NEXT_SCRIPT_ALLOWED: Cell<bool> = const { Cell::new(false) };
}
pub fn script_tag<'a>(cmd: &[&'a [u8]]) -> Option<&'a [u8]> {
let name = cmd.first()?;
if !(name.eq_ignore_ascii_case(b"EVAL")
|| name.eq_ignore_ascii_case(b"EVALSHA")
|| name.eq_ignore_ascii_case(b"EVAL_RO")
|| name.eq_ignore_ascii_case(b"EVALSHA_RO"))
{
return None;
}
let numkeys: usize = std::str::from_utf8(cmd.get(2)?).ok()?.parse().ok()?;
let keys = cmd.get(3..3usize.checked_add(numkeys)?)?;
let (first, rest) = keys.split_first()?;
let tag = tag_of(first)?;
rest.iter()
.all(|key| tag_of(key) == Some(tag))
.then_some(tag)
}
pub fn allow_next_script() {
NEXT_SCRIPT_ALLOWED.with(|allowed| allowed.set(true));
}
pub fn take_next_script_allowed() -> bool {
NEXT_SCRIPT_ALLOWED.with(|allowed| allowed.replace(false))
}
pub struct ScriptGuard {
_stripe: Option<MutexGuard<'static, ()>>,
_gate: Option<crate::write_gate::WriteGuard>,
outermost: bool,
_not_send: PhantomData<*const ()>,
}
impl Drop for ScriptGuard {
fn drop(&mut self) {
if self.outermost {
SCRIPT_TAG.with(|tag| *tag.borrow_mut() = None);
BESIDE_OTHERS.with(|beside| beside.set(false));
}
}
}
fn hold(
tag: &[u8],
stripe: Option<MutexGuard<'static, ()>>,
gate: Option<crate::write_gate::WriteGuard>,
) -> ScriptGuard {
let outermost = SCRIPT_TAG.with(|held| {
let mut held = held.borrow_mut();
if held.is_some() {
false
} else {
*held = Some(tag.to_vec());
true
}
});
if outermost {
BESIDE_OTHERS.with(|beside| beside.set(stripe.is_some()));
}
ScriptGuard {
_stripe: stripe,
_gate: gate,
outermost,
_not_send: PhantomData,
}
}
pub fn lock_for_script(tag: &[u8]) -> ScriptGuard {
let gate = crate::write_gate::enter();
hold(tag, Some(STRIPE[stripe_of(tag)].0.lock()), Some(gate))
}
static TURN: [tokio::sync::Mutex<()>; STRIPES] =
[const { tokio::sync::Mutex::const_new(()) }; STRIPES];
pub async fn script_turn(tag: &[u8]) -> tokio::sync::MutexGuard<'static, ()> {
TURN[stripe_of(tag)].lock().await
}
pub fn hold_script_to(tag: &[u8]) -> ScriptGuard {
hold(tag, None, None)
}
#[inline]
pub fn in_script() -> bool {
SCRIPT_TAG.with(|tag| tag.borrow().is_some())
}
#[inline]
pub fn beside_others() -> bool {
BESIDE_OTHERS.with(|beside| beside.get())
}
pub fn script_may_touch(key: &[u8]) -> bool {
SCRIPT_TAG.with(|tag| match tag.borrow().as_deref() {
None => true,
Some(tag) => tag_of(key) == Some(tag),
})
}
pub fn script_tag_for_message() -> String {
SCRIPT_TAG.with(|tag| {
tag.borrow()
.as_deref()
.map(|tag| String::from_utf8_lossy(tag).into_owned())
.unwrap_or_default()
})
}
pub struct KeysGuard {
_one: Option<MutexGuard<'static, ()>>,
_more: Vec<MutexGuard<'static, ()>>,
_gate: crate::write_gate::WriteGuard,
}
pub fn lock_keys<'a>(keys: impl Iterator<Item = &'a [u8]>) -> Option<KeysGuard> {
let mut first: Option<usize> = None;
let mut more: Vec<usize> = Vec::new();
for key in keys {
let Some(tag) = tag_of(key) else { continue };
let stripe = stripe_of(tag);
match first {
None => first = Some(stripe),
Some(one) if one == stripe => {}
Some(_) => more.push(stripe),
}
}
let first = first?;
let gate = crate::write_gate::enter();
if more.is_empty() {
return Some(KeysGuard {
_one: Some(STRIPE[first].0.lock()),
_more: Vec::new(),
_gate: gate,
});
}
more.push(first);
more.sort_unstable();
more.dedup();
Some(KeysGuard {
_one: None,
_more: more
.into_iter()
.map(|stripe| STRIPE[stripe].0.lock())
.collect(),
_gate: gate,
})
}
pub struct TriedKeys {
_held: Vec<MutexGuard<'static, ()>>,
busy: Vec<usize>,
}
impl TriedKeys {
#[inline]
pub fn may_take(&self, key: &[u8]) -> bool {
self.busy.is_empty() || tag_of(key).is_none_or(|tag| !self.busy.contains(&stripe_of(tag)))
}
#[inline]
pub fn left_some(&self) -> bool {
!self.busy.is_empty()
}
}
const PATIENT_AFTER: u8 = 3;
const PATIENCE: Duration = Duration::from_millis(5);
thread_local! {
static MISSES: [Cell<u8>; STRIPES] = const { [const { Cell::new(0) }; STRIPES] };
}
pub fn try_lock_keys<'a>(keys: impl Iterator<Item = &'a [u8]>) -> Option<TriedKeys> {
let mut stripes: Vec<usize> = keys.filter_map(tag_of).map(stripe_of).collect();
if stripes.is_empty() {
return None;
}
stripes.sort_unstable();
stripes.dedup();
let mut held = Vec::with_capacity(stripes.len());
let mut busy = Vec::new();
MISSES.with(|misses| {
for stripe in stripes {
let missed = &misses[stripe];
let lock = &STRIPE[stripe].0;
let guard = if missed.get() >= PATIENT_AFTER {
lock.try_lock_for(PATIENCE)
} else {
lock.try_lock()
};
match guard {
Some(guard) => {
missed.set(0);
held.push(guard);
}
None => {
missed.set(missed.get().saturating_add(1));
busy.push(stripe);
}
}
}
});
Some(TriedKeys { _held: held, busy })
}
pub fn sees_the_whole_keyspace(name: &str) -> bool {
matches!(
name,
"KEYS" | "SCAN" | "DBSIZE" | "RANDOMKEY" | "FLUSHALL" | "FLUSHDB" | "SWAPDB"
)
}
#[inline(always)]
pub fn is_switch(name: &str, cmd: &[&[u8]]) -> bool {
name == "CONFIG"
&& cmd
.get(1)
.is_some_and(|sub| sub.eq_ignore_ascii_case(b"SET"))
&& cmd
.iter()
.skip(2)
.step_by(2)
.any(|parameter| parameter.eq_ignore_ascii_case(b"lua-parallel-scripts"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_tag_is_what_is_between_the_first_braces() {
assert_eq!(tag_of(b"{q1}:wait"), Some(&b"q1"[..]));
assert_eq!(tag_of(b"bull:{q1}:wait"), Some(&b"q1"[..]));
assert_eq!(tag_of(b"{a}{b}"), Some(&b"a"[..]));
assert_eq!(tag_of(b"plain"), None);
assert_eq!(tag_of(b"{}x"), None);
assert_eq!(tag_of(b"{open"), None);
assert_eq!(tag_of(b"close}"), None);
}
#[test]
fn a_script_has_a_tag_when_all_its_keys_share_one() {
let tag = |cmd: &[&[u8]]| script_tag(cmd).map(|tag| tag.to_vec());
assert_eq!(
tag(&[b"EVALSHA", b"abc", b"2", b"{q}:a", b"x:{q}:b", b"arg"]),
Some(b"q".to_vec())
);
assert_eq!(
tag(&[b"eval", b"return 1", b"1", b"{q}:a"]),
Some(b"q".to_vec())
);
assert_eq!(tag(&[b"EVALSHA", b"abc", b"0", b"{q}:a"]), None);
assert_eq!(tag(&[b"EVALSHA", b"abc", b"2", b"{q}:a", b"b"]), None);
assert_eq!(tag(&[b"EVALSHA", b"abc", b"2", b"{q}:a", b"{r}:b"]), None);
assert_eq!(tag(&[b"FCALL", b"f", b"1", b"{q}:a"]), None);
assert_eq!(tag(&[b"EVALSHA", b"abc", b"5", b"{q}:a"]), None);
assert_eq!(tag(&[b"EVALSHA", b"abc", b"x", b"{q}:a"]), None);
}
#[test]
fn a_script_is_held_to_its_tag() {
assert!(script_may_touch(b"anything"), "no script here");
let guard = lock_for_script(b"q1");
assert!(in_script());
assert!(script_may_touch(b"{q1}:jobs"));
assert!(script_may_touch(b"bull:{q1}:7"));
assert!(!script_may_touch(b"{q2}:jobs"));
assert!(!script_may_touch(b"untagged"));
drop(guard);
assert!(!in_script());
assert!(script_may_touch(b"{q2}:jobs"));
}
#[test]
fn a_command_waits_for_the_script_on_its_tag_and_no_other() {
let script = lock_for_script(b"busy-queue");
let other = (0..)
.map(|i| format!("other-{i}"))
.find(|tag| stripe_of(tag.as_bytes()) != stripe_of(b"busy-queue"))
.unwrap();
let key = format!("{{{other}}}:k");
std::thread::scope(|scope| {
scope
.spawn(|| {
assert!(lock_keys([key.as_bytes(), b"plain".as_slice()].into_iter()).is_some());
assert!(lock_keys([b"plain".as_slice()].into_iter()).is_none());
})
.join()
.unwrap();
});
let (waiting_tx, waiting_rx) = std::sync::mpsc::channel();
let (done_tx, done_rx) = std::sync::mpsc::channel();
let waiter = std::thread::spawn(move || {
waiting_tx.send(()).unwrap();
let _held = lock_keys([b"{busy-queue}:k".as_slice()].into_iter());
done_tx.send(()).unwrap();
});
waiting_rx.recv().unwrap();
assert!(
done_rx
.recv_timeout(std::time::Duration::from_millis(100))
.is_err(),
"it did not wait for the script"
);
drop(script);
done_rx
.recv_timeout(std::time::Duration::from_secs(5))
.expect("it was let through when the script ended");
waiter.join().unwrap();
}
#[test]
fn a_tag_that_is_held_is_left_and_not_waited_for() {
let other = (0..)
.map(|i| format!("free-{i}"))
.find(|tag| stripe_of(tag.as_bytes()) != stripe_of(b"held-tag"))
.unwrap();
let free_key = format!("{{{other}}}:k");
let held = lock_for_script(b"held-tag");
std::thread::scope(|scope| {
scope
.spawn(|| {
let started = std::time::Instant::now();
let tried = try_lock_keys(
[b"{held-tag}:a".as_slice(), free_key.as_bytes(), b"plain"].into_iter(),
)
.expect("two keys have a tag");
assert!(started.elapsed() < Duration::from_secs(1), "it waited");
assert!(tried.left_some());
assert!(!tried.may_take(b"{held-tag}:a"));
assert!(tried.may_take(free_key.as_bytes()));
assert!(tried.may_take(b"plain"));
assert!(try_lock_keys([b"plain".as_slice()].into_iter()).is_none());
})
.join()
.unwrap();
});
drop(held);
}
#[test]
fn a_busy_tag_is_waited_for_a_little_and_not_for_ever() {
let forever = lock_for_script(b"never-let-go");
std::thread::scope(|scope| {
scope
.spawn(|| {
for _ in 0..10 {
let started = std::time::Instant::now();
let tried =
try_lock_keys([b"{never-let-go}:k".as_slice()].into_iter()).unwrap();
assert!(tried.left_some());
assert!(started.elapsed() < Duration::from_secs(1));
}
})
.join()
.unwrap();
});
drop(forever);
let stop = std::sync::atomic::AtomicBool::new(false);
std::thread::scope(|scope| {
scope.spawn(|| {
while !stop.load(Ordering::Relaxed) {
let _held = lock_for_script(b"busy-queue-tag");
std::thread::sleep(Duration::from_micros(300));
}
});
scope
.spawn(|| {
std::thread::sleep(Duration::from_millis(20));
let taken = (0..200).any(|_| {
let tried =
try_lock_keys([b"{busy-queue-tag}:k".as_slice()].into_iter()).unwrap();
!tried.left_some()
});
stop.store(true, Ordering::Relaxed);
assert!(taken, "the busy tag was never taken");
})
.join()
.unwrap();
});
}
#[test]
fn a_tag_is_held_inside_the_write_gate() {
assert!(!crate::write_gate::held_by_this_thread());
let keys = lock_keys([b"{gated}:k".as_slice()].into_iter());
assert!(crate::write_gate::held_by_this_thread());
drop(keys);
assert!(!crate::write_gate::held_by_this_thread());
assert!(lock_keys([b"untagged".as_slice()].into_iter()).is_none());
assert!(!crate::write_gate::held_by_this_thread(), "no tag, no gate");
let script = lock_for_script(b"gated");
assert!(crate::write_gate::held_by_this_thread());
drop(script);
assert!(!crate::write_gate::held_by_this_thread());
let held = hold_script_to(b"gated");
assert!(
!crate::write_gate::held_by_this_thread(),
"no lock, no gate"
);
drop(held);
}
#[test]
fn several_tags_are_taken_whatever_order_they_are_named_in() {
let a = lock_keys(
[
b"{t1}:a".as_slice(),
b"{t2}:b".as_slice(),
b"{t1}:c".as_slice(),
]
.into_iter(),
);
assert!(a.is_some());
drop(a);
std::thread::scope(|scope| {
for flip in [false, true] {
scope.spawn(move || {
for _ in 0..2000 {
let keys: [&[u8]; 2] = if flip {
[b"{t2}:b", b"{t1}:a"]
} else {
[b"{t1}:a", b"{t2}:b"]
};
let _held = lock_keys(keys.into_iter());
}
});
}
});
}
}