#include "settlement/core/checkpoint_files.hpp" #include #include #ifndef NOMINMAX #define NOMINMAX #endif #include #include #include #include #include #include #include #include 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 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 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(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(size.QuadPart)); std::array buffer; for (;;) { if (options.read_observer) options.read_observer(CheckpointReadPhase::BeforeRead); DWORD count = 0; if (!ReadFile(file.handle, buffer.data(), static_cast(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 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; try { std::ispanstream input{std::span{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 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(*executor); if (!executor->start()) throw std::runtime_error("cannot start checkpoint reader"); } CheckpointFilesOptions options; std::vector installed; SaveService writer; std::unique_ptr executor; std::unique_ptr 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 installed, CheckpointFilesOptions options) : impl_(std::make_unique(std::move(installed), std::move(options))) {} CheckpointFiles::~CheckpointFiles() { shutdown(); } SaveSubmission CheckpointFiles::try_save( const std::filesystem::path& destination, const std::shared_ptr& 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(impl_->executor->join()); impl_->writer.shutdown(); } } // namespace settlement