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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ obj/
# Documentations not for release
STUDY-GUIDE.md
*Design.md
INTERVIEW-*.md

# IDE configurations
.vs/
Expand Down
18 changes: 9 additions & 9 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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)
132 changes: 97 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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.
5 changes: 3 additions & 2 deletions src/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#ifdef _WIN32
#include <io.h>
#include <share.h> // _SH_DENYNO for _sopen_s
#include <sys/stat.h>

#ifndef O_RDWR
Expand Down Expand Up @@ -79,7 +80,7 @@ static inline int file_ftruncate(int fd, int64_t length) {
}
#endif

namespace ledgerdb {
namespace alphadb {

// ---------------------------------------------------------------------------
// Construction / destruction
Expand Down Expand Up @@ -238,4 +239,4 @@ std::size_t Engine::size() {
return keydir_.size();
}

} // namespace ledgerdb
} // namespace alphadb
4 changes: 2 additions & 2 deletions src/engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
#include <string>
#include <unordered_map>

namespace ledgerdb {
namespace alphadb {

class Engine {
public:
Expand Down Expand Up @@ -65,4 +65,4 @@ class Engine {
std::mutex mu_;
};

} // namespace ledgerdb
} // namespace alphadb
10 changes: 5 additions & 5 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -13,15 +13,15 @@
#include <string>

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";
Expand Down
4 changes: 2 additions & 2 deletions src/record.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#include "record.hpp"
#include <cstring> // std::memcpy

namespace ledgerdb {
namespace alphadb {

// ---------------------------------------------------------------------------
// CRC32 — table-based implementation of the standard polynomial 0xEDB88320.
Expand Down Expand Up @@ -105,4 +105,4 @@ DecodeResult decode(const uint8_t* buf, std::size_t available) {
return res;
}

} // namespace ledgerdb
} // namespace alphadb
4 changes: 2 additions & 2 deletions src/record.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
#include <string>
#include <vector>

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.
Expand Down Expand Up @@ -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
6 changes: 3 additions & 3 deletions src/server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {}

Expand Down Expand Up @@ -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);
Expand All @@ -149,4 +149,4 @@ void Server::run() {
#endif
}

} // namespace ledgerdb
} // namespace alphadb
4 changes: 2 additions & 2 deletions src/server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ using socket_t = std::uintptr_t;
using socket_t = int;
#endif

namespace ledgerdb {
namespace alphadb {

class Server {
public:
Expand All @@ -38,4 +38,4 @@ class Server {
int port_;
};

} // namespace ledgerdb
} // namespace alphadb
Loading
Loading