use crate::store::Key;
use crate::{
store::{self, Store},
types::KiviDBValue,
vector::IndexStore,
};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub const REDIS_WHEN_MAX_MS: i128 = 9223372036854775807;
pub const ERR_VALUE_NOT_INTEGER: &str = "ERR value is not an integer or out of range";
pub const ERR_INVALID_EXPIRE_EXPIRE_CMD: &str = "ERR invalid expire time in 'expire' command";
pub const ERR_INVALID_EXPIRE_SET_CMD: &str = "ERR invalid expire time in 'set' command";
pub const ERR_INVALID_EXPIRE_GETEX_CMD: &str = "ERR invalid expire time in 'getex' command";
pub const ERR_INVALID_EXPIRE_PEXPIRE_CMD: &str = "ERR invalid expire time in 'pexpire' command";
pub const ERR_INVALID_EXPIRE_PEXPIREAT_CMD: &str = "ERR invalid expire time in 'pexpireat' command";
pub const ERR_INVALID_EXPIRE_EXPIREAT_CMD: &str = "ERR invalid expire time in 'expireat' command";
pub const ERR_INVALID_EXPIRE_SETEX_CMD: &str = "ERR invalid expire time in 'setex' command";
pub const ERR_INVALID_EXPIRE_PSETEX_CMD: &str = "ERR invalid expire time in 'psetex' command";
pub const ERR_INVALID_EXPIRE_MSETEX_CMD: &str = "ERR invalid expire time in 'msetex' command";
pub const ERR_INVALID_EXPIRE_INCREX_CMD: &str = "ERR invalid expire time in 'increx' command";
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum TimeArg {
Secs,
Millis,
UnixSecs,
UnixMillis,
}
impl TimeArg {
pub fn of_option(token: &[u8]) -> Option<TimeArg> {
if token.eq_ignore_ascii_case(b"EX") {
Some(TimeArg::Secs)
} else if token.eq_ignore_ascii_case(b"PX") {
Some(TimeArg::Millis)
} else if token.eq_ignore_ascii_case(b"EXAT") {
Some(TimeArg::UnixSecs)
} else if token.eq_ignore_ascii_case(b"PXAT") {
Some(TimeArg::UnixMillis)
} else {
None
}
}
}
#[inline]
pub fn applying_stream(ctx: &crate::commands::ctx::Ctx) -> bool {
ctx.apply_replication || crate::expiry::replaying()
}
pub fn deadline_ms_of(
n: i128,
arg: TimeArg,
err_invalid: &'static str,
lenient: bool,
positive: bool,
) -> Result<i128, &'static str> {
let relative = matches!(arg, TimeArg::Secs | TimeArg::Millis);
if positive && n <= 0 && !(lenient && !relative && n == 0) {
return Err(err_invalid);
}
let secs = matches!(arg, TimeArg::Secs | TimeArg::UnixSecs);
if secs && !lenient && (n > (i64::MAX / 1000) as i128 || n < (i64::MIN / 1000) as i128) {
return Err(err_invalid);
}
let ms = if secs { n * 1000 } else { n };
let when = if relative {
wall_now_ms_i128() + ms
} else {
ms
};
if when > REDIS_WHEN_MAX_MS {
return if lenient {
Ok(REDIS_WHEN_MAX_MS)
} else {
Err(err_invalid)
};
}
if when < i64::MIN as i128 {
return Err(err_invalid);
}
Ok(when)
}
#[inline]
pub fn time_arg_of(arg: &[u8], lenient: bool) -> Result<i128, &'static str> {
match parse_bytes_as_i128(arg) {
Some(n) if i64::try_from(n).is_ok() => Ok(n),
Some(n) if lenient && (0..=u64::MAX as i128).contains(&n) => Ok(n),
_ => Err(ERR_VALUE_NOT_INTEGER),
}
}
#[inline]
fn system_time_of(
when: i128,
err_invalid: &'static str,
lenient: bool,
) -> Result<SystemTime, &'static str> {
match system_time_from_unix_millis_i128(when) {
Some(t) => Ok(t),
None if lenient && when > 0 => Ok(from_unix_ms(when as u64)),
None => Err(err_invalid),
}
}
#[inline]
pub fn key_deadline(
raw: &[u8],
arg: TimeArg,
err_invalid: &'static str,
lenient: bool,
) -> Result<SystemTime, &'static str> {
let n = time_arg_of(raw, lenient)?;
let when = deadline_ms_of(n, arg, err_invalid, lenient, true)?;
system_time_of(when, err_invalid, lenient)
}
#[inline]
pub fn expire_deadline(
raw: &[u8],
arg: TimeArg,
err_invalid: &'static str,
lenient: bool,
) -> Result<(i128, SystemTime), &'static str> {
let n = time_arg_of(raw, lenient)?;
let when = deadline_ms_of(n, arg, err_invalid, lenient, false)?;
Ok((n, system_time_of(when, err_invalid, lenient)?))
}
#[derive(Default, Clone, Copy)]
pub struct ExpireModifierFlags {
pub nx: bool,
pub xx: bool,
pub gt: bool,
pub lt: bool,
}
pub fn parse_expire_modifier_flags(
cmd: &[&[u8]],
start: usize,
) -> Result<ExpireModifierFlags, String> {
let mut f = ExpireModifierFlags::default();
let mut i = start;
while i < cmd.len() {
let raw = match parse_utf8(cmd[i]) {
Some(s) => s,
None => return Err("ERR syntax error".to_string()),
};
let u = raw.to_ascii_uppercase();
match u.as_str() {
"NX" => f.nx = true,
"XX" => f.xx = true,
"GT" => f.gt = true,
"LT" => f.lt = true,
_ => {
return Err(format!("ERR Unsupported option {}", raw));
}
}
i += 1;
}
if (f.lt || f.gt || f.xx) && f.nx {
return Err(
"ERR NX and XX, GT or LT options at the same time are not compatible".to_string(),
);
}
if f.gt && f.lt {
return Err("ERR GT and LT options at the same time are not compatible".to_string());
}
Ok(f)
}
pub fn expire_modifier_allows_set(
flags: &ExpireModifierFlags,
current: Option<SystemTime>,
new_abs: SystemTime,
) -> bool {
if flags.nx && current.is_some() {
return false;
}
if flags.xx && current.is_none() {
return false;
}
if flags.gt && current.is_none_or(|c| new_abs <= c) {
return false;
}
if flags.lt
&& let Some(c) = current
&& new_abs >= c
{
return false;
}
true
}
#[inline]
pub fn wall_now_ms_i128() -> i128 {
crate::script_clock::ttl_wall_ms_now() as i128
}
#[inline]
pub fn parse_bytes_as_i128(arg: &[u8]) -> Option<i128> {
let s = std::str::from_utf8(arg).ok()?;
if s.is_empty() {
return None;
}
s.parse().ok()
}
pub fn system_time_from_unix_millis_i128(ms: i128) -> Option<SystemTime> {
if ms >= 0 {
let u = u64::try_from(ms).ok()?;
UNIX_EPOCH.checked_add(Duration::from_millis(u))
} else {
let neg = ms.checked_neg()?;
let u = u64::try_from(neg).ok()?;
UNIX_EPOCH.checked_sub(Duration::from_millis(u))
}
}
#[inline]
pub fn ttl_remaining_ms(at: u64) -> i64 {
i64::try_from(at.saturating_sub(now_ms())).unwrap_or(i64::MAX)
}
#[inline]
pub fn ms_to_nearest_secs(ms: i64) -> i64 {
((ms as i128 + 500) / 1000) as i64
}
#[macro_export]
macro_rules! read_lock {
($shard:expr) => {
$shard.read()
};
}
#[macro_export]
macro_rules! write_lock {
($shard:expr) => {
$shard.write()
};
}
const ACTIVE_EXPIRE_BATCH: usize = 1024;
const TTL_SWEEP_STEPS: usize = 2048;
const ACTIVE_EXPIRE_BUDGET: Duration = Duration::from_millis(25);
const ACTIVE_EXPIRE_STALE_PERCENT: usize = 10;
#[derive(Default)]
pub struct ExpireCursor {
db: usize,
shard: usize,
part: usize,
parts: usize,
}
impl ExpireCursor {
pub fn part(part: usize, parts: usize) -> Self {
Self {
part,
parts,
..Self::default()
}
}
fn parts(&self) -> usize {
self.parts.max(1)
}
fn owns(&self, shard: usize) -> bool {
shard % self.parts() == self.part
}
}
fn expiry_threads() -> usize {
std::thread::available_parallelism()
.map(|n| n.get() / 4)
.unwrap_or(1)
.max(1)
}
pub fn active_expire_cycle(
store: &Store,
index_store: &IndexStore,
cursor: &mut ExpireCursor,
target: Option<&crate::expiry::Target>,
) -> bool {
if target.is_some_and(crate::expiry::Target::on_replica) {
return false;
}
let told = target.filter(|target| target.observed());
let shards: usize = store
.iter()
.map(|db| (0..db.len()).filter(|&s| cursor.owns(s)).count())
.sum();
if shards == 0 {
return false;
}
let started = std::time::Instant::now();
let mut visited = 0usize;
let (mut seen, mut due_total) = (0usize, 0usize);
let behind = stale;
while visited < shards {
if cursor.db >= store.len() {
cursor.db = 0;
}
let db_values = &store[cursor.db];
if cursor.shard >= db_values.len() {
cursor.db += 1;
cursor.shard = 0;
continue;
}
if !cursor.owns(cursor.shard) {
cursor.shard += 1;
continue;
}
let (db, shard) = (cursor.db, cursor.shard);
if !db_values[shard].holds_no_ttl() {
let now = now_ms();
if read_lock!(db_values[shard]).ttl_sweep_due(now) {
while !write_lock!(db_values[shard]).sweep_ttl(now, TTL_SWEEP_STEPS) {}
}
loop {
let (looked, due) = expire_pass(store, index_store, db, shard, now, told);
seen += looked;
due_total += due;
if started.elapsed() >= ACTIVE_EXPIRE_BUDGET {
return behind(seen, due_total);
}
if due < ACTIVE_EXPIRE_BATCH {
break;
}
}
}
cursor.shard += 1;
visited += 1;
if visited.is_multiple_of(64) && started.elapsed() >= ACTIVE_EXPIRE_BUDGET {
return visited < shards && behind(seen, due_total);
}
}
false
}
fn expire_pass(
store: &Store,
index_store: &IndexStore,
db: usize,
shard: usize,
now: u64,
told: Option<&crate::expiry::Target>,
) -> (usize, usize) {
let (due, looked) = read_lock!(store[db][shard]).due(now, ACTIVE_EXPIRE_BATCH);
if told.is_some() {
for part in due.chunks(TOLD_BATCH) {
expire_batch(store, index_store, db, shard, part, now, told);
}
} else if !due.is_empty() {
expire_batch(store, index_store, db, shard, &due, now, None);
}
(looked, due.len())
}
const TOLD_BATCH: usize = 64;
pub fn expire_keys_due_before(store: &Store, index_store: &IndexStore, before: u64) -> usize {
let mut deleted = 0;
for db in 0..store.len() {
for shard in 0..store[db].len() {
if store[db][shard].holds_no_ttl() {
continue;
}
loop {
let (due, _) = read_lock!(store[db][shard]).due(before, ACTIVE_EXPIRE_BATCH);
let full = due.len() == ACTIVE_EXPIRE_BATCH;
let gone = expire_batch(store, index_store, db, shard, &due, before, None);
deleted += gone;
if !full || gone == 0 {
break;
}
}
}
}
deleted
}
fn stale(seen: usize, due: usize) -> bool {
due > 0 && due * 100 > seen * ACTIVE_EXPIRE_STALE_PERCENT
}
fn expire_batch(
store: &Store,
index_store: &IndexStore,
db: usize,
shard: usize,
batch: &[Key],
now: u64,
told: Option<&crate::expiry::Target>,
) -> usize {
let _command = crate::command_gate::enter();
let _gate = told.map(|_| crate::write_gate::enter());
let tags = if crate::tag_locks::enabled() {
crate::tag_locks::try_lock_keys(batch.iter().map(|k| k.as_bytes()))
} else {
None
};
let batch: Vec<&Key> = match &tags {
Some(tags) if tags.left_some() => batch
.iter()
.filter(|key| tags.may_take(key.as_bytes()))
.collect(),
_ => batch.iter().collect(),
};
if batch.is_empty() {
return 0;
}
let ordered = told.map(|_| crate::expiry::order(db, batch.iter().map(|k| k.as_bytes())));
let unobserved = unobserved_order(told.is_none(), db, batch.iter().map(|k| k.as_bytes()));
if ordered.is_some() && crate::pause::expiry_deferred() {
return 0;
}
let id = crate::vector::store_id(store);
let marks = crate::vector::has_index_of(index_store, db);
let mut gone: Vec<&Key> = Vec::with_capacity(batch.len());
let mut freed: Vec<store::Taken> = Vec::with_capacity(batch.len());
{
let mut values = write_lock!(store[db][shard]);
if !crate::expiry::loading() {
for key in batch.iter().copied() {
if let Some(value) = values.remove_if_due(key, now) {
crate::keyspace_events::notify_expired(store, db, key);
if marks {
crate::vector::mark_leaving(id, db, key);
}
freed.push(value);
gone.push(key);
}
}
}
}
if let Some(told) = told {
told.propagate(db, gone.iter().map(|key| key.as_bytes()));
}
drop(ordered);
drop(unobserved);
drop(freed);
let count = gone.len();
for key in gone {
crate::stats::record_expired();
crate::stats::EXPIRED_KEYS_ACTIVE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
crate::watch::expired(store, db, key);
crate::tracking::expired(store, key);
crate::vector::maybe_unindex(index_store, db, key);
if marks {
crate::vector::unmark_leaving(id, db, key);
}
}
count
}
const SHRINK_PERIOD: Duration = Duration::from_secs(1);
fn shrink_sparse_tables(store: &Store, cursor: &ExpireCursor) {
for db in store.iter() {
for (s, shard) in db.iter().enumerate() {
if cursor.owns(s) {
shard.shrink_if_sparse();
}
}
}
}
pub(crate) fn unobserved_order<'a>(
unobserved: bool,
db: usize,
keys: impl Iterator<Item = &'a [u8]>,
) -> Option<crate::write_order::OrderGuard> {
(unobserved && !crate::command_gate::alone_on_this_thread())
.then(|| crate::write_order::lock_keys(db, keys))
}
#[inline]
pub fn lazy_expire_key(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
if is_expired(store, db, key) {
delete_key_if_expired(store, db, key)
} else {
false
}
}
#[inline]
pub fn expire_on_read(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
if crate::pause::expiry_deferred() {
return true;
}
delete_key_if_expired(store, db, key)
}
#[inline]
pub fn lazy_expire_on_read(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
is_expired(store, db, key) && expire_on_read(store, db, key)
}
pub fn spawn_active_expire_task(
store: Store,
index_store: IndexStore,
pubsub: crate::pubsub::PubSubHub,
latency: crate::latency::SharedLatencyTracker,
repl_state: &std::sync::Arc<crate::replication::ReplState>,
hub_tx: &crate::replication::HubTx,
) {
crate::keyspace_events::register_hub(&store, &pubsub);
crate::expiry::register(&store, repl_state, hub_tx);
crate::vector::register_index_store(&store, &index_store);
crate::field_expiry::rescan(&store);
let parts = expiry_threads();
for part in 0..parts {
let (store, index_store) = (store.clone(), index_store.clone());
let latency = (part == 0).then(|| latency.clone());
std::thread::spawn(move || {
let mut cursor = ExpireCursor::part(part, parts);
let target = crate::expiry::of(&store);
let mut wait = Duration::from_millis(100);
let mut shrunk_at = std::time::Instant::now();
loop {
std::thread::sleep(wait);
if !crate::expiry::active() {
wait = Duration::from_millis(100);
continue;
}
if crate::pause::expiry_deferred()
|| crate::expiry::loading()
|| target
.as_ref()
.is_some_and(crate::expiry::Target::stream_closed)
{
continue;
}
let started = std::time::Instant::now();
let behind =
active_expire_cycle(&store, &index_store, &mut cursor, target.as_ref());
wait = Duration::from_millis(if behind { 1 } else { 100 });
if shrunk_at.elapsed() >= SHRINK_PERIOD {
shrink_sparse_tables(&store, &cursor);
shrunk_at = std::time::Instant::now();
}
let Some(latency) = &latency else {
continue;
};
let threshold = crate::latency::threshold_ms();
let took = started.elapsed().as_millis() as u64;
if threshold > 0 && took >= threshold {
latency.record("expire-cycle", took.min(u32::MAX as u64) as u32);
}
crate::field_expiry::sweep(&store, &index_store);
}
});
}
}
pub fn glob_match(pattern: &str, text: &str) -> bool {
super::glob_redis::matches(pattern.as_bytes(), text.as_bytes())
}
pub fn glob_match_bytes(pattern: &[u8], text: &[u8]) -> bool {
super::glob_redis::matches(pattern, text)
}
pub const MAX_FIELD_DEADLINE_MS: i64 = 0xFFFF_FFFF_FFFF >> 2;
pub fn field_deadline_ms(n: i64, secs: bool, base_ms: i64) -> Option<i64> {
let ms = if secs {
if n > MAX_FIELD_DEADLINE_MS / 1000 {
return None;
}
n * 1000
} else {
n
};
ms.checked_add(base_ms)
.filter(|&at| at <= MAX_FIELD_DEADLINE_MS)
}
#[inline]
pub fn field_deadline_after(n: i64, secs: bool) -> Option<u64> {
if n < 0 {
return None;
}
field_deadline_ms(n, secs, now_ms() as i64).map(|at| at as u64)
}
pub fn invalid_field_expire_time(command: &str) -> Vec<u8> {
crate::resp::write::resp_error(&format!(
"ERR invalid expire time in '{}' command",
command.to_ascii_lowercase()
))
}
#[inline]
pub fn unix_ms(t: SystemTime) -> u64 {
match t.duration_since(UNIX_EPOCH) {
Ok(d) => d.as_millis().min(u64::MAX as u128) as u64,
Err(_) => 0,
}
}
#[inline]
pub fn from_unix_ms(ms: u64) -> SystemTime {
UNIX_EPOCH
.checked_add(Duration::from_millis(ms))
.unwrap_or_else(|| UNIX_EPOCH + Duration::from_secs(253_402_300_799))
}
#[inline]
pub fn now_ms() -> u64 {
crate::script_clock::wall_ms_now()
}
#[inline(always)]
pub fn is_past(at: u64) -> bool {
now_ms() > at && !crate::expiry::held()
}
pub fn is_expired(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
let shard = store::get_shard(&store[db], key);
if shard.holds_no_ttl() {
return false;
}
read_lock!(shard).expires(key).is_some_and(is_past)
}
pub fn get_expiry(
store: &Store,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
) -> Option<SystemTime> {
let shard = store::get_shard(&store[db], key);
if shard.holds_no_ttl() {
return None;
}
read_lock!(shard).expires(key).map(from_unix_ms)
}
pub fn parse_utf8(bytes: &[u8]) -> Option<&str> {
std::str::from_utf8(bytes).ok()
}
pub fn store_value(
store: &Store,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
value: KiviDBValue,
) {
let shard = store::get_shard(&store[db], key);
let replaced = write_lock!(shard).insert_expiring(key, value, None);
drop(replaced);
}
pub fn store_value_expiring(
store: &Store,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
value: KiviDBValue,
expires_at: Option<SystemTime>,
) {
let shard = store::get_shard(&store[db], key);
let replaced = write_lock!(shard).insert_expiring(key, value, expires_at.map(unix_ms));
drop(replaced);
}
pub fn set_expiry(
store: &Store,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
expires_at: SystemTime,
) -> bool {
let shard = store::get_shard(&store[db], key);
let set = write_lock!(shard).set_expires(key, unix_ms(expires_at));
if !set {
expire_if_past(store, db, key);
}
set
}
pub fn clear_expiry(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
let shard = store::get_shard(&store[db], key);
if shard.holds_no_ttl() {
if store::AccessScope::active() {
read_lock!(shard).contains_key(key);
}
return false;
}
let cleared = write_lock!(shard).persist(key);
if !cleared {
expire_if_past(store, db, key);
}
cleared
}
#[cold]
fn expire_if_past(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) {
if is_expired(store, db, key) {
delete_key_if_expired(store, db, key);
}
}
pub fn delete_key(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
take_key(store, db, key).is_some()
}
pub fn delete_key_sized(
store: &Store,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
) -> Option<usize> {
let value_shard = store::get_shard(&store[db], key);
let removed = write_lock!(value_shard).remove(key)?;
Some(removed.footprint())
}
pub fn take_key(
store: &Store,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
) -> Option<KiviDBValue> {
let value_shard = store::get_shard(&store[db], key);
let removed = write_lock!(value_shard).remove(key);
removed.map(store::Taken::into_value_to_free)
}
#[inline]
pub fn delete_key_if_expired(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
if crate::expiry::held() {
return false;
}
let shard = store::get_shard(&store[db], key);
let target = crate::expiry::of(store);
if target
.as_ref()
.is_some_and(crate::expiry::Target::on_replica)
{
return read_lock!(shard).expires(key).is_some_and(is_past);
}
let told = target.filter(crate::expiry::Target::observed);
let id = crate::vector::store_id(store);
let indexes = crate::vector::indexes_of(id, db);
let ordered = told
.as_ref()
.map(|_| crate::expiry::order(db, std::iter::once(key.as_ref())));
let unobserved = unobserved_order(told.is_none(), db, std::iter::once(key.as_ref()));
let removed = {
let mut map = write_lock!(shard);
let removed = map.remove_if_due(key, now_ms());
if removed.is_some() {
crate::keyspace_events::notify_expired(store, db, key);
if indexes.is_some() {
crate::vector::mark_leaving(id, db, key);
}
}
removed
};
let gone = removed.is_some();
if gone && let Some(told) = &told {
told.propagate(db, [key.as_ref()]);
}
drop(ordered);
drop(unobserved);
drop(removed);
if gone {
crate::stats::record_expired();
crate::watch::expired(store, db, key);
crate::tracking::expired(store, key);
if let Some(indexes) = &indexes {
crate::vector::maybe_unindex(indexes, db, key);
crate::vector::unmark_leaving(id, db, key);
}
}
gone
}
#[inline]
pub fn whole_score(score: f64) -> Option<i64> {
if score != 0.0 && score.abs() < 1e8 && score.fract() == 0.0 {
Some(score as i64)
} else {
None
}
}
pub fn format_score(score: f64) -> String {
if let Some(whole) = whole_score(score) {
return whole.to_string();
}
if score == f64::INFINITY {
return "inf".to_string();
}
if score == f64::NEG_INFINITY {
return "-inf".to_string();
}
if score == 0.0 {
return if score.is_sign_negative() { "-0" } else { "0" }.to_string();
}
let scientific = format!("{:e}", score.abs());
let (mantissa, exponent) = scientific.split_once('e').unwrap_or((&scientific, "0"));
let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
let exponent: i32 = exponent.parse().unwrap_or(0);
let count = digits.len() as i32;
let k = exponent - (count - 1);
let body = if k >= 0 && exponent.abs() < count + 7 {
format!("{digits}{}", "0".repeat(k as usize))
} else if k < 0 && (k > -7 || exponent.abs() < 4) {
let point = count + k;
if point <= 0 {
format!("0.{}{digits}", "0".repeat((-point) as usize))
} else {
format!(
"{}.{}",
&digits[..point as usize],
&digits[point as usize..]
)
}
} else {
let sign = if exponent < 0 { '-' } else { '+' };
if count > 1 {
format!("{}.{}e{sign}{}", &digits[..1], &digits[1..], exponent.abs())
} else {
format!("{digits}e{sign}{}", exponent.abs())
}
};
if score < 0.0 {
format!("-{body}")
} else {
body
}
}
#[cfg(test)]
mod score_format_tests {
use super::format_score;
#[test]
fn scores_are_written_as_redis_writes_them() {
for (score, text) in [
(0.0, "0"),
(1.0, "1"),
(-1.0, "-1"),
(1.5, "1.5"),
(-2.25, "-2.25"),
(10.0, "10"),
(100000.0, "100000"),
(0.1, "0.1"),
(0.001, "0.001"),
(3.0e-5, "0.00003"),
(1.0e-7, "1e-7"),
(1.0e21, "1e+21"),
(123456789012345680.0, "123456789012345680"),
(1.7976931348623157e308, "1.7976931348623157e+308"),
(-1.7976931348623157e308, "-1.7976931348623157e+308"),
(f64::INFINITY, "inf"),
(f64::NEG_INFINITY, "-inf"),
] {
assert_eq!(format_score(score), text, "{score:e}");
}
}
}
pub fn parse_mpop(
cmd: &[&[u8]],
at: usize,
words: [&str; 2],
) -> Result<(usize, bool, usize), Vec<u8>> {
use crate::resp::write::resp_error;
let num_keys =
cmd.get(at)
.and_then(|raw| std::str::from_utf8(raw).ok())
.and_then(|s| s.parse::<i64>().ok())
.filter(|n| *n > 0)
.ok_or_else(|| resp_error("ERR numkeys should be greater than 0"))? as usize;
let which = at + 1 + num_keys;
let Some(word) = cmd.get(which) else {
return Err(resp_error("ERR syntax error"));
};
let second = if word.eq_ignore_ascii_case(words[0].as_bytes()) {
false
} else if word.eq_ignore_ascii_case(words[1].as_bytes()) {
true
} else {
return Err(resp_error("ERR syntax error"));
};
let count = match &cmd[which + 1..] {
[] => 1,
[option, n] if option.eq_ignore_ascii_case(b"COUNT") => std::str::from_utf8(n)
.ok()
.and_then(|s| s.parse::<i64>().ok())
.filter(|n| *n > 0)
.ok_or_else(|| resp_error("ERR count should be greater than 0"))?
as usize,
_ => return Err(resp_error("ERR syntax error")),
};
Ok((num_keys, second, count))
}
const SCAN_POSITION_BITS: u32 = 48;
pub fn scan_position(element: &[u8]) -> u64 {
static HASHER: std::sync::LazyLock<ahash::RandomState> = std::sync::LazyLock::new(|| {
ahash::RandomState::with_seeds(0x6b69_7669, 0x7363_616e, 0x636f_6e73, 0x6973_7465)
});
HASHER.hash_one(element) >> (64 - SCAN_POSITION_BITS)
}
pub fn scan_page<T>(
elements: impl Iterator<Item = (u64, T)>,
cursor: u64,
count: usize,
len: usize,
pages: usize,
) -> (Vec<T>, u64) {
let want = count.max(len / pages.max(1)).max(1);
let mut ahead: Vec<(u64, T)> = elements
.filter(|(position, _)| *position >= cursor)
.collect();
if ahead.len() <= want {
return (ahead.into_iter().map(|(_, element)| element).collect(), 0);
}
ahead.select_nth_unstable_by_key(want, |(position, _)| *position);
let mut boundary = ahead[want].0;
if ahead[..want]
.iter()
.all(|(position, _)| *position == boundary)
{
boundary += 1;
}
let more = ahead.iter().any(|(position, _)| *position >= boundary);
(
ahead
.into_iter()
.filter(|(position, _)| *position < boundary)
.map(|(_, element)| element)
.collect(),
if more { boundary } else { 0 },
)
}
#[derive(Default)]
pub struct ScanOptions {
pub pattern: Option<Vec<u8>>,
pub count: usize,
pub of_type: Option<String>,
pub no_values: bool,
pub no_scores: bool,
}
pub fn scan_arguments(
cmd: &[&[u8]],
at: usize,
extra: &[&str],
) -> Result<(u64, ScanOptions), Vec<u8>> {
use crate::resp::write::resp_error;
let syntax = || resp_error("ERR syntax error");
let cursor = cmd
.get(at)
.and_then(|raw| parse_utf8(raw))
.and_then(|s| s.parse::<u64>().ok())
.ok_or_else(|| resp_error("ERR invalid cursor"))?;
let mut options = ScanOptions {
count: 10,
..Default::default()
};
let mut i = at + 1;
while i < cmd.len() {
let word = String::from_utf8_lossy(cmd[i]).to_ascii_uppercase();
let value = cmd.get(i + 1);
match (word.as_str(), value) {
("MATCH", Some(pattern)) => {
options.pattern = Some(pattern.to_vec());
i += 2;
}
("COUNT", Some(count)) => {
options.count = match parse_utf8(count).and_then(|s| s.parse::<i64>().ok()) {
Some(n) if n >= 1 => n as usize,
Some(_) => return Err(syntax()),
None => return Err(resp_error("ERR value is not an integer or out of range")),
};
i += 2;
}
("TYPE", Some(of_type)) if extra.contains(&"TYPE") => {
options.of_type = Some(String::from_utf8_lossy(of_type).to_ascii_lowercase());
i += 2;
}
("NOVALUES", _) if extra.contains(&"NOVALUES") => {
options.no_values = true;
i += 1;
}
("NOSCORES", _) if extra.contains(&"NOSCORES") => {
options.no_scores = true;
i += 1;
}
_ => return Err(syntax()),
}
}
Ok((cursor, options))
}
#[cfg(test)]
mod scan_tests {
use super::{scan_page, scan_position};
fn scan(
set: &mut std::collections::BTreeSet<u32>,
count: usize,
mut change: impl FnMut(&mut std::collections::BTreeSet<u32>, usize),
) -> Vec<u32> {
let mut seen = Vec::new();
let mut cursor = 0;
let mut calls = 0;
loop {
let (page, next) = scan_page(
set.iter().map(|n| (scan_position(&n.to_le_bytes()), *n)),
cursor,
count,
set.len(),
1024,
);
seen.extend(page);
calls += 1;
change(set, calls);
if next == 0 {
return seen;
}
assert!(next > cursor, "a scan goes forward");
cursor = next;
}
}
#[test]
fn everything_is_returned_once_when_nothing_changes() {
let mut set: std::collections::BTreeSet<u32> = (0..5000).collect();
let mut seen = scan(&mut set, 10, |_, _| {});
assert_eq!(seen.len(), 5000);
seen.sort_unstable();
seen.dedup();
assert_eq!(seen.len(), 5000);
}
#[test]
fn what_stays_is_returned_whatever_else_comes_and_goes() {
let mut set: std::collections::BTreeSet<u32> = (0..1100).collect();
let seen = scan(&mut set, 10, |set, calls| {
if calls == 3 {
set.retain(|n| *n < 100);
}
if calls == 5 {
set.extend(5000..7000);
}
if calls == 9 {
set.retain(|n| *n < 100 || *n % 2 == 0);
}
});
for n in 0..100 {
assert!(
seen.contains(&n),
"{n} was there throughout and was not returned"
);
}
}
#[test]
fn a_page_is_not_smaller_than_a_scan_in_a_thousand_calls_needs() {
let set: Vec<u32> = (0..100_000).collect();
let (page, next) = scan_page(
set.iter().map(|n| (scan_position(&n.to_le_bytes()), *n)),
0,
10,
set.len(),
1024,
);
assert!(page.len() >= 97 && next != 0);
let (page, next) = scan_page([(5u64, 'a'), (9, 'b')].into_iter(), 0, 10, 2, 1024);
assert_eq!((page, next), (vec!['a', 'b'], 0));
}
}
pub use crate::key_bytes::{bytes_of as name_to_bytes, text_of as name_from_bytes};
#[cfg(test)]
mod whole_score_tests {
use super::{format_score, whole_score};
#[test]
fn a_whole_score_is_written_as_its_digits_and_the_rest_as_before() {
for (score, text) in [
(3.0, "3"),
(-12.0, "-12"),
(1.0, "1"),
(99_999_999.0, "99999999"),
(-99_999_999.0, "-99999999"),
(100_000_000.0, "1e+8"),
(10_000_000.0, "10000000"),
(123_456_789.0, "123456789"),
(0.0, "0"),
(-0.0, "-0"),
(1.5, "1.5"),
(-0.25, "-0.25"),
(f64::INFINITY, "inf"),
(f64::NEG_INFINITY, "-inf"),
] {
assert_eq!(format_score(score), text, "{score:?}");
}
assert_eq!(whole_score(42.0), Some(42));
assert_eq!(whole_score(0.0), None);
assert_eq!(whole_score(-0.0), None);
assert_eq!(whole_score(0.5), None);
assert_eq!(whole_score(1e8), None);
assert_eq!(whole_score(f64::NAN), None);
assert_eq!(whole_score(f64::INFINITY), None);
}
}
#[cfg(test)]
mod active_expiry_tests {
use super::*;
use crate::shared_bytes::SharedBytes;
fn put(store: &Store, key: &(impl AsRef<[u8]> + ?Sized), at: SystemTime) {
store_value(
store,
0,
key,
KiviDBValue::String(SharedBytes::from(&b"v"[..])),
);
set_expiry(store, 0, key, at);
}
fn keys(store: &Store) -> usize {
store[0].iter().map(|s| s.read().len()).sum()
}
fn times(store: &Store) -> usize {
store[0].iter().map(|s| s.read().ttl_len()).sum()
}
#[test]
fn a_time_to_live_set_or_taken_away_finds_a_key_past_its_time_gone() {
let store = store::new_store(1);
let past = SystemTime::now() - Duration::from_secs(5);
let later = SystemTime::now() + Duration::from_secs(3600);
put(&store, "persisted", past);
put(&store, "expired", past);
put(&store, "live", later);
assert_eq!(keys(&store), 3);
assert!(!clear_expiry(&store, 0, "persisted"));
assert!(!set_expiry(&store, 0, "expired", later));
assert_eq!(keys(&store), 1, "both deleted");
assert_eq!(times(&store), 1);
assert!(set_expiry(
&store,
0,
"live",
later + Duration::from_secs(1)
));
assert!(clear_expiry(&store, 0, "live"));
assert_eq!((keys(&store), times(&store)), (1, 0));
assert!(!set_expiry(&store, 0, "missing", later));
assert!(!clear_expiry(&store, 0, "missing"));
assert_eq!(keys(&store), 1);
}
#[test]
fn unix_milliseconds_go_both_ways() {
let t = UNIX_EPOCH + Duration::from_millis(1_700_000_000_123);
assert_eq!(from_unix_ms(unix_ms(t)), t);
assert_eq!(unix_ms(UNIX_EPOCH - Duration::from_secs(1)), 0);
assert!(from_unix_ms(u64::MAX) > t);
}
#[test]
fn a_cycle_removes_every_expired_key_and_no_other() {
let store = store::new_store(1);
let index: IndexStore = Default::default();
let past = SystemTime::now() - Duration::from_secs(5);
let future = SystemTime::now() + Duration::from_secs(3600);
for i in 0..20_000 {
put(&store, &format!("gone:{i}"), past);
put(&store, &format!("kept:{i}"), future);
}
store_value(
&store,
0,
"forever",
KiviDBValue::String(SharedBytes::from(&b"v"[..])),
);
assert_eq!(times(&store), 40_000);
let before = crate::stats::EXPIRED_KEYS_ACTIVE.load(std::sync::atomic::Ordering::Relaxed);
let mut cursor = ExpireCursor::default();
let mut cycles = 0;
while keys(&store) > 20_001 {
active_expire_cycle(&store, &index, &mut cursor, None);
cycles += 1;
assert!(cycles < 1000, "the cycle never caught up");
}
assert_eq!(keys(&store), 20_001);
assert_eq!(times(&store), 20_000);
assert!(
store[0]
.iter()
.all(|s| s.read().keys().all(|k| !k.starts_with(b"gone:")))
);
let after = crate::stats::EXPIRED_KEYS_ACTIVE.load(std::sync::atomic::Ordering::Relaxed);
assert!(after - before >= 20_000);
}
#[test]
fn keys_that_are_not_text_expire() {
let store = store::new_store(1);
let index: IndexStore = Default::default();
let past = SystemTime::now() - Duration::from_secs(5);
let names: [&[u8]; 3] = [b"\xff\x00k", b"\xfe", b"text"];
for key in names {
put(&store, key, past);
}
let now = now_ms();
for key in names {
let shard = store::shard_index(store[0].len(), key);
expire_batch(&store, &index, 0, shard, &[Key::new(key)], now, None);
}
assert_eq!(keys(&store), 0);
assert_eq!(times(&store), 0);
}
#[test]
fn a_key_given_a_new_time_is_kept() {
let _u = crate::expiry::Undisturbed::here();
let store = store::new_store(1);
let index: IndexStore = Default::default();
let past = SystemTime::now() - Duration::from_secs(5);
put(&store, "k", past);
put(&store, "j", past);
let now = now_ms();
let due = |key: &str| {
let shard = store::shard_index(store[0].len(), key);
assert!(
read_lock!(store[0][shard])
.due(now, 10)
.0
.iter()
.any(|k| k == key)
);
shard
};
let shard = due("k");
put(&store, "k", SystemTime::now() + Duration::from_secs(60));
expire_batch(&store, &index, 0, shard, &[Key::from("k")], now, None);
let shard = due("j");
store_value(
&store,
0,
"j",
KiviDBValue::String(SharedBytes::from(&b"w"[..])),
);
expire_batch(&store, &index, 0, shard, &[Key::from("j")], now, None);
assert_eq!(keys(&store), 2);
assert_eq!(times(&store), 1);
}
#[test]
fn behind_takes_more_than_a_tenth_due() {
assert!(!stale(1_800_000, 9_000));
assert!(!stale(1_000, 100));
assert!(stale(1_000, 101));
assert!(stale(40_000, 20_000));
assert!(!stale(0, 0));
}
#[test]
fn a_full_round_is_not_behind() {
let _u = crate::expiry::Undisturbed::here();
let store = store::new_store(1);
let index: IndexStore = Default::default();
let past = SystemTime::now() - Duration::from_secs(5);
let future = SystemTime::now() + Duration::from_secs(3600);
for i in 0..2_000 {
put(&store, &format!("kept:{i}"), future);
}
put(&store, "gone", past);
let mut cursor = ExpireCursor::default();
assert!(!active_expire_cycle(&store, &index, &mut cursor, None));
assert_eq!(keys(&store), 2_000);
}
#[test]
fn a_pass_takes_one_batch_and_stops() {
let _u = crate::expiry::Undisturbed::here();
let store = store::new_store(1);
let index: IndexStore = Default::default();
let past = SystemTime::now() - Duration::from_secs(5);
let shards = store[0].len();
let mut n = 0;
let mut i = 0;
while n < 3 * ACTIVE_EXPIRE_BATCH {
let key = format!("gone:{i:0>40}");
i += 1;
if store::shard_index(shards, &key) == 0 {
put(&store, &key, past);
n += 1;
}
}
let (looked, due) = expire_pass(&store, &index, 0, 0, now_ms(), None);
assert_eq!(due, ACTIVE_EXPIRE_BATCH);
assert_eq!(
looked, ACTIVE_EXPIRE_BATCH,
"it went past the batch's last key"
);
assert_eq!(keys(&store), n - ACTIVE_EXPIRE_BATCH);
let mut cursor = ExpireCursor::default();
let mut cycles = 0;
while keys(&store) > 0 {
active_expire_cycle(&store, &index, &mut cursor, None);
cycles += 1;
assert!(cycles < 1000, "never emptied");
}
}
#[test]
fn parts_share_the_shards() {
let _u = crate::expiry::Undisturbed::here();
let store = store::new_store(1);
let index: IndexStore = Default::default();
let past = SystemTime::now() - Duration::from_secs(5);
for i in 0..5_000 {
put(&store, &format!("gone:{i}"), past);
}
let mut even = ExpireCursor::part(0, 2);
while active_expire_cycle(&store, &index, &mut even, None) {}
let shards = store[0].len();
for (s, cell) in store[0].iter().enumerate() {
let left = cell.read().ttl_len();
if s % 2 == 0 {
assert_eq!(left, 0, "shard {s} is part 0's");
}
}
let odd_left: usize = (1..shards)
.step_by(2)
.map(|s| store[0][s].read().ttl_len())
.sum();
assert!(odd_left > 0, "part 0 went through part 1's shards");
let mut odd = ExpireCursor::part(1, 2);
while active_expire_cycle(&store, &index, &mut odd, None) {}
assert_eq!(times(&store), 0);
assert_eq!(keys(&store), 0);
}
}