Skip to content

Commit

Permalink
Implement background expiry
Browse files Browse the repository at this point in the history
  • Loading branch information
mleleszi committed Jun 14, 2024
1 parent b9121d9 commit a71c389
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/controller.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

class Controller {
public:
Controller() { dataStore.startExpiryDaemon(); }

RedisType::RedisValue handleCommand(const std::vector<RedisType::BulkString> &command);

private:
Expand All @@ -14,6 +16,6 @@ class Controller {
RedisType::RedisValue handleGet(const std::vector<RedisType::BulkString> &command);
RedisType::RedisValue handleExists(const std::vector<RedisType::BulkString> &command);
RedisType::RedisValue handleConfig(const std::vector<RedisType::BulkString> &command);

DataStore dataStore;
};
17 changes: 17 additions & 0 deletions src/datastore.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <optional>
#include <random>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

Expand Down Expand Up @@ -65,6 +66,22 @@ class DataStore {
return deleted;
}

void startExpiryDaemon() {
auto backgroundThread = [this]() {
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
removeExpiredKeys();
}
};

std::thread(backgroundThread).detach();
}

int count() {
std::lock_guard<std::mutex> lock(mtx);
return store.size();
}


private:
std::unordered_map<std::string, Entry> store;
Expand Down
21 changes: 21 additions & 0 deletions tests/datastore_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,27 @@ TEST(DataStoreTests, RemoveExpiredKeys) {
auto val1 = store.get("key1");
ASSERT_FALSE(val1.has_value());

auto val2 = store.get("key2");
ASSERT_FALSE(val2.has_value());
}

TEST(DataStoreTests, ExpiryDaemon) {
DataStore store;
store.startExpiryDaemon();

store.setWithExpiry("key0", "val0", std::chrono::system_clock::now() + std::chrono::milliseconds(1000));
store.setWithExpiry("key1", "val1", std::chrono::system_clock::now() + std::chrono::milliseconds(200));
store.setWithExpiry("key2", "val2", std::chrono::system_clock::now() + std::chrono::milliseconds(300));
store.set("key3", "val3");

std::this_thread::sleep_for(std::chrono::milliseconds(500));

auto count = store.count();
ASSERT_EQ(count, 2);

auto val1 = store.get("key1");
ASSERT_FALSE(val1.has_value());

auto val2 = store.get("key2");
ASSERT_FALSE(val2.has_value());
}

0 comments on commit a71c389

Please sign in to comment.