Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ KacheDB implements the standard **RESP2 / RESP3** binary wire protocol. You can
| **`PERSIST`** | `PERSIST key` | Removes TTL expiration, making key persistent. | $\mathcal{O}(1)$ |
| **`FLUSHDB`** | `FLUSHDB` | Clears all keys and recycles slab pool memory blocks. | $\mathcal{O}(N)$ |
| **`FLUSHALL`** | `FLUSHALL` | Clears all keys across all database instances. | $\mathcal{O}(N)$ |
| **`BGREWRITEAOF`** | `BGREWRITEAOF` | Returns an unsupported-command error. | — |
| **`BGREWRITEAOF`** | `BGREWRITEAOF` | Compacts the append-only file in the background when AOF is enabled. | — |
| **`INFO`** | `INFO [section]` | Returns real-time telemetry, memory stats, and keyspace diagnostics. | $\mathcal{O}(1)$ |
| **`QUIT`** | `QUIT` | Closes the client connection gracefully. | $\mathcal{O}(1)$ |
| **`COMMAND`** | `COMMAND DOCS` | Returns Redis protocol capability metadata. | $\mathcal{O}(1)$ |
Expand Down
2 changes: 1 addition & 1 deletion crates/kachedb-cli/src/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ Available Commands in KacheDB:
INFO [section] - Return server runtime, memory, and stats
CLIENT SETNAME <name> - Assign connection name
CLIENT GETNAME - Get connection name
BGREWRITEAOF - Currently unsupported
BGREWRITEAOF - Compact the append-only file in the background
PING [msg] - Ping server
QUIT - Close connection
• Vector Engine:
Expand Down
13 changes: 9 additions & 4 deletions crates/kachedb-net/src/connection/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,15 @@ pub fn handle_admin(
encode_simple_string(write_buf, "OK");
}
Command::BgRewriteAof => {
encode_error(
write_buf,
"ERR BGREWRITEAOF is currently unsupported in this version",
);
let result = crate::durability::dispatch()
.ok_or(crate::durability::AdmissionError::RewriteDisabled)
.and_then(|writer| writer.request_rewrite());
match result {
Ok(()) => {
encode_simple_string(write_buf, "Background append only file rewriting started")
}
Err(error) => encode_error(write_buf, &error.to_string()),
}
}
Command::DBSize => {
encode_integer(write_buf, table.len() as i64);
Expand Down
4 changes: 2 additions & 2 deletions crates/kachedb-net/src/connection/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -887,7 +887,7 @@ fn test_auth_requirepass_flow() {
}

#[test]
fn process_incoming_bgrewriteaof_returns_unsupported() {
fn process_incoming_bgrewriteaof_requires_persistence() {
let mut conn = Connection::new();
let table = ShardedSwissTable::new();
let mut pool = SlabPool::new(0, 16 * 1024 * 1024).unwrap();
Expand All @@ -897,7 +897,7 @@ fn process_incoming_bgrewriteaof_returns_unsupported() {
assert!(conn.process_incoming(&table, &mut pool).unwrap());
assert_eq!(
conn.write_buf,
b"-ERR BGREWRITEAOF is currently unsupported in this version\r\n+PONG\r\n"
b"-ERR BGREWRITEAOF requires AOF persistence\r\n+PONG\r\n"
);
}

Expand Down
146 changes: 133 additions & 13 deletions crates/kachedb-net/src/durability.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
//! Bounded AOF admission and ordered publication shared by server workers.

use std::fs::File;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};

Expand Down Expand Up @@ -49,6 +52,10 @@ pub enum AdmissionError {
Oversized,
#[error("ERR persistence failed after publication; mutation outcome is uncertain")]
Uncertain,
#[error("ERR BGREWRITEAOF requires AOF persistence")]
RewriteDisabled,
#[error("ERR an AOF rewrite is already in progress")]
RewriteInProgress,
}

pub enum WriterRequest {
Expand All @@ -57,22 +64,38 @@ pub enum WriterRequest {
done: Option<Sender<()>>,
permit: Permit,
},
Sync(Sender<()>),
Sync(Sender<Checkpoint>),
BeginRewrite {
sequence: u64,
cancelled: Arc<AtomicBool>,
},
InstallRewrite {
replacement: RewriteFile,
installed: Sender<bool>,
},
AbortRewrite,
Stop,
}

pub struct RewriteFile {
pub file: File,
pub path: PathBuf,
pub checkpoint: Checkpoint,
}

struct QueueState {
used_bytes: usize,
used_records: usize,
failed: bool,
rewriting: bool,
sequence: u64,
}

pub struct AofDispatch {
tx: Sender<WriterRequest>,
state: Mutex<QueueState>,
available: Condvar,
generation: [u8; 16],
rewrite_trigger: OnceLock<Sender<()>>,
policy: AppendFsync,
byte_limit: usize,
record_limit: usize,
Expand Down Expand Up @@ -125,14 +148,15 @@ impl AofDispatch {
let dispatch = Arc::new(Self {
tx,
available: Condvar::new(),
generation: checkpoint.generation,
rewrite_trigger: OnceLock::new(),
policy,
byte_limit,
record_limit,
state: Mutex::new(QueueState {
used_bytes: 0,
used_records: 0,
failed: false,
rewriting: false,
sequence: checkpoint.sequence,
}),
});
Expand Down Expand Up @@ -177,9 +201,9 @@ impl AofDispatch {
self.available.notify_all();
}

/// Call under the commit fence. The receiver confirms the checkpoint's
/// log prefix reached disk, including under the asynchronous fsync policies.
pub fn checkpoint(&self) -> Result<(Checkpoint, Receiver<()>), AdmissionError> {
/// Enqueues a sync at the current commit boundary. The writer replies with the
/// checkpoint for the file that actually received the prefix.
pub fn checkpoint(&self) -> Result<Receiver<Checkpoint>, AdmissionError> {
let state = self.state.lock().unwrap();
if state.failed {
return Err(AdmissionError::Unavailable);
Expand All @@ -188,13 +212,72 @@ impl AofDispatch {
self.tx
.send(WriterRequest::Sync(send))
.map_err(|_| AdmissionError::Unavailable)?;
Ok((
Checkpoint {
generation: self.generation,
Ok(receive)
}

pub fn set_rewrite_trigger(&self, trigger: Sender<()>) {
assert!(self.rewrite_trigger.set(trigger).is_ok());
}

pub fn request_rewrite(&self) -> Result<(), AdmissionError> {
let trigger = self
.rewrite_trigger
.get()
.ok_or(AdmissionError::RewriteDisabled)?;
let mut state = self.state.lock().unwrap();
if state.failed {
return Err(AdmissionError::Unavailable);
}
if state.rewriting {
return Err(AdmissionError::RewriteInProgress);
}
trigger
.try_send(())
.map_err(|_| AdmissionError::Unavailable)?;
state.rewriting = true;
Ok(())
}

/// Call under the commit fence after copying the base.
pub fn begin_rewrite(&self, cancelled: Arc<AtomicBool>) -> Result<u64, AdmissionError> {
let state = self.state.lock().unwrap();
if state.failed {
return Err(AdmissionError::Unavailable);
}
self.tx
.send(WriterRequest::BeginRewrite {
sequence: state.sequence,
},
receive,
))
cancelled,
})
.map_err(|_| AdmissionError::Unavailable)?;
Ok(state.sequence)
}

/// Uses the same FIFO as mutations and checkpoint requests to define cutover.
pub fn install_rewrite(
&self,
replacement: RewriteFile,
) -> Result<Receiver<bool>, AdmissionError> {
let state = self.state.lock().unwrap();
if state.failed {
return Err(AdmissionError::Unavailable);
}
let (send, receive) = bounded(1);
self.tx
.send(WriterRequest::InstallRewrite {
replacement,
installed: send,
})
.map_err(|_| AdmissionError::Unavailable)?;
Ok(receive)
}

pub fn abort_rewrite(&self) {
let _ = self.tx.send(WriterRequest::AbortRewrite);
}

pub fn finish_rewrite(&self) {
self.state.lock().unwrap().rewriting = false;
}

pub fn stop(&self) {
Expand Down Expand Up @@ -262,6 +345,34 @@ impl Drop for Permit {
mod tests {
use super::*;

#[test]
fn rewrite_request_admits_one_job_at_a_time() {
let (dispatch, _) = AofDispatch::new(
Checkpoint {
generation: [0; 16],
sequence: 0,
},
AppendFsync::Always,
);
let (trigger, requests) = bounded(1);
assert_eq!(
dispatch.request_rewrite(),
Err(AdmissionError::RewriteDisabled)
);
dispatch.set_rewrite_trigger(trigger);
dispatch.request_rewrite().unwrap();
assert_eq!(
dispatch.request_rewrite(),
Err(AdmissionError::RewriteInProgress)
);
requests.recv().unwrap();
dispatch.finish_rewrite();
dispatch.request_rewrite().unwrap();
requests.recv().unwrap();
dispatch.fail();
assert_eq!(dispatch.request_rewrite(), Err(AdmissionError::Unavailable));
}

#[test]
fn asynchronous_admission_bounds_bytes_and_records() {
for policy in [AppendFsync::EverySec, AppendFsync::No] {
Expand All @@ -282,7 +393,7 @@ mod tests {
));
drop(second);
assert!(first.submit(vec![1; 5]).unwrap().is_none());
assert_eq!(dispatch.checkpoint().unwrap().0.sequence, 18);
let checkpoint_reply = dispatch.checkpoint().unwrap();
assert!(matches!(
dispatch.reserve(4),
Err(AdmissionError::Saturated)
Expand All @@ -291,6 +402,15 @@ mod tests {
panic!("record must precede checkpoint");
};
assert_eq!(bytes, [1; 5]);
let WriterRequest::Sync(sender) = requests.recv().unwrap() else {
panic!("expected checkpoint request");
};
let checkpoint = Checkpoint {
sequence: 18,
..checkpoint
};
sender.send(checkpoint).unwrap();
assert_eq!(checkpoint_reply.recv().unwrap(), checkpoint);
drop(permit);
assert!(dispatch.reserve(8).is_ok());
assert!(matches!(
Expand Down
18 changes: 16 additions & 2 deletions crates/kachedb-proto-resp/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,11 @@ pub(super) fn decode_inline(line: &[u8], consumed: usize) -> ParsedCommandFrame<
Ok(Some((Ok(Command::FlushDb), consumed)))
} else if cmd_name.eq_ignore_ascii_case(b"FLUSHALL") {
Ok(Some((Ok(Command::FlushAll), consumed)))
} else if cmd_name.eq_ignore_ascii_case(b"BGREWRITEAOF") {
Ok(Some((
decode_bgrewriteaof(parts.next().is_some()),
consumed,
)))
} else {
Ok(Some((Ok(Command::Unknown { name: cmd_name }), consumed)))
}
Expand All @@ -280,6 +285,15 @@ pub(super) fn decode_inline(line: &[u8], consumed: usize) -> ParsedCommandFrame<
}
}

fn decode_bgrewriteaof<'a>(has_arguments: bool) -> Result<Command<'a>, RespError> {
if has_arguments {
return Err(RespError::WrongArgumentCount {
command: "BGREWRITEAOF".into(),
});
}
Ok(Command::BgRewriteAof)
}

/// Parses one Redis wire command, borrowing argument data from the input slice.
pub fn parse_command<'a>(src: &'a [u8]) -> Result<Option<(Command<'a>, usize)>, RespError> {
match parse_command_frame(src)? {
Expand Down Expand Up @@ -659,7 +673,7 @@ impl<'a> Command<'a> {
Ok(Command::Unknown { name: cmd_name })
}
} else if cmd_name.eq_ignore_ascii_case(b"BGREWRITEAOF") {
Ok(Command::BgRewriteAof)
decode_bgrewriteaof(args.len() > 1)
} else if cmd_name.eq_ignore_ascii_case(b"AUTH") {
if args.len() == 2 {
Ok(Command::Auth {
Expand Down Expand Up @@ -1444,7 +1458,7 @@ impl<'a> Command<'a> {
Ok(Command::Unknown { name: cmd_name })
}
} else if cmd_name.eq_ignore_ascii_case(b"BGREWRITEAOF") {
Ok(Command::BgRewriteAof)
decode_bgrewriteaof(args.len() > 1)
} else if cmd_name.eq_ignore_ascii_case(b"AUTH") {
if args.len() == 2 {
let password = extract_required_bytes(&args[1], "AUTH")?;
Expand Down
Loading
Loading