载入中...
搜索中...
未找到
StateAccessScriptSeam.cpp
浏览该文件的文档.
2
3#include "common/Capability.h"
4#include "common/CrashLog.h"
7#include "common/Value.h"
8
9#include <algorithm>
10#include <array>
11#include <cstdint>
12#include <memory>
13#include <span>
14#include <string>
15#include <string_view>
16#include <utility>
17#include <vector>
18
19namespace eve::dialogue {
20namespace {
21
23template <class T>
24struct NameEntry {
26 std::string_view name;
27};
28
29constexpr std::array<NameEntry<eve::MutationKind>, 5> kMutationKinds = {{
30 {eve::MutationKind::Set, "set"},
31 {eve::MutationKind::Remove, "remove"},
32 {eve::MutationKind::AddTag, "addTag"},
33 {eve::MutationKind::RemoveTag, "removeTag"},
34 {eve::MutationKind::AddNumber, "addNumber"},
35}};
36static_assert(kMutationKinds.size() == 5, "变更种类表与枚举不同步(加枚举值要同时改表)");
37
38std::string_view mutationKindName(eve::MutationKind kind) noexcept {
39 for (const NameEntry<eve::MutationKind>& entry : kMutationKinds) {
40 if (entry.value == kind) return entry.name;
41 }
42 return {};
43}
44
45std::uint64_t& scriptStateQueryFailureCount() {
46 static std::uint64_t count = 0;
47 return count;
48}
49
50// ---------------------------------------------------------------------------
51// IStateQuery 的脚本适配器
52// ---------------------------------------------------------------------------
53
61class ScriptStateQuery final : public eve::IStateQuery {
62public:
63 explicit ScriptStateQuery(eve::ScriptProviderHandle handle) : handle_(std::move(handle)) {}
64
66 [[nodiscard]] const eve::ScriptProviderHandle& handle() const noexcept { return handle_; }
67
68 [[nodiscard]] std::optional<eve::Value> value(std::string_view subject, std::string_view key) const override {
69 return askValue("value", subject, key);
70 }
71 [[nodiscard]] std::optional<bool> hasTag(std::string_view subject, std::string_view tag) const override {
72 return askBool("hasTag", subject, tag);
73 }
74 [[nodiscard]] std::optional<eve::Value> attribute(std::string_view subject, std::string_view key) const override {
75 return askValue("attribute", subject, key);
76 }
77 [[nodiscard]] std::optional<eve::Value> resource(std::string_view subject, std::string_view key) const override {
78 return askValue("resource", subject, key);
79 }
80 [[nodiscard]] std::optional<eve::Value> state(std::string_view subject, std::string_view key) const override {
81 return askValue("state", subject, key);
82 }
83 [[nodiscard]] std::optional<bool> authority(std::string_view subject, std::string_view scope) const override {
84 return askBool("authority", subject, scope);
85 }
86
87private:
88 std::optional<eve::Value> askValue(const char* method, std::string_view subject, std::string_view key) const {
89 auto answer = ask(method, subject, key);
90 if (!answer.has_value() || answer->isNull()) return std::nullopt;
91 return answer;
92 }
93
94 std::optional<bool> askBool(const char* method, std::string_view subject, std::string_view key) const {
95 auto answer = ask(method, subject, key);
96 if (!answer.has_value() || answer->isNull()) return std::nullopt;
97 if (const auto* boolean = answer->getIf<bool>()) return *boolean;
98 reportFailure(std::string(method) + " must return a boolean (or null for 'not mine')");
99 return std::nullopt;
100 }
101
103 std::optional<eve::Value> ask(const char* method, std::string_view subject, std::string_view key) const {
104 const eve::ScriptArg args[] = {eve::ScriptArg::fromText(std::string(subject)),
105 eve::ScriptArg::fromText(std::string(key))};
106 auto answer = eve::ScriptProviderRegistry::instance().callValue(handle_, method, args);
107 if (answer.ok()) return std::move(answer).takeValue();
108 // 缺方法 = 这一类问题不归我(接口语义允许),不算失败。
109 if (answer.code() != eve::StatusCode::Unsupported)
110 reportFailure(std::string(method) + " failed: " + answer.status().describe());
111 return std::nullopt;
112 }
113
114 void reportFailure(std::string message) const {
115 ++scriptStateQueryFailureCount();
116 if (reportedGeneration_ == handle_.generation) return;
117 reportedGeneration_ = handle_.generation;
118 recordLogEvent("warn",
119 "script state query provider '" + handle_.name + "' declined a query: " + std::move(message));
120 }
121
124 mutable std::uint64_t reportedGeneration_ = 0;
125};
126
127// ---------------------------------------------------------------------------
128// IStateMutation 的脚本适配器
129// ---------------------------------------------------------------------------
130
132class ScriptStateMutation final : public eve::IStateMutation {
133public:
134 explicit ScriptStateMutation(eve::ScriptProviderHandle handle) : handle_(std::move(handle)) {}
135
137 [[nodiscard]] const eve::ScriptProviderHandle& handle() const noexcept { return handle_; }
138
139 [[nodiscard]] eve::Result<eve::MutationReceipt> apply(std::span<const eve::StateMutation> mutations,
140 const eve::MutationContext& context) override {
141 eve::Value::Array encoded;
142 encoded.reserve(mutations.size());
143 for (const eve::StateMutation& mutation : mutations) {
144 encoded.push_back(
145 eve::Value::object({{"subject", eve::Value::string(mutation.subject)},
146 {"key", eve::Value::string(mutation.key)},
147 {"kind", eve::Value::string(std::string(mutationKindName(mutation.kind)))},
148 {"persistent", eve::Value::boolean(mutation.persistent)},
149 {"value", mutation.value}}));
150 }
151 const eve::ScriptArg args[] = {
152 eve::ScriptArg::fromTable({{"transactionId", eve::Value::string(context.transactionId)},
153 {"correlationId", eve::Value::string(context.correlationId)},
154 {"causationId", eve::Value::string(context.causationId)},
155 {"mutations", eve::Value::array(std::move(encoded))}})};
156 auto answer = eve::ScriptProviderRegistry::instance().callValue(handle_, "applyStateMutations", args);
157 if (!answer.ok()) return eve::Result<eve::MutationReceipt>::failure(answer.status());
158
159 const auto* changed = answer.value().getIf<std::int64_t>();
160 if (changed == nullptr || *changed < 0)
163 "applyStateMutations must return the number of changed entries as a non-negative integer",
164 "applyStateMutations", {}, "dialogue.state-script"));
165 const std::size_t changedCount = static_cast<std::size_t>(*changed);
169 }
170
171private:
173};
174
175// ---------------------------------------------------------------------------
176// 归属
177// ---------------------------------------------------------------------------
178
180struct ScriptStateAccessProviders {
181 std::vector<std::unique_ptr<ScriptStateQuery>> liveQueries;
182 std::vector<std::unique_ptr<ScriptStateQuery>> retiredQueries;
183 std::vector<std::unique_ptr<ScriptStateMutation>> liveMutations;
184 std::vector<std::unique_ptr<ScriptStateMutation>> retiredMutations;
185};
186
187ScriptStateAccessProviders& scriptStateAccessProviders() {
188 static ScriptStateAccessProviders state;
189 return state;
190}
191
192} // namespace
193
194EVENGINE_API_ORCHESTRATION std::uint64_t scriptStateQueryFailures() { return scriptStateQueryFailureCount(); }
195
196EVENGINE_API_ORCHESTRATION void resetScriptStateQueryFailures() { scriptStateQueryFailureCount() = 0; }
197
199 ScriptStateAccessProviders& owned = scriptStateAccessProviders();
203 auto adapter = std::make_unique<ScriptStateQuery>(handle);
204 // listener 面:脚本 provider 补在原生 provider 后面(先问单实现、再按优先级问 listener),
205 // 谁也不顶掉谁。先注册再交所有权:能力表持有裸指针,`live` 是让它有效的唯一原因。
206 eve::cap::addListener<eve::IStateQuery>(adapter.get());
207 owned.liveQueries.push_back(std::move(adapter));
209 },
211 const auto match = std::find_if(
212 owned.liveQueries.begin(), owned.liveQueries.end(),
213 [&handle](const std::unique_ptr<ScriptStateQuery>& adapter) { return adapter->handle() == handle; });
214 if (match == owned.liveQueries.end()) {
215 // 幂等:后置条件是"这一代没有适配器",模块退出时可能已经撤过了。
217 }
218 eve::cap::removeListener<eve::IStateQuery>(match->get());
219 owned.retiredQueries.push_back(std::move(*match));
220 owned.liveQueries.erase(match);
222 });
223}
224
226 ScriptStateAccessProviders& owned = scriptStateAccessProviders();
227 for (auto& adapter : owned.liveQueries) {
228 eve::cap::removeListener<eve::IStateQuery>(adapter.get());
229 owned.retiredQueries.push_back(std::move(adapter));
230 }
231 owned.liveQueries.clear();
234 .ignore("a module may be destroyed without ever having declared the seam");
235}
236
238 ScriptStateAccessProviders& owned = scriptStateAccessProviders();
242 // 单实现槽位(消费方用 `cap::query`):顶掉当前实现必须可见,否则原生 provider 会
243 // "悄悄失效",症状只是世界状态不再被写入。
244 if (eve::cap::query<eve::IStateMutation>() != nullptr) {
245 recordLogEvent("warn", "script state mutation provider '" + handle.name +
246 "' replaced the provider that owned IStateMutation");
247 }
248 auto adapter = std::make_unique<ScriptStateMutation>(handle);
249 eve::cap::provide<eve::IStateMutation>(adapter.get());
250 owned.liveMutations.push_back(std::move(adapter));
252 },
254 const auto match = std::find_if(
255 owned.liveMutations.begin(), owned.liveMutations.end(),
256 [&handle](const std::unique_ptr<ScriptStateMutation>& adapter) { return adapter->handle() == handle; });
257 if (match == owned.liveMutations.end()) {
259 }
260 eve::cap::revoke<eve::IStateMutation>(match->get());
261 owned.retiredMutations.push_back(std::move(*match));
262 owned.liveMutations.erase(match);
264 });
265}
266
268 ScriptStateAccessProviders& owned = scriptStateAccessProviders();
269 for (auto& adapter : owned.liveMutations) {
270 eve::cap::revoke<eve::IStateMutation>(adapter.get());
271 owned.retiredMutations.push_back(std::move(adapter));
272 }
273 owned.liveMutations.clear();
276 .ignore("a module may be destroyed without ever having declared the seam");
277}
278
279} // namespace eve::dialogue
int subject
Definition AnimSmr.cpp:163
ActiveSource owned
bool changed
Persistent, thread-safe record of engine crash and problem events.
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::uint16_t method
#define EVENGINE_API_ORCHESTRATION
Definition Export.h:111
std::string message
JobScope scope
const std::string * tag
PrimitiveHandle handle
Object::Ptr value
std::string attribute
std::string kind
std::string resource
bool boolean
int count
std::string_view adapter
std::vector< std::unique_ptr< ScriptStateMutation > > liveMutations
std::vector< std::unique_ptr< ScriptStateQuery > > liveQueries
std::vector< std::unique_ptr< ScriptStateMutation > > retiredMutations
std::vector< std::unique_ptr< ScriptStateQuery > > retiredQueries
让脚本扮演 IStateQuery / IStateMutation(阶段 5 的第五、六个插座)。
Consumer-owned query and mutation contracts for authoritative world state.
Owning, renderer-independent dynamic values.
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
Result< void > removeCapability(std::string_view capability)
Withdraw a declared seam when its owning module goes away.
static ScriptProviderRegistry & instance()
Process-lifetime registry; clearAll is the only reset.
void declareCapability(std::string capability, ScriptCapabilityBinder binder, ScriptCapabilityUnbinder unbinder)
Declare that one native capability may be served by a script provider.
Result< Value > callValue(const ScriptProviderHandle &handle, std::string_view method, std::span< const ScriptArg > args) const
Call method(...) and read the script result as an owning eve::Value.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Value string(std::string value)
Compatibility factory for a string value.
Definition Value.h:121
std::vector< Value > Array
Definition Value.h:33
static Value array(Array value)
Compatibility factory for an array value.
Definition Value.cpp:128
static Value boolean(bool value)
Compatibility factory for a boolean value.
Definition Value.h:119
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
All-or-nothing mutation boundary owned by the consumer.
static constexpr const char * capabilityName
Read-only world-state boundary owned by consumers such as Dialogue.
Definition StateAccess.h:79
static constexpr const char * capabilityName
Definition StateAccess.h:81
EVENGINE_API_ORCHESTRATION void withdrawScriptStateQuerySeam()
撤回 IStateQuery 接缝与仍然在位的脚本适配器。
EVENGINE_API_ORCHESTRATION void declareScriptStateQuerySeam()
声明"`IStateQuery` 可以由脚本提供"这条接缝。
EVENGINE_API_ORCHESTRATION std::uint64_t scriptStateQueryFailures()
脚本 state query **失败**(抛错或答案形状不对)的累计次数。
EVENGINE_API_ORCHESTRATION void withdrawScriptStateMutationSeam()
撤回 IStateMutation 接缝与仍然在位的脚本适配器。
EVENGINE_API_ORCHESTRATION void resetScriptStateQueryFailures()
把上面的计数归零(测试隔离用)。
EVENGINE_API_ORCHESTRATION void declareScriptStateMutationSeam()
声明"`IStateMutation` 可以由脚本提供"这条接缝。
MutationKind
Kind of one requested world-state mutation.
Definition StateAccess.h:26
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
void recordLogEvent(const std::string &level, const std::string &message)
Appends a timestamped event line to the crash/error log.
Definition CrashLog.cpp:70
One argument passed to a script provider method.
static ScriptArg fromText(std::string value)
static ScriptArg fromTable(Value::Object fields)
One object argument (a table on the script side). @cost One Value tree copy.
Generation-qualified identity of one published script provider.
Correlation metadata shared by a mutation transaction.
Definition StateAccess.h:57
Observable result of an all-or-nothing mutation request.
Definition StateAccess.h:64
One immutable mutation request owned by its caller.
Definition StateAccess.h:42