feat(storage): implement original V1 durable Storage engine, tools, and async adapter

This commit is contained in:
faumaray committed 2026-11-26 15:32:43 +03:00
1 parent 427cc9a843
commit fdf0da5ca8
21 files changed
+6966

No files matched your search

+272
View File
@@ -0,0 +1,272 @@
#include <Void/Storage/AsyncAdapter.hpp>
#include <atomic>
#include <condition_variable>
#include <deque>
#include <mutex>
#include <thread>
#include <utility>
namespace Void::Storage
{
struct AsyncStorageAdapter::Impl {
struct WriteJob {
std::shared_ptr<Void::Async::OperationState<std::expected<CommitReceipt, WriteFailure>>> state{};
Batch batch{};
Durability durability{Durability::Sync};
std::size_t bytes{0};
};
Impl(Engine& eng, AsyncAdapterOptions opts, Void::Async::Executor* exec)
: engine(eng),
options(std::move(opts)),
clock(options.clock ? options.clock : &Void::Time::SystemMonotonicClock::instance()),
completion_executor(exec)
{
worker = std::thread([this]() { run_loop(); });
}
~Impl()
{
close_and_join();
}
void run_loop()
{
for (;;) {
WriteJob job;
{
std::unique_lock lk{mu};
cv.wait(lk, [this]() { return !queue.empty() || closing; });
if (queue.empty() && closing) {
return;
}
job = std::move(queue.front());
queue.pop_front();
pending_bytes -= job.bytes;
}
auto& st = job.state;
// Check stop / deadline BEFORE emitting WAL bytes.
if (st->stop_requested()) {
cancelled_before_append.fetch_add(1, std::memory_order_relaxed);
std::expected<CommitReceipt, WriteFailure> wf = std::unexpected{WriteFailure{
StorageError{StorageErrorCode::interrupted,
make_storage_error(StorageErrorCode::interrupted,
"AsyncStorageAdapter: stopped before append")},
Outcome::NotCommitted}};
if (auto t = st->try_commit_value(std::move(wf)); t) {
t->dispatch();
}
st->release_backend_ref_and_dispatch();
continue;
}
if (st->is_deadline_expired(*clock)) {
cancelled_before_append.fetch_add(1, std::memory_order_relaxed);
std::expected<CommitReceipt, WriteFailure> wf = std::unexpected{WriteFailure{
StorageError{StorageErrorCode::timeout,
make_storage_error(StorageErrorCode::timeout,
"AsyncStorageAdapter: deadline expired before append")},
Outcome::NotCommitted}};
if (auto t = st->try_commit_value(std::move(wf)); t) {
t->dispatch();
}
st->release_backend_ref_and_dispatch();
continue;
}
// Perform write: once append starts, external stop/deadline NEVER revokes
// a committed receipt or skips visibility publication!
auto wr = engine.write(std::move(job.batch), job.durability);
if (wr.has_value()) {
completed_writes.fetch_add(1, std::memory_order_relaxed);
} else if (wr.error().outcome == Outcome::Unknown) {
unknown_outcomes.fetch_add(1, std::memory_order_relaxed);
} else {
rejected_writes.fetch_add(1, std::memory_order_relaxed);
}
if (auto t = st->try_commit_value(std::move(wr)); t) {
t->dispatch();
}
st->release_backend_ref_and_dispatch();
}
}
void close_and_join()
{
{
std::lock_guard lk{mu};
if (closed) return;
closing = true;
}
cv.notify_all();
if (worker.joinable()) {
worker.join();
}
std::lock_guard lk{mu};
closed = true;
}
Engine& engine;
AsyncAdapterOptions options;
const Void::Time::MonotonicClock* clock;
Void::Async::Executor* completion_executor{nullptr};
mutable std::mutex mu{};
std::condition_variable cv{};
std::deque<WriteJob> queue{};
std::size_t pending_bytes{0};
bool closing{false};
bool closed{false};
std::thread worker{};
std::atomic<std::uint64_t> completed_writes{0};
std::atomic<std::uint64_t> rejected_writes{0};
std::atomic<std::uint64_t> unknown_outcomes{0};
std::atomic<std::uint64_t> cancelled_before_append{0};
};
AsyncStorageAdapter::AsyncStorageAdapter(
Engine& engine,
AsyncAdapterOptions options,
Void::Async::Executor* completion_executor)
: m_impl(std::make_shared<Impl>(engine, std::move(options), completion_executor))
{
}
AsyncStorageAdapter::~AsyncStorageAdapter()
{
close_and_join();
}
Void::Coro::Task<std::expected<CommitReceipt, WriteFailure>>
AsyncStorageAdapter::write_async(
Batch batch,
Durability durability,
Void::Async::OperationOptions op)
{
if (op.stop.stop_requested()) {
m_impl->cancelled_before_append.fetch_add(1, std::memory_order_relaxed);
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::interrupted,
make_storage_error(StorageErrorCode::interrupted,
"AsyncStorageAdapter: stopped before admission")},
Outcome::NotCommitted}};
}
if (op.deadline.has_value() && m_impl->clock->now() >= *op.deadline) {
m_impl->cancelled_before_append.fetch_add(1, std::memory_order_relaxed);
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::timeout,
make_storage_error(StorageErrorCode::timeout,
"AsyncStorageAdapter: deadline expired before admission")},
Outcome::NotCommitted}};
}
if (auto vb = batch.validate(m_impl->engine.limits()); !vb) {
m_impl->rejected_writes.fetch_add(1, std::memory_order_relaxed);
const auto code = static_cast<StorageErrorCode>(vb.error().code().value);
co_return std::unexpected{WriteFailure{
StorageError{code, std::move(vb).error()}, Outcome::NotCommitted}};
}
std::size_t batch_bytes = 0;
for (const auto& m : batch.mutations()) {
batch_bytes += m.key.size() + m.value.size();
}
auto state = Void::Async::OperationState<
std::expected<CommitReceipt, WriteFailure>>::create(
op, m_impl->completion_executor, Void::Async::StopBehavior::notify_only);
{
std::lock_guard lk{m_impl->mu};
if (m_impl->closing || m_impl->closed) {
m_impl->rejected_writes.fetch_add(1, std::memory_order_relaxed);
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::closed,
make_storage_error(StorageErrorCode::closed,
"AsyncStorageAdapter: closing")},
Outcome::NotCommitted}};
}
if (m_impl->queue.size() >= m_impl->options.max_pending_batches ||
batch_bytes > m_impl->options.max_pending_bytes ||
m_impl->pending_bytes > m_impl->options.max_pending_bytes - batch_bytes) {
m_impl->rejected_writes.fetch_add(1, std::memory_order_relaxed);
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::overloaded,
make_storage_error(StorageErrorCode::overloaded,
"AsyncStorageAdapter: pending queue overloaded")},
Outcome::NotCommitted}};
}
m_impl->pending_bytes += batch_bytes;
state->acquire_backend_ref();
m_impl->queue.push_back(Impl::WriteJob{
state, std::move(batch), durability, batch_bytes});
}
m_impl->cv.notify_one();
auto awaited = co_await state->awaitable(m_impl->completion_executor);
if (!awaited) {
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::io_error, std::move(awaited).error()},
Outcome::Unknown}};
}
co_return std::move(*awaited);
}
Void::Coro::Task<Result<OwnedValue>>
AsyncStorageAdapter::get_async(
ByteView key,
Void::Async::OperationOptions op)
{
if (op.stop.stop_requested()) {
co_return Void::Result::fail(make_storage_error(
StorageErrorCode::interrupted, "AsyncStorageAdapter::get_async cancelled"));
}
if (op.deadline.has_value() && m_impl->clock->now() >= *op.deadline) {
co_return Void::Result::fail(make_storage_error(
StorageErrorCode::timeout, "AsyncStorageAdapter::get_async timed out"));
}
auto snap = m_impl->engine.snapshot();
if (!snap) co_return Void::Result::fail(std::move(snap).error());
co_return m_impl->engine.get(*snap, key);
}
Void::Coro::Task<Result<void>>
AsyncStorageAdapter::checkpoint_async(Void::Async::OperationOptions op)
{
if (op.stop.stop_requested()) {
co_return Void::Result::fail(make_storage_error(
StorageErrorCode::interrupted, "AsyncStorageAdapter::checkpoint_async cancelled"));
}
if (op.deadline.has_value() && m_impl->clock->now() >= *op.deadline) {
co_return Void::Result::fail(make_storage_error(
StorageErrorCode::timeout, "AsyncStorageAdapter::checkpoint_async timed out"));
}
co_return m_impl->engine.checkpoint();
}
AsyncAdapterStats AsyncStorageAdapter::stats() const noexcept
{
AsyncAdapterStats st;
if (!m_impl) return st;
std::lock_guard lk{m_impl->mu};
st.queued_writes = m_impl->queue.size();
st.pending_bytes = m_impl->pending_bytes;
st.completed_writes = m_impl->completed_writes.load(std::memory_order_relaxed);
st.rejected_writes = m_impl->rejected_writes.load(std::memory_order_relaxed);
st.unknown_outcomes = m_impl->unknown_outcomes.load(std::memory_order_relaxed);
st.cancelled_before_append =
m_impl->cancelled_before_append.load(std::memory_order_relaxed);
return st;
}
void AsyncStorageAdapter::close_and_join()
{
if (m_impl) {
m_impl->close_and_join();
}
}
} // namespace Void::Storage
+122
View File
@@ -0,0 +1,122 @@
#include <Void/Storage/Batch.hpp>
#include <set>
namespace Void::Storage
{
Batch& Batch::put(ByteView key, ByteView value)
{
Mutation m;
m.kind = MutationKind::Put;
m.key.assign(key.begin(), key.end());
m.value.assign(value.begin(), value.end());
m_mutations.push_back(std::move(m));
return *this;
}
Batch& Batch::erase(ByteView key)
{
Mutation m;
m.kind = MutationKind::Erase;
m.key.assign(key.begin(), key.end());
m_mutations.push_back(std::move(m));
return *this;
}
Batch& Batch::require_absent(ByteView key)
{
Precondition p;
p.kind = PreconditionKind::Absent;
p.key.assign(key.begin(), key.end());
m_preconditions.push_back(std::move(p));
return *this;
}
Batch& Batch::require_version(ByteView key, Sequence expected_version)
{
Precondition p;
p.kind = PreconditionKind::VersionEquals;
p.key.assign(key.begin(), key.end());
p.expected_version = expected_version;
m_preconditions.push_back(std::move(p));
return *this;
}
Batch& Batch::require_value(ByteView key, ByteView expected_value)
{
Precondition p;
p.kind = PreconditionKind::ValueEquals;
p.key.assign(key.begin(), key.end());
p.expected_value.assign(expected_value.begin(), expected_value.end());
m_preconditions.push_back(std::move(p));
return *this;
}
Result<void> Batch::validate(const Limits& limits) const
{
if (m_mutations.size() > limits.max_batch_mutations) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: mutation count exceeds max_batch_mutations"));
}
if (m_preconditions.size() > limits.max_batch_conditions) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: precondition count exceeds max_batch_conditions"));
}
std::set<ByteView, ByteLess> seen_mut_keys;
std::size_t total_op_bytes = 0;
for (const auto& m : m_mutations) {
if (m.key.size() > limits.max_key_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: mutation key exceeds max_key_bytes"));
}
if (m.value.size() > limits.max_value_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: mutation value exceeds max_value_bytes"));
}
if (m.kind == MutationKind::Erase && !m.value.empty()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: erase mutation must have empty value"));
}
if (!seen_mut_keys.insert(ByteView{m.key}).second) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: duplicate mutation key in batch"));
}
const std::size_t pair_bytes = m.key.size() + m.value.size();
if (total_op_bytes > limits.max_batch_encoded_bytes - pair_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::quota_exceeded,
"Storage::Batch: mutation payload exceeds max_batch_encoded_bytes"));
}
total_op_bytes += pair_bytes;
}
std::set<ByteView, ByteLess> seen_cond_keys;
for (const auto& p : m_preconditions) {
if (p.key.size() > limits.max_key_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: precondition key exceeds max_key_bytes"));
}
if (p.expected_value.size() > limits.max_value_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: precondition expected_value exceeds max_value_bytes"));
}
if (!seen_cond_keys.insert(ByteView{p.key}).second) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: duplicate precondition for same key"));
}
}
return {};
}
} // namespace Void::Storage
File diff suppressed because it is too large. Load diff
+681
View File
@@ -0,0 +1,681 @@
#include <Void/Storage/FilePort.hpp>
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <format>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include <utility>
namespace Void::Storage
{
namespace
{
[[nodiscard]] StorageErrorCode map_errno(int err) noexcept
{
switch (err) {
case ENOENT:
return StorageErrorCode::not_found;
case EAGAIN:
#if EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
case EBUSY:
return StorageErrorCode::busy;
case EEXIST:
return StorageErrorCode::conflict;
case ENOSYS:
case EOPNOTSUPP:
#if ENOTSUP != EOPNOTSUPP
case ENOTSUP:
#endif
return StorageErrorCode::unsupported_capability;
case ENOSPC:
case EDQUOT:
return StorageErrorCode::quota_exceeded;
case EINVAL:
return StorageErrorCode::invalid_argument;
default:
return StorageErrorCode::io_error;
}
}
[[nodiscard]] Error errno_error(std::string_view op, const std::filesystem::path& p, int err)
{
return make_storage_error(
map_errno(err),
std::format("Storage: {} '{}' failed: {}", op, p.string(), std::strerror(err)),
std::error_code{err, std::generic_category()});
}
class PosixDirLock final : public DirLockHandle
{
public:
explicit PosixDirLock(int fd) noexcept : m_fd(fd) {}
~PosixDirLock() override
{
if (m_fd >= 0) {
::flock(m_fd, LOCK_UN);
::close(m_fd);
m_fd = -1;
}
}
private:
int m_fd{-1};
};
class PosixFileHandle final : public FileHandle
{
public:
PosixFileHandle(int fd, std::filesystem::path path, std::uint64_t initial_size) noexcept
: m_fd(fd), m_path(std::move(path)), m_append_pos(initial_size)
{
}
~PosixFileHandle() override
{
if (m_fd >= 0) {
::close(m_fd);
m_fd = -1;
}
}
Result<std::size_t> pread(std::uint64_t offset, std::span<std::byte> out) override
{
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: pread on closed handle"));
}
std::size_t total = 0;
while (total < out.size()) {
const ssize_t n = ::pread(
m_fd,
out.data() + total,
out.size() - total,
static_cast<off_t>(offset + total));
if (n > 0) {
total += static_cast<std::size_t>(n);
} else if (n == 0) {
break;
} else if (errno == EINTR) {
continue;
} else {
return Void::Result::fail(errno_error("pread", m_path, errno));
}
}
return total;
}
Result<void> pread_exact(std::uint64_t offset, std::span<std::byte> out) override
{
auto r = pread(offset, out);
if (!r) return Void::Result::fail(std::move(r).error());
if (*r != out.size()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::corrupt,
std::format("Storage: short pread on '{}' at offset {} (wanted {}, got {})",
m_path.string(), offset, out.size(), *r)));
}
return {};
}
Result<void> pwrite_all(std::uint64_t offset, ByteView data) override
{
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: pwrite_all on closed handle"));
}
std::size_t total = 0;
while (total < data.size()) {
const ssize_t n = ::pwrite(
m_fd,
data.data() + total,
data.size() - total,
static_cast<off_t>(offset + total));
if (n > 0) {
total += static_cast<std::size_t>(n);
} else if (n < 0 && errno == EINTR) {
continue;
} else {
const int err = (n < 0) ? errno : EIO;
return Void::Result::fail(errno_error("pwrite", m_path, err));
}
}
return {};
}
Result<std::uint64_t> append_all(ByteView data) override
{
std::lock_guard lk{m_mu};
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: append_all on closed handle"));
}
const std::uint64_t start = m_append_pos;
auto w = pwrite_all(start, data);
if (!w) {
// Refresh actual size from fstat so partial failures keep accurate EOF.
struct stat st {};
if (::fstat(m_fd, &st) == 0 && st.st_size >= 0) {
m_append_pos = static_cast<std::uint64_t>(st.st_size);
}
return Void::Result::fail(std::move(w).error());
}
m_append_pos = start + data.size();
return start;
}
Result<void> sync() override
{
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: sync on closed handle"));
}
for (;;) {
if (::fsync(m_fd) == 0) {
return {};
}
if (errno == EINTR) {
continue;
}
return Void::Result::fail(errno_error("fsync", m_path, errno));
}
}
Result<void> truncate(std::uint64_t new_size) override
{
std::lock_guard lk{m_mu};
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: truncate on closed handle"));
}
for (;;) {
if (::ftruncate(m_fd, static_cast<off_t>(new_size)) == 0) {
m_append_pos = new_size;
return {};
}
if (errno == EINTR) {
continue;
}
return Void::Result::fail(errno_error("ftruncate", m_path, errno));
}
}
Result<std::uint64_t> size() const override
{
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: size on closed handle"));
}
struct stat st {};
if (::fstat(m_fd, &st) != 0) {
return Void::Result::fail(errno_error("fstat", m_path, errno));
}
return st.st_size >= 0 ? static_cast<std::uint64_t>(st.st_size) : 0ULL;
}
Result<void> close() override
{
std::lock_guard lk{m_mu};
if (m_fd < 0) {
return {};
}
const int rc = ::close(m_fd);
m_fd = -1;
if (rc != 0) {
return Void::Result::fail(errno_error("close", m_path, errno));
}
return {};
}
private:
mutable std::mutex m_mu{};
int m_fd{-1};
std::filesystem::path m_path{};
std::uint64_t m_append_pos{0};
};
class PosixFilePort final : public FilePort
{
public:
Result<void> ensure_dir(const std::filesystem::path& dir) override
{
std::error_code ec;
std::filesystem::create_directories(dir, ec);
if (ec) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::io_error,
std::format("Storage: create_directories '{}' failed: {}",
dir.string(), ec.message()),
ec));
}
return {};
}
Result<bool> exists(const std::filesystem::path& p) override
{
std::error_code ec;
const bool ex = std::filesystem::exists(p, ec);
if (ec) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::io_error,
std::format("Storage: exists '{}' failed: {}", p.string(), ec.message()),
ec));
}
return ex;
}
Result<std::uint64_t> file_size(const std::filesystem::path& p) override
{
struct stat st {};
if (::lstat(p.c_str(), &st) != 0) {
return Void::Result::fail(errno_error("lstat", p, errno));
}
if (!S_ISREG(st.st_mode)) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::corrupt,
std::format("Storage: '{}' is not a regular file", p.string())));
}
return st.st_size >= 0 ? static_cast<std::uint64_t>(st.st_size) : 0ULL;
}
Result<std::vector<std::string>> list_dir(const std::filesystem::path& dir) override
{
std::error_code ec;
std::vector<std::string> out;
for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) {
if (ec) break;
out.push_back(entry.path().filename().string());
}
if (ec) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::io_error,
std::format("Storage: list_dir '{}' failed: {}", dir.string(), ec.message()),
ec));
}
std::sort(out.begin(), out.end());
return out;
}
Result<std::unique_ptr<DirLockHandle>> lock_directory(
const std::filesystem::path& dir) override
{
const auto lock_path = dir / "LOCK";
const int fd = ::open(
lock_path.c_str(),
O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC,
0600);
if (fd < 0) {
return Void::Result::fail(errno_error("open lock", lock_path, errno));
}
if (::flock(fd, LOCK_EX | LOCK_NB) != 0) {
const int err = errno;
::close(fd);
return Void::Result::fail(errno_error("flock", lock_path, err));
}
return std::unique_ptr<DirLockHandle>{new PosixDirLock{fd}};
}
Result<std::unique_ptr<FileHandle>> open_file(
const std::filesystem::path& p,
FileOpenMode mode) override
{
int flags = O_NOFOLLOW | O_CLOEXEC;
switch (mode) {
case FileOpenMode::ReadOnly:
flags |= O_RDONLY;
break;
case FileOpenMode::ReadWriteExisting:
flags |= O_RDWR;
break;
case FileOpenMode::CreateNew:
flags |= O_RDWR | O_CREAT | O_EXCL;
break;
case FileOpenMode::CreateOrOpen:
flags |= O_RDWR | O_CREAT;
break;
}
const int fd = ::open(p.c_str(), flags, 0600);
if (fd < 0) {
return Void::Result::fail(errno_error("open", p, errno));
}
struct stat st {};
if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
const int err = S_ISREG(st.st_mode) ? errno : EINVAL;
::close(fd);
return Void::Result::fail(errno_error("fstat", p, err));
}
const std::uint64_t sz =
st.st_size >= 0 ? static_cast<std::uint64_t>(st.st_size) : 0ULL;
return std::unique_ptr<FileHandle>{new PosixFileHandle{fd, p, sz}};
}
Result<void> rename_atomic(
const std::filesystem::path& from,
const std::filesystem::path& to) override
{
if (::rename(from.c_str(), to.c_str()) != 0) {
return Void::Result::fail(errno_error("rename", to, errno));
}
return {};
}
Result<void> unlink_file(const std::filesystem::path& p) override
{
if (::unlink(p.c_str()) != 0) {
return Void::Result::fail(errno_error("unlink", p, errno));
}
return {};
}
Result<void> sync_dir(const std::filesystem::path& dir) override
{
const int fd = ::open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (fd < 0) {
return Void::Result::fail(errno_error("open dir", dir, errno));
}
int rc = 0;
int saved_errno = 0;
for (;;) {
rc = ::fsync(fd);
if (rc == 0) break;
if (errno == EINTR) continue;
saved_errno = errno;
break;
}
::close(fd);
if (rc != 0) {
return Void::Result::fail(errno_error("fsync dir", dir, saved_errno));
}
return {};
}
Result<void> probe_durability_capabilities(
const std::filesystem::path& dir) override
{
const auto p_tmp = dir / std::format(".void-probe-{}.tmp", ::getpid());
const auto p_dst = dir / std::format(".void-probe-{}.dst", ::getpid());
(void)::unlink(p_tmp.c_str());
(void)::unlink(p_dst.c_str());
auto f = open_file(p_tmp, FileOpenMode::CreateOrOpen);
if (!f) return Void::Result::fail(std::move(f).error());
const std::byte one{0x5Au};
if (auto w = (*f)->append_all(ByteView{&one, 1}); !w) {
(void)::unlink(p_tmp.c_str());
return Void::Result::fail(std::move(w).error());
}
if (auto s = (*f)->sync(); !s) {
(void)::unlink(p_tmp.c_str());
return s;
}
(void)(*f)->close();
if (auto r = rename_atomic(p_tmp, p_dst); !r) {
(void)::unlink(p_tmp.c_str());
(void)::unlink(p_dst.c_str());
return r;
}
auto sd = sync_dir(dir);
(void)::unlink(p_dst.c_str());
if (!sd) return sd;
return sync_dir(dir);
}
};
} // namespace
std::shared_ptr<FilePort> make_posix_file_port()
{
return std::make_shared<PosixFilePort>();
}
class FaultFileHandle final : public FileHandle
{
public:
FaultFileHandle(
FaultInjectingFilePort* owner,
std::unique_ptr<FileHandle> inner,
std::string path) noexcept
: m_owner(owner), m_inner(std::move(inner)), m_path(std::move(path))
{
}
Result<std::size_t> pread(std::uint64_t offset, std::span<std::byte> out) override
{
return m_inner->pread(offset, out);
}
Result<void> pread_exact(std::uint64_t offset, std::span<std::byte> out) override
{
return m_inner->pread_exact(offset, out);
}
Result<void> pwrite_all(std::uint64_t offset, ByteView data) override
{
const auto mf = m_owner->check_fault(FaultOp::PWrite, m_path);
if (mf.triggered) {
if (mf.partial_write_bytes.has_value() && *mf.partial_write_bytes > 0) {
const std::size_t n = std::min(*mf.partial_write_bytes, data.size());
(void)m_inner->pwrite_all(offset, data.subspan(0, n));
}
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected pwrite fault on '{}'", m_path)));
}
return m_inner->pwrite_all(offset, data);
}
Result<std::uint64_t> append_all(ByteView data) override
{
const auto mf = m_owner->check_fault(FaultOp::AppendWrite, m_path);
if (mf.triggered) {
if (mf.partial_write_bytes.has_value() && *mf.partial_write_bytes > 0) {
const std::size_t n = std::min(*mf.partial_write_bytes, data.size());
(void)m_inner->append_all(data.subspan(0, n));
}
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected append fault on '{}'", m_path)));
}
return m_inner->append_all(data);
}
Result<void> sync() override
{
m_owner->maybe_run_sync_hook();
const auto mf = m_owner->check_fault(FaultOp::SyncFile, m_path);
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected fsync fault on '{}'", m_path)));
}
return m_inner->sync();
}
Result<void> truncate(std::uint64_t new_size) override
{
const auto mf = m_owner->check_fault(FaultOp::Truncate, m_path);
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected truncate fault on '{}'", m_path)));
}
return m_inner->truncate(new_size);
}
Result<std::uint64_t> size() const override
{
return m_inner->size();
}
Result<void> close() override
{
return m_inner->close();
}
private:
FaultInjectingFilePort* m_owner;
std::unique_ptr<FileHandle> m_inner;
std::string m_path;
};
FaultInjectingFilePort::FaultInjectingFilePort(std::shared_ptr<FilePort> delegate)
: delegate_(delegate ? std::move(delegate) : make_posix_file_port())
{
}
void FaultInjectingFilePort::add_rule(FaultRule rule)
{
std::lock_guard lk{mu_};
rules_.push_back(std::move(rule));
}
void FaultInjectingFilePort::clear_rules()
{
std::lock_guard lk{mu_};
rules_.clear();
}
void FaultInjectingFilePort::set_pause_before_sync(std::function<void()> hook)
{
std::lock_guard lk{mu_};
pause_before_sync_ = std::move(hook);
}
std::uint64_t FaultInjectingFilePort::op_count(FaultOp op) const noexcept
{
std::lock_guard lk{mu_};
return op_counts_[static_cast<std::size_t>(op)];
}
FaultInjectingFilePort::MatchedFault FaultInjectingFilePort::check_fault(
FaultOp op,
const std::string& path)
{
std::lock_guard lk{mu_};
++op_counts_[static_cast<std::size_t>(op)];
for (auto& r : rules_) {
if (r.consumed || r.op != op) continue;
if (!r.path_contains.empty() && path.find(r.path_contains) == std::string::npos) {
continue;
}
++r.match_count;
if (r.hit_index == 0 || r.match_count == r.hit_index) {
if (r.hit_index != 0) {
r.consumed = true;
}
return MatchedFault{r.error_code, r.partial_write_bytes, true};
}
}
return {};
}
void FaultInjectingFilePort::maybe_run_sync_hook()
{
std::function<void()> cb;
{
std::lock_guard lk{mu_};
cb = pause_before_sync_;
}
if (cb) {
cb();
}
}
Result<void> FaultInjectingFilePort::ensure_dir(const std::filesystem::path& dir)
{
return delegate_->ensure_dir(dir);
}
Result<bool> FaultInjectingFilePort::exists(const std::filesystem::path& p)
{
return delegate_->exists(p);
}
Result<std::uint64_t> FaultInjectingFilePort::file_size(const std::filesystem::path& p)
{
return delegate_->file_size(p);
}
Result<std::vector<std::string>> FaultInjectingFilePort::list_dir(const std::filesystem::path& dir)
{
return delegate_->list_dir(dir);
}
Result<std::unique_ptr<DirLockHandle>> FaultInjectingFilePort::lock_directory(
const std::filesystem::path& dir)
{
const auto mf = check_fault(FaultOp::LockDir, dir.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code, "Storage: injected directory lock fault"));
}
return delegate_->lock_directory(dir);
}
Result<std::unique_ptr<FileHandle>> FaultInjectingFilePort::open_file(
const std::filesystem::path& p,
FileOpenMode mode)
{
const auto mf = check_fault(FaultOp::OpenFile, p.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected open_file fault on '{}'", p.string())));
}
auto h = delegate_->open_file(p, mode);
if (!h) return Void::Result::fail(std::move(h).error());
return std::unique_ptr<FileHandle>{
new FaultFileHandle{this, std::move(*h), p.string()}};
}
Result<void> FaultInjectingFilePort::rename_atomic(
const std::filesystem::path& from,
const std::filesystem::path& to)
{
const auto mf = check_fault(FaultOp::Rename, to.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected rename fault to '{}'", to.string())));
}
return delegate_->rename_atomic(from, to);
}
Result<void> FaultInjectingFilePort::unlink_file(const std::filesystem::path& p)
{
const auto mf = check_fault(FaultOp::Unlink, p.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected unlink fault on '{}'", p.string())));
}
return delegate_->unlink_file(p);
}
Result<void> FaultInjectingFilePort::sync_dir(const std::filesystem::path& dir)
{
const auto mf = check_fault(FaultOp::SyncDir, dir.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected sync_dir fault on '{}'", dir.string())));
}
return delegate_->sync_dir(dir);
}
Result<void> FaultInjectingFilePort::probe_durability_capabilities(
const std::filesystem::path& dir)
{
const auto mf = check_fault(FaultOp::ProbeDurability, dir.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code, "Storage: injected probe durability fault"));
}
return delegate_->probe_durability_capabilities(dir);
}
} // namespace Void::Storage
File diff suppressed because it is too large. Load diff
+98
View File
@@ -0,0 +1,98 @@
#pragma once
#include <Void/Storage/FilePort.hpp>
#include <Void/Storage/Format.hpp>
#include <filesystem>
#include <memory>
#include <mutex>
#include <vector>
namespace Void::Storage::detail
{
class TableReader final
{
public:
[[nodiscard]] static Result<std::shared_ptr<TableReader>> open(
std::shared_ptr<FilePort> port,
std::filesystem::path path,
Void::Uuid::Uuid expected_uuid,
const TableMeta& meta,
const Limits& limits);
[[nodiscard]] const TableMeta& meta() const noexcept { return m_meta; }
[[nodiscard]] const std::filesystem::path& path() const noexcept { return m_path; }
[[nodiscard]] const std::vector<TableBlockIndexEntry>& index() const noexcept
{
return m_index;
}
/// Lookup highest version <= snap_seq for exact `key`.
/// Returns std::nullopt if `key` is absent at <= snap_seq in this table;
/// returns TableEntryRecord{key, seq, erased, value} if present (including tombstone).
[[nodiscard]] Result<std::optional<TableEntryRecord>> lookup(
ByteView key,
Sequence snap_seq) const;
/// Read and decode block `block_idx` while verifying its CRC32C.
[[nodiscard]] Result<std::vector<TableEntryRecord>> read_block(
std::size_t block_idx) const;
/// Verify every block's CRC32C, key ordering, AND full-file CRC32C.
[[nodiscard]] Result<std::uint64_t> verify_all_blocks_and_file_crc() const;
private:
TableReader() = default;
std::shared_ptr<FilePort> m_port{};
std::filesystem::path m_path{};
TableMeta m_meta{};
TableHeader m_header{};
TableFooter m_footer{};
Limits m_limits{};
std::vector<TableBlockIndexEntry> m_index{};
mutable std::mutex m_handle_mu{};
mutable std::unique_ptr<FileHandle> m_cached_handle{};
};
[[nodiscard]] Result<TableMeta> write_sorted_table(
FilePort& port,
const std::filesystem::path& tmp_path,
const std::filesystem::path& final_path,
Void::Uuid::Uuid db_uuid,
std::uint64_t table_id,
std::uint32_t level,
const std::vector<TableEntryRecord>& sorted_entries,
const Limits& limits);
/// Validate and replay a WAL segment, filling `recovered_batches` with valid committed batches.
struct WalRecoveredBatch {
Sequence sequence{0};
std::vector<TableEntryRecord> entries{};
};
struct WalSegmentScanResult {
WalSegmentHeader header{};
std::vector<WalRecoveredBatch> batches{};
std::uint64_t file_size{0};
std::optional<std::uint64_t> truncate_offset{};
};
[[nodiscard]] Result<WalSegmentScanResult> scan_wal_segment(
FilePort& port,
const std::filesystem::path& path,
Void::Uuid::Uuid expected_uuid,
std::uint64_t expected_seg_id,
std::optional<std::uint64_t> expected_prev_seg_id,
bool is_final_active_segment,
const Limits& limits,
bool allow_uncommitted_tail = true);
/// Salvage scan: recovers as many valid complete committed batches as possible before stopping.
[[nodiscard]] Result<WalSegmentScanResult> salvage_wal_segment(
FilePort& port,
const std::filesystem::path& path,
Void::Uuid::Uuid expected_uuid,
const Limits& limits);
} // namespace Void::Storage::detail
+327
View File
@@ -0,0 +1,327 @@
#include <Void/Core/Uuid.hpp>
#include <Void/Storage/Engine.hpp>
#include <Void/Storage/Format.hpp>
#include <Void/Storage/Tools.hpp>
#include "TableInternal.hpp"
#include <algorithm>
#include <format>
#include <limits>
#include <map>
#include <vector>
namespace Void::Storage
{
namespace
{
[[nodiscard]] Result<OwnedBytes> read_entire_file(
FilePort& port,
const std::filesystem::path& path,
std::size_t max_bytes)
{
auto sz_r = port.file_size(path);
if (!sz_r) return Void::Result::fail(std::move(sz_r).error());
if (*sz_r > max_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::corrupt,
std::format("Storage tool: '{}' size {} exceeds bound {}",
path.string(), *sz_r, max_bytes)));
}
OwnedBytes out(*sz_r);
auto f = port.open_file(path, FileOpenMode::ReadOnly);
if (!f) return Void::Result::fail(std::move(f).error());
if (*sz_r > 0) {
if (auto r = (*f)->pread_exact(0, out); !r) {
return Void::Result::fail(std::move(r).error());
}
}
return out;
}
} // namespace
Result<VerifyReport> verify_directory(
const std::filesystem::path& directory,
const Limits& limits,
std::shared_ptr<FilePort> port)
{
if (directory.empty()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument, "verify_directory: empty directory"));
}
if (auto vl = validate_limits(limits); !vl) {
return Void::Result::fail(std::move(vl).error());
}
if (!port) port = make_posix_file_port();
auto cur_bytes = read_entire_file(*port, directory / "CURRENT", 512);
if (!cur_bytes) return Void::Result::fail(std::move(cur_bytes).error());
auto cur = decode_current(*cur_bytes);
if (!cur) return Void::Result::fail(std::move(cur).error());
auto man_bytes = read_entire_file(
*port, directory / cur->manifest_filename, limits.max_manifest_bytes);
if (!man_bytes) return Void::Result::fail(std::move(man_bytes).error());
auto man = decode_manifest(
*man_bytes, limits.max_manifest_bytes, limits.max_manifest_tables, limits.max_key_bytes);
if (!man) return Void::Result::fail(std::move(man).error());
if (man->database_uuid != cur->database_uuid || man->generation != cur->generation) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::corrupt, "verify_directory: manifest mismatches CURRENT"));
}
VerifyReport report;
report.manifest_generation = man->generation;
report.checkpoint_sequence = man->checkpoint_sequence;
for (const auto& tm : man->tables) {
auto tr = detail::TableReader::open(
port,
directory / make_table_filename(tm.table_id),
man->database_uuid,
tm,
limits);
if (!tr) return Void::Result::fail(std::move(tr).error());
auto blks = (*tr)->verify_all_blocks_and_file_crc();
if (!blks) return Void::Result::fail(std::move(blks).error());
++report.tables_verified;
report.blocks_verified += *blks;
}
for (std::size_t i = 0; i < man->wal_segments.size(); ++i) {
const auto seg_id = man->wal_segments[i];
const bool is_final = (i + 1 == man->wal_segments.size());
const std::optional<std::uint64_t> exp_prev =
(i > 0) ? std::optional<std::uint64_t>{man->wal_segments[i - 1]}
: (seg_id == 1 ? std::optional<std::uint64_t>{0} : std::nullopt);
auto scan = detail::scan_wal_segment(
*port,
directory / make_wal_filename(seg_id),
man->database_uuid,
seg_id,
exp_prev,
is_final,
limits,
true);
if (!scan) return Void::Result::fail(std::move(scan).error());
++report.wal_segments_verified;
report.wal_batches_verified += scan->batches.size();
}
return report;
}
Result<void> restore_backup(
const std::filesystem::path& backup_dir,
const std::filesystem::path& destination,
const Limits& limits,
std::shared_ptr<FilePort> port)
{
if (backup_dir.empty() || destination.empty()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument, "restore_backup: empty path"));
}
if (!port) port = make_posix_file_port();
std::error_code ec;
if (std::filesystem::exists(destination, ec) &&
std::filesystem::equivalent(backup_dir, destination, ec)) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"restore_backup: source and destination cannot be identical"));
}
auto vr = verify_directory(backup_dir, limits, port);
if (!vr) return Void::Result::fail(std::move(vr).error());
if (auto ed = port->ensure_dir(destination); !ed) return ed;
auto lock = port->lock_directory(destination);
if (!lock) return Void::Result::fail(std::move(lock).error());
auto cur_bytes = read_entire_file(*port, backup_dir / "CURRENT", 512);
if (!cur_bytes) return Void::Result::fail(std::move(cur_bytes).error());
auto cur = decode_current(*cur_bytes);
if (!cur) return Void::Result::fail(std::move(cur).error());
auto man_bytes = read_entire_file(
*port, backup_dir / cur->manifest_filename, limits.max_manifest_bytes);
if (!man_bytes) return Void::Result::fail(std::move(man_bytes).error());
auto man = decode_manifest(
*man_bytes, limits.max_manifest_bytes, limits.max_manifest_tables, limits.max_key_bytes);
if (!man) return Void::Result::fail(std::move(man).error());
auto copy_file = [&](const std::string& name) -> Result<void> {
const auto src = backup_dir / name;
const auto dst = destination / name;
const auto dst_tmp = destination / (name + ".tmp");
auto sz = port->file_size(src);
if (!sz) return Void::Result::fail(std::move(sz).error());
OwnedBytes buf(*sz);
auto sf = port->open_file(src, FileOpenMode::ReadOnly);
if (!sf) return Void::Result::fail(std::move(sf).error());
if (*sz > 0) {
if (auto r = (*sf)->pread_exact(0, buf); !r) return r;
}
(void)port->unlink_file(dst_tmp);
auto df = port->open_file(dst_tmp, FileOpenMode::CreateNew);
if (!df) return Void::Result::fail(std::move(df).error());
if (!buf.empty()) {
if (auto w = (*df)->append_all(buf); !w) return Void::Result::fail(std::move(w).error());
}
if (auto s = (*df)->sync(); !s) return s;
if (auto c = (*df)->close(); !c) return c;
return port->rename_atomic(dst_tmp, dst);
};
for (const auto& tm : man->tables) {
if (auto r = copy_file(make_table_filename(tm.table_id)); !r) return r;
}
for (const auto seg : man->wal_segments) {
if (auto r = copy_file(make_wal_filename(seg)); !r) return r;
}
if (auto r = copy_file(cur->manifest_filename); !r) return r;
if (auto r = copy_file("CURRENT"); !r) return r;
return port->sync_dir(destination);
}
Result<SalvageReport> salvage_directory(
const std::filesystem::path& source_dir,
const std::filesystem::path& destination_dir,
const Limits& limits,
std::shared_ptr<FilePort> port)
{
if (source_dir.empty() || destination_dir.empty()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument, "salvage_directory: empty path"));
}
if (auto vl = validate_limits(limits); !vl) {
return Void::Result::fail(std::move(vl).error());
}
if (!port) port = make_posix_file_port();
std::error_code ec;
if (std::filesystem::exists(destination_dir, ec) &&
std::filesystem::equivalent(source_dir, destination_dir, ec)) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"salvage_directory: offline salvage must write into a distinct destination directory"));
}
// Collect latest committed/recoverable key states without mutating source_dir!
struct Val {
Sequence seq{0};
bool erased{false};
OwnedBytes bytes{};
};
std::map<OwnedBytes, Val, ByteLess> kv;
SalvageReport rep;
std::optional<Void::Uuid::Uuid> db_uuid;
std::vector<std::string> files;
if (auto fl = port->list_dir(source_dir); fl) {
files = std::move(*fl);
} else {
return Void::Result::fail(std::move(fl).error());
}
// Try CURRENT -> Manifest if intact, so valid checkpoint tables are recovered too.
if (auto ce = port->exists(source_dir / "CURRENT"); ce && *ce) {
auto cb = read_entire_file(*port, source_dir / "CURRENT", 512);
if (cb) {
if (auto cp = decode_current(*cb); cp) {
db_uuid = cp->database_uuid;
if (auto mb = read_entire_file(*port, source_dir / cp->manifest_filename, limits.max_manifest_bytes); mb) {
if (auto md = decode_manifest(*mb, limits.max_manifest_bytes, limits.max_manifest_tables, limits.max_key_bytes); md) {
for (const auto& tm : md->tables) {
auto tr = detail::TableReader::open(
port, source_dir / make_table_filename(tm.table_id),
md->database_uuid, tm, limits);
if (!tr) continue;
for (std::size_t bi = 0; bi < (*tr)->index().size(); ++bi) {
auto blk = (*tr)->read_block(bi);
if (!blk) continue;
for (const auto& e : *blk) {
auto it = kv.find(e.key);
if (it == kv.end() || e.sequence > it->second.seq) {
kv[e.key] = Val{e.sequence, e.erased, e.value};
}
rep.highest_recovered_sequence =
std::max(rep.highest_recovered_sequence, e.sequence);
}
}
}
}
}
}
}
}
// Scan every WAL-*.vwal in lexicographic name order stopping at first damaged record.
for (const auto& fname : files) {
if (!fname.starts_with("WAL-") || !fname.ends_with(".vwal")) continue;
const auto wpath = source_dir / fname;
// Peek segment header for UUID if CURRENT/Manifest wasn't usable.
if (!db_uuid.has_value()) {
OwnedBytes hdr_b(kWalSegmentHeaderSize);
auto wf = port->open_file(wpath, FileOpenMode::ReadOnly);
if (wf && (*wf)->pread_exact(0, hdr_b).has_value()) {
if (auto dec = decode_wal_segment_header(hdr_b); dec) {
db_uuid = dec->database_uuid;
}
}
}
if (!db_uuid.has_value()) continue;
auto scan = detail::salvage_wal_segment(*port, wpath, *db_uuid, limits);
if (!scan) continue;
if (scan->truncate_offset.has_value()) {
rep.truncated_or_skipped_bytes += (scan->file_size - *scan->truncate_offset);
}
for (const auto& b : scan->batches) {
++rep.recovered_batches;
rep.highest_recovered_sequence =
std::max(rep.highest_recovered_sequence, b.sequence);
for (const auto& e : b.entries) {
auto it = kv.find(e.key);
if (it == kv.end() || e.sequence > it->second.seq) {
kv[e.key] = Val{e.sequence, e.erased, e.value};
}
}
}
}
// Materialize salvaged data into fresh destination directory preserving versions!
OpenOptions out_opts;
out_opts.directory = destination_dir;
out_opts.limits = limits;
out_opts.file_port = port;
out_opts.initial_sequence = rep.highest_recovered_sequence;
auto dest_eng = Engine::open(std::move(out_opts));
if (!dest_eng) return Void::Result::fail(std::move(dest_eng).error());
Batch batch;
std::size_t approx = 0;
for (const auto& [k, v] : kv) {
if (v.erased) {
++rep.tombstones_preserved;
continue;
}
++rep.keys_recovered;
if (batch.mutations().size() + 1 > limits.max_batch_mutations ||
approx + k.size() + v.bytes.size() + 128 > limits.max_batch_encoded_bytes) {
auto wr = dest_eng->write(std::move(batch), Durability::Sync);
if (!wr.has_value()) return Void::Result::fail(wr.error().cause.error);
batch = Batch{};
approx = 0;
}
batch.put(k, v.bytes);
approx += k.size() + v.bytes.size() + 64;
}
if (!batch.empty()) {
auto wr = dest_eng->write(std::move(batch), Durability::Sync);
if (!wr.has_value()) return Void::Result::fail(wr.error().cause.error);
}
if (auto cl = dest_eng->close(); !cl) return Void::Result::fail(std::move(cl).error());
return rep;
}
} // namespace Void::Storage
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Storage
INTERNAL_DEPS Core Functional Time Memory Binary IO Async
)