SharedStorage/utils/io/RecoveryLog.cpp
2025-04-20 18:24:28 +03:00

70 lines
2.0 KiB
C++

//
// Created by Kirill Zhukov on 20.04.2025.
//
#include "RecoveryLog.h"
namespace usub::utils
{
RecoveryLog::RecoveryLog(const std::string& dbname)
: db_name(dbname),
metadata_dir("metadata/" + db_name + "/"),
log_file(metadata_dir + "recovery.log")
{
ensure_metadata_dir();
this->log_out.open(this->log_file, std::ios::binary | std::ios::app);
if (!this->log_out.is_open())
{
throw std::runtime_error("Failed to open recovery log for " + this->db_name);
}
}
RecoveryLog::~RecoveryLog()
{
if (this->log_out.is_open())
{
this->log_out.close();
}
}
void RecoveryLog::log_put(const std::string& key, const std::string& value)
{
uint8_t op = 0;
uint32_t key_len = key.size();
uint32_t value_len = value.size();
this->log_out.write(reinterpret_cast<const char*>(&op), sizeof(op));
this->log_out.write(reinterpret_cast<const char*>(&key_len), sizeof(key_len));
this->log_out.write(key.data(), key_len);
this->log_out.write(reinterpret_cast<const char*>(&value_len), sizeof(value_len));
this->log_out.write(value.data(), value_len);
this->log_out.flush();
}
void RecoveryLog::log_delete(const std::string& key)
{
uint8_t op = 1;
uint32_t key_len = key.size();
this->log_out.write(reinterpret_cast<const char*>(&op), sizeof(op));
this->log_out.write(reinterpret_cast<const char*>(&key_len), sizeof(key_len));
this->log_out.write(key.data(), key_len);
this->log_out.flush();
}
void RecoveryLog::ensure_metadata_dir()
{
try
{
if (!std::filesystem::exists(this->metadata_dir))
{
std::filesystem::create_directories(this->metadata_dir);
}
}
catch (const std::exception& e)
{
std::cerr << "Failed to create metadata dir: " << e.what() << std::endl;
}
}
} // utils
// usub