249 lines
11 KiB
C++
249 lines
11 KiB
C++
#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
|