Files
aevolution/include/evo/network/grant_ledger.hpp
T

45 lines
1.7 KiB
C++

#pragma once
#include "evo/network/admission.hpp"
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <expected>
#include <filesystem>
#include <memory>
#include <span>
#include <utility>
#include <vector>
// Durable record of consumed dev grants (ADR-0083), so a replacement region process
// refuses grants its predecessor already used. Append-only text lines
// "<grant id hex> <expires_at>", flushed and fsynced before the session is welcomed.
// Opening drops expired entries by an atomic rewrite. Corrupt content, I/O failure or
// a full ledger fail closed. Exclusive lifetime ownership via a stable .lock file; not a general
// database.
namespace evo::network {
enum class LedgerError : std::uint8_t { io, corrupt, full, busy };
class GrantLedger {
public:
static constexpr std::size_t max_entries = 65536;
[[nodiscard]] static std::expected<std::unique_ptr<GrantLedger>, LedgerError>
open(const std::filesystem::path& path, std::uint64_t now_seconds);
GrantLedger(const GrantLedger&) = delete;
GrantLedger& operator=(const GrantLedger&) = delete;
~GrantLedger();
// Unexpired entries loaded at open (for SessionAdmission::remember).
[[nodiscard]] std::span<const ConsumedGrant> loaded() const noexcept {
return loaded_;
}
// Durable once this returns success.
[[nodiscard]] std::expected<void, LedgerError> record(ConsumedGrant grant);
private:
struct Lock;
GrantLedger(std::FILE* file, std::vector<ConsumedGrant> loaded, std::unique_ptr<Lock> lock);
std::unique_ptr<Lock> lock_; // Outlives the append handle; never unlink its pathname.
std::FILE* file_;
std::vector<ConsumedGrant> loaded_;
std::size_t entries_;
};
} // namespace evo::network