载入中...
搜索中...
未找到
Snapshot.cpp
浏览该文件的文档.
2
3#include "common/Capability.h"
5
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>
11
12#include <squirrel.h>
13
14#include <algorithm>
15#include <cstdint>
16#include <fstream>
17#include <set>
18#include <sstream>
19#include <stdexcept>
20#include <tuple>
21#include <typeinfo>
22#include <unordered_map>
23#include <unordered_set>
24#include <utility>
25
26namespace eve::dev {
27namespace {
28
29bool isEngineName(const std::string& name) {
30 static const std::unordered_set<std::string> kSkip = {
31 "eve",
32 "win",
33 "gfx",
34 "event",
35 "timer",
36 "system",
37 "math",
38 "tf",
39 "ui",
40 "scene",
41 "particles",
42 "map",
43 "gpgpu",
44 "physics",
45 "keyboard",
46 "mouse",
47 "touch",
48 "sound",
49 "audio",
50 "model3d",
51 "font",
52 "thread",
53 "fs",
54 "hot",
55 "config",
56 "require",
57 "path",
58 "exports",
59 "module",
60 "console",
61 "process",
62 "stdin",
63 "stdout",
64 "stderr",
65 "_version_",
66 "ARGV",
67 "eve_init",
68 "eve_update",
69 "eve_render",
70 "eve_quit",
71 "eve_reload",
72 "eve_asset_reload",
73 "watched_scripts",
74 "track_script",
75 "soft_reload_scripts",
76 "poll_hot_reload",
77 "file_exists",
78 "format_script_error",
79 "emit_loop_error",
80 "clear_loop_error",
81 "_loop_errors",
82 "path_endswith",
83 "normalize_path",
84 "async_pump",
85 "async_dispatch_event",
86 "Promise",
87 "setTimeout",
88 "clearTimeout",
89 "nextTick",
90 "setImmediate",
91 "has_dev",
92 "dev_poll",
93 "dev_should_update",
94 "dev_notify_frame_done",
95 "handle_dev_key",
96 };
97 return kSkip.count(name) > 0;
98}
99
100constexpr size_t kMaxGraphObjects = 65536;
101
102StateValue objectReference(size_t id) {
103 StateValue ref = StateValue::object();
104 ref.set("$ref", StateValue::integer(static_cast<int64_t>(id)));
105 return ref;
106}
107
108struct CaptureGraph {
109 std::unordered_map<const void*, size_t> ids;
111};
112
113struct StackGuard {
115 SQInteger top;
116 explicit StackGuard(HSQUIRRELVM handle) : vm(handle), top(sq_gettop(handle)) {}
117 ~StackGuard() { sq_settop(vm, top); }
118};
119
120const void* objectId(HSQUIRRELVM vm, SQInteger idx) {
121 HSQOBJECT obj;
122 sq_resetobject(&obj);
123 sq_getstackobj(vm, idx, &obj);
124 return reinterpret_cast<const void*>(obj._unVal.pRefCounted);
125}
126
128bool isPlainDataType(SQObjectType t) {
129 return t == OT_NULL || t == OT_INTEGER || t == OT_FLOAT || t == OT_BOOL || t == OT_STRING || t == OT_TABLE ||
130 t == OT_ARRAY;
131}
132
133const char* sqTypeName(SQObjectType t) {
134 switch (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";
145 }
146}
147
159struct SkippedValues {
160 std::vector<std::string>* out = nullptr;
161
162 static constexpr std::size_t kMaxRecorded = 64;
163
164 void add(const std::string& path, SQObjectType type) {
165 if (!out || out->size() >= kMaxRecorded) return;
166 out->push_back(path + " (" + sqTypeName(type) + ")");
167 }
168};
169
170StateValue sqToStateValue(HSQUIRRELVM vm, SQInteger idx, CaptureGraph& graph, int depth, SkippedValues& skipped,
171 const std::string& path) {
172 if (idx < 0) idx = sq_gettop(vm) + idx + 1;
173
174 const SQObjectType t = sq_gettype(vm, idx);
175 size_t nodeId = 0;
176 if (t == OT_TABLE || t == OT_ARRAY) {
177 const void* id = objectId(vm, idx);
178 if (auto found = graph.ids.find(id); found != graph.ids.end()) return objectReference(found->second);
179 if (graph.objects.arraySize() >= kMaxGraphObjects)
180 throw std::runtime_error("snapshot object limit exceeded at " + path);
181 nodeId = graph.objects.arraySize();
182 graph.ids.emplace(id, nodeId);
183 // Reserve identity before descending so back edges resolve immediately.
184 graph.objects.pushBack(StateValue::null());
185 }
186 if (depth > 32) throw std::runtime_error("snapshot depth limit exceeded at " + path);
187 switch (t) {
188 // Not state at any depth. Capturing a class instance's members as a plain object
189 // looked harmless, but restore pushes a table, so the value came back with a
190 // different type than the reloaded script declared (`squad[0]` was an instance
191 // before and a table after). Recorded here as well as at the callers, so no future
192 // path can quietly coerce one.
193 case OT_CLOSURE:
194 case OT_NATIVECLOSURE:
195 case OT_CLASS:
196 case OT_INSTANCE:
197 case OT_USERDATA:
198 case OT_USERPOINTER:
199 case OT_THREAD:
200 case OT_GENERATOR:
201 case OT_WEAKREF: {
202 skipped.add(path.empty() ? std::string("<value>") : path, t);
203 return StateValue::null();
204 }
205 case OT_NULL: return StateValue::null();
206 case OT_INTEGER: {
207 SQInteger v = 0;
208 sq_getinteger(vm, idx, &v);
209 return StateValue::integer(static_cast<int64_t>(v));
210 }
211 case OT_FLOAT: {
212 SQFloat v = 0;
213 sq_getfloat(vm, idx, &v);
214 return StateValue::number(static_cast<double>(v));
215 }
216 case OT_BOOL: {
217 SQBool v = SQFalse;
218 sq_getbool(vm, idx, &v);
219 return StateValue::boolean(v != SQFalse);
220 }
221 case OT_STRING: {
222 const SQChar* s = nullptr;
223 sq_getstring(vm, idx, &s);
224 return StateValue::string(s ? std::string(s) : std::string{});
225 }
226 case OT_ARRAY: {
227 StateValue arr = StateValue::array();
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));
237 } else {
238 // Recorded and replaced by null so the remaining indices keep their
239 // position (the same reason a failed sq_get pushes null below).
240 skipped.add(childPath, et);
241 arr.pushBack(StateValue::null());
242 }
243 sq_poptop(vm);
244 } else {
245 arr.pushBack(StateValue::null());
246 }
247 }
248 sq_settop(vm, top);
249 StateValue node = StateValue::object();
250 node.set("type", StateValue::string("array"));
251 node.set("value", std::move(arr));
252 graph.objects.at(nodeId) = std::move(node);
253 return objectReference(nodeId);
254 }
255 case OT_TABLE: {
256 StateValue obj = StateValue::object();
257 const SQInteger top = sq_gettop(vm);
258 sq_pushnull(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);
263 if (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 ||
267 vt == OT_WEAKREF) {
268 // Left out on purpose (the reloaded script recreates it), but
269 // recorded so the omission is inspectable instead of silent.
270 skipped.add(path.empty() ? std::string(key) : path + "." + key, vt);
271 } else {
272 obj.set(std::string(key),
273 sqToStateValue(vm, -1, graph, depth + 1, skipped,
274 path.empty() ? std::string(key) : path + "." + key));
275 }
276 }
277 } else {
278 throw std::runtime_error("unsupported non-string table key at " + path);
279 }
280 sq_pop(vm, 2);
281 }
282 sq_settop(vm, top);
283 StateValue node = StateValue::object();
284 node.set("type", StateValue::string("table"));
285 node.set("value", std::move(obj));
286 graph.objects.at(nodeId) = std::move(node);
287 return objectReference(nodeId);
288 }
289 default: return StateValue::null();
290 }
291}
292
293bool pushStateValue(HSQUIRRELVM vm, const StateValue& var, int depth) {
294 if (depth > 32) return false;
295 switch (var.kind()) {
296 case StateValue::Kind::Null: sq_pushnull(vm); return true;
297 case StateValue::Kind::Bool: sq_pushbool(vm, var.asBool() ? SQTrue : SQFalse); return true;
298 case StateValue::Kind::Int: sq_pushinteger(vm, static_cast<SQInteger>(var.asInt())); return true;
299 case StateValue::Kind::Float: sq_pushfloat(vm, static_cast<SQFloat>(var.asDouble())); return true;
301 const std::string& s = var.asString();
302 sq_pushstring(vm, s.c_str(), static_cast<SQInteger>(s.size()));
303 return true;
304 }
306 sq_newarray(vm, 0);
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);
310 }
311 return true;
313 sq_newtable(vm);
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);
318 }
319 return true;
320 }
321 return false;
322}
323
324// Encoded values are scalars or exact {"$ref": index} records. User tables
325// live inside node.value, so a user member named "$ref" never becomes metadata.
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());
332}
333
334void validateGraphValue(const StateValue& value, size_t count) {
335 if (value.isObject()) {
336 referenceId(value, count);
337 } else if (value.isArray()) {
338 throw std::runtime_error("invalid snapshot: inline graph container");
339 }
340}
341
342const StateValue& validateGraph(const StateValue& state) {
343 const StateValue* objects = state.find("objects");
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");
347 const size_t count = objects->arraySize();
348 for (const auto& key : roots->keys()) validateGraphValue(*roots->find(key), count);
349 for (size_t i = 0; i < count; ++i) {
350 const auto& node = objects->at(i);
351 const auto* type = node.find("type");
352 const auto* value = node.find("value");
353 if (!node.isObject() || node.keys().size() != 2 || !type || !type->isString() || !value)
354 throw std::runtime_error("invalid snapshot: malformed object node " + std::to_string(i));
355 if (type->asString() == "table" && value->isObject()) {
356 for (const auto& key : value->keys()) validateGraphValue(*value->find(key), count);
357 } else if (type->asString() == "array" && value->isArray()) {
358 for (size_t j = 0; j < value->arraySize(); ++j) validateGraphValue(value->at(j), count);
359 } else {
360 throw std::runtime_error("invalid snapshot: object type/payload mismatch at " + std::to_string(i));
361 }
362 }
363 return *objects;
364}
365
366void pushGraphValue(HSQUIRRELVM vm, const StateValue& value, SQInteger registry, size_t count) {
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");
372 }
373}
374
375// The registry is a VM-owned array: it keeps every allocated container alive
376// throughout both passes without borrowing raw object pointers across allocations.
377SQInteger stageGraph(HSQUIRRELVM vm, const StateValue& state) {
378 const auto& objects = validateGraph(state);
379 sq_newarray(vm, 0);
380 const SQInteger registry = sq_gettop(vm);
381 for (size_t i = 0; i < objects.arraySize(); ++i) {
382 if (objects.at(i).find("type")->asString() == "table")
383 sq_newtable(vm);
384 else
385 sq_newarray(vm, 0);
386 if (SQ_FAILED(sq_arrayappend(vm, registry))) throw std::runtime_error("snapshot object allocation failed");
387 }
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);
392 const auto& value = *objects.at(i).find("value");
393 if (value.isObject()) {
394 for (const auto& key : value.keys()) {
395 sq_pushstring(vm, key.c_str(), static_cast<SQInteger>(key.size()));
396 pushGraphValue(vm, *value.find(key), registry, objects.arraySize());
397 if (SQ_FAILED(sq_rawset(vm, container))) throw std::runtime_error("snapshot table population failed");
398 }
399 } else {
400 for (size_t j = 0; j < value.arraySize(); ++j) {
401 pushGraphValue(vm, value.at(j), registry, objects.arraySize());
402 if (SQ_FAILED(sq_arrayappend(vm, container)))
403 throw std::runtime_error("snapshot array population failed");
404 }
405 }
406 sq_poptop(vm);
407 }
408 return registry;
409}
410
411Poco::Dynamic::Var stateToVar(const StateValue& var) {
412 switch (var.kind()) {
413 case StateValue::Kind::Null: return Poco::Dynamic::Var();
414 case StateValue::Kind::Bool: return Poco::Dynamic::Var(var.asBool());
415 case StateValue::Kind::Int: return Poco::Dynamic::Var(static_cast<Poco::Int64>(var.asInt()));
416 case StateValue::Kind::Float: return Poco::Dynamic::Var(var.asDouble());
417 case StateValue::Kind::String: return Poco::Dynamic::Var(var.asString());
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);
422 }
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);
427 }
428 }
429 return Poco::Dynamic::Var();
430}
431
432StateValue varToState(const Poco::Dynamic::Var& var) {
433 if (var.isEmpty()) return StateValue::null();
434 if (var.isBoolean()) return StateValue::boolean(var.convert<bool>());
435 if (var.isInteger()) return StateValue::integer(static_cast<int64_t>(var.convert<Poco::Int64>()));
436 if (var.isNumeric()) return StateValue::number(var.convert<double>());
437 if (var.isString()) return StateValue::string(var.convert<std::string>());
438
439 try {
440 if (var.type() == typeid(Poco::JSON::Array::Ptr)) {
441 StateValue arr = StateValue::array();
442 Poco::JSON::Array::Ptr a = var.extract<Poco::JSON::Array::Ptr>();
443 if (a)
444 for (size_t i = 0; i < a->size(); ++i)
445 arr.pushBack(varToState(a->get(static_cast<unsigned int>(i))));
446 return arr;
447 }
448 } catch (const Poco::BadCastException&) {
449 // fall through
450 }
451
452 try {
453 if (var.type() == typeid(Poco::JSON::Object::Ptr)) {
454 StateValue obj = StateValue::object();
455 Poco::JSON::Object::Ptr o = var.extract<Poco::JSON::Object::Ptr>();
456 if (o)
457 for (const auto& name : o->getNames()) obj.set(name, varToState(o->get(name)));
458 return obj;
459 }
460 } catch (const Poco::BadCastException&) {
461 // fall through
462 }
463 return StateValue::null();
464}
465
466} // namespace
467
469 static Snapshot inst;
470 return inst;
471}
472
473bool Snapshot::isEngineBinding(const std::string& name) { return isEngineName(name); }
474
475void Snapshot::markRoot(std::string name) {
476 if (name.empty()) return;
477 unmarkTransientRoot(name);
478 for (const auto& r : marked_) {
479 if (r == name) return;
480 }
481 marked_.push_back(std::move(name));
482}
483
484void Snapshot::unmarkRoot(const std::string& name) {
485 marked_.erase(std::remove(marked_.begin(), marked_.end(), name), marked_.end());
486}
487
489 if (name.empty()) return;
490 unmarkRoot(name);
491 for (const auto& r : transient_) {
492 if (r == name) return;
493 }
494 transient_.push_back(std::move(name));
495}
496
497void Snapshot::unmarkTransientRoot(const std::string& name) {
498 transient_.erase(std::remove(transient_.begin(), transient_.end(), name), transient_.end());
499}
500
502 marked_.clear();
503 transient_.clear();
504}
505
506std::vector<std::string> Snapshot::roots() const { return marked_; }
507
508std::vector<std::string> Snapshot::transientRoots() const { return transient_; }
509
510void Snapshot::setRootPolicies(std::vector<std::string> persistent, std::vector<std::string> transient) {
511 marked_.clear();
512 transient_.clear();
513 for (auto& name : persistent) markRoot(std::move(name));
514 for (auto& name : transient) markTransientRoot(std::move(name));
515}
516
517std::vector<std::string> Snapshot::resolveRoots(HSQUIRRELVM vm) const {
518 if (!marked_.empty()) return marked_;
519 std::vector<std::string> out;
520 if (!vm) return out;
521
522 const auto isTransient = [this](const std::string& name) {
523 return std::find(transient_.begin(), transient_.end(), name) != transient_.end();
524 };
525
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);
534 }
535 sq_settop(vm, top);
536 }
537 if (!out.empty()) return out;
538
539 const SQInteger top = sq_gettop(vm);
540 sq_pushroottable(vm);
541 const SQInteger rootIdx = sq_gettop(vm);
542 sq_pushnull(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 ||
550 vt == OT_ARRAY) {
551 out.emplace_back(key);
552 }
553 }
554 }
555 sq_pop(vm, 2);
556 }
557 sq_settop(vm, top);
558 return out;
559}
560
562 if (!vm) {
563 if (error) *error = "no vm";
564 return false;
565 }
566 StackGuard stack(vm);
567 try {
568 // The omissions travel inside the captured state (`skipped`), so callers and the
569 // persisted file see them without a second out-parameter.
570 std::vector<std::string> skippedList;
571 SkippedValues skip{&skippedList};
572 auto rootNames = resolveRoots(vm);
573
574 // Live objects at the root (`hero <- Hero()`, an ECS world) look like state but
575 // cannot be captured. The heuristic only *returns* plain-data roots, so without
576 // this pass they would vanish without a trace. Function and class definitions are
577 // ordinary script bindings -- naming every one of them would drown the list -- so
578 // only instances/userdata are reported, and only when the heuristic picked the
579 // roots (a caller who marked roots asked about those specific names).
580 if (marked_.empty()) {
581 const SQInteger scanTop = sq_gettop(vm);
582 sq_pushroottable(vm);
583 const SQInteger rootIdx = sq_gettop(vm);
584 sq_pushnull(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()) {
592 skip.add(key, vt);
593 }
594 }
595 sq_pop(vm, 2);
596 }
597 sq_settop(vm, scanTop);
598 }
599
601 CaptureGraph graph;
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 ||
610 rt == OT_WEAKREF) {
611 // Reachable for an explicitly marked root: left out and reported, the
612 // same as an unserializable member. Failing here made a marked entity
613 // root refuse the whole reload.
614 skip.add(name, rt);
615 } else {
616 roots.set(name, sqToStateValue(vm, -1, graph, 0, skip, name));
617 }
618 }
619 sq_settop(vm, top);
620 }
621
623 std::string nativeCaptureError;
624 eve::cap::forEach<eve::caps::IStateProvider>([&](eve::caps::IStateProvider* p) {
625 if (p->reloadPolicy() == eve::caps::StateReloadPolicy::Reset) return;
626 auto captured = p->capture();
627 if (captured.ok()) {
628 native.set(p->stateKind(), toLegacyStateValue(std::move(captured).takeValue()));
629 } else {
630 nativeCaptureError +=
631 std::string(p->stateKind()) + ": " + captured.diagnostics().front().message() + "; ";
632 }
633 });
634 if (!nativeCaptureError.empty()) {
635 if (error) *error = nativeCaptureError;
636 return false;
637 }
638
640 out.set("version", StateValue::integer(3));
641 out.set("objects", std::move(graph.objects));
642 out.set("roots", std::move(roots));
643 out.set("native", std::move(native));
644 // Kept in the snapshot so the omission is visible to whoever reads it (the tool
645 // response, the persisted eve_snapshot.json, ReloadSession's notice).
646 // restoreState() ignores this key.
647 if (!skippedList.empty()) {
649 for (const auto& entry : skippedList) list.pushBack(StateValue::string(entry));
650 out.set("skipped", std::move(list));
651 }
652 return true;
653 } catch (const std::exception& e) {
654 if (error) *error = e.what();
655 return false;
656 }
657}
658
659std::string Snapshot::capture(HSQUIRRELVM vm, std::string* error) const {
661 if (!captureState(vm, state, error)) return {};
662 try {
663 Poco::JSON::Object::Ptr doc = stateToVar(state).extract<Poco::JSON::Object::Ptr>();
664 std::ostringstream oss;
665 doc->stringify(oss);
666 return oss.str();
667 } catch (const Poco::Exception& e) {
668 if (error) *error = e.displayText();
669 return {};
670 } catch (const std::exception& e) {
671 if (error) *error = e.what();
672 return {};
673 }
674}
675
677 try {
678 const auto* oldVersion = captured.find("version");
679 const auto* newVersion = defaults.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");
686 const auto& newRoots = *defaults.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;
696 // Captured identities win when new definitions have a different alias
697 // topology. New fields referring to an existing node use its first match.
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);
703 }
704 };
705 for (const auto& name : oldRoots.keys()) {
706 if (const auto* value = newRoots.find(name)) pairValues(*oldRoots.find(name), *value, true);
707 }
708 // Establish correspondences before importing missing fields. Walk array
709 // items for identity matching too, but retain their entire captured content.
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");
714 if (oldValue.isObject()) {
715 for (const auto& key : oldValue.keys()) {
716 if (const auto* value = newValue.find(key)) pairValues(*oldValue.find(key), *value, mergeFields);
717 }
718 } else {
719 for (size_t j = 0; j < std::min(oldValue.arraySize(), newValue.arraySize()); ++j)
720 pairValues(oldValue.at(j), newValue.at(j), false);
721 }
722 }
723 StateValue result = captured;
724 StateValue& objects = *result.find("objects");
725 std::vector<size_t> imported;
726 auto remap = [&](const StateValue& value) {
727 if (!value.isObject()) return value;
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");
733 found = mapping.emplace(id, objects.arraySize()).first;
734 objects.pushBack(StateValue::null());
735 imported.push_back(id);
736 }
737 return objectReference(found->second);
738 };
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)) {
744 auto value = remap(*newValue.find(key));
745 // remap can grow objects; reacquire the owning node afterwards.
746 objects.at(oldId).find("value")->set(key, std::move(value));
747 }
748 }
749 }
750 // Import only nodes reachable from added fields. Reserve each identity
751 // before following its edges, preserving forward links and cycles.
752 for (size_t i = 0; i < imported.size(); ++i) {
753 const size_t id = imported[i];
754 StateValue node = newObjects.at(id);
755 auto& value = *node.find("value");
756 if (value.isObject()) {
757 for (const auto& key : value.keys()) value.set(key, remap(*value.find(key)));
758 } else {
759 for (size_t j = 0; j < value.arraySize(); ++j) value.at(j) = remap(value.at(j));
760 }
761 objects.at(mapping.at(id)) = std::move(node);
762 }
763 return Result<StateValue>::success(std::move(result));
764 } catch (const std::exception& error) {
766 }
767}
768
769bool Snapshot::restoreState(HSQUIRRELVM vm, const StateValue& state, std::string* error) const {
770 if (!vm) {
771 if (error) *error = "no vm";
772 return false;
773 }
774 StackGuard stack(vm);
775 try {
776 const StateValue* roots = state.find("roots");
777 if (!roots || !roots->isObject()) {
778 if (error) *error = "invalid snapshot: missing roots";
779 return false;
780 }
781 const StateValue* version = state.find("version");
782 if (version && (!version->isInt() || version->asInt() < 1 || version->asInt() > 3)) {
783 if (error) *error = "invalid snapshot: unsupported version";
784 return false;
785 }
786 const bool graphFormat = version && version->asInt() == 3;
787 const SQInteger registry = graphFormat ? stageGraph(vm, state) : 0;
788 // Build every root before touching live state. A late depth/type failure
789 // must not replace roots that happened to precede it in the document.
790 sq_newtable(vm);
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()));
794 if (graphFormat) {
795 pushGraphValue(vm, *roots->find(name), registry, state.find("objects")->arraySize());
796 } else if (!pushStateValue(vm, *roots->find(name), 0)) {
797 if (error) *error = "failed to restore " + name + ": snapshot depth limit exceeded";
798 return false;
799 }
800 if (SQ_FAILED(sq_rawset(vm, staged))) {
801 if (error) *error = "failed to stage " + name;
802 return false;
803 }
804 }
805
806 const StateValue* native = state.find("native");
807 if (native && !native->isObject()) {
808 if (error) *error = "invalid snapshot: native must be an object";
809 return false;
810 }
811 struct ProviderState {
812 eve::caps::IStateProvider* provider; // Borrowed for this synchronous restore.
813 Value before;
814 Value after;
815 bool reset;
816 };
817 std::vector<ProviderState> providers;
818 // Capture all affected providers before any provider mutates. Reset-policy
819 // providers need a backup too: reset itself can fail after changing state.
820 eve::cap::forEach<eve::caps::IStateProvider>([&](eve::caps::IStateProvider* p) {
821 const bool reset = p->reloadPolicy() == eve::caps::StateReloadPolicy::Reset;
822 const StateValue* value = native ? native->find(p->stateKind()) : nullptr;
823 if (!reset && !value) return;
824 auto before = p->capture();
825 if (!before.ok())
826 throw std::runtime_error(std::string(p->stateKind()) +
827 ": backup failed: " + before.diagnostics().front().message());
828 providers.push_back(
829 {p, std::move(before).takeValue(), value ? toCanonicalStateValue(*value) : Value::null(), reset});
830 });
831 size_t attempted = 0;
832 try {
833 for (auto& entry : providers) {
834 ++attempted;
835 auto result = entry.reset ? entry.provider->resetToDefaults() : entry.provider->restore(entry.after);
836 if (!result.ok())
837 throw std::runtime_error(std::string(entry.provider->stateKind()) + ": " +
838 result.diagnostics().front().message());
839 }
840 } catch (const std::exception& failure) {
841 std::string message = failure.what();
842 while (attempted > 0) {
843 auto& entry = providers[--attempted];
844 try {
845 auto rollback = entry.provider->restore(entry.before);
846 if (!rollback.ok())
847 message += "; rollback failed for " + std::string(entry.provider->stateKind()) + ": " +
848 rollback.diagnostics().front().message();
849 } catch (const std::exception& rollback) {
850 message +=
851 "; rollback failed for " + std::string(entry.provider->stateKind()) + ": " + rollback.what();
852 }
853 }
854 if (error) *error = message;
855 return false;
856 }
857 sq_pushroottable(vm);
858 const SQInteger root = sq_gettop(vm);
859 sq_pushnull(vm);
860 while (SQ_SUCCEEDED(sq_next(vm, staged))) {
861 // Raw writes cannot invoke script metamethods during commit.
862 sq_rawset(vm, root);
863 }
864 return true;
865 } catch (const std::exception& e) {
866 if (error) *error = e.what();
867 return false;
868 }
869}
870
871bool Snapshot::restore(HSQUIRRELVM vm, const std::string& json, std::string* error) const {
872 try {
873 Poco::JSON::Parser parser;
874 Poco::Dynamic::Var result = parser.parse(json);
875 return restoreState(vm, varToState(result), error);
876 } catch (const Poco::Exception& e) {
877 if (error) *error = e.displayText();
878 return false;
879 } catch (const std::exception& e) {
880 if (error) *error = e.what();
881 return false;
882 }
883}
884
885bool Snapshot::saveFile(HSQUIRRELVM vm, const std::string& path, std::string* error) const {
886 const std::string json = capture(vm, error);
887 if (json.empty()) return false;
888 std::ofstream ofs(path, std::ios::binary);
889 if (!ofs) {
890 if (error) *error = "cannot write " + path;
891 return false;
892 }
893 ofs << json;
894 return static_cast<bool>(ofs);
895}
896
897bool Snapshot::loadFile(HSQUIRRELVM vm, const std::string& path, std::string* error) const {
898 std::ifstream ifs(path, std::ios::binary);
899 if (!ifs) {
900 if (error) *error = "cannot read " + path;
901 return false;
902 }
903 std::ostringstream oss;
904 oss << ifs.rdbuf();
905 return restore(vm, oss.str(), error);
906}
907
908} // namespace eve::dev
int root
Definition AnimSmr.cpp:119
const std::string & s
struct SQVM * HSQUIRRELVM
glm::vec4 p[6]
std::string nodeId
HSQUIRRELVM vm
Definition ECS.cpp:38
std::vector< Value > defaults
Definition ECS.cpp:49
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::string message
double r
float v
std::string imported
std::string id
Poco::JSON::Object::Ptr result
MeleePoint3 a
Definition MeleeHit.cpp:40
std::string error
Definition Package.cpp:174
std::map< std::string, std::vector< std::string > > graph
Definition Package.cpp:173
int idx
std::string path
Definition PlayHost.cpp:111
PrimitiveHandle handle
const eve::script::BindingContractRegistry & registry
Object::Ptr value
float t
std::unordered_map< std::uint32_t, std::uint32_t > remap
const RoadNode * node
bool found
ScriptStructure out
std::map< size_t, size_t > pairs
std::string string
int count
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
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.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
JSON-compatible state value tree used by state hot reload.
Definition StateValue.h:30
static StateValue object()
Empty object.
Definition StateValue.h:50
static StateValue boolean(bool v)
Boolean value.
static StateValue array()
Empty array.
Definition StateValue.h:48
static StateValue integer(int64_t v)
Integer value.
size_t arraySize() const
Element count; only valid on arrays.
Definition StateValue.h:75
bool isObject() const
Definition StateValue.h:60
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.
Definition StateValue.h:38
StateValue & at(size_t index)
Indexed element (bounds-checked); only valid on arrays.
Definition StateValue.h:77
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.
Definition Value.h:31
static Value null()
Compatibility factory for a null value.
Definition Value.h:113
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.
Definition Snapshot.cpp:561
bool restore(HSQUIRRELVM vm, const std::string &json, std::string *error=nullptr) const
Definition Snapshot.cpp:871
bool restoreState(HSQUIRRELVM vm, const StateValue &state, std::string *error=nullptr) const
Restore a captured state; v1-shaped values restore roots only.
Definition Snapshot.cpp:769
void unmarkTransientRoot(const std::string &name)
Remove an explicit transient-root declaration.
Definition Snapshot.cpp:497
Result< StateValue > mergeDefaultsState(const StateValue &captured, const StateValue &defaults) const
Merge v3 script defaults while retaining captured values and identities.
Definition Snapshot.cpp:676
std::string capture(HSQUIRRELVM vm, std::string *error=nullptr) const
Capture marked roots, or heuristic roots when none marked.
Definition Snapshot.cpp:659
bool loadFile(HSQUIRRELVM vm, const std::string &path, std::string *error=nullptr) const
Definition Snapshot.cpp:897
std::vector< std::string > roots() const
Return the explicit persistent roots.
Definition Snapshot.cpp:506
std::vector< std::string > transientRoots() const
Return the explicit transient roots.
Definition Snapshot.cpp:508
void setRootPolicies(std::vector< std::string > persistent, std::vector< std::string > transient)
Atomically replace explicit persistent/transient root policy.
Definition Snapshot.cpp:510
static bool isEngineBinding(const std::string &name)
Built-in names never auto-captured (modules / boot bindings).
Definition Snapshot.cpp:473
void markTransientRoot(std::string name)
Mark a root for reconstruction from new script definitions.
Definition Snapshot.cpp:488
void markRoot(std::string name)
Mark a root as persistent, replacing a transient declaration.
Definition Snapshot.cpp:475
bool saveFile(HSQUIRRELVM vm, const std::string &path, std::string *error=nullptr) const
Definition Snapshot.cpp:885
static Snapshot & instance()
Definition Snapshot.cpp:468
void unmarkRoot(const std::string &name)
Remove an explicit persistent-root declaration.
Definition Snapshot.cpp:484
void clearRoots()
Clear every explicit persistent and transient declaration.
Definition Snapshot.cpp:501
StateValue objects
Definition Snapshot.cpp:110
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
SQInteger top
Definition Snapshot.cpp:115
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.