400 lines
20 KiB
C++
400 lines
20 KiB
C++
#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
|