├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── src ├── bin │ └── kvs.rs ├── kv │ ├── error.rs │ ├── kv_store.rs │ ├── mod.rs │ └── storage.rs └── lib.rs └── tests └── tests.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | .vscode/ 4 | logs/ 5 | 6 | *.data 7 | *.merge 8 | 9 | ### IntelliJ IDEA ### 10 | .idea 11 | *.iws 12 | *.iml 13 | *.ipr 14 | 15 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kvs" 3 | authors = ["ALiang "] 4 | version = "0.1.0" 5 | edition = "2021" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [[bin]] 10 | name = "kvs" 11 | path = "src/bin/kvs.rs" 12 | 13 | [dependencies] 14 | clap = { version = "3.1.18", features = ["derive"] } 15 | failure = "0.1.5" 16 | serde = { version = "1.0.89", features = ["derive"] } 17 | serde_repr = "0.1" 18 | bincode = "1.3.3" 19 | 20 | [dev-dependencies] 21 | assert_cmd = "0.11.0" 22 | predicates = "1.0.0" 23 | tempfile = "3.0.7" 24 | walkdir = "2.2.7" 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2022] [Wancheng Long] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # miniDB 2 | A mini kv database demo that using simplified [bitcask](https://riak.com/assets/bitcask-intro.pdf) storage model with rust implementation. 3 | 4 | ```Bash 5 | kvs 0.1.0 6 | 7 | USAGE: 8 | kvs 9 | 10 | OPTIONS: 11 | -h, --help Print help information 12 | -V, --version Print version information 13 | 14 | SUBCOMMANDS: 15 | get get 16 | rm rm 17 | set set 18 | ``` 19 | -------------------------------------------------------------------------------- /src/bin/kvs.rs: -------------------------------------------------------------------------------- 1 | extern crate kvs; 2 | 3 | use std::env::current_dir; 4 | use std::process::exit; 5 | 6 | use clap::{Parser, Subcommand}; 7 | use kvs::{KvStore, KvsError}; 8 | 9 | #[derive(Debug, Parser)] 10 | #[clap(version = env!("CARGO_PKG_VERSION"))] 11 | struct Cli { 12 | #[clap(subcommand)] 13 | command: Command, 14 | } 15 | 16 | #[derive(Debug, Subcommand)] 17 | enum Command { 18 | /// set 19 | #[clap(arg_required_else_help = true)] 20 | Set { key: String, val: String }, 21 | 22 | /// get 23 | #[clap(arg_required_else_help = true)] 24 | Get { key: String }, 25 | 26 | /// rm 27 | #[clap(arg_required_else_help = true)] 28 | #[clap(name = "rm")] 29 | Remove { key: String }, 30 | } 31 | 32 | fn main() { 33 | let args = Cli::parse(); 34 | let mut kv_store = KvStore::open(current_dir().unwrap().as_path()).unwrap(); 35 | 36 | match args.command { 37 | Command::Get { key } => { 38 | if let Some(val) = kv_store.get(key).unwrap() { 39 | println!("{}", val); 40 | } else { 41 | println!("Key not found"); 42 | } 43 | } 44 | Command::Set { key, val } => { 45 | if let Err(err) = kv_store.set(key, val) { 46 | eprintln!("{:?}", err); 47 | } 48 | } 49 | Command::Remove { key } => { 50 | if let Err(KvsError::KeyNotFound) = kv_store.remove(key) { 51 | println!("Key not found"); 52 | exit(1); 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/kv/error.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::string::FromUtf8Error; 3 | 4 | use failure::Fail; 5 | use failure::_core::array::TryFromSliceError; 6 | 7 | /// Error type for kvs. 8 | #[derive(Fail, Debug)] 9 | pub enum KvsError { 10 | #[fail(display = "{}", _0)] 11 | IO(#[cause] io::Error), 12 | 13 | #[fail(display = "{}", _0)] 14 | SliceDecode(#[cause] TryFromSliceError), 15 | 16 | #[fail(display = "{}", _0)] 17 | ReprDecode(#[cause] Box), 18 | 19 | #[fail(display = "{}", _0)] 20 | StringDecode(#[cause] FromUtf8Error), 21 | 22 | #[fail(display = "Key not found")] 23 | KeyNotFound, 24 | 25 | #[fail(display = "Reach the file end")] 26 | EOF, 27 | 28 | #[fail(display = "invalid data path")] 29 | InvalidDataPath, 30 | } 31 | 32 | impl From for KvsError { 33 | fn from(err: io::Error) -> KvsError { 34 | KvsError::IO(err) 35 | } 36 | } 37 | 38 | impl From for KvsError { 39 | fn from(err: TryFromSliceError) -> KvsError { 40 | KvsError::SliceDecode(err) 41 | } 42 | } 43 | 44 | impl From> for KvsError { 45 | fn from(err: Box) -> KvsError { 46 | KvsError::ReprDecode(err) 47 | } 48 | } 49 | 50 | impl From for KvsError { 51 | fn from(err: FromUtf8Error) -> KvsError { 52 | KvsError::StringDecode(err) 53 | } 54 | } 55 | 56 | /// Result type for kvs. 57 | pub type Result = std::result::Result; 58 | -------------------------------------------------------------------------------- /src/kv/kv_store.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | 3 | use super::error::Result; 4 | use super::storage::{SimplifiedBitcask, Storage}; 5 | 6 | pub struct KvStore { 7 | storage: Box, 8 | } 9 | 10 | impl KvStore { 11 | pub fn open(path: &Path) -> Result { 12 | let storage = SimplifiedBitcask::open(path.to_path_buf())?; 13 | Ok(KvStore { 14 | storage: Box::new(storage), 15 | }) 16 | } 17 | 18 | pub fn get(&mut self, key: String) -> Result> { 19 | self.storage.get(key) 20 | } 21 | 22 | pub fn set(&mut self, key: String, val: String) -> Result<()> { 23 | self.storage.put(key, val) 24 | } 25 | 26 | pub fn remove(&mut self, key: String) -> Result<()> { 27 | self.storage.remove(key) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/kv/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod error; 2 | pub mod kv_store; 3 | pub mod storage; 4 | -------------------------------------------------------------------------------- /src/kv/storage.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::convert::TryInto; 3 | use std::fs::{File, OpenOptions}; 4 | use std::io; 5 | use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write}; 6 | use std::path::PathBuf; 7 | 8 | use serde::{Deserialize, Serialize}; 9 | 10 | use serde_repr::*; 11 | 12 | use super::error::{KvsError, Result}; 13 | 14 | const STORAGE_FILE_PREFIX: &str = "miniDB"; 15 | const COMPACTION_THRESHOLD: u64 = 1 << 16; 16 | const USIZE_LEN: usize = std::mem::size_of::(); 17 | const ENTRY_HEAD_LEN: usize = USIZE_LEN * 2 + 1; 18 | 19 | #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] 20 | #[repr(u8)] 21 | pub enum CmdKind { 22 | PUT = 1, 23 | DEL = 2, 24 | } 25 | 26 | #[derive(Serialize, Deserialize, Debug)] 27 | pub struct Entry { 28 | key_len: usize, 29 | 30 | value_len: usize, 31 | 32 | key: String, 33 | 34 | value: String, 35 | 36 | kind: CmdKind, 37 | } 38 | 39 | impl Entry { 40 | pub fn new(key: String, value: String, kind: CmdKind) -> Entry { 41 | Entry { 42 | key_len: key.as_bytes().len(), 43 | value_len: value.as_bytes().len(), 44 | key, 45 | value, 46 | kind, 47 | } 48 | } 49 | 50 | pub fn size(&self) -> usize { 51 | ENTRY_HEAD_LEN + self.key_len + self.value_len 52 | } 53 | 54 | pub fn encode(&self) -> Vec { 55 | let mut buf = vec![0; self.size()]; 56 | // encode key len 57 | buf[0..USIZE_LEN].copy_from_slice(&self.key_len.to_be_bytes()); 58 | 59 | // encode value length 60 | buf[USIZE_LEN..USIZE_LEN * 2].copy_from_slice(&self.value_len.to_be_bytes()); 61 | 62 | // encode kind 63 | buf[USIZE_LEN * 2..ENTRY_HEAD_LEN] 64 | .copy_from_slice(bincode::serialize(&self.kind).unwrap().as_slice()); 65 | 66 | // encode key 67 | buf[ENTRY_HEAD_LEN..ENTRY_HEAD_LEN + self.key_len].copy_from_slice(self.key.as_bytes()); 68 | 69 | // encode value 70 | buf[ENTRY_HEAD_LEN + self.key_len..].copy_from_slice(self.value.as_bytes()); 71 | 72 | buf 73 | } 74 | 75 | pub fn decode(b: &[u8; ENTRY_HEAD_LEN]) -> Result { 76 | let key_len = usize::from_be_bytes(b[0..USIZE_LEN].try_into()?); 77 | let value_len = usize::from_be_bytes(b[USIZE_LEN..USIZE_LEN * 2].try_into()?); 78 | let kind: CmdKind = bincode::deserialize(&b[USIZE_LEN * 2..ENTRY_HEAD_LEN])?; 79 | Ok(Entry { 80 | key_len, 81 | value_len, 82 | kind, 83 | key: String::new(), 84 | value: String::new(), 85 | }) 86 | } 87 | } 88 | 89 | pub trait Storage { 90 | fn get(&mut self, key: String) -> Result>; 91 | 92 | fn put(&mut self, key: String, val: String) -> Result<()>; 93 | 94 | fn remove(&mut self, key: String) -> Result<()>; 95 | } 96 | 97 | pub struct SimplifiedBitcask { 98 | data_path_buf: PathBuf, 99 | 100 | reader: BufReaderWithPos, 101 | 102 | writer: BufWriterWithPos, 103 | 104 | index: HashMap, 105 | 106 | pending_compact: u64, 107 | } 108 | 109 | impl Storage for SimplifiedBitcask { 110 | fn get(&mut self, key: String) -> Result> { 111 | match self.read(&key) { 112 | Ok(e) => Ok(Some(e.value)), 113 | Err(KvsError::KeyNotFound) => Ok(None), 114 | Err(e) => Err(e), 115 | } 116 | } 117 | 118 | fn put(&mut self, key: String, val: String) -> Result<()> { 119 | let e = Entry::new(key, val, CmdKind::PUT); 120 | self.write(e)?; 121 | if self.pending_compact >= COMPACTION_THRESHOLD { 122 | self.merge()?; 123 | } 124 | Ok(()) 125 | } 126 | 127 | fn remove(&mut self, key: String) -> Result<()> { 128 | if self.index.contains_key(&key) { 129 | let e = Entry::new(key.clone(), String::new(), CmdKind::DEL); 130 | self.write(e)?; 131 | self.index.remove(&key); 132 | return Ok(()); 133 | } 134 | 135 | Err(KvsError::KeyNotFound) 136 | } 137 | } 138 | 139 | impl SimplifiedBitcask { 140 | pub fn open(path_buf: PathBuf) -> Result { 141 | let data_path_buf = path_buf.join(STORAGE_FILE_PREFIX.to_string() + ".data"); 142 | let writer = BufWriterWithPos::new( 143 | OpenOptions::new() 144 | .create(true) 145 | .write(true) 146 | .append(true) 147 | .open(data_path_buf.as_path())?, 148 | )?; 149 | let reader = BufReaderWithPos::new(File::open(data_path_buf.as_path())?)?; 150 | let mut instance = SimplifiedBitcask { 151 | data_path_buf, 152 | reader, 153 | writer, 154 | index: HashMap::new(), 155 | pending_compact: 0, 156 | }; 157 | instance.load_index()?; 158 | Ok(instance) 159 | } 160 | 161 | fn write(&mut self, entry: Entry) -> Result<()> { 162 | let key = entry.key.clone(); 163 | if let Some(old_pos) = self.index.insert(key, self.writer.pos) { 164 | self.pending_compact += self.read_at(old_pos).unwrap().size() as u64; 165 | } 166 | let buf = entry.encode(); 167 | self.writer.write(&buf)?; 168 | self.writer.flush()?; 169 | Ok(()) 170 | } 171 | 172 | fn read(&mut self, key: &str) -> Result { 173 | if let Some(offset) = self.index.get(key) { 174 | let pos = *offset; 175 | return self.read_at(pos); 176 | }; 177 | 178 | Err(KvsError::KeyNotFound) 179 | } 180 | 181 | fn read_at(&mut self, offset: u64) -> Result { 182 | self.reader.seek(SeekFrom::Start(offset))?; 183 | let mut buf: [u8; ENTRY_HEAD_LEN] = [0; ENTRY_HEAD_LEN]; 184 | let len = self.reader.read(&mut buf)?; 185 | if len == 0 { 186 | return Err(KvsError::EOF); 187 | } 188 | let mut e = Entry::decode(&buf)?; 189 | 190 | let mut key_buf = vec![0; e.key_len]; 191 | self.reader.read_exact(key_buf.as_mut_slice())?; 192 | e.key = String::from_utf8(key_buf)?; 193 | 194 | let mut val_buf = vec![0; e.value_len]; 195 | self.reader.read_exact(val_buf.as_mut_slice())?; 196 | e.value = String::from_utf8(val_buf)?; 197 | 198 | Ok(e) 199 | } 200 | 201 | fn load_index(&mut self) -> Result<()> { 202 | let mut offset = 0; 203 | loop { 204 | match self.read_at(offset) { 205 | Ok(e) => { 206 | let size = e.size() as u64; 207 | match e.kind { 208 | CmdKind::DEL => self.index.remove(&e.key), 209 | CmdKind::PUT => self.index.insert(e.key, offset), 210 | }; 211 | offset += size; 212 | } 213 | Err(KvsError::EOF) => { 214 | self.writer.pos = offset; 215 | return Ok(()); 216 | } 217 | Err(e) => { 218 | return Err(e); 219 | } 220 | } 221 | } 222 | } 223 | 224 | fn merge(&mut self) -> Result<()> { 225 | let mut offset = 0; 226 | let mut valid_entry = Vec::new(); 227 | loop { 228 | match self.read_at(offset) { 229 | Ok(e) => { 230 | let size = e.size() as u64; 231 | if let Some(valid_pos) = self.index.get(&e.key) { 232 | if e.kind == CmdKind::PUT && *valid_pos == offset { 233 | valid_entry.push(e); 234 | } 235 | } 236 | offset += size; 237 | } 238 | Err(KvsError::EOF) => { 239 | break; 240 | } 241 | Err(e) => { 242 | return Err(e); 243 | } 244 | } 245 | } 246 | 247 | if !valid_entry.is_empty() { 248 | let mut data_path_ancestors = self.data_path_buf.ancestors(); 249 | data_path_ancestors.next(); 250 | let merge_path_buf = data_path_ancestors 251 | .next() 252 | .ok_or(KvsError::InvalidDataPath)? 253 | .join(STORAGE_FILE_PREFIX.to_string() + ".merge"); 254 | let merge_file = File::create(merge_path_buf.as_path())?; 255 | let mut write_buf = BufWriterWithPos::new(merge_file)?; 256 | 257 | for e in &valid_entry { 258 | let key = e.key.clone(); 259 | self.index.insert(key, write_buf.pos); 260 | write_buf.write(&e.encode())?; 261 | } 262 | 263 | self.writer = write_buf; 264 | self.reader = BufReaderWithPos::new(File::open(merge_path_buf.as_path())?)?; 265 | std::fs::remove_file(self.data_path_buf.as_path())?; 266 | std::fs::rename(merge_path_buf.as_path(), self.data_path_buf.as_path())?; 267 | } 268 | 269 | self.pending_compact = 0; 270 | Ok(()) 271 | } 272 | } 273 | 274 | struct BufReaderWithPos { 275 | reader: BufReader, 276 | pos: u64, 277 | } 278 | 279 | impl BufReaderWithPos { 280 | fn new(mut inner: R) -> Result { 281 | let pos = inner.seek(SeekFrom::Current(0))?; 282 | Ok(BufReaderWithPos { 283 | reader: BufReader::new(inner), 284 | pos, 285 | }) 286 | } 287 | } 288 | 289 | impl Read for BufReaderWithPos { 290 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 291 | let len = self.reader.read(buf)?; 292 | self.pos += len as u64; 293 | Ok(len) 294 | } 295 | } 296 | 297 | impl Seek for BufReaderWithPos { 298 | fn seek(&mut self, pos: SeekFrom) -> io::Result { 299 | self.pos = self.reader.seek(pos)?; 300 | Ok(self.pos) 301 | } 302 | } 303 | 304 | struct BufWriterWithPos { 305 | writer: BufWriter, 306 | pos: u64, 307 | } 308 | 309 | impl BufWriterWithPos { 310 | fn new(mut inner: W) -> Result { 311 | let pos = inner.seek(SeekFrom::Current(0))?; 312 | Ok(BufWriterWithPos { 313 | writer: BufWriter::new(inner), 314 | pos, 315 | }) 316 | } 317 | } 318 | 319 | impl Write for BufWriterWithPos { 320 | fn write(&mut self, buf: &[u8]) -> io::Result { 321 | let len = self.writer.write(buf)?; 322 | self.pos += len as u64; 323 | Ok(len) 324 | } 325 | 326 | fn flush(&mut self) -> io::Result<()> { 327 | self.writer.flush() 328 | } 329 | } 330 | 331 | impl Seek for BufWriterWithPos { 332 | fn seek(&mut self, pos: SeekFrom) -> io::Result { 333 | self.pos = self.writer.seek(pos)?; 334 | Ok(self.pos) 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate failure; 2 | extern crate serde; 3 | 4 | pub use kv::error::{KvsError, Result}; 5 | pub use kv::kv_store::KvStore; 6 | 7 | pub mod kv; 8 | -------------------------------------------------------------------------------- /tests/tests.rs: -------------------------------------------------------------------------------- 1 | extern crate assert_cmd; 2 | extern crate kvs; 3 | extern crate predicates; 4 | extern crate tempfile; 5 | extern crate walkdir; 6 | 7 | use std::process::Command; 8 | 9 | use assert_cmd::cargo::CommandCargoExt; 10 | use assert_cmd::prelude::*; 11 | use predicates::ord::eq; 12 | use predicates::str::{contains, is_empty, PredicateStrExt}; 13 | use tempfile::TempDir; 14 | use walkdir::WalkDir; 15 | 16 | use kvs::{KvStore, Result}; 17 | 18 | // `kvs` with no args should exit with a non-zero code. 19 | #[test] 20 | fn cli_no_args() { 21 | Command::cargo_bin("kvs").unwrap().assert().failure(); 22 | } 23 | 24 | // `kvs -V` should print the version 25 | #[test] 26 | fn cli_version() { 27 | Command::cargo_bin("kvs") 28 | .unwrap() 29 | .args(&["-V"]) 30 | .assert() 31 | .stdout(contains(env!("CARGO_PKG_VERSION"))); 32 | } 33 | 34 | // `kvs get ` should print "Key not found" for a non-existent key and exit with zero. 35 | #[test] 36 | fn cli_get_non_existent_key() { 37 | let temp_dir = TempDir::new().unwrap(); 38 | Command::cargo_bin("kvs") 39 | .unwrap() 40 | .args(&["get", "key1"]) 41 | .current_dir(&temp_dir) 42 | .assert() 43 | .success() 44 | .stdout(eq("Key not found").trim()); 45 | } 46 | 47 | // `kvs rm ` should print "Key not found" for an empty database and exit with non-zero code. 48 | #[test] 49 | fn cli_rm_non_existent_key() { 50 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 51 | Command::cargo_bin("kvs") 52 | .unwrap() 53 | .args(&["rm", "key1"]) 54 | .current_dir(&temp_dir) 55 | .assert() 56 | .failure() 57 | .stdout(eq("Key not found").trim()); 58 | } 59 | 60 | // `kvs set ` should print nothing and exit with zero. 61 | #[test] 62 | fn cli_set() { 63 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 64 | Command::cargo_bin("kvs") 65 | .unwrap() 66 | .args(&["set", "key1", "value1"]) 67 | .current_dir(&temp_dir) 68 | .assert() 69 | .success() 70 | .stdout(is_empty()); 71 | } 72 | 73 | #[test] 74 | fn cli_get_stored() -> Result<()> { 75 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 76 | 77 | let mut store = KvStore::open(temp_dir.path())?; 78 | store.set("key1".to_owned(), "value1".to_owned())?; 79 | store.set("key2".to_owned(), "value2".to_owned())?; 80 | drop(store); 81 | 82 | Command::cargo_bin("kvs") 83 | .unwrap() 84 | .args(&["get", "key1"]) 85 | .current_dir(&temp_dir) 86 | .assert() 87 | .success() 88 | .stdout(eq("value1").trim()); 89 | 90 | Command::cargo_bin("kvs") 91 | .unwrap() 92 | .args(&["get", "key2"]) 93 | .current_dir(&temp_dir) 94 | .assert() 95 | .success() 96 | .stdout(eq("value2").trim()); 97 | 98 | Ok(()) 99 | } 100 | 101 | #[test] 102 | fn cli_invalid_get() { 103 | Command::cargo_bin("kvs") 104 | .unwrap() 105 | .args(&["get"]) 106 | .assert() 107 | .failure(); 108 | 109 | Command::cargo_bin("kvs") 110 | .unwrap() 111 | .args(&["get", "extra", "field"]) 112 | .assert() 113 | .failure(); 114 | } 115 | 116 | #[test] 117 | fn cli_invalid_set() { 118 | Command::cargo_bin("kvs") 119 | .unwrap() 120 | .args(&["set"]) 121 | .assert() 122 | .failure(); 123 | 124 | Command::cargo_bin("kvs") 125 | .unwrap() 126 | .args(&["set", "missing_field"]) 127 | .assert() 128 | .failure(); 129 | 130 | Command::cargo_bin("kvs") 131 | .unwrap() 132 | .args(&["set", "extra", "extra", "field"]) 133 | .assert() 134 | .failure(); 135 | } 136 | 137 | #[test] 138 | fn cli_invalid_rm() { 139 | Command::cargo_bin("kvs") 140 | .unwrap() 141 | .args(&["rm"]) 142 | .assert() 143 | .failure(); 144 | 145 | Command::cargo_bin("kvs") 146 | .unwrap() 147 | .args(&["rm", "extra", "field"]) 148 | .assert() 149 | .failure(); 150 | } 151 | 152 | #[test] 153 | fn cli_invalid_subcommand() { 154 | Command::cargo_bin("kvs") 155 | .unwrap() 156 | .args(&["unknown", "subcommand"]) 157 | .assert() 158 | .failure(); 159 | } 160 | 161 | // Should get previously stored value. 162 | #[test] 163 | fn get_stored_value() -> Result<()> { 164 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 165 | let mut store = KvStore::open(temp_dir.path())?; 166 | 167 | store.set("key1".to_owned(), "value1".to_owned())?; 168 | store.set("key2".to_owned(), "value2".to_owned())?; 169 | 170 | assert_eq!(store.get("key1".to_owned())?, Some("value1".to_owned())); 171 | assert_eq!(store.get("key2".to_owned())?, Some("value2".to_owned())); 172 | 173 | // Open from disk again and check persistent data. 174 | drop(store); 175 | let mut store = KvStore::open(temp_dir.path())?; 176 | assert_eq!(store.get("key1".to_owned())?, Some("value1".to_owned())); 177 | assert_eq!(store.get("key2".to_owned())?, Some("value2".to_owned())); 178 | 179 | Ok(()) 180 | } 181 | 182 | #[test] 183 | fn get_stored_value_with_deletion() -> Result<()> { 184 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 185 | let mut store = KvStore::open(temp_dir.path())?; 186 | 187 | store.set("key1".to_owned(), "value1".to_owned())?; 188 | store.set("key2".to_owned(), "value2".to_owned())?; 189 | store.remove("key1".to_owned())?; 190 | 191 | assert_eq!(store.get("key1".to_owned())?, None); 192 | assert_eq!(store.get("key2".to_owned())?, Some("value2".to_owned())); 193 | 194 | // Open from disk again and check persistent data. 195 | drop(store); 196 | let mut store = KvStore::open(temp_dir.path())?; 197 | assert_eq!(store.get("key1".to_owned())?, None); 198 | assert_eq!(store.get("key2".to_owned())?, Some("value2".to_owned())); 199 | 200 | Ok(()) 201 | } 202 | 203 | // Should overwrite existent value. 204 | #[test] 205 | fn overwrite_value() -> Result<()> { 206 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 207 | let mut store = KvStore::open(temp_dir.path())?; 208 | 209 | store.set("key1".to_owned(), "value1".to_owned())?; 210 | assert_eq!(store.get("key1".to_owned())?, Some("value1".to_owned())); 211 | store.set("key1".to_owned(), "value2".to_owned())?; 212 | assert_eq!(store.get("key1".to_owned())?, Some("value2".to_owned())); 213 | 214 | // Open from disk again and check persistent data. 215 | drop(store); 216 | let mut store = KvStore::open(temp_dir.path())?; 217 | assert_eq!(store.get("key1".to_owned())?, Some("value2".to_owned())); 218 | store.set("key1".to_owned(), "value3".to_owned())?; 219 | assert_eq!(store.get("key1".to_owned())?, Some("value3".to_owned())); 220 | 221 | Ok(()) 222 | } 223 | 224 | // Should get `None` when getting a non-existent key. 225 | #[test] 226 | fn get_non_existent_value() -> Result<()> { 227 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 228 | let mut store = KvStore::open(temp_dir.path())?; 229 | 230 | store.set("key1".to_owned(), "value1".to_owned())?; 231 | assert_eq!(store.get("key2".to_owned())?, None); 232 | 233 | // Open from disk again and check persistent data. 234 | drop(store); 235 | let mut store = KvStore::open(temp_dir.path())?; 236 | assert_eq!(store.get("key2".to_owned())?, None); 237 | 238 | Ok(()) 239 | } 240 | 241 | #[test] 242 | fn remove_non_existent_key() -> Result<()> { 243 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 244 | let mut store = KvStore::open(temp_dir.path())?; 245 | assert!(store.remove("key1".to_owned()).is_err()); 246 | Ok(()) 247 | } 248 | 249 | #[test] 250 | fn remove_key() -> Result<()> { 251 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 252 | let mut store = KvStore::open(temp_dir.path())?; 253 | store.set("key1".to_owned(), "value1".to_owned())?; 254 | assert!(store.remove("key1".to_owned()).is_ok()); 255 | assert_eq!(store.get("key1".to_owned())?, None); 256 | Ok(()) 257 | } 258 | 259 | // Insert data until total size of the directory decreases. 260 | // Test data correctness after compaction. 261 | #[test] 262 | fn compaction() -> Result<()> { 263 | let temp_dir = TempDir::new().expect("unable to create temporary working directory"); 264 | let mut store = KvStore::open(temp_dir.path())?; 265 | 266 | let dir_size = || { 267 | let entries = WalkDir::new(temp_dir.path()).into_iter(); 268 | let len: walkdir::Result = entries 269 | .map(|res| { 270 | res.and_then(|entry| entry.metadata()) 271 | .map(|metadata| metadata.len()) 272 | }) 273 | .sum(); 274 | len.expect("fail to get directory size") 275 | }; 276 | 277 | let mut current_size = dir_size(); 278 | for iter in 0..1000 { 279 | for key_id in 0..1000 { 280 | let key = format!("key{}", key_id); 281 | let value = format!("{}", iter); 282 | store.set(key, value)?; 283 | } 284 | 285 | let new_size = dir_size(); 286 | if new_size > current_size { 287 | current_size = new_size; 288 | continue; 289 | } 290 | // Compaction triggered. 291 | 292 | drop(store); 293 | // reopen and check content. 294 | let mut store = KvStore::open(temp_dir.path())?; 295 | for key_id in 0..1000 { 296 | let key = format!("key{}", key_id); 297 | assert_eq!(store.get(key)?, Some(format!("{}", iter))); 298 | } 299 | return Ok(()); 300 | } 301 | 302 | panic!("No compaction detected"); 303 | } 304 | --------------------------------------------------------------------------------