Integrate bounded checkpoint reads with stable logistics identities
This commit is contained in:
commit
4ba64f7e62
8 files changed
+731
-3
No files matched your search
@@ -16,6 +16,7 @@
|
||||
namespace settlement {
|
||||
|
||||
inline constexpr std::uint32_t checkpoint_version = 1;
|
||||
inline constexpr std::string_view checkpoint_signature = "STHCHKPT";
|
||||
inline constexpr std::size_t max_checkpoint_body_bytes = 128 * 1024 * 1024;
|
||||
inline constexpr std::size_t max_checkpoint_metadata_bytes = 64 * 1024;
|
||||
inline constexpr std::size_t max_checkpoint_bytes =
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/save_service.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
enum class CheckpointFileError {
|
||||
Io, TooLarge, UnsupportedFormat, InvalidCheckpoint, InvalidLegacy,
|
||||
IdentityGeneration, ResourceFailure, ReaderFailure,
|
||||
};
|
||||
|
||||
struct CheckpointFileDiagnostic {
|
||||
CheckpointFileError code;
|
||||
std::string message;
|
||||
std::uint32_t native_error = 0;
|
||||
// Present for a modern codec failure, including the exact incompatible package.
|
||||
std::optional<CheckpointDiagnostic> checkpoint;
|
||||
};
|
||||
|
||||
using CheckpointLoadResult = std::expected<WorldCheckpoint, CheckpointFileDiagnostic>;
|
||||
enum class CheckpointLoadAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted };
|
||||
|
||||
struct CheckpointLoadSubmission {
|
||||
CheckpointLoadAdmission admission = CheckpointLoadAdmission::InvalidRequest;
|
||||
std::uint64_t request_id = 0;
|
||||
std::future<CheckpointLoadResult> completion;
|
||||
};
|
||||
|
||||
enum class CheckpointReadPhase { Opened, BeforeRead };
|
||||
|
||||
struct CheckpointFilesOptions {
|
||||
std::size_t load_capacity = 4; // Includes the running read.
|
||||
std::size_t save_capacity = 8;
|
||||
std::size_t max_load_bytes = max_checkpoint_bytes;
|
||||
// Diagnostic/test seam on the reader. Captures must outlive shutdown.
|
||||
// Calling shutdown from this observer throws logic_error.
|
||||
std::function<void(CheckpointReadPhase)> read_observer;
|
||||
};
|
||||
|
||||
// Keep one instance for the window lifetime so accepted saves retain FIFO order
|
||||
// across world/session replacements. Workers own their paths, catalog and held
|
||||
// snapshots. The caller owns load-ticket fencing and UI completion handling.
|
||||
class CheckpointFiles {
|
||||
public:
|
||||
explicit CheckpointFiles(CheckpointFilesOptions options = {});
|
||||
explicit CheckpointFiles(std::vector<RulePackage> installed, CheckpointFilesOptions options = {});
|
||||
~CheckpointFiles();
|
||||
CheckpointFiles(const CheckpointFiles&) = delete;
|
||||
CheckpointFiles& operator=(const CheckpointFiles&) = delete;
|
||||
|
||||
// Obtain a healthy immutable view with SimulationRuntime::snapshot_for_save().
|
||||
// Materialization runs on the existing SaveService writer, bounded to
|
||||
// max_checkpoint_bytes. Rejected calls do not retain the snapshot.
|
||||
[[nodiscard]] SaveSubmission try_save(
|
||||
const std::filesystem::path& destination,
|
||||
const std::shared_ptr<const PublishedSnapshot>& snapshot);
|
||||
// Opens once and checks actual size/EOF under the byte limit. Modern failures
|
||||
// retain their diagnostics. Legacy imports receive a fresh stable world UUID
|
||||
// and the exact supported default manifest from this instance's catalog.
|
||||
[[nodiscard]] CheckpointLoadSubmission try_load(
|
||||
const std::filesystem::path& source, std::size_t workers = min_worker_count,
|
||||
ExecutionMode mode = ExecutionMode::Parallel);
|
||||
// Closes admission and drains both services, without holding the admission
|
||||
// mutex while joining. Destruction requires callers to stop using this object.
|
||||
void shutdown();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace settlement
|
||||
@@ -16,7 +16,6 @@
|
||||
namespace settlement {
|
||||
namespace {
|
||||
|
||||
constexpr std::string_view magic = "STHCHKPT";
|
||||
constexpr std::size_t header_size = 24;
|
||||
constexpr std::size_t digest_size = 32;
|
||||
constexpr std::size_t fixed_metadata_size = 68;
|
||||
@@ -173,7 +172,7 @@ std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
}
|
||||
std::string bytes(header_size + metadata_size + body.size() + digest_size, '\0');
|
||||
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}));
|
||||
put_bytes(writer, wire_bytes(magic));
|
||||
put_bytes(writer, wire_bytes(checkpoint_signature));
|
||||
put(writer, checkpoint_version);
|
||||
put(writer, static_cast<std::uint32_t>(metadata_size));
|
||||
put(writer, static_cast<std::uint64_t>(body.size()));
|
||||
@@ -210,7 +209,7 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
fail(CheckpointError::InvalidFrame, "frame", "Checkpoint is incomplete.");
|
||||
}
|
||||
Void::Binary::Reader header(wire_bytes(bytes).first(header_size));
|
||||
if (!std::ranges::equal(get_bytes(header, magic.size(), "magic"), wire_bytes(magic))) {
|
||||
if (!std::ranges::equal(get_bytes(header, checkpoint_signature.size(), "magic"), wire_bytes(checkpoint_signature))) {
|
||||
fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match.");
|
||||
}
|
||||
if (get<std::uint32_t>(header, "version") != checkpoint_version) {
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
#include "settlement/core/checkpoint_files.hpp"
|
||||
|
||||
#include <Void/Async/FuturePool.hpp>
|
||||
#include <Void/Async/ThreadExecutor.hpp>
|
||||
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <spanstream>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
|
||||
constexpr std::string_view legacy_signature = "SETTLERS";
|
||||
|
||||
bool valid_path(const std::filesystem::path& path) {
|
||||
return path.is_absolute() && !path.filename().empty() &&
|
||||
path.native().find(L'\0') == std::wstring::npos;
|
||||
}
|
||||
|
||||
std::vector<RulePackage> default_catalog() {
|
||||
auto catalog = builtin_rule_packages();
|
||||
if (!catalog) throw std::runtime_error(catalog.error().message);
|
||||
return std::move(*catalog);
|
||||
}
|
||||
|
||||
struct OpenFile {
|
||||
HANDLE handle;
|
||||
~OpenFile() { CloseHandle(handle); }
|
||||
};
|
||||
|
||||
CheckpointFileDiagnostic diagnostic(CheckpointFileError code, std::string message,
|
||||
std::uint32_t native_error = 0) {
|
||||
return {code, std::move(message), native_error, std::nullopt};
|
||||
}
|
||||
|
||||
// Void::FileSystem::read_file_bounded is unsupported on Windows at the pin.
|
||||
// https://git.faumaray.com/Void/Library/issues/9 tracks this adapter's replacement.
|
||||
// Reuse it after checkpoint-file tests prove one-handle reads, Unicode paths,
|
||||
// initial/growing-file limits, EOF checking and independent bounded admission.
|
||||
CheckpointLoadResult prepare(const std::filesystem::path& path,
|
||||
std::span<const RulePackage> catalog,
|
||||
const CheckpointFilesOptions& options,
|
||||
std::size_t workers, ExecutionMode mode) {
|
||||
try {
|
||||
OpenFile file{CreateFileW(path.c_str(), GENERIC_READ,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
|
||||
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr)};
|
||||
if (file.handle == INVALID_HANDLE_VALUE) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::Io,
|
||||
"Could not open the checkpoint file.", GetLastError())};
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
if (GetFileType(file.handle) != FILE_TYPE_DISK || !GetFileSizeEx(file.handle, &size)) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::Io,
|
||||
"Could not determine the checkpoint file size.", GetLastError())};
|
||||
}
|
||||
if (size.QuadPart < 0 ||
|
||||
static_cast<std::uint64_t>(size.QuadPart) > options.max_load_bytes) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::TooLarge,
|
||||
"Checkpoint file exceeds the configured byte limit.")};
|
||||
}
|
||||
if (options.read_observer) options.read_observer(CheckpointReadPhase::Opened);
|
||||
std::string bytes;
|
||||
bytes.reserve(static_cast<std::size_t>(size.QuadPart));
|
||||
std::array<char, 65536> buffer;
|
||||
for (;;) {
|
||||
if (options.read_observer) options.read_observer(CheckpointReadPhase::BeforeRead);
|
||||
DWORD count = 0;
|
||||
if (!ReadFile(file.handle, buffer.data(), static_cast<DWORD>(buffer.size()), &count, nullptr)) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::Io,
|
||||
"Could not read the checkpoint file.", GetLastError())};
|
||||
}
|
||||
if (count == 0) break;
|
||||
if (count > options.max_load_bytes - bytes.size()) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::TooLarge,
|
||||
"Checkpoint file grew beyond the configured byte limit.")};
|
||||
}
|
||||
bytes.append(buffer.data(), count);
|
||||
}
|
||||
if (bytes.starts_with(checkpoint_signature)) {
|
||||
auto candidate = decode_checkpoint(bytes, catalog, workers, mode);
|
||||
if (!candidate) {
|
||||
CheckpointFileDiagnostic error{CheckpointFileError::InvalidCheckpoint,
|
||||
candidate.error().message, 0, std::move(candidate.error())};
|
||||
return std::unexpected{std::move(error)};
|
||||
}
|
||||
return std::move(*candidate);
|
||||
}
|
||||
if (!bytes.starts_with(legacy_signature)) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::UnsupportedFormat,
|
||||
"File has neither a checkpoint nor a legacy settlement signature.")};
|
||||
}
|
||||
auto defaults = default_rules_manifest();
|
||||
if (!defaults) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::ResourceFailure,
|
||||
defaults.error().message)};
|
||||
}
|
||||
std::vector<std::string> selected;
|
||||
selected.reserve(defaults->packages().size());
|
||||
for (const auto& package : defaults->packages()) selected.push_back(package.id);
|
||||
auto installed_defaults = resolve_rules(catalog, selected);
|
||||
if (!installed_defaults || *installed_defaults != *defaults) {
|
||||
CheckpointDiagnostic detail{CheckpointError::RulesMismatch, "rules.packages", {},
|
||||
"Legacy imports require the exact supported default packages."};
|
||||
if (!installed_defaults) {
|
||||
detail.package = installed_defaults.error().package;
|
||||
detail.message = installed_defaults.error().message;
|
||||
} else {
|
||||
for (const auto& package : defaults->packages()) {
|
||||
const auto found = std::find(installed_defaults->packages().begin(),
|
||||
installed_defaults->packages().end(), package);
|
||||
if (found == installed_defaults->packages().end()) {
|
||||
detail.package = package.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return std::unexpected{CheckpointFileDiagnostic{CheckpointFileError::InvalidCheckpoint,
|
||||
detail.message, 0, std::move(detail)}};
|
||||
}
|
||||
std::unique_ptr<World> world;
|
||||
try {
|
||||
std::ispanstream input{std::span<const char>{bytes.data(), bytes.size()}};
|
||||
world = World::read_save(input, workers, mode);
|
||||
} catch (const std::bad_alloc&) {
|
||||
throw;
|
||||
} catch (const std::exception& error) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::InvalidLegacy, error.what())};
|
||||
}
|
||||
const auto id = Void::Uuid::try_v4();
|
||||
if (!id || id->is_nil()) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::IdentityGeneration,
|
||||
"Could not create an identity for the imported world.")};
|
||||
}
|
||||
return WorldCheckpoint{std::move(world), *id, 1, std::move(*installed_defaults)};
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::ResourceFailure, "Out of memory.")};
|
||||
} catch (const std::exception& error) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::ReaderFailure, error.what())};
|
||||
} catch (...) {
|
||||
return std::unexpected{diagnostic(CheckpointFileError::ReaderFailure, "Checkpoint reader failed.")};
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct CheckpointFiles::Impl {
|
||||
Impl(std::vector<RulePackage> catalog, CheckpointFilesOptions configured)
|
||||
: options(std::move(configured)), installed(std::move(catalog)),
|
||||
writer(SaveServiceOptions{.capacity = options.save_capacity,
|
||||
.max_bytes = max_checkpoint_bytes, .fault_hook = {}}) {
|
||||
if (options.load_capacity == 0 || options.max_load_bytes == 0 ||
|
||||
options.max_load_bytes > max_checkpoint_bytes) {
|
||||
throw std::invalid_argument("checkpoint reader limits are invalid");
|
||||
}
|
||||
auto created = Void::Async::ThreadExecutor::create(
|
||||
{.workers = 1, .max_admitted = options.load_capacity});
|
||||
if (!created) throw std::runtime_error("cannot create checkpoint reader");
|
||||
executor = std::move(*created);
|
||||
pool = std::make_unique<Void::Async::FuturePool>(*executor);
|
||||
if (!executor->start()) throw std::runtime_error("cannot start checkpoint reader");
|
||||
}
|
||||
|
||||
CheckpointFilesOptions options;
|
||||
std::vector<RulePackage> installed;
|
||||
SaveService writer;
|
||||
std::unique_ptr<Void::Async::ThreadExecutor> executor;
|
||||
std::unique_ptr<Void::Async::FuturePool> pool;
|
||||
std::mutex admission_mutex;
|
||||
bool closed = false;
|
||||
std::uint64_t next_id = 1;
|
||||
};
|
||||
|
||||
CheckpointFiles::CheckpointFiles(CheckpointFilesOptions options)
|
||||
: CheckpointFiles(default_catalog(), std::move(options)) {}
|
||||
|
||||
CheckpointFiles::CheckpointFiles(std::vector<RulePackage> installed, CheckpointFilesOptions options)
|
||||
: impl_(std::make_unique<Impl>(std::move(installed), std::move(options))) {}
|
||||
|
||||
CheckpointFiles::~CheckpointFiles() { shutdown(); }
|
||||
|
||||
SaveSubmission CheckpointFiles::try_save(
|
||||
const std::filesystem::path& destination,
|
||||
const std::shared_ptr<const PublishedSnapshot>& snapshot) {
|
||||
std::unique_lock lock(impl_->admission_mutex, std::try_to_lock);
|
||||
if (!lock.owns_lock()) return {SaveAdmission::Busy, 0, {}};
|
||||
if (impl_->closed) return {SaveAdmission::Closed, 0, {}};
|
||||
if (!snapshot || !snapshot->world || !snapshot->rules ||
|
||||
snapshot->identity.world.is_nil() || snapshot->identity.city == 0) {
|
||||
return {SaveAdmission::InvalidRequest, 0, {}};
|
||||
}
|
||||
return impl_->writer.try_submit(SaveRequest{destination, snapshot->world->tick(),
|
||||
snapshot->identity.session, [snapshot] {
|
||||
auto bytes = encode_checkpoint(*snapshot->world, snapshot->identity.world,
|
||||
snapshot->identity.city, *snapshot->rules);
|
||||
if (!bytes) throw std::runtime_error(bytes.error().message);
|
||||
return std::move(*bytes);
|
||||
}});
|
||||
}
|
||||
|
||||
CheckpointLoadSubmission CheckpointFiles::try_load(
|
||||
const std::filesystem::path& source, std::size_t workers, ExecutionMode mode) {
|
||||
std::unique_lock lock(impl_->admission_mutex, std::try_to_lock);
|
||||
if (!lock.owns_lock()) return {CheckpointLoadAdmission::Busy, 0, {}};
|
||||
if (impl_->closed) return {CheckpointLoadAdmission::Closed, 0, {}};
|
||||
if (impl_->executor->admitted() >= impl_->options.load_capacity) {
|
||||
return {CheckpointLoadAdmission::Busy, 0, {}};
|
||||
}
|
||||
if (!valid_path(source) ||
|
||||
(mode == ExecutionMode::Parallel && (workers < min_worker_count || workers > max_worker_count)) ||
|
||||
(mode != ExecutionMode::Parallel && mode != ExecutionMode::SerialReference)) {
|
||||
return {CheckpointLoadAdmission::InvalidRequest, 0, {}};
|
||||
}
|
||||
if (impl_->next_id == 0) return {CheckpointLoadAdmission::IdExhausted, 0, {}};
|
||||
auto future = impl_->pool->try_submit(
|
||||
[state = impl_.get(), source = std::filesystem::path(source), workers, mode] {
|
||||
return prepare(source, state->installed, state->options, workers, mode);
|
||||
});
|
||||
if (!future) {
|
||||
return {future.error() == Void::Async::AdmissionError::overloaded ?
|
||||
CheckpointLoadAdmission::Busy : CheckpointLoadAdmission::Closed, 0, {}};
|
||||
}
|
||||
const auto id = impl_->next_id++;
|
||||
return {CheckpointLoadAdmission::Accepted, id, std::move(*future)};
|
||||
}
|
||||
|
||||
void CheckpointFiles::shutdown() {
|
||||
if (impl_->executor->is_executor_thread()) {
|
||||
throw std::logic_error("checkpoint reader cannot join itself");
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(impl_->admission_mutex);
|
||||
impl_->closed = true;
|
||||
}
|
||||
static_cast<void>(impl_->executor->join());
|
||||
impl_->writer.shutdown();
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
Reference in new issue
Block a user