载入中...
搜索中...
未找到
GameSaveSession.cpp
浏览该文件的文档.
2
3#include <utility>
4#include <vector>
5
6namespace eve {
7namespace {
8
9LogicalId gameSaveSchema() {
10 const auto schema = LogicalId::parse("game:save-session");
11 return schema ? *schema : LogicalId{};
12}
13
14} // namespace
15
16GameSaveSession::GameSaveSession(std::string contentVersion) : contentVersion_(std::move(contentVersion)) {}
17
19 const std::string key(participant.saveKey());
20 if (key.empty())
22 Diagnostic::error(DiagnosticCode::InvalidArgument, "game-save participant key is empty", "saveKey"));
23 if (!participants_.emplace(key, &participant).second)
25 Diagnostic::error(DiagnosticCode::Conflict, "duplicate game-save participant", key));
26 return Result<void>::success();
27}
28
30 std::function<Result<Value>(const Value&)> migrate) {
31 if (fromVersion.empty() || fromVersion == contentVersion_ || !migrate)
33 Diagnostic::error(DiagnosticCode::InvalidArgument, "invalid game-save content migration", "fromVersion"));
34 if (!migrations_.emplace(std::move(fromVersion), std::move(migrate)).second)
36 Diagnostic::error(DiagnosticCode::Conflict, "duplicate game-save content migration", "fromVersion"));
37 return Result<void>::success();
38}
39
41 if (contentVersion_.empty() || participants_.empty())
43 "game save requires content version and participants"));
44 Value::Object states;
45 for (const auto& [key, participant] : participants_) {
46 auto state = participant->capture();
47 if (!state.ok()) return Result<std::string>::failure(state.status());
48 states.emplace(key, std::move(state).takeValue());
49 }
50 Value::Object payload{{"contentVersion", Value(contentVersion_)}, {"participants", Value(std::move(states))}};
51 auto envelope = makeSnapshotEnvelope("game.save-session", gameSaveSchema(), SchemaVersion(1), PersistentId::nil(),
52 Revision(0), SimulationTick(0), Value(std::move(payload)), hashProvider);
53 if (!envelope.ok()) return Result<std::string>::failure(envelope.status());
54 return serializeSnapshotEnvelope(envelope.value());
55}
56
57Result<void> GameSaveSession::restoreJson(std::string_view json, const SnapshotHashProvider& hashProvider) {
58 if (contentVersion_.empty() || participants_.empty())
60 "game save requires content version and participants"));
61 auto decoded = parseSnapshotEnvelope(json, hashProvider);
62 if (!decoded.ok()) return Result<void>::failure(decoded.status());
63 const auto& envelope = decoded.value();
64 if (envelope.type != "game.save-session" || envelope.schema != gameSaveSchema())
66 Diagnostic::error(DiagnosticCode::InvalidArgument, "snapshot is not a game save", "schema"));
67 if (envelope.schemaVersion != SchemaVersion(1))
69 Diagnostic::error(DiagnosticCode::UnknownVersion, "unknown game-save schema version", "schemaVersion"));
70 const auto* payload = envelope.payload.getIf<Value::Object>();
71 if (!payload || payload->size() != 2)
73 Diagnostic::error(DiagnosticCode::ParseError, "game-save payload requires exactly two fields", "payload"));
74 const Value* savedVersion = envelope.payload.find("contentVersion");
75 const Value* savedStates = envelope.payload.find("participants");
76 if (!savedVersion || !savedVersion->isString() || !savedStates || !savedStates->isObject())
78 Diagnostic::error(DiagnosticCode::ParseError, "invalid game-save payload", "payload"));
79 Value migratedStates;
80 if (savedVersion->asString() != contentVersion_) {
81 const auto migration = migrations_.find(savedVersion->asString());
82 if (migration == migrations_.end())
84 "game-save content version has no migration route",
85 "payload.contentVersion"));
86 auto migrated = migration->second(*savedStates);
87 if (!migrated.ok()) return Result<void>::failure(migrated.status());
88 migratedStates = std::move(migrated).takeValue();
89 savedStates = &migratedStates;
90 }
91 const auto* states = savedStates->getIf<Value::Object>();
92 if (!states || states->size() != participants_.size())
94 "game-save participant set differs from the current game",
95 "payload.participants"));
96 std::vector<std::unique_ptr<IPreparedGameRestore>> prepared;
97 prepared.reserve(participants_.size());
98 for (const auto& [key, participant] : participants_) {
99 const auto state = states->find(key);
100 if (state == states->end())
102 Diagnostic::error(DiagnosticCode::Unsupported, "game-save participant is absent", key));
103 auto candidate = participant->prepare(state->second);
104 if (!candidate.ok()) return Result<void>::failure(candidate.status());
105 if (!candidate.value())
107 "game-save participant returned no prepared state", key));
108 prepared.push_back(std::move(candidate).takeValue());
109 }
110 for (auto& candidate : prepared) candidate->commit();
112}
113
114} // namespace eve
Value::Object payload
SQObjectPtr key
Definition ECS.cpp:155
Single-transaction composition of domain save participants.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Result< void > addContentMigration(std::string fromVersion, std::function< Result< Value >(const Value &)> migrate)
Register a direct old-to-current content migration before loading.
Result< void > add(IGameSaveParticipant &participant)
Borrow one domain participant for this session's lifetime.
GameSaveSession(std::string contentVersion)
Configure the exact current content contract; empty identifiers are rejected by operations.
Result< std::string > snapshotJson(const SnapshotHashProvider &hashProvider) const
Capture and integrity-seal every participant in deterministic key order.
Result< void > restoreJson(std::string_view json, const SnapshotHashProvider &hashProvider)
Verify, migrate and prepare all participants before any publication.
One authoritative domain participating in a game save. @lifetime The participant and its live domain ...
virtual std::string_view saveKey() const noexcept=0
Stable unique participant key within the game-save schema.
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
const std::string & asString() const
Return the string payload; the caller must have checked the kind.
Definition Value.cpp:207
std::map< std::string, Value > Object
Definition Value.h:34
bool isString() const noexcept
Return true when this value is a string.
Definition Value.h:106
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
bool isObject() const noexcept
Return true when this value is an object.
Definition Value.h:110
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
static constexpr Id128 nil() noexcept
Returns the all-zero nil value.
Definition Identity.h:141
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
Result< SnapshotEnvelope > parseSnapshotEnvelope(std::string_view json, const SnapshotHashProvider &hashProvider)
Parse and verify an envelope from canonical or compatible JSON text.
Definition Snapshot.cpp:190
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
Result< std::string > serializeSnapshotEnvelope(const SnapshotEnvelope &snapshot)
Serialize an envelope as deterministic compact JSON.
Definition Snapshot.cpp:184
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
Result< SnapshotEnvelope > makeSnapshotEnvelope(std::string type, LogicalId schema, SchemaVersion schemaVersion, PersistentId instanceId, Revision revision, SimulationTick tick, Value payload, const SnapshotHashProvider &hashProvider)
Construct and seal a snapshot envelope.
Definition Snapshot.cpp:103
detail::StrongUint64< detail::RevisionTag > Revision
Monotonic content/state revision used for optimistic-concurrency checks.
Definition Revision.h:13
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36