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

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

No files matched your search

+72
View File
@@ -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
+93
View File
@@ -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
+83
View File
@@ -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
+147
View File
@@ -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
+145
View File
@@ -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
+216
View File
@@ -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
+10
View File
@@ -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>
+54
View File
@@ -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
+381
View File
@@ -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