SharedStorage/server.cpp

75 lines
2.2 KiB
C++

#include "core/SharedMemoryManager.h"
#include "core/SharedCommandQueue.h"
#include "core/Command.h"
#include "utils/hash/Hash128.h"
#include "utils/string/basic_utils.h"
#include <unordered_map>
#include <iostream>
#include <thread>
#include <optional>
using namespace usub::core;
using namespace usub::utils;
int main()
{
::shm_unlink("/shm_command_queue");
try
{
SharedMemoryManager shm("shm_command_queue", sizeof(SharedCommandQueue));
auto* cmd_queue = new(shm.base_ptr()) SharedCommandQueue(1024);
std::unordered_map<Hash128, std::string> database;
std::cout << "Server started. Listening for commands...\n";
while (true)
{
std::optional<Command> opt_cmd = cmd_queue->try_pop();
if (!opt_cmd)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
Command& cmd = *opt_cmd;
switch (cmd.op)
{
case OperationType::PUT:
{
std::string value(cmd.value, cmd.value_size);
database[cmd.key] = value;
std::cout << "[PUT] key = " << to_string(cmd.key) << ", value = " << value << "\n";
break;
}
case OperationType::DELETE:
{
database.erase(cmd.key);
std::cout << "[DELETE] key = " << to_string(cmd.key) << "\n";
break;
}
case OperationType::FIND:
{
auto it = database.find(cmd.key);
if (it != database.end())
std::cout << "[FIND] key = " << to_string(cmd.key) << " => " << it->second << "\n";
else
std::cout << "[FIND] key = " << to_string(cmd.key) << " not found\n";
break;
}
default:
std::cout << "[UNKNOWN COMMAND]\n";
break;
}
}
}
catch (const std::exception& ex)
{
std::cerr << "Server exception: " << ex.what() << std::endl;
return 1;
}
}