载入中...
搜索中...
未找到
StateAccessAdapter.cpp
浏览该文件的文档.
2#include "common/ValueRead.h"
3
5
6#include <array>
7#include <cmath>
8#include <limits>
9#include <map>
10#include <optional>
11#include <string>
12#include <utility>
13
14namespace eve::statepatch {
15namespace {
16
17eve::Result<eve::MutationReceipt> failure(eve::DiagnosticCode code, std::string message, std::string path = {}) {
19 eve::Diagnostic::error(code, std::move(message), std::move(path)));
20}
21
22eve::Result<eve::Value> readJsonValue(const Store& store, std::string_view subject, std::string_view key) {
23 if (!store.has(std::string(subject), std::string(key)))
25 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "state value is absent", "state"));
26 auto parsed = eve::Value::fromJson(store.get(std::string(subject), std::string(key)));
27 if (!parsed) return eve::Result<eve::Value>::failure(parsed.status());
28 return parsed;
29}
30
31bool numeric(const eve::Value& value, double& output) {
33 if (!parsed) return false;
34 output = parsed.value();
35 return std::isfinite(output);
36}
37
38std::string tagKey(std::string_view tag) { return "tag." + std::string(tag); }
39
40} // namespace
41
42std::optional<eve::Value> StatePatchStateAdapter::value(std::string_view subject, std::string_view key) const {
43 auto result = readJsonValue(store_, subject, key);
44 if (!result) return std::nullopt;
45 return std::move(result).takeValue();
46}
47
48std::optional<bool> StatePatchStateAdapter::hasTag(std::string_view subject, std::string_view tag) const {
49 if (subject.empty() || tag.empty()) return std::nullopt;
50 const std::string key = tagKey(tag);
51 if (!store_.has(std::string(subject), key)) return false;
52 auto value = readJsonValue(store_, subject, key);
53 if (!value) return std::nullopt;
54 const eve::Value& parsed = value.value();
55 if (!parsed.isBool()) return std::nullopt;
56 return parsed.asBool();
57}
58
59std::optional<eve::Value> StatePatchStateAdapter::state(std::string_view subject, std::string_view key) const {
60 return value(subject, key);
61}
62
63eve::Result<eve::MutationReceipt> StatePatchStateAdapter::apply(std::span<const eve::StateMutation> mutations,
65 if (context.transactionId.empty())
66 return failure(eve::DiagnosticCode::InvalidArgument, "persistent dialogue mutations require a transaction id",
67 "transactionId");
68
69 using Key = std::pair<std::string, std::string>;
70 std::map<Key, std::optional<eve::Value>> pending;
71 auto batchReference = store_.newBatch();
72 if (!batchReference) return eve::Result<eve::MutationReceipt>::failure(batchReference.status());
73 const PatchBatchHandleRef batchHandle = std::move(batchReference).takeValue();
74 auto batch = store_.resolveBatch(batchHandle);
75 if (!batch.isBound())
76 return failure(eve::DiagnosticCode::StaleHandle, "StatePatch patch batch became stale during allocation",
77 "batch");
78 struct BatchLease {
79 Store& store;
81 ~BatchLease() { store.releaseBatch(handle).ignore("release StatePatch adapter batch"); }
82 } batchLease{store_, batchHandle};
83
84 for (std::size_t index = 0; index < mutations.size(); ++index) {
85 const auto& mutation = mutations[index];
86 const std::string path = "mutations[" + std::to_string(index) + "]";
87 if (!mutation.persistent)
88 return failure(eve::DiagnosticCode::Unsupported, "StatePatch adapter accepts persistent mutations only",
89 path);
90 if (mutation.subject.empty() || mutation.key.empty())
91 return failure(eve::DiagnosticCode::InvalidArgument, "persistent mutation requires subject and key", path);
92
93 const std::string sourceKey = mutation.key;
94 const std::string key =
95 mutation.kind == eve::MutationKind::AddTag || mutation.kind == eve::MutationKind::RemoveTag
96 ? tagKey(sourceKey)
97 : sourceKey;
98 const Key pendingKey{mutation.subject, key};
99 auto current = [&]() -> std::optional<eve::Value> {
100 const auto found = pending.find(pendingKey);
101 if (found != pending.end()) return found->second;
102 if (!store_.has(mutation.subject, key)) return std::nullopt;
103 auto existing = readJsonValue(store_, mutation.subject, key);
104 if (!existing) return std::nullopt;
105 return std::move(existing).takeValue();
106 };
107
108 bool appended = false;
109 switch (mutation.kind) {
110 case eve::MutationKind::Set: {
111 auto json = mutation.value.toJson();
112 if (!json)
113 return failure(json.error() ? json.error()->code() : eve::DiagnosticCode::SerializationError,
114 json.error() ? json.error()->message() : "state value cannot be serialized",
115 path + ".value");
116 appended = batch->set(mutation.subject, key, json.value());
117 if (appended) pending[pendingKey] = mutation.value;
118 break;
119 }
120 case eve::MutationKind::Remove:
121 appended = batch->remove(mutation.subject, key);
122 if (appended) pending[pendingKey] = std::nullopt;
123 break;
124 case eve::MutationKind::AddTag:
125 appended = batch->set(mutation.subject, key, "true");
126 if (appended) pending[pendingKey] = eve::Value(true);
127 break;
128 case eve::MutationKind::RemoveTag:
129 appended = batch->remove(mutation.subject, key);
130 if (appended) pending[pendingKey] = std::nullopt;
131 break;
132 case eve::MutationKind::AddNumber: {
133 double delta = 0.0;
134 if (!numeric(mutation.value, delta))
135 return failure(eve::DiagnosticCode::InvalidArgument, "AddNumber requires a finite numeric value",
136 path + ".value");
137 const auto existing = current();
138 double base = 0.0;
139 if (existing && !numeric(*existing, base))
141 "AddNumber cannot add to a non-numeric state value", path);
142 const double total = base + delta;
143 if (!std::isfinite(total))
144 return failure(eve::DiagnosticCode::InvalidArgument, "AddNumber result must be finite", path);
145 const eve::Value result(total);
146 auto json = result.toJson();
147 if (!json)
148 return failure(eve::DiagnosticCode::SerializationError, "AddNumber result cannot be serialized",
149 path);
150 appended = batch->set(mutation.subject, key, json.value());
151 if (appended) pending[pendingKey] = result;
152 break;
153 }
154 }
155 if (!appended) return failure(eve::DiagnosticCode::Failed, "StatePatch rejected a mutation", path);
156 }
157
158 eve::transaction::TransactionContext transaction(context.transactionId, context.correlationId, context.causationId);
159 StoreTransactionParticipant participant(store_, *batch);
160 std::array<eve::transaction::ITransactionParticipant*, 1> participants{&participant};
162 auto committed = coordinator.execute(transaction, participants);
164
165 const PatchResult& summary = batch->result();
167 eve::MutationReceipt{context.transactionId, static_cast<std::size_t>(summary.changedCount)},
169}
170
171} // namespace eve::statepatch
int subject
Definition AnimSmr.cpp:163
std::string output
std::vector< QuestEvent > pending
bool committed
SQObjectPtr key
Definition ECS.cpp:155
std::string message
DiagnosticCode code
Poco::JSON::Object::Ptr result
const std::string * tag
std::string path
Definition PlayHost.cpp:111
PrimitiveHandle handle
Object::Ptr value
bool found
double current
uint32_t index
const VegetationPresetContext & context
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
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
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
bool asBool() const
Return the boolean payload; the caller must have checked the kind.
Definition Value.cpp:201
bool isBool() const noexcept
Return true when this value is a boolean.
Definition Value.h:100
std::optional< eve::Value > state(std::string_view subject, std::string_view key) const override
Query a persistent/world state value.
std::optional< eve::Value > value(std::string_view subject, std::string_view key) const override
Query a generic world value.
std::optional< bool > hasTag(std::string_view subject, std::string_view tag) const override
Query exact tag membership.
eve::Result< eve::MutationReceipt > apply(std::span< const eve::StateMutation > mutations, const eve::MutationContext &context) override
Apply a complete mutation set atomically.
Transaction participant that atomically applies one StatePatch batch.
Definition StatePatch.h:259
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.
std::string get(const std::string &subject, const std::string &key) const
Returns canonical JSON for a value, or an empty string when absent.
eve::Result< void > releaseBatch(PatchBatchHandleRef reference)
Releases a store-owned patch batch.
eve::script::Borrowed< PatchBatch > resolveBatch(PatchBatchHandleRef reference) noexcept
Resolves a live batch as a non-owning observation.
eve::Result< PatchBatchHandleRef > newBatch()
Allocates a store-owned empty patch batch and returns its handle.
Coordinates participant lifecycles with deterministic ordering.
Result< TransactionReceipt > execute(const TransactionContext &context, std::span< ITransactionParticipant * > participants) const
Execute borrowed participants with rollback and compensation.
Immutable context shared by every participant of one transaction.
Definition Transaction.h:31
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Result< double > readNumericDoubleValue(const Value &value)
Read an Int64 or Double as a double without imposing a finite-value policy.
Definition Value.cpp:74
StatePatch implementation of the common world-state contracts.
Correlation metadata shared by a mutation transaction.
Definition StateAccess.h:57
Observable result of an all-or-nothing mutation request.
Definition StateAccess.h:64
Compatibility summary of the most recent batch commit attempt. @compatibility Prefer Store::commit → ...
Definition StatePatch.h:87