#include "store/AtomicFile.hpp"
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio>
#include "core/Log.hpp"
#include "spec/StoreKeys.hpp"
namespace dp {
bool AtomicFile::write(const std::string& path, const std::string& content, unsigned mode, std::size_t maxBytes) {
if (content.size() > maxBytes) {
Log::error("file write refused: over cap: " + path);
return false;
}
const std::string temp = path + spec::SessionKeys::kTempSuffix;
const int fd = ::open(temp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, mode);
if (fd < 0) {
Log::error("file write failed (open): " + temp);
return false;
}
bool ok = ::fchmod(fd, mode) == 0;
std::size_t written = 0;
while (ok && written < content.size()) {
const ssize_t n = ::write(fd, content.data() + written, content.size() - written);
if (n < 0 && errno == EINTR) continue;
if (n <= 0) ok = false;
else written += static_cast<std::size_t>(n);
}
ok = (::close(fd) == 0) && ok;
if (ok) ok = std::rename(temp.c_str(), path.c_str()) == 0;
if (!ok) {
Log::error("file write failed: " + path);
::unlink(temp.c_str());
}
return ok;
}
std::optional<std::string> AtomicFile::read(const std::string& path, std::size_t maxBytes, bool* tooLarge) {
if (tooLarge) *tooLarge = false;
struct stat st{};
if (::stat(path.c_str(), &st) != 0) return std::nullopt;
if (static_cast<std::size_t>(st.st_size) > maxBytes) {
if (tooLarge) *tooLarge = true;
return std::nullopt;
}
std::FILE* f = std::fopen(path.c_str(), "rb");
if (!f) return std::nullopt;
std::string out(static_cast<std::size_t>(st.st_size), '\0');
const std::size_t n = out.empty() ? 0 : std::fread(out.data(), 1, out.size(), f);
std::fclose(f);
if (n != out.size()) return std::nullopt;
return out;
}
} // namespace dp