diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..99d36a1
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,54 @@
+# Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment include:
+
+- Using welcoming and inclusive language
+- Being respectful of differing viewpoints and experiences
+- Gracefully accepting constructive criticism
+- Focusing on what is best for the community
+- Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+- The use of sexualized language or imagery and unwelcome sexual attention or advances
+- Trolling, insulting/derogatory comments, and personal or political attacks
+- Public or private harassment
+- Publishing others' private information, such as a physical or electronic address, without explicit permission
+- Other conduct which could reasonably be considered inappropriate in a professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned with this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at sunkanmiadewumi1@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
+
+All project team members are obligated to respect the privacy and security of the reporter of any incident.
+
+## Enforcement Guidelines
+
+Project maintainers will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
+
+1. **Correction**: Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
+2. **Warning**: Community Impact: A violation through a single incident or series of actions.
+3. **Temporary Ban**: Community Impact: A serious violation of community standards, including sustained inappropriate behavior.
+4. **Permanent Ban**: Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
+
+For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..02749ed
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,66 @@
+# Contributing
+
+## License
+
+By contributing to this project, you agree that your contributions will be licensed under the project's license (MIT OR Apache-2.0).
+
+Thank you for your contribution!
+
+## Looking for issues?
+
+https://github.com/Gifted-s/bd/issues
+
+
+### How do I contribute
+
+Fork the project and use the `git clone` command to download the repository to your computer. A standard procedure for working on an issue would be to:
+
+1. Clone the `velarixdb` repository and download it to your computer.
+ ```bash
+ git clone https://github.com/Gifted-s/velarixdb
+ ```
+
+2. Pull all changes from the upstream `main` branch, before creating a new branch - to ensure that your `main` branch is up-to-date with the latest changes:
+ ```bash
+ git pull
+ ```
+
+3. Create a new branch from `main` like: `bugfix-232-ensure-compaction-runs-within-time-frame-allocated`:
+ ```bash
+ git checkout -b "[the name of your branch]"
+ ```
+
+4. Make changes to the code, and ensure all code changes are formatted correctly:
+ ```bash
+ cargo fmt
+ ```
+5. Ensure all clippy rules are obeyed:
+ ```bash
+ cargo clippy --tests
+ ```
+
+6. Ensure nothing is unexpectedly broken:
+ ```bash
+ cargo test
+ ```
+
+6. Commit your changes when finished:
+ ```bash
+ git add -A
+ git commit -m "[your commit message]"
+ ```
+
+7. Push changes to GitHub:
+ ```bash
+ git push origin "[the name of your branch]"
+ ```
+
+8. Submit your changes for review, by going to your repository on GitHub and clicking the `Compare & pull request` button.
+
+9. Ensure that you have entered a commit message which details the changes, and what the pull request is for.
+
+10. Now submit the pull request by clicking the `Create pull request` button.
+
+11. Wait for code review and approval.
+
+12. After approval, your pull request will be merged.
\ No newline at end of file
diff --git a/Cargo.toml b/Cargo.toml
index e0e2e7d..6bc399b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,10 +1,10 @@
[package]
-name = "vikingsdb"
+name = "velarixdb"
version = "0.1.0"
edition = "2021"
authors = ["Adewumi Sunkanmi D."]
description = "An LSM Storage Engine focused on reduced IO amplification"
-keywords = ["vikingsdb","database", "lsmt", "lsm", "rocksdb", "leveldb"]
+keywords = ["velarixdb","database", "lsmt", "lsm", "rocksdb", "leveldb"]
categories = ["data-structures", "database-implementations", "algorithms"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..62b8c91
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
\ No newline at end of file
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..9afeb3c
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 fjall-rs
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/README.md b/README.md
index b53e10b..ff4ccd4 100644
--- a/README.md
+++ b/README.md
@@ -1,18 +1,147 @@
-# BUMP STORAGE ENGINE
+# VelarixDB
-// In progress ...
+
+
+
+VelarixDB is an LSM-based storage engine designed to significantly reduce IO amplification, resulting in better performance and durability for storage devices.
+
+
+[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](code_of_conduct.md)
+
+## Introduction
+
+**VelarixDB: Efficient Data Management for High Performance**
+
+VelarixDB is an ongoing project (*not production ready*) designed to optimize data movement during load times, random access, and compaction. Inspired by the WiscKey paper, [WiscKey: Separating Keys from Values in SSD-conscious Storage](https://usenix.org/system/files/conference/fast16/fast16-papers-lu.pdf), velarixdb aims to significantly enhance performance over traditional key-value stores.
+
+## Performance Benefits
+
+According to the benchmarks presented in the WiscKey paper, implementations can outperform LevelDB and RocksDB by:
+- **2.5x to 111x** for database loading
+- **1.6x to 14x** for random lookups
+
+## Concurrency with Tokio
+
+To achieve high concurrency without the overhead of spawning new threads every time, velarixdb utilizes the Tokio runtime. This allows for efficient and scalable asynchronous operations, making the most of modern multi-core processors.
+
+## Disclaimer
+
+Please note that velarixdb is still under development and is not yet production-ready.
+
+### Features
+- [x] Atomic `Put()`, `Get()`, `Delete()`, and `Update()` operations
+- [x] 100% safe & stable Rust
+- [x] Separation of keys from values, reducing the amount of data moved during compaction (i.e., reduced IO amplification)
+- [x] Garbage Collector
+- [x] Lock-free memtable (no `Mutex`)
+- [x] Tokio Runtime for efficient thread management
+- [x] Bloom Filters for fast in-memory key searches
+- [x] Crash recovery using the Value Log
+- [x] Index to improve searches on Sorted String Tables (SSTs)
+- [x] Key Range to store the largest and smallest keys in an SST
+- [x] Sized Tier Compaction Strategy (STCS)
+- [ ] Batched Writes
+- [ ] Snappy Compression Algorithm
+- [ ] Value Buffer to keep values in memory and only flush in batches to reduce IO (under investigation)
+- [ ] Checksum to detect data corruption
+- [ ] Leveled Compaction (LCS), Time-Window Compaction (TCS), and Unified Compaction (UCS)
+- [ ] Monitoring module to continuously monitor and generate reports
+
+### It is not:
+- A standalone server
+- A relational database
+- A wide-column database: it has no notion of columns
+
+### Constraint
+- Keys are limited to 65,536 bytes, and values are limited to 2^32 bytes. Larger keys and values have a bigger performance impact.
+- Like any typical key-value store, keys are stored in lexicographic order. If you are storing integer keys (e.g., timeseries data), use the big-endian form to adhere to locality.
+
+# Basic usage
+
+```sh
+cargo add velarixdb
```
- BBBBBBBB UU UU MM MM PPPPPPP DDDDDDD BBBBBBB
- B BB UU UU MMM MMM P PPP D DDD B BB
- BBBBBBBB UU UU MMMM MMMM PPPPPPP D DDD BBBBBBB
- B BB UU UU MM MM MM MM P D DDD B BB
- BBBBBBBB UUUUU MM MM MM MM P DDDDDDD BBBBBBB
+
+```rust
+use velarixdb::db::DataStore;
+# use tempfile::tempdir;
+
+#[tokio::main]
+async fn main() {
+ let root = tempdir().unwrap();
+ let path = root.path().join("velarix");
+ let mut store = DataStore::open("big_tech", path).await.unwrap(); // handle IO error
+
+ store.put("apple", "tim cook").await;
+ store.put("google", "sundar pichai").await;
+ store.put("nvidia", "jensen huang").await;
+ store.put("microsoft", "satya nadella").await;
+ store.put("meta", "mark zuckerberg").await;
+ store.put("openai", "sam altman").await;
+
+
+ let entry1 = store.get("apple").await.unwrap(); // Handle error
+ let entry2 = store.get("google").await.unwrap();
+ let entry3 = store.get("nvidia").await.unwrap();
+ let entry4 = store.get("microsoft").await.unwrap();
+ let entry5 = store.get("meta").await.unwrap();
+ let entry6 = store.get("openai").await.unwrap();
+ let entry7 = store.get("***not_found_key**").await.unwrap();
+
+ assert_eq!(std::str::from_utf8(&entry1.unwrap().val).unwrap(), "tim cook");
+ assert_eq!(std::str::from_utf8(&entry2.unwrap().val).unwrap(), "sundar pichai");
+ assert_eq!(std::str::from_utf8(&entry3.unwrap().val).unwrap(), "jensen huang");
+ assert_eq!(std::str::from_utf8(&entry4.unwrap().val).unwrap(), "satya nadella");
+ assert_eq!(std::str::from_utf8(&entry5.unwrap().val).unwrap(), "mark zuckerberg");
+ assert_eq!(std::str::from_utf8(&entry6.unwrap().val).unwrap(), "sam altman");
+ assert!(entry7.is_none());
+
+ // Remove an entry
+ store.delete("apple").await.unwrap();
+
+ // Update an entry
+ let success = store.update("microsoft", "elon musk").await;
+ assert!(success.is_ok());
+}
```
-## Plans to increase read speed
-* Introduce Block Cache
-* Introduce Snappy Compression Algorithm to reduce offset scanned to retrieve blocks on the disk
-* Introduce LCS
+# Store JSON
+
+```rust
+use serde::{Deserialize, Serialize};
+use serde_json;
+use velarixdb::db::DataStore;
+# use tempfile::tempdir;
+
+#[tokio::main]
+async fn main() {
+ let root = tempdir().unwrap();
+ let path = root.path().join("velarix");
+ let mut store = DataStore::open("big_tech", path).await.unwrap(); // handle IO error
+
+ #[derive(Serialize, Deserialize)]
+ struct BigTech {
+ name: String,
+ rank: i32,
+ }
+ let new_entry = BigTech {
+ name: String::from("Google"),
+ rank: 50,
+ };
+ let json_string = serde_json::to_string(&new_entry).unwrap();
+
+ let res = store.put("google", json_string).await;
+ assert!(res.is_ok());
+
+ let entry = store.get("google").await.unwrap().unwrap();
+ let entry_string = std::str::from_utf8(&entry.val).unwrap();
+ let big_tech: BigTech = serde_json::from_str(&entry_string).unwrap();
+
+ assert_eq!(big_tech.name, new_entry.name);
+ assert_eq!(big_tech.rank, new_entry.rank);
+}
+```
-This will signnificantly improve the read speed for now we only have key index, bloomfilters and sized tier (grouped into buckets)
\ No newline at end of file
+## Examples
+[See here](https://usenix.org/system/files/conference/fast16/fast16-papers-lu.pdf) for practical examples
\ No newline at end of file
diff --git a/compaction_algo.txt b/compaction_algo.txt
index 0b7d08a..73528ea 100644
--- a/compaction_algo.txt
+++ b/compaction_algo.txt
@@ -6,7 +6,7 @@ Compaction algorithm (Adopted from Apache Cassandra Sized Tier Compaction Strate
NOTE1: We also collect the Bucket ID and SSTable filepaths of the tables selected for compaction so that we can delete them from previous bucket where they existed
NOTE2: You cannot delete the sstbales until they have been compacted and written to disk to prevent data loss in case of outage
- - Compact the SS Tables and write them to buckets
+ - Compact the SSTables and write them to buckets
- Once write is complete, you can delete the sstables from the bucket it once exisited and recalculate the average size of this bucket for the future
NOTE: The deletion should include both from the disk and in-memory buckets
diff --git a/examples/delete.rs b/examples/delete.rs
new file mode 100644
index 0000000..9e56583
--- /dev/null
+++ b/examples/delete.rs
@@ -0,0 +1,22 @@
+use tempfile::tempdir;
+use velarixdb::db::DataStore;
+
+#[tokio::main]
+async fn main() {
+ let root = tempdir().unwrap();
+ let path = root.path().join("velarix");
+ let mut store = DataStore::open("big_tech", path).await.unwrap(); // handle IO error
+
+ store.put("apple", "tim cook").await.unwrap(); // handle error
+
+ // Retrieve entry
+ let entry = store.get("apple").await.unwrap();
+ assert!(entry.is_some());
+
+ // Delete entry
+ store.delete("apple").await.unwrap();
+
+ // Entry should now be None
+ let entry = store.get("apple").await.unwrap();
+ assert!(entry.is_none());
+}
diff --git a/examples/get.rs b/examples/get.rs
new file mode 100644
index 0000000..9916ede
--- /dev/null
+++ b/examples/get.rs
@@ -0,0 +1,39 @@
+use tempfile::tempdir;
+use velarixdb::db::DataStore;
+
+#[tokio::main]
+async fn main() {
+ let root = tempdir().unwrap();
+ let path = root.path().join("velarix");
+ let mut store = DataStore::open("big_tech", path).await.unwrap(); // handle IO error
+
+ let res1 = store.put("apple", "tim cook").await;
+ let res2 = store.put("google", "sundar pichai").await;
+ let res3 = store.put("nvidia", "jensen huang").await;
+ let res4 = store.put("microsoft", "satya nadella").await;
+ let res5 = store.put("meta", "mark zuckerberg").await;
+ let res6 = store.put("openai", "sam altman").await;
+
+ assert!(res1.is_ok());
+ assert!(res2.is_ok());
+ assert!(res3.is_ok());
+ assert!(res4.is_ok());
+ assert!(res5.is_ok());
+ assert!(res6.is_ok());
+
+ let entry1 = store.get("apple").await.unwrap(); // Handle error
+ let entry2 = store.get("google").await.unwrap();
+ let entry3 = store.get("nvidia").await.unwrap();
+ let entry4 = store.get("microsoft").await.unwrap();
+ let entry5 = store.get("meta").await.unwrap();
+ let entry6 = store.get("openai").await.unwrap();
+ let entry7 = store.get("***not_found_key**").await.unwrap();
+
+ assert_eq!(std::str::from_utf8(&entry1.unwrap().val).unwrap(), "tim cook");
+ assert_eq!(std::str::from_utf8(&entry2.unwrap().val).unwrap(), "sundar pichai");
+ assert_eq!(std::str::from_utf8(&entry3.unwrap().val).unwrap(), "jensen huang");
+ assert_eq!(std::str::from_utf8(&entry4.unwrap().val).unwrap(), "satya nadella");
+ assert_eq!(std::str::from_utf8(&entry5.unwrap().val).unwrap(), "mark zuckerberg");
+ assert_eq!(std::str::from_utf8(&entry6.unwrap().val).unwrap(), "sam altman");
+ assert!(entry7.is_none())
+}
diff --git a/examples/get_concurrent.rs b/examples/get_concurrent.rs
new file mode 100644
index 0000000..fa3bf43
--- /dev/null
+++ b/examples/get_concurrent.rs
@@ -0,0 +1,62 @@
+use std::{collections::HashMap, sync::Arc};
+
+use futures::future::join_all;
+use tempfile::tempdir;
+use tokio::sync::RwLock;
+use velarixdb::db::DataStore;
+
+#[tokio::main]
+async fn main() {
+ let root = tempdir().unwrap();
+ let path = root.path().join("velarix");
+ let store = DataStore::open("big_tech", path).await.unwrap(); // handle IO error
+ let mut entries = HashMap::new();
+ entries.insert("apple", "tim cook");
+ entries.insert("google", "tim cook");
+ entries.insert("nvidia", "tim cook");
+ entries.insert("microsoft", "tim cook");
+ entries.insert("meta", "tim cook");
+ entries.insert("openai", "sam altman");
+
+ let store_ref = Arc::new(RwLock::new(store));
+ let writes = entries.iter().map(|(k, v)| {
+ let store_inner = Arc::clone(&store_ref);
+ let key = k.to_owned();
+ let val = v.to_owned();
+ tokio::spawn(async move {
+ let mut writer = store_inner.write().await;
+ writer.put(key, val).await
+ })
+ });
+ let all_results = join_all(writes).await;
+ for tokio_res in all_results {
+ assert!(tokio_res.is_ok());
+ assert!(tokio_res.as_ref().unwrap().is_ok());
+ }
+
+
+
+ // Read entries concurently
+ let reads = entries.iter().map(|(k, _)| {
+ let store_inner = Arc::clone(&store_ref);
+ let key = k.to_owned();
+ tokio::spawn(async move {
+ match store_inner.read().await.get(key.to_owned()).await {
+ Ok(entry) => Ok((key, entry)),
+ Err(err) => Err(err),
+ }
+ })
+ });
+
+ let all_results = join_all(reads).await;
+ for tokio_res in all_results {
+ assert!(tokio_res.is_ok());
+ assert!(tokio_res.as_ref().unwrap().is_ok());
+ let (key, value) = tokio_res.unwrap().unwrap();
+ assert!(value.is_some());
+ assert_eq!(
+ std::str::from_utf8(&value.unwrap().val).unwrap(),
+ *entries.get(&key).unwrap()
+ );
+ }
+}
diff --git a/examples/json.rs b/examples/json.rs
new file mode 100644
index 0000000..5a4cbe5
--- /dev/null
+++ b/examples/json.rs
@@ -0,0 +1,34 @@
+use serde::{Deserialize, Serialize};
+use serde_json;
+use tempfile::tempdir;
+use velarixdb::db::DataStore;
+
+#[tokio::main]
+async fn main() {
+ let root = tempdir().unwrap();
+ let path = root.path().join("velarix");
+ let mut store = DataStore::open("big_tech", path).await.unwrap(); // handle IO error
+
+ #[derive(Serialize, Deserialize)]
+ struct BigTech {
+ name: String,
+ rank: i32,
+ }
+
+ let new_entry = BigTech {
+ name: String::from("Google"),
+ rank: 50,
+ };
+
+ let json_string = serde_json::to_string(&new_entry).unwrap();
+ let res = store.put("google", json_string).await;
+
+ assert!(res.is_ok());
+
+ let entry = store.get("google").await.unwrap().unwrap();
+ let entry_string = std::str::from_utf8(&entry.val).unwrap();
+ let big_tech: BigTech = serde_json::from_str(&entry_string).unwrap();
+
+ assert_eq!(big_tech.name, new_entry.name);
+ assert_eq!(big_tech.rank, new_entry.rank);
+}
diff --git a/examples/put.rs b/examples/put.rs
index fa83b43..b1e83be 100644
--- a/examples/put.rs
+++ b/examples/put.rs
@@ -1,13 +1,23 @@
-// use std::path::PathBuf;
+use tempfile::tempdir;
+use velarixdb::db::DataStore;
-// use tempfile::tempdir;
-// use vikingsdb::db::DataStore;
+#[tokio::main]
+async fn main() {
+ let root = tempdir().unwrap();
+ let path = root.path().join("velarix");
+ let mut store = DataStore::open("big_tech", path).await.unwrap(); // handle IO error
-fn main() {}
+ let res1 = store.put("apple", "tim cook").await;
+ let res2 = store.put("google", "sundar pichai").await;
+ let res3 = store.put("nvidia", "jensen huang").await;
+ let res4 = store.put("microsoft", "satya nadella").await;
+ let res5 = store.put("meta", "mark zuckerberg").await;
+ let res6 = store.put("openai", "sam altman").await;
-// async fn put() {
-// let root = tempdir().unwrap();
-// let path = PathBuf::from(root.path().join("db"));
-// let store = DataStore::new("put_db", path.clone()).await.unwrap();
-// store.put()
-// }
+ assert!(res1.is_ok());
+ assert!(res2.is_ok());
+ assert!(res3.is_ok());
+ assert!(res4.is_ok());
+ assert!(res5.is_ok());
+ assert!(res6.is_ok());
+}
diff --git a/examples/put_concurrent.rs b/examples/put_concurrent.rs
new file mode 100644
index 0000000..88df7be
--- /dev/null
+++ b/examples/put_concurrent.rs
@@ -0,0 +1,38 @@
+use std::sync::Arc;
+
+use futures::future::join_all;
+use tempfile::tempdir;
+use tokio::sync::RwLock;
+use velarixdb::db::DataStore;
+
+#[tokio::main]
+async fn main() {
+ let root = tempdir().unwrap();
+ let path = root.path().join("velarix");
+ let store = DataStore::open("big_tech", path).await.unwrap(); // handle IO error
+
+ let entries = [
+ ["apple", "tim cook"],
+ ["google", "sundar pichai"],
+ ["nvidia", "jensen huang"],
+ ["microsoft", "satya nadella"],
+ ["meta", "mark zuckerberg"],
+ ["openai", "sam altman"],
+ ];
+
+ let store_ref = Arc::new(RwLock::new(store));
+ let write_tasks = entries.iter().map(|e| {
+ let store_inner = Arc::clone(&store_ref);
+ let key = e[0];
+ let val = e[1];
+ tokio::spawn(async move {
+ let mut writer = store_inner.write().await;
+ writer.put(key, val).await
+ })
+ });
+ let all_results = join_all(write_tasks).await;
+ for tokio_res in all_results {
+ assert!(tokio_res.is_ok());
+ assert!(tokio_res.as_ref().unwrap().is_ok());
+ }
+}
diff --git a/examples/update.rs b/examples/update.rs
new file mode 100644
index 0000000..2031bf9
--- /dev/null
+++ b/examples/update.rs
@@ -0,0 +1,20 @@
+use tempfile::tempdir;
+use velarixdb::db::DataStore;
+
+#[tokio::main]
+async fn main() {
+ let root = tempdir().unwrap();
+ let path = root.path().join("velarix");
+ let mut store = DataStore::open("big_tech", path).await.unwrap(); // handle IO error
+
+ store.put("apple", "tim cook").await.unwrap(); // handle error
+
+ // Update entry
+ let success = store.update("apple", "elon musk").await;
+ assert!(success.is_ok());
+
+ // Entry should now be updated
+ let entry = store.get("apple").await.unwrap(); // handle error
+ assert!(entry.is_some());
+ assert_eq!(std::str::from_utf8(&entry.unwrap().val).unwrap(), "elon musk")
+}
diff --git a/garbage_collection.txt b/garbage_collection.txt
index 797317d..3a6376e 100644
--- a/garbage_collection.txt
+++ b/garbage_collection.txt
@@ -1,5 +1,3 @@
-
-
1. We need to keep two pointers, head and tail
2. Only the part of the vLog between the head and the tail contains valid values
diff --git a/logo.png b/logo.png
new file mode 100644
index 0000000..7c7a814
Binary files /dev/null and b/logo.png differ
diff --git a/read_algo.txt b/read_algo.txt
deleted file mode 100644
index 66a3ef3..0000000
--- a/read_algo.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-Read algorithm
-
- - Check bloom filters to know which sstable contains the key
-
- - Read that sstable
-
- - Read the index that maps the key to its value_offset in the value log
-
- - Use this offset to read the value in value log file and return
diff --git a/src/block/block.rs b/src/block/block_manager.rs
similarity index 97%
rename from src/block/block.rs
rename to src/block/block_manager.rs
index bff80b3..26a7039 100644
--- a/src/block/block.rs
+++ b/src/block/block_manager.rs
@@ -121,7 +121,7 @@ impl Block {
let entry_size = key.as_ref().len() + SIZE_OF_U32 + SIZE_OF_U32 + SIZE_OF_U64 + SIZE_OF_U8;
if self.is_full(entry_size) {
- return Err(Error::BlockIsFullError);
+ return Err(Error::BlockIsFull);
}
let entry = BlockEntry {
@@ -186,7 +186,7 @@ impl Block {
entry_vec.push(entry.is_tombstone as u8);
if entry_len != entry_vec.len() {
- return Err(SerializationError("Invalid input"));
+ return Err(Serialization("Invalid input"));
}
Ok(entry_vec)
@@ -237,7 +237,7 @@ mod tests {
let res = block.set_entry(
key.len() as u32,
- key.to_owned(),
+ &key,
value_offset,
creation_date,
is_tombstone,
@@ -288,7 +288,7 @@ mod tests {
let res = block.set_entry(
key.len() as u32,
- key.to_owned(),
+ &key,
value_offset,
creation_date,
is_tombstone,
@@ -327,7 +327,7 @@ mod tests {
let res = block.set_entry(
key.len() as u32,
- key.to_owned(),
+ &key,
value_offset,
creation_date,
is_tombstone,
@@ -361,7 +361,7 @@ mod tests {
block
.set_entry(
key.len() as u32,
- key.to_owned(),
+ &key,
value_offset,
creation_date,
is_tombstone,
@@ -372,7 +372,7 @@ mod tests {
// Attempt to set a new entry, which should result in an error
let res = block.set_entry(
key.len() as u32,
- key.to_owned(),
+ &key,
value_offset,
creation_date,
is_tombstone,
diff --git a/src/block/mod.rs b/src/block/mod.rs
index 973a96b..2641a64 100644
--- a/src/block/mod.rs
+++ b/src/block/mod.rs
@@ -1,3 +1,3 @@
-mod block;
+mod block_manager;
-pub use block::Block;
+pub use block_manager::Block;
diff --git a/src/bucket/bucket.rs b/src/bucket/bucket_manager.rs
similarity index 97%
rename from src/bucket/bucket.rs
rename to src/bucket/bucket_manager.rs
index 0d3cb84..01e12e3 100644
--- a/src/bucket/bucket.rs
+++ b/src/bucket/bucket_manager.rs
@@ -116,7 +116,7 @@ impl Bucket {
for meta_task in fetch_files_meta {
let meta_data = meta_task
.await
- .map_err(|err| GetFileMetaDataError(err.into()))?
+ .map_err(|err| GetFileMetaData(err.into()))?
.unwrap();
all_sstable_size += meta_data.len() as usize;
}
@@ -236,7 +236,7 @@ impl BucketMap {
InsertionType::New => {
bucket.avarage_size = fs::metadata(sst.clone().data_file.path)
.await
- .map_err(GetFileMetaDataError)?
+ .map_err(GetFileMetaData)?
.len() as usize;
self.buckets.insert(bucket.id, bucket);
}
@@ -319,7 +319,7 @@ impl BucketMap {
} else {
buckets_to_delete.push(bucket_id);
if let Err(err) = fs::remove_dir_all(&bucket.dir).await {
- log::error!("{}", DirDeleteError(err));
+ log::error!("{}", DirDelete(err));
}
}
}
@@ -328,7 +328,7 @@ impl BucketMap {
if fs::metadata(&sst.dir).await.is_ok() {
if let Err(err) = fs::remove_dir_all(&sst.dir).await {
all_ssts_deleted = false;
- log::error!("{}", DirDeleteError(err));
+ log::error!("{}", DirDelete(err));
}
}
}
@@ -348,7 +348,7 @@ impl BucketMap {
for (_, bucket) in &self.buckets {
if fs::metadata(&bucket.dir).await.is_ok() {
if let Err(err) = fs::remove_dir_all(&bucket.dir).await {
- log::error!("{}", FileDeleteError(err));
+ log::error!("{}", FileDelete(err));
}
}
}
diff --git a/src/bucket/mod.rs b/src/bucket/mod.rs
index 76e489f..965cfdd 100644
--- a/src/bucket/mod.rs
+++ b/src/bucket/mod.rs
@@ -1,7 +1,8 @@
-pub(crate) mod bucket;
-pub use bucket::Bucket;
-pub use bucket::BucketID;
-pub use bucket::BucketMap;
-pub use bucket::ImbalancedBuckets;
-pub use bucket::InsertableToBucket;
-pub use bucket::SSTablesToRemove;
+
+pub(crate) mod bucket_manager;
+pub use bucket_manager::Bucket;
+pub use bucket_manager::BucketID;
+pub use bucket_manager::BucketMap;
+pub use bucket_manager::ImbalancedBuckets;
+pub use bucket_manager::InsertableToBucket;
+pub use bucket_manager::SSTablesToRemove;
diff --git a/src/cfg/config.rs b/src/cfg/config.rs
index c888ad2..e81770e 100644
--- a/src/cfg/config.rs
+++ b/src/cfg/config.rs
@@ -75,6 +75,7 @@ fn get_open_file_limit() -> usize {
}
impl Config {
+ #![allow(clippy::too_many_arguments)]
pub fn new(
false_positive_rate: f64,
enable_ttl: bool,
@@ -163,7 +164,7 @@ impl DataStore<'static, Key> {
/// The size must be at least 50 kilobytes.
pub fn with_write_buffer_size(mut self, size: usize) -> Self {
assert!(size >= 50, "write_buffer_size should not be less than 50 Kilobytes");
- self.config.write_buffer_size = SizeUnit::Kilobytes.to_bytes(size);
+ self.config.write_buffer_size = SizeUnit::Kilobytes.as_bytes(size);
self
}
@@ -258,7 +259,7 @@ impl DataStore<'static, Key> {
/// The size must be at least 50 kilobytes.
pub fn with_gc_chunk_size(mut self, size: usize) -> Self {
assert!(size >= 50, "gc_chunk_size should not be less than 50 Kilobyte");
- self.config.gc_chunk_size = SizeUnit::Kilobytes.to_bytes(size);
+ self.config.gc_chunk_size = SizeUnit::Kilobytes.as_bytes(size);
self
}
}
@@ -270,11 +271,11 @@ mod tests {
use crate::cfg::Config;
use super::*;
- use std::{path::PathBuf, time::Duration};
+ use std::time::Duration;
async fn create_datastore() -> DataStore<'static, Key> {
let root = tempdir().unwrap();
- let path = PathBuf::from(root.path().join("store_test_3"));
+ let path = root.path().join("store_test_3");
let mut store = DataStore::open("test", path).await.unwrap();
// Initialize with default or dummy values
let config = Config {
@@ -295,7 +296,7 @@ mod tests {
open_files_limit: 150,
};
store.config = config;
- return store;
+ store
}
#[tokio::test]
@@ -344,7 +345,7 @@ mod tests {
async fn test_with_write_buffer_size() {
let ds = create_datastore().await;
let ds = ds.with_write_buffer_size(100);
- assert_eq!(ds.config.write_buffer_size, SizeUnit::Kilobytes.to_bytes(100));
+ assert_eq!(ds.config.write_buffer_size, SizeUnit::Kilobytes.as_bytes(100));
}
#[tokio::test]
@@ -372,7 +373,7 @@ mod tests {
#[should_panic(expected = "entry_ttl_millis cannot be less than 3 days if enable_ttl is set to true")]
async fn test_with_entry_ttl_invalid() {
let ds = create_datastore().await.with_enable_ttl(true);
- ds.with_entry_ttl(Duration::from_secs(1 * 24 * 60 * 60)); // 1 day
+ ds.with_entry_ttl(Duration::from_secs(24 * 60 * 60)); // 1 day
}
#[tokio::test]
@@ -450,7 +451,7 @@ mod tests {
async fn test_with_compaction_strategy() {
let ds = create_datastore().await;
let strategy = compactors::Strategy::STCS; // Replace with actual strategy
- let ds = ds.with_compaction_strategy(strategy.clone());
+ let ds = ds.with_compaction_strategy(strategy);
assert_eq!(ds.config.compaction_strategy, compactors::Strategy::STCS);
}
@@ -479,6 +480,6 @@ mod tests {
async fn test_with_gc_chunk_size() {
let ds = create_datastore().await;
let ds = ds.with_gc_chunk_size(100);
- assert_eq!(ds.config.gc_chunk_size, SizeUnit::Kilobytes.to_bytes(100));
+ assert_eq!(ds.config.gc_chunk_size, SizeUnit::Kilobytes.as_bytes(100));
}
}
diff --git a/src/compactors/compact.rs b/src/compactors/compact.rs
index 03037b8..6759843 100644
--- a/src/compactors/compact.rs
+++ b/src/compactors/compact.rs
@@ -1,7 +1,8 @@
use crate::bucket::InsertableToBucket;
-use crate::types::{BloomFilterHandle, Bool, BucketMapHandle, FlushReceiver, KeyRangeHandle};
+use crate::types::{Bool, BucketMapHandle, FlushReceiver, KeyRangeHandle};
use crate::{err::Error, filter::BloomFilter};
use std::sync::Arc;
+use std::time;
use tokio::sync::Mutex;
use tokio::time::sleep;
use Error::*;
@@ -14,7 +15,7 @@ use Error::*;
/// These expired tombstones are removed entirely during compaction, freeing up disk space.
///
/// - **Unexpired Tombstones**: If a tombstone is not expired, it means the data it shadows might still be relevant in other tiers.
-/// In this case, VikingsDB keeps both the tombstone and the data in the new SSTable. This ensures consistency across tiers and allows for repairs if needed.
+/// In this case, velarixDB keeps both the tombstone and the data in the new SSTable. This ensures consistency across tiers and allows for repairs if needed.
///
/// Currently, only the Sized-Tier Compaction Strategy (STCS) is supported. However, support for Leveled Compaction (LCS), Time-Window Compaction (TWCS), and Unified Compaction (UCS) strategies is planned.
#[derive(Debug, Clone)]
@@ -55,6 +56,7 @@ pub struct Config {
pub(crate) filter_false_positive: f64,
}
impl Config {
+ #![allow(clippy::too_many_arguments)]
pub fn new(
use_ttl: Bool,
entry_ttl: std::time::Duration,
@@ -81,9 +83,9 @@ impl Config {
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Strategy {
STCS,
- LCS, // TODO
- TCS, // TODO
- UCS, // TODO
+ // LCS, TODO
+ // TCS, TODO
+ // UCS, TODO
}
#[derive(Debug, Clone)]
@@ -128,7 +130,7 @@ impl MergePointer {
}
}
-/// Merged SSTable stored here
+/// Merged SSTable stored here
/// before being flushed to disk
#[derive(Debug)]
pub struct MergedSSTable {
@@ -159,14 +161,15 @@ impl MergedSSTable {
}
impl Compactor {
+ #![allow(clippy::too_many_arguments)]
// Creates new `Compactor`
pub fn new(
use_ttl: Bool,
- entry_ttl: std::time::Duration,
- tombstone_ttl: std::time::Duration,
- background_interval: std::time::Duration,
- flush_listener_interval: std::time::Duration,
- tombstone_compaction_interval: std::time::Duration,
+ entry_ttl: time::Duration,
+ tombstone_ttl: time::Duration,
+ background_interval: time::Duration,
+ flush_listener_interval: time::Duration,
+ tombstone_compaction_interval: time::Duration,
strategy: Strategy,
reason: CompactionReason,
filter_false_positive: f64,
@@ -192,7 +195,6 @@ impl Compactor {
pub fn tombstone_compaction_condition_background_checker(
&self,
bucket_map: BucketMapHandle,
- filter: BloomFilterHandle,
key_range: KeyRangeHandle,
) {
let cfg = self.config.to_owned();
@@ -210,7 +212,6 @@ impl Compactor {
&self,
flush_rx: FlushReceiver,
bucket_map: BucketMapHandle,
- filter: BloomFilterHandle,
key_range: KeyRangeHandle,
) {
let mut rx = flush_rx.clone();
@@ -226,10 +227,10 @@ impl Compactor {
drop(state);
match err {
async_broadcast::TryRecvError::Overflowed(_) => {
- log::error!("{}", FlushSignalChannelOverflowError)
+ log::error!("{}", FlushSignalChannelOverflow)
}
async_broadcast::TryRecvError::Closed => {
- log::error!("{}", FlushSignalChannelClosedError)
+ log::error!("{}", FlushSignalChannelClosed)
}
async_broadcast::TryRecvError::Empty => {}
}
@@ -237,13 +238,8 @@ impl Compactor {
}
*state = CompState::Active;
drop(state);
- if let Err(err) = Compactor::handle_compaction(
- Arc::clone(&bucket_map),
- Arc::clone(&filter),
- Arc::clone(&key_range),
- &cfg,
- )
- .await
+ if let Err(err) =
+ Compactor::handle_compaction(Arc::clone(&bucket_map), Arc::clone(&key_range), &cfg).await
{
log::info!("{}", Error::CompactionFailed(Box::new(err)));
continue;
@@ -257,12 +253,7 @@ impl Compactor {
}
/// Background compaction runner for maintenance
- pub fn start_periodic_background_compaction(
- &self,
- buckets: BucketMapHandle,
- filter: BloomFilterHandle,
- key_range: KeyRangeHandle,
- ) {
+ pub fn spawn_compaction_worker(&self, buckets: BucketMapHandle, key_range: KeyRangeHandle) {
let cfg = self.config.to_owned();
let comp_state = Arc::clone(&self.is_active);
tokio::spawn(async move {
@@ -272,13 +263,8 @@ impl Compactor {
if let CompState::Sleep = *state {
*state = CompState::Active;
drop(state);
- if let Err(err) = Compactor::handle_compaction(
- Arc::clone(&buckets),
- Arc::clone(&filter),
- Arc::clone(&key_range),
- &cfg,
- )
- .await
+ if let Err(err) =
+ Compactor::handle_compaction(Arc::clone(&buckets), Arc::clone(&key_range), &cfg).await
{
log::info!("{}", Error::CompactionFailed(Box::new(err)))
}
@@ -291,32 +277,15 @@ impl Compactor {
pub async fn handle_compaction(
buckets: BucketMapHandle,
- filter: BloomFilterHandle,
key_range: KeyRangeHandle,
cfg: &Config,
) -> Result<(), Error> {
match cfg.strategy {
Strategy::STCS => {
- let mut runner = super::sized::SizedTierRunner::new(
- Arc::clone(&buckets),
- Arc::clone(&filter),
- Arc::clone(&key_range),
- cfg,
- );
+ let mut runner = super::sized::SizedTierRunner::new(Arc::clone(&buckets), Arc::clone(&key_range), cfg);
runner.run_compaction().await
}
- Strategy::LCS => {
- log::info!("LCS not curently supported, try SCS instead");
- Ok(())
- }
- Strategy::TCS => {
- log::info!("TCS not curently supported, try SCS instead");
- Ok(())
- }
- Strategy::UCS => {
- log::info!("UCS not curently supported, try SCS instead");
- Ok(())
- }
+ // LCS, UCS and TWS will be added later
}
}
diff --git a/src/compactors/sized.rs b/src/compactors/sized.rs
index 902cfc5..88faaff 100644
--- a/src/compactors/sized.rs
+++ b/src/compactors/sized.rs
@@ -1,7 +1,6 @@
-use std::{cmp, collections::HashMap, path::PathBuf, sync::Arc};
+use std::{cmp, collections::HashMap, sync::Arc};
use crossbeam_skiplist::SkipMap;
-use uuid::Uuid;
use super::{
compact::{Config, MergePointer, WriteTracker},
@@ -12,8 +11,7 @@ use crate::{
err::Error,
filter::BloomFilter,
memtable::Entry,
- sst::Table,
- types::{BloomFilterHandle, Bool, BucketMapHandle, CreatedAt, Key, KeyRangeHandle, ValOffset},
+ types::{ Bool, BucketMapHandle, CreatedAt, Key, KeyRangeHandle, ValOffset},
};
use crate::{err::Error::*, memtable::SkipMapValue};
@@ -27,9 +25,6 @@ pub struct SizedTierRunner<'a> {
/// A thread-safe BucketMap with each bucket mapped to its id
bucket_map: BucketMapHandle,
- /// A thread-safe vector of sstable bloom filters
- filters: BloomFilterHandle,
-
/// A thread-safe hashmap of sstables each mapped to its key range
key_range: KeyRangeHandle,
@@ -45,14 +40,12 @@ impl<'a> SizedTierRunner<'a> {
/// creates new instance of `SizedTierRunner`
pub fn new(
bucket_map: BucketMapHandle,
- filters: BloomFilterHandle,
key_range: KeyRangeHandle,
config: &'a Config,
) -> SizedTierRunner<'a> {
Self {
tombstones: HashMap::new(),
bucket_map,
- filters,
key_range,
config,
}
@@ -73,7 +66,6 @@ impl<'a> SizedTierRunner<'a> {
// TODO: Handle this with multiple threads
loop {
let buckets: BucketMapHandle = Arc::clone(&self.bucket_map);
- let filters = Arc::clone(&self.filters);
let key_range = Arc::clone(&self.key_range);
// Step 1: Extract imbalanced buckets
let (imbalanced_buckets, ssts_to_remove) =
@@ -96,64 +88,44 @@ impl<'a> SizedTierRunner<'a> {
match insert_res {
Ok(sst) => {
if sst.summary.is_none() {
- return Err(TableSummaryIsNoneError);
+ return Err(TableSummaryIsNone);
}
if sst.filter.is_none() {
return Err(FilterNotProvidedForFlush);
}
// IMPORTANT: Don't keep sst entries in memory
sst.entries.clear();
- // Step 4 Store Filter in Filters Vec
- filters.write().await.push(sst.filter.to_owned().unwrap());
let summary = sst.summary.clone().unwrap();
// Step 5 Store sst key range
- key_range.write().await.set(
- sst.dir.to_owned(),
- summary.smallest_key,
- summary.biggest_key,
- sst,
- );
+ key_range
+ .set(sst.dir.to_owned(), summary.smallest_key, summary.biggest_key, sst)
+ .await;
tracker.actual += 1;
}
Err(err) => {
- // Step 6 (Optional): Trigger recovery in case compaction failed at any point
- // Ensure filters are restored to the previous state
- // Remove merged sstables written to disk so far to prevent stale data
- while tracker.actual > 0 {
- if let Some(filter) = filters.write().await.pop() {
- let sst_dir = filter.get_sst_dir().to_owned();
- if let Err(err) = tokio::fs::remove_dir_all(sst_dir.to_owned()).await {
- log::error!("{}", CompactionFailed(Box::new(DirDeleteError(err))));
- tracker.actual -= 1;
- continue;
- }
- key_range.write().await.remove(sst_dir.to_owned());
- }
- tracker.actual -= 1;
- }
return Err(CompactionFailed(Box::new(err)));
}
}
}
if tracker.expected == tracker.actual {
- // Step 7: Delete the sstables that we already merged from their previous buckets and update bloom filters
+ // Step 6: Delete the sstables that we already merged from their previous buckets and update bloom filters
let filters_updated = self
- .clean_up_after_compaction(buckets, &ssts_to_remove.clone(), filters, key_range)
+ .clean_up_after_compaction(buckets, &ssts_to_remove.clone(), key_range)
.await;
match filters_updated {
Ok(None) => {
return Err(Error::CompactionPartiallyFailed(Box::new(
- CompactionCleanupPartialError,
+ CompactionCleanupPartial,
)));
}
Err(err) => {
- return Err(Error::CompactionCleanupError(Box::new(err)));
+ return Err(Error::CompactionCleanup(Box::new(err)));
}
_ => {}
}
} else {
- log::error!("{}", Error::CannotRemoveObsoleteSSTError)
+ log::error!("{}", Error::CannotRemoveObsoleteSST)
}
}
Err(err) => return Err(CompactionFailed(Box::new(err))),
@@ -173,48 +145,27 @@ impl<'a> SizedTierRunner<'a> {
&self,
buckets: BucketMapHandle,
ssts_to_delete: &SSTablesToRemove,
- filters: BloomFilterHandle,
key_range: KeyRangeHandle,
) -> Result