载入中...
搜索中...
未找到
Authority.cpp
浏览该文件的文档.
2
3#include "common/Json.h"
5
6#include <simplesquirrel/simplesquirrel.hpp>
7
8#include <algorithm>
9#include <cmath>
10#include <functional>
11#include <iomanip>
12#include <sstream>
13#include <utility>
14
15namespace eve::authority {
16namespace {
17
19struct ScriptAuthorityStore {
20 explicit ScriptAuthorityStore(AuthorityStoreHandleRef value) : reference(value) {}
21 ~ScriptAuthorityStore() noexcept {
22 Authority::release(reference).ignore("script authority store proxy destruction");
23 }
25};
26
27template <class Ref, class Proxy, class Release>
28ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result<Ref>&& reference, Release&& release) {
30 const Ref ref = std::move(reference).takeValue();
31 auto object = eve::script::makeOwnedSquirrelInstance<Proxy>(vm, std::make_unique<Proxy>(ref));
32 if (!object) {
33 const eve::Status status = object.status();
34 object.ignore("failed to create owned authority proxy");
35 std::invoke(std::forward<Release>(release), ref).ignore("rollback failed owned authority allocation");
37 }
38 ssq::Object owned = std::move(object).takeValue();
40 result.set("value", owned);
41 result.set("ownership", std::string("owned"));
42 result.set("ownerEpoch", static_cast<std::int64_t>(ref.ownerEpoch));
43 result.set("handle", static_cast<std::int64_t>(ref.packed()));
44 return result;
45}
46
47std::string quote(const std::string& value) {
48 return eve::json::quoteString(value, eve::json::StringEscapeStyle::UnicodeBackspaceFormFeed);
49}
50
51bool parseU64(const eve::json::Value& value, uint64_t& output) {
52 if (!value.isString()) return false;
53 auto parsed = eve::json::scanUnsignedInteger(value.asString(), eve::json::UnsignedIntegerSyntax::LegacyStoull);
54 if (!parsed) return false;
55 output = parsed.value().value;
56 return parsed.value().consumed == parsed.value().size;
57}
58
59bool parseRuleId(const std::string& id, uint64_t& output) {
60 constexpr const char* prefix = "authority-";
61 if (!id.starts_with(prefix)) return false;
62 const std::string suffix = id.substr(std::char_traits<char>::length(prefix));
63 if (suffix.size() != 16) return false;
64 try {
65 size_t pos = 0;
66 output = std::stoull(suffix, &pos);
67 return pos == suffix.size() && output != 0;
68 } catch (...) {
69 return false;
70 }
71}
72
73bool wins(const Rule& candidate, const Rule& current) {
74 if (candidate.priority != current.priority) return candidate.priority > current.priority;
75 if (candidate.effect != current.effect) return candidate.effect == RuleEffect::Deny;
76 return candidate.order < current.order;
77}
78
79void advanceRevision(eve::Revision& revision) {
80 if (const auto next = revision.incremented()) revision = *next;
81}
82
83eve::LogicalId authoritySchema() {
84 const auto schema = eve::LogicalId::parse("authority:store");
85 if (!schema) std::terminate();
86 return *schema;
87}
88
89const eve::SnapshotMigrationChain& authorityMigrations() {
90 static const eve::SnapshotMigrationChain chain = [] {
92 const auto registration =
93 result.add(authoritySchema(), eve::SchemaVersion(0), eve::SchemaVersion(1),
95 const auto* object = payload.getIf<eve::Value::Object>();
96 if (!object)
98 eve::DiagnosticCode::ParseError, "authority snapshot payload must be an object"));
99 eve::Value::Object migrated = *object;
100 migrated["version"] = eve::Value(std::int64_t(1));
101 return eve::Result<eve::Value>::success(eve::Value(std::move(migrated)));
102 });
103 if (!registration.ok()) std::terminate();
104 return result;
105 }();
106 return chain;
107}
108
109} // namespace
110
112
113std::string effectName(RuleEffect effect) { return effect == RuleEffect::Grant ? "grant" : "deny"; }
115 switch (kind) {
116 case EventKind::Granted: return "granted";
117 case EventKind::Denied: return "denied";
118 case EventKind::Revoked: return "revoked";
119 case EventKind::Expired: return "expired";
120 }
121 return "unknown";
122}
123
124namespace {
125
126eve::Result<std::string> rejectedRule(std::string message) {
128 std::move(message), "rule", {}, "authority.store"));
129}
130
131eve::Result<void> notFoundRule(std::string message) {
133 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, std::move(message), "rule", {}, "authority.store"));
134}
135
136eve::Value projectRuleId(std::string&& id) { return eve::Value(std::move(id)); }
137
138} // namespace
139
140std::string Store::exactKey(const std::string& actor, const std::string& scope, const std::string& capability) {
141 std::string key;
142 key.reserve(actor.size() + scope.size() + capability.size() + 2);
143 key.append(actor);
144 key.push_back('\x1f');
145 key.append(scope);
146 key.push_back('\x1f');
147 key.append(capability);
148 return key;
149}
150
151bool Store::hasWildcard(const Rule& rule) {
152 return rule.actor == kWildcard || rule.scope == kWildcard || rule.capability == kWildcard;
153}
154
155bool Store::ruleMatches(const Rule& rule, const std::string& actor, const std::string& scope,
156 const std::string& capability) {
157 const bool actorOk = rule.actor == kWildcard || rule.actor == actor;
158 const bool scopeOk = rule.scope == kWildcard || rule.scope == scope;
159 const bool capOk = rule.capability == kWildcard || rule.capability == capability;
160 return actorOk && scopeOk && capOk;
161}
162
163void Store::indexInsert(const Rule& rule) {
164 if (hasWildcard(rule)) {
165 wildcardIds_.push_back(rule.id);
166 return;
167 }
168 exactIndex_[exactKey(rule.actor, rule.scope, rule.capability)].push_back(rule.id);
169}
170
171void Store::indexErase(const Rule& rule) {
172 if (hasWildcard(rule)) {
173 wildcardIds_.erase(std::remove(wildcardIds_.begin(), wildcardIds_.end(), rule.id), wildcardIds_.end());
174 return;
175 }
176 const auto key = exactKey(rule.actor, rule.scope, rule.capability);
177 const auto it = exactIndex_.find(key);
178 if (it == exactIndex_.end()) return;
179 auto& ids = it->second;
180 ids.erase(std::remove(ids.begin(), ids.end(), rule.id), ids.end());
181 if (ids.empty()) exactIndex_.erase(it);
182}
183
184void Store::rebuildIndex() {
185 exactIndex_.clear();
186 wildcardIds_.clear();
187 for (const auto& rule : rules_) indexInsert(rule);
188}
189
190void Store::trimEvents() {
191 if (eventCapacity_ <= 0) return;
192 while (static_cast<int>(events_.size()) > eventCapacity_) events_.pop_front();
193}
194
195void Store::emit(EventKind kind, const Rule& rule, const std::string& reason) {
196 events_.push_back({nextSequence_++, kind, rule.id, rule.actor, rule.scope, rule.capability, rule.source, reason});
197 trimEvents();
198}
199
200eve::Result<std::string> Store::add(RuleEffect effect, const std::string& actor, const std::string& scope,
201 const std::string& capability, const std::string& source, int priority,
202 double duration) {
203 if (actor.empty() || scope.empty() || capability.empty())
204 return rejectedRule("authority actor, scope, and capability must be non-empty");
205 if (!std::isfinite(duration)) return rejectedRule("authority rule duration must be finite");
206 std::ostringstream id;
207 id << "authority-" << std::setw(16) << std::setfill('0') << nextId_++;
208 Rule rule;
209 rule.id = id.str();
210 rule.actor = actor;
211 rule.scope = scope;
212 rule.capability = capability;
213 rule.source = source;
214 rule.effect = effect;
215 rule.priority = priority;
216 rule.duration = std::max(0.0, duration);
217 rule.remaining = duration > 0.0 ? duration : -1.0;
218 rule.order = nextOrder_++;
219 rules_.push_back(std::move(rule));
220 indexInsert(rules_.back());
221 emit(effect == RuleEffect::Grant ? EventKind::Granted : EventKind::Denied, rules_.back());
222 advanceRevision(revision_);
223 query_.clear();
225}
226
227eve::Result<std::string> Store::grant(const std::string& actor, const std::string& scope, const std::string& capability,
228 const std::string& source, int priority, double duration) {
229 return add(RuleEffect::Grant, actor, scope, capability, source, priority, duration);
230}
231eve::Result<std::string> Store::deny(const std::string& actor, const std::string& scope, const std::string& capability,
232 const std::string& source, int priority, double duration) {
233 return add(RuleEffect::Deny, actor, scope, capability, source, priority, duration);
234}
235
236eve::Result<void> Store::revoke(const std::string& id, const std::string& reason) {
237 const auto it = std::find_if(rules_.begin(), rules_.end(), [&id](const Rule& rule) { return rule.id == id; });
238 if (it == rules_.end()) return notFoundRule("authority rule is not active");
239 emit(EventKind::Revoked, *it, reason);
240 indexErase(*it);
241 rules_.erase(it);
242 query_.clear();
243 advanceRevision(revision_);
245}
246
247int Store::revokeMatching(const std::string& reason, const std::function<bool(const Rule&)>& predicate) {
248 int removed = 0;
249 for (auto it = rules_.begin(); it != rules_.end();) {
250 if (predicate(*it)) {
251 emit(EventKind::Revoked, *it, reason);
252 indexErase(*it);
253 it = rules_.erase(it);
254 ++removed;
255 } else {
256 ++it;
257 }
258 }
259 query_.clear();
260 if (removed > 0) advanceRevision(revision_);
261 return removed;
262}
263
264int Store::revokeBySource(const std::string& source, const std::string& reason) {
265 return revokeMatching(reason, [&](const Rule& rule) { return rule.source == source; });
266}
267
268int Store::revokeByActor(const std::string& actor, const std::string& reason) {
269 return revokeMatching(reason, [&](const Rule& rule) { return rule.actor == actor; });
270}
271
272int Store::revokeByScope(const std::string& scope, const std::string& reason) {
273 return revokeMatching(reason, [&](const Rule& rule) { return rule.scope == scope; });
274}
275
276int Store::revokeByCapability(const std::string& capability, const std::string& reason) {
277 return revokeMatching(reason, [&](const Rule& rule) { return rule.capability == capability; });
278}
279
280void Store::update(double dtSeconds) {
281 if (dtSeconds <= 0.0 || !std::isfinite(dtSeconds)) return;
282 bool changed = false;
283 for (auto it = rules_.begin(); it != rules_.end();) {
284 if (it->remaining < 0.0) {
285 ++it;
286 continue;
287 }
288 it->remaining = std::max(0.0, it->remaining - dtSeconds);
289 changed = true;
290 if (it->remaining == 0.0) {
291 emit(EventKind::Expired, *it, "duration_elapsed");
292 indexErase(*it);
293 it = rules_.erase(it);
294 } else {
295 ++it;
296 }
297 }
298 query_.clear();
299 if (changed) advanceRevision(revision_);
300}
301
302Decision Store::explain(const std::string& actor, const std::string& scope, const std::string& capability) const {
303 const Rule* winner = nullptr;
304 std::vector<std::string> candidateIds;
305 if (const auto it = exactIndex_.find(exactKey(actor, scope, capability)); it != exactIndex_.end())
306 candidateIds.insert(candidateIds.end(), it->second.begin(), it->second.end());
307 candidateIds.insert(candidateIds.end(), wildcardIds_.begin(), wildcardIds_.end());
308 for (const auto& id : candidateIds) {
309 const Rule* rule = find(id);
310 if (!rule || !ruleMatches(*rule, actor, scope, capability)) continue;
311 if (!winner || wins(*rule, *winner)) winner = rule;
312 }
313 if (!winner) return {false, "no_matching_rule", {}, {}, 0};
314 return {winner->effect == RuleEffect::Grant, winner->effect == RuleEffect::Grant ? "granted" : "denied", winner->id,
315 winner->source, winner->priority};
316}
317bool Store::can(const std::string& actor, const std::string& scope, const std::string& capability) const {
318 return explain(actor, scope, capability).allowed;
319}
320const Rule* Store::find(const std::string& id) const {
321 const auto it = std::find_if(rules_.begin(), rules_.end(), [&id](const Rule& rule) { return rule.id == id; });
322 return it == rules_.end() ? nullptr : &*it;
323}
324
325int Store::query(const std::string& actor, const std::string& scope, const std::string& capability) {
326 query_.clear();
327 for (const auto& rule : rules_) {
328 const bool actorOk = actor.empty() || rule.actor == actor || rule.actor == kWildcard;
329 const bool scopeOk = scope.empty() || rule.scope == scope || rule.scope == kWildcard;
330 const bool capOk = capability.empty() || rule.capability == capability || rule.capability == kWildcard;
331 if (actorOk && scopeOk && capOk) query_.push_back(&rule);
332 }
333 return static_cast<int>(query_.size());
334}
335int Store::queryActor(const std::string& actor) { return query(actor, {}, {}); }
336int Store::queryScope(const std::string& scope) { return query({}, scope, {}); }
337int Store::queryCapability(const std::string& capability) { return query({}, {}, capability); }
338const Rule* Store::queryAt(int index) const {
339 return index >= 0 && static_cast<size_t>(index) < query_.size() ? query_[static_cast<size_t>(index)] : nullptr;
340}
341
343 if (capacity < 0)
345 "authority event capacity must be non-negative",
346 "eventCapacity", {}, "authority.store"));
347 eventCapacity_ = capacity;
348 trimEvents();
349 advanceRevision(revision_);
351}
352
353int Store::eventCount() const { return static_cast<int>(events_.size()); }
354const Event* Store::eventAt(int index) const {
355 return index >= 0 && static_cast<size_t>(index) < events_.size() ? &events_[static_cast<size_t>(index)] : nullptr;
356}
358 if (!events_.empty()) {
359 events_.clear();
360 advanceRevision(revision_);
361 }
362}
363
364std::string Store::snapshotJson() const {
365 std::ostringstream out;
366 out << "{\"version\":1,\"nextId\":" << quote(std::to_string(nextId_))
367 << ",\"nextOrder\":" << quote(std::to_string(nextOrder_))
368 << ",\"nextSequence\":" << quote(std::to_string(nextSequence_)) << ",\"rules\":[";
369 bool first = true;
370 for (const auto& rule : rules_) {
371 if (!first) out << ',';
372 first = false;
373 out << "{\"id\":" << quote(rule.id) << ",\"actor\":" << quote(rule.actor) << ",\"scope\":" << quote(rule.scope)
374 << ",\"capability\":" << quote(rule.capability) << ",\"source\":" << quote(rule.source)
375 << ",\"effect\":" << quote(effectName(rule.effect)) << ",\"priority\":" << rule.priority
376 << ",\"duration\":" << std::setprecision(17) << rule.duration << ",\"remaining\":" << rule.remaining
377 << ",\"order\":" << quote(std::to_string(rule.order)) << '}';
378 }
379 return out.str() + "]}";
380}
381
382eve::Result<void> Store::restoreJson(const std::string& json) {
383 std::string parseError;
384 auto document = eve::json::Document::parse(json, &parseError);
385 const auto root = document.root();
386 uint64_t nextId = 0, nextOrder = 0, nextSequence = 0;
387 if (!document.valid() || !root.isObject() || root.getInt("version") != 1 || !parseU64(root.get("nextId"), nextId) ||
388 !parseU64(root.get("nextOrder"), nextOrder) || !parseU64(root.get("nextSequence"), nextSequence) ||
389 nextId == 0 || nextOrder == 0 || nextSequence == 0 || !root.get("rules").isArray()) {
392 parseError.empty() ? "invalid authority snapshot" : parseError, "authority.store"));
393 }
394 std::deque<Rule> restored;
395 const auto values = root.get("rules");
396 for (size_t i = 0; i < values.size(); ++i) {
397 const auto item = values.at(i);
398 Rule rule;
399 uint64_t order = 0, numericId = 0;
400 const auto effect = item.getString("effect");
401 if (!item.isObject() || item.getString("id").empty() || item.getString("actor").empty() ||
402 item.getString("scope").empty() || item.getString("capability").empty() ||
403 (effect != "grant" && effect != "deny") || !parseU64(item.get("order"), order) || order == 0 ||
404 order >= nextOrder || !parseRuleId(item.getString("id"), numericId) || numericId >= nextId ||
405 !item.get("priority").isNumber() || !item.get("duration").isNumber() || !item.get("remaining").isNumber()) {
407 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "invalid rule at index " + std::to_string(i),
408 "authority.store.rules[" + std::to_string(i) + "]"));
409 }
410 rule.id = item.getString("id");
411 rule.actor = item.getString("actor");
412 rule.scope = item.getString("scope");
413 rule.capability = item.getString("capability");
414 rule.source = item.getString("source");
415 rule.effect = effect == "grant" ? RuleEffect::Grant : RuleEffect::Deny;
416 rule.priority = item.getInt("priority");
417 rule.duration = item.getDouble("duration");
418 rule.remaining = item.getDouble("remaining");
419 rule.order = order;
420 if (!std::isfinite(rule.duration) || !std::isfinite(rule.remaining) || rule.duration < 0.0 ||
421 rule.remaining == 0.0 || rule.remaining < -1.0 ||
422 std::any_of(
423 restored.begin(), restored.end(),
424 [&](const Rule& old) { return old.id == rule.id || old.order == rule.order; })) {
426 eve::DiagnosticCode::InvariantViolation, "invalid rule state at index " + std::to_string(i),
427 "authority.store.rules[" + std::to_string(i) + "]"));
428 }
429 restored.push_back(std::move(rule));
430 }
431 rules_ = std::move(restored);
432 nextId_ = nextId;
433 nextOrder_ = nextOrder;
434 nextSequence_ = nextSequence;
435 events_.clear();
436 query_.clear();
437 rebuildIndex();
438 revision_ = eve::Revision(nextSequence > 0 ? nextSequence - 1 : 0);
439 tick_ = eve::SimulationTick{};
441}
442
446 return eve::makeSnapshotEnvelope("authority.store", authoritySchema(), eve::SchemaVersion(1), instanceId_,
447 revision_, tick_, std::move(payload).takeValue(), hashProvider);
448}
449
451 const eve::SnapshotHashProvider& hashProvider) {
452 if (source.type != "authority.store" || source.schema != authoritySchema())
454 "snapshot does not belong to authority::Store"));
455 if (!instanceId_.isNil() && source.instanceId != instanceId_)
457 eve::DiagnosticCode::Conflict, "snapshot instanceId does not match authority::Store"));
458
459 auto migrated = authorityMigrations().migrate(source, eve::SchemaVersion(1), hashProvider);
460 if (!migrated.ok()) return eve::Result<void>::failure(migrated.status());
461 const auto& candidate = migrated.value();
462 auto metadata = eve::validateSnapshotPayloadMetadata(candidate.payload, candidate.revision, candidate.tick);
463 if (!metadata.ok()) return eve::Result<void>::failure(metadata.status());
464 auto payload = candidate.payload.toJson();
465 if (!payload.ok()) return eve::Result<void>::failure(payload.status());
466 const std::string payloadJson = std::move(payload).takeValue();
467
468 // restoreJson parses into local containers before replacing rules/counters;
469 // it is therefore the domain candidate-builder and has no partial writes.
470 auto restored = restoreJson(payloadJson);
471 if (!restored.ok()) return eve::Result<void>::failure(restored.status());
472
473 instanceId_ = candidate.instanceId;
474 revision_ = candidate.revision;
475 tick_ = candidate.tick;
477}
478
480 auto value = snapshot(hashProvider);
481 if (!value.ok()) return eve::Result<std::string>::failure(value.status());
482 return std::move(value).andThen(
483 [](eve::SnapshotEnvelope&& envelope) { return eve::serializeSnapshotEnvelope(envelope); });
484}
485
486eve::Result<void> Store::restoreSnapshotJson(std::string_view json, const eve::SnapshotHashProvider& hashProvider) {
487 auto source = eve::parseSnapshotEnvelope(json, hashProvider);
488 if (!source.ok()) return eve::Result<void>::failure(source.status());
489 return restoreSnapshot(std::move(source).takeValue(), hashProvider);
490}
491
493 Authority* module = Authority::create();
494 return module->stores_.emplace(std::make_unique<Store>());
495}
496
498 Authority* module = ModuleManager::getInstance<Authority>("Authority");
499 if (!module) return {};
500 return module->stores_.resolve(reference);
501}
502
504 Authority* module = ModuleManager::getInstance<Authority>("Authority");
505 if (!module)
507 "Authority module is no longer loaded", "store", {},
508 "authority.squirrel"));
509 return module->stores_.erase(reference);
510}
511
513 if (!reference.isValid()) return false;
514 Authority* module = ModuleManager::getInstance<Authority>("Authority");
515 return !module || module->stores_.isStale(reference);
516}
517
519
520void Authority::expose(ssq::Table& table) {
521 const HSQUIRRELVM vm = table.getHandle();
522 auto rule = table.addClass<Rule>("AuthorityRule", std::function<Rule*()>([] { return nullptr; }), false);
523 rule.addFunc("getId", [](Rule* r) { return r ? r->id : std::string{}; });
524 rule.addFunc("getActor", [](Rule* r) { return r ? r->actor : std::string{}; });
525 rule.addFunc("getScope", [](Rule* r) { return r ? r->scope : std::string{}; });
526 rule.addFunc("getCapability", [](Rule* r) { return r ? r->capability : std::string{}; });
527 rule.addFunc("getSource", [](Rule* r) { return r ? r->source : std::string{}; });
528 rule.addFunc("getEffect", [](Rule* r) { return r ? effectName(r->effect) : std::string{}; });
529 rule.addFunc("getPriority", [](Rule* r) { return r ? r->priority : 0; });
530 rule.addFunc("getRemaining", [](Rule* r) { return r ? static_cast<float>(r->remaining) : 0.0f; });
531
532 auto decision =
533 table.addClass<Decision>("AuthorityDecision", std::function<Decision*()>([] { return nullptr; }), false);
534 decision.addFunc("isAllowed", [](Decision* d) { return d && d->allowed; });
535 decision.addFunc("getReason", [](Decision* d) { return d ? d->reason : std::string{}; });
536 decision.addFunc("getWinningRuleId", [](Decision* d) { return d ? d->winningRuleId : std::string{}; });
537 decision.addFunc("getSource", [](Decision* d) { return d ? d->source : std::string{}; });
538 decision.addFunc("getPriority", [](Decision* d) { return d ? d->priority : 0; });
539
540 auto event = table.addClass<Event>("AuthorityEvent", std::function<Event*()>([] { return nullptr; }), false);
541 event.addFunc("getSequence", [](Event* e) { return e ? static_cast<int64_t>(e->sequence) : int64_t{0}; });
542 event.addFunc("getKind", [](Event* e) { return e ? eventKindName(e->kind) : std::string{}; });
543 event.addFunc("getRuleId", [](Event* e) { return e ? e->ruleId : std::string{}; });
544 event.addFunc("getReason", [](Event* e) { return e ? e->reason : std::string{}; });
545
546 auto store = table.addClass<Store>("AuthorityStore", std::function<Store*()>([] { return nullptr; }), false);
547 store.addFunc(
548 "grant", [vm](Store* s, const std::string& actor, const std::string& scope, const std::string& capability,
549 const std::string& source, int priority, float duration) {
550 if (!s)
552 vm,
554 "authority store must not be null",
555 "store", {}, "authority.squirrel")),
556 projectRuleId);
557 return eve::script::projectResult(vm, s->grant(actor, scope, capability, source, priority, duration),
558 projectRuleId);
559 });
560 store.addFunc("deny", [vm](Store* s, const std::string& actor, const std::string& scope,
561 const std::string& capability, const std::string& source, int priority, float duration) {
562 if (!s)
564 vm,
566 "authority store must not be null", "store",
567 {}, "authority.squirrel")),
568 projectRuleId);
569 return eve::script::projectResult(vm, s->deny(actor, scope, capability, source, priority, duration),
570 projectRuleId);
571 });
572 store.addFunc("revoke", [vm](Store* s, const std::string& id, const std::string& reason) {
573 if (!s)
576 "authority store must not be null", "store", {},
577 "authority.squirrel")));
578 return eve::script::projectResult(vm, s->revoke(id, reason));
579 });
580 store.addFunc("revokeBySource", [](Store* s, const std::string& source, const std::string& reason) {
581 return s ? s->revokeBySource(source, reason) : 0;
582 });
583 store.addFunc("revokeByActor", [](Store* s, const std::string& actor, const std::string& reason) {
584 return s ? s->revokeByActor(actor, reason) : 0;
585 });
586 store.addFunc("revokeByScope", [](Store* s, const std::string& scope, const std::string& reason) {
587 return s ? s->revokeByScope(scope, reason) : 0;
588 });
589 store.addFunc("revokeByCapability", [](Store* s, const std::string& capability, const std::string& reason) {
590 return s ? s->revokeByCapability(capability, reason) : 0;
591 });
592 store.addFunc("update", [](Store* s, float dt) {
593 if (s) s->update(dt);
594 });
595 store.addFunc("can", &Store::can);
596 store.addFunc("explain", &Store::explain);
597 store.addFunc(
598 "find", [](Store* s, const std::string& id) -> Rule* { return s ? const_cast<Rule*>(s->find(id)) : nullptr; });
599 store.addFunc("queryActor", &Store::queryActor);
600 store.addFunc("queryScope", &Store::queryScope);
601 store.addFunc("queryCapability", &Store::queryCapability);
602 store.addFunc("query", &Store::query);
603 store.addFunc("queryAt",
604 [](Store* s, int index) -> Rule* { return s ? const_cast<Rule*>(s->queryAt(index)) : nullptr; });
605 store.addFunc("setEventCapacity", [vm](Store* s, int capacity) {
606 if (!s)
609 "authority store must not be null", "store", {},
610 "authority.squirrel")));
611 return eve::script::projectResult(vm, s->setEventCapacity(capacity));
612 });
613 store.addFunc("eventCapacity", [](Store* s) { return s ? s->eventCapacity() : 0; });
614 store.addFunc("eventCount", &Store::eventCount);
615 store.addFunc("eventAt",
616 [](Store* s, int index) -> Event* { return s ? const_cast<Event*>(s->eventAt(index)) : nullptr; });
617 store.addFunc("clearEvents", &Store::clearEvents);
618 store.addFunc("snapshotJson", &Store::snapshotJson);
619 store.addFunc("restoreJson", [vm](Store* value, const std::string& json) {
620 if (!value)
623 "authority store must not be null", "store", {},
624 "authority.squirrel")));
625 return eve::script::projectResult(vm, value->restoreJson(json));
626 });
627
628 auto ownedStore = table.addClass<ScriptAuthorityStore>(
629 "AuthorityStoreProxy", std::function<ScriptAuthorityStore*()>([] { return nullptr; }), true);
630 ownedStore.addFunc("ownership", [](ScriptAuthorityStore*) { return std::string("owned"); });
631 ownedStore.addFunc("ownerEpoch", [](ScriptAuthorityStore* value) {
632 return value ? static_cast<int64_t>(value->reference.ownerEpoch) : int64_t{0};
633 });
634 ownedStore.addFunc("handle", [](ScriptAuthorityStore* value) {
635 return value ? static_cast<int64_t>(value->reference.packed()) : int64_t{0};
636 });
637 ownedStore.addFunc("isStale",
638 [](ScriptAuthorityStore* value) { return !value || Authority::isStale(value->reference); });
639 ownedStore.addFunc("release", [vm](ScriptAuthorityStore* value) {
640 if (!value)
643 "owned authority store proxy must not be null",
644 "store", {}, "authority.squirrel")));
646 });
647 ownedStore.addFunc(
648 "grant", [vm](ScriptAuthorityStore* value, const std::string& actor, const std::string& scope,
649 const std::string& capability, const std::string& source, int priority, float duration) {
650 if (!value)
652 vm,
654 eve::DiagnosticCode::InvalidArgument, "owned authority store proxy must not be null", "store",
655 {}, "authority.squirrel")),
656 projectRuleId);
657 auto view = Authority::resolve(value->reference);
658 if (!view.isBound())
660 vm,
662 "owned authority store handle is stale",
663 "store", {}, "authority.squirrel")),
664 projectRuleId);
665 return eve::script::projectResult(vm, view->grant(actor, scope, capability, source, priority, duration),
666 projectRuleId);
667 });
668 ownedStore.addFunc(
669 "deny", [vm](ScriptAuthorityStore* value, const std::string& actor, const std::string& scope,
670 const std::string& capability, const std::string& source, int priority, float duration) {
671 if (!value)
673 vm,
675 "authority store proxy must not be null",
676 "store", {}, "authority.squirrel")),
677 projectRuleId);
678 auto view = Authority::resolve(value->reference);
679 if (!view.isBound())
681 vm,
683 "authority store handle is stale", "store",
684 {}, "authority.squirrel")),
685 projectRuleId);
686 return eve::script::projectResult(vm, view->deny(actor, scope, capability, source, priority, duration),
687 projectRuleId);
688 });
689 ownedStore.addFunc("revoke", [vm](ScriptAuthorityStore* value, const std::string& id, const std::string& reason) {
690 if (!value)
693 "owned authority store proxy must not be null",
694 "store", {}, "authority.squirrel")));
695 auto view = Authority::resolve(value->reference);
696 if (!view.isBound())
699 "owned authority store handle is stale", "store",
700 {}, "authority.squirrel")));
701 return eve::script::projectResult(vm, view->revoke(id, reason));
702 });
703 ownedStore.addFunc("revokeBySource",
704 [](ScriptAuthorityStore* value, const std::string& source, const std::string& reason) {
705 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
706 return view.isBound() ? view->revokeBySource(source, reason) : 0;
707 });
708 ownedStore.addFunc("revokeByActor",
709 [](ScriptAuthorityStore* value, const std::string& actor, const std::string& reason) {
710 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
711 return view.isBound() ? view->revokeByActor(actor, reason) : 0;
712 });
713 ownedStore.addFunc("revokeByScope",
714 [](ScriptAuthorityStore* value, const std::string& scope, const std::string& reason) {
715 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
716 return view.isBound() ? view->revokeByScope(scope, reason) : 0;
717 });
718 ownedStore.addFunc("revokeByCapability",
719 [](ScriptAuthorityStore* value, const std::string& capability, const std::string& reason) {
720 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
721 return view.isBound() ? view->revokeByCapability(capability, reason) : 0;
722 });
723 ownedStore.addFunc("update", [](ScriptAuthorityStore* value, float dt) {
724 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
725 if (view.isBound()) view->update(dt);
726 });
727 ownedStore.addFunc("can", [](ScriptAuthorityStore* value, const std::string& actor, const std::string& scope,
728 const std::string& capability) {
729 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
730 return view.isBound() && view->can(actor, scope, capability);
731 });
732 ownedStore.addFunc("explain", [](ScriptAuthorityStore* value, const std::string& actor, const std::string& scope,
733 const std::string& capability) {
734 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
735 return view.isBound() ? view->explain(actor, scope, capability) : Decision{};
736 });
737 ownedStore.addFunc("find", [](ScriptAuthorityStore* value, const std::string& id) -> Rule* {
738 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
739 return view.isBound() ? const_cast<Rule*>(view->find(id)) : nullptr;
740 });
741 ownedStore.addFunc("queryActor", [](ScriptAuthorityStore* value, const std::string& actor) {
742 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
743 return view.isBound() ? view->queryActor(actor) : 0;
744 });
745 ownedStore.addFunc("queryScope", [](ScriptAuthorityStore* value, const std::string& scope) {
746 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
747 return view.isBound() ? view->queryScope(scope) : 0;
748 });
749 ownedStore.addFunc("queryCapability", [](ScriptAuthorityStore* value, const std::string& capability) {
750 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
751 return view.isBound() ? view->queryCapability(capability) : 0;
752 });
753 ownedStore.addFunc("query", [](ScriptAuthorityStore* value, const std::string& actor, const std::string& scope,
754 const std::string& capability) {
755 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
756 return view.isBound() ? view->query(actor, scope, capability) : 0;
757 });
758 ownedStore.addFunc("queryAt", [](ScriptAuthorityStore* value, int index) -> Rule* {
759 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
760 return view.isBound() ? const_cast<Rule*>(view->queryAt(index)) : nullptr;
761 });
762 ownedStore.addFunc("setEventCapacity", [vm](ScriptAuthorityStore* value, int capacity) {
763 if (!value)
766 "owned authority store proxy must not be null",
767 "store", {}, "authority.squirrel")));
768 auto view = Authority::resolve(value->reference);
769 if (!view.isBound())
772 "owned authority store handle is stale", "store",
773 {}, "authority.squirrel")));
774 return eve::script::projectResult(vm, view->setEventCapacity(capacity));
775 });
776 ownedStore.addFunc("eventCapacity", [](ScriptAuthorityStore* value) {
777 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
778 return view.isBound() ? view->eventCapacity() : 0;
779 });
780 ownedStore.addFunc("eventCount", [](ScriptAuthorityStore* value) {
781 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
782 return view.isBound() ? view->eventCount() : 0;
783 });
784 ownedStore.addFunc("eventAt", [](ScriptAuthorityStore* value, int index) -> Event* {
785 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
786 return view.isBound() ? const_cast<Event*>(view->eventAt(index)) : nullptr;
787 });
788 ownedStore.addFunc("clearEvents", [](ScriptAuthorityStore* value) {
789 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
790 if (view.isBound()) view->clearEvents();
791 });
792 ownedStore.addFunc("snapshotJson", [](ScriptAuthorityStore* value) {
793 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
794 return view.isBound() ? view->snapshotJson() : std::string{};
795 });
796 ownedStore.addFunc("restoreJson", [vm](ScriptAuthorityStore* value, const std::string& json) {
797 auto view = value ? Authority::resolve(value->reference) : eve::script::Borrowed<Store>();
798 if (!view.isBound())
801 "owned authority store handle is stale", "store",
802 {}, "authority.squirrel")));
803 return eve::script::projectResult(vm, view->restoreJson(json));
804 });
805
806 auto cls = table.addClass(name, Authority::create, false);
807 expose(cls);
808}
809void Authority::expose(ssq::Class& cls) {
810 cls.addFunc("getName", &Authority::getName);
811 cls.addFunc("newStore", [vm = cls.getHandle()](Authority*) -> ssq::Table {
812 return makeOwnedProxy<AuthorityStoreHandleRef, ScriptAuthorityStore>(
813 vm, Authority::newStore(), [](AuthorityStoreHandleRef ref) { return Authority::release(ref); });
814 });
815}
816
817} // namespace eve::authority
Value::Object payload
float duration
int root
Definition AnimSmr.cpp:119
std::string output
ActiveSource owned
std::uint64_t revision
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
const std::string & s
int priority
struct SQVM * HSQUIRRELVM
bool changed
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
std::string message
std::uint32_t capacity
wgpu::PopErrorScopeStatus status
double r
std::int32_t first
JobScope scope
char quote
std::string id
Poco::JSON::Object::Ptr result
std::vector< std::int32_t > order
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
double dt
OceanSprayView view
std::unique_ptr< ParticleEffect > effect
std::string script
Definition PlayHost.cpp:117
std::set< std::string > values
Object::Ptr value
float d
int winner
int removed
ScriptStructure out
std::string_view source
std::string kind
double current
std::string string
The single Squirrel projection for common Result, Status and Value.
Json object
uint32_t index
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
virtual std::string getName() const =0
Returns the name.
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
Script module factory for generic authority stores.
Definition Authority.h:286
static eve::Result< void > release(AuthorityStoreHandleRef reference)
Releases a module-owned store.
static eve::Result< AuthorityStoreHandleRef > newStore()
Allocates an authority store and returns its ownership reference.
static bool isStale(AuthorityStoreHandleRef reference) noexcept
Reports whether a store reference is stale for the current module.
static eve::script::Borrowed< Store > resolve(AuthorityStoreHandleRef reference) noexcept
Resolves a live store as a non-owning observation.
Authority()=default
Constructs a Authority.
const Rule * queryAt(int index) const
Returns a rule from the latest query, or nullptr. @ownership Borrowed from this store; callers must n...
Store(eve::PersistentId instanceId={})
Creates an authority store with an optional persistent identity.
eve::Result< std::string > deny(const std::string &actor, const std::string &scope, const std::string &capability, const std::string &source, int priority=0, double duration=0.0)
Adds a deny rule and returns its stable ID.
void update(double dtSeconds)
Advances finite rule durations and expires rules reaching zero.
eve::Result< void > restoreSnapshot(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Restores a verified or migratable snapshot transactionally.
int revokeBySource(const std::string &source, const std::string &reason="source_revoked")
Revokes every rule from a source and returns the number removed.
int eventCount() const
Returns retained authority event count.
int queryScope(const std::string &scope)
Queries rules for a scope in deterministic creation order.
eve::Result< void > setEventCapacity(int capacity)
Sets the maximum number of retained lifecycle events.
int revokeByCapability(const std::string &capability, const std::string &reason="capability_revoked")
Revokes every rule whose capability field equals capability.
eve::Result< std::string > grant(const std::string &actor, const std::string &scope, const std::string &capability, const std::string &source, int priority=0, double duration=0.0)
Adds a grant rule and returns its stable ID.
eve::Result< void > revoke(const std::string &id, const std::string &reason="revoked")
Revokes a rule by stable ID.
eve::Result< std::string > snapshotEnvelopeJson(const eve::SnapshotHashProvider &hashProvider) const
Serializes the common snapshot envelope as canonical JSON.
eve::Result< void > restoreSnapshotJson(std::string_view json, const eve::SnapshotHashProvider &hashProvider)
Parses and transactionally restores a common snapshot envelope.
int query(const std::string &actor, const std::string &scope, const std::string &capability)
Queries rules matching actor, scope, and capability.
void clearEvents()
Clears retained events without resetting sequence allocation.
const Event * eventAt(int index) const
Returns a retained event, or nullptr. @ownership Borrowed from this store's retained event deque....
int queryActor(const std::string &actor)
Queries rules for an actor in deterministic creation order.
const Rule * find(const std::string &id) const
Returns a rule by stable ID, or nullptr. @ownership Borrowed from this store; callers must not delete...
bool can(const std::string &actor, const std::string &scope, const std::string &capability) const
Returns whether the winning rule allows a capability. @cost Linear in candidate rules for the query t...
int revokeByScope(const std::string &scope, const std::string &reason="scope_revoked")
Revokes every rule whose scope field equals scope.
Decision explain(const std::string &actor, const std::string &scope, const std::string &capability) const
Returns an explainable decision and its winning rule. @cost Linear in candidate rules for the query t...
eve::Result< eve::SnapshotEnvelope > snapshot(const eve::SnapshotHashProvider &hashProvider) const
Captures this store in the common versioned snapshot envelope.
eve::Result< void > restoreJson(const std::string &json)
Transactionally restores a snapshot produced by snapshotJson().
int revokeByActor(const std::string &actor, const std::string &reason="actor_revoked")
Revokes every rule whose actor field equals actor.
int queryCapability(const std::string &capability)
Queries rules for a capability in deterministic creation order.
std::string snapshotJson() const
Exports persistent state as deterministic compact JSON.
Id128 public API.
Definition Identity.h:111
constexpr bool isNil() const noexcept
Returns whether this value is the all-zero nil ID.
Definition Identity.h:175
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.
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
std::string effectName(RuleEffect effect)
Returns the stable lowercase name of a rule effect.
eve::script::RuntimeHandleRef< AuthorityStoreHandleTag > AuthorityStoreHandleRef
Generation- and module-epoch-qualified authority store reference.
Definition Authority.h:24
EventKind
Kind of authority lifecycle event.
Definition Authority.h:61
RuleEffect
Whether an authority rule grants or denies a capability.
Definition Authority.h:27
constexpr std::string_view kWildcard
Opaque field token that matches any actor, scope, or capability.
Definition Authority.h:35
std::string eventKindName(EventKind kind)
Returns the stable lowercase name of an event kind.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
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
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.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
Result< void > validateSnapshotPayloadMetadata(const Value &payload, Revision revision, SimulationTick tick)
Validate optional payload copies of envelope revision and tick.
Definition Snapshot.cpp:80
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
detail::StrongUint64< detail::RevisionTag > Revision
Monotonic content/state revision used for optimistic-concurrency checks.
Definition Revision.h:13
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
Explainable result of an authority decision.
Definition Authority.h:52
Deterministically sequenced authority lifecycle event.
Definition Authority.h:64
One stable authority rule over an opaque actor and scope.
Definition Authority.h:38
std::string scope
Definition Authority.h:41
RuleEffect effect
Definition Authority.h:44
std::string actor
Definition Authority.h:40
std::string capability
Definition Authority.h:42
std::string source
Definition Authority.h:43
Handle plus owner-lifetime epoch for a non-ECS registry object.
constexpr bool isValid() const noexcept
Returns whether both the handle and its registry epoch are set.