载入中...
搜索中...
未找到
Settlement.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <cmath>
5#include <exception>
6#include <limits>
7#include <memory>
8#include <utility>
9#include "common/Profile.h"
10
11namespace eve::settlement {
12namespace {
13
16}
17
18eve::Result<void> validateFiniteNonNegative(double value, std::string_view name) {
19 if (!std::isfinite(value) || value < 0.0)
21 std::string(name) + " must be finite and non-negative",
22 std::string(name)));
24}
25
26bool isTerminalDisposition(SettlementDisposition disposition) noexcept {
27 switch (disposition) {
35 }
36 return true;
37}
38
39} // namespace
40
42 if (!request.target.isValid())
44 eve::DiagnosticCode::InvalidArgument, "settlement target must be a valid SubjectRef", "target"));
45 if (request.kind.empty())
47 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "settlement kind must not be empty", "kind"));
48
49 auto magnitude = validateFiniteNonNegative(request.magnitude, "magnitude");
50 if (!magnitude) {
51 const auto status = magnitude.status();
53 }
54 if (!request.causation.isCanonical())
57 "settlement causation must use a canonical event or command id", "causation"));
58 if (!request.correlation.isCanonical())
60 eve::DiagnosticCode::InvalidArgument, "settlement correlation must use a canonical id", "correlation"));
61 for (std::size_t index = 0; index < request.decisions.size(); ++index) {
62 const auto& decision = request.decisions[index];
63 const auto path = "decisions[" + std::to_string(index) + "]";
64 if (!decision.stream.isValid())
67 "settlement random decision stream must be a valid LogicalId", path + ".stream"));
68 if (decision.sequence > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))
71 "settlement random decision sequence exceeds the event encoding range", path + ".sequence"));
72 if (!std::isfinite(decision.sample) || decision.sample < 0.0 || decision.sample > 1.0)
74 eve::DiagnosticCode::InvalidArgument, "settlement random decision sample must be in [0,1]",
75 path + ".sample"));
76 if (!std::isfinite(decision.threshold) || decision.threshold < 0.0 || decision.threshold > 1.0)
78 eve::DiagnosticCode::InvalidArgument, "settlement random decision threshold must be in [0,1]",
79 path + ".threshold"));
80 for (std::size_t previous = 0; previous < index; ++previous)
81 if (request.decisions[previous].stream == decision.stream &&
82 request.decisions[previous].sequence == decision.sequence)
85 "settlement random decision stream and sequence must be unique", path + ".sequence"));
86 }
87 if (request.chain.depth == 0) {
88 if (!request.trigger.empty() || request.chain.emittedCount != 0 || !request.chain.triggerPath.empty())
91 "root settlement requests must not contain derived-chain metadata", "chain"));
92 } else {
93 if (request.trigger.empty())
96 "derived settlement requests require a non-empty trigger key", "trigger"));
97 if (request.chain.triggerPath.size() != request.chain.depth || request.chain.triggerPath.back() != request.trigger)
100 "derived settlement trigger path must match its depth and current trigger", "chain"));
101 if (request.chain.emittedCount == 0)
104 "derived settlement requests require a positive emitted count", "chain.emittedCount"));
105 }
107}
108
109namespace {
110
111const char* traceLevelName(SettlementTraceLevel level) noexcept {
112 switch (level) {
113 case SettlementTraceLevel::Off: return "off";
114 case SettlementTraceLevel::Summary: return "summary";
115 case SettlementTraceLevel::Full: return "full";
116 }
117 return "unknown";
118}
119
120eve::Result<void> validateFrame(const SettlementContext& context) {
121 auto magnitude = validateFiniteNonNegative(context.magnitude(), "working magnitude");
122 if (!magnitude) {
123 const auto status = magnitude.status();
125 }
126 auto absorbed = validateFiniteNonNegative(context.projectedResult().absorbed, "absorbed");
127 if (!absorbed) {
128 const auto status = absorbed.status();
130 }
131 auto resisted = validateFiniteNonNegative(context.projectedResult().resisted, "resisted");
132 if (!resisted) {
133 const auto status = resisted.status();
135 }
137}
138
139eve::Diagnostic stageDiagnostic(std::string_view stage, const eve::Status& status) {
141 details.emplace_back("stage", std::string(stage));
142 details.emplace_back("status", std::string(eve::statusCodeName(status.code())));
144 "settlement stage failed: " + std::string(stage),
145 "settlement.stage." + std::string(stage), details);
146}
147
148eve::Status stageFailureStatus(std::string_view stage, const eve::Status& status) {
149 auto diagnostics = status.diagnostics();
150 diagnostics.emplace_back(stageDiagnostic(stage, status));
151 return eve::Status(status.code(), std::move(diagnostics));
152}
153
154eve::Result<game_event::GameEvent> makeEvent(const SettlementContext& context) {
155 const auto& request = context.request();
156 const auto& result = context.projectedResult();
157
158 auto schema = eve::LogicalId::parse("settlement:result");
159 if (!schema)
162 "settlement result schema id is not a valid LogicalId", "event.schemaId"));
163
165 payload["kind"] = request.kind;
166 payload["resource"] = request.resource;
167 payload["requested"] = result.requested;
168 payload["applied"] = result.applied;
169 payload["absorbed"] = result.absorbed;
170 payload["resisted"] = result.resisted;
171 payload["clamped"] = result.clamped;
172 payload["critical"] = result.critical;
173 payload["disposition"] = settlementDispositionName(result.disposition);
174 payload["tick"] = static_cast<std::int64_t>(result.tick.value());
175 payload["context"] = request.context;
176
178 tags.reserve(request.tags.size());
179 for (const auto& tag : request.tags) tags.emplace_back(tag);
180 payload["tags"] = eve::Value(std::move(tags));
181
182 eve::Value::Array decisions;
183 decisions.reserve(request.decisions.size());
184 for (const auto& decision : request.decisions) {
186 value["stream"] = decision.stream.format();
187 value["sequence"] = static_cast<std::int64_t>(decision.sequence);
188 value["sample"] = decision.sample;
189 value["threshold"] = decision.threshold;
190 value["accepted"] = decision.accepted;
191 decisions.emplace_back(std::move(value));
192 }
193 payload["decisions"] = eve::Value(std::move(decisions));
194
195 eve::Value::Array triggerPath;
196 triggerPath.reserve(request.chain.triggerPath.size());
197 for (const auto& trigger : request.chain.triggerPath) triggerPath.emplace_back(trigger);
198 payload["trigger"] = request.trigger;
200 {"depth", eve::Value(static_cast<std::int64_t>(request.chain.depth))},
201 {"emitted_count", eve::Value(static_cast<std::int64_t>(request.chain.emittedCount))},
202 {"trigger_path", eve::Value(std::move(triggerPath))},
203 });
204 payload["trace_level"] = traceLevelName(request.trace);
205
206 eve::Value::Array stages;
207 {
208 EV_PROFILE_MODULE("settlement", "SettlementPipeline::encodeStages");
209 stages.reserve(result.stages.size());
210 for (const auto& stage : result.stages) {
211 eve::Value::Object stageValue;
212 stageValue["name"] = stage.name;
213 stageValue["kind"] = stageKindName(stage.kind);
214 stageValue["status"] = std::string(eve::statusCodeName(stage.status));
215 stageValue["before"] = stage.before;
216 stageValue["after"] = stage.after;
217 stageValue["details"] = stage.details;
218 stages.emplace_back(std::move(stageValue));
219 }
220 }
221 payload["stages"] = eve::Value(std::move(stages));
222
223 auto encoded = [&] {
224 EV_PROFILE_MODULE("settlement", "SettlementPipeline::serializeEvent");
225 return eve::Value(std::move(payload)).toJson();
226 }();
227 if (!encoded) {
228 const auto status = encoded.status();
230 }
231
232 game_event::GameEvent envelope;
233 envelope.type = "settlement.result";
234 envelope.source = request.source.isValid() ? request.source.format() : std::string{};
235 envelope.subject = request.target.format();
236 envelope.causation = request.causation;
237 envelope.correlation = request.correlation;
238 envelope.schemaId = *schema;
239 envelope.schemaVersion = eve::SchemaVersion(1);
240 envelope.tick = request.tick;
241 envelope.flags = result.critical ? 1u : 0u;
242 envelope.payload = std::move(encoded).takeValue();
243 return eve::Result<game_event::GameEvent>::success(std::move(envelope));
244}
245
246} // namespace
247
248const char* stageKindName(StageKind kind) noexcept {
249 switch (kind) {
250 case StageKind::Validate: return "validate";
251 case StageKind::Decision: return "decision";
252 case StageKind::SourceModifiers: return "source_modifiers";
253 case StageKind::TargetMitigation: return "target_mitigation";
254 case StageKind::ArmorShield: return "armor_shield";
255 case StageKind::Clamp: return "clamp";
256 case StageKind::Apply: return "apply";
257 case StageKind::Event: return "event";
258 case StageKind::Trigger: return "trigger";
259 }
260 return "unknown";
261}
262
263const char* settlementDispositionName(SettlementDisposition disposition) noexcept {
264 switch (disposition) {
265 case SettlementDisposition::Applied: return "applied";
266 case SettlementDisposition::NoOp: return "no_op";
267 case SettlementDisposition::Immune: return "immune";
268 case SettlementDisposition::Resisted: return "resisted";
269 case SettlementDisposition::PartiallyApplied: return "partially_applied";
270 case SettlementDisposition::Blocked: return "blocked";
271 case SettlementDisposition::InvalidTarget: return "invalid_target";
272 }
273 return "unknown";
274}
275
276bool SettlementResult::hasStage(std::string_view name) const noexcept { return stage(name) != nullptr; }
277
278std::size_t SettlementResult::ruleEvaluationCount() const noexcept {
279 return static_cast<std::size_t>(std::count_if(stages.begin(), stages.end(), [](const auto& stage) {
280 return stage.name.starts_with("zz_rule.");
281 }));
282}
283
284std::size_t SettlementResult::ruleMatchCount() const noexcept {
285 return static_cast<std::size_t>(std::count_if(stages.begin(), stages.end(), [](const auto& stage) {
286 return stage.name.starts_with("zz_rule.") && stage.status == eve::StatusCode::Applied;
287 }));
288}
289
290const SettlementStageResult* SettlementResult::stage(std::string_view name) const noexcept {
291 const auto it = std::find_if(stages.begin(), stages.end(), [&](const auto& value) { return value.name == name; });
292 return it == stages.end() ? nullptr : &*it;
293}
294
296 : commit_(std::move(commit)), rollback_(std::move(rollback)) {}
297
299 : commit_(std::move(other.commit_)),
300 rollback_(std::move(other.rollback_)),
301 committed_(other.committed_),
302 rolledBack_(other.rolledBack_) {
303 other.commit_ = {};
304 other.rollback_ = {};
305 other.committed_ = true;
306 other.rolledBack_ = true;
307}
308
310 if (this == &other) return *this;
311 rollback();
312 commit_ = std::move(other.commit_);
313 rollback_ = std::move(other.rollback_);
314 committed_ = other.committed_;
315 rolledBack_ = other.rolledBack_;
316 other.commit_ = {};
317 other.rollback_ = {};
318 other.committed_ = true;
319 other.rolledBack_ = true;
320 return *this;
321}
322
324 // A successful commit remains published. The pipeline invokes rollback
325 // explicitly only when a later event append fails.
326 if (!committed_) rollback();
327}
328
329bool PreparedApply::isValid() const noexcept {
330 return static_cast<bool>(commit_) && static_cast<bool>(rollback_) && !rolledBack_;
331}
332
334 if (committed_) return success(eve::StatusCode::Applied);
335 if (!isValid())
337 eve::DiagnosticCode::InvariantViolation, "settlement mutation is empty or already rolled back", "apply"));
338
339 try {
340 auto outcome = commit_();
341 const bool passed = outcome.ok();
342 if (passed) {
343 committed_ = true;
344 return outcome;
345 }
346 const auto status = outcome.status();
348 } catch (const std::exception& exception) {
350 eve::DiagnosticCode::Failed, std::string("settlement apply commit threw: ") + exception.what(), "apply"));
351 } catch (...) {
353 eve::DiagnosticCode::Failed, "settlement apply commit threw an unknown exception", "apply"));
354 }
355}
356
357void PreparedApply::rollback() noexcept {
358 if (rolledBack_ || !rollback_) return;
359 try {
360 rollback_();
361 } catch (...) {
362 // A rollback exception would make the public failure contract false:
363 // the caller could observe a failure while domain state remained
364 // partially applied. There is no safe recovery path from noexcept
365 // rollback (including the destructor path), so fail closed.
366 std::terminate();
367 }
368 rolledBack_ = true;
369}
370
371SettlementContext::SettlementContext(const SettlementRequest& request, SettlementResult& result,
372 ISettlementPolicy& policy)
373 : request_(request), result_(result), policy_(policy), magnitude_(request.magnitude) {}
374
376 if (applyPrepared_) {
377 recordMutationViolation("settlement magnitude cannot change after apply preparation", "magnitude");
379 eve::DiagnosticCode::Conflict, "settlement magnitude is frozen after apply preparation", "magnitude"));
380 }
381 auto valid = validateFiniteNonNegative(value, "working magnitude");
382 if (!valid) {
383 const auto status = valid.status();
385 }
386 magnitude_ = isTerminalDisposition(disposition_) ? 0.0 : value;
388}
389
391 if (applyPrepared_) {
392 recordMutationViolation("settlement absorbed amount cannot change after apply preparation", "absorbed");
394 eve::DiagnosticCode::Conflict, "settlement absorbed amount is frozen after apply preparation", "absorbed"));
395 }
396 auto valid = validateFiniteNonNegative(value, "absorbed amount");
397 if (!valid) {
398 const auto status = valid.status();
400 }
401 if (value > std::numeric_limits<double>::max() - absorbed_)
403 eve::Diagnostic::error(eve::DiagnosticCode::InvariantViolation, "absorbed amount overflowed", "absorbed"));
404 absorbed_ += value;
406}
407
409 if (applyPrepared_) {
410 recordMutationViolation("settlement resisted amount cannot change after apply preparation", "resisted");
412 eve::DiagnosticCode::Conflict, "settlement resisted amount is frozen after apply preparation", "resisted"));
413 }
414 auto valid = validateFiniteNonNegative(value, "resisted amount");
415 if (!valid) {
416 const auto status = valid.status();
418 }
419 if (value > std::numeric_limits<double>::max() - resisted_)
421 eve::Diagnostic::error(eve::DiagnosticCode::InvariantViolation, "resisted amount overflowed", "resisted"));
422 resisted_ += value;
424}
425
427 if (applyPrepared_) {
428 recordMutationViolation("settlement clamped amount cannot change after apply preparation", "clamped");
430 eve::DiagnosticCode::Conflict, "settlement clamped amount is frozen after apply preparation", "clamped"));
431 }
432 auto valid = validateFiniteNonNegative(value, "clamped amount");
433 if (!valid) {
434 const auto status = valid.status();
436 }
437 if (value > std::numeric_limits<double>::max() - clamped_)
439 eve::Diagnostic::error(eve::DiagnosticCode::InvariantViolation, "clamped amount overflowed", "clamped"));
440 clamped_ += value;
442}
443
445 if (applyPrepared_) {
446 recordMutationViolation("settlement disposition cannot change after apply preparation", "disposition");
448 eve::DiagnosticCode::Conflict, "settlement disposition is frozen after apply preparation",
449 "disposition"));
450 }
451 disposition_ = disposition;
452 dispositionExplicit_ = true;
453 switch (disposition) {
457 case SettlementDisposition::InvalidTarget: magnitude_ = 0.0; break;
461 }
463}
464
466 if (applyPrepared_) {
467 recordMutationViolation("settlement clamp cannot change after apply preparation", "clamp");
469 eve::DiagnosticCode::Conflict, "settlement clamp is frozen after apply preparation", "clamp"));
470 }
471 if (value) {
472 auto valid = validateFiniteNonNegative(*value, "clamp maximum");
473 if (!valid) {
474 const auto status = valid.status();
476 }
477 }
478 clampMax_ = value;
480}
481
483 if (key.empty()) return;
484 if (request_.trace != SettlementTraceLevel::Full) return;
485 if (eventPrepared_) {
486 recordMutationViolation("settlement stage details cannot change after event preparation", "stage.details");
487 return;
488 }
489 stageDetails_[std::move(key)] = std::move(value);
490}
491
493 double next = std::max(0.0, magnitude_);
494 if (clampMax_) next = std::min(next, *clampMax_);
495 const double lost = magnitude_ - next;
496 if (lost > 0.0) {
497 auto recorded = addClamped(lost);
498 if (!recorded) {
499 const auto status = recorded.status();
501 }
502 }
503 magnitude_ = next;
505}
506
508 if (applyPrepared_)
510 eve::DiagnosticCode::Conflict, "settlement apply preparation may run only once", "apply"));
511 auto prepared = policy().prepareApply(*this);
512 const bool preparedOk = prepared.ok();
513 if (!preparedOk) {
514 const auto status = prepared.status();
516 }
517 auto mutation = std::move(prepared).takeValue();
518 if (!mutation.isValid())
520 eve::DiagnosticCode::InvariantViolation, "settlement policy returned an invalid mutation", "apply"));
521 pendingApply_.emplace(std::move(mutation));
522 applyPrepared_ = true;
524}
525
527 if (eventPrepared_)
529 eve::DiagnosticCode::Conflict, "settlement event preparation may run only once", "event"));
531 auto event = makeEvent(*this);
532 const bool eventOk = event.ok();
533 if (!eventOk) {
534 const auto status = event.status();
536 }
537 pendingEvent_.emplace(std::move(event).takeValue());
538 eventPrepared_ = true;
540}
541
543 result_.applied = magnitude_;
544 result_.absorbed = absorbed_;
545 result_.resisted = resisted_;
546 result_.clamped = clamped_;
547 result_.critical = critical_;
548 if (dispositionExplicit_) {
549 result_.disposition = disposition_;
550 } else if (magnitude_ > 0.0 && (absorbed_ > 0.0 || resisted_ > 0.0 || clamped_ > 0.0)) {
552 } else if (magnitude_ > 0.0) {
554 } else if (resisted_ > 0.0) {
556 } else if (absorbed_ > 0.0) {
558 } else {
560 }
561}
562
564 if (request.trigger.empty())
567 "derived settlement request requires a non-empty trigger key", "derived.trigger"));
568 if (request.chain.depth != 0 || request.chain.emittedCount != 0 || !request.chain.triggerPath.empty())
571 "derived settlement request must not pre-populate chain metadata", "derived.chain"));
572 result_.derived.push_back(std::move(request));
574}
575
576void SettlementContext::recordMutationViolation(std::string message, std::string path) noexcept {
577 if (mutationViolation_) return;
578 try {
579 mutationViolation_.emplace(
581 } catch (...) {
582 // A late mutation is a contract violation. If recording its
583 // diagnostic itself cannot allocate, fail closed instead of allowing
584 // a possibly stale successful result to escape.
585 std::terminate();
586 }
587}
588
590
595
597 auto install = [&](StageKind kind, const char* name, StageFunction function, bool terminal = false) {
598 const int priority = terminal ? 0 : std::numeric_limits<int>::min();
599 stages_.push_back(StageEntry{kind, name, priority, nextRegistration_++, true, terminal, std::move(function)});
600 };
601
602 install(StageKind::Validate, "validate", [](SettlementContext& context) {
603 auto generic = validateSettlementRequest(context.request());
604 const bool genericOk = generic.ok();
605 if (!genericOk) {
606 const auto status = generic.status();
608 }
609 return context.policy().validate(context);
610 });
611 install(StageKind::Decision, "decision",
612 [](SettlementContext& context) { return context.policy().decide(context); });
613 install(StageKind::SourceModifiers, "source_modifiers",
614 [](SettlementContext& context) { return context.policy().sourceModifiers(context); });
615 install(StageKind::TargetMitigation, "target_mitigation",
616 [](SettlementContext& context) { return context.policy().targetMitigation(context); });
617 install(StageKind::ArmorShield, "armor_shield",
618 [](SettlementContext& context) { return context.policy().armorShield(context); });
619 install(
620 StageKind::Clamp, "clamp",
622 auto configured = context.policy().clamp(context);
623 const bool configuredOk = configured.ok();
624 if (!configuredOk) {
625 const auto status = configured.status();
627 }
628 return context.applyClamp();
629 },
630 true);
631 install(
632 StageKind::Apply, "apply",
634 context.synchronizeResult();
635 return context.prepareApply();
636 },
637 true);
638 install(
639 StageKind::Trigger, "trigger",
641 context.synchronizeResult();
642 auto derived = context.policy().prepareTrigger(context, context.projectedResult());
643 if (!derived) return eve::Result<void>::failure(derived.status());
644 for (auto& request : std::move(derived).takeValue()) {
645 auto emitted = context.emitDerived(std::move(request));
646 if (!emitted) return emitted;
647 }
648 return eve::Result<void>::success(context.result_.derived.empty()
651 },
652 true);
653 install(StageKind::Event, "event", [](SettlementContext& context) { return context.prepareEvent(); }, true);
654}
655
657 if (name.empty())
659 eve::DiagnosticCode::InvalidArgument, "settlement stage name must not be empty", "stage.name"));
660 if (!function)
662 eve::DiagnosticCode::InvalidArgument, "settlement stage function must not be empty", "stage.function"));
663 const auto duplicate =
664 std::find_if(stages_.begin(), stages_.end(), [&](const auto& stage) { return stage.name == name; });
665 if (duplicate != stages_.end())
667 eve::DiagnosticCode::AlreadyExists, "settlement stage name is already registered", "stage.name"));
668 if (nextRegistration_ == std::numeric_limits<std::uint64_t>::max())
670 eve::DiagnosticCode::InvariantViolation, "settlement stage registration sequence exhausted", "stage"));
671 stages_.push_back(StageEntry{kind, std::move(name), priority, nextRegistration_++, false, false,
672 std::move(function)});
674}
675
676eve::Result<void> SettlementPipeline::prepare(SettlementContext& context, SettlementResult& result) const {
677 EV_PROFILE_MODULE("settlement", "SettlementPipeline::prepare");
678 if (context.request().trace != SettlementTraceLevel::Off) result.stages.reserve(stages_.size());
679 std::vector<const StageEntry*> ordered;
680 {
681 EV_PROFILE_MODULE("settlement", "SettlementPipeline::orderStages");
682 ordered.reserve(stages_.size());
683 for (const auto& stage : stages_) ordered.push_back(&stage);
684 std::sort(ordered.begin(), ordered.end(), [](const auto* left, const auto* right) {
685 const auto leftKind = static_cast<std::uint8_t>(left->kind);
686 const auto rightKind = static_cast<std::uint8_t>(right->kind);
687 if (leftKind != rightKind) return leftKind < rightKind;
688 // Terminal preparation is an unregistrable phase boundary. It must
689 // sort after every custom stage in the same phase, even when a custom
690 // stage deliberately uses a larger priority or a lexicographically
691 // later name.
692 if (left->terminal != right->terminal) return !left->terminal && right->terminal;
693 if (left->canonical != right->canonical) return left->canonical && !right->canonical;
694 if (left->priority != right->priority) return left->priority < right->priority;
695 if (left->name != right->name) return left->name < right->name;
696 return left->registration < right->registration;
697 });
698 }
699
700 auto rollback = [&]() noexcept {
701 if (auto* pending = context.pendingApply()) pending->rollback();
702 };
703
704 for (const StageEntry* entry : ordered) {
705 context.beginStage();
706 const double before = context.magnitude();
707 auto outcome = entry->function(context);
708 const bool outcomeOk = outcome.ok();
709 const auto outcomeStatus = outcome.status();
710
711 context.synchronizeResult();
712 auto frame = validateFrame(context);
713 const bool frameOk = frame.ok();
714 const auto frameStatus = frame.status();
715 const auto* violation = context.mutationViolation();
716 const bool violationPresent = violation != nullptr;
717 const eve::Status violationStatus =
718 violationPresent ? eve::Status::failure(*violation) : eve::Status::success();
719
720 if (context.request().trace != SettlementTraceLevel::Off) {
721 EV_PROFILE_MODULE("settlement", "SettlementPipeline::recordStage");
722 SettlementStageResult stageResult;
723 stageResult.kind = entry->kind;
724 stageResult.name = entry->name;
725 stageResult.status = !outcomeOk ? outcomeStatus.code()
726 : !frameOk ? frameStatus.code()
727 : violationPresent ? violationStatus.code()
728 : outcomeStatus.code();
729 stageResult.before = before;
730 stageResult.after = context.magnitude();
731 stageResult.details = Value(context.stageDetails());
732 result.stages.push_back(std::move(stageResult));
733 }
734
735 if (!outcomeOk) {
736 rollback();
737 return eve::Result<void>::failure(stageFailureStatus(entry->name, outcomeStatus));
738 }
739 if (!frameOk) {
740 rollback();
741 return eve::Result<void>::failure(stageFailureStatus(entry->name, frameStatus));
742 }
743 if (violationPresent) {
744 rollback();
745 return eve::Result<void>::failure(stageFailureStatus(entry->name, violationStatus));
746 }
747 }
748
749 context.synchronizeResult();
750 if (context.pendingApply() == nullptr)
752 eve::DiagnosticCode::InvariantViolation, "settlement pipeline did not prepare an apply mutation",
753 "apply"));
755}
756
760 result.requested = request.magnitude;
761 result.tick = request.tick;
763
764 auto prepared = prepare(context, result);
765 if (!prepared) return eve::Result<SettlementResult>::failure(prepared.status());
766
767 auto rollback = [&]() noexcept {
768 if (auto* pending = context.pendingApply()) pending->rollback();
769 };
770 auto* pending = context.pendingApply();
771
772 auto committed = pending->commit();
773 const bool committedOk = committed.ok();
774 if (!committedOk) {
775 const auto status = committed.status();
776 rollback();
778 }
779
780 if (const auto* preparedEvent = context.pendingEvent()) {
781 game_event::GameEvent envelope = *preparedEvent;
782 result.event = envelope;
783 if (events != nullptr) {
784 try {
785 auto appended = events->append(envelope);
786 const bool appendedOk = appended.ok();
787 if (!appendedOk) {
788 const auto status = appended.status();
789 rollback();
791 }
792 const auto sequence = std::move(appended).takeValue();
793 envelope.sequence = sequence;
794 if (const auto* stored = events->find(sequence)) {
795 result.event = *stored;
796 } else {
797 result.event = envelope;
798 }
799 } catch (const std::exception& exception) {
800 rollback();
803 std::string("settlement result event append threw: ") + exception.what(), "event"));
804 } catch (...) {
805 rollback();
807 eve::DiagnosticCode::Failed, "settlement result event append threw an unknown exception", "event"));
808 }
809 }
810 }
811
812 const auto status = result.applied == 0.0 ? eve::StatusCode::NoOp : eve::StatusCode::Applied;
814}
815
816} // namespace eve::settlement
Value::Object payload
std::vector< QuestEvent > pending
int priority
bool committed
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
bool passed
std::vector< std::uint8_t > stored
Definition Evpack.cpp:171
std::string message
DiagnosticCode code
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
float u
Definition Grass.cpp:233
HexVec3 left
HexVec3 right
bool ordered
Poco::JSON::Object::Ptr result
bool valid
std::unordered_set< std::string > tags
int level
const std::string * tag
ssq::Object frame
std::shared_ptr< const OceanSprayFrame > previous
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
std::vector< particles::ParticleRecordEvent > events
std::string path
Definition PlayHost.cpp:111
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
Object::Ptr value
MigrationFunction function
std::string kind
uint32_t index
const VegetationPresetContext & context
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
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
StatusCode code() const noexcept
Stable operation outcome.
Definition Status.h:102
const std::vector< Diagnostic > & diagnostics() const noexcept
All diagnostics in stable insertion order.
Definition Status.h:128
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
Result< std::string > toJson() const
Serialize this value as deterministic compact JSON.
Definition Value.cpp:187
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
Deterministic in-memory stream of topic-neutral event envelopes.
Definition GameEvent.h:262
Domain-owned policy hooks used by the common settlement pipeline.
Definition Settlement.h:497
virtual eve::Result< std::vector< SettlementRequest > > prepareTrigger(const SettlementContext &context, const SettlementResult &result)
Produce owning derived requests without mutating domain state.
virtual eve::Result< void > decide(SettlementContext &context)
Resolve deterministic hit, immunity, block or other supplied decisions.
virtual eve::Result< PreparedApply > prepareApply(const SettlementContext &context)=0
Build an atomic candidate mutation without publishing it.
Prepared domain mutation used to make settlement application atomic.
Definition Settlement.h:281
std::function< eve::Result< void >()> CommitFunction
Definition Settlement.h:283
PreparedApply & operator=(const PreparedApply &)=delete
void rollback() noexcept
Restore or discard the staged candidate; safe to call repeatedly.
bool isValid() const noexcept
Return whether both transaction callbacks are available.
PreparedApply()=default
Construct an empty invalid mutation.
eve::Result< void > commit()
Publish the staged candidate; failure must leave state unchanged.
std::function< void()> RollbackFunction
Definition Settlement.h:284
Mutable calculation frame visible to policy and custom stage code.
Definition Settlement.h:338
SettlementDisposition disposition() const noexcept
Return the current semantic outcome.
Definition Settlement.h:391
eve::Result< void > addAbsorbed(double value)
Add an amount absorbed by a barrier or shield; late writes are rejected.
void setStageDetail(std::string key, Value value)
Attach one serializable explanation field to the current stage.
const SettlementRequest & request() const noexcept
Return the immutable request currently being settled.
Definition Settlement.h:341
eve::Result< void > setDisposition(SettlementDisposition disposition)
Set an explicit semantic outcome during calculation.
eve::Result< void > setClampMax(std::optional< double > value)
Set or clear the maximum amount used by the generic clamp stage.
eve::Result< void > emitDerived(SettlementRequest request)
Append one owning derived request during the Trigger phase.
eve::Result< void > prepareEvent()
Build the canonical GameEvent without appending it.
eve::Result< void > addClamped(double value)
Add an amount removed by the final clamp stage; late writes are rejected.
void synchronizeResult() noexcept
Copy the current frame counters into SettlementResult.
eve::Result< void > addResisted(double value)
Add an amount removed by target mitigation; late writes are rejected.
ISettlementPolicy & policy() const noexcept
Return the policy participating in this synchronous call.
Definition Settlement.h:344
eve::Result< void > applyClamp()
Apply the adapter-configured max bound and record any clamp loss.
eve::Result< void > setMagnitude(double value)
Set the current amount; late writes after Apply are rejected.
eve::Result< void > prepareApply()
Prepare the adapter mutation without publishing domain state.
std::function< eve::Result< void >(SettlementContext &)> StageFunction
Definition Settlement.h:544
eve::Result< void > addStage(StageKind kind, std::string name, int priority, StageFunction function)
Add one named custom stage; duplicate names are rejected.
eve::Result< SettlementResult > settle(const SettlementRequest &request, ISettlementPolicy &policy, game_event::GameEventLog *events=nullptr) const
Execute one settlement transaction against a domain policy.
SettlementPipeline()
Construct a pipeline with the canonical stages installed.
const char * settlementDispositionName(SettlementDisposition disposition) noexcept
Return the stable lowercase spelling of a settlement disposition.
StageKind
Kind of ordered calculation stage in a settlement pipeline.
Definition Settlement.h:36
const char * stageKindName(StageKind kind) noexcept
Return the stable lowercase spelling of a stage kind.
SettlementTraceLevel
Amount of stage explanation retained by one settlement request.
Definition Settlement.h:60
eve::Result< void > validateSettlementRequest(const SettlementRequest &request)
Validate the canonical semantic invariants of a settlement request.
SettlementDisposition
Semantic outcome of a completed settlement, distinct from its numeric amount.
Definition Settlement.h:49
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
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
constexpr std::string_view statusCodeName(StatusCode code) noexcept
Return the stable protocol spelling of a status code.
Definition Status.h:46
Domain-neutral, deterministic settlement pipeline.
Envelope metadata shared by event domains.
Definition GameEvent.h:184
EventSequence sequence
Sequence assigned by the owning stream; it is never global identity.
Definition GameEvent.h:188
std::vector< std::string > triggerPath
Definition Settlement.h:85
Domain-neutral input to one settlement operation.
Definition Settlement.h:107
std::string trigger
Stable re-entry key for a derived request; empty only for a root request.
Definition Settlement.h:119
SettlementChainContext chain
Definition Settlement.h:120
Complete observable outcome of one successful settlement.
Definition Settlement.h:163
const SettlementStageResult * stage(std::string_view name) const noexcept
Return the first stage explanation with this name, or null.
std::vector< SettlementRequest > derived
Owning derived requests emitted by the policy in deterministic order.
Definition Settlement.h:175
std::size_t ruleEvaluationCount() const noexcept
Count declarative rules evaluated in this retained trace.
std::size_t ruleMatchCount() const noexcept
Count declarative rules whose filter and condition matched.
std::vector< SettlementStageResult > stages
Definition Settlement.h:172
SettlementDisposition disposition
Definition Settlement.h:170
bool hasStage(std::string_view name) const noexcept
Return whether a named stage explanation exists.
Explanation emitted for one executed stage.
Definition Settlement.h:145