use std::sync::atomic::{AtomicU64, Ordering};
use tokio::sync::mpsc;
pub static AOF_WRITTEN: AtomicU64 = AtomicU64::new(0);
pub static AOF_FSYNCED: AtomicU64 = AtomicU64::new(0);
pub static AOF_LOST_RECORDS: AtomicU64 = AtomicU64::new(0);
pub static AOF_ACKS_BEFORE_WRITE: AtomicU64 = AtomicU64::new(0);
pub fn record_lost_aof_record() {
if AOF_LOST_RECORDS.fetch_add(1, Ordering::Relaxed) == 0 {
log_error!(
"AOF writer unavailable ā write records are being lost; \
the AOF can no longer reconstruct this dataset"
);
}
}
pub static AOF_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub const AOF_MAGIC: &[u8; 8] = b"KIVIAOF1";
pub const AOF_HEADER_LEN: usize = 8 + 1 + 8;
const AOF_FLAG_PREAMBLE: u8 = 1;
pub const AOF_DELTA_MAGIC: &[u8; 8] = b"KIVIDLT1";
pub const AOF_DELTA_HEADER_LEN: usize = 16;
pub const AOF_GEN_PATH: &str = "dump.kdb.gen";
static AOF_LAST_REWRITE_MS: AtomicU64 = AtomicU64::new(u64::MAX);
static AOF_BASE_SIZE: AtomicU64 = AtomicU64::new(0);
static AOF_LAST_REWRITE_OK: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(true);
pub fn current_size() -> u64 {
std::fs::metadata(AOF_PATH).map(|m| m.len()).unwrap_or(0)
}
pub fn base_size() -> u64 {
AOF_BASE_SIZE.load(Ordering::Relaxed)
}
pub fn record_base_size() {
AOF_BASE_SIZE.store(current_size(), Ordering::Relaxed);
}
pub fn last_rewrite_duration() -> Option<std::time::Duration> {
match AOF_LAST_REWRITE_MS.load(Ordering::Relaxed) {
u64::MAX => None,
ms => Some(std::time::Duration::from_millis(ms)),
}
}
pub fn last_rewrite_ok() -> bool {
AOF_LAST_REWRITE_OK.load(Ordering::Relaxed)
}
pub fn rewrite_in_progress() -> bool {
REWRITE_ACTIVE.load(Ordering::Relaxed) || REWRITE_ASKED.load(Ordering::Relaxed)
}
struct BackgroundRewrite {
running: bool,
again: bool,
}
static BACKGROUND_REWRITE: parking_lot::Mutex<BackgroundRewrite> =
parking_lot::Mutex::new(BackgroundRewrite {
running: false,
again: false,
});
static REWRITE_ASKED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn checkpoint_in_background(
store: crate::store::Store,
index_store: crate::vector::IndexStore,
) {
{
let mut rewrite = BACKGROUND_REWRITE.lock();
if rewrite.running {
rewrite.again = true;
return;
}
rewrite.running = true;
REWRITE_ASKED.store(true, Ordering::Release);
}
fn stopped() {
let mut rewrite = BACKGROUND_REWRITE.lock();
rewrite.running = false;
rewrite.again = false;
REWRITE_ASKED.store(false, Ordering::Release);
}
struct Unwinding;
impl Drop for Unwinding {
fn drop(&mut self) {
if std::thread::panicking() {
stopped();
}
}
}
let spawned = std::thread::Builder::new()
.name("kividb-bgrewrite".into())
.spawn(move || {
let _unwinding = Unwinding;
loop {
BACKGROUND_REWRITE.lock().again = false;
if let Err(e) = checkpoint(&store, &index_store) {
log_warn!("AOF: BGREWRITEAOF failed: {e}");
}
let mut rewrite = BACKGROUND_REWRITE.lock();
if !rewrite.again {
rewrite.running = false;
REWRITE_ASKED.store(false, Ordering::Release);
return;
}
}
});
if let Err(e) = spawned {
stopped();
log_error!("AOF: BGREWRITEAOF could not start its thread: {e}");
}
}
static FLUSH_TX: std::sync::OnceLock<tokio::sync::mpsc::Sender<()>> = std::sync::OnceLock::new();
static WRITER_RUNNING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static TURN_OVER_WAITERS: parking_lot::Mutex<
Vec<(u64, std::sync::mpsc::SyncSender<std::io::Result<OldLog>>)>,
> = parking_lot::Mutex::new(Vec::new());
type OldLog = Option<(std::fs::File, u64)>;
static OLD_LOG_UNSYNCED: AtomicU64 = AtomicU64::new(0);
static TURN_OVERS: AtomicU64 = AtomicU64::new(0);
fn old_log_synced(seen: u64) {
let _ = OLD_LOG_UNSYNCED.compare_exchange(seen, 0, Ordering::AcqRel, Ordering::Acquire);
}
const TURN_OVER_MARK: &[u8] = b"\0kividb-aof-turn-over\0";
fn turn_over_mark(generation: u64) -> Vec<u8> {
let mut mark = TURN_OVER_MARK.to_vec();
mark.extend_from_slice(&generation.to_le_bytes());
mark
}
fn as_turn_over_mark(item: &[u8]) -> Option<u64> {
let rest = item.strip_prefix(TURN_OVER_MARK)?;
Some(u64::from_le_bytes(rest.try_into().ok()?))
}
struct Log {
rx: mpsc::UnboundedReceiver<Vec<u8>>,
file: std::fs::File,
}
static LOG: parking_lot::Mutex<Option<Log>> = parking_lot::const_mutex(None);
static UNOPENED: parking_lot::Mutex<Option<mpsc::UnboundedReceiver<Vec<u8>>>> =
parking_lot::const_mutex(None);
static LOG_SUPERSEDED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn log_superseded() {
LOG_SUPERSEDED.store(true, Ordering::Relaxed);
}
pub fn open_log(_turn: &CheckpointTurn) -> std::io::Result<()> {
let made = |e: std::io::Error| {
std::io::Error::new(e.kind(), format!("a new {AOF_PATH} cannot be made: {e}"))
};
let mut log = LOG.lock();
if let Some(log) = log.as_mut() {
let on_disk = DumpOnDisk::read(std::path::Path::new("dump.kdb").exists());
if LOG_SUPERSEDED.load(Ordering::Relaxed) || on_disk.age_of(AOF_PATH) != LogAge::GoesOn {
write_queued(&mut log.file, &mut log.rx, None);
log.file = start_new_log(NewLogWhy::Enable, &[]).map_err(made)?;
}
return Ok(());
}
let mut unopened = UNOPENED.lock();
let Some(rx) = unopened.take() else {
return Err(std::io::Error::other("the AOF writer has not started yet"));
};
match start_new_log(NewLogWhy::EnableOverEarlierRun, &[]) {
Ok(file) => {
*log = Some(Log { rx, file });
Ok(())
}
Err(e) => {
*unopened = Some(rx);
Err(made(e))
}
}
}
fn start_new_log(why: NewLogWhy, added: &[u8]) -> std::io::Result<std::fs::File> {
let mut kept = Vec::new();
for path in [AOF_PREV_PATH, AOF_PATH, TURN_OVER_TMP] {
if let Some(name) = keep_aside(path)? {
kept.push((path, name));
}
}
if !kept.is_empty() {
sync_dir()?;
}
for (path, name) in &kept {
let why = if *path == TURN_OVER_TMP {
NewLogWhy::Older
} else {
why
};
log_warn!("{}", kept_warning(why, path, name));
}
let file = write_new_log(added)?;
remove_log_leftovers()?;
LOG_SUPERSEDED.store(false, Ordering::Relaxed);
Ok(file)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NewLogWhy {
Enable,
EnableOverEarlierRun,
Older,
AddedTo { prev: bool, log_whole: bool },
FinishedBesideSaveWithAofOff,
}
fn kept_warning(why: NewLogWhy, path: &str, name: &str) -> String {
let kept = format!("It is kept as {name}, which the server never removes.");
let apply = format!(
"Writes in it that are not in dump.kdb are not in the dataset. To apply those, send them \
to the server (`tail -c +17 {name} | redis-cli --pipe` for a file that starts with \
KIVIDLT1, `redis-cli --pipe < {name}` for one that starts with `*`), leaving out what \
dump.kdb holds, which would be applied twice; remove the file once it is not needed"
);
match why {
NewLogWhy::Enable => format!(
"AOF: {path} no longer goes on from dump.kdb (a save with the AOF off, or a full \
sync, came since), and the AOF turned on starts a new log. {kept} Its writes are \
already in the dataset: this server made them or replayed them (or a full sync \
replaced them with its master's dataset). Do not send them to the server, which \
would apply them twice; remove the file once it is not needed"
),
NewLogWhy::EnableOverEarlierRun => format!(
"AOF: {path} was left by an earlier run and is not part of this dataset, and the AOF \
turned on starts a new log. {kept} {apply}"
),
NewLogWhy::AddedTo {
log_whole: true, ..
} if path == AOF_PATH => format!(
"AOF: {path} was written to after dump.kdb was saved with the AOF off, and the log \
starts again on dump.kdb with its records. {kept} All of its records have been \
replayed, and are in the dataset: do not send the file to the server, which would \
apply them twice. Remove the file once it is not needed"
),
NewLogWhy::AddedTo { prev, .. } if path != AOF_PREV_PATH || prev => format!(
"AOF: {path} was added to after dump.kdb was saved with the AOF off, and the log \
starts again on dump.kdb with what was added. {kept} What was added to it since that \
save has been replayed, and is in the dataset: do not send the file to the server, \
which would apply those writes twice. What it held before that save is older than \
dump.kdb and was not replayed: if writes from then are missing, read the file (RESP, \
after a 16-byte header if it starts with KIVIDLT1) and send only those. Remove the \
file once it is not needed"
),
NewLogWhy::FinishedBesideSaveWithAofOff => format!(
"AOF: {path} was left by a checkpoint, beside a log that goes on from dump.kdb, and \
dump.kdb.gen is that of a save with the AOF off. {kept} Its records may be in \
dump.kdb or in the log already, or in neither: do not send the whole file to the \
server, which could apply writes twice. If writes from it are missing, read it \
(RESP, after a 16-byte header if it starts with KIVIDLT1) and send only those; \
remove the file once it is not needed"
),
NewLogWhy::Older | NewLogWhy::AddedTo { .. } => {
format!("AOF: {path} is older than dump.kdb and is not replayed. {kept} {apply}")
}
}
}
const KEPT_PREFIX: &str = "superseded.";
fn keep_aside(path: &str) -> std::io::Result<Option<String>> {
let len = match std::fs::metadata(path) {
Ok(meta) => meta.len(),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
let header = if aof_delta_generation(&read_head(path)).is_some() {
AOF_DELTA_HEADER_LEN as u64
} else {
0
};
if len <= header {
return Ok(None);
}
let suffix = format!(".{path}");
for (kept, kept_len) in kept_logs() {
if kept_len == len && kept.ends_with(&suffix) && same_bytes(path, &kept).unwrap_or(false) {
std::fs::File::open(&kept)?.sync_all()?;
return Ok(Some(kept));
}
}
static SEQ: AtomicU64 = AtomicU64::new(0);
let ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |at| at.as_millis());
let name = format!(
"{KEPT_PREFIX}{ms}.{}.{path}",
SEQ.fetch_add(1, Ordering::Relaxed)
);
if std::fs::hard_link(path, &name).is_err() {
copy_synced(path, &name, |from, to| std::fs::copy(from, to))?;
}
Ok(Some(name))
}
fn same_bytes(a: &str, b: &str) -> std::io::Result<bool> {
use std::io::Read;
fn fill(file: &mut std::fs::File, buf: &mut [u8]) -> std::io::Result<usize> {
let mut filled = 0;
while filled < buf.len() {
match file.read(&mut buf[filled..])? {
0 => break,
n => filled += n,
}
}
Ok(filled)
}
let (mut fa, mut fb) = (std::fs::File::open(a)?, std::fs::File::open(b)?);
if fa.metadata()?.len() != fb.metadata()?.len() {
return Ok(false);
}
let (mut ba, mut bb) = (vec![0u8; 64 * 1024], vec![0u8; 64 * 1024]);
loop {
let (n, m) = (fill(&mut fa, &mut ba)?, fill(&mut fb, &mut bb)?);
if ba[..n] != bb[..m] {
return Ok(false);
}
if n == 0 {
return Ok(true);
}
}
}
fn copy_synced(
from: &str,
to: &str,
copy: impl FnOnce(&str, &str) -> std::io::Result<u64>,
) -> std::io::Result<()> {
let copied = copy(from, to).and_then(|_| std::fs::File::open(to)?.sync_all());
if copied.is_err() {
let _ = std::fs::remove_file(to);
}
copied
}
fn kept_logs() -> Vec<(String, u64)> {
let Ok(entries) = std::fs::read_dir(".") else {
return Vec::new();
};
let mut kept: Vec<(String, u64)> = entries
.flatten()
.filter_map(|entry| {
let name = entry.file_name().to_string_lossy().into_owned();
(name.starts_with(KEPT_PREFIX) && name.contains(AOF_PATH)).then(|| {
let len = entry.metadata().map_or(0, |meta| meta.len());
(name, len)
})
})
.collect();
kept.sort();
kept
}
pub fn kept_logs_size() -> (usize, u64) {
let kept = kept_logs();
(kept.len(), kept.iter().map(|(_, len)| len).sum())
}
fn warn_of_kept_logs() {
let kept: Vec<String> = kept_logs().into_iter().map(|(name, _)| name).collect();
if kept.is_empty() {
return;
}
log_warn!(
"AOF: {} log(s) kept aside, never replayed and never removed by the server, are in the \
data directory: {}. Each may hold writes that are not in dump.kdb (see the warning \
logged when it was kept); remove them once they are not needed",
kept.len(),
kept.join(", ")
);
}
fn write_new_log(added: &[u8]) -> std::io::Result<std::fs::File> {
use std::io::Write;
let generation = generation_of_dump_on_disk()?;
let tmp = format!("{AOF_PATH}.tmp");
let made = (|| -> std::io::Result<std::fs::File> {
remove_if_there(&tmp)?;
let mut file = std::fs::OpenOptions::new()
.append(true)
.create_new(true)
.open(&tmp)?;
file.write_all(&delta_header(generation))?;
file.write_all(added)?;
file.sync_all()?;
std::fs::rename(&tmp, AOF_PATH)?;
Ok(file)
})();
let file = made.inspect_err(|_| {
let _ = std::fs::remove_file(&tmp);
})?;
sync_dir()?;
Ok(file)
}
fn open_log_at_start() -> std::io::Result<std::fs::File> {
let make = match std::fs::symlink_metadata(AOF_PATH) {
Ok(meta) => meta.is_file() && meta.len() == 0,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
Err(e) => return Err(e),
};
if make {
return write_new_log(&[]);
}
open_aof()
}
fn remove_log_leftovers() -> std::io::Result<()> {
for left in [TURN_OVER_TMP, TURN_OVER_APPENDING, AOF_PREV_PATH] {
failpoint("new-log-removing");
remove_if_there(left)?;
}
sync_dir()
}
fn remove_if_there(path: &str) -> std::io::Result<()> {
match std::fs::remove_file(path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
}
fn generation_of_dump_on_disk() -> std::io::Result<u64> {
if !std::path::Path::new("dump.kdb").exists() {
return Ok(read_generation());
}
let found = file_fingerprint("dump.kdb")?;
match read_saved() {
Some(saved) if saved.dump == found => Ok(saved.number),
_ => {
let generation = next_generation();
write_saved(generation, found, Some(logs_on_disk()?))?;
sync_dir()?;
log_warn!(
"AOF: {AOF_GEN_PATH} did not describe dump.kdb (saved with the AOF off by an \
earlier release, or replaced) ā dump.kdb is now save number {generation}"
);
Ok(generation)
}
}
}
pub(crate) fn dump_saved_without_log() {
LOG_SUPERSEDED.store(true, Ordering::Relaxed);
}
static QUEUED: std::sync::LazyLock<tokio::sync::Notify> =
std::sync::LazyLock::new(tokio::sync::Notify::new);
#[inline]
pub fn records_queued() {
if !acks_wait() {
QUEUED.notify_one();
}
}
#[inline]
pub fn stream_applied() {
if WRITER_RUNNING.load(Ordering::Acquire) {
QUEUED.notify_one();
}
}
fn write_what_is_queued(block: bool) -> Option<bool> {
let mut log = if block { LOG.lock() } else { LOG.try_lock()? };
let log = log.as_mut()?;
Some(write_queued(&mut log.file, &mut log.rx, None).1)
}
const BARRIER_MARK: &[u8] = b"\0kividb-aof-barrier\0";
static BARRIERS: std::sync::LazyLock<
parking_lot::Mutex<ahash::AHashMap<u64, tokio::sync::oneshot::Sender<()>>>,
> = std::sync::LazyLock::new(Default::default);
static NEXT_BARRIER: AtomicU64 = AtomicU64::new(1);
fn as_barrier(item: &[u8]) -> Option<u64> {
let rest = item.strip_prefix(BARRIER_MARK)?;
Some(u64::from_le_bytes(rest.try_into().ok()?))
}
static ACK_AFTER_WRITE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
pub fn set_ack_after_write(on: bool) {
ACK_AFTER_WRITE.store(on, Ordering::Relaxed);
}
static FSYNC_ALWAYS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn set_fsync_always(on: bool) {
FSYNC_ALWAYS.store(on, Ordering::Relaxed);
SYNC_WANTED.notify_one();
QUEUED.notify_one();
}
#[inline]
fn fsync_always() -> bool {
FSYNC_ALWAYS.load(Ordering::Relaxed)
}
static UNSYNCED_BARRIERS: parking_lot::Mutex<Vec<u64>> = parking_lot::const_mutex(Vec::new());
static SYNC_WANTED: tokio::sync::Notify = tokio::sync::Notify::const_new();
fn syncs_for_replies() -> bool {
fsync_always() || !UNSYNCED_BARRIERS.lock().is_empty()
}
fn sync_failed_under_always(what: &str, e: &std::io::Error) -> ! {
log_fatal!(
"AOF: {what} failed under appendfsync always: {e} ā exiting rather than acknowledge writes that may not be on disk"
);
std::process::exit(1);
}
#[inline]
pub fn acks_wait() -> bool {
AOF_ENABLED.load(Ordering::Relaxed)
&& (ACK_AFTER_WRITE.load(Ordering::Relaxed) || fsync_always())
}
#[inline]
pub fn may_log(cmd: &[&[u8]]) -> bool {
let Some(&cmd0) = cmd.first() else {
return false;
};
if crate::replication::is_write_command_bytes(cmd0) {
return true;
}
let is = |name: &str| cmd0.eq_ignore_ascii_case(name.as_bytes());
let by_arguments =
|name: &str| is(name) && crate::replication::command_mutates_for_replication(name, cmd);
match cmd0.len() {
4 => is("EVAL") || is("EXEC"),
5 => is("FCALL"),
6 => by_arguments("SCRIPT"),
7 => is("EVALSHA") || by_arguments("MIGRATE"),
8 => by_arguments("FUNCTION"),
9 => by_arguments("GEORADIUS"),
17 => by_arguments("GEORADIUSBYMEMBER"),
_ => false,
}
}
const ACK_WAIT_LIMIT: std::time::Duration = std::time::Duration::from_secs(5);
pub async fn written(tx: &tokio::sync::mpsc::UnboundedSender<Vec<u8>>) {
if !acks_wait() || !WRITER_RUNNING.load(Ordering::Acquire) {
return;
}
let id = NEXT_BARRIER.fetch_add(1, Ordering::Relaxed);
let (done, wait) = tokio::sync::oneshot::channel();
BARRIERS.lock().insert(id, done);
let mut mark = BARRIER_MARK.to_vec();
mark.extend_from_slice(&id.to_le_bytes());
if tx.send(mark).is_err() {
BARRIERS.lock().remove(&id);
return;
}
if write_what_is_queued(false).is_none() {
QUEUED.notify_one();
}
let mut wait = wait;
loop {
if tokio::time::timeout(ACK_WAIT_LIMIT, &mut wait)
.await
.is_ok()
{
return;
}
if fsync_always() {
log_throttled!(
10,
crate::loglevel::WARN,
"AOF: a reply has waited over 5 s for its write to be synced to {AOF_PATH} (appendfsync always): the disk is behind"
);
continue;
}
BARRIERS.lock().remove(&id);
AOF_ACKS_BEFORE_WRITE.fetch_add(1, Ordering::Relaxed);
log_throttled!(
10,
crate::loglevel::WARN,
"AOF: a reply waited 5 s for its write to reach {AOF_PATH} and was sent without it"
);
return;
}
}
fn release_barriers(barriers: &mut Vec<u64>) {
if barriers.is_empty() {
return;
}
let mut waiting = BARRIERS.lock();
for id in barriers.drain(..) {
if let Some(done) = waiting.remove(&id) {
let _ = done.send(());
}
}
}
static GLOBAL_AOF_TX: std::sync::OnceLock<Box<dyn crate::commands::ctx::AofSender>> =
std::sync::OnceLock::new();
pub fn install_global_aof_sender(tx: Box<dyn crate::commands::ctx::AofSender>) {
let _ = GLOBAL_AOF_TX.set(tx);
}
thread_local! {
static RECORD_GROUP: std::cell::RefCell<Option<Vec<u8>>> =
const { std::cell::RefCell::new(None) };
}
pub fn queue_record(tx: &dyn crate::commands::ctx::AofSender, data: Vec<u8>) {
let data = RECORD_GROUP.with(|group| match group.borrow_mut().as_mut() {
Some(held) => {
held.extend_from_slice(&data);
None
}
None => Some(data),
});
if let Some(data) = data {
tx.send_aof(data);
}
}
pub(crate) fn put_in_front_of_group(data: &[u8]) -> bool {
RECORD_GROUP.with(|group| match group.borrow_mut().as_mut() {
Some(held) => {
held.splice(0..0, data.iter().copied());
true
}
None => false,
})
}
pub struct RecordGroup<'a> {
tx: &'a dyn crate::commands::ctx::AofSender,
outermost: bool,
}
impl<'a> RecordGroup<'a> {
pub fn begin(tx: &'a dyn crate::commands::ctx::AofSender) -> Self {
let outermost = RECORD_GROUP.with(|group| {
let mut group = group.borrow_mut();
if group.is_some() {
false
} else {
*group = Some(Vec::new());
true
}
});
RecordGroup { tx, outermost }
}
}
impl Drop for RecordGroup<'_> {
fn drop(&mut self) {
if !self.outermost {
return;
}
if let Some(held) = RECORD_GROUP.with(|group| group.borrow_mut().take())
&& !held.is_empty()
{
self.tx.send_aof(held);
}
}
}
pub fn send_to_global_writer(data: Vec<u8>) {
match GLOBAL_AOF_TX.get() {
Some(tx) => tx.send_aof(data),
None => record_lost_aof_record(),
}
}
pub fn request_flush() {
match FLUSH_TX.get() {
Some(tx) => {
let r = tx.try_send(());
log_debug!("AOF: request_flush result: {r:?}");
}
None => log_debug!("AOF: request_flush: FLUSH_TX not initialized"),
}
}
pub fn start_aof_writer(
rx: mpsc::UnboundedReceiver<Vec<u8>>,
) -> impl std::future::Future<Output = ()> + Send + 'static {
let (flush_tx, flush_rx) = tokio::sync::mpsc::channel::<()>(1);
let _ = FLUSH_TX.set(flush_tx);
if AOF_ENABLED.load(Ordering::Relaxed) {
let file = match open_log_at_start() {
Ok(file) => file,
Err(e) => fatal_persistence(&format!("{AOF_PATH} cannot be opened for appending: {e}")),
};
*LOG.lock() = Some(Log { rx, file });
*UNOPENED.lock() = None;
} else {
*UNOPENED.lock() = Some(rx);
}
WRITER_RUNNING.store(true, Ordering::Release);
record_base_size();
run_aof_writer(flush_rx)
}
async fn run_aof_writer(mut flush_rx: tokio::sync::mpsc::Receiver<()>) {
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(1));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = interval.tick() => {
do_fsync();
}
Some(()) = flush_rx.recv() => {
do_fsync();
}
() = SYNC_WANTED.notified(), if syncs_for_replies() => {
sync_for_replies();
}
() = QUEUED.notified() => {
let released = write_what_is_queued(true).unwrap_or(false);
if !released && !acks_wait() {
std::thread::sleep(WRITER_PAUSE);
}
}
}
}
}
fn open_aof() -> std::io::Result<std::fs::File> {
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(AOF_PATH)
}
pub const AOF_PREV_PATH: &str = "appendonly.aof.prev";
fn perform_turn_over(file: &mut std::fs::File) -> std::io::Result<OldLog> {
let moved = move_log_aside();
let old = std::mem::replace(file, open_aof()?);
match moved? {
MovedAside::ToSync => {
let number = TURN_OVERS.fetch_add(1, Ordering::Relaxed) + 1;
OLD_LOG_UNSYNCED.store(number, Ordering::Release);
Ok(Some((old, number)))
}
MovedAside::Synced => Ok(None),
}
}
fn finish_turn_over(old: OldLog) -> std::io::Result<()> {
let Some((old, number)) = old else {
return Ok(());
};
failpoint("turn-over-syncing");
let synced = if injected_failure("turn-over-sync-fails") {
Err(std::io::Error::other("failure injected by a test"))
} else {
old.sync_data().and_then(|()| sync_dir())
};
match &synced {
Ok(()) => old_log_synced(number),
Err(e) if fsync_always() => {
sync_failed_under_always(&format!("the sync of {AOF_PREV_PATH}"), e)
}
Err(_) => {}
}
synced
}
fn sync_old_log() -> std::io::Result<()> {
match std::fs::File::open(AOF_PREV_PATH) {
Ok(old) => old.sync_data()?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
sync_dir()
}
fn write_queued(
file: &mut std::fs::File,
rx: &mut mpsc::UnboundedReceiver<Vec<u8>>,
mut first: Option<Vec<u8>>,
) -> (bool, bool) {
let mut wrote = false;
let mut released = false;
let mut barriers = Vec::new();
let mut drained = 0usize;
loop {
let mut batch = Vec::new();
let mark = match first.take() {
Some(item) => match (as_turn_over_mark(&item), as_barrier(&item)) {
(Some(generation), _) => Some(generation),
(None, Some(id)) => {
barriers.push(id);
drain_into(&mut batch, rx, &mut barriers)
}
(None, None) => {
batch = item;
drain_into(&mut batch, rx, &mut barriers)
}
},
None => drain_into(&mut batch, rx, &mut barriers),
};
let more_queued = batch.len() >= MAX_AOF_BATCH_BYTES;
drained += batch.len();
wrote |= !batch.is_empty();
write_batch(file, &batch);
released |= !barriers.is_empty();
if !barriers.is_empty() && fsync_always() {
UNSYNCED_BARRIERS.lock().append(&mut barriers);
SYNC_WANTED.notify_one();
} else {
release_barriers(&mut barriers);
}
let Some(generation) = mark else {
if more_queued {
if drained < MAX_AOF_PASS_BYTES {
continue;
}
QUEUED.notify_one();
}
return (wrote, released);
};
let result = perform_turn_over(file);
let done = {
let mut waiters = TURN_OVER_WAITERS.lock();
waiters
.iter()
.position(|(g, _)| *g == generation)
.map(|at| waiters.swap_remove(at).1)
};
let undelivered = match done {
Some(done) => done.send(result).err().map(|unsent| unsent.0),
None => Some(result),
};
if let Some(Ok(old)) = undelivered {
let _ = finish_turn_over(old);
}
}
}
const TURN_OVER_TMP: &str = "appendonly.aof.rewrite.tmp";
const TURN_OVER_APPENDING: &str = "appendonly.aof.prev.len";
fn prepare_new_log(generation: u64) -> std::io::Result<()> {
use std::io::Write;
settle_turn_over()?;
FINISHED_OLD_LOG_KEPT.store(false, Ordering::Relaxed);
if std::path::Path::new(AOF_PREV_PATH).exists() && checkpoint_completed(&read_head(AOF_PATH)) {
keep_finished_old_log()?;
FINISHED_OLD_LOG_KEPT.store(true, Ordering::Relaxed);
}
let mut fresh = std::fs::File::create(TURN_OVER_TMP)?;
fresh.write_all(AOF_DELTA_MAGIC)?;
fresh.write_all(&generation.to_le_bytes())?;
fresh.sync_all()
}
enum MovedAside {
ToSync,
Synced,
}
fn move_log_aside() -> std::io::Result<MovedAside> {
use std::io::Write;
let prev = std::path::Path::new(AOF_PREV_PATH);
let mut current = Vec::new();
if prev.exists() {
current = match std::fs::read(AOF_PATH) {
Ok(current) => current,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
Err(e) => return Err(e),
};
if checkpoint_completed(¤t) {
if !FINISHED_OLD_LOG_KEPT.swap(false, Ordering::Relaxed)
&& read_saved().is_some_and(|saved| saved.alone)
{
return Err(std::io::Error::other(format!(
"{AOF_PREV_PATH}, left by a checkpoint that finished, was not kept aside"
)));
}
remove_if_there(AOF_PREV_PATH)?;
}
}
if prev.exists() {
let records = if aof_delta_generation(¤t).is_some() {
¤t[AOF_DELTA_HEADER_LEN..]
} else {
¤t[..]
};
let mut old = std::fs::OpenOptions::new().append(true).open(prev)?;
let before = old.metadata()?.len();
write_file_durably(TURN_OVER_APPENDING, &before.to_le_bytes())?;
old.write_all(records)?;
old.sync_data()?;
failpoint("turn-over-appended");
std::fs::rename(TURN_OVER_TMP, AOF_PATH)?;
sync_dir()?;
std::fs::remove_file(TURN_OVER_APPENDING)?;
Ok(MovedAside::Synced)
} else {
if std::path::Path::new(AOF_PATH).exists() {
std::fs::rename(AOF_PATH, prev)?;
failpoint("turn-over-moved-aside");
}
std::fs::rename(TURN_OVER_TMP, AOF_PATH)?;
Ok(MovedAside::ToSync)
}
}
fn settle_turn_over() -> std::io::Result<()> {
let noted = match std::fs::read(TURN_OVER_APPENDING) {
Ok(noted) => noted,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e),
};
if std::path::Path::new(TURN_OVER_TMP).exists() {
let before = noted
.get(..8)
.and_then(|b| b.try_into().ok())
.map(u64::from_le_bytes)
.ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("{TURN_OVER_APPENDING} is damaged"),
)
})?;
let old = std::fs::OpenOptions::new()
.write(true)
.open(AOF_PREV_PATH)?;
if old.metadata()?.len() > before {
old.set_len(before)?;
old.sync_all()?;
}
}
std::fs::remove_file(TURN_OVER_APPENDING)
}
fn recover_turn_over() {
if let Err(e) = settle_turn_over() {
fatal_persistence(&format!(
"a turn-over of {AOF_PATH} that was stopped part-way cannot be put right: {e}"
));
}
let log_len = match std::fs::metadata(AOF_PATH) {
Ok(meta) => meta.len(),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
Err(e) => fatal_persistence(&format!("{AOF_PATH} exists but cannot be examined: {e}")),
};
if std::path::Path::new(AOF_PREV_PATH).exists() && log_len == 0 {
log_warn!(
"AOF: a checkpoint was stopped while turning {AOF_PATH} over ā completing the \
turn-over, and replaying {AOF_PREV_PATH}"
);
let fresh = std::fs::read(TURN_OVER_TMP)
.is_ok_and(|b| b.len() == AOF_DELTA_HEADER_LEN && aof_delta_generation(&b).is_some());
let done = if fresh {
std::fs::rename(TURN_OVER_TMP, AOF_PATH)
} else {
let mut header = AOF_DELTA_MAGIC.to_vec();
header.extend_from_slice(&read_generation().saturating_add(1).to_le_bytes());
write_file_durably(AOF_PATH, &header)
};
if let Err(e) = done.and_then(|()| sync_dir()) {
fatal_persistence(&format!(
"{AOF_PATH} could not be put back after an interrupted checkpoint: {e}"
));
}
} else {
let kept = keep_aside(TURN_OVER_TMP).and_then(|kept| {
if let Some(name) = &kept {
sync_dir()?;
log_warn!("{}", kept_warning(NewLogWhy::Older, TURN_OVER_TMP, name));
}
Ok(kept)
});
let removed = kept.and_then(|_| remove_if_there(TURN_OVER_TMP));
if let Err(e) = removed {
log_warn!("AOF: {TURN_OVER_TMP} could not be removed: {e}");
}
}
}
static FINISHED_OLD_LOG_KEPT: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
fn keep_finished_old_log() -> std::io::Result<()> {
if read_saved().is_some_and(|saved| saved.alone)
&& let Some(name) = keep_aside(AOF_PREV_PATH)?
{
sync_dir()?;
log_warn!(
"{}",
kept_warning(
NewLogWhy::FinishedBesideSaveWithAofOff,
AOF_PREV_PATH,
&name
)
);
}
Ok(())
}
fn write_file_durably(path: &str, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let tmp = format!("{path}.tmp");
{
let mut file = std::fs::File::create(&tmp)?;
file.write_all(bytes)?;
file.sync_all()?;
}
std::fs::rename(&tmp, path)?;
sync_dir()
}
fn sync_dir() -> std::io::Result<()> {
#[cfg(unix)]
{
std::fs::File::open(".")?.sync_all()?;
}
Ok(())
}
const MAX_AOF_BATCH_BYTES: usize = 4 * 1024 * 1024;
const MAX_AOF_PASS_BYTES: usize = 64 * 1024 * 1024;
const WRITER_PAUSE: std::time::Duration = std::time::Duration::from_micros(150);
fn drain_into(
batch: &mut Vec<u8>,
rx: &mut mpsc::UnboundedReceiver<Vec<u8>>,
barriers: &mut Vec<u64>,
) -> Option<u64> {
while batch.len() < MAX_AOF_BATCH_BYTES {
match rx.try_recv() {
Ok(more) => match (as_turn_over_mark(&more), as_barrier(&more)) {
(Some(generation), _) => return Some(generation),
(None, Some(id)) => barriers.push(id),
(None, None) => batch.extend_from_slice(&more),
},
Err(_) => break,
}
}
None
}
fn write_batch(file: &mut std::fs::File, batch: &[u8]) {
use std::io::Write;
if batch.is_empty() {
return;
}
if let Err(e) = file.write_all(batch) {
if fsync_always() {
log_fatal!(
"AOF: write to {AOF_PATH} failed under appendfsync always: {e} ā exiting rather than acknowledge writes that are not on disk"
);
std::process::exit(1);
}
log_throttled!(
10,
crate::loglevel::ERROR,
"AOF: write to {AOF_PATH} failed: {e} ā writes are not being made durable; check free disk space and permissions on the data directory"
);
}
}
fn sync_for_replies() {
let (mut barriers, written, file) = {
let log = LOG.lock();
let barriers = std::mem::take(&mut *UNSYNCED_BARRIERS.lock());
let written = AOF_WRITTEN.load(Ordering::Relaxed);
match log.as_ref() {
Some(log) => (barriers, written, Some(log.file.try_clone())),
None => (barriers, written, None),
}
};
if barriers.is_empty() {
return;
}
match file {
Some(Ok(file)) => {
sync_before_reply(&file);
AOF_FSYNCED.fetch_max(written, Ordering::Relaxed);
}
Some(Err(e)) => sync_failed_under_always(&format!("opening {AOF_PATH} to sync"), &e),
None => {}
}
release_barriers(&mut barriers);
}
fn sync_before_reply(file: &std::fs::File) {
failpoint("aof-fsync-before-reply");
let synced = (|| {
if OLD_LOG_UNSYNCED.load(Ordering::Acquire) != 0 {
sync_old_log()?;
}
file.sync_data()
})();
if let Err(e) = synced {
sync_failed_under_always(&format!("the fsync of {AOF_PATH}"), &e);
}
}
fn do_fsync() {
let (had_data, written, file) = {
let mut log = LOG.lock();
let Some(log) = log.as_mut() else {
return;
};
let had_data = write_queued(&mut log.file, &mut log.rx, None).0;
let written = AOF_WRITTEN.load(Ordering::Relaxed);
(had_data, written, log.file.try_clone())
};
let Ok(file) = file else {
return;
};
if !had_data && written == AOF_FSYNCED.load(Ordering::Relaxed) {
return;
}
failpoint("fsync");
if fsync_always() {
sync_before_reply(&file);
AOF_FSYNCED.fetch_max(written, Ordering::Relaxed);
return;
}
let seen = OLD_LOG_UNSYNCED.load(Ordering::Acquire);
if seen != 0 {
match sync_old_log() {
Ok(()) => {
failpoint("old-log-synced");
old_log_synced(seen);
}
Err(e) => {
log_throttled!(
10,
crate::loglevel::ERROR,
"AOF: fsync of {AOF_PREV_PATH} failed: {e} ā writes acknowledged since the last good fsync may be lost on power failure; check the disk"
);
return;
}
}
}
if let Err(e) = file.sync_data() {
log_throttled!(
10,
crate::loglevel::ERROR,
"AOF: fsync of {AOF_PATH} failed: {e} ā writes acknowledged since the last good fsync may be lost on power failure; check the disk"
);
} else {
AOF_FSYNCED.fetch_max(written, Ordering::Relaxed);
}
}
fn turn_over_aof(generation: u64) -> impl FnOnce() -> std::io::Result<()> {
let queued = if WRITER_RUNNING.load(Ordering::Acquire) {
debug_assert!(
LOG.try_lock().is_none_or(|log| log.is_some()),
"a turn-over with no log open"
);
let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1);
TURN_OVER_WAITERS.lock().push((generation, done_tx));
send_to_global_writer(turn_over_mark(generation));
QUEUED.notify_one();
Some(done_rx)
} else {
None
};
move || match queued {
None => match move_log_aside()? {
MovedAside::ToSync => {
if let Ok(old) = std::fs::File::open(AOF_PREV_PATH) {
old.sync_data()?;
}
sync_dir()
}
MovedAside::Synced => Ok(()),
},
Some(done) => finish_turn_over(
done.recv()
.map_err(|_| std::io::Error::other("AOF writer dropped the turn-over"))??,
),
}
}
pub fn checkpoint(
store: &crate::store::Store,
index_store: &crate::vector::IndexStore,
) -> std::io::Result<()> {
let turn = checkpoint_turn()?;
checkpoint_noting(&turn, store, index_store, &mut || {})
}
static CHECKPOINT_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
static LAST_GENERATION: AtomicU64 = AtomicU64::new(0);
pub struct CheckpointTurn {
_held: parking_lot::MutexGuard<'static, ()>,
}
pub fn checkpoint_turn() -> std::io::Result<CheckpointTurn> {
let held = if crate::write_gate::held_by_this_thread() {
CHECKPOINT_LOCK
.try_lock()
.ok_or_else(|| std::io::Error::other("another checkpoint is in progress"))?
} else {
CHECKPOINT_LOCK.lock()
};
Ok(CheckpointTurn { _held: held })
}
pub fn checkpoint_noting(
_turn: &CheckpointTurn,
store: &crate::store::Store,
index_store: &crate::vector::IndexStore,
at_cut: &mut dyn FnMut(),
) -> std::io::Result<()> {
struct Active;
impl Drop for Active {
fn drop(&mut self) {
REWRITE_ACTIVE.store(false, Ordering::Release);
}
}
REWRITE_ACTIVE.store(true, Ordering::Release);
let _active = Active;
let aof_on = AOF_ENABLED.load(Ordering::Relaxed);
let started = std::time::Instant::now();
let result = checkpoint_inner(store, index_store, at_cut);
if aof_on {
AOF_LAST_REWRITE_OK.store(result.is_ok(), Ordering::Relaxed);
if result.is_ok() {
AOF_LAST_REWRITE_MS.store(started.elapsed().as_millis() as u64, Ordering::Relaxed);
}
}
if result.is_ok() {
crate::stats::record_save();
}
result
}
fn checkpoint_inner(
store: &crate::store::Store,
index_store: &crate::vector::IndexStore,
at_cut: &mut dyn FnMut(),
) -> std::io::Result<()> {
let aof_on = AOF_ENABLED.load(Ordering::Relaxed);
let generation = next_generation();
failpoint("checkpoint-cutting");
if aof_on {
prepare_new_log(generation)?;
}
let cut = crate::write_gate::cut();
let started = std::time::Instant::now();
at_cut();
let frozen = crate::snapshot::freeze_dataset_for_disk(store, Some(index_store));
let turn_over = match (&frozen, aof_on) {
(Ok(_), true) => {
LOG_SUPERSEDED.store(false, Ordering::Relaxed);
Some(turn_over_aof(generation))
}
_ => None,
};
drop(cut);
let held = started.elapsed();
let frozen = frozen?;
if let Some(turned) = turn_over
&& let Err(e) = turned()
{
LOG_SUPERSEDED.store(true, Ordering::Relaxed);
return Err(e);
}
failpoint("checkpoint-turned-over");
if held > std::time::Duration::from_millis(100) {
log_info!(
"AOF: the checkpoint held writes for {} ms",
held.as_millis()
);
}
static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let tmp_path = format!(
"dump.kdb.{}.{}.tmp",
std::process::id(),
TMP_SEQ.fetch_add(1, Ordering::Relaxed)
);
let written = frozen
.write_file(&tmp_path)
.and_then(|()| install_dump(&tmp_path, generation, !aof_on));
if let Err(e) = written {
let _ = std::fs::remove_file(&tmp_path);
log_warn!(
"AOF: the snapshot of the checkpoint could not be written: {e} ā {AOF_PREV_PATH} is \
kept and replayed before the log on the next start"
);
return Err(e);
}
crate::stats::reset_rdb_changes();
if aof_on {
if let Err(e) = std::fs::remove_file(AOF_PREV_PATH)
&& e.kind() != std::io::ErrorKind::NotFound
{
log_warn!("AOF: {AOF_PREV_PATH} could not be removed: {e}");
}
record_base_size();
log_info!("AOF: rebased onto dump.kdb (generation {generation}) ā log is now the delta");
} else {
dump_saved_without_log();
}
failpoint("checkpoint-finished");
Ok(())
}
fn file_fingerprint(path: &str) -> std::io::Result<(u64, u64)> {
let file = std::fs::File::open(path)?;
let len = file.metadata()?.len();
fingerprint_of_first(&file, len)
}
const EDGE: u64 = 64 * 1024;
fn fingerprint_of_bytes(buf: &[u8]) -> (u64, u64) {
let len = buf.len() as u64;
let mut sample = buf[..EDGE.min(len) as usize].to_vec();
if len > EDGE {
let from = len - EDGE.min(len - EDGE);
sample.extend_from_slice(&buf[from as usize..]);
}
(len, xxhash_rust::xxh3::xxh3_64(&sample))
}
fn delta_header(generation: u64) -> [u8; AOF_DELTA_HEADER_LEN] {
let mut header = [0; AOF_DELTA_HEADER_LEN];
header[..8].copy_from_slice(AOF_DELTA_MAGIC);
header[8..].copy_from_slice(&generation.to_le_bytes());
header
}
fn fingerprint_of_first(mut file: &std::fs::File, len: u64) -> std::io::Result<(u64, u64)> {
use std::io::{Read, Seek, SeekFrom};
file.seek(SeekFrom::Start(0))?;
let mut sample = Vec::with_capacity((2 * EDGE) as usize);
(&mut file).take(EDGE.min(len)).read_to_end(&mut sample)?;
if len > EDGE {
let from = len - EDGE.min(len - EDGE);
file.seek(SeekFrom::Start(from))?;
(&mut file).take(len - from).read_to_end(&mut sample)?;
}
Ok((len, xxhash_rust::xxh3::xxh3_64(&sample)))
}
fn log_fingerprint(path: &str) -> std::io::Result<(u64, u64)> {
match file_fingerprint(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Ok((0, xxhash_rust::xxh3::xxh3_64(&[])))
}
found => found,
}
}
type LogsAtSave = ([(u64, u64); 2], [u64; 2]);
const NO_HEADER: u64 = u64::MAX;
fn logs_on_disk() -> std::io::Result<LogsAtSave> {
let number = |path| aof_delta_generation(&read_head(path)).unwrap_or(NO_HEADER);
Ok((
[log_fingerprint(AOF_PATH)?, log_fingerprint(AOF_PREV_PATH)?],
[number(AOF_PATH), number(AOF_PREV_PATH)],
))
}
fn logs_as_saved() -> std::io::Result<LogsAtSave> {
if let Some(log) = LOG.lock().as_mut() {
write_queued(&mut log.file, &mut log.rx, None);
if let Err(e) = log.file.sync_data()
&& fsync_always()
{
sync_failed_under_always(&format!("the fsync of {AOF_PATH}"), &e);
}
}
logs_on_disk()
}
pub(crate) fn install_dump(tmp: &str, generation: u64, alone: bool) -> std::io::Result<()> {
let logs = if alone { Some(logs_as_saved()?) } else { None };
write_saved(generation, file_fingerprint(tmp)?, logs)?;
sync_dir()?;
failpoint("dump-installing");
std::fs::rename(tmp, "dump.kdb")?;
sync_dir()
}
fn write_saved(
generation: u64,
(len, hash): (u64, u64),
logs: Option<LogsAtSave>,
) -> std::io::Result<()> {
use std::io::Write;
let gen_tmp = format!("{AOF_GEN_PATH}.tmp");
{
let mut file = std::fs::File::create(&gen_tmp)?;
file.write_all(&generation.to_le_bytes())?;
file.write_all(&len.to_le_bytes())?;
file.write_all(&hash.to_le_bytes())?;
file.write_all(&[u8::from(logs.is_some())])?;
if let Some((fingerprints, numbers)) = logs {
for (log_len, log_hash) in fingerprints {
file.write_all(&log_len.to_le_bytes())?;
file.write_all(&log_hash.to_le_bytes())?;
}
for number in numbers {
file.write_all(&number.to_le_bytes())?;
}
}
file.sync_all()?;
}
std::fs::rename(&gen_tmp, AOF_GEN_PATH)
}
struct Saved {
number: u64,
dump: (u64, u64),
alone: bool,
logs: Option<[(u64, u64); 2]>,
numbers: Option<[u64; 2]>,
}
fn read_saved() -> Option<Saved> {
let saved = std::fs::read(AOF_GEN_PATH).ok()?;
let field = |at: usize| Some(u64::from_le_bytes(saved.get(at..at + 8)?.try_into().ok()?));
let pair = |at: usize| Some((field(at)?, field(at + 8)?));
let alone = saved.get(24) == Some(&1);
let logs = if alone {
pair(25).zip(pair(41)).map(|(log, prev)| [log, prev])
} else {
None
};
let numbers = logs.and(pair(57)).map(|(log, prev)| [log, prev]);
Some(Saved {
number: field(0)?,
dump: pair(8)?,
alone,
logs,
numbers,
})
}
fn read_head(path: &str) -> Vec<u8> {
use std::io::Read;
let mut head = Vec::new();
if let Ok(file) = std::fs::File::open(path) {
let _ = file
.take(AOF_DELTA_HEADER_LEN as u64)
.read_to_end(&mut head);
}
head
}
fn checkpoint_completed(log: &[u8]) -> bool {
let Some(saved) = read_saved() else {
return false;
};
aof_delta_generation(log) == Some(saved.number)
&& file_fingerprint("dump.kdb").is_ok_and(|found| found == saved.dump)
}
pub(crate) fn next_generation() -> u64 {
let logs = [AOF_PATH, AOF_PREV_PATH, TURN_OVER_TMP]
.into_iter()
.filter_map(|path| aof_delta_generation(&read_head(path)))
.max()
.unwrap_or(0);
let next = read_generation()
.max(LAST_GENERATION.load(Ordering::Relaxed))
.max(logs)
.saturating_add(1);
LAST_GENERATION.store(next, Ordering::Relaxed);
next
}
struct DumpOnDisk {
kdb: bool,
saved: Option<(Saved, bool)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LogAge {
GoesOn,
Older,
AddedToFrom(u64),
}
impl DumpOnDisk {
fn read(kdb: bool) -> Self {
let saved = read_saved().map(|saved| {
let own = file_fingerprint("dump.kdb").is_ok_and(|found| found == saved.dump);
(saved, own)
});
DumpOnDisk { kdb, saved }
}
fn age_of(&self, path: &str) -> LogAge {
let Some((saved, own)) = self.saved.as_ref().filter(|_| self.kdb) else {
return LogAge::GoesOn;
};
let head = read_head(path);
match (aof_delta_generation(&head), *own) {
(Some(log), true) if log < saved.number => {
if written_since_a_save_with_no_log(path, saved) {
LogAge::AddedToFrom(AOF_DELTA_HEADER_LEN as u64)
} else {
match added_to_since(path, saved) {
Some(from) => LogAge::AddedToFrom(from),
None => LogAge::Older,
}
}
}
(None, true) if saved.alone && !head.is_empty() => {
let as_saved = saved.logs.is_some_and(|logs| {
file_fingerprint(path).is_ok_and(|found| logs.contains(&found))
});
if as_saved {
LogAge::Older
} else {
LogAge::GoesOn
}
}
(Some(log), false) if log == saved.number => LogAge::Older,
_ => LogAge::GoesOn,
}
}
}
impl DumpOnDisk {
fn replayed_beside_an_older_old_log(&self, buf: &[u8]) -> bool {
let Some((saved, own)) = self.saved.as_ref().filter(|_| self.kdb) else {
return false;
};
if !*own || buf.len() <= records_start(buf) || buf.starts_with(AOF_MAGIC) {
return false;
}
match aof_delta_generation(buf) {
None => true,
Some(_) => saved.logs.is_some_and(|logs| logs[0].0 == 0),
}
}
}
fn written_since_a_save_with_no_log(path: &str, saved: &Saved) -> bool {
let Some(logs) = saved.logs.filter(|_| saved.alone && path == AOF_PATH) else {
return false;
};
logs[0].0 == 0
&& std::fs::metadata(path).is_ok_and(|meta| meta.len() > AOF_DELTA_HEADER_LEN as u64)
}
fn added_to_since(path: &str, saved: &Saved) -> Option<u64> {
use std::io::{Read, Seek, SeekFrom};
let logs = saved.logs?;
let mut file = std::fs::File::open(path).ok()?;
let len = file.metadata().ok()?.len();
let (which, was) = logs
.into_iter()
.enumerate()
.find_map(|(which, (was, hash))| {
let added_to = was >= AOF_DELTA_HEADER_LEN as u64
&& was < len
&& fingerprint_of_first(&file, was).is_ok_and(|found| found == (was, hash));
added_to.then_some((which, was))
})?;
if path != AOF_PREV_PATH || which != 1 {
return Some(was);
}
let (log_was, log_hash) = logs[0];
if log_was == 0 {
return Some(was);
}
let mut then = match saved.numbers?[0] {
NO_HEADER => Vec::new(),
number => delta_header(number).to_vec(),
};
let records = log_was.checked_sub(then.len() as u64)?;
file.seek(SeekFrom::Start(was)).ok()?;
(&mut file).take(records).read_to_end(&mut then).ok()?;
(fingerprint_of_bytes(&then) == (log_was, log_hash)).then_some(was + records)
}
fn read_generation() -> u64 {
std::fs::read(AOF_GEN_PATH)
.ok()
.and_then(|b| b.get(..8).and_then(|s| s.try_into().ok()))
.map(u64::from_le_bytes)
.unwrap_or(0)
}
fn aof_delta_generation(buf: &[u8]) -> Option<u64> {
if buf.len() < AOF_DELTA_HEADER_LEN || !buf.starts_with(AOF_DELTA_MAGIC) {
return None;
}
buf[8..16].try_into().ok().map(u64::from_le_bytes)
}
fn records_start(buf: &[u8]) -> usize {
if aof_delta_generation(buf).is_some() {
AOF_DELTA_HEADER_LEN
} else {
0
}
}
const AUTO_REWRITE_CHECK: std::time::Duration = std::time::Duration::from_secs(10);
pub fn should_auto_rewrite(percentage: u64, min_size: u64) -> bool {
if percentage == 0 || !AOF_ENABLED.load(Ordering::Relaxed) || rewrite_in_progress() {
return false;
}
let current = current_size();
if current < min_size {
return false;
}
let base = base_size();
if base == 0 {
return true;
}
current
.saturating_sub(base)
.saturating_mul(100)
.checked_div(base)
.is_some_and(|growth| growth >= percentage)
}
pub static AUTO_REWRITE_PERCENTAGE: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(100);
pub static AUTO_REWRITE_MIN_SIZE: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(64 * 1024 * 1024);
pub fn spawn_auto_rewrite_thread(
store: crate::store::Store,
index_store: crate::vector::IndexStore,
percentage: u64,
min_size: u64,
) {
AUTO_REWRITE_PERCENTAGE.store(percentage, Ordering::Relaxed);
AUTO_REWRITE_MIN_SIZE.store(min_size, Ordering::Relaxed);
if percentage == 0 {
log_info!("AOF: automatic rewrite disabled (aof-rewrite-percentage 0)");
}
std::thread::spawn(move || {
loop {
std::thread::sleep(AUTO_REWRITE_CHECK);
let percentage = AUTO_REWRITE_PERCENTAGE.load(Ordering::Relaxed);
let min_size = AUTO_REWRITE_MIN_SIZE.load(Ordering::Relaxed);
if !should_auto_rewrite(percentage, min_size) {
continue;
}
log_info!(
"AOF: auto-checkpoint: {:.2} MB is {}%+ above the {:.2} MB baseline ā \
folding into dump.kdb",
current_size() as f64 / (1024.0 * 1024.0),
percentage,
base_size() as f64 / (1024.0 * 1024.0),
);
if let Err(e) = checkpoint(&store, &index_store) {
log_warn!("AOF: auto-checkpoint failed: {e}");
}
}
});
}
#[derive(Debug, Default)]
pub struct ReplayStats {
pub commands: u64,
pub errors: u64,
pub truncated_tail: bool,
pub valid_len: u64,
pub bytes: u64,
pub skipped: u64,
pub preamble_keys: u64,
pub reverted: u64,
}
fn split_aof(buf: &[u8]) -> std::io::Result<(Option<&[u8]>, &[u8])> {
if buf.starts_with(AOF_DELTA_MAGIC) {
if buf.len() < AOF_DELTA_HEADER_LEN {
return Ok((None, &[]));
}
return Ok((None, &buf[AOF_DELTA_HEADER_LEN..]));
}
if !buf.starts_with(AOF_MAGIC) {
return Ok((None, buf));
}
if buf.len() < AOF_HEADER_LEN {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"AOF header is truncated",
));
}
let flags = buf[8];
let body = &buf[AOF_HEADER_LEN..];
if flags & AOF_FLAG_PREAMBLE == 0 {
return Ok((None, body));
}
let len = u64::from_le_bytes(buf[9..17].try_into().expect("8 bytes")) as usize;
let end = AOF_HEADER_LEN.checked_add(len).ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"AOF preamble length overflows the file",
)
})?;
if buf.len() < end {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"AOF preamble is truncated: header claims {len} bytes, file holds {}",
buf.len().saturating_sub(AOF_HEADER_LEN)
),
));
}
Ok((Some(&buf[AOF_HEADER_LEN..end]), &buf[end..]))
}
fn live_after_flushes(commands: &[Vec<Vec<u8>>]) -> Vec<bool> {
let is = |cmd: &[Vec<u8>], name: &[u8]| {
cmd.first().map(|c| c.eq_ignore_ascii_case(name)) == Some(true)
};
let mut db_of = Vec::with_capacity(commands.len());
let mut last_flushall: Option<usize> = None;
let mut last_flushdb: std::collections::HashMap<usize, usize> =
std::collections::HashMap::new();
let mut db = 0usize;
for (i, cmd) in commands.iter().enumerate() {
if is(cmd, b"SELECT")
&& let Some(n) = cmd
.get(1)
.and_then(|a| std::str::from_utf8(a).ok())
.and_then(|s| s.parse::<usize>().ok())
{
db = n;
}
db_of.push(db);
if is(cmd, b"FLUSHALL") {
last_flushall = Some(i);
} else if is(cmd, b"FLUSHDB") {
last_flushdb.insert(db, i);
}
}
commands
.iter()
.enumerate()
.map(|(i, cmd)| {
if is(cmd, b"SELECT") {
return true;
}
if last_flushall.is_some_and(|f| i < f) {
return false;
}
last_flushdb.get(&db_of[i]).is_none_or(|&f| i >= f)
})
.collect()
}
fn parse_aof_commands(buf: &[u8]) -> (Vec<Vec<Vec<u8>>>, usize) {
let mut out = Vec::new();
let mut pos = 0usize;
while let Some(rest) = buf.get(pos..).filter(|r| !r.is_empty()) {
match parse_one_command(rest) {
Some((cmd, used)) => {
out.push(cmd);
pos += used;
}
None => break,
}
}
(out, pos)
}
fn is_transaction_mark(cmd: &[Vec<u8>]) -> bool {
cmd.len() == 1
&& (cmd[0].eq_ignore_ascii_case(b"MULTI") || cmd[0].eq_ignore_ascii_case(b"EXEC"))
}
fn unfinished_transaction(commands: &[Vec<Vec<u8>>]) -> Option<usize> {
let mut open = None;
for (i, cmd) in commands.iter().enumerate() {
if cmd.len() != 1 {
continue;
}
if cmd[0].eq_ignore_ascii_case(b"MULTI") {
open = open.or(Some(i));
} else if cmd[0].eq_ignore_ascii_case(b"EXEC") {
open = None;
}
}
open
}
fn record_offset(buf: &[u8], index: usize) -> usize {
let mut pos = 0;
for _ in 0..index {
match parse_one_command(&buf[pos..]) {
Some((_, used)) => pos += used,
None => break,
}
}
pos
}
#[derive(Debug, PartialEq, Eq)]
enum Tail {
Truncated,
Corrupt,
}
fn classify_tail(rest: &[u8]) -> Tail {
fn number(buf: &[u8], from: usize) -> Result<Option<(usize, usize)>, Tail> {
match find_crlf(buf, from) {
Some(end) => std::str::from_utf8(&buf[from..end])
.ok()
.and_then(|s| s.parse::<usize>().ok())
.map(|n| Some((n, end + 2)))
.ok_or(Tail::Corrupt),
None => {
let digits = buf[from..].strip_suffix(b"\r").unwrap_or(&buf[from..]);
if digits.len() <= 20 && digits.iter().all(u8::is_ascii_digit) {
Ok(None)
} else {
Err(Tail::Corrupt)
}
}
}
}
let end = rest
.iter()
.rposition(|&b| b != 0)
.map_or(0, |last| last + 1);
if end < rest.len() {
return if end == 0 {
Tail::Truncated
} else {
classify_tail(&rest[..end])
};
}
if rest.first() != Some(&b'*') {
return Tail::Corrupt;
}
let (argc, mut pos) = match number(rest, 1) {
Ok(Some(found)) => found,
Ok(None) => return Tail::Truncated,
Err(tail) => return tail,
};
for _ in 0..argc {
match rest.get(pos) {
None => return Tail::Truncated,
Some(b'$') => {}
Some(_) => return Tail::Corrupt,
}
let (len, data) = match number(rest, pos + 1) {
Ok(Some(found)) => found,
Ok(None) => return Tail::Truncated,
Err(tail) => return tail,
};
match data.checked_add(len).and_then(|end| end.checked_add(2)) {
Some(end) if end <= rest.len() => pos = end,
Some(_) => return Tail::Truncated,
None => return Tail::Corrupt,
}
}
Tail::Corrupt
}
pub(crate) fn fatal_persistence(what: &str) -> ! {
log_fatal!("{what}");
log_fatal!(
"Refusing to start with an empty dataset in place of one that could not be \
loaded. Fix the file (or its permissions), or move it out of the working directory \
to start empty on purpose."
);
std::process::exit(1);
}
pub(crate) fn parse_one_command(buf: &[u8]) -> Option<(Vec<Vec<u8>>, usize)> {
if *buf.first()? != b'*' {
return None;
}
let mut pos = 0usize;
let line_end = find_crlf(buf, pos)?;
let argc: usize = std::str::from_utf8(&buf[pos + 1..line_end])
.ok()?
.parse()
.ok()?;
pos = line_end + 2;
let mut args = Vec::with_capacity(argc);
for _ in 0..argc {
if *buf.get(pos)? != b'$' {
return None;
}
let line_end = find_crlf(buf, pos)?;
let len: usize = std::str::from_utf8(&buf[pos + 1..line_end])
.ok()?
.parse()
.ok()?;
pos = line_end + 2;
let end = pos.checked_add(len)?;
if buf.len() < end + 2 {
return None;
}
args.push(buf[pos..end].to_vec());
pos = end + 2;
}
Some((args, pos))
}
fn find_crlf(buf: &[u8], from: usize) -> Option<usize> {
buf.get(from..)?
.windows(2)
.position(|w| w == b"\r\n")
.map(|i| from + i)
}
struct DeferIndexing;
impl DeferIndexing {
fn start() -> Self {
crate::vector::DEFER_INDEXING.store(true, Ordering::Release);
Self
}
}
impl Drop for DeferIndexing {
fn drop(&mut self) {
crate::vector::DEFER_INDEXING.store(false, Ordering::Release);
}
}
#[allow(clippy::too_many_arguments)]
pub fn replay_aof(
path: &str,
store: &crate::store::Store,
index_store: &crate::vector::IndexStore,
dict_store: &crate::vector::DictStore,
wait_table: &std::sync::Arc<crate::wait_table::WaitTable>,
ts_index: &crate::store::SharedTsIndex,
config: &std::sync::Arc<crate::config::Config>,
compaction_tx: &crate::vector::CompactionTx,
repl_state: &std::sync::Arc<crate::replication::ReplState>,
skip_preamble: bool,
) -> std::io::Result<ReplayStats> {
let _hold = crate::expiry::hold();
let _loading = crate::expiry::Loading::start();
let _replay = crate::expiry::replay();
let buf = std::fs::read(path)?;
let mut stats = ReplayStats {
bytes: buf.len() as u64,
..Default::default()
};
if buf.is_empty() {
return Ok(stats);
}
let (image, tail) = split_aof(&buf)?;
let image = if skip_preamble { None } else { image };
let (commands, consumed) = parse_aof_commands(tail);
stats.valid_len = (buf.len() - tail.len() + consumed) as u64;
if consumed < tail.len() {
match classify_tail(&tail[consumed..]) {
Tail::Truncated => stats.truncated_tail = true,
Tail::Corrupt => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"bad file format at byte offset {} of {} ā what follows is not a \
command record",
stats.valid_len,
buf.len()
),
));
}
}
}
let mut commands = commands;
if let Some(multi) = unfinished_transaction(&commands) {
stats.reverted = (commands.len() - multi) as u64;
stats.valid_len = (buf.len() - tail.len() + record_offset(tail, multi)) as u64;
stats.truncated_tail = true;
commands.truncate(multi);
}
let live = live_after_flushes(&commands);
let image = match image {
Some(_)
if commands.iter().any(|c| {
c.first()
.is_some_and(|n| n.eq_ignore_ascii_case(b"FLUSHALL"))
}) =>
{
log_info!("AOF preamble skipped ā a FLUSHALL later in the log discards it anyway");
None
}
other => other,
};
if let Some(image) = image {
let loaded = crate::snapshot::load_snapshot_bytes(image)
.map_err(|e| crate::snapshot::refusal_of_file(e, "the AOF's preamble"))?;
let crate::snapshot::LoadedSnapshot {
dbs,
index_schemas,
dictionaries,
hnsw_graphs,
expiries,
functions,
} = loaded;
crate::vector::restore_dictionaries(index_store, dictionaries);
stats.preamble_keys = crate::snapshot::restore_into_store(dbs, store) as u64;
crate::snapshot::restore_expiries_into_store(expiries, store);
crate::vector::register_index_schemas(index_store, &index_schemas, &hnsw_graphs);
crate::snapshot::restore_functions(functions)?;
}
let env = crate::replication::replica_client::ReplicationApplyEnv::new_inert();
let watch_registry = crate::watch::NoopWatchRegistry;
let mut selected_db = 0usize;
let _indexing = DeferIndexing::start();
for (cmd, live) in commands.into_iter().zip(live) {
if cmd.is_empty() || is_transaction_mark(&cmd) {
continue;
}
if !live {
stats.skipped += 1;
continue;
}
stats.commands += 1;
if env
.apply_command(
cmd,
store,
repl_state,
index_store,
dict_store,
wait_table,
ts_index,
config,
compaction_tx,
&mut selected_db,
&watch_registry,
"aof-replay",
)
.is_err()
{
stats.errors += 1;
}
if let Some(delay) = test_replay_delay() {
std::thread::sleep(delay);
}
}
Ok(stats)
}
fn test_replay_delay() -> Option<std::time::Duration> {
static DELAY: std::sync::OnceLock<Option<std::time::Duration>> = std::sync::OnceLock::new();
*DELAY.get_or_init(|| {
let ms: u64 = std::env::var("KIVIDB_TEST_REPLAY_DELAY_MS")
.ok()?
.parse()
.ok()?;
Some(std::time::Duration::from_millis(ms))
})
}
pub const AOF_PATH: &str = "appendonly.aof";
pub fn should_recover_from_aof(aof_enabled: bool) -> bool {
if !aof_enabled {
return false;
}
match std::path::Path::new(AOF_PATH).metadata() {
Ok(meta) => meta.len() > 0,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(e) => fatal_persistence(&format!("{AOF_PATH} exists but cannot be examined: {e}")),
}
}
pub struct LocalRecovery {
pub index_names: Vec<String>,
pub hnsw_loaded: bool,
pub exact_dump: bool,
pub dump_fingerprint: Option<crate::replication::DumpFingerprint>,
}
#[allow(clippy::too_many_arguments)]
pub fn recover_local(
aof_enabled: bool,
store: &crate::store::Store,
index_store: &crate::vector::IndexStore,
dict_store: &crate::vector::DictStore,
wait_table: &std::sync::Arc<crate::wait_table::WaitTable>,
ts_index: &crate::store::SharedTsIndex,
config: &std::sync::Arc<crate::config::Config>,
compaction_tx: &crate::vector::CompactionTx,
repl_state: &std::sync::Arc<crate::replication::ReplState>,
) -> LocalRecovery {
let _hold = crate::expiry::hold();
let _loading = crate::expiry::Loading::start();
let mut recovery = LocalRecovery {
index_names: Vec::new(),
hnsw_loaded: false,
exact_dump: false,
dump_fingerprint: None,
};
if !config.preload_file.is_empty() {
match preload(
&config.preload_file,
store,
index_store,
dict_store,
wait_table,
ts_index,
config,
compaction_tx,
repl_state,
) {
Ok(names) => {
recovery.index_names = names;
return recovery;
}
Err(e) => {
log_fatal!(
"preload-file '{}' could not be loaded: {e}",
config.preload_file
);
std::process::exit(1);
}
}
}
warn_of_kept_logs();
let kdb_path = std::path::Path::new("dump.kdb");
let rdb_path = std::path::Path::new("dump.rdb");
let mut dump_loaded = false;
let mut kdb_loaded = false;
if kdb_path.exists() {
log_info!("Found dump.kdb ā loading native snapshot");
match crate::replication::load_dump("dump.kdb") {
Ok((loaded, fingerprint)) => {
kdb_loaded = true;
recovery.exact_dump = true;
recovery.dump_fingerprint = Some(fingerprint);
let crate::snapshot::LoadedSnapshot {
dbs,
index_schemas,
dictionaries,
hnsw_graphs,
expiries,
functions,
} = loaded;
if let Err(e) = crate::snapshot::restore_functions(functions) {
fatal_persistence(&format!("dump.kdb cannot be loaded: {e}"));
}
crate::vector::restore_dictionaries(index_store, dictionaries);
if !dbs.is_empty() {
let total = crate::snapshot::restore_into_store(dbs, store);
let with_ttl = crate::snapshot::restore_expiries_into_store(expiries, store);
log_info!("Loaded {total} keys from snapshot ({with_ttl} with a TTL)");
dump_loaded = true;
}
if !index_schemas.is_empty() {
recovery.hnsw_loaded = !hnsw_graphs.is_empty();
crate::vector::register_index_schemas(
index_store,
&index_schemas,
&hnsw_graphs,
);
recovery.index_names = index_schemas.iter().map(|s| s.name.clone()).collect();
if recovery.hnsw_loaded {
log_info!("HNSW graph(s) loaded from snapshot ā precision preserved");
}
}
}
Err(e) => fatal_persistence(&format!("dump.kdb cannot be loaded: {e}")),
}
} else if rdb_path.exists() {
log_info!("Found dump.rdb ā loading Redis RDB snapshot");
match crate::snapshot::load_redis_rdb_with_expiry("dump.rdb") {
Ok((dbs, expiries, functions)) if !dbs.is_empty() => {
if let Err(e) = crate::snapshot::restore_functions(functions) {
fatal_persistence(&format!("dump.rdb cannot be loaded: {e}"));
}
let total = crate::snapshot::restore_into_store(dbs, store);
let with_ttl = crate::snapshot::restore_expiries_into_store(expiries, store);
log_info!("Loaded {total} keys from snapshot ({with_ttl} with a TTL)");
dump_loaded = true;
}
Ok(_) => {}
Err(e) => fatal_persistence(&format!("dump.rdb cannot be loaded: {e}")),
}
}
if aof_enabled {
recover_turn_over();
}
if should_recover_from_aof(aof_enabled) {
let mut buf = match std::fs::read(AOF_PATH) {
Ok(buf) => buf,
Err(e) => fatal_persistence(&format!("{AOF_PATH} cannot be read: {e}")),
};
let on_disk = DumpOnDisk::read(kdb_loaded);
let older_than_dump = |what: &str| {
log_warn!(
"AOF: {what} older than dump.kdb (saved since, with the AOF off, or replaced) ā \
not replayed: replayed on top of it, writes the dump holds would be applied \
twice. The old log is kept aside, and {AOF_PATH} starts again on dump.kdb"
);
};
let mut left_out = false;
let mut resumed_checkpoint = false;
let mut added: Option<(&str, bool, Vec<u8>)> = None;
if std::path::Path::new(AOF_PREV_PATH).exists() {
let prev_age = (!checkpoint_completed(&buf)).then(|| on_disk.age_of(AOF_PREV_PATH));
if prev_age.is_none() {
if let Err(e) = keep_finished_old_log() {
log_fatal!(
"{AOF_PREV_PATH}, left by a checkpoint that finished, cannot be kept \
aside: {e}. dump.kdb was saved with the AOF off since, and may not hold \
its writes, so it is not removed without a copy. Free disk space in the \
data directory, or move {AOF_PREV_PATH} out of it, and start again"
);
std::process::exit(1);
}
if let Err(e) = remove_if_there(AOF_PREV_PATH) {
log_warn!(
"AOF: {AOF_PREV_PATH}, left by a checkpoint that finished, could not be \
removed: {e} ā it is left in place. dump.kdb holds its writes. Until it is \
removed, every checkpoint fails (INFO persistence shows \
aof_last_bgrewrite_status:err) and {AOF_PATH} keeps growing: fix the \
permissions of the data directory, and the next checkpoint removes it, or \
remove {AOF_PREV_PATH} by hand"
);
}
} else if prev_age == Some(LogAge::Older) {
match on_disk.age_of(AOF_PATH) {
LogAge::AddedToFrom(from) => {
added = Some((
AOF_PATH,
false,
buf.get(from as usize..).unwrap_or_default().to_vec(),
));
}
LogAge::GoesOn if on_disk.replayed_beside_an_older_old_log(&buf) => {
added = Some((AOF_PATH, true, buf[records_start(&buf)..].to_vec()));
}
_ => {
older_than_dump(&format!("{AOF_PREV_PATH} and {AOF_PATH} are"));
left_out = true;
}
}
} else if let Some(LogAge::AddedToFrom(from)) = prev_age {
let prev = match std::fs::read(AOF_PREV_PATH) {
Ok(prev) => prev,
Err(e) => fatal_persistence(&format!("{AOF_PREV_PATH} cannot be read: {e}")),
};
let mut both = prev.get(from as usize..).unwrap_or_default().to_vec();
both.extend_from_slice(&buf[records_start(&buf)..]);
added = Some((AOF_PREV_PATH, true, both));
} else {
log_warn!(
"AOF: a checkpoint did not finish ā replaying {AOF_PREV_PATH} and then \
{AOF_PATH} on top of the snapshot it started from"
);
resumed_checkpoint = true;
recovery.exact_dump = false;
if let Err(e) = replay_aof(
AOF_PREV_PATH,
store,
index_store,
dict_store,
wait_table,
ts_index,
config,
compaction_tx,
repl_state,
dump_loaded,
) {
fatal_persistence(&format!("{AOF_PREV_PATH} cannot be replayed: {e}"));
}
}
}
if let (Some(aof_generation), dump_generation) =
(aof_delta_generation(&buf), read_generation())
&& !resumed_checkpoint
&& !left_out
&& added.is_none()
&& dump_generation > 0
&& aof_generation > dump_generation
{
fatal_persistence(&format!(
"{AOF_PATH} continues from save number {aof_generation}, but dump.kdb is save \
number {dump_generation}: the two files do not belong together, and the writes \
made between those saves are in neither"
));
}
if !left_out && !resumed_checkpoint && added.is_none() {
match on_disk.age_of(AOF_PATH) {
LogAge::Older => {
older_than_dump(&format!("{AOF_PATH} is"));
left_out = true;
}
LogAge::AddedToFrom(from) => {
added = Some((
AOF_PATH,
false,
buf.get(from as usize..).unwrap_or_default().to_vec(),
));
}
LogAge::GoesOn => {}
}
}
if let Some((name, log_whole, added)) = added {
if name == AOF_PATH && log_whole {
log_warn!(
"AOF: {AOF_PATH} was written to after dump.kdb was saved with the AOF off (by \
an earlier release started with the AOF on) ā it is replayed on top of \
dump.kdb, all of it, as that release replayed it; {AOF_PREV_PATH}, older \
than dump.kdb, is not"
);
} else {
log_warn!(
"AOF: {name} was added to after dump.kdb was saved with the AOF off (by an \
earlier release started with the AOF on) ā what was added is replayed on \
top of dump.kdb; the records from before that save, which dump.kdb holds, \
are not"
);
}
let why = NewLogWhy::AddedTo {
prev: name == AOF_PREV_PATH,
log_whole,
};
if let Err(e) = start_new_log(why, &added) {
fatal_persistence(&format!(
"{AOF_PATH} cannot be started again on dump.kdb with what was added to it: {e}"
));
}
buf = match std::fs::read(AOF_PATH) {
Ok(buf) => buf,
Err(e) => fatal_persistence(&format!("{AOF_PATH} cannot be read: {e}")),
};
}
if !left_out {
if dump_loaded {
log_info!("Replaying {AOF_PATH} on top of the snapshot (writes since the dump)");
if aof_delta_generation(&buf).is_none() {
log_warn!(
"{AOF_PATH} is a full-history log, not a delta. Replaying it on \
top of dump.kdb can double-apply INCR/RPUSH/APPEND. SAVE will rebase \
the AOF to a delta."
);
}
}
let empty_delta =
aof_delta_generation(&buf).is_some() && buf.len() <= AOF_DELTA_HEADER_LEN;
if empty_delta {
} else {
recovery.exact_dump = false;
let names = recover_from_aof(
store,
index_store,
dict_store,
wait_table,
ts_index,
config,
compaction_tx,
repl_state,
dump_loaded,
);
if recovery.index_names.is_empty() {
recovery.index_names = names;
}
if dump_loaded {
recovery.hnsw_loaded = false;
}
}
}
if left_out && let Err(e) = start_new_log(NewLogWhy::Older, &[]) {
fatal_persistence(&format!(
"{AOF_PATH} is older than dump.kdb and cannot be started again on it: {e}"
));
}
}
recovery
}
#[allow(clippy::too_many_arguments)]
fn preload(
target: &str,
store: &crate::store::Store,
index_store: &crate::vector::IndexStore,
dict_store: &crate::vector::DictStore,
wait_table: &std::sync::Arc<crate::wait_table::WaitTable>,
ts_index: &crate::store::SharedTsIndex,
config: &std::sync::Arc<crate::config::Config>,
compaction_tx: &crate::vector::CompactionTx,
repl_state: &std::sync::Arc<crate::replication::ReplState>,
) -> std::io::Result<Vec<String>> {
let invalid = |msg: String| std::io::Error::new(std::io::ErrorKind::InvalidInput, msg);
let (kind, path) = target
.split_once(':')
.ok_or_else(|| invalid("expected aof:<manifest> or rdb:<file>".into()))?;
let path = std::path::Path::new(path);
let (base, incr) = match kind.to_ascii_lowercase().as_str() {
"rdb" => (path.to_path_buf(), None),
"aof" => {
let (base, incr) =
crate::commands::backup::parse_manifest(&std::fs::read_to_string(path)?)?;
let dir = path.parent().unwrap_or_else(|| std::path::Path::new(""));
(dir.join(base), incr.map(|incr| dir.join(incr)))
}
other => return Err(invalid(format!("unknown preload type '{other}'"))),
};
if base
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("dfs"))
{
return Err(invalid(format!(
"{} is a file of a Dragonfly snapshot in Dragonfly's own format (.dfs), which \
keeps each shard's keys in a file of its own; save one in RDB format \
(Dragonfly's SAVE RDB) and load that",
base.display()
)));
}
log_info!("preload-file: loading {}", base.display());
let base_str = base.to_string_lossy();
let is_redis_rdb = std::fs::File::open(&base)
.and_then(|mut f| {
let mut magic = [0u8; 6];
std::io::Read::read_exact(&mut f, &mut magic).map(|()| magic)
})
.is_ok_and(|magic| crate::snapshot::is_rdb_header(&magic));
let mut index_names = Vec::new();
let keys = if is_redis_rdb {
let (dbs, expiries, functions) = crate::snapshot::load_redis_rdb_with_expiry(&base_str)?;
if dbs.iter().all(|db| db.is_empty())
&& crate::snapshot::rdb_written_by_dragonfly(&base_str)?
{
return Err(invalid(format!(
"{} was written by Dragonfly and holds no keys: it is the summary file of \
a snapshot in Dragonfly's own format (.dfs), or a snapshot of an empty \
Dragonfly. Save the data in RDB format (Dragonfly's SAVE RDB) and load that",
base.display()
)));
}
crate::snapshot::restore_functions(functions)?;
let keys = crate::snapshot::restore_into_store(dbs, store);
crate::snapshot::restore_expiries_into_store(expiries, store);
keys
} else {
let crate::snapshot::LoadedSnapshot {
dbs,
index_schemas,
dictionaries,
hnsw_graphs,
expiries,
functions,
} = crate::snapshot::load_snapshot(&base_str)?;
crate::snapshot::restore_functions(functions)?;
crate::vector::restore_dictionaries(index_store, dictionaries);
let keys = crate::snapshot::restore_into_store(dbs, store);
crate::snapshot::restore_expiries_into_store(expiries, store);
crate::vector::register_index_schemas(index_store, &index_schemas, &hnsw_graphs);
index_names = index_schemas.into_iter().map(|s| s.name).collect();
keys
};
crate::store::rebuild_ts_label_index(store, ts_index);
log_info!("preload-file: {keys} keys from the base snapshot");
if let Some(incr) = incr {
let stats = replay_aof(
&incr.to_string_lossy(),
store,
index_store,
dict_store,
wait_table,
ts_index,
config,
compaction_tx,
repl_state,
false,
)?;
log_info!(
"preload-file: {} commands replayed from {}",
stats.commands,
incr.display()
);
if stats.truncated_tail {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"the incremental file ends in a partial record ā a sealed backup never does",
));
}
index_names = index_store.read().keys().cloned().collect();
}
Ok(index_names)
}
#[allow(clippy::too_many_arguments)]
#[must_use = "indexes are left empty by the replay and must be backfilled"]
pub fn recover_from_aof(
store: &crate::store::Store,
index_store: &crate::vector::IndexStore,
dict_store: &crate::vector::DictStore,
wait_table: &std::sync::Arc<crate::wait_table::WaitTable>,
ts_index: &crate::store::SharedTsIndex,
config: &std::sync::Arc<crate::config::Config>,
compaction_tx: &crate::vector::CompactionTx,
repl_state: &std::sync::Arc<crate::replication::ReplState>,
dump_already_loaded: bool,
) -> Vec<String> {
log_info!("Found {AOF_PATH} ā recovering from the append-only file");
let started = std::time::Instant::now();
match replay_aof(
AOF_PATH,
store,
index_store,
dict_store,
wait_table,
ts_index,
config,
compaction_tx,
repl_state,
dump_already_loaded,
) {
Ok(stats) => {
let keys: usize = store
.iter()
.map(|db| {
db.iter()
.map(|shard| crate::read_lock!(shard).len())
.sum::<usize>()
})
.sum();
log_info!(
"AOF replay: {} commands, {} keys, {:.2} MB in {:.2}s",
stats.commands,
keys,
stats.bytes as f64 / (1024.0 * 1024.0),
started.elapsed().as_secs_f64()
);
if stats.preamble_keys > 0 {
log_info!(
"AOF preamble: {} of those keys came from the KDB image, \
not from replayed records",
stats.preamble_keys
);
}
if stats.skipped > 0 {
log_info!(
"AOF replay: {} record(s) skipped ā a later FLUSHDB/FLUSHALL \
had already discarded them",
stats.skipped
);
}
if stats.errors > 0 {
log_warn!(
"{} AOF command(s) failed to apply and were skipped",
stats.errors
);
}
if stats.truncated_tail {
if stats.reverted > 0 {
log_warn!(
"Revert incomplete MULTI/EXEC transaction in AOF file: its EXEC is \
not in the file, and its {} record(s) are dropped",
stats.reverted
);
}
log_warn!(
"AOF ended with a partial record or transaction (likely an unclean \
shutdown); the incomplete tail ({} bytes) is cut off",
stats.bytes - stats.valid_len
);
let trimmed = std::fs::OpenOptions::new()
.write(true)
.open(AOF_PATH)
.and_then(|file| {
file.set_len(stats.valid_len)?;
file.sync_all()
});
if let Err(e) = trimmed {
fatal_persistence(&format!(
"{AOF_PATH} ends in a partial record that could not be cut off: {e}"
));
}
}
}
Err(e) => fatal_persistence(&format!("{AOF_PATH} cannot be loaded: {e}")),
}
index_store.read().keys().cloned().collect()
}
pub(crate) fn failpoint(name: &'static str) {
if !failpoint_named(name) {
return;
}
static HITS: parking_lot::Mutex<Vec<(&'static str, u64)>> = parking_lot::Mutex::new(Vec::new());
let hit = {
let mut hits = HITS.lock();
match hits.iter_mut().find(|(n, _)| *n == name) {
Some((_, count)) => {
*count += 1;
*count
}
None => {
hits.push((name, 1));
1
}
}
};
let path = format!("failpoint.{name}.{hit}");
if std::fs::write(&path, b"").is_err() {
return;
}
log_warn!("Test failpoint {path} reached ā waiting for it to be removed");
crate::cluster::migration::off_the_runtime(|| {
while std::path::Path::new(&path).exists() {
std::thread::sleep(std::time::Duration::from_millis(5));
}
});
}
fn failpoint_named(name: &str) -> bool {
static NAMES: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
NAMES
.get_or_init(|| {
std::env::var("KIVIDB_TEST_FAILPOINTS")
.map(|list| {
list.split(',')
.map(|name| name.trim().to_string())
.filter(|name| !name.is_empty())
.collect()
})
.unwrap_or_default()
})
.iter()
.any(|n| n == name)
}
fn injected_failure(name: &str) -> bool {
failpoint_named(name)
}
pub static REWRITE_ACTIVE: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
#[cfg(test)]
mod kept_file_tests {
use super::*;
fn in_temp(name: &str) -> (tempfile::TempDir, String) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(name).to_str().unwrap().to_string();
(dir, path)
}
#[test]
fn a_copy_that_fails_leaves_no_partial_file() {
let (dir, from) = in_temp("appendonly.aof");
std::fs::write(&from, b"*1\r\n$4\r\nPING\r\n").unwrap();
let to = dir
.path()
.join("superseded.1.0.appendonly.aof")
.to_str()
.unwrap()
.to_string();
let failed = copy_synced(&from, &to, |_, to| {
std::fs::write(to, b"*1\r\n$4")?;
Err(std::io::Error::other("disk full"))
});
assert!(failed.is_err());
assert!(
!std::path::Path::new(&to).exists(),
"the partial copy was left"
);
copy_synced(&from, &to, |from, to| std::fs::copy(from, to)).unwrap();
assert_eq!(std::fs::read(&to).unwrap(), std::fs::read(&from).unwrap());
}
#[test]
fn same_bytes_reads_all_of_both_files() {
let (dir, a) = in_temp("a");
let b = dir.path().join("b").to_str().unwrap().to_string();
let bytes: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect();
std::fs::write(&a, &bytes).unwrap();
std::fs::write(&b, &bytes).unwrap();
assert!(same_bytes(&a, &b).unwrap());
let mut middle = bytes.clone();
middle[100_000] ^= 1;
std::fs::write(&b, &middle).unwrap();
assert!(!same_bytes(&a, &b).unwrap());
std::fs::write(&b, &bytes[..199_999]).unwrap();
assert!(!same_bytes(&a, &b).unwrap());
}
#[test]
fn a_log_added_to_has_its_old_fingerprint_at_its_old_length() {
let (_dir, path) = in_temp("appendonly.aof");
let bytes: Vec<u8> = (0..300_000u32).map(|i| (i * 7 % 251) as u8).collect();
for was in [0, 16, 1000, 65_536, 65_537, 131_072, 131_073, 200_000] {
std::fs::write(&path, &bytes[..was]).unwrap();
let then = file_fingerprint(&path).unwrap();
std::fs::write(&path, &bytes).unwrap();
let file = std::fs::File::open(&path).unwrap();
assert_eq!(
fingerprint_of_first(&file, was as u64).unwrap(),
then,
"{was}"
);
}
std::fs::write(&path, &bytes).unwrap();
let file = std::fs::File::open(&path).unwrap();
for was in [1000u64, 16, 200_000, 16] {
assert_eq!(
fingerprint_of_first(&file, was).unwrap(),
fingerprint_of_bytes(&bytes[..was as usize]),
"{was}"
);
}
for len in [0, 16, 65_536, 65_537, 131_073, 300_000] {
std::fs::write(&path, &bytes[..len]).unwrap();
assert_eq!(
fingerprint_of_bytes(&bytes[..len]),
file_fingerprint(&path).unwrap(),
"{len}"
);
}
std::fs::write(&path, b"").unwrap();
let empty = file_fingerprint(&path).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!(log_fingerprint(&path).unwrap(), empty);
}
}
#[cfg(test)]
mod kept_warning_tests {
use super::*;
const NAME: &str = "superseded.1.0.appendonly.aof";
fn says_to_apply(warning: &str) -> bool {
warning.contains("redis-cli --pipe")
}
#[test]
fn a_log_whose_writes_are_in_the_dataset_is_not_to_be_applied() {
let enable = kept_warning(NewLogWhy::Enable, AOF_PATH, NAME);
assert!(enable.contains("already in the dataset"), "{enable}");
assert!(!says_to_apply(&enable), "{enable}");
let added = kept_warning(
NewLogWhy::AddedTo {
prev: false,
log_whole: false,
},
AOF_PATH,
NAME,
);
assert!(added.contains("has been replayed"), "{added}");
assert!(!says_to_apply(&added), "{added}");
for prev in [false, true] {
let whole = kept_warning(
NewLogWhy::AddedTo {
prev,
log_whole: true,
},
AOF_PATH,
NAME,
);
assert!(
whole.contains("All of its records have been replayed"),
"{whole}"
);
assert!(!whole.contains("was not replayed"), "{whole}");
assert!(!says_to_apply(&whole), "{whole}");
}
let prev_added = kept_warning(
NewLogWhy::AddedTo {
prev: true,
log_whole: true,
},
AOF_PREV_PATH,
NAME,
);
assert!(prev_added.contains("has been replayed"), "{prev_added}");
assert!(!says_to_apply(&prev_added), "{prev_added}");
}
#[test]
fn an_old_log_kept_beside_a_save_with_the_aof_off_is_not_to_be_sent_whole() {
let warning = kept_warning(NewLogWhy::FinishedBesideSaveWithAofOff, AOF_PREV_PATH, NAME);
assert!(!says_to_apply(&warning), "{warning}");
assert!(warning.contains("send only those"), "{warning}");
assert!(warning.contains(NAME), "{warning}");
}
#[test]
fn a_log_not_loaded_says_how_to_apply_its_writes() {
for (why, path) in [
(NewLogWhy::Older, AOF_PATH),
(NewLogWhy::Older, AOF_PREV_PATH),
(NewLogWhy::EnableOverEarlierRun, AOF_PATH),
(
NewLogWhy::AddedTo {
prev: false,
log_whole: false,
},
AOF_PREV_PATH,
),
(
NewLogWhy::AddedTo {
prev: false,
log_whole: true,
},
AOF_PREV_PATH,
),
] {
let warning = kept_warning(why, path, NAME);
assert!(says_to_apply(&warning), "{why:?} {path}: {warning}");
assert!(warning.contains("not in the dataset"), "{warning}");
assert!(warning.contains(NAME), "{warning}");
}
}
}
#[cfg(test)]
mod replay_parse_tests {
use super::*;
#[test]
fn a_record_cut_short_is_a_truncation_and_anything_else_is_corruption() {
let whole = b"*3\r\n$3\r\nSET\r\n$1\r\nk\r\n$5\r\nvalue\r\n";
assert!(parse_one_command(whole).is_some());
for cut in 1..whole.len() {
assert_eq!(
classify_tail(&whole[..cut]),
Tail::Truncated,
"cut at {cut}: {:?}",
String::from_utf8_lossy(&whole[..cut])
);
}
for damaged in [
&b"this is not a record"[..],
b"\x00\x01\x02",
b"*x\r\n",
b"*2\r\nSET\r\n",
b"*2\r\n$z\r\n",
b"*1\r\n$3junk-with-no-line-end",
b"KIVI-something",
] {
assert_eq!(classify_tail(damaged), Tail::Corrupt, "{damaged:?}");
}
}
#[test]
fn zeros_to_the_end_of_the_file_are_a_truncation() {
let whole = b"*3\r\n$3\r\nSET\r\n$1\r\nk\r\n$5\r\nvalue\r\n";
assert_eq!(classify_tail(&[0u8; 316]), Tail::Truncated);
for cut in 1..whole.len() {
let mut torn = whole[..cut].to_vec();
torn.extend_from_slice(&[0u8; 64]);
assert_eq!(classify_tail(&torn), Tail::Truncated, "cut at {cut}");
}
let mut hole = vec![0u8; 64];
hole.extend_from_slice(whole);
assert_eq!(classify_tail(&hole), Tail::Corrupt);
let mut damaged = b"not a record".to_vec();
damaged.extend_from_slice(&[0u8; 64]);
assert_eq!(classify_tail(&damaged), Tail::Corrupt);
}
#[test]
fn a_log_ending_in_zeros_is_cut_where_they_start() {
let mut buf = enc(&["SET", "a", "1"]);
buf.extend_from_slice(&enc(&["SET", "b", "2"]));
let valid = buf.len();
buf.extend_from_slice(b"*3\r\n$3\r\nSE");
buf.extend_from_slice(&[0u8; 4096]);
let (commands, consumed) = parse_aof_commands(&buf);
assert_eq!(commands.len(), 2);
assert_eq!(consumed, valid);
assert_eq!(classify_tail(&buf[consumed..]), Tail::Truncated);
}
fn enc(parts: &[&str]) -> Vec<u8> {
let mut v = format!("*{}\r\n", parts.len()).into_bytes();
for p in parts {
v.extend_from_slice(format!("${}\r\n{}\r\n", p.len(), p).as_bytes());
}
v
}
#[test]
fn parses_a_sequence_of_commands() {
let mut buf = enc(&["SELECT", "0"]);
buf.extend_from_slice(&enc(&["SET", "a", "1"]));
buf.extend_from_slice(&enc(&["RPUSH", "l", "x", "y"]));
let (cmds, used) = parse_aof_commands(&buf);
assert_eq!(used, buf.len(), "whole buffer should be consumed");
assert_eq!(cmds.len(), 3);
assert_eq!(cmds[1], vec![b"SET".to_vec(), b"a".to_vec(), b"1".to_vec()]);
assert_eq!(cmds[2].len(), 4);
}
#[test]
fn binary_values_survive_the_round_trip() {
let mut buf = Vec::new();
let val = b"bin\r\n\x00\xffdata";
buf.extend_from_slice(b"*3\r\n$3\r\nSET\r\n$1\r\nk\r\n");
buf.extend_from_slice(format!("${}\r\n", val.len()).as_bytes());
buf.extend_from_slice(val);
buf.extend_from_slice(b"\r\n");
let (cmds, used) = parse_aof_commands(&buf);
assert_eq!(used, buf.len());
assert_eq!(cmds.len(), 1);
assert_eq!(cmds[0][2], val.to_vec());
}
#[test]
fn a_torn_final_record_is_dropped_but_the_prefix_is_kept() {
let mut buf = enc(&["SET", "a", "1"]);
let good = buf.len();
buf.extend_from_slice(b"*3\r\n$3\r\nSET\r\n$1\r\nb\r\n$5\r\nunfin");
let (cmds, used) = parse_aof_commands(&buf);
assert_eq!(cmds.len(), 1, "only the complete record applies");
assert_eq!(used, good, "the torn tail is not consumed");
assert!(used < buf.len());
}
#[test]
fn an_empty_file_yields_nothing() {
let (cmds, used) = parse_aof_commands(b"");
assert!(cmds.is_empty());
assert_eq!(used, 0);
}
#[test]
fn a_truncated_length_header_is_not_consumed() {
let buf = b"*3\r\n$3\r\nSET\r\n$1";
let (cmds, used) = parse_aof_commands(buf);
assert!(cmds.is_empty());
assert_eq!(used, 0);
}
#[test]
fn a_transaction_without_its_exec_is_found_where_it_starts() {
let mut buf = enc(&["SET", "a", "1"]);
buf.extend_from_slice(&enc(&["MULTI"]));
buf.extend_from_slice(&enc(&["SET", "b", "1"]));
buf.extend_from_slice(&enc(&["SET", "c", "1"]));
buf.extend_from_slice(&enc(&["EXEC"]));
let whole = enc(&["SET", "a", "1"]).len();
let first_multi = buf.len() - whole;
buf.extend_from_slice(&enc(&["MULTI"]));
buf.extend_from_slice(&enc(&["SET", "d", "1"]));
let (cmds, _) = parse_aof_commands(&buf);
assert_eq!(
unfinished_transaction(&cmds[..5]),
None,
"closed by its EXEC"
);
assert_eq!(unfinished_transaction(&cmds), Some(5));
assert_eq!(record_offset(&buf, 5), whole + first_multi);
assert_eq!(record_offset(&buf, 1), whole);
let mut nested = cmds.clone();
nested.push(vec![b"MULTI".to_vec()]);
assert_eq!(unfinished_transaction(&nested), Some(5));
assert_eq!(unfinished_transaction(&[vec![b"EXEC".to_vec()]]), None);
assert!(is_transaction_mark(&cmds[1]) && is_transaction_mark(&cmds[4]));
assert!(!is_transaction_mark(&cmds[0]));
}
}
#[cfg(test)]
mod flush_skip_tests {
use super::*;
fn cmds(rows: &[&[&str]]) -> Vec<Vec<Vec<u8>>> {
rows.iter()
.map(|r| r.iter().map(|s| s.as_bytes().to_vec()).collect())
.collect()
}
#[test]
fn everything_before_a_flushall_is_dead() {
let c = cmds(&[
&["SET", "gone", "1"],
&["INCR", "gone"],
&["FLUSHALL"],
&["SET", "kept", "1"],
]);
assert_eq!(live_after_flushes(&c), vec![false, false, true, true]);
}
#[test]
fn a_flushdb_only_kills_its_own_database() {
let c = cmds(&[
&["SET", "db0-gone", "1"],
&["SELECT", "1"],
&["SET", "db1-kept", "1"],
&["SELECT", "0"],
&["FLUSHDB"],
&["SET", "db0-kept", "1"],
]);
assert_eq!(
live_after_flushes(&c),
vec![false, true, true, true, true, true]
);
}
#[test]
fn select_is_never_dropped() {
let c = cmds(&[&["SELECT", "3"], &["SET", "a", "1"], &["FLUSHALL"]]);
let live = live_after_flushes(&c);
assert!(live[0], "SELECT survives even ahead of a FLUSHALL");
assert!(!live[1]);
}
#[test]
fn a_log_with_no_flush_keeps_everything() {
let c = cmds(&[&["SET", "a", "1"], &["INCR", "a"], &["DEL", "a"]]);
assert_eq!(live_after_flushes(&c), vec![true, true, true]);
}
#[test]
fn the_last_flush_wins_when_there_are_several() {
let c = cmds(&[
&["SET", "a", "1"],
&["FLUSHALL"],
&["SET", "b", "1"],
&["FLUSHALL"],
&["SET", "c", "1"],
]);
assert_eq!(
live_after_flushes(&c),
vec![false, false, false, true, true]
);
}
#[test]
fn case_does_not_matter() {
let c = cmds(&[&["set", "a", "1"], &["flushall"], &["set", "b", "1"]]);
assert_eq!(live_after_flushes(&c), vec![false, true, true]);
}
}
#[cfg(test)]
mod preamble_framing_tests {
use super::*;
fn framed(image: &[u8], tail: &[u8]) -> Vec<u8> {
let mut buf = Vec::new();
buf.extend_from_slice(AOF_MAGIC);
buf.push(AOF_FLAG_PREAMBLE);
buf.extend_from_slice(&(image.len() as u64).to_le_bytes());
buf.extend_from_slice(image);
buf.extend_from_slice(tail);
buf
}
#[test]
fn a_legacy_log_is_all_tail() {
let buf = b"*1\r\n$4\r\nPING\r\n";
let (image, tail) = split_aof(buf).expect("legacy log parses");
assert!(image.is_none());
assert_eq!(tail, buf);
}
#[test]
fn an_image_and_its_tail_are_separated() {
let buf = framed(b"KIVIDB01-image-bytes", b"*1\r\n$4\r\nPING\r\n");
let (image, tail) = split_aof(&buf).expect("framed log parses");
assert_eq!(image, Some(&b"KIVIDB01-image-bytes"[..]));
assert_eq!(tail, b"*1\r\n$4\r\nPING\r\n");
}
#[test]
fn an_empty_tail_is_fine() {
let buf = framed(b"image", b"");
let (image, tail) = split_aof(&buf).expect("framed log parses");
assert_eq!(image, Some(&b"image"[..]));
assert!(tail.is_empty());
}
#[test]
fn a_truncated_image_refuses_to_load() {
let mut buf = framed(b"the-whole-image", b"");
buf.truncate(buf.len() - 4);
let err = split_aof(&buf).expect_err("a short image must not load");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
}
#[test]
fn a_delta_header_is_not_an_image() {
let mut buf = Vec::new();
buf.extend_from_slice(AOF_DELTA_MAGIC);
buf.extend_from_slice(&7u64.to_le_bytes());
buf.extend_from_slice(b"*1\r\n$4\r\nPING\r\n");
let (image, tail) = split_aof(&buf).expect("delta log parses");
assert!(image.is_none());
assert_eq!(tail, b"*1\r\n$4\r\nPING\r\n");
}
#[test]
fn an_empty_delta_has_no_tail() {
let mut buf = Vec::new();
buf.extend_from_slice(AOF_DELTA_MAGIC);
buf.extend_from_slice(&1u64.to_le_bytes());
let (image, tail) = split_aof(&buf).expect("empty delta parses");
assert!(image.is_none());
assert!(tail.is_empty());
}
#[test]
fn a_header_without_the_preamble_flag_is_all_tail() {
let mut buf = Vec::new();
buf.extend_from_slice(AOF_MAGIC);
buf.push(0);
buf.extend_from_slice(&0u64.to_le_bytes());
buf.extend_from_slice(b"*1\r\n$4\r\nPING\r\n");
let (image, tail) = split_aof(&buf).expect("flagless header parses");
assert!(image.is_none());
assert_eq!(tail, b"*1\r\n$4\r\nPING\r\n");
}
#[test]
fn a_header_cut_off_mid_way_is_rejected() {
let buf = &AOF_MAGIC[..];
let err = split_aof(buf).expect_err("a partial header must not load");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
}
}
#[cfg(test)]
mod auto_rewrite_tests {
use super::*;
fn ratio_triggers(current: u64, base: u64, percentage: u64) -> bool {
if base == 0 {
return true;
}
current
.saturating_sub(base)
.saturating_mul(100)
.checked_div(base)
.is_some_and(|growth| growth >= percentage)
}
#[test]
fn doubling_hits_the_default_threshold() {
assert!(ratio_triggers(200, 100, 100));
assert!(!ratio_triggers(199, 100, 100));
}
#[test]
fn an_empty_baseline_always_triggers() {
assert!(ratio_triggers(1, 0, 100));
}
#[test]
fn a_disabled_percentage_never_triggers() {
assert!(!should_auto_rewrite(0, 0));
}
#[test]
fn a_log_below_the_floor_never_triggers() {
assert!(!should_auto_rewrite(100, u64::MAX));
}
}
#[cfg(test)]
mod record_group_tests {
use super::*;
#[derive(Default)]
struct Sent(parking_lot::Mutex<Vec<Vec<u8>>>);
impl crate::commands::ctx::AofSender for Sent {
fn send_aof(&self, data: Vec<u8>) {
self.0.lock().push(data);
}
}
#[test]
fn a_scripts_records_are_queued_together_when_it_ends() {
let sent = Sent::default();
queue_record(&sent, b"before".to_vec());
{
let _script = RecordGroup::begin(&sent);
queue_record(&sent, b"one,".to_vec());
{
let _inner = RecordGroup::begin(&sent);
queue_record(&sent, b"two,".to_vec());
}
queue_record(&sent, b"three".to_vec());
assert_eq!(
*sent.0.lock(),
[b"before".to_vec()],
"held until the script ends"
);
}
queue_record(&sent, b"after".to_vec());
assert_eq!(
*sent.0.lock(),
[
b"before".to_vec(),
b"one,two,three".to_vec(),
b"after".to_vec()
]
);
drop(RecordGroup::begin(&sent));
assert_eq!(sent.0.lock().len(), 3);
}
}
#[cfg(test)]
mod backlog_tests {
use super::*;
#[test]
fn everything_queued_is_written_not_one_batch_of_it() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("appendonly.aof");
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.expect("open");
let (tx, mut rx) = mpsc::unbounded_channel::<Vec<u8>>();
let record = vec![b'x'; 64 * 1024];
let records = 3 * MAX_AOF_BATCH_BYTES / record.len() + 7;
for _ in 0..records {
tx.send(record.clone()).expect("send");
}
let (wrote, released) = write_queued(&mut file, &mut rx, None);
assert!(wrote);
assert!(!released);
assert!(rx.try_recv().is_err(), "nothing is left queued");
let len = std::fs::metadata(&path).expect("metadata").len();
assert_eq!(len, (records * record.len()) as u64);
}
#[test]
fn a_pass_stops_at_its_budget_and_the_next_takes_the_rest() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("appendonly.aof");
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.expect("open");
let (tx, mut rx) = mpsc::unbounded_channel::<Vec<u8>>();
let record = vec![b'x'; MAX_AOF_BATCH_BYTES];
let records = MAX_AOF_PASS_BYTES / record.len() + 3;
for _ in 0..records {
tx.send(record.clone()).expect("send");
}
write_queued(&mut file, &mut rx, None);
let len = std::fs::metadata(&path).expect("metadata").len();
assert_eq!(len, MAX_AOF_PASS_BYTES as u64, "one pass writes its budget");
write_queued(&mut file, &mut rx, None);
assert!(rx.try_recv().is_err(), "the next pass takes the rest");
let len = std::fs::metadata(&path).expect("metadata").len();
assert_eq!(len, (records * record.len()) as u64);
}
}
#[cfg(test)]
mod ts_option_replay_tests {
use super::past_deadline_replay_tests::{replayed, replayed_with_index};
use crate::store::ValueRef;
#[test]
fn incrby_records_of_1_2_0_are_read_as_1_2_0_read_them() {
let store = replayed(&[
vec!["TS.INCRBY", "a", "1", "LABELS", "x", "TIMESTAMP", "42"],
vec!["TS.INCRBY", "a", "1", "TIMESTAMP", "50"],
vec!["TS.INCRBY", "b", "1", "RETENTION", "TIMESTAMP", "42"],
vec!["TS.INCRBY", "c", "1", "ENCODING", "TIMESTAMP", "42"],
vec![
"TS.INCRBY",
"d",
"1",
"RETENTION",
"100",
"LABELS",
"x",
"y",
"z",
"TIMESTAMP",
"42",
],
vec!["TS.INCRBY", "e", "1", "DUPLICATE_POLICY", "TIMESTAMP", "42"],
vec!["TS.INCRBY", "f", "1", "LABELS", "a", "b", "TIMESTAMP", "42"],
vec!["TS.CREATE", "r", "RETENTION", "10"],
vec!["TS.INCRBY", "r", "1", "TIMESTAMP", "1"],
vec!["TS.INCRBY", "r", "1", "RETENTION", "10", "TIMESTAMP", "100"],
vec![
"TS.INCRBY",
"m",
"1",
"timestamp",
"5",
"RETENTION",
"10",
"LABELS",
"a",
"b",
],
vec!["TS.INCRBY", "m", "1", "timestamp", "100"],
]);
let series = |key: &str| {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
match map.get(key.as_bytes()) {
Some(ValueRef::TimeSeries(inner)) => inner.read().clone(),
_ => panic!("{key} is not a series"),
}
};
let samples = |key: &str| {
series(key)
.samples
.iter()
.map(|(t, v)| (*t, *v))
.collect::<Vec<_>>()
};
assert_eq!(samples("a"), [(42, 1.0), (50, 2.0)]);
for key in ["a", "b", "c", "d", "e", "f"] {
let s = series(key);
assert!(s.labels.is_empty(), "{key}");
assert_eq!(s.retention, 0, "{key}");
assert_eq!(s.samples.get(&42), Some(&1.0), "{key}");
}
assert_eq!(samples("r"), [(1, 1.0), (100, 2.0)]);
let m = series("m");
assert_eq!(m.retention, 10);
assert_eq!(m.labels.get("a").map(String::as_str), Some("b"));
assert_eq!(samples("m"), [(100, 2.0)]);
}
#[test]
fn times_above_i64_max_of_1_2_0_replay() {
let max = u64::MAX.to_string();
let below = (u64::MAX - 1).to_string();
let store = replayed(&[
vec!["TS.ADD", "h", below.as_str(), "1"],
vec!["TS.MADD", "h", max.as_str(), "2"],
vec!["TS.INCRBY", "i", "1", "TIMESTAMP", "-1"],
]);
let samples = |key: &str| {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
match map.get(key.as_bytes()) {
Some(ValueRef::TimeSeries(inner)) => inner
.read()
.samples
.iter()
.map(|(t, v)| (*t, *v))
.collect::<Vec<_>>(),
_ => panic!("{key} is not a series"),
}
};
assert_eq!(samples("h"), [(u64::MAX - 1, 1.0), (u64::MAX, 2.0)]);
assert_eq!(samples("i"), [(u64::MAX, 1.0)]);
}
#[test]
fn compaction_links_replay_as_they_ran() {
let store = replayed(&[
vec!["TS.CREATE", "s"],
vec!["TS.CREATE", "d"],
vec!["TS.CREATERULE", "s", "d", "AGGREGATION", "sum", "10"],
vec!["TS.ADD", "s", "1", "1"],
vec!["PEXPIREAT", "d", "1"],
vec!["TS.ADD", "s", "15", "1"],
vec!["DEL", "d"],
vec!["TS.CREATE", "d"],
vec!["TS.CREATERULE", "s", "d", "AGGREGATION", "sum", "10"],
vec!["TS.ADD", "s", "25", "1"],
vec!["RENAME", "s", "s2"],
vec!["TS.ADD", "s2", "35", "1"],
vec!["TS.CREATE", "w"],
vec!["TS.CREATE", "a"],
vec!["TS.CREATE", "b"],
vec!["TS.CREATERULE", "w", "a", "AGGREGATION", "sum", "10"],
vec!["TS.CREATERULE", "w", "b", "AGGREGATION", "sum", "10"],
vec!["RENAME", "a", "b"],
vec!["TS.ADD", "w", "1", "1"],
vec!["TS.ADD", "w", "15", "1"],
]);
let series = |key: &str| {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
match map.get(key.as_bytes()) {
Some(ValueRef::TimeSeries(inner)) => inner.read().clone(),
_ => panic!("{key} is not a series"),
}
};
let s = series("s2");
assert_eq!(s.rules.len(), 1);
assert_eq!(s.rules[0].dest_key, "d");
let d = series("d");
assert_eq!(d.source.as_deref(), Some("s2"));
assert_eq!(
d.samples.iter().map(|(t, v)| (*t, *v)).collect::<Vec<_>>(),
[(10, 1.0), (20, 1.0)]
);
let w = series("w");
assert_eq!(w.rules.len(), 1);
assert_eq!(w.rules[0].dest_key, "b");
assert_eq!(series("b").source.as_deref(), Some("w"));
assert_eq!(series("b").samples.get(&0), Some(&1.0));
}
#[test]
fn options_replay_as_they_ran() {
let (store, index) = replayed_with_index(&[
vec!["TS.CREATE", "k", "LABELS", "a", "b"],
vec!["TS.ALTER", "k", "LABELS"],
vec!["TS.CREATE", "d", "DUPLICATE_POLICY", "BLOCK"],
vec!["TS.ADD", "d", "1", "1"],
vec!["TS.ADD", "d", "1", "5", "ON_DUPLICATE", "SUM"],
vec!["TS.INCRBY", "c", "2", "timestamp", "9", "LABELS", "x"],
]);
let series = |key: &str| {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
match map.get(key.as_bytes()) {
Some(ValueRef::TimeSeries(inner)) => inner.read().clone(),
_ => panic!("{key} is not a series"),
}
};
assert!(series("k").labels.is_empty());
let indexed = |entry: &str| {
crate::read_lock!(index)
.get(entry)
.is_some_and(|keys| !keys.is_empty())
};
assert!(!indexed("a=b"));
let d = series("d");
assert_eq!(d.samples.get(&1), Some(&6.0));
assert_eq!(d.duplicate_policy, crate::types::DuplicatePolicy::Block);
let c = series("c");
assert_eq!(c.samples.get(&9), Some(&2.0));
assert!(c.labels.is_empty());
}
#[test]
fn words_an_older_version_passed_over_are_passed_over_again() {
let store = replayed(&[
vec![
"TS.CREATE",
"k",
"RETENTION",
"5000",
"FOO",
"LABELS",
"a",
"b",
],
vec!["TS.ALTER", "k", "CHUNK", "SIZE", "100"],
vec!["TS.INCRBY", "c", "1", "BOGUS", "TIMESTAMP", "7"],
vec!["TS.ADD", "k", "10", "1.5", "IGNORE", "5", "0.5"],
]);
let series = |key: &str| {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
match map.get(key.as_bytes()) {
Some(ValueRef::TimeSeries(inner)) => inner.read().clone(),
_ => panic!("{key} is not a series"),
}
};
let k = series("k");
assert_eq!(k.retention, 5000);
assert_eq!(k.chunk_size, 100);
assert_eq!(k.labels.get("a").map(String::as_str), Some("b"));
assert_eq!(k.samples.get(&10), Some(&1.5));
let c = series("c");
assert_eq!(c.samples.get(&7), Some(&1.0));
}
}
#[cfg(test)]
mod past_deadline_replay_tests {
use super::*;
use crate::commands::helpers::{delete_key_if_expired, is_expired, now_ms};
use crate::store::{Store, ValueRef};
fn record(parts: &[&str]) -> Vec<u8> {
let parts: Vec<Vec<u8>> = parts.iter().map(|p| p.as_bytes().to_vec()).collect();
crate::resp::write::encode_resp_command(&parts)
}
pub(super) fn replayed(records: &[Vec<&str>]) -> Store {
replayed_with_index(records).0
}
pub(super) fn replayed_with_index(
records: &[Vec<&str>],
) -> (Store, crate::store::SharedTsIndex) {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("appendonly.aof");
let log: Vec<u8> = records.iter().flat_map(|r| record(r)).collect();
std::fs::write(&path, log).expect("write");
let store = crate::store::new_store(1);
let index_store = crate::vector::new_index_store();
let dict_store = crate::vector::new_dict_store();
let wait_table = std::sync::Arc::new(crate::wait_table::WaitTable::new());
let ts_index = crate::store::new_ts_index();
let config = std::sync::Arc::new(crate::config::Config::default());
let (compaction_tx, _compaction_rx) = crate::vector::new_compaction_channel();
let repl_state = std::sync::Arc::new(crate::replication::ReplState::new_master());
let stats = replay_aof(
&path.to_string_lossy(),
&store,
&index_store,
&dict_store,
&wait_table,
&ts_index,
&config,
&compaction_tx,
&repl_state,
false,
)
.expect("replay");
assert_eq!(stats.errors, 0, "every record applied");
(store, ts_index)
}
fn expires(store: &Store, key: &str) -> Option<u64> {
crate::store::get_shard(&store[0], key).read().expires(key)
}
fn hash_fields(store: &Store, key: &str) -> Vec<String> {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
let mut fields: Vec<String> = match map.peek_expiring(key) {
Some((ValueRef::Hash(h), _)) => h.read().keys().cloned().collect(),
Some((ValueRef::HashEx(h), _)) => h.read().fields.keys().cloned().collect(),
other => panic!(
"{key} is not a hash: {:?}",
other.map(|(v, _)| v.type_name())
),
};
fields.sort();
fields
}
fn string(store: &Store, key: &str) -> Vec<u8> {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
match map.peek_expiring(key) {
Some((ValueRef::String(b), _)) => b.to_vec(),
_ => panic!("{key} is not a string"),
}
}
fn list_len(store: &Store, key: &str) -> usize {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
match map.peek_expiring(key) {
Some((ValueRef::List(l), _)) => l.read().len(),
_ => panic!("{key} is not a list"),
}
}
#[test]
fn a_deadline_that_has_passed_is_set_and_the_writes_after_it_go_into_the_key() {
let past = (now_ms() - 5_000).to_string();
let store = replayed(&[
vec!["SELECT", "0"],
vec!["HSET", "h", "f0", "v0"],
vec!["PEXPIREAT", "h", &past],
vec!["HSET", "h", "f1", "v1"],
vec!["SET", "s", "v"],
vec!["PEXPIREAT", "s", &past],
vec!["APPEND", "s", "x"],
vec!["RPUSH", "l", "a"],
vec!["PEXPIREAT", "l", &past],
vec!["RPUSH", "l", "b"],
]);
let at: u64 = past.parse().unwrap();
for key in ["h", "s", "l"] {
assert_eq!(expires(&store, key), Some(at), "{key} kept its deadline");
assert!(is_expired(&store, 0, key), "{key} is past it");
}
assert_eq!(hash_fields(&store, "h"), ["f0", "f1"]);
assert_eq!(string(&store, "s"), b"vx");
assert_eq!(list_len(&store, "l"), 2);
for key in ["h", "s", "l"] {
assert!(delete_key_if_expired(&store, 0, key), "{key}");
assert_eq!(expires(&store, key), None);
assert!(
crate::store::get_shard(&store[0], key)
.read()
.peek_expiring(key)
.is_none()
);
}
}
#[test]
fn a_deadline_still_ahead_is_kept_with_every_write() {
let ahead = (now_ms() + 3_600_000).to_string();
let store = replayed(&[
vec!["HSET", "h", "f0", "v0"],
vec!["PEXPIREAT", "h", &ahead],
vec!["HSET", "h", "f1", "v1"],
vec!["SET", "s", "v"],
vec!["PEXPIREAT", "s", &ahead],
vec!["APPEND", "s", "x"],
vec!["RPUSH", "l", "a"],
vec!["PEXPIREAT", "l", &ahead],
vec!["RPUSH", "l", "b"],
]);
let at: u64 = ahead.parse().unwrap();
for key in ["h", "s", "l"] {
assert_eq!(expires(&store, key), Some(at), "{key}");
assert!(!is_expired(&store, 0, key), "{key}");
}
assert_eq!(hash_fields(&store, "h"), ["f0", "f1"]);
assert_eq!(string(&store, "s"), b"vx");
assert_eq!(list_len(&store, "l"), 2);
}
fn field(store: &Store, key: &str, field: &str) -> (Option<Vec<u8>>, Option<bool>) {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
match map.peek_expiring(key) {
Some((ValueRef::HashEx(h), _)) => {
let h = h.read();
(
h.fields.get(field).map(|v| v.to_vec()),
h.expiries.get(field).map(|_| h.is_field_expired(field)),
)
}
Some((ValueRef::Hash(h), _)) => (h.read().get(field).map(|v| v.to_vec()), None),
_ => (None, None),
}
}
#[test]
fn a_field_deadline_that_has_passed_is_set_and_the_writes_after_it_go_into_the_field() {
let past = (now_ms() - 5_000).to_string();
let store = replayed(&[
vec!["HSET", "h", "keep", "1", "g", "5", "f", "v0"],
vec!["HPEXPIREAT", "h", &past, "FIELDS", "2", "g", "f"],
vec!["HINCRBY", "h", "g", "1"],
vec!["HSET", "h", "f", "v1"],
vec!["HSETEX", "x", "PXAT", &past, "FIELDS", "1", "n", "1.5"],
vec!["HINCRBYFLOAT", "x", "n", "1"],
vec!["HSET", "y", "keep", "1", "m", "7"],
vec!["HGETEX", "y", "PXAT", &past, "FIELDS", "1", "m"],
vec!["HINCRBY", "y", "m", "1"],
vec!["HSET", "h", "z", "5"],
vec!["HPEXPIREAT", "h", &past, "FIELDS", "1", "z"],
vec!["HDEL", "h", "z"],
vec!["HINCRBY", "h", "z", "1"],
]);
assert_eq!(field(&store, "h", "z"), (Some(b"1".to_vec()), None));
assert_eq!(field(&store, "h", "g"), (Some(b"6".to_vec()), Some(true)));
assert_eq!(field(&store, "h", "f").0, Some(b"v1".to_vec()));
assert_eq!(
field(&store, "h", "f").1,
None,
"HSET took f's deadline away"
);
assert_eq!(field(&store, "h", "keep"), (Some(b"1".to_vec()), None));
assert_eq!(field(&store, "x", "n"), (Some(b"2.5".to_vec()), Some(true)));
assert_eq!(field(&store, "y", "m"), (Some(b"8".to_vec()), Some(true)));
for (key, gone) in [("h", "g"), ("x", "n"), ("y", "m")] {
let shard = crate::store::get_shard(&store[0], key);
let map = shard.read();
if let Some((ValueRef::HashEx(h), _)) = map.peek_expiring(key) {
let mut h = h.write();
assert_eq!(h.sweep_expired(), 1, "{key}");
assert!(!h.fields.contains_key(gone), "{key}");
} else {
panic!("{key} is not a hash with field deadlines");
}
}
}
#[test]
fn outside_a_replay_a_field_deadline_that_has_passed_deletes_the_field() {
let mut inner = crate::types::HashInner::new();
inner
.fields
.insert("g".to_string(), std::sync::Arc::from(&b"5"[..]));
inner
.expiries
.insert("g".to_string(), crate::types::field_now() - 1);
{
let _replay = crate::expiry::replay();
assert!(!inner.is_field_expired("g"));
assert_eq!(inner.sweep_expired(), 0);
}
assert!(inner.is_field_expired("g"));
assert_eq!(inner.sweep_expired(), 1);
}
#[test]
fn a_del_after_the_deadline_still_deletes() {
let past = (now_ms() - 5_000).to_string();
let store = replayed(&[
vec!["HSET", "h", "f0", "v0"],
vec!["PEXPIREAT", "h", &past],
vec!["UNLINK", "h"],
vec!["HSET", "h", "f1", "v1"],
]);
assert_eq!(expires(&store, "h"), None);
assert_eq!(hash_fields(&store, "h"), ["f1"]);
}
}
#[cfg(test)]
mod may_log_tests {
use super::may_log;
fn logs(cmd: &[&str]) -> bool {
let cmd: Vec<&[u8]> = cmd.iter().map(|a| a.as_bytes()).collect();
may_log(&cmd)
}
#[test]
fn writes_are_told_by_name_or_by_their_arguments() {
for write in [
&["SET", "k", "v"][..],
&["incr", "k"],
&["eval", "return 1", "0"],
&["EVALSHA", "x", "0"],
&["fcall", "f", "0"],
&["EXEC"],
&["GEORADIUS", "k", "15", "37", "200", "km", "STORE", "d"],
&["georadiusbymember", "k", "m", "200", "km", "storedist", "d"],
&["MIGRATE", "h", "1", "k", "0", "100"],
&["SCRIPT", "LOAD", "return 1"],
&["FUNCTION", "FLUSH"],
] {
assert!(logs(write), "{write:?}");
}
for read in [
&["GET", "k"][..],
&["PING"],
&["GEORADIUS", "k", "15", "37", "200", "km"],
&["GEORADIUSBYMEMBER", "k", "store", "200", "km"],
&["FUNCTION", "LIST"],
&["SCRIPT", "EXISTS", "x"],
&["EVAL_RO", "return 1", "0"],
] {
assert!(!logs(read), "{read:?}");
}
}
}