载入中...
搜索中...
未找到
StatePatch.cpp
浏览该文件的文档.
2
3#include "common/Capability.h"
4#include "common/Json.h"
8
9#include <simplesquirrel/simplesquirrel.hpp>
10
11#include <algorithm>
12#include <exception>
13#include <functional>
14#include <iomanip>
15#include <limits>
16#include <sstream>
17
18namespace eve::statepatch {
19namespace {
20
22struct ScriptStateStore {
23 explicit ScriptStateStore(StateStoreHandleRef value) : reference(value) {}
24 ~ScriptStateStore() noexcept {
25 StatePatch::release(reference).ignore("script state-patch store proxy destruction");
26 }
28};
29
31struct ScriptStateBatch {
32 explicit ScriptStateBatch(StateBatchHandleRef value) : reference(value) {}
33 ~ScriptStateBatch() noexcept {
34 StatePatch::releaseBatch(reference).ignore("script state-patch batch proxy destruction");
35 }
36 StateBatchHandleRef reference;
37};
38
39template <class Ref, class Proxy, class Release>
40ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result<Ref>&& reference, Release&& release) {
42 const Ref ref = std::move(reference).takeValue();
43 auto object = eve::script::makeOwnedSquirrelInstance<Proxy>(vm, std::make_unique<Proxy>(ref));
44 if (!object) {
45 const eve::Status status = object.status();
46 object.ignore("failed to create owned state-patch proxy");
47 std::invoke(std::forward<Release>(release), ref).ignore("rollback failed owned state-patch allocation");
49 }
50 ssq::Object owned = std::move(object).takeValue();
52 result.set("value", owned);
53 result.set("ownership", std::string("owned"));
54 result.set("ownerEpoch", static_cast<std::int64_t>(ref.ownerEpoch));
55 result.set("handle", static_cast<std::int64_t>(ref.packed()));
56 return result;
57}
58
59std::string quote(const std::string& value) {
60 return eve::json::quoteString(value, eve::json::StringEscapeStyle::Canonical);
61}
62
63std::string canonicalJson(const eve::json::Value& value) {
64 if (value.isNull()) return "null";
65 if (value.isBool()) return value.asBool() ? "true" : "false";
66 if (value.isNumber()) return value.asString();
67 if (value.isString()) return quote(value.asString());
68 if (value.isArray()) {
69 std::string out = "[";
70 for (size_t i = 0; i < value.size(); ++i) {
71 if (i) out += ',';
72 out += canonicalJson(value.at(i));
73 }
74 return out + ']';
75 }
76 if (value.isObject()) {
77 auto keys = value.keys();
78 std::sort(keys.begin(), keys.end());
79 std::string out = "{";
80 for (size_t i = 0; i < keys.size(); ++i) {
81 if (i) out += ',';
82 out += quote(keys[i]) + ':' + canonicalJson(value.get(keys[i].c_str()));
83 }
84 return out + '}';
85 }
86 return {};
87}
88
89bool normalize(const std::string& input, std::string& output) {
90 auto document = eve::json::Document::parse(input);
91 if (!document.valid()) return false;
92 output = canonicalJson(document.root());
93 return true;
94}
95
96bool parseU64(const eve::json::Value& value, uint64_t& output) {
97 if (!value.isString()) return false;
98 auto parsed = eve::json::scanUnsignedInteger(value.asString(), eve::json::UnsignedIntegerSyntax::LegacyStoull);
99 if (!parsed) return false;
100 output = parsed.value().value;
101 return parsed.value().consumed == parsed.value().size;
102}
103
104eve::LogicalId statePatchSchema() {
105 const auto schema = eve::LogicalId::parse("statepatch:store");
106 if (!schema) std::terminate();
107 return *schema;
108}
109
110const eve::SnapshotMigrationChain& statePatchMigrations() {
111 static const eve::SnapshotMigrationChain chain = [] {
113 const auto registration =
114 result.add(statePatchSchema(), eve::SchemaVersion(0), eve::SchemaVersion(1),
116 const auto* object = payload.getIf<eve::Value::Object>();
117 if (!object)
119 eve::DiagnosticCode::ParseError, "state patch payload must be an object"));
120 eve::Value::Object migrated = *object;
121 if (!migrated.contains("version")) migrated.emplace("version", eve::Value(std::int64_t(1)));
122 return eve::Result<eve::Value>::success(eve::Value(std::move(migrated)));
123 });
124 if (!registration.ok()) std::terminate();
125 return result;
126 }();
127 return chain;
128}
129
130} // namespace
131
133
134bool PatchBatch::set(const std::string& subject, const std::string& key, const std::string& jsonValue) {
135 std::string value;
136 const bool valid = normalize(jsonValue, value);
137 operations_.push_back({false, subject, key, value, std::nullopt, valid ? "" : "value must be valid JSON"});
138 return valid;
139}
140
141bool PatchBatch::setExpected(const std::string& subject, const std::string& key, const std::string& jsonValue,
142 const std::string& expectedJson) {
143 std::string value;
144 std::string expected;
145 const bool valueValid = normalize(jsonValue, value);
146 const bool expectedValid = normalize(expectedJson, expected);
147 std::string error;
148 if (!valueValid) error = "value must be valid JSON";
149 if (!expectedValid)
150 error = error.empty() ? "expected value must be valid JSON" : error + "; expected value must be valid JSON";
151 operations_.push_back({false, subject, key, value, expected, error});
152 return valueValid && expectedValid;
153}
154
155bool PatchBatch::remove(const std::string& subject, const std::string& key) {
156 operations_.push_back({true, subject, key, {}, std::nullopt, {}});
157 return true;
158}
159
160bool PatchBatch::removeExpected(const std::string& subject, const std::string& key, const std::string& expectedJson) {
161 std::string expected;
162 const bool valid = normalize(expectedJson, expected);
163 operations_.push_back({true, subject, key, {}, expected, valid ? "" : "expected value must be valid JSON"});
164 return valid;
165}
166
168 operations_.clear();
169 result_ = {};
170}
171
172int PatchBatch::size() const { return static_cast<int>(operations_.size()); }
173
174const PatchResult& PatchBatch::result() const { return result_; }
175
176eve::Result<PatchBatchHandleRef> Store::newBatch() { return batches_.emplace(std::make_unique<PatchBatch>()); }
177
181
183
185 if (!reference.isValid()) return false;
186 return batches_.isStale(reference);
187}
188
189namespace {
190
191eve::Result<PatchCommitInfo> patchCommitFailure(const PatchResult& result) {
194 std::vector<eve::Diagnostic> diagnostics;
195 for (const auto& error : result.errors) {
196 if (error.code == "conflict") {
197 statusCode = eve::StatusCode::Conflict;
198 diagnosticCode = eve::DiagnosticCode::Conflict;
199 } else if (statusCode == eve::StatusCode::Failed && error.code.starts_with("invalid_")) {
200 statusCode = eve::StatusCode::Rejected;
202 }
204 details.emplace_back("rule", error.code);
205 details.emplace_back("operationIndex", std::to_string(error.operationIndex));
206 if (!error.subject.empty()) details.emplace_back("subject", error.subject);
207 if (!error.key.empty()) details.emplace_back("key", error.key);
208 diagnostics.push_back(eve::Diagnostic::error(
209 diagnosticCode, error.message.empty() ? "state patch batch was rejected" : error.message,
210 "statepatch[" + std::to_string(error.operationIndex) + "]", std::move(details), "statepatch.commit"));
211 }
212 if (diagnostics.empty())
214 "state patch batch could not be prepared", "statepatch", {},
215 "statepatch.commit"));
216 return eve::Result<PatchCommitInfo>::failure(eve::Status(statusCode, std::move(diagnostics)));
217}
218
219} // namespace
220
222 if (!batch)
224 eve::DiagnosticCode::InvalidArgument, "patch batch must not be null", "batch", {}, "statepatch.commit"));
225 batch->result_ = {};
226 batch->result_.revisionBefore = revision_;
227 batch->result_.revisionAfter = revision_;
228 Values staged = values_;
229 for (size_t i = 0; i < batch->operations_.size(); ++i) {
230 const auto& operation = batch->operations_[i];
231 auto fail = [&](const std::string& code, const std::string& message) {
232 batch->result_.errors.push_back({static_cast<int>(i), operation.subject, operation.key, code, message});
233 };
234 if (operation.subject.empty()) fail("invalid_subject", "subject must not be empty");
235 if (operation.key.empty()) fail("invalid_key", "key must not be empty");
236 if (!operation.inputError.empty()) fail("invalid_json", operation.inputError);
237 if (!batch->result_.errors.empty() && batch->result_.errors.back().operationIndex == static_cast<int>(i))
238 continue;
239 const auto subjectIt = staged.find(operation.subject);
240 const auto valueIt = subjectIt == staged.end() ? std::map<std::string, Value>::const_iterator{}
241 : subjectIt->second.find(operation.key);
242 const bool exists = subjectIt != staged.end() && valueIt != subjectIt->second.end();
243 if (operation.expected && (!exists || valueIt->second.json != *operation.expected)) {
244 fail("conflict", "current value does not match expected JSON");
245 continue;
246 }
247 if (operation.remove) {
248 if (exists) {
249 staged[operation.subject].erase(operation.key);
250 if (staged[operation.subject].empty()) staged.erase(operation.subject);
251 }
252 } else {
253 staged[operation.subject][operation.key].json = operation.value;
254 }
255 }
256 if (!batch->result_.errors.empty()) return patchCommitFailure(batch->result_);
257
258 struct Pending {
259 std::string subject;
260 std::string key;
261 std::string oldJson;
262 std::string newJson;
263 bool removed;
264 };
265 std::vector<Pending> changes;
266 std::set<std::pair<std::string, std::string>> keys;
267 for (const auto& [subject, entries] : values_)
268 for (const auto& [key, value] : entries) keys.emplace(subject, key);
269 for (const auto& [subject, entries] : staged)
270 for (const auto& [key, value] : entries) keys.emplace(subject, key);
271 for (const auto& [subject, key] : keys) {
272 const auto oldSubject = values_.find(subject);
273 const auto newSubject = staged.find(subject);
274 const auto oldValue =
275 oldSubject == values_.end() ? std::map<std::string, Value>::const_iterator{} : oldSubject->second.find(key);
276 const auto newValue =
277 newSubject == staged.end() ? std::map<std::string, Value>::const_iterator{} : newSubject->second.find(key);
278 const bool had = oldSubject != values_.end() && oldValue != oldSubject->second.end();
279 const bool has = newSubject != staged.end() && newValue != newSubject->second.end();
280 if (had != has || (had && oldValue->second.json != newValue->second.json))
281 changes.push_back({subject, key, had ? oldValue->second.json : "", has ? newValue->second.json : "", !has});
282 }
283 if (!changes.empty()) {
284 if (revision_ == std::numeric_limits<uint64_t>::max() ||
285 nextSequence_ > std::numeric_limits<uint64_t>::max() - changes.size()) {
286 batch->result_.errors.push_back({-1, {}, {}, "revision_exhausted", "revision or event sequence exhausted"});
287 return patchCommitFailure(batch->result_);
288 }
289 ++revision_;
290 for (const auto& change : changes) {
291 if (!change.removed) staged[change.subject][change.key].revision = revision_;
292 dirty_.emplace(change.subject, change.key);
293 events_.push_back({nextSequence_++, revision_, change.subject, change.key, change.oldJson, change.newJson,
294 change.removed});
295 }
296 values_ = std::move(staged);
297 }
298 batch->result_.success = true;
299 batch->result_.changedCount = static_cast<int>(changes.size());
300 batch->result_.revisionAfter = revision_;
301 PatchCommitInfo info{batch->result_.changedCount, batch->result_.revisionBefore, batch->result_.revisionAfter};
304}
305
306bool Store::has(const std::string& subject, const std::string& key) const {
307 const auto found = values_.find(subject);
308 return found != values_.end() && found->second.find(key) != found->second.end();
309}
310
311std::string Store::get(const std::string& subject, const std::string& key) const {
312 const auto found = values_.find(subject);
313 if (found == values_.end()) return {};
314 const auto value = found->second.find(key);
315 return value == found->second.end() ? std::string{} : value->second.json;
316}
317
318uint64_t Store::valueRevision(const std::string& subject, const std::string& key) const {
319 const auto found = values_.find(subject);
320 if (found == values_.end()) return 0;
321 const auto value = found->second.find(key);
322 return value == found->second.end() ? 0 : value->second.revision;
323}
324
325uint64_t Store::revision() const { return revision_; }
326
327int Store::querySubjects() {
328 query_.clear();
329 for (const auto& [subject, entries] : values_) query_.push_back(subject);
330 return static_cast<int>(query_.size());
331}
332
333int Store::queryKeys(const std::string& subject) {
334 query_.clear();
335 const auto found = values_.find(subject);
336 if (found != values_.end())
337 for (const auto& [key, value] : found->second) query_.push_back(key);
338 return static_cast<int>(query_.size());
339}
340
341std::string Store::queryAt(int index) const {
342 return index >= 0 && static_cast<size_t>(index) < query_.size() ? query_[static_cast<size_t>(index)]
343 : std::string{};
344}
345
346int Store::queryDirty() {
347 dirtyQuery_.assign(dirty_.begin(), dirty_.end());
348 return static_cast<int>(dirtyQuery_.size());
349}
350
351std::string Store::dirtySubjectAt(int index) const {
352 return index >= 0 && static_cast<size_t>(index) < dirtyQuery_.size() ? dirtyQuery_[static_cast<size_t>(index)].first
353 : std::string{};
354}
355
356std::string Store::dirtyKeyAt(int index) const {
357 return index >= 0 && static_cast<size_t>(index) < dirtyQuery_.size()
358 ? dirtyQuery_[static_cast<size_t>(index)].second
359 : std::string{};
360}
361
362void Store::clearDirty() {
363 dirty_.clear();
364 dirtyQuery_.clear();
365}
366
367int Store::eventCount() const { return static_cast<int>(events_.size()); }
368
369const ChangeEvent* Store::eventAt(int index) const {
370 return index >= 0 && static_cast<size_t>(index) < events_.size() ? &events_[static_cast<size_t>(index)] : nullptr;
371}
372
373void Store::clearEvents() { events_.clear(); }
374
375std::string Store::snapshotJson() const {
376 std::ostringstream out;
377 out << "{\"version\":1,\"revision\":" << quote(std::to_string(revision_))
378 << ",\"nextSequence\":" << quote(std::to_string(nextSequence_)) << ",\"values\":[";
379 bool first = true;
380 for (const auto& [subject, entries] : values_)
381 for (const auto& [key, value] : entries) {
382 if (!first) out << ',';
383 first = false;
384 out << "{\"subject\":" << quote(subject) << ",\"key\":" << quote(key)
385 << ",\"revision\":" << quote(std::to_string(value.revision)) << ",\"value\":" << value.json << '}';
386 }
387 out << "],\"dirty\":[";
388 first = true;
389 for (const auto& [subject, key] : dirty_) {
390 if (!first) out << ',';
391 first = false;
392 out << "[" << quote(subject) << ',' << quote(key) << ']';
393 }
394 return out.str() + "]}";
395}
396
397eve::Result<void> Store::restoreJson(const std::string& json) {
398 std::string parseError;
399 auto document = eve::json::Document::parse(json, &parseError);
400 if (!document.valid())
401 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, parseError.empty() ? "invalid state patch snapshot" : parseError,
402 "$", {}, "statepatch.store.restoreJson"));
403
404 const auto root = document.root();
405 if (!root.isObject()) return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "snapshot root must be an object",
406 "$", {}, "statepatch.store.restoreJson"));
407
408 uint64_t restoredRevision = 0;
409 uint64_t restoredSequence = 0;
410 if (root.getInt("version") != 1) return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "unsupported state patch snapshot version",
411 "$.version", {}, "statepatch.store.restoreJson"));
412 if (!parseU64(root.get("revision"), restoredRevision))
413 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "snapshot revision must be a decimal string",
414 "$.revision", {}, "statepatch.store.restoreJson"));
415 if (!parseU64(root.get("nextSequence"), restoredSequence) || restoredSequence == 0)
416 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "snapshot nextSequence must be a non-zero decimal string",
417 "$.nextSequence", {}, "statepatch.store.restoreJson"));
418
419 const auto values = root.get("values");
420 const auto dirty = root.get("dirty");
421 if (!values.isArray() || !dirty.isArray()) {
423 "$", {}, "statepatch.store.restoreJson"));
424 }
425 Values restoredValues;
426 std::set<std::pair<std::string, std::string>> restoredDirty;
427 for (size_t i = 0; i < values.size(); ++i) {
428 const auto item = values.at(i);
429 uint64_t valueRevision = 0;
430 if (!item.isObject() || item.getString("subject").empty() || item.getString("key").empty() ||
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),
433 "$.values[" + std::to_string(i) + "]", {}, "statepatch.store.restoreJson"));
434 }
435 const auto subject = item.getString("subject");
436 const auto key = item.getString("key");
437 if (restoredValues[subject].contains(key)) {
439 "$.values[" + std::to_string(i) + "]", {}, "statepatch.store.restoreJson"));
440 }
441 restoredValues[subject][key] = {canonicalJson(item.get("value")), valueRevision};
442 }
443 for (size_t i = 0; i < dirty.size(); ++i) {
444 const auto item = dirty.at(i);
445 if (!item.isArray() || item.size() != 2 || !item.at(0).isString() || !item.at(1).isString() ||
446 item.at(0).asString().empty() || item.at(1).asString().empty()) {
447 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "invalid dirty key at index " + std::to_string(i),
448 "$.dirty[" + std::to_string(i) + "]", {}, "statepatch.store.restoreJson"));
449 }
450 restoredDirty.emplace(item.at(0).asString(), item.at(1).asString());
451 }
452 values_ = std::move(restoredValues);
453 dirty_ = std::move(restoredDirty);
454 revision_ = restoredRevision;
455 nextSequence_ = restoredSequence;
456 events_.clear();
457 query_.clear();
458 dirtyQuery_.clear();
459 batches_.clear();
461}
462
463eve::Result<eve::SnapshotEnvelope> Store::snapshot(const eve::SnapshotHashProvider& hashProvider) const {
464 auto payload = eve::Value::fromJson(snapshotJson());
466 return eve::makeSnapshotEnvelope("statepatch.store", statePatchSchema(), eve::SchemaVersion(1), instanceId_,
467 eve::Revision(revision_), tick_, std::move(payload).takeValue(), hashProvider);
468}
469
470eve::Result<void> Store::restoreSnapshot(const eve::SnapshotEnvelope& source,
471 const eve::SnapshotHashProvider& hashProvider) {
472 if (source.type != "statepatch.store" || source.schema != statePatchSchema())
474 "snapshot does not belong to statepatch::Store"));
475 if (!instanceId_.isNil() && source.instanceId != instanceId_)
477 eve::DiagnosticCode::Conflict, "snapshot instanceId does not match statepatch::Store"));
478 auto migrated = statePatchMigrations().migrate(source, eve::SchemaVersion(1), hashProvider);
479 if (!migrated.ok()) return eve::Result<void>::failure(migrated.status());
480 const auto& candidateEnvelope = migrated.value();
481 auto metadata = eve::validateSnapshotPayloadMetadata(candidateEnvelope.payload, candidateEnvelope.revision,
482 candidateEnvelope.tick);
483 if (!metadata.ok()) return eve::Result<void>::failure(metadata.status());
484 auto payload = candidateEnvelope.payload.toJson();
485 if (!payload.ok()) return eve::Result<void>::failure(payload.status());
486
487 Store candidate(instanceId_);
488 auto restored = candidate.restoreJson(std::move(payload).takeValue());
489 if (!restored.ok()) return eve::Result<void>::failure(restored.status());
490 if (candidate.revision_ != candidateEnvelope.revision.value())
492 eve::DiagnosticCode::Conflict, "state patch payload revision disagrees with snapshot envelope"));
493 candidate.instanceId_ = candidateEnvelope.instanceId;
494 candidate.tick_ = candidateEnvelope.tick;
495 *this = std::move(candidate);
497}
498
499eve::Result<std::string> Store::snapshotEnvelopeJson(const eve::SnapshotHashProvider& hashProvider) const {
500 auto value = snapshot(hashProvider);
501 if (!value.ok()) return eve::Result<std::string>::failure(value.status());
502 return std::move(value).andThen(
503 [](eve::SnapshotEnvelope&& envelope) { return eve::serializeSnapshotEnvelope(envelope); });
504}
505
506eve::Result<void> Store::restoreSnapshotJson(std::string_view json, const eve::SnapshotHashProvider& hashProvider) {
507 auto source = eve::parseSnapshotEnvelope(json, hashProvider);
508 if (!source.ok()) return eve::Result<void>::failure(source.status());
509 return restoreSnapshot(std::move(source).takeValue(), hashProvider);
510}
511
512void Store::copyTransactionStateFrom(const Store& source) {
513 values_ = source.values_;
514 revision_ = source.revision_;
515 nextSequence_ = source.nextSequence_;
516 dirty_ = source.dirty_;
517 events_ = source.events_;
518 query_.clear();
519 dirtyQuery_.clear();
520 batches_.clear();
521}
522
523void Store::swapTransactionState(Store& other) noexcept {
524 values_.swap(other.values_);
525 std::swap(revision_, other.revision_);
526 std::swap(nextSequence_, other.nextSequence_);
527 dirty_.swap(other.dirty_);
528 events_.swap(other.events_);
529 query_.clear();
530 dirtyQuery_.clear();
531 other.query_.clear();
532 other.dirtyQuery_.clear();
533}
534
535bool Store::transactionStateEquals(const Store& other) const {
536 if (snapshotJson() != other.snapshotJson() || events_.size() != other.events_.size()) return false;
537 for (size_t i = 0; i < events_.size(); ++i) {
538 const auto& left = events_[i];
539 const auto& right = other.events_[i];
540 if (left.sequence != right.sequence || left.revision != right.revision || left.subject != right.subject ||
541 left.key != right.key || left.oldJson != right.oldJson || left.newJson != right.newJson ||
542 left.removed != right.removed)
543 return false;
544 }
545 return true;
546}
547
548bool StoreTransactionParticipant::contextMatches(const transaction::TransactionContext& context) const noexcept {
549 return context.transactionId() == transactionId_ && context.correlationId() == correlationId_ &&
550 context.causationId() == causationId_;
551}
552
553eve::Result<void> StoreTransactionParticipant::lifecycleFailure(std::string_view operation) const {
556 "statepatch participant cannot " + std::string(operation) + " in its current lifecycle phase",
557 "statepatch.lifecycle"));
558}
559
560eve::Result<void> StoreTransactionParticipant::contextFailure(const transaction::TransactionContext& context) const {
561 (void)context;
563 eve::DiagnosticCode::Conflict, "transaction context changed between participant lifecycle calls",
564 "statepatch.context"));
565}
566
567eve::Result<void> StoreTransactionParticipant::prepare(const transaction::TransactionContext& context) {
568 if (phase_ != Phase::Idle) return lifecycleFailure("prepare");
569 if (context.transactionId().empty())
571 "transaction id must not be empty", "transactionId"));
572
573 transactionId_ = context.transactionId();
574 correlationId_ = context.correlationId();
575 causationId_ = context.causationId();
576 before_ = std::make_unique<Store>();
577 before_->copyTransactionStateFrom(store_);
578 prepared_ = std::make_unique<Store>();
579 prepared_->copyTransactionStateFrom(*before_);
580
581 auto committed = prepared_->commit(&batch_);
582 if (!committed.ok()) {
584 before_.reset();
585 prepared_.reset();
586 phase_ = Phase::Failed;
587 return result;
588 }
589
590 expectedAfter_ = std::make_unique<Store>();
591 expectedAfter_->copyTransactionStateFrom(*prepared_);
592 phase_ = Phase::Prepared;
594}
595
596eve::Result<void> StoreTransactionParticipant::commit(const transaction::TransactionContext& context) {
597 if (phase_ != Phase::Prepared) return lifecycleFailure("commit");
598 if (!contextMatches(context)) return contextFailure(context);
599 if (!before_ || !prepared_ || !expectedAfter_ || !store_.transactionStateEquals(*before_))
601 eve::DiagnosticCode::Conflict, "state patch store changed after prepare", "statepatch.store"));
602
603 store_.swapTransactionState(*prepared_);
604 phase_ = Phase::Committed;
606}
607
608eve::Result<void> StoreTransactionParticipant::rollback(const transaction::TransactionContext& context) {
609 if (phase_ != Phase::Prepared) return lifecycleFailure("rollback");
610 if (!contextMatches(context)) return contextFailure(context);
611 before_.reset();
612 prepared_.reset();
613 expectedAfter_.reset();
614 phase_ = Phase::RolledBack;
616}
617
618eve::Result<void> StoreTransactionParticipant::compensate(const transaction::TransactionContext& context) {
619 if (phase_ != Phase::Committed) return lifecycleFailure("compensate");
620 if (!contextMatches(context)) return contextFailure(context);
621 if (!prepared_ || !expectedAfter_ || !store_.transactionStateEquals(*expectedAfter_))
623 eve::DiagnosticCode::Conflict, "state patch store changed before compensation", "statepatch.store"));
624
625 store_.swapTransactionState(*prepared_);
626 expectedAfter_.reset();
627 phase_ = Phase::Compensated;
629}
630
631StatePatch::~StatePatch() {
632 for (auto& [store, adapter] : worldAdapters_) {
633 (void)store;
634 if (!adapter) continue;
635 eve::cap::removeListener<eve::IStateQuery>(static_cast<eve::IStateQuery*>(adapter.get()));
636 eve::cap::removeListener<eve::IStateMutation>(static_cast<eve::IStateMutation*>(adapter.get()));
637 }
638 worldAdapters_.clear();
639}
640
641void StatePatch::attachWorldAdapter(Store& store) {
642 if (worldAdapters_.contains(&store)) return;
643 auto adapter = std::make_unique<StatePatchStateAdapter>(store);
644 eve::cap::addListener<eve::IStateQuery>(static_cast<eve::IStateQuery*>(adapter.get()));
645 eve::cap::addListener<eve::IStateMutation>(static_cast<eve::IStateMutation*>(adapter.get()));
646 worldAdapters_.emplace(&store, std::move(adapter));
647}
648
649void StatePatch::detachWorldAdapter(Store& store) {
650 const auto found = worldAdapters_.find(&store);
651 if (found == worldAdapters_.end()) return;
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()));
654 worldAdapters_.erase(found);
655}
656
657eve::Result<StateStoreHandleRef> StatePatch::newStore() {
658 StatePatch* module = StatePatch::create();
659 auto created = module->stores_.emplace(std::make_unique<Store>());
660 if (!created) return created;
661 auto ref = std::move(created).takeValue();
662 auto store = module->stores_.resolve(ref);
663 if (store.isBound()) module->attachWorldAdapter(*store);
665}
666
668 StatePatch* module = ModuleManager::getInstance<StatePatch>("StatePatch");
669 if (!module) return {};
670 auto store = module->stores_.resolve(reference.store);
671 if (!store.isBound()) return {};
672 return store->resolveBatch(reference.batch);
673}
674
676 StatePatch* module = ModuleManager::getInstance<StatePatch>("StatePatch");
677 if (!module)
679 "StatePatch module is no longer loaded", "batch", {},
680 "statepatch.squirrel"));
681 auto store = module->stores_.resolve(reference.store);
682 if (!store.isBound())
684 eve::DiagnosticCode::StaleHandle, "owning StatePatch store is stale", "store", {}, "statepatch.squirrel"));
685 return store->releaseBatch(reference.batch);
686}
687
688bool StatePatch::isBatchStale(StateBatchHandleRef reference) noexcept {
689 if (!reference.isValid()) return false;
690 StatePatch* module = ModuleManager::getInstance<StatePatch>("StatePatch");
691 if (!module) return true;
692 auto store = module->stores_.resolve(reference.store);
693 return !store.isBound() || store->isBatchStale(reference.batch);
694}
695
697 StatePatch* module = ModuleManager::getInstance<StatePatch>("StatePatch");
698 if (!module) return {};
699 return module->stores_.resolve(reference);
700}
701
703 StatePatch* module = ModuleManager::getInstance<StatePatch>("StatePatch");
704 if (!module)
706 "StatePatch module is no longer loaded", "store", {},
707 "statepatch.squirrel"));
708 auto store = module->stores_.resolve(reference);
709 if (store.isBound()) module->detachWorldAdapter(*store);
710 return module->stores_.erase(reference);
711}
712
713bool StatePatch::isStale(StateStoreHandleRef reference) noexcept {
714 if (!reference.isValid()) return false;
715 StatePatch* module = ModuleManager::getInstance<StatePatch>("StatePatch");
716 return !module || module->stores_.isStale(reference);
717}
718
720
721void StatePatch::expose(ssq::Table& table) {
722 const HSQUIRRELVM vm = table.getHandle();
723 auto error = table.addClass<PatchError>("PatchError", std::function<PatchError*()>([] { return nullptr; }), false);
724 error.addFunc("getOperationIndex", [](PatchError* e) { return e ? e->operationIndex : -1; });
725 error.addFunc("getSubject", [](PatchError* e) { return e ? e->subject : std::string{}; });
726 error.addFunc("getKey", [](PatchError* e) { return e ? e->key : std::string{}; });
727 error.addFunc("getCode", [](PatchError* e) { return e ? e->code : std::string{}; });
728 error.addFunc("getMessage", [](PatchError* e) { return e ? e->message : std::string{}; });
729
730 auto result =
731 table.addClass<PatchResult>("PatchResult", std::function<PatchResult*()>([] { return nullptr; }), false);
732 result.addFunc("isSuccess", [](PatchResult* r) { return r && r->success; });
733 result.addFunc("getChangedCount", [](PatchResult* r) { return r ? r->changedCount : 0; });
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; });
737 result.addFunc("errorAt", [](PatchResult* r, int index) -> PatchError* {
738 return r && index >= 0 && static_cast<size_t>(index) < r->errors.size() ? &r->errors[static_cast<size_t>(index)]
739 : nullptr;
740 });
741
742 auto event =
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; });
746 event.addFunc("getSubject", [](ChangeEvent* e) { return e ? e->subject : std::string{}; });
747 event.addFunc("getKey", [](ChangeEvent* e) { return e ? e->key : std::string{}; });
748 event.addFunc("getOldJson", [](ChangeEvent* e) { return e ? e->oldJson : std::string{}; });
749 event.addFunc("getNewJson", [](ChangeEvent* e) { return e ? e->newJson : std::string{}; });
750 event.addFunc("isRemoved", [](ChangeEvent* e) { return e && e->removed; });
751
752 auto batch = table.addClass<PatchBatch>("PatchBatch", std::function<PatchBatch*()>([] { return nullptr; }), false);
753 batch.addFunc("set", &PatchBatch::set);
754 batch.addFunc("setExpected", &PatchBatch::setExpected);
755 batch.addFunc("remove", &PatchBatch::remove);
756 batch.addFunc("removeExpected", &PatchBatch::removeExpected);
757 batch.addFunc("clear", &PatchBatch::clear);
758 batch.addFunc("size", &PatchBatch::size);
759 batch.addFunc("result",
760 [](PatchBatch* b) -> PatchResult* { return b ? const_cast<PatchResult*>(&b->result()) : nullptr; });
761
762 auto ownedBatch = table.addClass<ScriptStateBatch>(
763 "StateBatchProxy", std::function<ScriptStateBatch*()>([] { return nullptr; }), true);
764 ownedBatch.addFunc("ownership", [](ScriptStateBatch*) { return std::string("owned"); });
765 ownedBatch.addFunc("ownerEpoch", [](ScriptStateBatch* value) {
766 return value ? static_cast<int64_t>(value->reference.ownerEpoch) : int64_t{0};
767 });
768 ownedBatch.addFunc("handle", [](ScriptStateBatch* value) {
769 return value ? static_cast<int64_t>(value->reference.packed()) : int64_t{0};
770 });
771 ownedBatch.addFunc("isStale",
772 [](ScriptStateBatch* value) { return !value || StatePatch::isBatchStale(value->reference); });
773 ownedBatch.addFunc("release", [vm](ScriptStateBatch* value) {
774 if (!value)
777 "owned state batch proxy must not be null",
778 "batch", {}, "statepatch.squirrel")));
779 return eve::script::projectResult(vm, StatePatch::releaseBatch(value->reference));
780 });
781 ownedBatch.addFunc("set", [vm](ScriptStateBatch* value, const std::string& subject, const std::string& key,
782 const std::string& jsonValue) {
783 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
784 if (!view.isBound())
786 vm,
788 eve::DiagnosticCode::StaleHandle, std::string("owned state-patch ") + "batch" + " handle is stale",
789 "batch", {}, "statepatch.squirrel")),
790 [](bool value) { return eve::Value(value); });
792 [](bool value) { return eve::Value(value); });
793 });
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>();
796 if (!view.isBound())
798 vm,
800 eve::DiagnosticCode::StaleHandle, std::string("owned state-patch ") + "batch" + " handle is stale",
801 "batch", {}, "statepatch.squirrel")),
802 [](bool value) { return eve::Value(value); });
804 [](bool value) { return eve::Value(value); });
805 });
806 ownedBatch.addFunc("setExpected", [vm](ScriptStateBatch* value, const std::string& subject, const std::string& key,
807 const std::string& jsonValue, const std::string& expectedJson) {
808 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
809 if (!view.isBound())
811 vm,
813 eve::DiagnosticCode::StaleHandle, std::string("owned state-patch ") + "batch" + " handle is stale",
814 "batch", {}, "statepatch.squirrel")),
815 [](bool value) { return eve::Value(value); });
817 vm, eve::Result<bool>::success(view->setExpected(subject, key, jsonValue, expectedJson)),
818 [](bool result) { return eve::Value(result); });
819 });
820 ownedBatch.addFunc("removeExpected", [vm](ScriptStateBatch* value, const std::string& subject,
821 const std::string& key, const std::string& expectedJson) {
822 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
823 if (!view.isBound())
825 vm,
827 eve::DiagnosticCode::StaleHandle, std::string("owned state-patch ") + "batch" + " handle is stale",
828 "batch", {}, "statepatch.squirrel")),
829 [](bool value) { return eve::Value(value); });
831 eve::Result<bool>::success(view->removeExpected(subject, key, expectedJson)),
832 [](bool result) { return eve::Value(result); });
833 });
834 ownedBatch.addFunc("clear", [](ScriptStateBatch* value) {
835 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
836 if (view.isBound()) view->clear();
837 });
838 ownedBatch.addFunc("size", [](ScriptStateBatch* value) {
839 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
840 return view.isBound() ? view->size() : 0;
841 });
842 ownedBatch.addFunc("result", [](ScriptStateBatch* value) -> PatchResult* {
843 auto view = value ? StatePatch::resolveBatch(value->reference) : eve::script::Borrowed<PatchBatch>();
844 return view.isBound() ? const_cast<PatchResult*>(&view->result()) : nullptr;
845 });
846
847 auto store = table.addClass<Store>("StateStore", std::function<Store*()>([] { return nullptr; }), false);
848 store.addFunc("commit", [vm](Store* value, PatchBatch* batch) {
849 if (!value)
852 eve::DiagnosticCode::InvalidArgument, "state store must not be null", "store", {},
853 "statepatch.squirrel")),
854 [](const PatchCommitInfo& info) {
855 return eve::Value(eve::Value::Object{{"changedCount", eve::Value(static_cast<std::int64_t>(info.changedCount))},
856 {"revisionBefore", eve::Value(static_cast<std::int64_t>(info.revisionBefore))},
857 {"revisionAfter", eve::Value(static_cast<std::int64_t>(info.revisionAfter))}});
858 });
860 vm, value->commit(batch), [](const PatchCommitInfo& info) {
861 return eve::Value(eve::Value::Object{{"changedCount", eve::Value(static_cast<std::int64_t>(info.changedCount))},
862 {"revisionBefore", eve::Value(static_cast<std::int64_t>(info.revisionBefore))},
863 {"revisionAfter", eve::Value(static_cast<std::int64_t>(info.revisionAfter))}});
864 });
865 });
866 store.addFunc("has", &Store::has);
867 store.addFunc("get", &Store::get);
868 store.addFunc("valueRevision", [](Store* s, const std::string& subject, const std::string& key) {
869 return s ? static_cast<int64_t>(s->valueRevision(subject, key)) : 0;
870 });
871 store.addFunc("revision", [](Store* s) { return s ? static_cast<int64_t>(s->revision()) : 0; });
872 store.addFunc("querySubjects", &Store::querySubjects);
873 store.addFunc("queryKeys", &Store::queryKeys);
874 store.addFunc("queryAt", &Store::queryAt);
875 store.addFunc("queryDirty", &Store::queryDirty);
876 store.addFunc("dirtySubjectAt", &Store::dirtySubjectAt);
877 store.addFunc("dirtyKeyAt", &Store::dirtyKeyAt);
878 store.addFunc("clearDirty", &Store::clearDirty);
879 store.addFunc("eventCount", &Store::eventCount);
880 store.addFunc("eventAt", [](Store* s, int index) -> ChangeEvent* {
881 return s ? const_cast<ChangeEvent*>(s->eventAt(index)) : nullptr;
882 });
883 store.addFunc("clearEvents", &Store::clearEvents);
884 store.addFunc("snapshotJson", &Store::snapshotJson);
885 store.addFunc("restoreJson", [vm](Store* value, const std::string& json) {
886 if (!value)
889 "state store must not be null", "store", {},
890 "statepatch.squirrel")));
891 return eve::script::projectResult(vm, value->restoreJson(json));
892 });
893
894 auto ownedStore = table.addClass<ScriptStateStore>(
895 "StateStoreProxy", std::function<ScriptStateStore*()>([] { return nullptr; }), true);
896 ownedStore.addFunc("ownership", [](ScriptStateStore*) { return std::string("owned"); });
897 ownedStore.addFunc("ownerEpoch", [](ScriptStateStore* value) {
898 return value ? static_cast<int64_t>(value->reference.ownerEpoch) : int64_t{0};
899 });
900 ownedStore.addFunc("handle", [](ScriptStateStore* value) {
901 return value ? static_cast<int64_t>(value->reference.packed()) : int64_t{0};
902 });
903 ownedStore.addFunc("isStale",
904 [](ScriptStateStore* value) { return !value || StatePatch::isStale(value->reference); });
905 ownedStore.addFunc("release", [vm](ScriptStateStore* value) {
906 if (!value)
909 "owned state store proxy must not be null",
910 "store", {}, "statepatch.squirrel")));
911 return eve::script::projectResult(vm, StatePatch::release(value->reference));
912 });
913 ownedStore.addFunc("commit", [vm](ScriptStateStore* value, ScriptStateBatch* batch) {
914 auto projectInfo = [](const PatchCommitInfo& info) {
915 return eve::Value(eve::Value::Object{{"changedCount", eve::Value(static_cast<std::int64_t>(info.changedCount))},
916 {"revisionBefore", eve::Value(static_cast<std::int64_t>(info.revisionBefore))},
917 {"revisionAfter", eve::Value(static_cast<std::int64_t>(info.revisionAfter))}});
918 };
919 if (!value || !batch || !(batch->reference.store == value->reference))
922 eve::DiagnosticCode::InvalidArgument, "owned state store/batch commit arguments are invalid",
923 "commit", {}, "statepatch.squirrel")),
924 projectInfo);
925 auto store = StatePatch::resolve(value->reference);
926 auto staged = StatePatch::resolveBatch(batch->reference);
927 if (!store.isBound() || !staged.isBound())
930 eve::DiagnosticCode::StaleHandle, "owned state-patch store or batch handle is stale", "commit",
931 {}, "statepatch.squirrel")),
932 projectInfo);
933 return eve::script::projectResult(vm, store->commit(staged.get()), projectInfo);
934 });
935 ownedStore.addFunc("revision", [](ScriptStateStore* value) {
936 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
937 return view.isBound() ? static_cast<int64_t>(view->revision()) : int64_t{0};
938 });
939 ownedStore.addFunc("has", [](ScriptStateStore* value, const std::string& subject, const std::string& key) {
940 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
941 return view.isBound() && view->has(subject, key);
942 });
943 ownedStore.addFunc("get", [](ScriptStateStore* value, const std::string& subject, const std::string& key) {
944 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
945 return view.isBound() ? view->get(subject, key) : std::string{};
946 });
947 ownedStore.addFunc("valueRevision",
948 [](ScriptStateStore* value, const std::string& subject, const std::string& key) {
949 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
950 return view.isBound() ? static_cast<int64_t>(view->valueRevision(subject, key)) : int64_t{0};
951 });
952 ownedStore.addFunc("querySubjects", [](ScriptStateStore* value) {
953 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
954 return view.isBound() ? view->querySubjects() : 0;
955 });
956 ownedStore.addFunc("queryKeys", [](ScriptStateStore* value, const std::string& subject) {
957 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
958 return view.isBound() ? view->queryKeys(subject) : 0;
959 });
960 ownedStore.addFunc("queryAt", [](ScriptStateStore* value, int index) {
961 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
962 return view.isBound() ? view->queryAt(index) : std::string{};
963 });
964 ownedStore.addFunc("queryDirty", [](ScriptStateStore* value) {
965 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
966 return view.isBound() ? view->queryDirty() : 0;
967 });
968 ownedStore.addFunc("dirtySubjectAt", [](ScriptStateStore* value, int index) {
969 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
970 return view.isBound() ? view->dirtySubjectAt(index) : std::string{};
971 });
972 ownedStore.addFunc("dirtyKeyAt", [](ScriptStateStore* value, int index) {
973 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
974 return view.isBound() ? view->dirtyKeyAt(index) : std::string{};
975 });
976 ownedStore.addFunc("clearDirty", [](ScriptStateStore* value) {
977 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
978 if (view.isBound()) view->clearDirty();
979 });
980 ownedStore.addFunc("eventCount", [](ScriptStateStore* value) {
981 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
982 return view.isBound() ? view->eventCount() : 0;
983 });
984 ownedStore.addFunc("eventAt", [](ScriptStateStore* value, int index) -> ChangeEvent* {
985 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
986 return view.isBound() ? const_cast<ChangeEvent*>(view->eventAt(index)) : nullptr;
987 });
988 ownedStore.addFunc("clearEvents", [](ScriptStateStore* value) {
989 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
990 if (view.isBound()) view->clearEvents();
991 });
992 ownedStore.addFunc("snapshotJson", [](ScriptStateStore* value) {
993 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
994 return view.isBound() ? view->snapshotJson() : std::string{};
995 });
996 ownedStore.addFunc("restoreJson", [vm](ScriptStateStore* value, const std::string& json) {
997 auto view = value ? StatePatch::resolve(value->reference) : eve::script::Borrowed<Store>();
998 if (!view.isBound())
1001 "owned state-patch store handle is stale",
1002 "store", {}, "statepatch.squirrel")));
1003 return eve::script::projectResult(vm, view->restoreJson(json));
1004 });
1005 ownedStore.addFunc("newBatch", [vm](ScriptStateStore* value) -> ssq::Table {
1006 if (!value)
1009 "owned state store proxy must not be null",
1010 "store", {}, "statepatch.squirrel"))
1011 .status());
1012 auto store = StatePatch::resolve(value->reference);
1013 if (!store.isBound())
1016 "owned state-patch store handle is stale",
1017 "store", {}, "statepatch.squirrel"))
1018 .status());
1019 auto batch = store->newBatch();
1020 if (!batch) return eve::script::projectStatusResult(vm, batch.status());
1021 const auto batchRef = std::move(batch).takeValue();
1022 StateBatchHandleRef reference{value->reference, batchRef, batchRef.ownerEpoch};
1023 return makeOwnedProxy<StateBatchHandleRef, ScriptStateBatch>(
1025 [](StateBatchHandleRef ref) { return StatePatch::releaseBatch(ref); });
1026 });
1027
1028 auto cls = table.addClass(name, StatePatch::create, false);
1029 expose(cls);
1030}
1031
1032void StatePatch::expose(ssq::Class& cls) {
1033 cls.addFunc("getName", &StatePatch::getName);
1034 cls.addFunc("newStore", [vm = cls.getHandle()](StatePatch*) -> ssq::Table {
1035 return makeOwnedProxy<StateStoreHandleRef, ScriptStateStore>(
1036 vm, StatePatch::newStore(), [](StateStoreHandleRef ref) { return StatePatch::release(ref); });
1037 });
1038}
1039
1040} // namespace eve::statepatch
ActionParameterOperation operation
Value::Object payload
int root
Definition AnimSmr.cpp:119
int subject
Definition AnimSmr.cpp:163
std::string output
ActiveSource owned
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
const std::string & s
std::unordered_map< std::string, QuestRuntime > entries
struct SQVM * HSQUIRRELVM
bool committed
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
int instanceId
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
DiagnosticCode code
wgpu::PopErrorScopeStatus status
double r
HexVec3 left
HexVec3 right
std::int32_t second
std::int32_t first
char quote
Poco::JSON::Object::Ptr result
Snapshot snapshot
bool exists
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
OceanSprayView view
std::string error
Definition Package.cpp:174
bool dirty
std::string script
Definition PlayHost.cpp:117
std::set< std::string > values
Object::Ptr value
bool found
int created
int removed
ScriptStructure out
std::string_view source
The single Squirrel projection for common Result, Status and Value.
std::string_view adapter
Consumer-owned query and mutation contracts for authoritative world state.
Json object
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.
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
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
One directed payload migration step.
Definition Snapshot.h:145
Result< void > add(LogicalId schema, SchemaVersion from, SchemaVersion to, Migration migration)
Register one schema-local migration edge.
Definition Snapshot.cpp:196
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
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
std::map< std::string, Value > Object
Definition Value.h:34
Id128 public API.
Definition Identity.h:111
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
Non-owning observation of a registry-owned object.
All-or-nothing mutation boundary owned by the consumer.
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
void clear()
Removes every operation and resets the latest result.
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.
bool set(const std::string &subject, const std::string &key, const std::string &jsonValue)
Appends an unconditional set operation.
bool remove(const std::string &subject, const std::string &key)
Appends an unconditional remove operation.
const PatchResult & result() const
Returns the result of the most recent commit attempt.
int size() const
Returns the number of queued operations.
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.
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.
static eve::script::Borrowed< PatchBatch > resolveBatch(StateBatchHandleRef reference) noexcept
Resolves a store-qualified batch as a non-owning observation.
static bool isBatchStale(StateBatchHandleRef reference) noexcept
Reports whether a store-qualified batch reference is stale.
static eve::Result< void > release(StateStoreHandleRef reference)
Releases a module-owned state store.
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.
eve::Result< void > releaseBatch(PatchBatchHandleRef reference)
Releases a store-owned patch batch.
eve::Result< PatchCommitInfo > commit(PatchBatch *batch)
Validates and atomically commits a batch.
eve::Result< void > restoreJson(const std::string &json)
Transactionally restores a snapshot produced by snapshotJson().
eve::script::Borrowed< PatchBatch > resolveBatch(PatchBatchHandleRef reference) noexcept
Resolves a live batch as a non-owning observation.
Store(eve::PersistentId instanceId={})
Creates an empty store with an optional persistent identity.
bool isBatchStale(PatchBatchHandleRef reference) const noexcept
Reports whether a batch reference is stale for this Store.
eve::Result< PatchBatchHandleRef > newBatch()
Allocates a store-owned empty patch batch and returns its handle.
Immutable context shared by every participant of one transaction.
Definition Transaction.h:31
void keys(const Value &value, std::initializer_list< const char * > names)
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
V3 normalize(V3 a)
Module-private road bake implementation helper.
Definition RoadBake.cpp:31
ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result< Ref > &&reference, Release &&release)
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
eve::script::RuntimeHandleRef< StateStoreHandleTag > StateStoreHandleRef
Generation- and module-epoch-qualified state store reference.
Definition StatePatch.h:28
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
std::vector< DiagnosticDetail > DiagnosticDetails
Owning collection of diagnostic details with stable insertion order.
Definition Diagnostic.h:88
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Result< void > validateSnapshotPayloadMetadata(const Value &payload, Revision revision, SimulationTick tick)
Validate optional payload copies of envelope revision and tick.
Definition Snapshot.cpp:80
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
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
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
std::vector< PatchError > errors
Definition StatePatch.h:92
A patch batch reference qualified by both its owning Store and batch slot.
Definition StatePatch.h:41
glm::uvec4 info