feat(storage): implement original V1 durable Storage engine, tools, and async adapter
This commit is contained in:
1 parent
427cc9a843
commit
fdf0da5ca8
21 files changed
+6966
No files matched your search
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
#include <Void/Storage/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
|
||||
namespace Void::Storage
|
||||
{
|
||||
struct AsyncAdapterOptions {
|
||||
std::size_t max_pending_batches{64};
|
||||
std::size_t max_pending_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
const Void::Time::MonotonicClock* clock{nullptr};
|
||||
};
|
||||
|
||||
struct AsyncAdapterStats {
|
||||
std::size_t queued_writes{0};
|
||||
std::size_t pending_bytes{0};
|
||||
std::uint64_t completed_writes{0};
|
||||
std::uint64_t rejected_writes{0};
|
||||
std::uint64_t unknown_outcomes{0};
|
||||
std::uint64_t cancelled_before_append{0};
|
||||
};
|
||||
|
||||
/// Bounded blocking async adapter over Storage::Engine following C-03
|
||||
/// domain-result classification (never steals a persisted commit outcome with
|
||||
/// a synthetic timeout/cancel once WAL append begins; single delivery only).
|
||||
class AsyncStorageAdapter
|
||||
{
|
||||
public:
|
||||
explicit AsyncStorageAdapter(
|
||||
Engine& engine,
|
||||
AsyncAdapterOptions options = {},
|
||||
Void::Async::Executor* completion_executor = nullptr);
|
||||
~AsyncStorageAdapter();
|
||||
|
||||
AsyncStorageAdapter(const AsyncStorageAdapter&) = delete;
|
||||
AsyncStorageAdapter& operator=(const AsyncStorageAdapter&) = delete;
|
||||
AsyncStorageAdapter(AsyncStorageAdapter&&) = delete;
|
||||
AsyncStorageAdapter& operator=(AsyncStorageAdapter&&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<std::expected<CommitReceipt, WriteFailure>>
|
||||
write_async(
|
||||
Batch batch,
|
||||
Durability durability,
|
||||
Void::Async::OperationOptions op = {});
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Result<OwnedValue>>
|
||||
get_async(
|
||||
ByteView key,
|
||||
Void::Async::OperationOptions op = {});
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Result<void>>
|
||||
checkpoint_async(Void::Async::OperationOptions op = {});
|
||||
|
||||
[[nodiscard]] AsyncAdapterStats stats() const noexcept;
|
||||
void close_and_join();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::shared_ptr<Impl> m_impl{};
|
||||
};
|
||||
|
||||
} // namespace Void::Storage
|
||||
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Storage/Types.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Storage
|
||||
{
|
||||
enum class MutationKind : std::uint8_t {
|
||||
Put = 1,
|
||||
Erase = 2
|
||||
};
|
||||
|
||||
enum class PreconditionKind : std::uint8_t {
|
||||
Absent = 1,
|
||||
VersionEquals = 2,
|
||||
ValueEquals = 3
|
||||
};
|
||||
|
||||
struct Mutation {
|
||||
MutationKind kind{MutationKind::Put};
|
||||
OwnedBytes key{};
|
||||
OwnedBytes value{};
|
||||
};
|
||||
|
||||
struct Precondition {
|
||||
PreconditionKind kind{PreconditionKind::Absent};
|
||||
OwnedBytes key{};
|
||||
Sequence expected_version{0};
|
||||
OwnedBytes expected_value{};
|
||||
};
|
||||
|
||||
/// Atomic conditional write batch owning all key and value bytes.
|
||||
/// Rejects duplicate mutation keys and duplicate preconditions per key.
|
||||
class Batch
|
||||
{
|
||||
public:
|
||||
Batch() = default;
|
||||
|
||||
Batch& put(ByteView key, ByteView value);
|
||||
Batch& put(std::string_view key, std::string_view value)
|
||||
{
|
||||
return put(to_byte_view(key), to_byte_view(value));
|
||||
}
|
||||
|
||||
Batch& erase(ByteView key);
|
||||
Batch& erase(std::string_view key)
|
||||
{
|
||||
return erase(to_byte_view(key));
|
||||
}
|
||||
|
||||
Batch& require_absent(ByteView key);
|
||||
Batch& require_absent(std::string_view key)
|
||||
{
|
||||
return require_absent(to_byte_view(key));
|
||||
}
|
||||
|
||||
Batch& require_version(ByteView key, Sequence expected_version);
|
||||
Batch& require_version(std::string_view key, Sequence expected_version)
|
||||
{
|
||||
return require_version(to_byte_view(key), expected_version);
|
||||
}
|
||||
|
||||
Batch& require_value(ByteView key, ByteView expected_value);
|
||||
Batch& require_value(std::string_view key, std::string_view expected_value)
|
||||
{
|
||||
return require_value(to_byte_view(key), to_byte_view(expected_value));
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::vector<Mutation>& mutations() const noexcept
|
||||
{
|
||||
return m_mutations;
|
||||
}
|
||||
[[nodiscard]] const std::vector<Precondition>& preconditions() const noexcept
|
||||
{
|
||||
return m_preconditions;
|
||||
}
|
||||
[[nodiscard]] bool empty() const noexcept
|
||||
{
|
||||
return m_mutations.empty() && m_preconditions.empty();
|
||||
}
|
||||
|
||||
[[nodiscard]] Result<void> validate(const Limits& limits) const;
|
||||
|
||||
private:
|
||||
std::vector<Mutation> m_mutations{};
|
||||
std::vector<Precondition> m_preconditions{};
|
||||
};
|
||||
|
||||
} // namespace Void::Storage
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Storage
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
[[nodiscard]] constexpr std::array<std::uint32_t, 256>
|
||||
make_crc32c_table() noexcept
|
||||
{
|
||||
// Reflected Castagnoli polynomial (normal 0x1EDC6F41, reflected 0x82F63B78).
|
||||
constexpr std::uint32_t kPoly = 0x82F63B78u;
|
||||
std::array<std::uint32_t, 256> table{};
|
||||
for (std::uint32_t i = 0; i < 256; ++i) {
|
||||
std::uint32_t c = i;
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
c = (c & 1u) ? (kPoly ^ (c >> 1)) : (c >> 1);
|
||||
}
|
||||
table[i] = c;
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
inline constexpr auto kCrc32cTable = make_crc32c_table();
|
||||
} // namespace detail
|
||||
|
||||
inline constexpr std::uint32_t kCrc32cInitial = 0xFFFFFFFFu;
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t crc32c_init() noexcept
|
||||
{
|
||||
return kCrc32cInitial;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t crc32c_update(
|
||||
std::uint32_t state,
|
||||
std::span<const std::byte> data) noexcept
|
||||
{
|
||||
for (const auto b : data) {
|
||||
const auto idx =
|
||||
(state ^ static_cast<std::uint32_t>(std::to_integer<unsigned char>(b))) &
|
||||
0xFFu;
|
||||
state = detail::kCrc32cTable[idx] ^ (state >> 8);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t crc32c_update(
|
||||
std::uint32_t state,
|
||||
std::string_view text) noexcept
|
||||
{
|
||||
for (const unsigned char c : text) {
|
||||
state = detail::kCrc32cTable[(state ^ c) & 0xFFu] ^ (state >> 8);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t crc32c_finalize(std::uint32_t state) noexcept
|
||||
{
|
||||
return state ^ 0xFFFFFFFFu;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t crc32c(
|
||||
std::span<const std::byte> data) noexcept
|
||||
{
|
||||
return crc32c_finalize(crc32c_update(crc32c_init(), data));
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t crc32c(std::string_view text) noexcept
|
||||
{
|
||||
return crc32c_finalize(crc32c_update(crc32c_init(), text));
|
||||
}
|
||||
|
||||
static_assert(crc32c(std::string_view{"123456789"}) == 0xE3069283u,
|
||||
"CRC32C golden vector mismatch");
|
||||
static_assert(crc32c(std::string_view{""}) == 0u,
|
||||
"CRC32C empty vector mismatch");
|
||||
|
||||
} // namespace Void::Storage
|
||||
@@ -0,0 +1,147 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Storage/Batch.hpp>
|
||||
#include <Void/Storage/FilePort.hpp>
|
||||
#include <Void/Storage/Types.hpp>
|
||||
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
|
||||
namespace Void::Storage
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
class EngineControl;
|
||||
struct SourceView;
|
||||
} // namespace detail
|
||||
|
||||
class Engine;
|
||||
class Cursor;
|
||||
|
||||
/// Move-only reader pin of a committed sequence and immutable source set.
|
||||
class Snapshot
|
||||
{
|
||||
public:
|
||||
Snapshot() noexcept = default;
|
||||
~Snapshot();
|
||||
Snapshot(Snapshot&&) noexcept;
|
||||
Snapshot& operator=(Snapshot&&) noexcept;
|
||||
Snapshot(const Snapshot&) = delete;
|
||||
Snapshot& operator=(const Snapshot&) = delete;
|
||||
|
||||
[[nodiscard]] Sequence sequence() const noexcept { return m_sequence; }
|
||||
[[nodiscard]] bool valid() const noexcept { return static_cast<bool>(m_control); }
|
||||
void reset() noexcept;
|
||||
|
||||
private:
|
||||
friend class Engine;
|
||||
friend class Cursor;
|
||||
friend class detail::EngineControl;
|
||||
|
||||
Snapshot(std::shared_ptr<detail::EngineControl> control,
|
||||
std::shared_ptr<const detail::SourceView> view,
|
||||
Sequence seq,
|
||||
std::uint64_t pin_id) noexcept;
|
||||
|
||||
std::shared_ptr<detail::EngineControl> m_control{};
|
||||
std::shared_ptr<const detail::SourceView> m_view{};
|
||||
Sequence m_sequence{0};
|
||||
std::uint64_t m_pin_id{0};
|
||||
};
|
||||
|
||||
/// Move-only ordered byte-lexicographic iterator retaining its Snapshot.
|
||||
class Cursor
|
||||
{
|
||||
public:
|
||||
Cursor() noexcept = default;
|
||||
~Cursor();
|
||||
Cursor(Cursor&&) noexcept;
|
||||
Cursor& operator=(Cursor&&) noexcept;
|
||||
Cursor(const Cursor&) = delete;
|
||||
Cursor& operator=(const Cursor&) = delete;
|
||||
|
||||
[[nodiscard]] Result<ScanPage> next_page();
|
||||
[[nodiscard]] bool valid() const noexcept { return !m_closed && m_snapshot.valid(); }
|
||||
void close() noexcept;
|
||||
|
||||
private:
|
||||
friend class Engine;
|
||||
|
||||
Cursor(Snapshot snap,
|
||||
ScanBounds bounds,
|
||||
std::size_t page_bytes,
|
||||
std::size_t page_rows,
|
||||
std::uint64_t cursor_id) noexcept;
|
||||
|
||||
Snapshot m_snapshot{};
|
||||
ScanBounds m_bounds{};
|
||||
std::size_t m_page_bytes{0};
|
||||
std::size_t m_page_rows{0};
|
||||
std::uint64_t m_cursor_id{0};
|
||||
std::optional<OwnedBytes> m_resume_after{};
|
||||
bool m_finished{false};
|
||||
bool m_closed{false};
|
||||
};
|
||||
|
||||
class Engine
|
||||
{
|
||||
public:
|
||||
Engine() noexcept = default;
|
||||
~Engine();
|
||||
Engine(Engine&&) noexcept;
|
||||
Engine& operator=(Engine&&) noexcept;
|
||||
Engine(const Engine&) = delete;
|
||||
Engine& operator=(const Engine&) = delete;
|
||||
|
||||
[[nodiscard]] static Result<Engine> open(OpenOptions options);
|
||||
|
||||
[[nodiscard]] Result<Snapshot> snapshot();
|
||||
|
||||
[[nodiscard]] std::expected<CommitReceipt, WriteFailure> write(
|
||||
Batch batch,
|
||||
Durability durability);
|
||||
|
||||
[[nodiscard]] std::expected<CommitReceipt, WriteFailure> write(Batch batch)
|
||||
{
|
||||
return write(std::move(batch), default_durability());
|
||||
}
|
||||
|
||||
[[nodiscard]] Result<OwnedValue> get(
|
||||
const Snapshot& snap,
|
||||
ByteView key) const;
|
||||
|
||||
[[nodiscard]] Result<OwnedValue> get(
|
||||
const Snapshot& snap,
|
||||
std::string_view key) const
|
||||
{
|
||||
return get(snap, to_byte_view(key));
|
||||
}
|
||||
|
||||
[[nodiscard]] Result<Cursor> scan(
|
||||
Snapshot snap,
|
||||
ScanBounds bounds = ScanBounds::all()) const;
|
||||
|
||||
[[nodiscard]] Result<void> checkpoint();
|
||||
[[nodiscard]] Result<void> compact();
|
||||
[[nodiscard]] Result<void> sync();
|
||||
[[nodiscard]] Result<void> close();
|
||||
|
||||
/// Copy consistent manifest, tables, and necessary WAL prefix into
|
||||
/// `destination` while keeping this engine open and pinning sources.
|
||||
[[nodiscard]] Result<void> export_backup(
|
||||
const std::filesystem::path& destination);
|
||||
|
||||
[[nodiscard]] EngineState state() const noexcept;
|
||||
[[nodiscard]] EngineStats stats() const noexcept;
|
||||
[[nodiscard]] Durability default_durability() const noexcept;
|
||||
[[nodiscard]] const Limits& limits() const noexcept;
|
||||
|
||||
private:
|
||||
friend class AsyncStorageAdapter;
|
||||
explicit Engine(std::shared_ptr<detail::EngineControl> control) noexcept;
|
||||
|
||||
std::shared_ptr<detail::EngineControl> m_control{};
|
||||
};
|
||||
|
||||
} // namespace Void::Storage
|
||||
@@ -0,0 +1,145 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Storage/Types.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Storage
|
||||
{
|
||||
enum class FileOpenMode : std::uint8_t {
|
||||
ReadOnly = 0,
|
||||
ReadWriteExisting = 1,
|
||||
CreateNew = 2,
|
||||
CreateOrOpen = 3
|
||||
};
|
||||
|
||||
class FileHandle
|
||||
{
|
||||
public:
|
||||
virtual ~FileHandle() = default;
|
||||
|
||||
[[nodiscard]] virtual Result<std::size_t> pread(
|
||||
std::uint64_t offset, std::span<std::byte> out) = 0;
|
||||
[[nodiscard]] virtual Result<void> pread_exact(
|
||||
std::uint64_t offset, std::span<std::byte> out) = 0;
|
||||
[[nodiscard]] virtual Result<void> pwrite_all(
|
||||
std::uint64_t offset, ByteView data) = 0;
|
||||
[[nodiscard]] virtual Result<std::uint64_t> append_all(ByteView data) = 0;
|
||||
[[nodiscard]] virtual Result<void> sync() = 0;
|
||||
[[nodiscard]] virtual Result<void> truncate(std::uint64_t new_size) = 0;
|
||||
[[nodiscard]] virtual Result<std::uint64_t> size() const = 0;
|
||||
[[nodiscard]] virtual Result<void> close() = 0;
|
||||
};
|
||||
|
||||
class DirLockHandle
|
||||
{
|
||||
public:
|
||||
virtual ~DirLockHandle() = default;
|
||||
};
|
||||
|
||||
class FilePort
|
||||
{
|
||||
public:
|
||||
virtual ~FilePort() = default;
|
||||
|
||||
[[nodiscard]] virtual Result<void> ensure_dir(
|
||||
const std::filesystem::path& dir) = 0;
|
||||
[[nodiscard]] virtual Result<bool> exists(
|
||||
const std::filesystem::path& p) = 0;
|
||||
[[nodiscard]] virtual Result<std::uint64_t> file_size(
|
||||
const std::filesystem::path& p) = 0;
|
||||
[[nodiscard]] virtual Result<std::vector<std::string>> list_dir(
|
||||
const std::filesystem::path& dir) = 0;
|
||||
[[nodiscard]] virtual Result<std::unique_ptr<DirLockHandle>>
|
||||
lock_directory(const std::filesystem::path& dir) = 0;
|
||||
[[nodiscard]] virtual Result<std::unique_ptr<FileHandle>> open_file(
|
||||
const std::filesystem::path& p, FileOpenMode mode) = 0;
|
||||
[[nodiscard]] virtual Result<void> rename_atomic(
|
||||
const std::filesystem::path& from,
|
||||
const std::filesystem::path& to) = 0;
|
||||
[[nodiscard]] virtual Result<void> unlink_file(
|
||||
const std::filesystem::path& p) = 0;
|
||||
[[nodiscard]] virtual Result<void> sync_dir(
|
||||
const std::filesystem::path& dir) = 0;
|
||||
[[nodiscard]] virtual Result<void> probe_durability_capabilities(
|
||||
const std::filesystem::path& dir) = 0;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::shared_ptr<FilePort> make_posix_file_port();
|
||||
|
||||
enum class FaultOp : std::uint8_t {
|
||||
LockDir = 0,
|
||||
ProbeDurability = 1,
|
||||
OpenFile = 2,
|
||||
AppendWrite = 3,
|
||||
PWrite = 4,
|
||||
SyncFile = 5,
|
||||
SyncDir = 6,
|
||||
Rename = 7,
|
||||
Unlink = 8,
|
||||
Truncate = 9
|
||||
};
|
||||
|
||||
struct FaultRule {
|
||||
FaultOp op{FaultOp::SyncFile};
|
||||
std::string path_contains{};
|
||||
/// 1-based hit index among matching operations (0 = fail every match).
|
||||
std::uint64_t hit_index{1};
|
||||
StorageErrorCode error_code{StorageErrorCode::io_error};
|
||||
/// For write ops: write at most this many bytes before failing (SIZE_MAX = skip write).
|
||||
std::optional<std::size_t> partial_write_bytes{};
|
||||
bool consumed{false};
|
||||
std::uint64_t match_count{0};
|
||||
};
|
||||
|
||||
/// Deterministic filesystem fault-injection proxy wrapping a FilePort
|
||||
/// (default: PosixFilePort) for crash, partial-write, and sync-failure tests.
|
||||
class FaultInjectingFilePort final : public FilePort
|
||||
{
|
||||
public:
|
||||
explicit FaultInjectingFilePort(
|
||||
std::shared_ptr<FilePort> delegate = make_posix_file_port());
|
||||
|
||||
void add_rule(FaultRule rule);
|
||||
void clear_rules();
|
||||
void set_pause_before_sync(std::function<void()> hook);
|
||||
[[nodiscard]] std::uint64_t op_count(FaultOp op) const noexcept;
|
||||
|
||||
[[nodiscard]] Result<void> ensure_dir(const std::filesystem::path& dir) override;
|
||||
[[nodiscard]] Result<bool> exists(const std::filesystem::path& p) override;
|
||||
[[nodiscard]] Result<std::uint64_t> file_size(const std::filesystem::path& p) override;
|
||||
[[nodiscard]] Result<std::vector<std::string>> list_dir(const std::filesystem::path& dir) override;
|
||||
[[nodiscard]] Result<std::unique_ptr<DirLockHandle>> lock_directory(const std::filesystem::path& dir) override;
|
||||
[[nodiscard]] Result<std::unique_ptr<FileHandle>> open_file(const std::filesystem::path& p, FileOpenMode mode) override;
|
||||
[[nodiscard]] Result<void> rename_atomic(const std::filesystem::path& from, const std::filesystem::path& to) override;
|
||||
[[nodiscard]] Result<void> unlink_file(const std::filesystem::path& p) override;
|
||||
[[nodiscard]] Result<void> sync_dir(const std::filesystem::path& dir) override;
|
||||
[[nodiscard]] Result<void> probe_durability_capabilities(const std::filesystem::path& dir) override;
|
||||
|
||||
private:
|
||||
friend class FaultFileHandle;
|
||||
|
||||
struct MatchedFault {
|
||||
StorageErrorCode error_code{StorageErrorCode::none};
|
||||
std::optional<std::size_t> partial_write_bytes{};
|
||||
bool triggered{false};
|
||||
};
|
||||
|
||||
[[nodiscard]] MatchedFault check_fault(FaultOp op, const std::string& path);
|
||||
void maybe_run_sync_hook();
|
||||
|
||||
std::shared_ptr<FilePort> delegate_;
|
||||
mutable std::mutex mu_;
|
||||
std::vector<FaultRule> rules_{};
|
||||
std::function<void()> pause_before_sync_{};
|
||||
std::uint64_t op_counts_[10]{};
|
||||
};
|
||||
|
||||
} // namespace Void::Storage
|
||||
@@ -0,0 +1,216 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
#include <Void/Storage/Types.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Storage
|
||||
{
|
||||
inline constexpr std::array<char, 8> kWalSegmentMagic{'V', 'O', 'I', 'D', 'W', 'A', 'L', '1'};
|
||||
inline constexpr std::uint16_t kWalFormatMajor = 1;
|
||||
inline constexpr std::uint16_t kWalFormatMinor = 0;
|
||||
inline constexpr std::uint32_t kWalSegmentHeaderSize = 64;
|
||||
|
||||
inline constexpr std::uint32_t kWalRecordMagic = 0x56575231u; // "1RWV" little-endian
|
||||
inline constexpr std::uint16_t kWalRecordVersion = 1;
|
||||
inline constexpr std::uint32_t kWalRecordHeaderSize = 36;
|
||||
inline constexpr std::uint32_t kWalRecordTrailerSize = 8;
|
||||
|
||||
enum class WalRecordType : std::uint16_t {
|
||||
Begin = 1,
|
||||
Put = 2,
|
||||
Erase = 3,
|
||||
Commit = 4
|
||||
};
|
||||
|
||||
struct WalSegmentHeader {
|
||||
std::uint16_t major{kWalFormatMajor};
|
||||
std::uint16_t minor{kWalFormatMinor};
|
||||
std::uint32_t header_size{kWalSegmentHeaderSize};
|
||||
Void::Uuid::Uuid database_uuid{};
|
||||
std::uint64_t segment_id{0};
|
||||
std::uint64_t previous_segment_id{0};
|
||||
Sequence first_candidate_sequence{0};
|
||||
std::uint32_t flags{0};
|
||||
};
|
||||
|
||||
struct WalRecordHeader {
|
||||
std::uint32_t total_length{0};
|
||||
WalRecordType type{WalRecordType::Begin};
|
||||
std::uint16_t record_version{kWalRecordVersion};
|
||||
std::uint32_t flags{0};
|
||||
Sequence batch_sequence{0};
|
||||
std::uint32_t ordinal{0};
|
||||
std::uint32_t payload_length{0};
|
||||
};
|
||||
|
||||
struct WalBeginPayload {
|
||||
std::uint32_t op_count{0};
|
||||
std::uint64_t total_op_bytes{0};
|
||||
};
|
||||
|
||||
struct WalMutationPayload {
|
||||
OwnedBytes key{};
|
||||
OwnedBytes value{};
|
||||
};
|
||||
|
||||
struct WalCommitPayload {
|
||||
std::uint32_t op_count{0};
|
||||
std::uint64_t total_op_bytes{0};
|
||||
std::uint32_t aggregate_crc32c{0};
|
||||
};
|
||||
|
||||
[[nodiscard]] Result<OwnedBytes> encode_wal_segment_header(const WalSegmentHeader& hdr);
|
||||
[[nodiscard]] Result<WalSegmentHeader> decode_wal_segment_header(ByteView bytes);
|
||||
|
||||
[[nodiscard]] Result<OwnedBytes> encode_wal_record_frame(
|
||||
WalRecordType type,
|
||||
Sequence batch_sequence,
|
||||
std::uint32_t ordinal,
|
||||
ByteView payload);
|
||||
|
||||
/// Decode and verify ONLY the 36-byte record header before reading/allocating payload.
|
||||
[[nodiscard]] Result<WalRecordHeader> decode_wal_record_header(
|
||||
ByteView header_bytes,
|
||||
std::size_t max_payload_bytes);
|
||||
|
||||
/// Verify full record CRC32C and trailing repeated length after reading payload+trailer.
|
||||
[[nodiscard]] Result<void> verify_wal_record_frame(
|
||||
const WalRecordHeader& hdr,
|
||||
ByteView full_record_bytes);
|
||||
|
||||
[[nodiscard]] Result<OwnedBytes> encode_wal_begin_payload(const WalBeginPayload& p);
|
||||
[[nodiscard]] Result<WalBeginPayload> decode_wal_begin_payload(ByteView bytes);
|
||||
|
||||
[[nodiscard]] Result<OwnedBytes> encode_wal_mutation_payload(
|
||||
bool is_erase, ByteView key, ByteView value);
|
||||
[[nodiscard]] Result<WalMutationPayload> decode_wal_mutation_payload(
|
||||
bool is_erase,
|
||||
ByteView bytes,
|
||||
std::size_t max_key_bytes,
|
||||
std::size_t max_value_bytes);
|
||||
|
||||
[[nodiscard]] Result<OwnedBytes> encode_wal_commit_payload(const WalCommitPayload& p);
|
||||
[[nodiscard]] Result<WalCommitPayload> decode_wal_commit_payload(ByteView bytes);
|
||||
|
||||
// ── V1 Immutable Sorted Table (`VOIDTBL1`) ───────────────────────────────
|
||||
|
||||
inline constexpr std::array<char, 8> kTableMagic{'V', 'O', 'I', 'D', 'T', 'B', 'L', '1'};
|
||||
inline constexpr std::array<char, 8> kTableFooterMagic{'V', 'O', 'I', 'D', 'T', 'B', 'F', '1'};
|
||||
inline constexpr std::uint32_t kTableHeaderSize = 76;
|
||||
inline constexpr std::uint32_t kTableFooterSize = 48;
|
||||
|
||||
struct TableEntryRecord {
|
||||
OwnedBytes key{};
|
||||
Sequence sequence{0};
|
||||
bool erased{false};
|
||||
OwnedBytes value{};
|
||||
};
|
||||
|
||||
struct TableHeader {
|
||||
std::uint16_t major{1};
|
||||
std::uint16_t minor{0};
|
||||
std::uint32_t header_size{kTableHeaderSize};
|
||||
Void::Uuid::Uuid database_uuid{};
|
||||
std::uint64_t table_id{0};
|
||||
std::uint32_t level{0};
|
||||
std::uint32_t flags{0};
|
||||
std::uint64_t entry_count{0};
|
||||
Sequence min_sequence{0};
|
||||
Sequence max_sequence{0};
|
||||
};
|
||||
|
||||
struct TableBlockIndexEntry {
|
||||
OwnedBytes first_key{};
|
||||
OwnedBytes last_key{};
|
||||
std::uint64_t offset{0};
|
||||
std::uint32_t byte_length{0};
|
||||
};
|
||||
|
||||
struct TableFooter {
|
||||
std::uint64_t index_offset{0};
|
||||
std::uint64_t index_size{0};
|
||||
std::uint64_t data_end_offset{0};
|
||||
std::uint32_t file_crc32c{0};
|
||||
};
|
||||
|
||||
struct TableMeta {
|
||||
std::uint64_t table_id{0};
|
||||
std::uint32_t level{0};
|
||||
std::uint64_t file_size{0};
|
||||
std::uint64_t entry_count{0};
|
||||
Sequence min_sequence{0};
|
||||
Sequence max_sequence{0};
|
||||
OwnedBytes min_key{};
|
||||
OwnedBytes max_key{};
|
||||
std::uint32_t file_crc32c{0};
|
||||
};
|
||||
|
||||
[[nodiscard]] Result<OwnedBytes> encode_table_header(const TableHeader& hdr);
|
||||
[[nodiscard]] Result<TableHeader> decode_table_header(ByteView bytes);
|
||||
[[nodiscard]] Result<OwnedBytes> encode_table_block(
|
||||
std::span<const TableEntryRecord> entries,
|
||||
std::size_t max_bytes);
|
||||
[[nodiscard]] Result<std::vector<TableEntryRecord>> decode_table_block(
|
||||
ByteView bytes,
|
||||
std::size_t max_key_bytes,
|
||||
std::size_t max_value_bytes);
|
||||
[[nodiscard]] Result<OwnedBytes> encode_table_index(
|
||||
std::span<const TableBlockIndexEntry> index,
|
||||
std::size_t max_bytes);
|
||||
[[nodiscard]] Result<std::vector<TableBlockIndexEntry>> decode_table_index(
|
||||
ByteView bytes,
|
||||
std::size_t max_key_bytes);
|
||||
[[nodiscard]] Result<OwnedBytes> encode_table_footer(const TableFooter& footer);
|
||||
[[nodiscard]] Result<TableFooter> decode_table_footer(ByteView bytes);
|
||||
|
||||
// ── V1 Manifest (`VOIDMNF1`) & CURRENT (`VOIDCUR1`) ──────────────────────
|
||||
|
||||
inline constexpr std::array<char, 8> kManifestMagic{'V', 'O', 'I', 'D', 'M', 'N', 'F', '1'};
|
||||
inline constexpr std::array<char, 8> kCurrentMagic{'V', 'O', 'I', 'D', 'C', 'U', 'R', '1'};
|
||||
inline constexpr std::string_view kComparatorIdV1 = "void.byte.lex.v1";
|
||||
|
||||
struct ManifestData {
|
||||
std::uint16_t major{1};
|
||||
std::uint16_t minor{0};
|
||||
std::uint32_t flags{0};
|
||||
Void::Uuid::Uuid database_uuid{};
|
||||
std::uint64_t generation{0};
|
||||
Sequence checkpoint_sequence{0};
|
||||
Sequence next_sequence_hint{1};
|
||||
std::uint64_t next_file_id{1};
|
||||
std::string comparator{kComparatorIdV1};
|
||||
std::vector<TableMeta> tables{};
|
||||
std::vector<std::uint64_t> wal_segments{};
|
||||
};
|
||||
|
||||
struct CurrentPointer {
|
||||
std::uint16_t major{1};
|
||||
std::uint16_t minor{0};
|
||||
Void::Uuid::Uuid database_uuid{};
|
||||
std::uint64_t generation{0};
|
||||
std::string manifest_filename{};
|
||||
};
|
||||
|
||||
[[nodiscard]] Result<OwnedBytes> encode_manifest(
|
||||
const ManifestData& m,
|
||||
std::size_t max_manifest_bytes);
|
||||
[[nodiscard]] Result<ManifestData> decode_manifest(
|
||||
ByteView bytes,
|
||||
std::size_t max_manifest_bytes,
|
||||
std::size_t max_tables,
|
||||
std::size_t max_key_bytes);
|
||||
|
||||
[[nodiscard]] Result<OwnedBytes> encode_current(const CurrentPointer& cur);
|
||||
[[nodiscard]] Result<CurrentPointer> decode_current(ByteView bytes);
|
||||
|
||||
[[nodiscard]] std::string make_wal_filename(std::uint64_t segment_id);
|
||||
[[nodiscard]] std::string make_table_filename(std::uint64_t table_id);
|
||||
[[nodiscard]] std::string make_manifest_filename(std::uint64_t generation);
|
||||
|
||||
} // namespace Void::Storage
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Storage/AsyncAdapter.hpp>
|
||||
#include <Void/Storage/Batch.hpp>
|
||||
#include <Void/Storage/Crc32c.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
#include <Void/Storage/FilePort.hpp>
|
||||
#include <Void/Storage/Format.hpp>
|
||||
#include <Void/Storage/Tools.hpp>
|
||||
#include <Void/Storage/Types.hpp>
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Storage/FilePort.hpp>
|
||||
#include <Void/Storage/Types.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
|
||||
namespace Void::Storage
|
||||
{
|
||||
struct VerifyReport {
|
||||
std::uint64_t manifest_generation{0};
|
||||
Sequence checkpoint_sequence{0};
|
||||
std::uint64_t tables_verified{0};
|
||||
std::uint64_t blocks_verified{0};
|
||||
std::uint64_t wal_segments_verified{0};
|
||||
std::uint64_t wal_batches_verified{0};
|
||||
};
|
||||
|
||||
struct SalvageReport {
|
||||
Sequence highest_recovered_sequence{0};
|
||||
std::uint64_t recovered_batches{0};
|
||||
std::uint64_t keys_recovered{0};
|
||||
std::uint64_t tombstones_preserved{0};
|
||||
std::uint64_t truncated_or_skipped_bytes{0};
|
||||
};
|
||||
|
||||
/// Read-only full structural & block-level verification of an offline or
|
||||
/// quiesced Storage directory (CURRENT, MANIFEST, every block of every table,
|
||||
/// and every manifest-listed WAL segment).
|
||||
[[nodiscard]] Result<VerifyReport> verify_directory(
|
||||
const std::filesystem::path& directory,
|
||||
const Limits& limits = {},
|
||||
std::shared_ptr<FilePort> port = nullptr);
|
||||
|
||||
/// Restore a verified backup directory into `destination` without mutating
|
||||
/// `backup_dir`.
|
||||
[[nodiscard]] Result<void> restore_backup(
|
||||
const std::filesystem::path& backup_dir,
|
||||
const std::filesystem::path& destination,
|
||||
const Limits& limits = {},
|
||||
std::shared_ptr<FilePort> port = nullptr);
|
||||
|
||||
/// Offline salvage: extracts the valid prefix of committed data and valid
|
||||
/// tables/WAL records from `source_dir` into a fresh `destination_dir`.
|
||||
/// Refuses same-directory salvage.
|
||||
[[nodiscard]] Result<SalvageReport> salvage_directory(
|
||||
const std::filesystem::path& source_dir,
|
||||
const std::filesystem::path& destination_dir,
|
||||
const Limits& limits = {},
|
||||
std::shared_ptr<FilePort> port = nullptr);
|
||||
|
||||
} // namespace Void::Storage
|
||||
@@ -0,0 +1,381 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <memory_resource>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Storage
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
using Sequence = std::uint64_t;
|
||||
using ByteView = std::span<const std::byte>;
|
||||
using OwnedBytes = std::vector<std::byte>;
|
||||
|
||||
class FilePort;
|
||||
|
||||
enum class Durability : std::uint8_t {
|
||||
Sync = 0,
|
||||
Buffered = 1
|
||||
};
|
||||
|
||||
enum class Outcome : std::uint8_t {
|
||||
NotCommitted = 0,
|
||||
Committed = 1,
|
||||
Unknown = 2
|
||||
};
|
||||
|
||||
enum class EngineState : std::uint8_t {
|
||||
Open = 0,
|
||||
RecoveryRequired = 1,
|
||||
Closed = 2
|
||||
};
|
||||
|
||||
enum class StorageErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
not_found = 2,
|
||||
conflict = 3,
|
||||
interrupted = 4,
|
||||
timeout = 5,
|
||||
overloaded = 6,
|
||||
unsupported_capability = 7,
|
||||
io_error = 8,
|
||||
corrupt = 9,
|
||||
incomplete_init = 10,
|
||||
sequence_exhausted = 11,
|
||||
recovery_required = 12,
|
||||
busy = 13,
|
||||
closed = 14,
|
||||
page_too_small = 15,
|
||||
quota_exceeded = 16
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Error make_storage_error(
|
||||
StorageErrorCode code,
|
||||
std::string message,
|
||||
std::error_code sys_err = {})
|
||||
{
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case StorageErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case StorageErrorCode::invalid_argument:
|
||||
case StorageErrorCode::page_too_small:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case StorageErrorCode::not_found:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case StorageErrorCode::conflict:
|
||||
case StorageErrorCode::recovery_required:
|
||||
case StorageErrorCode::busy:
|
||||
case StorageErrorCode::incomplete_init:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case StorageErrorCode::interrupted:
|
||||
case StorageErrorCode::closed:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case StorageErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case StorageErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case StorageErrorCode::unsupported_capability:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case StorageErrorCode::io_error:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case StorageErrorCode::corrupt:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case StorageErrorCode::sequence_exhausted:
|
||||
case StorageErrorCode::quota_exceeded:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
}
|
||||
|
||||
return Error{
|
||||
kind,
|
||||
std::move(message),
|
||||
ErrorCode{Void::Result::kStorageErrorDomain,
|
||||
static_cast<std::int32_t>(code)},
|
||||
sys_err};
|
||||
}
|
||||
|
||||
struct StorageError {
|
||||
StorageErrorCode code{StorageErrorCode::none};
|
||||
Error error{};
|
||||
};
|
||||
|
||||
struct CommitReceipt {
|
||||
Sequence sequence{0};
|
||||
Durability durability{Durability::Sync};
|
||||
};
|
||||
|
||||
struct WriteFailure {
|
||||
StorageError cause{};
|
||||
Outcome outcome{Outcome::NotCommitted};
|
||||
};
|
||||
|
||||
struct OwnedValue {
|
||||
OwnedBytes bytes{};
|
||||
Sequence version{0};
|
||||
|
||||
[[nodiscard]] std::string_view as_string_view() const noexcept
|
||||
{
|
||||
return bytes.empty()
|
||||
? std::string_view{}
|
||||
: std::string_view{
|
||||
reinterpret_cast<const char*>(bytes.data()),
|
||||
bytes.size()};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool operator==(const OwnedValue&) const = default;
|
||||
};
|
||||
|
||||
[[nodiscard]] inline OwnedBytes to_owned_bytes(std::string_view s)
|
||||
{
|
||||
OwnedBytes out(s.size());
|
||||
for (std::size_t i = 0; i < s.size(); ++i) {
|
||||
out[i] = static_cast<std::byte>(static_cast<unsigned char>(s[i]));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline ByteView to_byte_view(std::string_view s) noexcept
|
||||
{
|
||||
return std::as_bytes(std::span{s.data(), s.size()});
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::string_view to_string_view(ByteView b) noexcept
|
||||
{
|
||||
return b.empty()
|
||||
? std::string_view{}
|
||||
: std::string_view{
|
||||
reinterpret_cast<const char*>(b.data()),
|
||||
b.size()};
|
||||
}
|
||||
|
||||
/// Locale-independent unsigned-byte lexicographic comparison.
|
||||
[[nodiscard]] inline int byte_compare(ByteView a, ByteView b) noexcept
|
||||
{
|
||||
const std::size_t n = std::min(a.size(), b.size());
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
const auto xa = std::to_integer<unsigned char>(a[i]);
|
||||
const auto yb = std::to_integer<unsigned char>(b[i]);
|
||||
if (xa < yb) return -1;
|
||||
if (xa > yb) return 1;
|
||||
}
|
||||
if (a.size() < b.size()) return -1;
|
||||
if (a.size() > b.size()) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct ByteLess {
|
||||
using is_transparent = void;
|
||||
|
||||
[[nodiscard]] bool operator()(ByteView a, ByteView b) const noexcept
|
||||
{
|
||||
return byte_compare(a, b) < 0;
|
||||
}
|
||||
[[nodiscard]] bool operator()(const OwnedBytes& a, const OwnedBytes& b) const noexcept
|
||||
{
|
||||
return byte_compare(a, b) < 0;
|
||||
}
|
||||
[[nodiscard]] bool operator()(const OwnedBytes& a, ByteView b) const noexcept
|
||||
{
|
||||
return byte_compare(a, b) < 0;
|
||||
}
|
||||
[[nodiscard]] bool operator()(ByteView a, const OwnedBytes& b) const noexcept
|
||||
{
|
||||
return byte_compare(a, b) < 0;
|
||||
}
|
||||
};
|
||||
|
||||
struct ScanBounds {
|
||||
std::optional<OwnedBytes> begin{};
|
||||
std::optional<OwnedBytes> end{};
|
||||
std::size_t page_bytes{0};
|
||||
std::size_t page_rows{0};
|
||||
|
||||
[[nodiscard]] static ScanBounds all() { return {}; }
|
||||
|
||||
[[nodiscard]] static ScanBounds range(ByteView b, ByteView e)
|
||||
{
|
||||
ScanBounds sb;
|
||||
sb.begin.emplace(b.begin(), b.end());
|
||||
sb.end.emplace(e.begin(), e.end());
|
||||
return sb;
|
||||
}
|
||||
|
||||
[[nodiscard]] static ScanBounds range(std::string_view b, std::string_view e)
|
||||
{
|
||||
return range(to_byte_view(b), to_byte_view(e));
|
||||
}
|
||||
|
||||
[[nodiscard]] static ScanBounds prefix(ByteView p)
|
||||
{
|
||||
ScanBounds sb;
|
||||
sb.begin.emplace(p.begin(), p.end());
|
||||
OwnedBytes upper(p.begin(), p.end());
|
||||
while (!upper.empty()) {
|
||||
const auto b = std::to_integer<unsigned char>(upper.back());
|
||||
if (b < 0xFFu) {
|
||||
upper.back() = static_cast<std::byte>(b + 1u);
|
||||
sb.end = std::move(upper);
|
||||
return sb;
|
||||
}
|
||||
upper.pop_back();
|
||||
}
|
||||
// All-0xFF prefix has no finite upper bound.
|
||||
return sb;
|
||||
}
|
||||
|
||||
[[nodiscard]] static ScanBounds prefix(std::string_view p)
|
||||
{
|
||||
return prefix(to_byte_view(p));
|
||||
}
|
||||
};
|
||||
|
||||
struct ScanEntry {
|
||||
OwnedBytes key{};
|
||||
OwnedBytes value{};
|
||||
Sequence version{0};
|
||||
};
|
||||
|
||||
struct ScanPage {
|
||||
std::vector<ScanEntry> entries{};
|
||||
bool has_more{false};
|
||||
};
|
||||
|
||||
struct Limits {
|
||||
std::size_t max_key_bytes{4096};
|
||||
std::size_t max_value_bytes{4ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_batch_encoded_bytes{16ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_batch_mutations{1024};
|
||||
std::size_t max_batch_conditions{1024};
|
||||
|
||||
std::size_t max_pending_batches{64};
|
||||
std::size_t max_pending_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
|
||||
std::size_t active_memtable_target_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_total_memtable_bytes{256ULL * 1024ULL * 1024ULL};
|
||||
|
||||
std::size_t max_snapshots{128};
|
||||
std::size_t max_cursors{128};
|
||||
std::size_t default_scan_page_bytes{1024ULL * 1024ULL};
|
||||
std::size_t max_scan_page_bytes{8ULL * 1024ULL * 1024ULL};
|
||||
std::size_t default_scan_page_rows{1024};
|
||||
|
||||
std::size_t max_obsolete_pinned_bytes{1024ULL * 1024ULL * 1024ULL};
|
||||
std::size_t block_cache_bytes{32ULL * 1024ULL * 1024ULL};
|
||||
std::size_t compaction_workspace_bytes{16ULL * 1024ULL * 1024ULL};
|
||||
|
||||
std::uint64_t wal_segment_target_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
std::uint64_t max_wal_total_bytes{4ULL * 1024ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_active_runs{32};
|
||||
std::size_t table_block_target_bytes{32768};
|
||||
std::size_t max_manifest_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_manifest_tables{65536};
|
||||
std::size_t max_compaction_merge_runs{4};
|
||||
std::uint64_t compaction_output_target_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
std::size_t compaction_work_slice_bytes{8ULL * 1024ULL * 1024ULL};
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Result<void> validate_limits(const Limits& l)
|
||||
{
|
||||
if (l.max_key_bytes == 0 ||
|
||||
l.max_value_bytes == 0 ||
|
||||
l.max_batch_encoded_bytes == 0 ||
|
||||
l.max_batch_mutations == 0 ||
|
||||
l.max_batch_conditions == 0 ||
|
||||
l.max_pending_batches == 0 ||
|
||||
l.max_pending_bytes == 0 ||
|
||||
l.active_memtable_target_bytes == 0 ||
|
||||
l.max_total_memtable_bytes == 0 ||
|
||||
l.max_snapshots == 0 ||
|
||||
l.max_cursors == 0 ||
|
||||
l.default_scan_page_bytes == 0 ||
|
||||
l.max_scan_page_bytes == 0 ||
|
||||
l.default_scan_page_rows == 0 ||
|
||||
l.max_obsolete_pinned_bytes == 0 ||
|
||||
l.block_cache_bytes == 0 ||
|
||||
l.compaction_workspace_bytes == 0 ||
|
||||
l.wal_segment_target_bytes == 0 ||
|
||||
l.max_wal_total_bytes == 0 ||
|
||||
l.max_active_runs == 0 ||
|
||||
l.table_block_target_bytes == 0 ||
|
||||
l.max_manifest_bytes == 0 ||
|
||||
l.max_manifest_tables == 0 ||
|
||||
l.max_compaction_merge_runs == 0 ||
|
||||
l.compaction_output_target_bytes == 0 ||
|
||||
l.compaction_work_slice_bytes == 0) {
|
||||
return Void::Result::fail(make_storage_error(
|
||||
StorageErrorCode::invalid_argument,
|
||||
"Storage::Limits: all limits must be positive finite values"));
|
||||
}
|
||||
if (l.default_scan_page_bytes > l.max_scan_page_bytes ||
|
||||
l.active_memtable_target_bytes > l.max_total_memtable_bytes ||
|
||||
l.wal_segment_target_bytes > l.max_wal_total_bytes ||
|
||||
l.max_batch_encoded_bytes > l.wal_segment_target_bytes) {
|
||||
return Void::Result::fail(make_storage_error(
|
||||
StorageErrorCode::invalid_argument,
|
||||
"Storage::Limits: inconsistent bound ordering (max batch must fit in one WAL segment)"));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
struct OpenOptions {
|
||||
std::filesystem::path directory{};
|
||||
Durability default_durability{Durability::Sync};
|
||||
Limits limits{};
|
||||
std::pmr::memory_resource* memory_resource{nullptr};
|
||||
std::shared_ptr<FilePort> file_port{};
|
||||
const Void::Time::MonotonicClock* monotonic_clock{nullptr};
|
||||
std::function<void(std::string_view)> metric_hook{};
|
||||
/// Optional explicit sequence seed used only when opening a brand-new
|
||||
/// database (e.g. sequence-exhaustion tests).
|
||||
Sequence initial_sequence{0};
|
||||
};
|
||||
|
||||
struct EngineStats {
|
||||
EngineState state{EngineState::Closed};
|
||||
Sequence committed_sequence{0};
|
||||
Sequence checkpoint_sequence{0};
|
||||
Sequence oldest_snapshot_sequence{0};
|
||||
std::uint64_t live_snapshots{0};
|
||||
std::uint64_t live_cursors{0};
|
||||
std::uint64_t active_memtable_bytes{0};
|
||||
std::uint64_t total_memtable_bytes{0};
|
||||
std::uint64_t wal_total_bytes{0};
|
||||
std::uint64_t active_table_count{0};
|
||||
std::uint64_t obsolete_pinned_bytes{0};
|
||||
std::uint64_t total_table_bytes{0};
|
||||
std::uint64_t recovery_truncated_bytes{0};
|
||||
bool durable_sync_verified{false};
|
||||
};
|
||||
|
||||
} // namespace Void::Storage
|
||||
@@ -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
|
||||
@@ -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
@@ -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
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(Storage
|
||||
INTERNAL_DEPS Core Functional Time Memory Binary IO Async
|
||||
)
|
||||
@@ -232,6 +232,11 @@ if(_has_sqlite_async)
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE)
|
||||
endif()
|
||||
|
||||
has_modules(_has_storage Storage Core Functional Time Memory Binary IO Async)
|
||||
if(_has_storage)
|
||||
run_consumer(StorageOnly "${install_prefix}" "StorageOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidStorageOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS Storage)
|
||||
|
||||
add_executable(void_storage_only_consumer main.cpp)
|
||||
target_link_libraries(void_storage_only_consumer PRIVATE Void::Storage)
|
||||
target_compile_features(void_storage_only_consumer PRIVATE cxx_std_26)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME StorageOnlyConsumer COMMAND void_storage_only_consumer)
|
||||
@@ -0,0 +1,36 @@
|
||||
#include <Void/Storage/Storage.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
if (Void::Storage::crc32c(std::string_view{"123456789"}) != 0xE3069283u) {
|
||||
return 1;
|
||||
}
|
||||
const auto dir = std::filesystem::temp_directory_path() /
|
||||
("void-storage-pkg-" + std::to_string(::getpid()));
|
||||
std::error_code ec;
|
||||
std::filesystem::remove_all(dir, ec);
|
||||
|
||||
Void::Storage::OpenOptions opts;
|
||||
opts.directory = dir;
|
||||
auto eng = Void::Storage::Engine::open(opts);
|
||||
if (!eng) return 2;
|
||||
|
||||
Void::Storage::Batch b;
|
||||
b.require_absent("hello").put("hello", "world");
|
||||
auto wr = eng->write(std::move(b), Void::Storage::Durability::Sync);
|
||||
if (!wr) return 3;
|
||||
|
||||
auto snap = eng->snapshot();
|
||||
if (!snap) return 4;
|
||||
auto val = eng->get(*snap, "hello");
|
||||
const bool ok = val && val->as_string_view() == "world" && val->version == wr->sequence;
|
||||
snap->reset();
|
||||
const bool closed = eng->close().has_value();
|
||||
|
||||
std::filesystem::remove_all(dir, ec);
|
||||
return (ok && closed) ? 0 : 5;
|
||||
}
|
||||
@@ -0,0 +1,855 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
#include <Void/Storage/Storage.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <limits>
|
||||
#include <map>
|
||||
#include <random>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace Void::Storage;
|
||||
|
||||
struct TempStorageDir {
|
||||
std::filesystem::path path;
|
||||
TempStorageDir()
|
||||
{
|
||||
static std::atomic<std::uint64_t> seq{0};
|
||||
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
|
||||
path = std::filesystem::temp_directory_path() /
|
||||
("void-storage-test-" + std::to_string(::getpid()) + "-" + std::to_string(id));
|
||||
std::error_code ec;
|
||||
std::filesystem::remove_all(path, ec);
|
||||
std::filesystem::create_directories(path, ec);
|
||||
}
|
||||
~TempStorageDir()
|
||||
{
|
||||
std::error_code ec;
|
||||
std::filesystem::remove_all(path, ec);
|
||||
}
|
||||
};
|
||||
|
||||
void write_raw_bytes(const std::filesystem::path& p, ByteView data)
|
||||
{
|
||||
auto port = make_posix_file_port();
|
||||
(void)port->unlink_file(p);
|
||||
auto f = port->open_file(p, FileOpenMode::CreateNew);
|
||||
Void::Testing::require(f.has_value());
|
||||
Void::Testing::require((*f)->append_all(data).has_value());
|
||||
Void::Testing::require((*f)->sync().has_value());
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> run_async_stop_before_append(
|
||||
AsyncStorageAdapter& adapter,
|
||||
std::expected<CommitReceipt, WriteFailure>* out,
|
||||
bool* done)
|
||||
{
|
||||
std::stop_source ss;
|
||||
ss.request_stop();
|
||||
Batch b;
|
||||
b.put("k_cancelled", "never_written");
|
||||
Void::Async::OperationOptions op;
|
||||
op.stop = ss.get_token();
|
||||
*out = co_await adapter.write_async(std::move(b), Durability::Sync, op);
|
||||
*done = true;
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> run_async_write_tracked(
|
||||
AsyncStorageAdapter& adapter,
|
||||
std::string key,
|
||||
std::string val,
|
||||
std::stop_token st,
|
||||
std::expected<CommitReceipt, WriteFailure>* out,
|
||||
std::atomic<int>* deliveries,
|
||||
bool* done)
|
||||
{
|
||||
Batch b;
|
||||
b.put(key, val);
|
||||
Void::Async::OperationOptions op;
|
||||
op.stop = st;
|
||||
*out = co_await adapter.write_async(std::move(b), Durability::Sync, op);
|
||||
deliveries->fetch_add(1, std::memory_order_acq_rel);
|
||||
*done = true;
|
||||
}
|
||||
|
||||
Void::Testing::Test storage_crc32c_golden_and_v1_format_codecs()
|
||||
{
|
||||
// Golden CRC32C check (Cyphal / Castagnoli)
|
||||
Void::Testing::expect_eq(crc32c(std::string_view{"123456789"}), 0xE3069283u);
|
||||
Void::Testing::expect_eq(crc32c(std::string_view{""}), 0u);
|
||||
|
||||
// Incremental chunked update must match single-pass CRC32C
|
||||
std::uint32_t st = crc32c_init();
|
||||
st = crc32c_update(st, std::string_view{"1234"});
|
||||
st = crc32c_update(st, std::string_view{"56789"});
|
||||
Void::Testing::expect_eq(crc32c_finalize(st), 0xE3069283u);
|
||||
|
||||
// Limits validation rejects zero fields
|
||||
Limits bad_lim;
|
||||
bad_lim.max_key_bytes = 0;
|
||||
Void::Testing::expect(!validate_limits(bad_lim).has_value());
|
||||
|
||||
// WAL segment header encode/decode + corruption & unknown major/flags rejection
|
||||
auto uuid = Void::Uuid::try_v4();
|
||||
Void::Testing::require(uuid.has_value());
|
||||
WalSegmentHeader wsh;
|
||||
wsh.database_uuid = *uuid;
|
||||
wsh.segment_id = 7;
|
||||
wsh.previous_segment_id = 6;
|
||||
wsh.first_candidate_sequence = 42;
|
||||
auto raw_seg = encode_wal_segment_header(wsh);
|
||||
Void::Testing::require(raw_seg.has_value());
|
||||
Void::Testing::expect_eq(raw_seg->size(), static_cast<std::size_t>(kWalSegmentHeaderSize));
|
||||
auto dec_seg = decode_wal_segment_header(*raw_seg);
|
||||
Void::Testing::require(dec_seg.has_value());
|
||||
Void::Testing::expect_eq(dec_seg->segment_id, static_cast<std::uint64_t>(7));
|
||||
|
||||
// Flip a byte in segment header -> corrupt
|
||||
auto flipped_seg = *raw_seg;
|
||||
flipped_seg[20] ^= std::byte{0x01};
|
||||
auto bad_seg = decode_wal_segment_header(flipped_seg);
|
||||
Void::Testing::expect(!bad_seg.has_value());
|
||||
Void::Testing::expect(bad_seg.error().kind() == Void::Result::ErrorKind::corrupt);
|
||||
|
||||
// WAL record header checks header CRC BEFORE trusting huge payload_length!
|
||||
auto mp = encode_wal_mutation_payload(false, to_byte_view("k"), to_byte_view("v"));
|
||||
Void::Testing::require(mp.has_value());
|
||||
auto frame = encode_wal_record_frame(WalRecordType::Put, 5, 1, *mp);
|
||||
Void::Testing::require(frame.has_value());
|
||||
auto rh = decode_wal_record_header(
|
||||
std::span<const std::byte>{frame->data(), kWalRecordHeaderSize}, 65536);
|
||||
Void::Testing::require(rh.has_value());
|
||||
Void::Testing::require(verify_wal_record_frame(*rh, *frame).has_value());
|
||||
|
||||
// Flip header payload_len without updating header CRC -> rejected before allocation
|
||||
auto huge_len_hdr = *frame;
|
||||
huge_len_hdr[28] = std::byte{0xFF};
|
||||
huge_len_hdr[29] = std::byte{0xFF};
|
||||
huge_len_hdr[30] = std::byte{0xFF};
|
||||
huge_len_hdr[31] = std::byte{0x7F};
|
||||
auto bad_rh = decode_wal_record_header(
|
||||
std::span<const std::byte>{huge_len_hdr.data(), kWalRecordHeaderSize}, 1024);
|
||||
Void::Testing::expect(!bad_rh.has_value());
|
||||
|
||||
// Erase payload with non-zero value fails decode
|
||||
auto bad_erase = encode_wal_mutation_payload(true, to_byte_view("k"), to_byte_view("nonempty"));
|
||||
Void::Testing::expect(!bad_erase.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test storage_model_atomic_batches_preconditions_snapshots_and_scans()
|
||||
{
|
||||
TempStorageDir dir;
|
||||
OpenOptions opts;
|
||||
opts.directory = dir.path;
|
||||
opts.limits.max_snapshots = 8;
|
||||
opts.limits.max_cursors = 8;
|
||||
|
||||
auto eng_r = Engine::open(opts);
|
||||
Void::Testing::require(eng_r.has_value());
|
||||
auto& eng = *eng_r;
|
||||
|
||||
// Reference model: key -> (value, version_seq)
|
||||
struct RefVal {
|
||||
OwnedBytes val;
|
||||
Sequence seq;
|
||||
};
|
||||
std::map<OwnedBytes, RefVal, ByteLess> ref;
|
||||
|
||||
// Test empty key and empty value distinct from absence, plus binary 0x00/0xFF keys.
|
||||
const OwnedBytes k_empty{};
|
||||
const OwnedBytes k_nul{std::byte{0x00}, std::byte{0x41}, std::byte{0x00}};
|
||||
const OwnedBytes k_ff{std::byte{0xFF}, std::byte{0xFF}};
|
||||
{
|
||||
Batch b;
|
||||
b.require_absent(k_empty)
|
||||
.put(k_empty, OwnedBytes{})
|
||||
.put(k_nul, to_byte_view("zero"))
|
||||
.put(k_ff, to_byte_view("ffval"));
|
||||
auto r = eng.write(std::move(b), Durability::Sync);
|
||||
Void::Testing::require(r.has_value());
|
||||
ref[k_empty] = RefVal{{}, r->sequence};
|
||||
ref[k_nul] = RefVal{to_owned_bytes("zero"), r->sequence};
|
||||
ref[k_ff] = RefVal{to_owned_bytes("ffval"), r->sequence};
|
||||
}
|
||||
|
||||
// Duplicate key & duplicate precondition rejected cleanly as NotCommitted
|
||||
{
|
||||
Batch dup_mut;
|
||||
dup_mut.put("a", "1").put("a", "2");
|
||||
auto r = eng.write(std::move(dup_mut), Durability::Sync);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect(r.error().outcome == Outcome::NotCommitted);
|
||||
|
||||
Batch dup_cond;
|
||||
dup_cond.require_absent("a").require_value("a", "1").put("b", "2");
|
||||
auto r2 = eng.write(std::move(dup_cond), Durability::Sync);
|
||||
Void::Testing::expect(!r2.has_value());
|
||||
Void::Testing::expect(r2.error().outcome == Outcome::NotCommitted);
|
||||
}
|
||||
|
||||
// Delete + reinsert ABA version check: old sequence must fail after delete!
|
||||
Sequence seq_a1 = 0;
|
||||
{
|
||||
Batch b;
|
||||
b.put("aba", "v1");
|
||||
auto r = eng.write(std::move(b), Durability::Sync);
|
||||
Void::Testing::require(r.has_value());
|
||||
seq_a1 = r->sequence;
|
||||
}
|
||||
{
|
||||
Batch b;
|
||||
b.require_version("aba", seq_a1).erase("aba");
|
||||
Void::Testing::require(eng.write(std::move(b), Durability::Sync).has_value());
|
||||
}
|
||||
{
|
||||
// Obsolete version check after delete MUST fail!
|
||||
Batch b;
|
||||
b.require_version("aba", seq_a1).put("aba", "should_fail");
|
||||
auto r = eng.write(std::move(b), Durability::Sync);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect(r.error().outcome == Outcome::NotCommitted);
|
||||
Void::Testing::expect(r.error().cause.code == StorageErrorCode::conflict);
|
||||
}
|
||||
|
||||
// Take Snapshot before randomized model mutations!
|
||||
auto early_snap = eng.snapshot();
|
||||
Void::Testing::require(early_snap.has_value());
|
||||
{
|
||||
auto g = eng.get(*early_snap, k_empty);
|
||||
Void::Testing::require(g.has_value());
|
||||
Void::Testing::expect(g->bytes.empty());
|
||||
}
|
||||
|
||||
// Deterministic RNG model check comparing EVERY snapshot against ordered std::map!
|
||||
std::mt19937 rng{20261126u};
|
||||
{
|
||||
auto s0 = eng.snapshot();
|
||||
Void::Testing::require(s0.has_value());
|
||||
auto cur0 = eng.scan(std::move(*s0), ScanBounds::all());
|
||||
Void::Testing::require(cur0.has_value());
|
||||
for (;;) {
|
||||
auto pg = cur0->next_page();
|
||||
Void::Testing::require(pg.has_value());
|
||||
for (const auto& e : pg->entries) {
|
||||
ref[e.key] = RefVal{e.value, e.version};
|
||||
}
|
||||
if (!pg->has_more) break;
|
||||
}
|
||||
}
|
||||
for (int step = 0; step < 60; ++step) {
|
||||
const auto kb = to_owned_bytes("m/" + std::to_string(rng() % 7));
|
||||
Batch b;
|
||||
const bool do_erase = (rng() % 3) == 0;
|
||||
const std::string val_str = "val_" + std::to_string(step);
|
||||
if ((rng() % 4) == 0) {
|
||||
if (auto it = ref.find(kb); it != ref.end()) {
|
||||
b.require_value(kb, it->second.val);
|
||||
} else {
|
||||
b.require_absent(kb);
|
||||
}
|
||||
}
|
||||
if (do_erase) {
|
||||
b.erase(kb);
|
||||
} else {
|
||||
b.put(ByteView{kb}, to_byte_view(val_str));
|
||||
}
|
||||
auto wr = eng.write(std::move(b), (step % 2 == 0) ? Durability::Sync : Durability::Buffered);
|
||||
Void::Testing::require(wr.has_value());
|
||||
if (do_erase) {
|
||||
ref.erase(kb);
|
||||
} else {
|
||||
ref[kb] = RefVal{to_owned_bytes(val_str), wr->sequence};
|
||||
}
|
||||
|
||||
auto s = eng.snapshot();
|
||||
Void::Testing::require(s.has_value());
|
||||
auto cur = eng.scan(std::move(*s), ScanBounds::all());
|
||||
Void::Testing::require(cur.has_value());
|
||||
std::map<OwnedBytes, RefVal, ByteLess> got;
|
||||
for (;;) {
|
||||
auto pg = cur->next_page();
|
||||
Void::Testing::require(pg.has_value());
|
||||
for (const auto& e : pg->entries) {
|
||||
got[e.key] = RefVal{e.value, e.version};
|
||||
}
|
||||
if (!pg->has_more) break;
|
||||
}
|
||||
Void::Testing::expect_eq(got.size(), ref.size());
|
||||
for (const auto& [k, rv] : ref) {
|
||||
Void::Testing::require(got.contains(k));
|
||||
Void::Testing::expect(got[k].val == rv.val);
|
||||
Void::Testing::expect_eq(got[k].seq, rv.seq);
|
||||
}
|
||||
}
|
||||
|
||||
// Prefix scan including 0xFF prefix and close()-while-snapshot-live -> Busy!
|
||||
{
|
||||
auto cur = eng.scan(std::move(*early_snap), ScanBounds::prefix(k_ff));
|
||||
Void::Testing::require(cur.has_value());
|
||||
auto busy = eng.close();
|
||||
Void::Testing::expect(!busy.has_value());
|
||||
Void::Testing::expect(busy.error().code().value ==
|
||||
static_cast<std::int32_t>(StorageErrorCode::busy));
|
||||
auto pg = cur->next_page();
|
||||
Void::Testing::require(pg.has_value());
|
||||
Void::Testing::expect_eq(pg->entries.size(), static_cast<std::size_t>(1));
|
||||
Void::Testing::expect(pg->entries[0].key == k_ff);
|
||||
cur->close();
|
||||
}
|
||||
|
||||
// PageTooSmall reported when entry exceeds ScanBounds::page_bytes
|
||||
{
|
||||
Batch big_b;
|
||||
const std::string big_v(2048, 'B');
|
||||
big_b.put("big_key", big_v);
|
||||
Void::Testing::require(eng.write(std::move(big_b), Durability::Sync).has_value());
|
||||
auto s = eng.snapshot();
|
||||
Void::Testing::require(s.has_value());
|
||||
ScanBounds sb = ScanBounds::prefix("big_key");
|
||||
sb.page_bytes = 512;
|
||||
auto cur = eng.scan(std::move(*s), sb);
|
||||
Void::Testing::require(cur.has_value());
|
||||
auto pg = cur->next_page();
|
||||
Void::Testing::expect(!pg.has_value());
|
||||
Void::Testing::expect(pg.error().code().value ==
|
||||
static_cast<std::int32_t>(StorageErrorCode::page_too_small));
|
||||
}
|
||||
|
||||
// Sequence counter exhaustion returns sequence_exhausted without wrapping
|
||||
{
|
||||
TempStorageDir max_dir;
|
||||
OpenOptions mopts;
|
||||
mopts.directory = max_dir.path;
|
||||
mopts.initial_sequence = std::numeric_limits<Sequence>::max();
|
||||
auto meng = Engine::open(mopts);
|
||||
Void::Testing::require(meng.has_value());
|
||||
Batch b;
|
||||
b.put("x", "1");
|
||||
auto wr = meng->write(std::move(b), Durability::Sync);
|
||||
Void::Testing::expect(!wr.has_value());
|
||||
Void::Testing::expect(wr.error().outcome == Outcome::NotCommitted);
|
||||
Void::Testing::expect(wr.error().cause.code == StorageErrorCode::sequence_exhausted);
|
||||
}
|
||||
|
||||
Void::Testing::require(eng.close().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test storage_wal_recovery_byte_truncation_corruption_and_rotation()
|
||||
{
|
||||
// 1. Orphan manifest without CURRENT -> incomplete_init (never adopts orphan!)
|
||||
{
|
||||
TempStorageDir dir;
|
||||
auto uuid = Void::Uuid::try_v4();
|
||||
Void::Testing::require(uuid.has_value());
|
||||
ManifestData m;
|
||||
m.database_uuid = *uuid;
|
||||
m.generation = 5;
|
||||
m.wal_segments = {1};
|
||||
auto enc = encode_manifest(m, 65536);
|
||||
Void::Testing::require(enc.has_value());
|
||||
write_raw_bytes(dir.path / make_manifest_filename(5), *enc);
|
||||
|
||||
OpenOptions opts;
|
||||
opts.directory = dir.path;
|
||||
auto r = Engine::open(opts);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect(r.error().code().value ==
|
||||
static_cast<std::int32_t>(StorageErrorCode::incomplete_init));
|
||||
}
|
||||
|
||||
// 2. Truncate EVERY byte offset across a multi-batch WAL & test reopen recovery!
|
||||
TempStorageDir base_dir;
|
||||
OpenOptions base_opts;
|
||||
base_opts.directory = base_dir.path;
|
||||
base_opts.limits.max_batch_encoded_bytes = 4096;
|
||||
base_opts.limits.wal_segment_target_bytes = 4096; // force small target for rotation later
|
||||
|
||||
std::vector<Sequence> expected_seqs;
|
||||
{
|
||||
auto eng = Engine::open(base_opts);
|
||||
Void::Testing::require(eng.has_value());
|
||||
for (int i = 1; i <= 2; ++i) {
|
||||
Batch b;
|
||||
b.put(std::string(1, static_cast<char>('a' + i - 1)), std::to_string(i));
|
||||
auto wr = eng->write(std::move(b), Durability::Sync);
|
||||
Void::Testing::require(wr.has_value());
|
||||
expected_seqs.push_back(wr->sequence);
|
||||
}
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
|
||||
const auto orig_wal_path = base_dir.path / make_wal_filename(1);
|
||||
OwnedBytes orig_wal_bytes;
|
||||
{
|
||||
auto port = make_posix_file_port();
|
||||
auto sz = port->file_size(orig_wal_path);
|
||||
Void::Testing::require(sz.has_value());
|
||||
orig_wal_bytes.resize(*sz);
|
||||
auto f = port->open_file(orig_wal_path, FileOpenMode::ReadOnly);
|
||||
Void::Testing::require(f.has_value());
|
||||
Void::Testing::require((*f)->pread_exact(0, orig_wal_bytes).has_value());
|
||||
}
|
||||
|
||||
// Sweep EVERY truncation length from kWalSegmentHeaderSize up to orig_wal_bytes.size()
|
||||
for (std::size_t cut = kWalSegmentHeaderSize; cut <= orig_wal_bytes.size(); ++cut) {
|
||||
TempStorageDir copy_dir;
|
||||
std::filesystem::copy(
|
||||
base_dir.path, copy_dir.path,
|
||||
std::filesystem::copy_options::recursive |
|
||||
std::filesystem::copy_options::overwrite_existing);
|
||||
(void)std::filesystem::remove(copy_dir.path / "LOCK");
|
||||
{
|
||||
auto port = make_posix_file_port();
|
||||
auto wf = port->open_file(
|
||||
copy_dir.path / make_wal_filename(1), FileOpenMode::ReadWriteExisting);
|
||||
Void::Testing::require(wf.has_value());
|
||||
Void::Testing::require((*wf)->truncate(cut).has_value());
|
||||
Void::Testing::require((*wf)->sync().has_value());
|
||||
}
|
||||
OpenOptions ropts;
|
||||
ropts.directory = copy_dir.path;
|
||||
ropts.limits = base_opts.limits;
|
||||
auto eng = Engine::open(ropts);
|
||||
Void::Testing::require(eng.has_value());
|
||||
const auto st1 = eng->stats();
|
||||
Void::Testing::expect(st1.committed_sequence <= 3);
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
|
||||
// Idempotent second recovery!
|
||||
auto eng2 = Engine::open(ropts);
|
||||
Void::Testing::require(eng2.has_value());
|
||||
Void::Testing::expect_eq(eng2->stats().committed_sequence, st1.committed_sequence);
|
||||
Void::Testing::expect_eq(eng2->stats().recovery_truncated_bytes, static_cast<std::uint64_t>(0));
|
||||
Void::Testing::require(eng2->close().has_value());
|
||||
}
|
||||
|
||||
// 3. Complete record with single-bit corruption (including final byte!) MUST fail closed (Corrupt)
|
||||
{
|
||||
TempStorageDir bad_dir;
|
||||
std::filesystem::copy(base_dir.path, bad_dir.path,
|
||||
std::filesystem::copy_options::overwrite_existing);
|
||||
(void)std::filesystem::remove(bad_dir.path / "LOCK");
|
||||
{
|
||||
auto port = make_posix_file_port();
|
||||
auto wf = port->open_file(
|
||||
bad_dir.path / make_wal_filename(1), FileOpenMode::ReadWriteExisting);
|
||||
Void::Testing::require(wf.has_value());
|
||||
auto b = orig_wal_bytes;
|
||||
b[b.size() - 12] ^= std::byte{0x04}; // flip inside final complete COMMIT trailer/payload
|
||||
Void::Testing::require((*wf)->pwrite_all(0, b).has_value());
|
||||
Void::Testing::require((*wf)->sync().has_value());
|
||||
}
|
||||
OpenOptions ropts = base_opts;
|
||||
ropts.directory = bad_dir.path;
|
||||
auto r = Engine::open(ropts);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect(r.error().kind() == Void::Result::ErrorKind::corrupt);
|
||||
}
|
||||
|
||||
// 4. WAL segment rotation across multiple small batches preserves full recovery
|
||||
{
|
||||
TempStorageDir rot_dir;
|
||||
OpenOptions ropts;
|
||||
ropts.directory = rot_dir.path;
|
||||
ropts.limits.max_batch_encoded_bytes = 256;
|
||||
ropts.limits.wal_segment_target_bytes = 384; // rotate every ~2 batches!
|
||||
|
||||
auto eng = Engine::open(ropts);
|
||||
Void::Testing::require(eng.has_value());
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
Batch b;
|
||||
b.put("r/" + std::to_string(i), std::string(48, static_cast<char>('A' + i)));
|
||||
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
|
||||
}
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
|
||||
auto reopened = Engine::open(ropts);
|
||||
Void::Testing::require(reopened.has_value());
|
||||
Void::Testing::expect_eq(reopened->stats().committed_sequence, static_cast<Sequence>(10));
|
||||
auto s = reopened->snapshot();
|
||||
Void::Testing::require(s.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
reopened->get(*s, "r/9")->as_string_view(),
|
||||
std::string_view{std::string(48, 'J')});
|
||||
s->reset();
|
||||
Void::Testing::require(reopened->close().has_value());
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test storage_fault_injected_crashes_sync_unknown_checkpoint_and_compaction()
|
||||
{
|
||||
// 1. Initial CURRENT creation failure -> directory fails incomplete_init on reopen
|
||||
{
|
||||
TempStorageDir dir;
|
||||
auto fp = std::make_shared<FaultInjectingFilePort>();
|
||||
fp->add_rule(FaultRule{
|
||||
.op = FaultOp::Rename,
|
||||
.path_contains = "CURRENT",
|
||||
.hit_index = 1,
|
||||
.error_code = StorageErrorCode::io_error});
|
||||
OpenOptions opts;
|
||||
opts.directory = dir.path;
|
||||
opts.file_port = fp;
|
||||
Void::Testing::expect(!Engine::open(opts).has_value());
|
||||
|
||||
OpenOptions clean_opts;
|
||||
clean_opts.directory = dir.path;
|
||||
auto reopen = Engine::open(clean_opts);
|
||||
Void::Testing::expect(!reopen.has_value());
|
||||
Void::Testing::expect(reopen.error().code().value ==
|
||||
static_cast<std::int32_t>(StorageErrorCode::incomplete_init));
|
||||
}
|
||||
|
||||
// 2. Sync failure AFTER append -> Outcome::Unknown + RecoveryRequired,
|
||||
// existing snapshots keep reading last published state, reopen recovers persisted batch!
|
||||
{
|
||||
TempStorageDir dir;
|
||||
auto fp = std::make_shared<FaultInjectingFilePort>();
|
||||
OpenOptions opts;
|
||||
opts.directory = dir.path;
|
||||
opts.file_port = fp;
|
||||
auto eng = Engine::open(opts);
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
{
|
||||
Batch b1;
|
||||
b1.put("k", "v1");
|
||||
Void::Testing::require(eng->write(std::move(b1), Durability::Sync).has_value());
|
||||
}
|
||||
auto pre_snap = eng->snapshot();
|
||||
Void::Testing::require(pre_snap.has_value());
|
||||
|
||||
// Inject fsync failure on next WAL sync!
|
||||
fp->add_rule(FaultRule{
|
||||
.op = FaultOp::SyncFile,
|
||||
.path_contains = "WAL-",
|
||||
.hit_index = 1,
|
||||
.error_code = StorageErrorCode::io_error});
|
||||
{
|
||||
Batch b2;
|
||||
b2.put("k", "v2");
|
||||
auto wr = eng->write(std::move(b2), Durability::Sync);
|
||||
Void::Testing::expect(!wr.has_value());
|
||||
Void::Testing::expect(wr.error().outcome == Outcome::Unknown);
|
||||
}
|
||||
Void::Testing::expect(eng->state() == EngineState::RecoveryRequired);
|
||||
// Existing snapshot still sees pre-failure published v1!
|
||||
Void::Testing::expect_eq(eng->get(*pre_snap, "k")->as_string_view(), std::string_view{"v1"});
|
||||
// Further writes rejected cleanly
|
||||
{
|
||||
Batch b3;
|
||||
b3.put("k", "v3");
|
||||
auto wr3 = eng->write(std::move(b3), Durability::Sync);
|
||||
Void::Testing::expect(!wr3.has_value());
|
||||
Void::Testing::expect(wr3.error().outcome == Outcome::NotCommitted);
|
||||
}
|
||||
pre_snap->reset();
|
||||
(void)eng->close();
|
||||
|
||||
// Clean reopen recovers v2 because COMMIT was appended before fsync error!
|
||||
OpenOptions clean_opts;
|
||||
clean_opts.directory = dir.path;
|
||||
auto eng2 = Engine::open(clean_opts);
|
||||
Void::Testing::require(eng2.has_value());
|
||||
auto s2 = eng2->snapshot();
|
||||
Void::Testing::require(s2.has_value());
|
||||
Void::Testing::expect_eq(eng2->get(*s2, "k")->as_string_view(), std::string_view{"v2"});
|
||||
s2->reset();
|
||||
Void::Testing::require(eng2->close().has_value());
|
||||
}
|
||||
|
||||
// 3. Checkpoint failure before CURRENT rename leaves previous generation intact,
|
||||
// and slow Snapshot pins keep obsolete compacted tables alive until released!
|
||||
{
|
||||
TempStorageDir dir;
|
||||
auto fp = std::make_shared<FaultInjectingFilePort>();
|
||||
OpenOptions opts;
|
||||
opts.directory = dir.path;
|
||||
opts.file_port = fp;
|
||||
auto eng = Engine::open(opts);
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
// Create key k across 2 checkpoints so we have 2 immutable tables + a pinned snapshot!
|
||||
{
|
||||
Batch b;
|
||||
b.put("alpha", "gen1");
|
||||
b.put("beta", "keep");
|
||||
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
|
||||
}
|
||||
Void::Testing::require(eng->checkpoint().has_value());
|
||||
|
||||
auto snap_v1 = eng->snapshot();
|
||||
Void::Testing::require(snap_v1.has_value());
|
||||
|
||||
{
|
||||
Batch b;
|
||||
b.put("alpha", "gen2");
|
||||
b.erase("beta");
|
||||
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
|
||||
}
|
||||
Void::Testing::require(eng->checkpoint().has_value());
|
||||
|
||||
// Inject checkpoint rename failure on CURRENT -> old generation remains authoritative on reopen!
|
||||
{
|
||||
Batch b;
|
||||
b.put("alpha", "gen3_in_wal");
|
||||
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
|
||||
}
|
||||
fp->add_rule(FaultRule{
|
||||
.op = FaultOp::Rename,
|
||||
.path_contains = "CURRENT",
|
||||
.hit_index = 1,
|
||||
.error_code = StorageErrorCode::io_error});
|
||||
Void::Testing::expect(!eng->checkpoint().has_value());
|
||||
Void::Testing::expect(eng->state() == EngineState::RecoveryRequired);
|
||||
snap_v1->reset();
|
||||
(void)eng->close();
|
||||
|
||||
// Clean reopen still recovers gen3 cleanly!
|
||||
OpenOptions clean_opts;
|
||||
clean_opts.directory = dir.path;
|
||||
auto eng2 = Engine::open(clean_opts);
|
||||
Void::Testing::require(eng2.has_value());
|
||||
auto s_latest = eng2->snapshot();
|
||||
Void::Testing::require(s_latest.has_value());
|
||||
Void::Testing::expect_eq(eng2->get(*s_latest, "alpha")->as_string_view(),
|
||||
std::string_view{"gen3_in_wal"});
|
||||
Void::Testing::require(eng2->checkpoint().has_value());
|
||||
|
||||
// Now pin s_latest and trigger compaction across multiple tables!
|
||||
Void::Testing::require(eng2->stats().active_table_count >= 2);
|
||||
Void::Testing::require(eng2->compact().has_value());
|
||||
Void::Testing::expect(eng2->stats().obsolete_pinned_bytes > 0);
|
||||
Void::Testing::expect_eq(eng2->get(*s_latest, "alpha")->as_string_view(),
|
||||
std::string_view{"gen3_in_wal"});
|
||||
|
||||
// Dropping s_latest releases the pin and lets obsolete files be reclaimed!
|
||||
s_latest->reset();
|
||||
Void::Testing::expect_eq(eng2->stats().obsolete_pinned_bytes, static_cast<std::uint64_t>(0));
|
||||
Void::Testing::require(eng2->close().has_value());
|
||||
}
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> drive_stop_before_append_test(
|
||||
AsyncStorageAdapter& adapter,
|
||||
std::expected<CommitReceipt, WriteFailure>* out,
|
||||
bool* done)
|
||||
{
|
||||
co_await run_async_stop_before_append(adapter, out, done);
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> drive_tracked_write_test(
|
||||
AsyncStorageAdapter& adapter,
|
||||
std::string key,
|
||||
std::string val,
|
||||
std::stop_token st,
|
||||
std::expected<CommitReceipt, WriteFailure>* out,
|
||||
std::atomic<int>* deliveries,
|
||||
bool* done)
|
||||
{
|
||||
co_await run_async_write_tracked(
|
||||
adapter, std::move(key), std::move(val), st, out, deliveries, done);
|
||||
}
|
||||
|
||||
Void::Testing::Test storage_tools_verify_backup_restore_salvage_and_async_stop_races()
|
||||
{
|
||||
TempStorageDir dir;
|
||||
TempStorageDir backup_dir;
|
||||
TempStorageDir restore_dir;
|
||||
TempStorageDir salvage_dir;
|
||||
|
||||
// 1. Live export_backup, offline verify_directory, block-level corruption detection, restore & salvage
|
||||
{
|
||||
OpenOptions opts;
|
||||
opts.directory = dir.path;
|
||||
auto eng = Engine::open(opts);
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
{
|
||||
Batch b;
|
||||
b.put("t1", std::string(1024, 'X'));
|
||||
b.put("t2", std::string(1024, 'Y'));
|
||||
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
|
||||
}
|
||||
Void::Testing::require(eng->checkpoint().has_value());
|
||||
{
|
||||
Batch b;
|
||||
b.put("w1", "after_ckpt");
|
||||
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
|
||||
}
|
||||
|
||||
// Backup while engine remains open
|
||||
Void::Testing::require(eng->export_backup(backup_dir.path).has_value());
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
|
||||
// Offline verify_directory passes on backup
|
||||
auto vr = verify_directory(backup_dir.path);
|
||||
Void::Testing::require(vr.has_value());
|
||||
Void::Testing::expect(vr->tables_verified >= 1);
|
||||
Void::Testing::expect(vr->blocks_verified >= 1);
|
||||
|
||||
// Restore backup into restore_dir and verify data
|
||||
Void::Testing::require(restore_backup(backup_dir.path, restore_dir.path).has_value());
|
||||
OpenOptions r_opts;
|
||||
r_opts.directory = restore_dir.path;
|
||||
auto reng = Engine::open(r_opts);
|
||||
Void::Testing::require(reng.has_value());
|
||||
auto rs = reng->snapshot();
|
||||
Void::Testing::require(rs.has_value());
|
||||
Void::Testing::expect_eq(reng->get(*rs, "w1")->as_string_view(), std::string_view{"after_ckpt"});
|
||||
Void::Testing::expect_eq(reng->get(*rs, "t1")->bytes.size(), static_cast<std::size_t>(1024));
|
||||
rs->reset();
|
||||
Void::Testing::require(reng->close().has_value());
|
||||
|
||||
// Corrupt a single bit inside table data block in dir -> verify_directory fails!
|
||||
for (const auto& entry : std::filesystem::directory_iterator(dir.path)) {
|
||||
const auto name = entry.path().filename().string();
|
||||
if (name.starts_with("TABLE-") && name.ends_with(".vtbl")) {
|
||||
auto port = make_posix_file_port();
|
||||
auto tf = port->open_file(entry.path(), FileOpenMode::ReadWriteExisting);
|
||||
Void::Testing::require(tf.has_value());
|
||||
std::byte b{};
|
||||
Void::Testing::require((*tf)->pread_exact(kTableHeaderSize + 12, std::span{&b, 1}).has_value());
|
||||
b ^= std::byte{0x01};
|
||||
Void::Testing::require((*tf)->pwrite_all(kTableHeaderSize + 12, ByteView{&b, 1}).has_value());
|
||||
Void::Testing::require((*tf)->sync().has_value());
|
||||
break;
|
||||
}
|
||||
}
|
||||
auto bad_vr = verify_directory(dir.path);
|
||||
Void::Testing::expect(!bad_vr.has_value());
|
||||
Void::Testing::expect(bad_vr.error().kind() == Void::Result::ErrorKind::corrupt);
|
||||
|
||||
// Same-directory salvage refused
|
||||
auto same_sal = salvage_directory(dir.path, dir.path);
|
||||
Void::Testing::expect(!same_sal.has_value());
|
||||
|
||||
// Salvage backup (or WAL) to separate salvage_dir succeeds!
|
||||
auto sal = salvage_directory(backup_dir.path, salvage_dir.path);
|
||||
Void::Testing::require(sal.has_value());
|
||||
Void::Testing::expect(sal->keys_recovered >= 3);
|
||||
}
|
||||
|
||||
// 2. AsyncStorageAdapter C-03 stop-race conformance
|
||||
{
|
||||
TempStorageDir adir;
|
||||
auto fp = std::make_shared<FaultInjectingFilePort>();
|
||||
OpenOptions opts;
|
||||
opts.directory = adir.path;
|
||||
opts.file_port = fp;
|
||||
auto eng = Engine::open(opts);
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
Void::Async::ManualExecutor exec;
|
||||
AsyncStorageAdapter adapter{*eng, AsyncAdapterOptions{}, &exec};
|
||||
|
||||
// Case A: stop before append -> Outcome::NotCommitted
|
||||
{
|
||||
std::expected<CommitReceipt, WriteFailure> out = CommitReceipt{};
|
||||
bool done = false;
|
||||
auto t = drive_stop_before_append_test(adapter, &out, &done);
|
||||
t.handle().resume();
|
||||
Void::Testing::expect(done);
|
||||
Void::Testing::expect(!out.has_value());
|
||||
Void::Testing::expect(out.error().outcome == Outcome::NotCommitted);
|
||||
}
|
||||
|
||||
// Case B: stop requested WHILE WAL sync is pending, then sync SUCCEEDS ->
|
||||
// must still publish index and deliver CommitReceipt once (no stolen cancel!)
|
||||
{
|
||||
std::atomic<bool> in_sync{false};
|
||||
std::atomic<bool> release_sync{false};
|
||||
fp->set_pause_before_sync([&]() {
|
||||
in_sync.store(true, std::memory_order_release);
|
||||
while (!release_sync.load(std::memory_order_acquire)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||
}
|
||||
});
|
||||
|
||||
std::stop_source ss;
|
||||
std::expected<CommitReceipt, WriteFailure> out =
|
||||
std::unexpected{WriteFailure{{}, Outcome::Unknown}};
|
||||
std::atomic<int> deliveries{0};
|
||||
bool done = false;
|
||||
auto t = drive_tracked_write_test(
|
||||
adapter, "race_ok", "persisted", ss.get_token(), &out, &deliveries, &done);
|
||||
t.handle().resume();
|
||||
|
||||
while (!in_sync.load(std::memory_order_acquire)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||
}
|
||||
// Stop while sync is pending: nothing delivered yet!
|
||||
ss.request_stop();
|
||||
exec.drain();
|
||||
Void::Testing::expect(!done);
|
||||
Void::Testing::expect_eq(deliveries.load(), 0);
|
||||
|
||||
// Let sync succeed -> CommitReceipt delivered exactly once & visible!
|
||||
release_sync.store(true, std::memory_order_release);
|
||||
while (!done) {
|
||||
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||
}
|
||||
fp->set_pause_before_sync({});
|
||||
Void::Testing::expect_eq(deliveries.load(), 1);
|
||||
Void::Testing::require(out.has_value());
|
||||
auto snap = eng->snapshot();
|
||||
Void::Testing::require(snap.has_value());
|
||||
Void::Testing::expect_eq(eng->get(*snap, "race_ok")->as_string_view(),
|
||||
std::string_view{"persisted"});
|
||||
}
|
||||
|
||||
// Case C: sync FAILS after append while stop requested -> Outcome::Unknown + RecoveryRequired, single delivery
|
||||
{
|
||||
std::atomic<bool> in_sync{false};
|
||||
std::atomic<bool> release_sync{false};
|
||||
fp->set_pause_before_sync([&]() {
|
||||
in_sync.store(true, std::memory_order_release);
|
||||
while (!release_sync.load(std::memory_order_acquire)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||
}
|
||||
});
|
||||
fp->add_rule(FaultRule{
|
||||
.op = FaultOp::SyncFile,
|
||||
.path_contains = "WAL-",
|
||||
.hit_index = 1,
|
||||
.error_code = StorageErrorCode::io_error});
|
||||
std::stop_source live_ss;
|
||||
std::expected<CommitReceipt, WriteFailure> out = CommitReceipt{};
|
||||
std::atomic<int> deliveries{0};
|
||||
bool done = false;
|
||||
auto t = drive_tracked_write_test(
|
||||
adapter, "race_fail", "uncertain", live_ss.get_token(), &out, &deliveries, &done);
|
||||
t.handle().resume();
|
||||
while (!in_sync.load(std::memory_order_acquire)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||
}
|
||||
live_ss.request_stop();
|
||||
release_sync.store(true, std::memory_order_release);
|
||||
while (!done) {
|
||||
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||
}
|
||||
fp->set_pause_before_sync({});
|
||||
Void::Testing::expect_eq(deliveries.load(), 1);
|
||||
Void::Testing::expect(!out.has_value());
|
||||
Void::Testing::expect(out.error().outcome == Outcome::Unknown);
|
||||
Void::Testing::expect(eng->state() == EngineState::RecoveryRequired);
|
||||
}
|
||||
|
||||
adapter.close_and_join();
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
Reference in new issue
Block a user