6#include <Poco/Dynamic/Var.h>
7#include <Poco/JSON/Array.h>
8#include <Poco/JSON/Object.h>
9#include <Poco/JSON/Parser.h>
10#include <Poco/JSON/Stringifier.h>
22#include <unordered_map>
23#include <unordered_set>
29bool isEngineName(
const std::string&
name) {
30 static const std::unordered_set<std::string> kSkip = {
75 "soft_reload_scripts",
78 "format_script_error",
85 "async_dispatch_event",
94 "dev_notify_frame_done",
97 return kSkip.count(
name) > 0;
100constexpr size_t kMaxGraphObjects = 65536;
102StateValue objectReference(
size_t id) {
109 std::unordered_map<const void*, size_t>
ids;
117 ~StackGuard() { sq_settop(vm, top); }
122 sq_resetobject(&obj);
123 sq_getstackobj(
vm,
idx, &obj);
124 return reinterpret_cast<const void*
>(obj._unVal.pRefCounted);
128bool isPlainDataType(SQObjectType
t) {
129 return t == OT_NULL ||
t == OT_INTEGER ||
t == OT_FLOAT ||
t == OT_BOOL ||
t == OT_STRING ||
t == OT_TABLE ||
133const char* sqTypeName(SQObjectType
t) {
135 case OT_CLOSURE:
return "function";
136 case OT_NATIVECLOSURE:
return "native function";
137 case OT_CLASS:
return "class";
138 case OT_INSTANCE:
return "class instance";
139 case OT_USERDATA:
return "userdata";
140 case OT_USERPOINTER:
return "userpointer";
141 case OT_THREAD:
return "thread";
142 case OT_GENERATOR:
return "generator";
143 case OT_WEAKREF:
return "weakref";
144 default:
return "value";
159struct SkippedValues {
160 std::vector<std::string>*
out =
nullptr;
162 static constexpr std::size_t kMaxRecorded = 64;
164 void add(
const std::string&
path, SQObjectType
type) {
165 if (!
out ||
out->size() >= kMaxRecorded)
return;
166 out->push_back(
path +
" (" + sqTypeName(
type) +
")");
171 const std::string&
path) {
174 const SQObjectType
t = sq_gettype(
vm,
idx);
176 if (
t == OT_TABLE ||
t == OT_ARRAY) {
177 const void*
id = objectId(
vm,
idx);
179 if (
graph.objects.arraySize() >= kMaxGraphObjects)
180 throw std::runtime_error(
"snapshot object limit exceeded at " +
path);
186 if (
depth > 32)
throw std::runtime_error(
"snapshot depth limit exceeded at " +
path);
194 case OT_NATIVECLOSURE:
202 skipped.add(
path.empty() ? std::string(
"<value>") :
path,
t);
208 sq_getinteger(
vm,
idx, &
v);
222 const SQChar*
s =
nullptr;
223 sq_getstring(
vm,
idx, &
s);
228 const SQInteger
top = sq_gettop(
vm);
229 const SQInteger
size = sq_getsize(
vm,
idx);
230 for (SQInteger i = 0; i <
size; ++i) {
231 sq_pushinteger(
vm, i);
232 if (SQ_SUCCEEDED(sq_get(
vm,
idx))) {
233 const SQObjectType et = sq_gettype(
vm, -1);
234 const std::string childPath =
path +
"[" + std::to_string(i) +
"]";
235 if (isPlainDataType(et)) {
236 arr.pushBack(sqToStateValue(
vm, -1,
graph,
depth + 1, skipped, childPath));
240 skipped.add(childPath, et);
251 node.set(
"value", std::move(arr));
253 return objectReference(
nodeId);
257 const SQInteger
top = sq_gettop(
vm);
259 while (SQ_SUCCEEDED(sq_next(
vm,
idx))) {
260 if (sq_gettype(
vm, -2) == OT_STRING) {
261 const SQChar*
key =
nullptr;
262 sq_getstring(
vm, -2, &
key);
264 const SQObjectType vt = sq_gettype(
vm, -1);
265 if (vt == OT_CLOSURE || vt == OT_NATIVECLOSURE || vt == OT_CLASS || vt == OT_INSTANCE ||
266 vt == OT_USERDATA || vt == OT_USERPOINTER || vt == OT_THREAD || vt == OT_GENERATOR ||
270 skipped.add(
path.empty() ? std::string(
key) :
path +
"." +
key, vt);
272 obj.set(std::string(
key),
278 throw std::runtime_error(
"unsupported non-string table key at " +
path);
285 node.set(
"value", std::move(obj));
287 return objectReference(
nodeId);
294 if (
depth > 32)
return false;
295 switch (var.kind()) {
301 const std::string&
s = var.asString();
302 sq_pushstring(
vm,
s.c_str(),
static_cast<SQInteger
>(
s.size()));
307 for (
size_t i = 0; i < var.arraySize(); ++i) {
308 if (!pushStateValue(
vm, var.at(i),
depth + 1))
return false;
309 sq_arrayappend(
vm, -2);
314 for (
const auto&
key : var.
keys()) {
315 sq_pushstring(
vm,
key.c_str(),
static_cast<SQInteger
>(
key.size()));
316 if (!pushStateValue(
vm, *var.find(
key),
depth + 1))
return false;
317 sq_newslot(
vm, -3, SQFalse);
326size_t referenceId(
const StateValue&
value,
size_t count) {
327 const StateValue*
id =
value.find(
"$ref");
328 if (!
value.isObject() ||
value.keys().size() != 1 || !
id || !
id->isInt() ||
id->asInt() < 0 ||
329 static_cast<uint64_t
>(
id->asInt()) >=
count)
330 throw std::runtime_error(
"invalid snapshot: malformed or dangling object reference");
331 return static_cast<size_t>(
id->asInt());
334void validateGraphValue(
const StateValue&
value,
size_t count) {
335 if (
value.isObject()) {
337 }
else if (
value.isArray()) {
338 throw std::runtime_error(
"invalid snapshot: inline graph container");
342const StateValue& validateGraph(
const StateValue& state) {
344 const StateValue* roots =
state.find(
"roots");
345 if (!
objects || !
objects->isArray() ||
objects->arraySize() > kMaxGraphObjects || !roots || !roots->isObject())
346 throw std::runtime_error(
"invalid snapshot: expected roots and object graph");
348 for (
const auto&
key : roots->
keys()) validateGraphValue(*roots->find(
key),
count);
349 for (
size_t i = 0; i <
count; ++i) {
351 const auto*
type =
node.find(
"type");
354 throw std::runtime_error(
"invalid snapshot: malformed object node " + std::to_string(i));
355 if (
type->asString() ==
"table" &&
value->isObject()) {
357 }
else if (
type->asString() ==
"array" &&
value->isArray()) {
358 for (
size_t j = 0; j <
value->arraySize(); ++j) validateGraphValue(
value->at(j),
count);
360 throw std::runtime_error(
"invalid snapshot: object type/payload mismatch at " + std::to_string(i));
367 if (
value.isObject()) {
368 sq_pushinteger(
vm,
static_cast<SQInteger
>(referenceId(
value,
count)));
369 if (SQ_FAILED(sq_rawget(
vm,
registry)))
throw std::runtime_error(
"snapshot object lookup failed");
370 }
else if (!pushStateValue(
vm,
value, 0)) {
371 throw std::runtime_error(
"invalid snapshot graph value");
377SQInteger stageGraph(
HSQUIRRELVM vm,
const StateValue& state) {
378 const auto&
objects = validateGraph(state);
381 for (
size_t i = 0; i <
objects.arraySize(); ++i) {
382 if (
objects.at(i).find(
"type")->asString() ==
"table")
386 if (SQ_FAILED(sq_arrayappend(
vm,
registry)))
throw std::runtime_error(
"snapshot object allocation failed");
388 for (
size_t i = 0; i <
objects.arraySize(); ++i) {
389 sq_pushinteger(
vm,
static_cast<SQInteger
>(i));
390 if (SQ_FAILED(sq_rawget(
vm,
registry)))
throw std::runtime_error(
"snapshot object lookup failed");
391 const SQInteger container = sq_gettop(
vm);
393 if (
value.isObject()) {
395 sq_pushstring(
vm,
key.c_str(),
static_cast<SQInteger
>(
key.size()));
397 if (SQ_FAILED(sq_rawset(
vm, container)))
throw std::runtime_error(
"snapshot table population failed");
400 for (
size_t j = 0; j <
value.arraySize(); ++j) {
402 if (SQ_FAILED(sq_arrayappend(
vm, container)))
403 throw std::runtime_error(
"snapshot array population failed");
411Poco::Dynamic::Var stateToVar(
const StateValue& var) {
412 switch (var.kind()) {
419 Poco::JSON::Array::Ptr arr(
new Poco::JSON::Array());
420 for (
size_t i = 0; i < var.arraySize(); ++i) arr->add(stateToVar(var.at(i)));
421 return Poco::Dynamic::Var(arr);
424 Poco::JSON::Object::Ptr obj(
new Poco::JSON::Object());
425 for (
const auto&
key : var.
keys()) obj->set(
key, stateToVar(*var.find(
key)));
426 return Poco::Dynamic::Var(obj);
429 return Poco::Dynamic::Var();
432StateValue varToState(
const Poco::Dynamic::Var& var) {
435 if (var.isInteger())
return StateValue::integer(
static_cast<int64_t
>(var.convert<Poco::Int64>()));
440 if (var.type() ==
typeid(Poco::JSON::Array::Ptr)) {
442 Poco::JSON::Array::Ptr
a = var.extract<Poco::JSON::Array::Ptr>();
444 for (
size_t i = 0; i <
a->size(); ++i)
445 arr.pushBack(varToState(
a->get(
static_cast<unsigned int>(i))));
448 }
catch (
const Poco::BadCastException&) {
453 if (var.type() ==
typeid(Poco::JSON::Object::Ptr)) {
455 Poco::JSON::Object::Ptr o = var.extract<Poco::JSON::Object::Ptr>();
457 for (
const auto&
name : o->getNames()) obj.set(
name, varToState(o->get(
name)));
460 }
catch (
const Poco::BadCastException&) {
476 if (
name.empty())
return;
477 unmarkTransientRoot(
name);
478 for (
const auto&
r : marked_) {
479 if (
r ==
name)
return;
481 marked_.push_back(std::move(
name));
485 marked_.erase(std::remove(marked_.begin(), marked_.end(),
name), marked_.end());
489 if (
name.empty())
return;
491 for (
const auto&
r : transient_) {
492 if (
r ==
name)
return;
494 transient_.push_back(std::move(
name));
498 transient_.erase(std::remove(transient_.begin(), transient_.end(),
name), transient_.end());
513 for (
auto&
name : persistent) markRoot(std::move(
name));
514 for (
auto&
name : transient) markTransientRoot(std::move(
name));
517std::vector<std::string> Snapshot::resolveRoots(
HSQUIRRELVM vm)
const {
518 if (!marked_.empty())
return marked_;
519 std::vector<std::string>
out;
522 const auto isTransient = [
this](
const std::string&
name) {
523 return std::find(transient_.begin(), transient_.end(),
name) != transient_.end();
526 for (
const char* pref : {
"eve_state",
"gameState",
"state"}) {
527 if (isTransient(pref))
continue;
528 const SQInteger
top = sq_gettop(
vm);
529 sq_pushroottable(
vm);
530 sq_pushstring(
vm, pref, -1);
531 if (SQ_SUCCEEDED(sq_get(
vm, -2))) {
532 const SQObjectType
t = sq_gettype(
vm, -1);
533 if (
t == OT_TABLE ||
t == OT_INSTANCE ||
t == OT_ARRAY)
out.emplace_back(pref);
537 if (!
out.empty())
return out;
539 const SQInteger
top = sq_gettop(
vm);
540 sq_pushroottable(
vm);
541 const SQInteger rootIdx = sq_gettop(
vm);
543 while (SQ_SUCCEEDED(sq_next(
vm, rootIdx))) {
544 if (sq_gettype(
vm, -2) == OT_STRING) {
545 const SQChar*
key =
nullptr;
546 sq_getstring(
vm, -2, &
key);
547 if (
key && !isEngineName(
key) && !isTransient(
key)) {
548 const SQObjectType vt = sq_gettype(
vm, -1);
549 if (vt == OT_INTEGER || vt == OT_FLOAT || vt == OT_BOOL || vt == OT_STRING || vt == OT_TABLE ||
566 StackGuard stack(
vm);
570 std::vector<std::string> skippedList;
571 SkippedValues skip{&skippedList};
572 auto rootNames = resolveRoots(
vm);
580 if (marked_.empty()) {
581 const SQInteger scanTop = sq_gettop(
vm);
582 sq_pushroottable(
vm);
583 const SQInteger rootIdx = sq_gettop(
vm);
585 while (SQ_SUCCEEDED(sq_next(
vm, rootIdx))) {
586 if (sq_gettype(
vm, -2) == OT_STRING) {
587 const SQChar*
key =
nullptr;
588 sq_getstring(
vm, -2, &
key);
589 const SQObjectType vt = sq_gettype(
vm, -1);
590 if (
key && (vt == OT_INSTANCE || vt == OT_USERDATA || vt == OT_USERPOINTER) && !isEngineName(
key) &&
591 std::find(transient_.begin(), transient_.end(),
key) == transient_.end()) {
597 sq_settop(
vm, scanTop);
602 for (
const auto&
name : rootNames) {
603 const SQInteger
top = sq_gettop(
vm);
604 sq_pushroottable(
vm);
605 sq_pushstring(
vm,
name.c_str(), -1);
606 if (SQ_SUCCEEDED(sq_get(
vm, -2))) {
607 const SQObjectType rt = sq_gettype(
vm, -1);
608 if (rt == OT_CLOSURE || rt == OT_NATIVECLOSURE || rt == OT_CLASS || rt == OT_INSTANCE ||
609 rt == OT_USERDATA || rt == OT_USERPOINTER || rt == OT_THREAD || rt == OT_GENERATOR ||
623 std::string nativeCaptureError;
626 auto captured =
p->capture();
630 nativeCaptureError +=
631 std::string(
p->stateKind()) +
": " + captured.diagnostics().front().message() +
"; ";
634 if (!nativeCaptureError.empty()) {
641 out.set(
"objects", std::move(
graph.objects));
642 out.set(
"roots", std::move(roots));
643 out.set(
"native", std::move(native));
647 if (!skippedList.empty()) {
650 out.set(
"skipped", std::move(list));
653 }
catch (
const std::exception& e) {
663 Poco::JSON::Object::Ptr doc = stateToVar(
state).extract<Poco::JSON::Object::Ptr>();
664 std::ostringstream oss;
667 }
catch (
const Poco::Exception& e) {
670 }
catch (
const std::exception& e) {
678 const auto* oldVersion = captured.
find(
"version");
680 if (!oldVersion || !oldVersion->isInt() || oldVersion->asInt() != 3 || !newVersion || !newVersion->isInt() ||
681 newVersion->asInt() != 3)
682 throw std::runtime_error(
"snapshot defaults merge requires version 3");
683 const auto& oldObjects = validateGraph(captured);
684 const auto& newObjects = validateGraph(
defaults);
685 const auto& oldRoots = *captured.
find(
"roots");
687 using Pair = std::tuple<size_t, size_t, bool>;
688 std::vector<Pair>
pairs;
689 std::set<Pair> visited;
690 std::unordered_map<size_t, size_t> mapping;
691 auto pairValues = [&](
const StateValue& oldValue,
const StateValue& newValue,
bool mergeFields) {
692 if (!oldValue.
isObject() || !newValue.isObject())
return;
693 const size_t oldId = referenceId(oldValue, oldObjects.
arraySize());
694 const size_t newId = referenceId(newValue, newObjects.arraySize());
695 if (oldObjects.at(oldId).find(
"type")->asString() != newObjects.at(newId).find(
"type")->asString())
return;
698 mapping.emplace(newId, oldId);
699 if (visited.emplace(oldId, newId, mergeFields).second) {
700 if (
pairs.size() >= kMaxGraphObjects)
701 throw std::runtime_error(
"snapshot correspondence limit exceeded during merge");
702 pairs.emplace_back(oldId, newId, mergeFields);
705 for (
const auto&
name : oldRoots.keys()) {
706 if (
const auto*
value = newRoots.find(
name)) pairValues(*oldRoots.find(
name), *
value,
true);
710 for (
size_t i = 0; i <
pairs.size(); ++i) {
711 const auto [oldId, newId, mergeFields] =
pairs[i];
712 const auto& oldValue = *oldObjects.
at(oldId).
find(
"value");
713 const auto& newValue = *newObjects.
at(newId).
find(
"value");
715 for (
const auto&
key : oldValue.
keys()) {
716 if (
const auto*
value = newValue.find(
key)) pairValues(*oldValue.
find(
key), *
value, mergeFields);
719 for (
size_t j = 0; j < std::min(oldValue.
arraySize(), newValue.arraySize()); ++j)
720 pairValues(oldValue.
at(j), newValue.
at(j),
false);
728 const size_t id = referenceId(
value, newObjects.arraySize());
729 auto found = mapping.find(
id);
730 if (
found == mapping.end()) {
731 if (
objects.arraySize() >= kMaxGraphObjects)
732 throw std::runtime_error(
"snapshot object limit exceeded during merge");
737 return objectReference(
found->second);
739 for (
const auto& [oldId, newId, mergeFields] :
pairs) {
740 const auto& newValue = *newObjects.at(newId).find(
"value");
741 if (!mergeFields || !newValue.isObject())
continue;
742 for (
const auto&
key : newValue.keys()) {
743 if (!
objects.at(oldId).find(
"value")->find(
key)) {
752 for (
size_t i = 0; i <
imported.size(); ++i) {
756 if (
value.isObject()) {
764 }
catch (
const std::exception&
error) {
774 StackGuard stack(
vm);
778 if (
error) *
error =
"invalid snapshot: missing roots";
783 if (
error) *
error =
"invalid snapshot: unsupported version";
791 const SQInteger staged = sq_gettop(
vm);
792 for (
const auto&
name : roots->
keys()) {
793 sq_pushstring(
vm,
name.c_str(),
static_cast<SQInteger
>(
name.size()));
796 }
else if (!pushStateValue(
vm, *roots->
find(
name), 0)) {
797 if (
error) *
error =
"failed to restore " +
name +
": snapshot depth limit exceeded";
800 if (SQ_FAILED(sq_rawset(
vm, staged))) {
807 if (native && !native->
isObject()) {
808 if (
error) *
error =
"invalid snapshot: native must be an object";
811 struct ProviderState {
817 std::vector<ProviderState> providers;
823 if (!reset && !
value)
return;
824 auto before =
p->capture();
826 throw std::runtime_error(std::string(
p->stateKind()) +
827 ": backup failed: " + before.diagnostics().front().message());
831 size_t attempted = 0;
833 for (
auto& entry : providers) {
835 auto result = entry.reset ? entry.provider->resetToDefaults() : entry.provider->restore(entry.after);
837 throw std::runtime_error(std::string(entry.provider->stateKind()) +
": " +
838 result.diagnostics().front().message());
840 }
catch (
const std::exception& failure) {
841 std::string
message = failure.what();
842 while (attempted > 0) {
843 auto& entry = providers[--attempted];
845 auto rollback = entry.provider->restore(entry.before);
847 message +=
"; rollback failed for " + std::string(entry.provider->stateKind()) +
": " +
848 rollback.diagnostics().front().message();
849 }
catch (
const std::exception& rollback) {
851 "; rollback failed for " + std::string(entry.provider->stateKind()) +
": " + rollback.what();
857 sq_pushroottable(
vm);
858 const SQInteger
root = sq_gettop(
vm);
860 while (SQ_SUCCEEDED(sq_next(
vm, staged))) {
865 }
catch (
const std::exception& e) {
873 Poco::JSON::Parser parser;
874 Poco::Dynamic::Var
result = parser.parse(json);
876 }
catch (
const Poco::Exception& e) {
879 }
catch (
const std::exception& e) {
886 const std::string json = capture(
vm,
error);
887 if (json.empty())
return false;
888 std::ofstream ofs(
path, std::ios::binary);
894 return static_cast<bool>(ofs);
898 std::ifstream ifs(
path, std::ios::binary);
903 std::ostringstream oss;
905 return restore(
vm, oss.str(),
error);
struct SQVM * HSQUIRRELVM
std::vector< Value > defaults
std::map< std::string, std::vector< std::string > > graph
const eve::script::BindingContractRegistry & registry
std::unordered_map< std::uint32_t, std::uint32_t > remap
ScriptProviderHandle provider
std::map< size_t, size_t > pairs
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
JSON-compatible state value tree used by state hot reload.
static StateValue object()
Empty object.
static StateValue boolean(bool v)
Boolean value.
static StateValue array()
Empty array.
static StateValue integer(int64_t v)
Integer value.
size_t arraySize() const
Element count; only valid on arrays.
static StateValue number(double v)
Floating-point value.
const StateValue * find(const std::string &key) const
Look up key; nullptr when absent.
static StateValue null()
Null value.
StateValue & at(size_t index)
Indexed element (bounds-checked); only valid on arrays.
std::vector< std::string > keys() const
Member names in insertion order.
static StateValue string(std::string v)
String value.
void set(const std::string &key, StateValue v)
Insert or replace key; only valid on objects.
The canonical owning dynamic value used by data-facing protocols.
static Value null()
Compatibility factory for a null value.
Runtime-state serialization for state hot reload.
bool captureState(HSQUIRRELVM vm, StateValue &out, std::string *error=nullptr) const
Capture script roots plus every Preserve IStateProvider.
bool restore(HSQUIRRELVM vm, const std::string &json, std::string *error=nullptr) const
bool restoreState(HSQUIRRELVM vm, const StateValue &state, std::string *error=nullptr) const
Restore a captured state; v1-shaped values restore roots only.
void unmarkTransientRoot(const std::string &name)
Remove an explicit transient-root declaration.
Result< StateValue > mergeDefaultsState(const StateValue &captured, const StateValue &defaults) const
Merge v3 script defaults while retaining captured values and identities.
std::string capture(HSQUIRRELVM vm, std::string *error=nullptr) const
Capture marked roots, or heuristic roots when none marked.
bool loadFile(HSQUIRRELVM vm, const std::string &path, std::string *error=nullptr) const
std::vector< std::string > roots() const
Return the explicit persistent roots.
std::vector< std::string > transientRoots() const
Return the explicit transient roots.
void setRootPolicies(std::vector< std::string > persistent, std::vector< std::string > transient)
Atomically replace explicit persistent/transient root policy.
static bool isEngineBinding(const std::string &name)
Built-in names never auto-captured (modules / boot bindings).
void markTransientRoot(std::string name)
Mark a root for reconstruction from new script definitions.
void markRoot(std::string name)
Mark a root as persistent, replacing a transient declaration.
bool saveFile(HSQUIRRELVM vm, const std::string &path, std::string *error=nullptr) const
static Snapshot & instance()
void unmarkRoot(const std::string &name)
Remove an explicit persistent-root declaration.
void clearRoots()
Clear every explicit persistent and transient declaration.
void keys(const Value &value, std::initializer_list< const char * > names)
StateValue toLegacyStateValue(const Value &value)
Project a canonical value into the legacy reload snapshot format.
Value toCanonicalStateValue(const StateValue &value)
Copy a legacy reload tree into the canonical owning value protocol.