diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ca925e7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,47 @@ +name: CI + +on: + push: + pull_request: + +jobs: + build-and-test: + name: ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + steps: + - uses: actions/checkout@v5 + + - name: Configure + run: cmake -B build -DCMAKE_BUILD_TYPE=Debug + + # --config and -C matter on Windows, where the Visual Studio generator + # builds several configurations; without them ctest finds no tests. + - name: Build + run: cmake --build build --config Debug + + # --no-tests=error fails the job if no tests were found, instead of + # reporting success after running nothing. + - name: Test + run: ctest --test-dir build -C Debug --output-on-failure --no-tests=error + + sanitizers: + name: ubuntu-latest (ASan + UBSan) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + # -fno-sanitize-recover=all makes any UBSan report fail the test run. + - name: Configure + run: > + cmake -B build -DCMAKE_BUILD_TYPE=Debug + -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=all" + + - name: Build + run: cmake --build build + + - name: Test + run: ctest --test-dir build --output-on-failure --no-tests=error diff --git a/.gitignore b/.gitignore index 52c6f46..983a6e8 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ obj/ # Documentations not for release STUDY-GUIDE.md *Design.md +INTERVIEW-*.md # IDE configurations .vs/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 5665390..6d78b81 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(ledgerdb CXX) +project(alphadb CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -14,19 +14,19 @@ find_package(Threads REQUIRED) # The reusable storage-engine code (no networking) lives here so it can be # tested on its own. -add_library(ledgerdb_core src/record.cpp src/engine.cpp) -target_link_libraries(ledgerdb_core PUBLIC Threads::Threads) +add_library(alphadb_core src/record.cpp src/engine.cpp) +target_link_libraries(alphadb_core PUBLIC Threads::Threads) # The server executable. -add_executable(ledgerdb src/main.cpp src/server.cpp) -target_link_libraries(ledgerdb PRIVATE ledgerdb_core) +add_executable(alphadb src/main.cpp src/server.cpp) +target_link_libraries(alphadb PRIVATE alphadb_core) if(WIN32) - target_link_libraries(ledgerdb PRIVATE ws2_32) + target_link_libraries(alphadb PRIVATE ws2_32) endif() # The test executable. -add_executable(ledgerdb_tests tests/test_engine.cpp) -target_link_libraries(ledgerdb_tests PRIVATE ledgerdb_core) +add_executable(alphadb_tests tests/test_engine.cpp) +target_link_libraries(alphadb_tests PRIVATE alphadb_core) enable_testing() -add_test(NAME engine_tests COMMAND ledgerdb_tests) +add_test(NAME engine_tests COMMAND alphadb_tests) diff --git a/README.md b/README.md index dc50417..0dea2c2 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,70 @@ -# LedgerDB +# AlphaDB -A small, persistent **key-value store** written in C++17. Writes are appended -to a log file on disk; an in-memory hash table maps each key to the byte offset -of its latest value; on restart the log is replayed to rebuild the index. It -serves multiple clients concurrently over TCP. +[![CI](https://github.com/Codealpha07/AlphaDB--Key-Value-Store/actions/workflows/ci.yml/badge.svg)](https://github.com/Codealpha07/AlphaDB--Key-Value-Store/actions/workflows/ci.yml) -This is a learning project modeled on **Bitcask** (the storage engine behind -Riak). It is intentionally small so that every line can be understood and -explained. +A small, persistent **key-value store** written in C++17, modeled on +**Bitcask** (the storage engine behind Riak). Every write is appended to a log +file on disk; an in-memory hash table maps each key to the byte offset of its +latest value; on restart the log is replayed to rebuild the index. It serves +multiple clients concurrently over TCP. + +It is intentionally small so that every line can be understood and explained. +The [known limitations](#known-limitations) below are listed on purpose: fixing +them is the current work. ## What it does -- `SET`, `GET`, `DEL` over a plain-text TCP protocol -- Durable across restarts and **crash-safe** (CRC-checked records; a torn tail - from a power loss is detected and dropped on recovery) -- Handles many concurrent clients (one thread per connection, a single mutex - guarding the engine) +- `SET`, `GET`, `DEL` and `PING` over a plain-text TCP protocol. +- Persists across restarts: each write is `fsync`ed before the client gets `+OK`, + and the log is replayed at startup. +- Detects a torn record at the end of the log. If the process or machine dies + mid-append, the partly written record fails its CRC32 check at startup and is + dropped. +- Serves concurrent clients with one thread per connection and a single mutex + around the engine. + +A read is one hash lookup plus one positional disk read (`pread`). Keys must fit +in memory; values stay on disk. + +## On-disk format + +One append-only file. Each record: + +| Field | Bytes | Notes | +|--------------|--------------|-----------------------------------------| +| `crc32` | 4 | Covers every byte after it in the record | +| `timestamp` | 8 | Microseconds since the epoch | +| `key_size` | 4 | | +| `value_size` | 4 | `0xFFFFFFFF` marks a delete (tombstone) | +| `key` | `key_size` | | +| `value` | `value_size` | Absent for a tombstone | ## Build ```bash -# with CMake -cmake -B build && cmake --build build -./build/ledgerdb # data file ./ledgerdb.data, port 5555 +cmake -B build +cmake --build build --config Release +``` + +The server binary is `build/alphadb` (or `build\Release\alphadb.exe` with Visual +Studio). It uses `./alphadb.data` and port 5555 by default: + +```bash +./build/alphadb # defaults +./build/alphadb mydata.data 5555 # explicit data file and port +``` + +Without CMake: -# or a one-line g++ build -g++ -std=c++17 -pthread src/main.cpp src/server.cpp src/record.cpp src/engine.cpp -o ledgerdb -./ledgerdb mydata.data 5555 +```bash +g++ -std=c++17 -pthread src/main.cpp src/server.cpp src/record.cpp src/engine.cpp -o alphadb ``` ## Try it ```bash # in one terminal -./ledgerdb +./build/alphadb # in another nc localhost 5555 @@ -47,27 +78,58 @@ PING # -> +PONG ## Run the tests ```bash -g++ -std=c++17 -pthread tests/test_engine.cpp src/record.cpp src/engine.cpp -o ledgerdb_tests -./ledgerdb_tests +ctest --test-dir build -C Release --output-on-failure ``` -Tests cover put/get/overwrite/delete, durability across a restart, CRC catching -a corrupted record, and torn-tail recovery. +The tests cover put, get, overwrite and delete; persistence across a restart; the +CRC rejecting a corrupted record; and recovery from a torn tail. The torn tail is +simulated by appending bytes to the file. Nothing yet kills a process, injects an +I/O error, or exercises the server or concurrency. + +CI builds and runs the tests on Linux and Windows on every push, plus a Linux +build with AddressSanitizer and UndefinedBehaviorSanitizer. + +## Known limitations + +These are known bugs or gaps, not design goals. + +- **Mid-log damage loses data.** Recovery stops at the first record that fails to + decode and truncates the file there, so damage in the middle of the log loses + every record after it. Opening a file that is not an AlphaDB log truncates it + to zero bytes. +- **Reads do not verify the CRC.** Corrupted bytes on disk are returned as a + valid value. +- **A failed `fsync` is not detected.** The client still receives `+OK`. +- **No file lock.** Two processes must not open the same data file. +- **Logs over 2 GiB cannot be reopened.** Recovery reads the whole file in one + call and needs memory equal to its size. +- **The protocol is ambiguous.** A missing key and the stored value `(nil)` give + the same reply, keys cannot contain spaces, and values cannot contain newlines. +- **One client can stop the server.** On Linux, a client that disconnects without + reading its replies can kill the process with `SIGPIPE`, and any storage error + in a client thread terminates the whole server. +- **Writes do not scale with clients.** The single mutex is held across `fsync`, + so concurrent writers wait for each other's flushes and readers wait too. +- **The log grows forever.** There is no compaction yet. ## Source layout | File | Responsibility | |------|----------------| -| `src/record.{hpp,cpp}` | On-disk record format + CRC32 (encode/decode) | -| `src/engine.{hpp,cpp}` | The Bitcask core: KeyDir index, get/put/del, crash recovery | -| `src/server.{hpp,cpp}` | TCP server + text protocol | -| `src/main.cpp` | Startup / wiring | +| `src/record.{hpp,cpp}` | On-disk record format and CRC32 (encode/decode) | +| `src/engine.{hpp,cpp}` | The Bitcask core: KeyDir index, get/put/del, recovery | +| `src/server.{hpp,cpp}` | TCP server and text protocol | +| `src/main.cpp` | Startup and wiring | | `tests/test_engine.cpp` | Unit tests | -## Deliberately not built (discussion / future work) - -Due to certain trade off decisions in this project ; focusing to come to optimal trade off points. :) - -Compaction (merging the log to reclaim space), hint files for faster startup, -multiple data files with rotation, a reader-writer lock and a thread pool, and -range queries. +## Not built, and why + +- **Compaction, multiple data files and hint files.** Correct compaction needs + an ordering of records across files and a safe rule for dropping tombstones. + It comes after recovery is fixed. +- **Reader-writer lock.** It would not help while the lock is held across + `fsync`; the real fix is moving disk I/O out from under the lock. +- **Thread pool.** Thread creation is not the bottleneck; the flush under the + lock is. +- **Range queries.** The hash index is unordered; range scans need an ordered + index, which is a different engine design. diff --git a/src/engine.cpp b/src/engine.cpp index 041a044..2dcc0d3 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -8,6 +8,7 @@ #ifdef _WIN32 #include +#include // _SH_DENYNO for _sopen_s #include #ifndef O_RDWR @@ -79,7 +80,7 @@ static inline int file_ftruncate(int fd, int64_t length) { } #endif -namespace ledgerdb { +namespace alphadb { // --------------------------------------------------------------------------- // Construction / destruction @@ -238,4 +239,4 @@ std::size_t Engine::size() { return keydir_.size(); } -} // namespace ledgerdb +} // namespace alphadb diff --git a/src/engine.hpp b/src/engine.hpp index f975537..48d3fbf 100644 --- a/src/engine.hpp +++ b/src/engine.hpp @@ -18,7 +18,7 @@ #include #include -namespace ledgerdb { +namespace alphadb { class Engine { public: @@ -65,4 +65,4 @@ class Engine { std::mutex mu_; }; -} // namespace ledgerdb +} // namespace alphadb diff --git a/src/main.cpp b/src/main.cpp index 8210fb5..57543d8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,9 +2,9 @@ // main.cpp — wire everything together and start serving. // // Usage: -// ledgerdb [data_file] [port] +// alphadb [data_file] [port] // -// Defaults to ./ledgerdb.data on port 5555. +// Defaults to ./alphadb.data on port 5555. // #include "engine.hpp" #include "server.hpp" @@ -13,15 +13,15 @@ #include int main(int argc, char** argv) { - std::string data_file = (argc > 1) ? argv[1] : "ledgerdb.data"; + std::string data_file = (argc > 1) ? argv[1] : "alphadb.data"; int port = (argc > 2) ? std::stoi(argv[2]) : 5555; try { - ledgerdb::Engine engine(data_file, /*fsync_on_write=*/true); + alphadb::Engine engine(data_file, /*fsync_on_write=*/true); std::cout << "Opened '" << data_file << "' with " << engine.size() << " live keys.\n"; - ledgerdb::Server server(engine, port); + alphadb::Server server(engine, port); server.run(); // blocks forever } catch (const std::exception& e) { std::cerr << "fatal: " << e.what() << "\n"; diff --git a/src/record.cpp b/src/record.cpp index 6e5b645..749b8fc 100644 --- a/src/record.cpp +++ b/src/record.cpp @@ -1,7 +1,7 @@ #include "record.hpp" #include // std::memcpy -namespace ledgerdb { +namespace alphadb { // --------------------------------------------------------------------------- // CRC32 — table-based implementation of the standard polynomial 0xEDB88320. @@ -105,4 +105,4 @@ DecodeResult decode(const uint8_t* buf, std::size_t available) { return res; } -} // namespace ledgerdb +} // namespace alphadb diff --git a/src/record.hpp b/src/record.hpp index 73b1836..89bd2f5 100644 --- a/src/record.hpp +++ b/src/record.hpp @@ -25,7 +25,7 @@ #include #include -namespace ledgerdb { +namespace alphadb { // value_size is set to this sentinel when the record is a "tombstone" — our // marker for a deleted key. A tombstone has a key but no value bytes. @@ -62,4 +62,4 @@ struct DecodeResult { // doesn't match (which is how we detect a torn record after a crash). DecodeResult decode(const uint8_t* buf, std::size_t available); -} // namespace ledgerdb +} // namespace alphadb diff --git a/src/server.cpp b/src/server.cpp index 43866d2..efc5e30 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -34,7 +34,7 @@ static inline ssize_t sock_write(socket_t s, const char* buf, size_t len) { #define IS_INVALID_SOCKET(s) ((s) < 0) #endif -namespace ledgerdb { +namespace alphadb { Server::Server(Engine& engine, int port) : engine_(engine), port_(port) {} @@ -135,7 +135,7 @@ void Server::run() { if (::listen(listen_fd, 16) < 0) throw std::runtime_error("listen() failed"); - std::cout << "LedgerDB listening on port " << port_ << " ...\n"; + std::cout << "AlphaDB listening on port " << port_ << " ...\n"; while (true) { socket_t client_fd = ::accept(listen_fd, nullptr, nullptr); @@ -149,4 +149,4 @@ void Server::run() { #endif } -} // namespace ledgerdb +} // namespace alphadb diff --git a/src/server.hpp b/src/server.hpp index d086b69..b137f4f 100644 --- a/src/server.hpp +++ b/src/server.hpp @@ -22,7 +22,7 @@ using socket_t = std::uintptr_t; using socket_t = int; #endif -namespace ledgerdb { +namespace alphadb { class Server { public: @@ -38,4 +38,4 @@ class Server { int port_; }; -} // namespace ledgerdb +} // namespace alphadb diff --git a/tests/test_engine.cpp b/tests/test_engine.cpp index 854b02d..74a658d 100644 --- a/tests/test_engine.cpp +++ b/tests/test_engine.cpp @@ -27,9 +27,9 @@ static int g_failures = 0; // Each test uses a fresh file so runs don't interfere. static std::string fresh_file(const char* name) { #ifdef _WIN32 - std::string path = std::string("ledgerdb_test_") + name + ".data"; + std::string path = std::string("alphadb_test_") + name + ".data"; #else - std::string path = std::string("/tmp/ledgerdb_test_") + name + ".data"; + std::string path = std::string("/tmp/alphadb_test_") + name + ".data"; #endif std::remove(path.c_str()); return path; @@ -39,7 +39,7 @@ static std::string fresh_file(const char* name) { static void test_basic() { std::printf("[test_basic]\n"); std::string f = fresh_file("basic"); - ledgerdb::Engine db(f); + alphadb::Engine db(f); CHECK(!db.get("missing").has_value()); // absent key -> nullopt @@ -63,14 +63,14 @@ static void test_persistence() { std::printf("[test_persistence]\n"); std::string f = fresh_file("persist"); { - ledgerdb::Engine db(f); // open #1 + alphadb::Engine db(f); // open #1 db.put("a", "1"); db.put("b", "2"); db.put("a", "11"); // overwrite db.del("b"); // tombstone } // db destroyed = process "exits" - ledgerdb::Engine db2(f); // open #2: replays the log + alphadb::Engine db2(f); // open #2: replays the log CHECK(db2.get("a").value() == "11"); // newest value survived CHECK(!db2.get("b").has_value()); // deletion survived CHECK(db2.size() == 1); @@ -80,20 +80,20 @@ static void test_persistence() { static void test_crc_detects_corruption() { std::printf("[test_crc_detects_corruption]\n"); - ledgerdb::Record rec; + alphadb::Record rec; rec.timestamp = 42; rec.key = "k"; rec.value = "v"; - auto bytes = ledgerdb::encode(rec); + auto bytes = alphadb::encode(rec); // A clean record decodes fine. - auto ok = ledgerdb::decode(bytes.data(), bytes.size()); + auto ok = alphadb::decode(bytes.data(), bytes.size()); CHECK(ok.ok == true); CHECK(ok.record.value == "v"); // Flip one byte in the value -> CRC must reject it. bytes.back() ^= 0xFF; - auto bad = ledgerdb::decode(bytes.data(), bytes.size()); + auto bad = alphadb::decode(bytes.data(), bytes.size()); CHECK(bad.ok == false); } @@ -102,7 +102,7 @@ static void test_torn_tail_recovery() { std::printf("[test_torn_tail_recovery]\n"); std::string f = fresh_file("torn"); { - ledgerdb::Engine db(f); + alphadb::Engine db(f); db.put("good", "value"); } // Simulate a crash mid-write: append a few garbage bytes to the file. @@ -112,7 +112,7 @@ static void test_torn_tail_recovery() { out.write(junk, sizeof(junk)); } // Recovery should skip the torn tail and still see the good key. - ledgerdb::Engine db2(f); + alphadb::Engine db2(f); CHECK(db2.get("good").value() == "value"); CHECK(db2.size() == 1); // And it should be usable afterwards (tail was truncated cleanly).