Combine rule-aware checkpoints with background save publication
This commit is contained in:
commit
db4ac304b8
11 files changed
+1530
-4
No files matched your search
+14
-4
@@ -23,7 +23,8 @@ function(add_void_library)
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
set(VOID_ENABLE_TESTING OFF)
|
||||
set(VOID_ENABLE_BENCHMARKS OFF)
|
||||
set(VOID_ENABLED_MODULES Async Binary Core)
|
||||
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Text)
|
||||
set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL ON)
|
||||
if(BUILD_TESTING)
|
||||
list(APPEND VOID_ENABLED_MODULES Testing)
|
||||
endif()
|
||||
@@ -38,7 +39,9 @@ endif()
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
add_library(settlement_core
|
||||
engine/src/checkpoint.cpp
|
||||
engine/src/first_colony.cpp
|
||||
engine/src/rules_manifest.cpp
|
||||
engine/src/save_service_win32.cpp
|
||||
engine/src/worker_pool.cpp
|
||||
engine/src/world.cpp
|
||||
@@ -50,10 +53,10 @@ target_include_directories(settlement_core
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/engine/include
|
||||
)
|
||||
|
||||
target_compile_features(settlement_core PUBLIC cxx_std_20)
|
||||
target_compile_features(settlement_core PUBLIC cxx_std_23)
|
||||
target_link_libraries(settlement_core
|
||||
PUBLIC Threads::Threads Void::Core
|
||||
PRIVATE Void::Async Void::Binary
|
||||
PRIVATE Void::Algorithms Void::Async Void::Binary Void::Crypto Void::Data Void::Text
|
||||
)
|
||||
|
||||
if(MSVC)
|
||||
@@ -105,7 +108,14 @@ else()
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_executable(settlement_core_tests tests/core_tests.cpp tests/replay_tests.cpp tests/save_service_tests.cpp tests/test_main.cpp)
|
||||
add_executable(settlement_core_tests
|
||||
tests/checkpoint_tests.cpp
|
||||
tests/core_tests.cpp
|
||||
tests/replay_tests.cpp
|
||||
tests/rules_tests.cpp
|
||||
tests/save_service_tests.cpp
|
||||
tests/test_main.cpp
|
||||
)
|
||||
target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing)
|
||||
add_test(NAME settlement_core_tests COMMAND settlement_core_tests)
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Encode and validate versioned world checkpoints with frozen rules
|
||||
|
||||
Task ID: S15-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/checkpoint, detached de38aff (reviewed S19 rules + M01 replay). Parent integrates this into system/s15-persistence. Legacy World::write_save/read_save and their validations implement formats 1–13. default_rules_manifest resolves two real built-ins. Pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement a bounded modern checkpoint codec admitting a stable world UUID, city identity and a verified rules manifest together with the existing canonical world state. Produce a complete validated candidate without touching live state.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Game-specific envelope, built-in installed-catalog API only if needed, tests. SaveService, asynchronous requests, session/epoch assignment, UI, new custody fields, scripting are independent packages. Existing default format13 encoding and LAN11 fixtures must still pass.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect engine/include/settlement/core/{world,rules_manifest}.hpp, engine/src/{world_save,rules_manifest}.cpp, tests/{rules,core,replay}_tests.cpp, CMakeLists.txt, docs/plan/systems/{S15,S19}.md. Inspect pinned Void/Binary, Crypto SHA256, Core Uuid public types/tests.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; tests/checkpoint_tests.cpp; CMakeLists.txt; engine/include/settlement/core/rules_manifest.hpp; engine/src/rules_manifest.cpp
|
||||
Use last two only for extracting the actual built-in catalog behind existing default_rules_manifest. Others own writers, S01/S16 and separate checkouts. You are not alone, do not revert others or change Serena/Git.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Define NEW encode_checkpoint(const World&, stable world UUID, nonzero city, const RulesManifest&) and decode_checkpoint(bytes, installed RulePackage catalog, workers/mode), or equivalent precisely typed API. Use distinct magic+schema, little endian Void Binary, SHA-256 integrity over all meaningful header+payload bytes. Persist complete selected closure with each sorted stable ID, exact version, content digest and compare recomputed manifest from installed catalog, naming missing/changed package. Serialize core once with existing World codec. Verify bounded lengths/counts and outer integrity before domain/world allocations. Reject extra bytes, unsupported version, nil identity/zero city, metadata mismatch incl tick if stored, missing/extra/conflicting rules. Candidate returns unique World, identity, matching immutable manifest. No on-disk active session/ledger. Report simple actionable diagnostics while preserving ownership; do not make persistence a signature/authentication.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Use Void::Uuid::Uuid for world, uint64 city, RulesManifest and RulePackage directly. Add public installed builtin_rule_packages() returning expected catalog if needed, reuse in default_rules_manifest. Keep compiled-in fixture contents identical. Frozen rules independent of current active world. Allow later versioned state for new custody data without breaking old fixture. Match preexisting 128 MiB body cap plus separately bounded metadata before buffering. Communicate actual API early.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
No dependency on writer or runtime; immutable capture later calls encode in background, validated decoded world goes to runtime replacement. No new framework/dependency or external issue is needed for game framing using supported primitives; report a genuine missing generic capability to root.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Adversarial truncations, length overflow, malformed counts/input, duplicate packages, package digest/version/build mismatch, corrupted canonical body with recomputed outer checksum, lossless old bytes, world/identity/city survival. Decode allocates only from bounded data; respect existing output failure behaviors. Reading legacy file remains via World::read_save.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Round-trip a live and mid-carry world, compare full canonical world bytes and continued ticks. 2. Selecting alternate installed packages round-trips and validates against a catalog in different order. 3. Corruption, incompatible/uninstalled rules, bad UUID/city, lengths/trailing data fail with usable diagnostics while original world is untouched. 4. Old save13 & LAN11 and all existing suites pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/checkpoint-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <build>/settlement_core_tests.exe --tag checkpoint and git diff --check. Check commands from YOUR worktree.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No changes to shared checkouts or external services. Stop on ambiguous destructive format migration or incompatible real library semantics. Escalate after two failed repairs of the same defect.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Parent owns Git. User approved milestones/systems, commits/push; plans M01, M01-F3 cover independent validation before any owner replacement. Parent will review actual diff.
|
||||
|
||||
## 14. Return format
|
||||
Return S15-02 READY/BLOCKED, exact API, owned files, frame and limits, test results incl counts, residual limitations and later runtime integration. No subagents.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Resolve a frozen set of game rule packages from actual manifests
|
||||
|
||||
Task ID: S19-01
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive worktree /home/faumaray/Projects/stoneheart_at_home-worktrees/s19, system/s19-rules at 8d2870a. Main working directory belongs to another task. Exact Void pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. M01-P2/R2 and preflight F2 confirm the implementation seam.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement S19-W01 typed game rule manifest loading, validation and reproducible identity, with real JSON inputs and CTest coverage. Supply the public interface S15/S01 will freeze into worlds.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S19/M01 core support and its tests/build wiring; no Lua, UI, save codec or network yet. Plan requires diagnostics usable by a caller and frozen identity for explicit world selection.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect docs/plan/systems/S19.md, M01, CMakeLists.txt, exact upstream Void/Data/StrictJson.hpp, Void/Text/Semver.hpp, Void/Algorithms/Graph.hpp, Void/Crypto/Crypto.hpp and respective tests. Source root for pin is /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/rules_manifest.hpp; engine/src/rules_manifest.cpp; tests/rules_tests.cpp; CMakeLists.txt
|
||||
You are not alone. Use ONLY your specified worktree with explicit workdir/absolute paths, verify root/HEAD before edits. Other systems have separate checkouts. Do not edit the main checkout, change shared Serena project, stage, commit, push or spawn. Root integrates CMake.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Bound byte count and node/dependency/depth limits before/while using Void::Json::Strict. Manifest schema v1 includes namespaced package ID, exact strict SemVer, named dependencies and version constraints, exclusive providers, definitions with stable qualified IDs and references. For M01 definitions live in the JSON file (no external untrusted file paths/scripts). Resolve transitive deps from installed packages (one installed version per ID), detect duplicates/missing/range incompatibility/cycles/exclusive-provider clashes/unresolved definition refs. Use Void::Semver, Algorithms, Crypto and StrictJson. Sort sets, include definition content in SHA256, recompute digests; preserve semantically ordered data. Write diagnostics containing package/source and field. Provide usable base game package(s) for later startup via an explicit built-in loader or factory in owned code. Avoid implementing generic library alternatives.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW public RulePackage source + immutable RulesManifest (sorted frozen package ID/exact version/SHA256 and manifest fingerprint), loading/resolution via settlement/core/rules_manifest.hpp. Expose a base default and real catalog/selection input. Keep public types independent of upstream internals where practical. Define schema, duplicate/unknown semantics and source error handling in a short header comment. Send final signatures to root ASAP for S15/runtime.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
No upstream dependency update. Validate SHA-256 pure C++ fallback on Windows; use modules Data, Text, Algorithms, Crypto and transitive deps only. Matching generic candidate issue draft for reusable resolver is root-owned; game-specific capability names and decisions use published primitives. Root handles cross-system consumers and remote tracker outcome.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Reject unknown schema/invalid UTF-8/duplicate fields, malformed IDs/versions, digest spoofing, large files and excessive fan-out. Range semantics need explicit prerelease policy. SemVer == ignores build metadata, so frozen exact identities compare normalized full string and 32-byte digest. Stable diagnostic path relevant to user-provided files. No third-party game content.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Load and select from at least two meaningful original package documents with deps; reversing input/definition sets produces identical frozen identity. 2. Content, exact version or build change alters fingerprint. 3. Missing dependency, bad range, duplicate, cycle, exclusive conflict, dangling references and malformed/oversize JSON give actionable diagnostics. 4. Windows target/test suites pass and API ready to persist/compare a manifest.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/rules-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Add a discoverable Void suite with tag rules. Check actual diff and log timings.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Escalate any required new generic mechanism or library incompatibility. No network writes, no Git mutations, no competing branch/source edits. Stop after two unsuccessful repairs of one issue and send original failures.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorized full plan, milestone/system branches and pushes. The root handles those; preflight READY for S19 under these limits.
|
||||
|
||||
## 14. Return format
|
||||
Return S19-01 status, actual files and API, schema/canonicalization decisions, failure coverage, commands/results, unverified limits, integration notes for runtime/save. Do not spawn.
|
||||
@@ -25,6 +25,8 @@
|
||||
|
||||
## Границы интерфейсов
|
||||
|
||||
Контрольная точка версии 1 содержит постоянный UUID мира, город, такт, полный выбранный набор пакетов с точными версиями и SHA-256, а также состояние мира в формате 13. Декодер проверяет внешнюю контрольную сумму, заново разрешает набор правил по установленному каталогу и создаёт кандидат мира существующим проверенным загрузчиком. Клиенту доступны имя несовместимого пакета и поле ошибки. Восемь проверок под Wine охватывают переноску материалов, продолжение расчёта, перестановку каталога, обрезанные файлы, недопустимое состояние и тело размером более 16 МиБ. [Кодек контрольной точки](../../../engine/include/settlement/core/checkpoint.hpp) · [Проверки](../../../tests/checkpoint_tests.cpp)
|
||||
|
||||
`SaveRequest`, `SaveSnapshot`, `SaveManifest` и `LoadCandidate` — предлагаемые новые интерфейсы. Запрос содержит слот и желаемую операцию. Снимок привязан к одному завершённому такту. Манифест описывает все необходимые блоки и контрольные суммы. Кандидат загрузки предоставляет результат проверки до замены мира. Завершение операции возвращает идентификатор запроса, состояние и диагностическую причину ошибки.
|
||||
|
||||
При каждом успешном открытии файла создаётся новый экземпляр сетевой сессии, в том числе при откате того же мира на ранний такт. Запоздалый результат рабочего потока и команда клиента относятся к старому экземпляру и отбрасываются. Состояние переносимых резервов определяется сохранением, а права подключений проверяются заново. [Контракт сессии](S16.md)
|
||||
|
||||
@@ -4,6 +4,12 @@
|
||||
|
||||
Статус — план реализации. Игрок выбирает совместимый набор механик при создании мира. Собственные материалы и моды подключаются через документированный формат, а состояние этой конфигурации сохраняется вместе с колонией. Основа вводится в [M01](../milestones/M01.md), используется игровыми системами и публикуется для авторов в [M10](../milestones/M10.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
|
||||
## Первый исполняемый срез M01
|
||||
|
||||
`load_rule_package` читает ограниченный по размеру JSON с версией схемы, определениями, ссылками и зависимостями. `resolve_rules` для выбранных модулей вычисляет транзитивный состав, проверяет конфликты и возвращает точные версии с SHA-256. Порядок обхода файлов не меняет идентичность. Для проверки запустить `settlement_core_tests.exe --tag rules`. [Публичный интерфейс](../../../engine/include/settlement/core/rules_manifest.hpp) · [Реализация](../../../engine/src/rules_manifest.cpp) · [Проверки](../../../tests/rules_tests.cpp)
|
||||
|
||||
На Windows x64 под Wine прошли 9 сценариев для манифестов. Разбор JSON, версии, граф и хеш использованы из закреплённой VoidLibrary. Для замены локального разрешения наборов библиотечным сервисом повторить проверки транзитивных зависимостей, перестановок, конфликтов и идентичности. [Запрос в Void/Library](https://git.faumaray.com/Void/Library/issues/4)
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
Предметы, профессии, рецепты и команды прототипа определяются C++-типами, а стартовая партия создаётся кодом. В проверенной CMake-конфигурации подключены `Void::Binary`, `Void::Core` и `Void::Testing`. Скриптовый runtime в этот перечень не входит. План вводит новые определения контента и границу расширения. [Текущая конфигурация сборки](../../../CMakeLists.txt)
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/rules_manifest.hpp"
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
inline constexpr std::uint32_t checkpoint_version = 1;
|
||||
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 =
|
||||
24 + max_checkpoint_metadata_bytes + max_checkpoint_body_bytes + 32;
|
||||
|
||||
enum class CheckpointError : std::uint8_t {
|
||||
InvalidFrame,
|
||||
UnsupportedVersion,
|
||||
LimitExceeded,
|
||||
IntegrityMismatch,
|
||||
InvalidIdentity,
|
||||
RulesMismatch,
|
||||
InvalidWorld,
|
||||
ResourceFailure
|
||||
};
|
||||
|
||||
struct CheckpointDiagnostic {
|
||||
CheckpointError code;
|
||||
std::string field;
|
||||
std::string package;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
struct WorldCheckpoint {
|
||||
std::unique_ptr<World> world;
|
||||
Void::Uuid::Uuid world_id;
|
||||
std::uint64_t city;
|
||||
RulesManifest rules;
|
||||
};
|
||||
|
||||
// Version 1 stores magic, schema, metadata length and body length, then world UUID,
|
||||
// city, tick, rules fingerprint and the sorted complete package closure. Each
|
||||
// package stores its ID, exact version and SHA-256. The body uses World's save
|
||||
// codec. A final SHA-256 covers every preceding byte. Integers are little-endian.
|
||||
// The caller holds a stable World for the entire synchronous encode operation.
|
||||
[[nodiscard]] std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
const World& world, Void::Uuid::Uuid world_id, std::uint64_t city,
|
||||
const RulesManifest& rules);
|
||||
|
||||
// Input is bounded and integrity checked before package or World decoding.
|
||||
// Rules are resolved from the installed catalog and must match the complete
|
||||
// saved closure exactly. The returned candidate is independent of any live world.
|
||||
[[nodiscard]] std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
std::string_view bytes, std::span<const RulePackage> installed,
|
||||
std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel);
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
using RulesDigest = std::array<std::byte, 32>;
|
||||
|
||||
struct RulesDiagnostic {
|
||||
std::string package;
|
||||
std::string source;
|
||||
std::string field;
|
||||
std::string message;
|
||||
std::size_t byte_offset = 0;
|
||||
};
|
||||
|
||||
struct RulesLimits {
|
||||
std::size_t package_bytes = 256 * 1024;
|
||||
std::size_t catalog_bytes = 4 * 1024 * 1024;
|
||||
std::size_t packages = 128;
|
||||
std::size_t definitions = 1024;
|
||||
std::size_t dependencies = 64;
|
||||
std::size_t references = 64;
|
||||
std::size_t json_depth = 24;
|
||||
std::size_t json_nodes = 16384;
|
||||
};
|
||||
|
||||
struct RuleDefinition {
|
||||
std::string id;
|
||||
std::string kind;
|
||||
std::string canonical_data;
|
||||
std::vector<std::string> references;
|
||||
};
|
||||
|
||||
struct FrozenRulePackage {
|
||||
std::string id;
|
||||
std::string exact_version;
|
||||
RulesDigest content_sha256{};
|
||||
bool operator==(const FrozenRulePackage&) const = default;
|
||||
};
|
||||
|
||||
class RulesManifest;
|
||||
struct RulePackageData;
|
||||
|
||||
// Schema 1 requires schema/id/version/dependencies/exclusive_capabilities/definitions.
|
||||
// Package IDs use lower-case dot-separated segments. Definition IDs and capabilities
|
||||
// use package:local-name. Each definition has id/kind/data/references, where data is
|
||||
// integer-valued strict JSON. Unknown metadata fields are errors. Set-like arrays are
|
||||
// sorted; arrays inside data retain order. Sources are diagnostic labels, never paths
|
||||
// to execute or open. Only one installed version of each package ID is allowed.
|
||||
class RulePackage {
|
||||
public:
|
||||
[[nodiscard]] const FrozenRulePackage& identity() const noexcept;
|
||||
[[nodiscard]] std::span<const RuleDefinition> definitions() const noexcept;
|
||||
[[nodiscard]] std::string_view canonical_json() const noexcept;
|
||||
|
||||
private:
|
||||
explicit RulePackage(std::shared_ptr<const RulePackageData> data);
|
||||
std::shared_ptr<const RulePackageData> data_;
|
||||
friend std::expected<RulePackage, RulesDiagnostic> load_rule_package(
|
||||
std::string_view, std::string_view, const RulesLimits&);
|
||||
friend std::expected<RulesManifest, RulesDiagnostic> resolve_rules(
|
||||
std::span<const RulePackage>, std::span<const std::string>, const RulesLimits&);
|
||||
};
|
||||
|
||||
class RulesManifest {
|
||||
public:
|
||||
[[nodiscard]] std::span<const FrozenRulePackage> packages() const noexcept { return packages_; }
|
||||
[[nodiscard]] const RulesDigest& fingerprint() const noexcept { return fingerprint_; }
|
||||
// Schema-tagged canonical UTF-8 bytes shared by persistence and handshake callers.
|
||||
[[nodiscard]] std::string_view canonical_json() const noexcept { return canonical_json_; }
|
||||
bool operator==(const RulesManifest&) const = default;
|
||||
|
||||
private:
|
||||
RulesManifest(std::vector<FrozenRulePackage>, RulesDigest, std::string);
|
||||
std::vector<FrozenRulePackage> packages_;
|
||||
RulesDigest fingerprint_{};
|
||||
std::string canonical_json_;
|
||||
friend std::expected<RulesManifest, RulesDiagnostic> resolve_rules(
|
||||
std::span<const RulePackage>, std::span<const std::string>, const RulesLimits&);
|
||||
};
|
||||
|
||||
[[nodiscard]] std::expected<RulePackage, RulesDiagnostic> load_rule_package(
|
||||
std::string_view source, std::string_view json, const RulesLimits& limits = {});
|
||||
|
||||
// Resolves selected IDs and their transitive dependencies. Prerelease dependencies
|
||||
// require an exact constraint equal to that full version, optionally prefixed by '='.
|
||||
// Content digests are computed from the parsed content and never trusted from input.
|
||||
[[nodiscard]] std::expected<RulesManifest, RulesDiagnostic> resolve_rules(
|
||||
std::span<const RulePackage> available, std::span<const std::string> selected,
|
||||
const RulesLimits& limits = {});
|
||||
|
||||
[[nodiscard]] std::expected<std::vector<RulePackage>, RulesDiagnostic> builtin_rule_packages();
|
||||
[[nodiscard]] std::expected<RulesManifest, RulesDiagnostic> default_rules_manifest();
|
||||
[[nodiscard]] std::string rules_digest_hex(const RulesDigest& digest);
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,282 @@
|
||||
#include "settlement/core/checkpoint.hpp"
|
||||
|
||||
#include <Void/Binary/Reader.hpp>
|
||||
#include <Void/Binary/Writer.hpp>
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <new>
|
||||
#include <spanstream>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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;
|
||||
constexpr std::size_t max_packages = 128;
|
||||
constexpr std::size_t max_package_id_bytes = 128;
|
||||
constexpr std::size_t max_version_bytes = 256;
|
||||
|
||||
struct InvalidCheckpoint {
|
||||
CheckpointDiagnostic diagnostic;
|
||||
};
|
||||
|
||||
[[noreturn]] void fail(CheckpointError code, std::string field, std::string message,
|
||||
std::string package = {}) {
|
||||
throw InvalidCheckpoint{{code, std::move(field), std::move(package), std::move(message)}};
|
||||
}
|
||||
|
||||
std::span<const std::byte> wire_bytes(std::string_view text) {
|
||||
return std::as_bytes(std::span{text.data(), text.size()});
|
||||
}
|
||||
|
||||
RulesDigest digest(std::span<const std::byte> bytes) {
|
||||
// The incremental API accepts the complete checkpoint size. Void's one-shot
|
||||
// helper has a separate 16 MiB message limit.
|
||||
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
|
||||
if (!hasher || !hasher->update(bytes)) {
|
||||
fail(CheckpointError::ResourceFailure, "sha256", "Could not hash the checkpoint.");
|
||||
}
|
||||
const auto result = hasher->finalize();
|
||||
if (!result || result->size() != digest_size) {
|
||||
fail(CheckpointError::ResourceFailure, "sha256", "Could not finalize the checkpoint hash.");
|
||||
}
|
||||
RulesDigest value{};
|
||||
std::copy(result->begin(), result->end(), value.begin());
|
||||
return value;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
void put(Void::Binary::Writer& writer, T value) {
|
||||
if (!writer.writeLittle(value)) {
|
||||
fail(CheckpointError::InvalidFrame, "frame", "Could not encode the checkpoint field.");
|
||||
}
|
||||
}
|
||||
|
||||
void put_bytes(Void::Binary::Writer& writer, std::span<const std::byte> bytes) {
|
||||
if (!writer.writeBytes(bytes)) {
|
||||
fail(CheckpointError::InvalidFrame, "frame", "Could not encode checkpoint bytes.");
|
||||
}
|
||||
}
|
||||
|
||||
void put_text(Void::Binary::Writer& writer, std::string_view text) {
|
||||
put(writer, static_cast<std::uint16_t>(text.size()));
|
||||
put_bytes(writer, wire_bytes(text));
|
||||
}
|
||||
|
||||
template<class T>
|
||||
T get(Void::Binary::Reader& reader, std::string_view field) {
|
||||
const auto result = reader.readLittle<T>();
|
||||
if (!result) fail(CheckpointError::InvalidFrame, std::string(field), "Checkpoint field is incomplete.");
|
||||
return *result;
|
||||
}
|
||||
|
||||
std::span<const std::byte> get_bytes(Void::Binary::Reader& reader, std::size_t count,
|
||||
std::string_view field) {
|
||||
const auto result = reader.readBytes(count);
|
||||
if (!result) fail(CheckpointError::InvalidFrame, std::string(field), "Checkpoint bytes are incomplete.");
|
||||
return *result;
|
||||
}
|
||||
|
||||
std::string get_text(Void::Binary::Reader& reader, std::size_t limit, std::string_view field) {
|
||||
const auto count = get<std::uint16_t>(reader, field);
|
||||
if (count == 0 || count > limit) {
|
||||
fail(CheckpointError::LimitExceeded, std::string(field), "Package metadata length is invalid.");
|
||||
}
|
||||
const auto bytes = get_bytes(reader, count, field);
|
||||
return {reinterpret_cast<const char*>(bytes.data()), bytes.size()};
|
||||
}
|
||||
|
||||
void validate_identity(const Void::Uuid::Uuid& world_id, std::uint64_t city) {
|
||||
if (world_id.is_nil()) fail(CheckpointError::InvalidIdentity, "world_id", "World UUID must be nonnil.");
|
||||
if (city == 0) fail(CheckpointError::InvalidIdentity, "city", "City identity must be nonzero.");
|
||||
}
|
||||
|
||||
RulesManifest validate_rules(std::span<const FrozenRulePackage> saved, const RulesDigest& fingerprint,
|
||||
std::span<const RulePackage> installed) {
|
||||
std::vector<std::string> selected;
|
||||
selected.reserve(saved.size());
|
||||
for (const auto& expected : saved) {
|
||||
const auto found = std::find_if(installed.begin(), installed.end(), [&](const RulePackage& package) {
|
||||
return package.identity().id == expected.id;
|
||||
});
|
||||
if (found == installed.end()) {
|
||||
fail(CheckpointError::RulesMismatch, "rules.packages", "Required package is not installed.", expected.id);
|
||||
}
|
||||
if (found->identity().exact_version != expected.exact_version) {
|
||||
fail(CheckpointError::RulesMismatch, "rules.version", "Installed package version differs from the checkpoint.", expected.id);
|
||||
}
|
||||
if (found->identity().content_sha256 != expected.content_sha256) {
|
||||
fail(CheckpointError::RulesMismatch, "rules.sha256", "Installed package content differs from the checkpoint.", expected.id);
|
||||
}
|
||||
selected.push_back(expected.id);
|
||||
}
|
||||
auto resolved = resolve_rules(installed, selected);
|
||||
if (!resolved) {
|
||||
const auto& diagnostic = resolved.error();
|
||||
fail(CheckpointError::RulesMismatch, "rules." + diagnostic.field,
|
||||
diagnostic.message, diagnostic.package);
|
||||
}
|
||||
if (!std::ranges::equal(resolved->packages(), saved)) {
|
||||
const auto added = std::find_if(resolved->packages().begin(), resolved->packages().end(),
|
||||
[&](const FrozenRulePackage& package) {
|
||||
return std::none_of(saved.begin(), saved.end(), [&](const FrozenRulePackage& expected) {
|
||||
return expected.id == package.id;
|
||||
});
|
||||
});
|
||||
fail(CheckpointError::RulesMismatch, "rules.packages", "Saved package set does not include its complete dependency closure.",
|
||||
added == resolved->packages().end() ? std::string{} : added->id);
|
||||
}
|
||||
if (resolved->fingerprint() != fingerprint) {
|
||||
fail(CheckpointError::RulesMismatch, "rules.fingerprint", "Rules fingerprint differs from the resolved packages.");
|
||||
}
|
||||
return std::move(*resolved);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
const World& world, Void::Uuid::Uuid world_id, std::uint64_t city, const RulesManifest& rules) {
|
||||
try {
|
||||
validate_identity(world_id, city);
|
||||
if (rules.packages().empty() || rules.packages().size() > max_packages) {
|
||||
fail(CheckpointError::LimitExceeded, "rules.packages", "Checkpoint requires between 1 and 128 packages.");
|
||||
}
|
||||
std::size_t metadata_size = fixed_metadata_size;
|
||||
std::string_view previous;
|
||||
for (const auto& package : rules.packages()) {
|
||||
if (package.id.empty() || package.id.size() > max_package_id_bytes ||
|
||||
package.exact_version.empty() || package.exact_version.size() > max_version_bytes) {
|
||||
fail(CheckpointError::LimitExceeded, "rules.packages", "Package metadata length is invalid.", package.id);
|
||||
}
|
||||
if (!previous.empty() && previous >= package.id) {
|
||||
fail(CheckpointError::RulesMismatch, "rules.packages", "Package IDs must be unique and sorted.", package.id);
|
||||
}
|
||||
previous = package.id;
|
||||
metadata_size += 4 + package.id.size() + package.exact_version.size() + digest_size;
|
||||
}
|
||||
if (metadata_size > max_checkpoint_metadata_bytes) {
|
||||
fail(CheckpointError::LimitExceeded, "metadata_length", "Checkpoint metadata exceeds 64 KiB.");
|
||||
}
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream);
|
||||
auto body = std::move(stream).str();
|
||||
if (body.size() > max_checkpoint_body_bytes) {
|
||||
fail(CheckpointError::LimitExceeded, "body_length", "Checkpoint world exceeds 128 MiB.");
|
||||
}
|
||||
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(writer, checkpoint_version);
|
||||
put(writer, static_cast<std::uint32_t>(metadata_size));
|
||||
put(writer, static_cast<std::uint64_t>(body.size()));
|
||||
put_bytes(writer, std::as_bytes(std::span{world_id.bytes}));
|
||||
put(writer, city);
|
||||
put(writer, world.tick());
|
||||
put_bytes(writer, rules.fingerprint());
|
||||
put(writer, static_cast<std::uint32_t>(rules.packages().size()));
|
||||
for (const auto& package : rules.packages()) {
|
||||
put_text(writer, package.id);
|
||||
put_text(writer, package.exact_version);
|
||||
put_bytes(writer, package.content_sha256);
|
||||
}
|
||||
put_bytes(writer, wire_bytes(body));
|
||||
const auto checksum = digest(writer.written());
|
||||
put_bytes(writer, checksum);
|
||||
return bytes;
|
||||
} catch (const InvalidCheckpoint& error) {
|
||||
return std::unexpected{error.diagnostic};
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected{CheckpointDiagnostic{CheckpointError::ResourceFailure, "memory", {}, "Checkpoint allocation failed."}};
|
||||
} catch (const std::exception& error) {
|
||||
return std::unexpected{CheckpointDiagnostic{CheckpointError::InvalidWorld, "world", {}, error.what()}};
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
std::string_view bytes, std::span<const RulePackage> installed, std::size_t workers, ExecutionMode mode) {
|
||||
try {
|
||||
if (bytes.size() > max_checkpoint_bytes) {
|
||||
fail(CheckpointError::LimitExceeded, "frame", "Checkpoint exceeds its byte limit.");
|
||||
}
|
||||
if (bytes.size() < header_size + fixed_metadata_size + digest_size) {
|
||||
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))) {
|
||||
fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match.");
|
||||
}
|
||||
if (get<std::uint32_t>(header, "version") != checkpoint_version) {
|
||||
fail(CheckpointError::UnsupportedVersion, "version", "Checkpoint schema is not supported.");
|
||||
}
|
||||
const auto metadata_size = get<std::uint32_t>(header, "metadata_length");
|
||||
const auto body_size = get<std::uint64_t>(header, "body_length");
|
||||
if (metadata_size < fixed_metadata_size || metadata_size > max_checkpoint_metadata_bytes ||
|
||||
body_size == 0 || body_size > max_checkpoint_body_bytes) {
|
||||
fail(CheckpointError::LimitExceeded, "lengths", "Checkpoint metadata or world length is invalid.");
|
||||
}
|
||||
if (bytes.size() != header_size + metadata_size + body_size + digest_size) {
|
||||
fail(CheckpointError::InvalidFrame, "lengths", "Checkpoint lengths do not match its complete frame.");
|
||||
}
|
||||
const auto wire = wire_bytes(bytes);
|
||||
const auto checksum = digest(wire.first(wire.size() - digest_size));
|
||||
if (!std::ranges::equal(checksum, wire.last(digest_size))) {
|
||||
fail(CheckpointError::IntegrityMismatch, "sha256", "Checkpoint integrity hash does not match.");
|
||||
}
|
||||
Void::Binary::Reader metadata(wire.subspan(header_size, metadata_size));
|
||||
Void::Uuid::Uuid world_id;
|
||||
const auto identity_bytes = get_bytes(metadata, world_id.bytes.size(), "world_id");
|
||||
for (std::size_t i = 0; i < world_id.bytes.size(); ++i) {
|
||||
world_id.bytes[i] = std::to_integer<std::uint8_t>(identity_bytes[i]);
|
||||
}
|
||||
const auto city = get<std::uint64_t>(metadata, "city");
|
||||
validate_identity(world_id, city);
|
||||
const auto tick = get<std::uint64_t>(metadata, "tick");
|
||||
RulesDigest fingerprint{};
|
||||
const auto fingerprint_bytes = get_bytes(metadata, fingerprint.size(), "rules.fingerprint");
|
||||
std::copy(fingerprint_bytes.begin(), fingerprint_bytes.end(), fingerprint.begin());
|
||||
const auto package_count = get<std::uint32_t>(metadata, "rules.packages");
|
||||
if (package_count == 0 || package_count > max_packages) {
|
||||
fail(CheckpointError::LimitExceeded, "rules.packages", "Checkpoint requires between 1 and 128 packages.");
|
||||
}
|
||||
std::vector<FrozenRulePackage> saved;
|
||||
saved.reserve(package_count);
|
||||
for (std::uint32_t i = 0; i < package_count; ++i) {
|
||||
FrozenRulePackage package;
|
||||
package.id = get_text(metadata, max_package_id_bytes, "rules.id");
|
||||
package.exact_version = get_text(metadata, max_version_bytes, "rules.version");
|
||||
const auto package_digest = get_bytes(metadata, digest_size, "rules.sha256");
|
||||
std::copy(package_digest.begin(), package_digest.end(), package.content_sha256.begin());
|
||||
if (!saved.empty() && saved.back().id >= package.id) {
|
||||
fail(CheckpointError::RulesMismatch, "rules.packages", "Package IDs must be unique and sorted.", package.id);
|
||||
}
|
||||
saved.push_back(std::move(package));
|
||||
}
|
||||
if (!metadata.empty()) {
|
||||
fail(CheckpointError::InvalidFrame, "metadata", "Checkpoint metadata contains trailing bytes.");
|
||||
}
|
||||
auto rules = validate_rules(saved, fingerprint, installed);
|
||||
const auto body = bytes.substr(header_size + metadata_size, static_cast<std::size_t>(body_size));
|
||||
std::ispanstream stream(std::span<const char>{body.data(), body.size()});
|
||||
auto world = World::read_save(stream, workers, mode);
|
||||
if (world->tick() != tick) {
|
||||
fail(CheckpointError::InvalidWorld, "tick", "Checkpoint tick differs from its world state.");
|
||||
}
|
||||
return WorldCheckpoint{std::move(world), world_id, city, std::move(rules)};
|
||||
} catch (const InvalidCheckpoint& error) {
|
||||
return std::unexpected{error.diagnostic};
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected{CheckpointDiagnostic{CheckpointError::ResourceFailure, "memory", {}, "Checkpoint allocation failed."}};
|
||||
} catch (const std::exception& error) {
|
||||
return std::unexpected{CheckpointDiagnostic{CheckpointError::InvalidWorld, "world", {}, error.what()}};
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,399 @@
|
||||
#include "settlement/core/rules_manifest.hpp"
|
||||
|
||||
#include <Void/Algorithms/Graph.hpp>
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/Text/Semver.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
namespace json = Void::Json::Strict;
|
||||
|
||||
struct RuleDependency {
|
||||
std::string id;
|
||||
std::string range;
|
||||
};
|
||||
|
||||
struct RulePackageData {
|
||||
FrozenRulePackage identity;
|
||||
std::string source;
|
||||
std::string canonical_json;
|
||||
std::vector<RuleDependency> dependencies;
|
||||
std::vector<std::string> capabilities;
|
||||
std::vector<RuleDefinition> definitions;
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
struct InvalidRules {
|
||||
RulesDiagnostic diagnostic;
|
||||
};
|
||||
|
||||
struct Context {
|
||||
std::string package;
|
||||
std::string source;
|
||||
|
||||
[[noreturn]] void fail(std::string field, std::string message, std::size_t offset = 0) const {
|
||||
throw InvalidRules{{package, source, std::move(field), std::move(message), offset}};
|
||||
}
|
||||
};
|
||||
|
||||
bool local_name(std::string_view text) {
|
||||
if (text.empty() || text.size() > 128 || text.front() < 'a' || text.front() > 'z') return false;
|
||||
return std::all_of(text.begin(), text.end(), [](char ch) {
|
||||
return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-';
|
||||
});
|
||||
}
|
||||
|
||||
bool package_id(std::string_view text) {
|
||||
if (text.size() > 128 || text.find('.') == std::string_view::npos) return false;
|
||||
for (;;) {
|
||||
const auto separator = text.find('.');
|
||||
if (!local_name(text.substr(0, separator))) return false;
|
||||
if (separator == std::string_view::npos) return true;
|
||||
text.remove_prefix(separator + 1);
|
||||
}
|
||||
}
|
||||
|
||||
bool qualified_id(std::string_view text) {
|
||||
const auto separator = text.find(':');
|
||||
return separator != std::string_view::npos && package_id(text.substr(0, separator)) &&
|
||||
local_name(text.substr(separator + 1));
|
||||
}
|
||||
|
||||
void input_budget(std::string_view text, const RulesLimits& limits, const Context& context) {
|
||||
if (text.size() > limits.package_bytes) context.fail("$", "package byte limit exceeded");
|
||||
if (limits.json_depth == 0 || limits.json_depth > 64) context.fail("$", "JSON depth limit must be 1..64");
|
||||
// Count lexical nodes (including object keys) before the JSON parser allocates.
|
||||
std::size_t nodes = 0;
|
||||
bool in_string = false;
|
||||
bool escaped = false;
|
||||
bool scalar = false;
|
||||
for (char ch : text) {
|
||||
if (in_string) {
|
||||
if (escaped) escaped = false;
|
||||
else if (ch == '\\') escaped = true;
|
||||
else if (ch == '"') in_string = false;
|
||||
continue;
|
||||
}
|
||||
if (ch == '"') {
|
||||
in_string = true;
|
||||
scalar = false;
|
||||
++nodes;
|
||||
} else if (ch == '{' || ch == '[') {
|
||||
scalar = false;
|
||||
++nodes;
|
||||
} else if (ch == '}' || ch == ']' || ch == ',' || ch == ':' ||
|
||||
ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t') {
|
||||
scalar = false;
|
||||
} else if (!scalar) {
|
||||
scalar = true;
|
||||
++nodes;
|
||||
}
|
||||
if (nodes > limits.json_nodes) context.fail("$", "JSON node limit exceeded");
|
||||
}
|
||||
}
|
||||
|
||||
template <class T>
|
||||
const T& as(const json::Value& value, const Context& context, std::string_view field) {
|
||||
const auto* result = std::get_if<T>(&value.value);
|
||||
if (!result) context.fail(std::string(field), "unexpected JSON type");
|
||||
return *result;
|
||||
}
|
||||
|
||||
const json::Value::Object& object(const json::Value& value, const Context& context,
|
||||
std::string_view field, std::initializer_list<std::string_view> names) {
|
||||
const auto& result = as<json::Value::Object>(value, context, field);
|
||||
for (const auto& [key, ignored] : result) {
|
||||
static_cast<void>(ignored);
|
||||
if (std::find(names.begin(), names.end(), key) == names.end()) {
|
||||
context.fail(std::string(field) + "." + key, "unknown field");
|
||||
}
|
||||
}
|
||||
for (auto key : names) {
|
||||
if (!result.contains(key)) context.fail(std::string(field) + "." + std::string(key), "required field is missing");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string text(const json::Value& value, const Context& context, const std::string& field) {
|
||||
const auto& result = as<std::string>(value, context, field);
|
||||
if (result.size() > 256) context.fail(field, "metadata string limit exceeded");
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<std::string> id_set(const json::Value& value, const Context& context,
|
||||
const std::string& field, std::size_t maximum) {
|
||||
const auto& entries = as<json::Value::Array>(value, context, field);
|
||||
if (entries.size() > maximum) context.fail(field, "entry limit exceeded");
|
||||
std::vector<std::string> result;
|
||||
for (const auto& entry : entries) {
|
||||
auto id = text(entry, context, field);
|
||||
if (!qualified_id(id)) context.fail(field, "expected a package:local-name identifier");
|
||||
result.push_back(std::move(id));
|
||||
}
|
||||
std::sort(result.begin(), result.end());
|
||||
if (std::adjacent_find(result.begin(), result.end()) != result.end()) context.fail(field, "duplicate identifier");
|
||||
return result;
|
||||
}
|
||||
|
||||
json::Value string_array(const std::vector<std::string>& values) {
|
||||
json::Value::Array result;
|
||||
for (const auto& value : values) result.push_back(json::Value{value});
|
||||
return json::Value{std::move(result)};
|
||||
}
|
||||
|
||||
std::string serialize(const json::Value& value, const Context& context, std::size_t depth) {
|
||||
auto result = json::serialize(value, depth);
|
||||
if (!result) context.fail("$", result.error().message, result.error().offset);
|
||||
return std::move(*result);
|
||||
}
|
||||
|
||||
RulesDigest digest(std::string_view bytes, const Context& context) {
|
||||
auto result = Void::Crypto::sha256(bytes);
|
||||
if (!result || result->size() != 32) context.fail("sha256", "SHA-256 computation failed");
|
||||
RulesDigest output{};
|
||||
std::copy(result->begin(), result->end(), output.begin());
|
||||
return output;
|
||||
}
|
||||
|
||||
std::shared_ptr<const RulePackageData> parse_package(std::string_view source, std::string_view bytes,
|
||||
const RulesLimits& limits) {
|
||||
Context context{"", std::string(source)};
|
||||
input_budget(bytes, limits, context);
|
||||
auto parsed = json::parse(bytes, json::ParseOptions{limits.json_depth, false});
|
||||
if (!parsed) context.fail("$", parsed.error().message, parsed.error().offset);
|
||||
const auto& root = object(*parsed, context, "$",
|
||||
{"schema", "id", "version", "dependencies", "exclusive_capabilities", "definitions"});
|
||||
auto result = std::make_shared<RulePackageData>();
|
||||
result->source = source;
|
||||
context.package = text(root.at("id"), context, "id");
|
||||
if (!package_id(context.package)) context.fail("id", "expected a lower-case dot-separated package ID");
|
||||
result->identity.id = context.package;
|
||||
if (as<std::int64_t>(root.at("schema"), context, "schema") != 1) context.fail("schema", "unsupported package schema");
|
||||
const auto version = Void::Semver::parse_strict(text(root.at("version"), context, "version"));
|
||||
if (!version) context.fail("version", "invalid strict SemVer");
|
||||
result->identity.exact_version = version->to_string();
|
||||
const auto& dependencies = as<json::Value::Array>(root.at("dependencies"), context, "dependencies");
|
||||
if (dependencies.size() > limits.dependencies) context.fail("dependencies", "dependency limit exceeded");
|
||||
for (std::size_t i = 0; i < dependencies.size(); ++i) {
|
||||
const auto field = "dependencies[" + std::to_string(i) + "]";
|
||||
const auto& dep = object(dependencies[i], context, field, {"id", "version"});
|
||||
auto id = text(dep.at("id"), context, field + ".id");
|
||||
auto range = text(dep.at("version"), context, field + ".version");
|
||||
if (!package_id(id)) context.fail(field + ".id", "invalid dependency package ID");
|
||||
if (range.empty() || !Void::Semver::VersionRange::parse(range)) context.fail(field + ".version", "invalid version range");
|
||||
result->dependencies.push_back({std::move(id), std::move(range)});
|
||||
}
|
||||
std::sort(result->dependencies.begin(), result->dependencies.end(), [](const auto& a, const auto& b) { return a.id < b.id; });
|
||||
if (std::adjacent_find(result->dependencies.begin(), result->dependencies.end(),
|
||||
[](const auto& a, const auto& b) { return a.id == b.id; }) != result->dependencies.end()) {
|
||||
context.fail("dependencies", "duplicate dependency package ID");
|
||||
}
|
||||
result->capabilities = id_set(root.at("exclusive_capabilities"), context, "exclusive_capabilities", limits.definitions);
|
||||
const auto& definitions = as<json::Value::Array>(root.at("definitions"), context, "definitions");
|
||||
if (definitions.size() > limits.definitions) context.fail("definitions", "definition limit exceeded");
|
||||
std::map<std::string, json::Value> canonical_definitions;
|
||||
for (std::size_t i = 0; i < definitions.size(); ++i) {
|
||||
const auto field = "definitions[" + std::to_string(i) + "]";
|
||||
const auto& entry = object(definitions[i], context, field, {"id", "kind", "data", "references"});
|
||||
RuleDefinition definition;
|
||||
definition.id = text(entry.at("id"), context, field + ".id");
|
||||
if (!qualified_id(definition.id) || !definition.id.starts_with(context.package + ":")) {
|
||||
context.fail(field + ".id", "definition must belong to its package namespace");
|
||||
}
|
||||
definition.kind = text(entry.at("kind"), context, field + ".kind");
|
||||
constexpr std::string_view kinds[]{"item", "profession", "recipe", "material", "event"};
|
||||
if (std::find(std::begin(kinds), std::end(kinds), definition.kind) == std::end(kinds)) context.fail(field + ".kind", "unknown definition kind");
|
||||
definition.references = id_set(entry.at("references"), context, field + ".references", limits.references);
|
||||
definition.canonical_data = serialize(entry.at("data"), context, limits.json_depth);
|
||||
auto canonical = entry;
|
||||
canonical.at("references") = string_array(definition.references);
|
||||
if (!canonical_definitions.emplace(definition.id, json::Value{std::move(canonical)}).second) {
|
||||
context.fail(field + ".id", "duplicate definition ID");
|
||||
}
|
||||
result->definitions.push_back(std::move(definition));
|
||||
}
|
||||
std::sort(result->definitions.begin(), result->definitions.end(), [](const auto& a, const auto& b) { return a.id < b.id; });
|
||||
json::Value::Array canonical_dependencies;
|
||||
for (const auto& dep : result->dependencies) canonical_dependencies.push_back(json::Value{json::Value::Object{
|
||||
{"id", json::Value{dep.id}}, {"version", json::Value{dep.range}}}});
|
||||
json::Value::Array canonical_definition_array;
|
||||
for (auto& [id, value] : canonical_definitions) {
|
||||
static_cast<void>(id);
|
||||
canonical_definition_array.push_back(std::move(value));
|
||||
}
|
||||
auto canonical = root;
|
||||
canonical.at("version") = json::Value{result->identity.exact_version};
|
||||
canonical.at("dependencies") = json::Value{std::move(canonical_dependencies)};
|
||||
canonical.at("exclusive_capabilities") = string_array(result->capabilities);
|
||||
canonical.at("definitions") = json::Value{std::move(canonical_definition_array)};
|
||||
result->canonical_json = serialize(json::Value{std::move(canonical)}, context, limits.json_depth);
|
||||
result->identity.content_sha256 = digest(result->canonical_json, context);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
RulePackage::RulePackage(std::shared_ptr<const RulePackageData> data) : data_(std::move(data)) {}
|
||||
const FrozenRulePackage& RulePackage::identity() const noexcept { return data_->identity; }
|
||||
std::span<const RuleDefinition> RulePackage::definitions() const noexcept { return data_->definitions; }
|
||||
std::string_view RulePackage::canonical_json() const noexcept { return data_->canonical_json; }
|
||||
|
||||
RulesManifest::RulesManifest(std::vector<FrozenRulePackage> packages, RulesDigest fingerprint, std::string bytes)
|
||||
: packages_(std::move(packages)), fingerprint_(fingerprint), canonical_json_(std::move(bytes)) {}
|
||||
|
||||
std::expected<RulePackage, RulesDiagnostic> load_rule_package(std::string_view source, std::string_view bytes,
|
||||
const RulesLimits& limits) {
|
||||
try {
|
||||
return RulePackage{parse_package(source, bytes, limits)};
|
||||
} catch (const InvalidRules& error) {
|
||||
return std::unexpected{error.diagnostic};
|
||||
}
|
||||
}
|
||||
|
||||
std::string rules_digest_hex(const RulesDigest& hash) {
|
||||
constexpr char alphabet[] = "0123456789abcdef";
|
||||
std::string result;
|
||||
result.reserve(hash.size() * 2);
|
||||
for (auto byte : hash) {
|
||||
const auto value = std::to_integer<unsigned int>(byte);
|
||||
result.push_back(alphabet[value >> 4]);
|
||||
result.push_back(alphabet[value & 15]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::expected<RulesManifest, RulesDiagnostic> resolve_rules(std::span<const RulePackage> available,
|
||||
std::span<const std::string> selected,
|
||||
const RulesLimits& limits) {
|
||||
try {
|
||||
Context context{"", "catalog"};
|
||||
if (available.size() > limits.packages || selected.size() > limits.packages) context.fail("packages", "package count limit exceeded");
|
||||
std::map<std::string, const RulePackageData*> catalog;
|
||||
std::size_t byte_count = 0;
|
||||
for (const auto& package : available) {
|
||||
const auto& data = *package.data_;
|
||||
context = {data.identity.id, data.source};
|
||||
// Revalidate limits at the resolver boundary, including callers using a
|
||||
// package parsed with more permissive limits.
|
||||
if (data.canonical_json.size() > limits.catalog_bytes - std::min(byte_count, limits.catalog_bytes)) {
|
||||
context.fail("packages", "catalog byte limit exceeded");
|
||||
}
|
||||
static_cast<void>(parse_package(data.source, data.canonical_json, limits));
|
||||
byte_count += data.canonical_json.size();
|
||||
if (!catalog.emplace(data.identity.id, &data).second) context.fail("id", "duplicate installed package ID");
|
||||
}
|
||||
std::set<std::string> chosen;
|
||||
std::vector<std::string> pending(selected.begin(), selected.end());
|
||||
std::sort(pending.begin(), pending.end());
|
||||
if (pending.empty()) context.fail("selected", "select at least one package");
|
||||
if (std::adjacent_find(pending.begin(), pending.end()) != pending.end()) context.fail("selected", "duplicate selected package ID");
|
||||
for (std::size_t i = 0; i < pending.size(); ++i) {
|
||||
const auto id = pending[i];
|
||||
context = {id, "selection"};
|
||||
if (!package_id(id)) context.fail("selected", "invalid selected package ID");
|
||||
if (chosen.contains(id)) continue;
|
||||
const auto found = catalog.find(id);
|
||||
if (found == catalog.end()) context.fail("selected", "package is not installed: " + id);
|
||||
const auto& package = *found->second;
|
||||
context = {id, package.source};
|
||||
chosen.insert(id);
|
||||
for (const auto& dep : package.dependencies) {
|
||||
const auto dependency = catalog.find(dep.id);
|
||||
if (dependency == catalog.end()) context.fail("dependencies." + dep.id, "required package is not installed");
|
||||
const auto version = Void::Semver::parse_strict(dependency->second->identity.exact_version);
|
||||
const auto range = Void::Semver::VersionRange::parse(dep.range);
|
||||
const bool prerelease_allowed = version->pre_release.empty() || dep.range == version->to_string() || dep.range == "=" + version->to_string();
|
||||
if (!prerelease_allowed || !range->contains(*version)) context.fail("dependencies." + dep.id, "installed version does not satisfy the constraint");
|
||||
if (!chosen.contains(dep.id)) pending.push_back(dep.id);
|
||||
}
|
||||
}
|
||||
std::vector<const RulePackageData*> packages;
|
||||
std::map<std::string, std::size_t> indices;
|
||||
for (const auto& id : chosen) {
|
||||
indices.emplace(id, packages.size());
|
||||
packages.push_back(catalog.at(id));
|
||||
}
|
||||
std::vector<std::vector<std::size_t>> edges(packages.size());
|
||||
for (std::size_t i = 0; i < packages.size(); ++i) {
|
||||
for (const auto& dep : packages[i]->dependencies) edges[indices.at(dep.id)].push_back(i);
|
||||
}
|
||||
Void::Algorithms::WorkLimits graph_limits;
|
||||
graph_limits.max_vertices = limits.packages;
|
||||
const auto topology = Void::Algorithms::topological_order(Void::Algorithms::AdjacencyView{edges}, graph_limits);
|
||||
if (!topology) {
|
||||
std::string message = topology.error().message;
|
||||
for (auto index : topology.error().cycle) message += " " + packages.at(index)->identity.id;
|
||||
context.fail("dependencies", message);
|
||||
}
|
||||
std::map<std::string, std::string> providers;
|
||||
std::set<std::string> definition_ids;
|
||||
for (const auto* package : packages) {
|
||||
context = {package->identity.id, package->source};
|
||||
for (const auto& capability : package->capabilities) {
|
||||
auto [provider, inserted] = providers.emplace(capability, package->identity.id);
|
||||
if (!inserted) context.fail("exclusive_capabilities", "conflicting provider for " + capability + ": " + provider->second);
|
||||
}
|
||||
for (const auto& definition : package->definitions) definition_ids.insert(definition.id);
|
||||
}
|
||||
for (const auto* package : packages) {
|
||||
context = {package->identity.id, package->source};
|
||||
std::set<std::string> accessible{package->identity.id};
|
||||
std::vector<std::string> dependencies{package->identity.id};
|
||||
for (std::size_t i = 0; i < dependencies.size(); ++i) {
|
||||
for (const auto& dep : catalog.at(dependencies[i])->dependencies) {
|
||||
if (accessible.insert(dep.id).second) dependencies.push_back(dep.id);
|
||||
}
|
||||
}
|
||||
for (const auto& definition : package->definitions) {
|
||||
for (const auto& reference : definition.references) {
|
||||
const auto owner = reference.substr(0, reference.find(':'));
|
||||
if (!accessible.contains(owner) || !definition_ids.contains(reference)) {
|
||||
context.fail("definitions." + definition.id + ".references", "unresolved or undeclared reference: " + reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<FrozenRulePackage> frozen;
|
||||
json::Value::Array array;
|
||||
for (const auto* package : packages) {
|
||||
frozen.push_back(package->identity);
|
||||
array.push_back(json::Value{json::Value::Object{
|
||||
{"id", json::Value{package->identity.id}},
|
||||
{"version", json::Value{package->identity.exact_version}},
|
||||
{"sha256", json::Value{rules_digest_hex(package->identity.content_sha256)}}}});
|
||||
}
|
||||
auto canonical = serialize(json::Value{json::Value::Object{
|
||||
{"schema", json::Value{std::int64_t{1}}}, {"packages", json::Value{std::move(array)}}}}, context, 8);
|
||||
const auto fingerprint = digest(canonical, context);
|
||||
return RulesManifest{std::move(frozen), fingerprint, std::move(canonical)};
|
||||
} catch (const InvalidRules& error) {
|
||||
return std::unexpected{error.diagnostic};
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<std::vector<RulePackage>, RulesDiagnostic> builtin_rule_packages() {
|
||||
constexpr std::string_view core = R"({"schema":1,"id":"settlement.core","version":"1.0.0","dependencies":[],"exclusive_capabilities":["settlement.core:materials"],"definitions":[{"id":"settlement.core:wood","kind":"item","data":{"stack_limit":64},"references":[]},{"id":"settlement.core:stone","kind":"item","data":{"stack_limit":64},"references":[]}]})";
|
||||
constexpr std::string_view colony = R"({"schema":1,"id":"settlement.colony","version":"1.0.0","dependencies":[{"id":"settlement.core","version":"1.0.0"}],"exclusive_capabilities":["settlement.colony:construction"],"definitions":[{"id":"settlement.colony:board","kind":"recipe","data":{"output_count":1,"work_ticks":8},"references":["settlement.core:wood"]}]})";
|
||||
auto first = load_rule_package("builtin/core", core);
|
||||
if (!first) return std::unexpected{first.error()};
|
||||
auto second = load_rule_package("builtin/colony", colony);
|
||||
if (!second) return std::unexpected{second.error()};
|
||||
return std::vector<RulePackage>{std::move(*first), std::move(*second)};
|
||||
}
|
||||
|
||||
std::expected<RulesManifest, RulesDiagnostic> default_rules_manifest() {
|
||||
auto packages = builtin_rule_packages();
|
||||
if (!packages) return std::unexpected{packages.error()};
|
||||
const std::array selected{std::string{"settlement.colony"}};
|
||||
return resolve_rules(*packages, selected);
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,336 @@
|
||||
#include "settlement/core/checkpoint.hpp"
|
||||
|
||||
#include <Void/Binary/Reader.hpp>
|
||||
#include <Void/Binary/Writer.hpp>
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
|
||||
constexpr Void::Uuid::Uuid world_id{{0x91, 2, 3, 4, 5, 6, 0x47, 8, 0x89, 10, 11, 12, 13, 14, 15, 16}};
|
||||
|
||||
void require(bool condition, std::string_view message) {
|
||||
if (!condition) throw std::runtime_error(std::string(message));
|
||||
}
|
||||
|
||||
template<class T, class Error>
|
||||
T checked(std::expected<T, Error> result) {
|
||||
if (!result) throw std::runtime_error(result.error().message);
|
||||
return std::move(*result);
|
||||
}
|
||||
|
||||
std::string saved_state(const World& world) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream);
|
||||
return std::move(stream).str();
|
||||
}
|
||||
|
||||
std::string encoded(const World& world, const RulesManifest& rules) {
|
||||
return checked(encode_checkpoint(world, world_id, 7, rules));
|
||||
}
|
||||
|
||||
WorldCheckpoint decoded(std::string_view bytes, std::span<const RulePackage> catalog) {
|
||||
return checked(decode_checkpoint(bytes, catalog, 1, ExecutionMode::SerialReference));
|
||||
}
|
||||
|
||||
void rejected(std::string_view bytes, std::span<const RulePackage> catalog,
|
||||
CheckpointError code, std::string_view field = {}, std::string_view package = {}) {
|
||||
const auto result = decode_checkpoint(bytes, catalog, 1, ExecutionMode::SerialReference);
|
||||
require(!result, "invalid checkpoint was accepted");
|
||||
require(result.error().code == code && !result.error().message.empty(), "checkpoint error lost its code or message");
|
||||
require(result.error().field.find(field) != std::string::npos, "checkpoint error named the wrong field");
|
||||
require(result.error().package.find(package) != std::string::npos, "checkpoint error lost its package");
|
||||
}
|
||||
|
||||
template<class T>
|
||||
void change(std::string& bytes, std::size_t offset, T value) {
|
||||
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}).subspan(offset));
|
||||
require(writer.writeLittle(value).has_value(), "fixture field write failed");
|
||||
}
|
||||
|
||||
void rehash(std::string& bytes) {
|
||||
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
|
||||
require(hasher.has_value(), "fixture hasher creation failed");
|
||||
require(hasher->update(std::string_view(bytes).substr(0, bytes.size() - 32)).has_value(), "fixture hash failed");
|
||||
const auto checksum = hasher->finalize();
|
||||
require(checksum.has_value() && checksum->size() == 32, "fixture hash finalization failed");
|
||||
std::memcpy(bytes.data() + bytes.size() - 32, checksum->data(), checksum->size());
|
||||
}
|
||||
|
||||
struct PackageLocation {
|
||||
std::size_t begin;
|
||||
std::size_t version_length;
|
||||
std::size_t end;
|
||||
};
|
||||
|
||||
struct FrameLayout {
|
||||
std::uint32_t metadata_size;
|
||||
std::uint64_t body_size;
|
||||
std::size_t body_begin;
|
||||
std::vector<PackageLocation> packages;
|
||||
};
|
||||
|
||||
FrameLayout layout(std::string_view bytes) {
|
||||
Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(), bytes.size()}));
|
||||
require(reader.skip(12).has_value(), "fixture header skip failed");
|
||||
FrameLayout result{};
|
||||
result.metadata_size = reader.readLittle<std::uint32_t>().value();
|
||||
result.body_size = reader.readLittle<std::uint64_t>().value();
|
||||
result.body_begin = 24 + result.metadata_size;
|
||||
require(reader.skip(64).has_value(), "fixture metadata skip failed");
|
||||
const auto count = reader.readLittle<std::uint32_t>().value();
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
const auto begin = reader.position();
|
||||
const auto id_size = reader.readLittle<std::uint16_t>().value();
|
||||
require(reader.skip(id_size).has_value(), "fixture ID skip failed");
|
||||
const auto version_length = reader.position();
|
||||
const auto version_size = reader.readLittle<std::uint16_t>().value();
|
||||
require(reader.skip(version_size + 32).has_value(), "fixture identity skip failed");
|
||||
result.packages.push_back({begin, version_length, reader.position()});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string package_json(std::string_view id, std::string_view version = "1.0.0",
|
||||
std::string_view dependencies = "[]") {
|
||||
return "{\"schema\":1,\"id\":\"" + std::string(id) + "\",\"version\":\"" + std::string(version) +
|
||||
"\",\"dependencies\":" + std::string(dependencies) + ",\"exclusive_capabilities\":[],\"definitions\":[]}";
|
||||
}
|
||||
|
||||
RulePackage load(std::string_view json) { return checked(load_rule_package("checkpoint-fixture.json", json)); }
|
||||
|
||||
struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Testing::Suite<CheckpointTests> {
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_round_trip_preserves_identity_and_legacy_world_bytes();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_mid_carry_round_trip_continues_the_same_world();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_selected_rules_survive_catalog_reordering();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_missing_changed_and_duplicate_installed_packages();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_integrity_covers_the_entire_frame_and_rejects_truncation();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_bounded_metadata_and_complete_dependency_closure();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_valid_checksum_still_requires_valid_identity_and_world();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_world_body_larger_than_one_shot_hash_limit();
|
||||
};
|
||||
|
||||
Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes() {
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto rules = checked(default_rules_manifest());
|
||||
World world(43, 8, 9, 1, ExecutionMode::SerialReference);
|
||||
static_cast<void>(world.spawn_agent({1, 1}));
|
||||
static_cast<void>(world.add_job({6, 6}, 4));
|
||||
for (int i = 0; i < 4; ++i) world.step();
|
||||
const auto before = saved_state(world);
|
||||
const auto bytes = encoded(world, rules);
|
||||
auto restored = decoded(bytes, catalog);
|
||||
require(restored.world_id == world_id && restored.city == 7 && restored.rules == rules,
|
||||
"checkpoint lost stable world identity, city or rules");
|
||||
require(saved_state(*restored.world) == before && saved_state(world) == before,
|
||||
"checkpoint changed the original or restored canonical state");
|
||||
require(bytes.substr(layout(bytes).body_begin, before.size()) == before,
|
||||
"checkpoint did not use the existing world serialization");
|
||||
require(before.substr(0, 8) == "SETTLERS" && static_cast<unsigned char>(before[8]) == 13,
|
||||
"canonical serialization version changed");
|
||||
require(encoded(*restored.world, restored.rules) == bytes, "re-encoding changed the checkpoint frame");
|
||||
auto parallel = checked(decode_checkpoint(bytes, catalog, 6));
|
||||
require(parallel.world->worker_count() == 6 && saved_state(*parallel.world) == before,
|
||||
"checkpoint did not honor requested execution configuration");
|
||||
auto nil = encode_checkpoint(world, {}, 7, rules);
|
||||
auto no_city = encode_checkpoint(world, world_id, 0, rules);
|
||||
require(!nil && nil.error().code == CheckpointError::InvalidIdentity &&
|
||||
!no_city && no_city.error().code == CheckpointError::InvalidIdentity,
|
||||
"encode accepted an invalid world or city identity");
|
||||
}
|
||||
|
||||
Test CheckpointTests::test_mid_carry_round_trip_continues_the_same_world() {
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto rules = checked(default_rules_manifest());
|
||||
auto world = make_first_colony(2);
|
||||
require(world->apply_command({1, 1, CommandKind::PlaceBed, {16, 18}}).status == CommandStatus::Accepted,
|
||||
"fixture bed placement failed");
|
||||
bool carrying = false;
|
||||
for (int i = 0; i < 300 && !carrying; ++i) {
|
||||
world->step();
|
||||
carrying = std::any_of(world->agents().begin(), world->agents().end(), [](const Agent& agent) {
|
||||
return agent.inventory.item_count(ItemType::Wood) > 0 ||
|
||||
agent.inventory.item_count(ItemType::Stone) > 0 ||
|
||||
agent.inventory.item_count(ItemType::Cloth) > 0;
|
||||
});
|
||||
}
|
||||
require(carrying, "fixture never carried construction material");
|
||||
const auto before = saved_state(*world);
|
||||
auto restored = decoded(encoded(*world, rules), catalog);
|
||||
require(saved_state(*restored.world) == before, "mid-carry checkpoint changed reservations or inventory");
|
||||
for (int i = 0; i < 300; ++i) {
|
||||
world->step();
|
||||
restored.world->step();
|
||||
require(saved_state(*world) == saved_state(*restored.world), "checkpoint continuation diverged");
|
||||
}
|
||||
require(world->scenario_progress().assigned_beds >= 1, "checkpoint fixture never completed its bed");
|
||||
}
|
||||
|
||||
Test CheckpointTests::test_selected_rules_survive_catalog_reordering() {
|
||||
std::vector<RulePackage> catalog{
|
||||
load(package_json("game.core")),
|
||||
load(package_json("game.water", "1.0.0", R"([{"id":"game.core","version":"1.0.0"}])")),
|
||||
load(package_json("game.unselected"))};
|
||||
const std::array dry_selection{std::string{"game.core"}};
|
||||
const std::array wet_selection{std::string{"game.water"}};
|
||||
const auto dry = checked(resolve_rules(catalog, dry_selection));
|
||||
const auto wet = checked(resolve_rules(catalog, wet_selection));
|
||||
World world(12, 5, 5, 1, ExecutionMode::SerialReference);
|
||||
const auto dry_frame = encoded(world, dry);
|
||||
const auto wet_frame = encoded(world, wet);
|
||||
std::reverse(catalog.begin(), catalog.end());
|
||||
require(decoded(dry_frame, catalog).rules == dry && decoded(wet_frame, catalog).rules == wet && dry != wet,
|
||||
"installed discovery order changed selected world rules");
|
||||
require(decoded(wet_frame, catalog).rules.packages().size() == 2,
|
||||
"unselected installed package entered the saved rules");
|
||||
}
|
||||
|
||||
Test CheckpointTests::test_missing_changed_and_duplicate_installed_packages() {
|
||||
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
|
||||
std::vector<RulePackage> catalog{load(package_json("game.core"))};
|
||||
const std::array selected{std::string{"game.core"}};
|
||||
const auto rules = checked(resolve_rules(catalog, selected));
|
||||
const auto bytes = encoded(world, rules);
|
||||
rejected(bytes, {}, CheckpointError::RulesMismatch, "packages", "game.core");
|
||||
for (std::string_view version : {"1.0.1", "1.0.0+build2"}) {
|
||||
const std::array changed{load(package_json("game.core", version))};
|
||||
rejected(bytes, changed, CheckpointError::RulesMismatch, "version", "game.core");
|
||||
}
|
||||
const std::array changed_content{load(R"({"schema":1,"id":"game.core","version":"1.0.0","dependencies":[],"exclusive_capabilities":["game.core:changed"],"definitions":[]})")};
|
||||
rejected(bytes, changed_content, CheckpointError::RulesMismatch, "sha256", "game.core");
|
||||
catalog.push_back(catalog.front());
|
||||
rejected(bytes, catalog, CheckpointError::RulesMismatch, "id", "game.core");
|
||||
}
|
||||
|
||||
Test CheckpointTests::test_integrity_covers_the_entire_frame_and_rejects_truncation() {
|
||||
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto bytes = encoded(world, checked(default_rules_manifest()));
|
||||
for (std::size_t length = 0; length < bytes.size(); ++length) {
|
||||
require(!decode_checkpoint(std::string_view(bytes).substr(0, length), catalog), "truncated frame was accepted");
|
||||
}
|
||||
rejected(bytes + "x", catalog, CheckpointError::InvalidFrame, "lengths");
|
||||
for (std::size_t offset : {std::size_t{24}, std::size_t{40}, std::size_t{48}, std::size_t{56},
|
||||
layout(bytes).packages.front().begin + 2, layout(bytes).body_begin, bytes.size() - 1}) {
|
||||
auto corrupt = bytes;
|
||||
corrupt[offset] ^= 1;
|
||||
rejected(corrupt, catalog, CheckpointError::IntegrityMismatch, "sha256");
|
||||
}
|
||||
auto unsupported = bytes;
|
||||
change(unsupported, 8, checkpoint_version + 1);
|
||||
rejected(unsupported, catalog, CheckpointError::UnsupportedVersion, "version");
|
||||
auto wrong_magic = bytes;
|
||||
wrong_magic[0] = 'X';
|
||||
rejected(wrong_magic, catalog, CheckpointError::InvalidFrame, "magic");
|
||||
}
|
||||
|
||||
Test CheckpointTests::test_bounded_metadata_and_complete_dependency_closure() {
|
||||
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto bytes = encoded(world, checked(default_rules_manifest()));
|
||||
const auto wire = layout(bytes);
|
||||
auto huge_body = bytes;
|
||||
change(huge_body, 16, std::numeric_limits<std::uint64_t>::max());
|
||||
rejected(huge_body, catalog, CheckpointError::LimitExceeded, "lengths");
|
||||
auto huge_metadata = bytes;
|
||||
change(huge_metadata, 12, static_cast<std::uint32_t>(max_checkpoint_metadata_bytes + 1));
|
||||
rejected(huge_metadata, catalog, CheckpointError::LimitExceeded, "lengths");
|
||||
for (std::uint32_t count : {0U, 129U}) {
|
||||
auto invalid = bytes;
|
||||
change(invalid, 88, count);
|
||||
rehash(invalid);
|
||||
rejected(invalid, catalog, CheckpointError::LimitExceeded, "rules.packages");
|
||||
}
|
||||
for (std::uint16_t count : {std::uint16_t{0}, std::uint16_t{129}}) {
|
||||
auto invalid = bytes;
|
||||
change(invalid, wire.packages.front().begin, count);
|
||||
rehash(invalid);
|
||||
rejected(invalid, catalog, CheckpointError::LimitExceeded, "rules.id");
|
||||
}
|
||||
auto long_version = bytes;
|
||||
change(long_version, wire.packages.front().version_length, std::uint16_t{257});
|
||||
rehash(long_version);
|
||||
rejected(long_version, catalog, CheckpointError::LimitExceeded, "rules.version");
|
||||
const auto first = wire.packages.front();
|
||||
const auto last = wire.packages.back();
|
||||
auto duplicate = bytes;
|
||||
const auto record = bytes.substr(first.begin, first.end - first.begin);
|
||||
duplicate.replace(last.begin, last.end - last.begin, record);
|
||||
change(duplicate, 12, static_cast<std::uint32_t>(wire.metadata_size + record.size() - (last.end - last.begin)));
|
||||
rehash(duplicate);
|
||||
rejected(duplicate, catalog, CheckpointError::RulesMismatch, "rules.packages", "settlement.colony");
|
||||
auto missing_dependency = bytes;
|
||||
missing_dependency.erase(last.begin, last.end - last.begin);
|
||||
change(missing_dependency, 12, static_cast<std::uint32_t>(wire.metadata_size - (last.end - last.begin)));
|
||||
change(missing_dependency, 88, std::uint32_t{1});
|
||||
rehash(missing_dependency);
|
||||
rejected(missing_dependency, catalog, CheckpointError::RulesMismatch, "rules.packages", "settlement.core");
|
||||
auto bad_fingerprint = bytes;
|
||||
bad_fingerprint[56] ^= 1;
|
||||
rehash(bad_fingerprint);
|
||||
rejected(bad_fingerprint, catalog, CheckpointError::RulesMismatch, "rules.fingerprint");
|
||||
}
|
||||
|
||||
Test CheckpointTests::test_valid_checksum_still_requires_valid_identity_and_world() {
|
||||
World world(4, 5, 5, 1, ExecutionMode::SerialReference);
|
||||
const auto before = saved_state(world);
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto bytes = encoded(world, checked(default_rules_manifest()));
|
||||
const auto wire = layout(bytes);
|
||||
auto nil = bytes;
|
||||
std::fill_n(nil.begin() + 24, 16, '\0');
|
||||
rehash(nil);
|
||||
rejected(nil, catalog, CheckpointError::InvalidIdentity, "world_id");
|
||||
auto no_city = bytes;
|
||||
change(no_city, 40, std::uint64_t{0});
|
||||
rehash(no_city);
|
||||
rejected(no_city, catalog, CheckpointError::InvalidIdentity, "city");
|
||||
auto wrong_tick = bytes;
|
||||
change(wrong_tick, 48, std::uint64_t{1});
|
||||
rehash(wrong_tick);
|
||||
rejected(wrong_tick, catalog, CheckpointError::InvalidWorld, "tick");
|
||||
auto invalid_dimensions = bytes;
|
||||
change(invalid_dimensions, wire.body_begin + 20, std::int32_t{0});
|
||||
rehash(invalid_dimensions);
|
||||
rejected(invalid_dimensions, catalog, CheckpointError::InvalidWorld, "world");
|
||||
auto invalid_counter = bytes;
|
||||
// The existing save13 header places next_agent_id after tick, four counters and hunger.
|
||||
change(invalid_counter, wire.body_begin + 69, std::uint64_t{0});
|
||||
rehash(invalid_counter);
|
||||
rejected(invalid_counter, catalog, CheckpointError::InvalidWorld, "world");
|
||||
auto inner_trailing = bytes;
|
||||
inner_trailing.insert(wire.body_begin + static_cast<std::size_t>(wire.body_size), 1, 'x');
|
||||
change(inner_trailing, 16, wire.body_size + 1);
|
||||
rehash(inner_trailing);
|
||||
rejected(inner_trailing, catalog, CheckpointError::InvalidWorld, "world");
|
||||
require(saved_state(world) == before, "failed checkpoint preparation changed the live world");
|
||||
}
|
||||
|
||||
Test CheckpointTests::test_world_body_larger_than_one_shot_hash_limit() {
|
||||
World world(1, 5, 5, 1, ExecutionMode::SerialReference);
|
||||
for (int i = 0; i < 700'000; ++i) static_cast<void>(world.add_job({1, 1}, 1));
|
||||
const auto rules = checked(default_rules_manifest());
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto bytes = encoded(world, rules);
|
||||
require(layout(bytes).body_size > 16 * 1024 * 1024, "fixture did not exceed the one-shot hash limit");
|
||||
auto restored = decoded(bytes, catalog);
|
||||
require(restored.world->jobs().size() == world.jobs().size() &&
|
||||
restored.world->jobs().back().id == world.jobs().back().id &&
|
||||
saved_state(*restored.world) == saved_state(world),
|
||||
"incremental checkpoint hash lost a large supported world");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -0,0 +1,226 @@
|
||||
#include "settlement/core/rules_manifest.hpp"
|
||||
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
|
||||
void require(bool condition, std::string_view message) {
|
||||
if (!condition) throw std::runtime_error(std::string(message));
|
||||
}
|
||||
|
||||
template <class T>
|
||||
T checked(std::expected<T, RulesDiagnostic> result) {
|
||||
if (!result) {
|
||||
const auto& d = result.error();
|
||||
throw std::runtime_error(d.source + " " + d.package + " " + d.field + " " + d.message);
|
||||
}
|
||||
return std::move(*result);
|
||||
}
|
||||
|
||||
std::string package(std::string_view id, std::string_view definitions = "[]",
|
||||
std::string_view dependencies = "[]", std::string_view capabilities = "[]",
|
||||
std::string_view version = "1.0.0") {
|
||||
return "{\"schema\":1,\"id\":\"" + std::string(id) + "\",\"version\":\"" + std::string(version) +
|
||||
"\",\"dependencies\":" + std::string(dependencies) + ",\"exclusive_capabilities\":" +
|
||||
std::string(capabilities) + ",\"definitions\":" + std::string(definitions) + "}";
|
||||
}
|
||||
|
||||
constexpr std::string_view wood = R"({"id":"game.core:wood","kind":"item","data":{"stack_limit":64},"references":[]})";
|
||||
constexpr std::string_view stone = R"({"id":"game.core:stone","kind":"item","data":{"stack_limit":32},"references":[]})";
|
||||
constexpr std::string_view board = R"([{"id":"game.colony:board","kind":"recipe","data":{"work_ticks":8},"references":["game.core:wood","game.core:stone"]}])";
|
||||
constexpr std::string_view core_dependency = R"([{"id":"game.core","version":">=1.0.0 <2.0.0"}])";
|
||||
|
||||
RulePackage load(std::string_view json) { return checked(load_rule_package("fixture.json", json)); }
|
||||
|
||||
RulesManifest resolve(std::vector<RulePackage> packages, std::vector<std::string> selected = {"game.colony"},
|
||||
const RulesLimits& limits = {}) {
|
||||
return checked(resolve_rules(packages, selected, limits));
|
||||
}
|
||||
|
||||
void parse_error(std::string_view json, std::string_view field, const RulesLimits& limits = {}) {
|
||||
const auto result = load_rule_package("bad-package.json", json, limits);
|
||||
require(!result, "invalid package was accepted");
|
||||
require(result.error().source == "bad-package.json" && result.error().field.find(field) != std::string::npos &&
|
||||
!result.error().message.empty(), "parser diagnostic lost source or field");
|
||||
}
|
||||
|
||||
void resolution_error(const std::vector<RulePackage>& packages, const std::vector<std::string>& selected,
|
||||
std::string_view field, const RulesLimits& limits = {}) {
|
||||
const auto result = resolve_rules(packages, selected, limits);
|
||||
require(!result, "invalid package set was accepted");
|
||||
require(result.error().field.find(field) != std::string::npos && !result.error().source.empty() &&
|
||||
!result.error().message.empty(), "resolver diagnostic lost source or field");
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("RulesTests")]] RulesTests : Void::Testing::Suite<RulesTests> {
|
||||
[[= Void::Testing::tag("rules")]] Test test_manifest_identity_is_independent_of_discovery_order();
|
||||
[[= Void::Testing::tag("rules")]] Test test_frozen_identity_covers_content_and_exact_versions();
|
||||
[[= Void::Testing::tag("rules")]] Test test_transitive_selection_and_unselected_packages();
|
||||
[[= Void::Testing::tag("rules")]] Test test_invalid_dependencies_and_provider_conflicts();
|
||||
[[= Void::Testing::tag("rules")]] Test test_definition_references_and_namespaces();
|
||||
[[= Void::Testing::tag("rules")]] Test test_strict_json_schema_and_input_budgets();
|
||||
[[= Void::Testing::tag("rules")]] Test test_catalog_and_model_limits();
|
||||
[[= Void::Testing::tag("rules")]] Test test_prerelease_policy();
|
||||
[[= Void::Testing::tag("rules")]] Test test_builtin_default_and_known_digest();
|
||||
};
|
||||
|
||||
Test RulesTests::test_manifest_identity_is_independent_of_discovery_order() {
|
||||
const auto core_a = load(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]"));
|
||||
const auto core_b = load(package("game.core", "[" + std::string(stone) + "," + std::string(wood) + "]"));
|
||||
const auto tools = load(package("game.tools"));
|
||||
const auto colony_a = load(package("game.colony", board,
|
||||
R"([{"id":"game.core","version":">=1.0.0 <2.0.0"},{"id":"game.tools","version":"1.0.0"}])",
|
||||
R"(["game.colony:weather","game.colony:building"])"));
|
||||
std::string reversed_board(board);
|
||||
const auto refs = reversed_board.find("\"game.core:wood\",\"game.core:stone\"");
|
||||
reversed_board.replace(refs, std::string("\"game.core:wood\",\"game.core:stone\"").size(),
|
||||
"\"game.core:stone\",\"game.core:wood\"");
|
||||
const auto colony_b = load(package("game.colony", reversed_board,
|
||||
R"([{"id":"game.tools","version":"1.0.0"},{"id":"game.core","version":">=1.0.0 <2.0.0"}])",
|
||||
R"(["game.colony:building","game.colony:weather"])"));
|
||||
const auto first = resolve({core_a, colony_a, tools});
|
||||
const auto second = resolve({tools, colony_b, core_b});
|
||||
require(first == second, "permuting package, definition, capability or reference order changed identity");
|
||||
require(first.packages().size() == 3 && first.packages()[0].id == "game.colony" &&
|
||||
first.packages()[1].id == "game.core", "frozen packages are not sorted by ID");
|
||||
require(core_a.canonical_json() == core_b.canonical_json(), "canonical package bytes changed with input order");
|
||||
const auto reloaded = load(core_a.canonical_json());
|
||||
require(reloaded.identity() == core_a.identity(), "canonical document did not round-trip");
|
||||
}
|
||||
|
||||
Test RulesTests::test_frozen_identity_covers_content_and_exact_versions() {
|
||||
const auto source = package("game.core", "[" + std::string(wood) + "]");
|
||||
const auto original = resolve({load(source)}, {"game.core"});
|
||||
const auto compare = [&](std::string changed) {
|
||||
require(resolve({load(changed)}, {"game.core"}) != original, "simulation change kept the frozen fingerprint");
|
||||
};
|
||||
auto modified = source;
|
||||
modified.replace(modified.find("64"), 2, "65");
|
||||
compare(modified);
|
||||
compare(package("game.core", "[" + std::string(wood) + "]", "[]", "[]", "1.0.1"));
|
||||
compare(package("game.core", "[" + std::string(wood) + "]", "[]", "[]", "1.0.0+build2"));
|
||||
compare(package("game.core"));
|
||||
modified = source;
|
||||
modified.replace(modified.find("game.core:wood"), 14, "game.core:logs");
|
||||
compare(modified);
|
||||
const auto a = resolve({load(package("game.core", R"([{"id":"game.core:path","kind":"event","data":[1,2],"references":[]}])"))}, {"game.core"});
|
||||
const auto b = resolve({load(package("game.core", R"([{"id":"game.core:path","kind":"event","data":[2,1],"references":[]}])"))}, {"game.core"});
|
||||
require(a != b, "ordered definition data was sorted as a set");
|
||||
}
|
||||
|
||||
Test RulesTests::test_transitive_selection_and_unselected_packages() {
|
||||
const auto core = load(package("game.core"));
|
||||
const auto colony = load(package("game.colony", "[]", core_dependency));
|
||||
const auto ui = load(package("game.ui", "[]", R"([{"id":"game.colony","version":"1.0.0"}])"));
|
||||
const auto broken_unselected = load(package("game.unselected", "[]", R"([{"id":"game.missing","version":"1.0.0"}])"));
|
||||
const auto first = resolve({ui, colony, core, broken_unselected}, {"game.ui"});
|
||||
const auto second = resolve({core, ui, colony}, {"game.core", "game.ui"});
|
||||
require(first == second && first.packages().size() == 3, "transitive dependency closure changed with selection order");
|
||||
resolution_error({core}, {"game.absent"}, "selected");
|
||||
resolution_error({core}, {}, "selected");
|
||||
resolution_error({core}, {"game.core", "game.core"}, "selected");
|
||||
}
|
||||
|
||||
Test RulesTests::test_invalid_dependencies_and_provider_conflicts() {
|
||||
const auto core = load(package("game.core"));
|
||||
resolution_error({core, core}, {"game.core"}, "id");
|
||||
resolution_error({load(package("game.colony", "[]", core_dependency))}, {"game.colony"}, "dependencies");
|
||||
const auto incompatible = load(package("game.colony", "[]", R"([{"id":"game.core","version":"^2.0.0"}])"));
|
||||
resolution_error({core, incompatible}, {"game.colony"}, "dependencies.game.core");
|
||||
const auto back_edge = load(package("game.core", "[]", R"([{"id":"game.colony","version":"*"}])"));
|
||||
resolution_error({back_edge, load(package("game.colony", "[]", core_dependency))}, {"game.colony"}, "dependencies");
|
||||
const auto provider_a = load(package("game.first", "[]", "[]", R"(["game.core:terrain"])"));
|
||||
const auto provider_b = load(package("game.second", "[]", "[]", R"(["game.core:terrain"])"));
|
||||
resolution_error({provider_a, provider_b}, {"game.first", "game.second"}, "exclusive_capabilities");
|
||||
parse_error(package("game.colony", "[]", R"([{"id":"game.core","version":"=>broken"}])"), "version");
|
||||
parse_error(package("game.colony", "[]", R"([{"id":"game.core","version":"*"},{"id":"game.core","version":"*"}])"), "dependencies");
|
||||
}
|
||||
|
||||
Test RulesTests::test_definition_references_and_namespaces() {
|
||||
const auto core = load(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]"));
|
||||
const auto colony = load(package("game.colony", board, core_dependency));
|
||||
static_cast<void>(resolve({core, colony}));
|
||||
resolution_error({load(package("game.core")), colony}, {"game.colony"}, "references");
|
||||
resolution_error({core, load(package("game.colony", board))}, {"game.core", "game.colony"}, "references");
|
||||
parse_error(package("game.colony", "[" + std::string(wood) + "]"), ".id");
|
||||
parse_error(package("game.core", "[" + std::string(wood) + "," + std::string(wood) + "]"), ".id");
|
||||
parse_error(package("game.core", R"([{"id":"game.core:bad","kind":"native","data":{},"references":[]}])"), ".kind");
|
||||
parse_error(package("game.core", R"([{"id":"game.core:bad","kind":"item","data":{},"references":["not-qualified"]}])"), ".references");
|
||||
}
|
||||
|
||||
Test RulesTests::test_strict_json_schema_and_input_budgets() {
|
||||
const auto valid = package("game.core");
|
||||
parse_error("{\"schema\":1,\"schema\":1}", "$");
|
||||
parse_error(valid + " false", "$");
|
||||
parse_error("{\"id\":\"\xff\"}", "$");
|
||||
parse_error("{}", "$");
|
||||
auto modified = valid;
|
||||
modified.insert(1, "\"sha256\":\"forged\",");
|
||||
parse_error(modified, "sha256");
|
||||
modified = valid;
|
||||
modified.replace(modified.find("\"schema\":1"), 10, "\"schema\":2");
|
||||
parse_error(modified, "schema");
|
||||
parse_error(package("Game"), "id");
|
||||
parse_error(package("game.core", "[]", "[]", "[]", "v1.0.0"), "version");
|
||||
parse_error(package("game.core", R"([{"id":"game.core:bad","kind":"item","data":0.5,"references":[]}])"), "$");
|
||||
RulesLimits limits;
|
||||
limits.package_bytes = valid.size() - 1;
|
||||
parse_error(valid, "$", limits);
|
||||
limits = {};
|
||||
limits.json_nodes = 4;
|
||||
parse_error(valid, "$", limits);
|
||||
limits = {};
|
||||
limits.json_depth = 2;
|
||||
parse_error(package("game.core", "[" + std::string(wood) + "]"), "$", limits);
|
||||
}
|
||||
|
||||
Test RulesTests::test_catalog_and_model_limits() {
|
||||
const auto core = load(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]"));
|
||||
const auto colony = load(package("game.colony", board, core_dependency));
|
||||
RulesLimits limits;
|
||||
limits.packages = 1;
|
||||
resolution_error({core, colony}, {"game.colony"}, "packages", limits);
|
||||
limits = {};
|
||||
limits.catalog_bytes = 2;
|
||||
resolution_error({core, colony}, {"game.colony"}, "packages", limits);
|
||||
limits = {};
|
||||
limits.definitions = 1;
|
||||
resolution_error({core}, {"game.core"}, "definitions", limits);
|
||||
parse_error(package("game.core", "[" + std::string(wood) + "," + std::string(stone) + "]"), "definitions", limits);
|
||||
limits = {};
|
||||
limits.dependencies = 0;
|
||||
parse_error(package("game.colony", board, core_dependency), "dependencies", limits);
|
||||
limits = {};
|
||||
limits.references = 1;
|
||||
parse_error(package("game.colony", board, core_dependency), "references", limits);
|
||||
}
|
||||
|
||||
Test RulesTests::test_prerelease_policy() {
|
||||
const auto prerelease = load(package("game.core", "[]", "[]", "[]", "1.0.0-preview+test"));
|
||||
const auto broad = load(package("game.colony", "[]", R"([{"id":"game.core","version":"*"}])"));
|
||||
resolution_error({prerelease, broad}, {"game.colony"}, "dependencies");
|
||||
const auto exact = load(package("game.colony", "[]", R"([{"id":"game.core","version":"=1.0.0-preview+test"}])"));
|
||||
const auto result = resolve({prerelease, exact});
|
||||
require(result.packages()[1].exact_version == "1.0.0-preview+test", "prerelease exact identity was lost");
|
||||
}
|
||||
|
||||
Test RulesTests::test_builtin_default_and_known_digest() {
|
||||
const auto first = checked(default_rules_manifest());
|
||||
const auto second = checked(default_rules_manifest());
|
||||
require(first == second && first.packages().size() == 2, "default rules were not reproducible");
|
||||
const auto empty = load(package("game.core"));
|
||||
require(rules_digest_hex(empty.identity().content_sha256) == "f6d1f704ccbb3ec707d2e1ba7b0db27dab8494b7787eeee10f1449dabee1477a", "package SHA-256 differs from the canonical-byte known vector");
|
||||
require(empty.definitions().empty(), "empty package gained a definition");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
Reference in new issue
Block a user