载入中...
搜索中...
未找到
AtomicBatch.cpp
浏览该文件的文档.
2#include <map>
3#include <simplesquirrel/simplesquirrel.hpp>
6
7namespace eve::transaction {
8namespace {
9int ownerSlot;
10}
12 std::vector<std::unique_ptr<ITransactionParticipant>> effects;
13 std::vector<std::function<Result<void>()>> guards;
14 std::optional<resource::CostSpec> cost;
15 std::shared_ptr<resource::IResourceAccount> accountOwner;
17 std::optional<Status> failure;
18 std::map<std::string, resource::ResourceCost> floors;
19 bool consumed = false;
20 bool executing = false;
21 std::function<std::optional<Value>(std::string_view)> query;
22};
23AtomicBatch::AtomicBatch() : impl_(std::make_unique<Impl>()) {}
26 if (!impl_->failure) impl_->failure = std::move(status);
27 return Result<void>::failure(*impl_->failure);
28}
30 std::function<std::optional<Value>(std::string_view)> query) {
31 if (impl_->consumed || impl_->executing || (impl_->account && impl_->account != &account))
33 DiagnosticCode::Conflict, "batch is consumed or has a different payer", "batch.account")));
34 impl_->account = &account;
35 if (query) impl_->query = std::move(query);
36 if (impl_->failure) return Result<void>::failure(*impl_->failure);
37 return Result<void>::success();
38}
39Result<void> AtomicBatch::bindAccount(std::shared_ptr<resource::IResourceAccount> account,
40 std::function<std::optional<Value>(std::string_view)> query) {
41 if (!account)
42 return reject(
44 auto bound = bindAccount(*account, std::move(query));
45 if (!bound) return bound;
46 impl_->accountOwner = std::move(account);
47 return Result<void>::success();
48}
50 auto value = Value::fromJson(json);
51 if (!value) return Result<resource::CostSpec>::failure(value.status());
52 const auto* object = value.value().getIf<Value::Object>();
53 if (!object)
55 Diagnostic::error(DiagnosticCode::InvalidArgument, "cost must be an object", "cost"));
56 std::vector<resource::ResourceCost> items;
57 for (const auto& [name, amount] : *object) {
58 const auto* integer = amount.getIf<std::int64_t>();
59 if (!integer)
61 Diagnostic::error(DiagnosticCode::InvalidArgument, "cost must be integral", "cost"));
62 auto item = resource::ResourceCost::create(name, *integer);
63 if (!item) return Result<resource::CostSpec>::failure(item.status());
64 items.push_back(std::move(item).takeValue());
65 }
66 return resource::CostSpec::create(std::move(items));
67}
68Result<void> AtomicBatch::guard(std::function<Result<void>()> validate) {
69 if (impl_->consumed || impl_->executing || !validate)
70 return reject(Status::failure(Diagnostic::error(DiagnosticCode::Conflict, "cannot add batch guard", "batch")));
71 if (impl_->failure) return Result<void>::failure(*impl_->failure);
72 impl_->guards.push_back(std::move(validate));
73 return Result<void>::success();
74}
76 if (impl_->consumed || impl_->executing)
77 return reject(Status::failure(Diagnostic::error(DiagnosticCode::Conflict, "batch is consumed", "batch")));
78 if (impl_->failure) return Result<void>::failure(*impl_->failure);
79 if (!floor.resource.isValid() || floor.amount.isZero())
80 return reject(
81 Status::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "invalid resource floor", "batch")));
82 const auto name = std::string(floor.resource.value());
83 const auto found = impl_->floors.find(name);
84 if (found == impl_->floors.end() || found->second.amount.value() < floor.amount.value())
85 impl_->floors.insert_or_assign(name, std::move(floor));
86 return Result<void>::success();
87}
88Result<void> AtomicBatch::add(std::vector<std::unique_ptr<ITransactionParticipant>> effects,
89 std::optional<resource::CostSpec> cost) {
90 if (impl_->consumed || impl_->executing)
91 return reject(Status::failure(Diagnostic::error(DiagnosticCode::Conflict, "batch is consumed", "batch")));
92 if (impl_->failure) return Result<void>::failure(*impl_->failure);
93 for (const auto& effect : effects)
94 if (!effect)
96 Diagnostic::error(DiagnosticCode::InvalidArgument, "batch effect is null", "batch.effects")));
97 if (cost) {
98 auto items = cost->items();
99 if (impl_->cost) items.insert(items.end(), impl_->cost->items().begin(), impl_->cost->items().end());
100 auto merged = resource::CostSpec::create(std::move(items));
101 if (!merged) return reject(merged.status());
102 impl_->cost = std::move(merged).takeValue();
103 }
104 for (auto& effect : effects) impl_->effects.push_back(std::move(effect));
105 return Result<void>::success();
106}
107std::optional<Value> AtomicBatch::resource(std::string_view name) const {
108 if (!impl_->account || impl_->consumed) return std::nullopt;
109 for (const auto& guard : impl_->guards) {
110 auto valid = guard();
111 if (!valid) return std::nullopt;
112 }
113 return impl_->query ? impl_->query(name) : std::nullopt;
114}
116 if (impl_->consumed || impl_->executing)
117 return reject(Status::failure(Diagnostic::error(DiagnosticCode::Conflict, "batch is consumed", "batch")));
118 auto vm = static_cast<HSQUIRRELVM>(handle);
119 const auto top = sq_gettop(vm);
120 sq_push(vm, 2);
121 sq_pushuserpointer(vm, &ownerSlot);
122 if (SQ_FAILED(sq_get(vm, -2))) {
123 sq_settop(vm, top);
124 return reject(
125 Status::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "batch owner slot absent", "batch")));
126 }
127 if (sq_gettype(vm, -1) == OT_NULL) {
128 sq_pop(vm, 1);
129 sq_pushuserpointer(vm, &ownerSlot);
130 sq_newarray(vm, 0);
131 sq_set(vm, -3);
132 sq_pushuserpointer(vm, &ownerSlot);
133 sq_get(vm, -2);
134 }
135 sq_push(vm, 1);
136 if (SQ_FAILED(sq_arrayappend(vm, -2))) {
137 sq_settop(vm, top);
138 return reject(
139 Status::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "cannot retain domain owner", "batch")));
140 }
141 sq_settop(vm, top);
142 return Result<void>::success();
143}
145 if (impl_->consumed || impl_->executing)
147 Diagnostic::error(DiagnosticCode::Conflict, "batch is consumed", "batch"));
148 // Keep condition queries available through prepare, then release all borrowed roots.
149 impl_->executing = true;
150 auto result = [&]() -> Result<TransactionReceipt> {
151 if (impl_->failure) return Result<TransactionReceipt>::failure(*impl_->failure);
152 for (const auto& guard : impl_->guards) {
153 auto valid = guard();
154 if (!valid) return Result<TransactionReceipt>::failure(valid.status());
155 }
156 if (impl_->effects.empty() && !impl_->cost)
158 Diagnostic::error(DiagnosticCode::InvalidArgument, "batch has no effects", "batch"));
159 if (!impl_->floors.empty()) {
160 if (!impl_->account)
162 Diagnostic::error(DiagnosticCode::InvalidArgument, "protected batch has no payer", "batch"));
163 auto items = impl_->cost ? impl_->cost->items() : std::vector<resource::ResourceCost>{};
164 for (const auto& [name, floor] : impl_->floors) items.push_back(floor);
165 auto cost = resource::CostSpec::create(std::move(items));
166 if (!cost) return Result<TransactionReceipt>::failure(cost.status());
167 auto affordable = impl_->account->canAfford(cost.value());
168 if (!affordable) return Result<TransactionReceipt>::failure(affordable.status());
169 if (!affordable.value().isAffordable())
172 "merged payment would consume protected resources", "batch"));
173 }
174 std::vector<ITransactionParticipant*> effects;
175 for (auto& effect : impl_->effects) effects.push_back(effect.get());
176 TransactionContext context("script.atomic");
177 if (impl_->cost) {
178 if (!impl_->account)
180 Diagnostic::error(DiagnosticCode::InvalidArgument, "paid batch has no payer", "batch.account"));
181 return AtomicResourcePayment::execute(context, *impl_->account, *impl_->cost, effects);
182 }
184 }();
185 impl_->consumed = true;
186 impl_->executing = false;
187 impl_->query = {};
188 impl_->effects.clear();
189 impl_->guards.clear();
190 impl_->account = nullptr;
191 impl_->accountOwner.reset();
192 return result;
193}
194namespace script_internal {
195void exposeAtomicBatch(ssq::Table& table, ssq::Class& module) {
196 auto cls = table.addClass("AtomicBatch", ssq::Class::Ctor<AtomicBatch()>(), true);
197 const auto vm = table.getHandle();
198 sq_pushobject(vm, cls.getRaw());
199 sq_pushuserpointer(vm, &ownerSlot);
200 sq_pushnull(vm);
201 sq_newslot(vm, -3, SQFalse);
202 sq_pop(vm, 1);
203 cls.addFunc("commit", [vm](AtomicBatch* batch) {
204 auto result = batch->commit();
205 const auto top = sq_gettop(vm);
206 sq_push(vm, 1);
207 sq_pushuserpointer(vm, &ownerSlot);
208 if (SQ_SUCCEEDED(sq_get(vm, -2)) && sq_gettype(vm, -1) == OT_ARRAY) sq_arrayresize(vm, -1, 0);
209 sq_settop(vm, top);
210 return script::projectResult(vm, std::move(result), [](TransactionReceipt receipt) {
211 return Value(Value::Object{{"transactionId", receipt.transactionId},
212 {"participants", static_cast<std::int64_t>(receipt.participantCount)}});
213 });
214 });
215 module.addFunc("newAtomicBatch", [vm](Transaction*) {
216 const auto top = sq_gettop(vm);
217 sq_pushroottable(vm);
218 sq_pushstring(vm, "eve", -1);
219 if (SQ_FAILED(sq_get(vm, -2))) {
220 sq_settop(vm, top);
221 throw ssq::RuntimeException("eve table is absent");
222 }
223 sq_pushstring(vm, "AtomicBatch", -1);
224 if (SQ_FAILED(sq_get(vm, -2))) {
225 sq_settop(vm, top);
226 throw ssq::RuntimeException("AtomicBatch class is absent");
227 }
228 sq_pushroottable(vm);
229 if (SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue))) {
230 sq_settop(vm, top);
231 throw ssq::RuntimeException("cannot create atomic batch");
232 }
233 ssq::Instance instance(vm);
234 sq_getstackobj(vm, -1, &instance.getRaw());
235 sq_addref(vm, &instance.getRaw());
236 sq_settop(vm, top);
237 return instance;
238 });
239}
240} // namespace script_internal
241} // namespace eve::transaction
Small transaction facade for a resource cost plus one domain effect.
struct SQVM * HSQUIRRELVM
eve::resource::CostSpec cost
eve::resource::IResourceAccount * account
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
wgpu::PopErrorScopeStatus status
Poco::JSON::Object::Ptr result
bool valid
std::unique_ptr< ParticleEffect > effect
PrimitiveHandle handle
Object::Ptr value
bool found
The single Squirrel projection for common Result, Status and Value.
Json object
const VegetationPresetContext & context
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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 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
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
constexpr std::int64_t value() const noexcept
Return the native quantity at an explicit adapter boundary.
constexpr bool isZero() const noexcept
Whether the quantity is zero.
const std::vector< ResourceCost > & items() const noexcept
Return canonical items as a read-only borrowed view.
static eve::Result< CostSpec > create(std::vector< ResourceCost > items)
Validate and canonicalize resource items.
Provider-neutral resource account contract.
const std::string & value() const noexcept
Return the canonical owned spelling.
bool isValid() const noexcept
Whether this id passed the resource-name validation.
Single-use composition of domain participants and one payer's costs. Owns staged participants,...
Definition AtomicBatch.h:19
Result< void > guard(std::function< Result< void >()> validate)
Add a synchronous read-only lifetime/time precondition. Guards run before account access; scripts can...
Result< TransactionReceipt > commit()
Commit all stages once, or roll back/compensate via Coordinator. @cost Linear in stages plus their do...
Result< void > reject(Status status)
Preserve the first admission error and reject further execution.
static Result< resource::CostSpec > parseCost(const std::string &json)
Parse a positive-integer resource cost object at the script boundary.
Result< void > retainScriptOwner(void *vm)
Retain the current native script method's self for staged lifetimes.
Result< void > add(std::vector< std::unique_ptr< ITransactionParticipant > > effects, std::optional< resource::CostSpec > cost={})
Append owning effects and optional cost without executing them. @cost Linear in effect/cost count; st...
~AtomicBatch()
Release uncommitted stages and retained script owners.
std::optional< Value > resource(std::string_view name) const
Query the selected authoritative account for condition evaluation.
AtomicBatch()
Create an empty owner-thread batch.
Result< void > protect(resource::ResourceCost floor)
Preserve a resource floor after the complete merged payment. Multiple contributors combine floors by ...
Result< void > bindAccount(resource::IResourceAccount &account, std::function< std::optional< Value >(std::string_view)> query={})
Select the authoritative payer; a different second payer is rejected. @ownership Borrowed account; na...
static eve::Result< TransactionReceipt > execute(const TransactionContext &context, std::span< ITransactionParticipant * > participants)
Execute already prepared domain participants as one transaction.
Immutable context shared by every participant of one transaction.
Definition Transaction.h:31
SQInteger top
Definition Snapshot.cpp:115
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
void exposeAtomicBatch(ssq::Table &table, ssq::Class &module)
One positive resource and quantity pair in a canonical cost.
static eve::Result< ResourceCost > create(std::string_view resourceId, std::int64_t amountValue)
Construct and validate one cost item.
std::optional< Status > failure
std::shared_ptr< resource::IResourceAccount > accountOwner
std::function< std::optional< Value >(std::string_view)> query
resource::IResourceAccount * account
std::vector< std::unique_ptr< ITransactionParticipant > > effects
std::map< std::string, resource::ResourceCost > floors
std::vector< std::function< Result< void >()> > guards
std::optional< resource::CostSpec > cost
Observable summary returned after an atomic participant commit.
Definition Transaction.h:98