载入中...
搜索中...
未找到
StatePatch.cpp
浏览该文件的文档.
47 std::invoke(std::forward<Release>(release), ref).ignore("rollback failed owned state-patch allocation");
51 auto result = eve::script::projectStatusResult(vm, eve::Status::success(eve::StatusCode::Applied));
98 auto parsed = eve::json::scanUnsignedInteger(value.asString(), eve::json::UnsignedIntegerSyntax::LegacyStoull);
134bool PatchBatch::set(const std::string& subject, const std::string& key, const std::string& jsonValue) {
141bool PatchBatch::setExpected(const std::string& subject, const std::string& key, const std::string& jsonValue,
160bool PatchBatch::removeExpected(const std::string& subject, const std::string& key, const std::string& expectedJson) {
176eve::Result<PatchBatchHandleRef> Store::newBatch() { return batches_.emplace(std::make_unique<PatchBatch>()); }
182eve::Result<void> Store::releaseBatch(PatchBatchHandleRef reference) { return batches_.erase(reference); }
210 "statepatch[" + std::to_string(error.operationIndex) + "]", std::move(details), "statepatch.commit"));
224 eve::DiagnosticCode::InvalidArgument, "patch batch must not be null", "batch", {}, "statepatch.commit"));
232 batch->result_.errors.push_back({static_cast<int>(i), operation.subject, operation.key, code, message});
237 if (!batch->result_.errors.empty() && batch->result_.errors.back().operationIndex == static_cast<int>(i))
275 oldSubject == values_.end() ? std::map<std::string, Value>::const_iterator{} : oldSubject->second.find(key);
277 newSubject == staged.end() ? std::map<std::string, Value>::const_iterator{} : newSubject->second.find(key);
281 changes.push_back({subject, key, had ? oldValue->second.json : "", has ? newValue->second.json : "", !has});
286 batch->result_.errors.push_back({-1, {}, {}, "revision_exhausted", "revision or event sequence exhausted"});
293 events_.push_back({nextSequence_++, revision_, change.subject, change.key, change.oldJson, change.newJson,
301 PatchCommitInfo info{batch->result_.changedCount, batch->result_.revisionBefore, batch->result_.revisionAfter};
303 info, eve::Status::success(info.changedCount == 0 ? eve::StatusCode::NoOp : eve::StatusCode::Applied));
401 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, parseError.empty() ? "invalid state patch snapshot" : parseError,
405 if (!root.isObject()) return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "snapshot root must be an object",
410 if (root.getInt("version") != 1) return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "unsupported state patch snapshot version",
413 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "snapshot revision must be a decimal string",
416 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "snapshot nextSequence must be a non-zero decimal string",
422 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "values and dirty must be arrays",
431 !parseU64(item.get("revision"), valueRevision) || valueRevision > restoredRevision || !item.get("value")) {
432 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "invalid value at index " + std::to_string(i),
438 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "duplicate subject and key",
447 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "invalid dirty key at index " + std::to_string(i),
463eve::Result<eve::SnapshotEnvelope> Store::snapshot(const eve::SnapshotHashProvider& hashProvider) const {
466 return eve::makeSnapshotEnvelope("statepatch.store", statePatchSchema(), eve::SchemaVersion(1), instanceId_,
481 auto metadata = eve::validateSnapshotPayloadMetadata(candidateEnvelope.payload, candidateEnvelope.revision,
492 eve::DiagnosticCode::Conflict, "state patch payload revision disagrees with snapshot envelope"));
499eve::Result<std::string> Store::snapshotEnvelopeJson(const eve::SnapshotHashProvider& hashProvider) const {
506eve::Result<void> Store::restoreSnapshotJson(std::string_view json, const eve::SnapshotHashProvider& hashProvider) {
536 if (snapshotJson() != other.snapshotJson() || events_.size() != other.events_.size()) return false;
540 if (left.sequence != right.sequence || left.revision != right.revision || left.subject != right.subject ||
548bool StoreTransactionParticipant::contextMatches(const transaction::TransactionContext& context) const noexcept {
549 return context.transactionId() == transactionId_ && context.correlationId() == correlationId_ &&
553eve::Result<void> StoreTransactionParticipant::lifecycleFailure(std::string_view operation) const {
560eve::Result<void> StoreTransactionParticipant::contextFailure(const transaction::TransactionContext& context) const {
563 eve::DiagnosticCode::Conflict, "transaction context changed between participant lifecycle calls",
567eve::Result<void> StoreTransactionParticipant::prepare(const transaction::TransactionContext& context) {
596eve::Result<void> StoreTransactionParticipant::commit(const transaction::TransactionContext& context) {
608eve::Result<void> StoreTransactionParticipant::rollback(const transaction::TransactionContext& context) {
618eve::Result<void> StoreTransactionParticipant::compensate(const transaction::TransactionContext& context) {
623 eve::DiagnosticCode::Conflict, "state patch store changed before compensation", "statepatch.store"));
631StatePatch::~StatePatch() {
636 eve::cap::removeListener<eve::IStateMutation>(static_cast<eve::IStateMutation*>(adapter.get()));
652 eve::cap::removeListener<eve::IStateQuery>(static_cast<eve::IStateQuery*>(found->second.get()));
653 eve::cap::removeListener<eve::IStateMutation>(static_cast<eve::IStateMutation*>(found->second.get()));
667eve::script::Borrowed<PatchBatch> StatePatch::resolveBatch(StateBatchHandleRef reference) noexcept {
684 eve::DiagnosticCode::StaleHandle, "owning StatePatch store is stale", "store", {}, "statepatch.squirrel"));
723 auto error = table.addClass<PatchError>("PatchError", std::function<PatchError*()>([] { return nullptr; }), false);
731 table.addClass<PatchResult>("PatchResult", std::function<PatchResult*()>([] { return nullptr; }), false);
734 result.addFunc("getRevisionBefore", [](PatchResult* r) { return r ? static_cast<int64_t>(r->revisionBefore) : 0; });
735 result.addFunc("getRevisionAfter", [](PatchResult* r) { return r ? static_cast<int64_t>(r->revisionAfter) : 0; });
736 result.addFunc("errorCount", [](PatchResult* r) { return r ? static_cast<int>(r->errors.size()) : 0; });
738 return r && index >= 0 && static_cast<size_t>(index) < r->errors.size() ? &r->errors[static_cast<size_t>(index)]
743 table.addClass<ChangeEvent>("StateChangeEvent", std::function<ChangeEvent*()>([] { return nullptr; }), false);
744 event.addFunc("getSequence", [](ChangeEvent* e) { return e ? static_cast<int64_t>(e->sequence) : 0; });
745 event.addFunc("getRevision", [](ChangeEvent* e) { return e ? static_cast<int64_t>(e->revision) : 0; });
752 auto batch = table.addClass<PatchBatch>("PatchBatch", std::function<PatchBatch*()>([] { return nullptr; }), false);
760 [](PatchBatch* b) -> PatchResult* { return b ? const_cast<PatchResult*>(&b->result()) : nullptr; });
781 ownedBatch.addFunc("set", [vm](ScriptStateBatch* value, const std::string& subject, const std::string& key,
783 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
788 eve::DiagnosticCode::StaleHandle, std::string("owned state-patch ") + "batch" + " handle is stale",
791 return eve::script::projectResult(vm, eve::Result<bool>::success(view->set(subject, key, jsonValue)),
794 ownedBatch.addFunc("remove", [vm](ScriptStateBatch* value, const std::string& subject, const std::string& key) {
795 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
800 eve::DiagnosticCode::StaleHandle, std::string("owned state-patch ") + "batch" + " handle is stale",
806 ownedBatch.addFunc("setExpected", [vm](ScriptStateBatch* value, const std::string& subject, const std::string& key,
808 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
813 eve::DiagnosticCode::StaleHandle, std::string("owned state-patch ") + "batch" + " handle is stale",
822 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
827 eve::DiagnosticCode::StaleHandle, std::string("owned state-patch ") + "batch" + " handle is stale",
835 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
839 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
843 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
847 auto store = table.addClass<Store>("StateStore", std::function<Store*()>([] { return nullptr; }), false);
855 return eve::Value(eve::Value::Object{{"changedCount", eve::Value(static_cast<std::int64_t>(info.changedCount))},
861 return eve::Value(eve::Value::Object{{"changedCount", eve::Value(static_cast<std::int64_t>(info.changedCount))},
868 store.addFunc("valueRevision", [](Store* s, const std::string& subject, const std::string& key) {
871 store.addFunc("revision", [](Store* s) { return s ? static_cast<int64_t>(s->revision()) : 0; });
915 return eve::Value(eve::Value::Object{{"changedCount", eve::Value(static_cast<std::int64_t>(info.changedCount))},
939 ownedStore.addFunc("has", [](ScriptStateStore* value, const std::string& subject, const std::string& key) {
943 ownedStore.addFunc("get", [](ScriptStateStore* value, const std::string& subject, const std::string& key) {
The single Squirrel projection for common Result, Status and Value.
Consumer-owned query and mutation contracts for authoritative world state.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Definition Diagnostic.cpp:21
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Result< void > add(LogicalId schema, SchemaVersion from, SchemaVersion to, Migration migration)
Register one schema-local migration edge.
Definition Snapshot.cpp:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Non-owning observation of a registry-owned object.
Definition RuntimeBorrow.h:27
All-or-nothing mutation boundary owned by the consumer.
Definition StateAccess.h:107
Read-only world-state boundary owned by consumers such as Dialogue.
Definition StateAccess.h:79
Ordered collection of set and remove operations committed atomically.
Definition StatePatch.h:107
bool setExpected(const std::string &subject, const std::string &key, const std::string &jsonValue, const std::string &expectedJson)
Appends a set operation guarded by an expected current JSON value.
Definition StatePatch.cpp:141
bool set(const std::string &subject, const std::string &key, const std::string &jsonValue)
Appends an unconditional set operation.
Definition StatePatch.cpp:134
bool remove(const std::string &subject, const std::string &key)
Appends an unconditional remove operation.
Definition StatePatch.cpp:155
const PatchResult & result() const
Returns the result of the most recent commit attempt.
Definition StatePatch.cpp:174
bool removeExpected(const std::string &subject, const std::string &key, const std::string &expectedJson)
Appends a remove operation guarded by an expected current JSON value.
Definition StatePatch.cpp:160
Script module factory for generic state patch stores.
Definition StatePatch.h:301
static eve::Result< void > releaseBatch(StateBatchHandleRef reference)
Releases a store-qualified patch batch.
Definition StatePatch.cpp:675
static eve::script::Borrowed< PatchBatch > resolveBatch(StateBatchHandleRef reference) noexcept
Resolves a store-qualified batch as a non-owning observation.
Definition StatePatch.cpp:667
static bool isBatchStale(StateBatchHandleRef reference) noexcept
Reports whether a store-qualified batch reference is stale.
Definition StatePatch.cpp:688
static eve::Result< void > release(StateStoreHandleRef reference)
Releases a module-owned state store.
Definition StatePatch.cpp:702
Deterministic subject-and-key JSON value store with atomic patching.
Definition StatePatch.h:140
bool has(const std::string &subject, const std::string &key) const
Returns whether a subject and key currently exist.
Definition StatePatch.cpp:306
eve::Result< void > releaseBatch(PatchBatchHandleRef reference)
Releases a store-owned patch batch.
Definition StatePatch.cpp:182
eve::Result< PatchCommitInfo > commit(PatchBatch *batch)
Validates and atomically commits a batch.
Definition StatePatch.cpp:221
eve::Result< void > restoreJson(const std::string &json)
Transactionally restores a snapshot produced by snapshotJson().
Definition StatePatch.cpp:397
eve::script::Borrowed< PatchBatch > resolveBatch(PatchBatchHandleRef reference) noexcept
Resolves a live batch as a non-owning observation.
Definition StatePatch.cpp:178
Store(eve::PersistentId instanceId={})
Creates an empty store with an optional persistent identity.
Definition StatePatch.cpp:132
bool isBatchStale(PatchBatchHandleRef reference) const noexcept
Reports whether a batch reference is stale for this Store.
Definition StatePatch.cpp:184
eve::Result< PatchBatchHandleRef > newBatch()
Allocates a store-owned empty patch batch and returns its handle.
Definition StatePatch.cpp:176
Immutable context shared by every participant of one transaction.
Definition Transaction.h:31
void keys(const Value &value, std::initializer_list< const char * > names)
Definition OceanCodecInternal.h:8
std::string quoteString(std::string_view value, StringEscapeStyle style)
Encode an owning JSON string using the canonical serializer's escaping implementation.
Definition Json.cpp:576
Result< UnsignedIntegerScan > scanUnsignedInteger(std::string_view text, UnsignedIntegerSyntax syntax)
Scan an unsigned integer prefix without mutating caller state.
Definition Json.cpp:583
ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result< Ref > &&reference, Release &&release)
Definition ProcgenScriptSupport.h:200
@ Borrowed
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
Definition SquirrelBinding.cpp:524
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Definition SquirrelBinding.cpp:540
Definition StateAccessAdapter.cpp:14
eve::script::RuntimeHandleRef< StateStoreHandleTag > StateStoreHandleRef
Generation- and module-epoch-qualified state store reference.
Definition StatePatch.h:28
std::vector< DiagnosticDetail > DiagnosticDetails
Owning collection of diagnostic details with stable insertion order.
Definition Diagnostic.h:88
@ InvalidArgument
@ PreconditionViolation
@ Failed
@ ParseError
@ StaleHandle
@ Conflict
Result< void > validateSnapshotPayloadMetadata(const Value &payload, Revision revision, SimulationTick tick)
Validate optional payload copies of envelope revision and tick.
Definition Snapshot.cpp:80
@ Pending
@ NoOp
@ Applied
@ Rejected
@ Failed
@ Conflict
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
Result< std::string > serializeSnapshotEnvelope(const SnapshotEnvelope &snapshot)
Serialize an envelope as deterministic compact JSON.
Definition Snapshot.cpp:184
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
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
Definition Container.h:602
StatePatch implementation of the common world-state contracts.
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
Immutable description of one committed value change.
Definition StatePatch.h:96
One validation error produced while applying a patch batch.
Definition StatePatch.h:57
Compatibility summary of the most recent batch commit attempt. @compatibility Prefer Store::commit → ...
Definition StatePatch.h:87
A patch batch reference qualified by both its owning Store and batch slot.
Definition StatePatch.h:41