载入中...
搜索中...
未找到
Authority.cpp
浏览该文件的文档.
35 std::invoke(std::forward<Release>(release), ref).ignore("rollback failed owned authority allocation");
39 auto result = eve::script::projectStatusResult(vm, eve::Status::success(eve::StatusCode::Applied));
53 auto parsed = eve::json::scanUnsignedInteger(value.asString(), eve::json::UnsignedIntegerSyntax::LegacyStoull);
113std::string effectName(RuleEffect effect) { return effect == RuleEffect::Grant ? "grant" : "deny"; }
127 return eve::Result<std::string>::failure(eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument,
133 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, std::move(message), "rule", {}, "authority.store"));
140std::string Store::exactKey(const std::string& actor, const std::string& scope, const std::string& capability) {
173 wildcardIds_.erase(std::remove(wildcardIds_.begin(), wildcardIds_.end(), rule.id), wildcardIds_.end());
196 events_.push_back({nextSequence_++, kind, rule.id, rule.actor, rule.scope, rule.capability, rule.source, reason});
200eve::Result<std::string> Store::add(RuleEffect effect, const std::string& actor, const std::string& scope,
224 return eve::Result<std::string>::success(rules_.back().id, eve::Status::success(eve::StatusCode::Applied));
227eve::Result<std::string> Store::grant(const std::string& actor, const std::string& scope, const std::string& capability,
231eve::Result<std::string> Store::deny(const std::string& actor, const std::string& scope, const std::string& capability,
237 const auto it = std::find_if(rules_.begin(), rules_.end(), [&id](const Rule& rule) { return rule.id == id; });
247int Store::revokeMatching(const std::string& reason, const std::function<bool(const Rule&)>& predicate) {
302Decision Store::explain(const std::string& actor, const std::string& scope, const std::string& capability) const {
305 if (const auto it = exactIndex_.find(exactKey(actor, scope, capability)); it != exactIndex_.end())
314 return {winner->effect == RuleEffect::Grant, winner->effect == RuleEffect::Grant ? "granted" : "denied", winner->id,
317bool Store::can(const std::string& actor, const std::string& scope, const std::string& capability) const {
321 const auto it = std::find_if(rules_.begin(), rules_.end(), [&id](const Rule& rule) { return rule.id == id; });
325int Store::query(const std::string& actor, const std::string& scope, const std::string& capability) {
330 const bool capOk = capability.empty() || rule.capability == capability || rule.capability == kWildcard;
373 out << "{\"id\":" << quote(rule.id) << ",\"actor\":" << quote(rule.actor) << ",\"scope\":" << quote(rule.scope)
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) ||
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),
443eve::Result<eve::SnapshotEnvelope> Store::snapshot(const eve::SnapshotHashProvider& hashProvider) const {
446 return eve::makeSnapshotEnvelope("authority.store", authoritySchema(), eve::SchemaVersion(1), instanceId_,
462 auto metadata = eve::validateSnapshotPayloadMetadata(candidate.payload, candidate.revision, candidate.tick);
479eve::Result<std::string> Store::snapshotEnvelopeJson(const eve::SnapshotHashProvider& hashProvider) const {
486eve::Result<void> Store::restoreSnapshotJson(std::string_view json, const eve::SnapshotHashProvider& hashProvider) {
522 auto rule = table.addClass<Rule>("AuthorityRule", std::function<Rule*()>([] { return nullptr; }), false);
530 rule.addFunc("getRemaining", [](Rule* r) { return r ? static_cast<float>(r->remaining) : 0.0f; });
533 table.addClass<Decision>("AuthorityDecision", std::function<Decision*()>([] { return nullptr; }), false);
536 decision.addFunc("getWinningRuleId", [](Decision* d) { return d ? d->winningRuleId : std::string{}; });
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}; });
546 auto store = table.addClass<Store>("AuthorityStore", std::function<Store*()>([] { return nullptr; }), false);
548 "grant", [vm](Store* s, const std::string& actor, const std::string& scope, const std::string& capability,
557 return eve::script::projectResult(vm, s->grant(actor, scope, capability, source, priority, duration),
569 return eve::script::projectResult(vm, s->deny(actor, scope, capability, source, priority, duration),
580 store.addFunc("revokeBySource", [](Store* s, const std::string& source, const std::string& reason) {
583 store.addFunc("revokeByActor", [](Store* s, const std::string& actor, const std::string& reason) {
586 store.addFunc("revokeByScope", [](Store* s, const std::string& scope, const std::string& reason) {
589 store.addFunc("revokeByCapability", [](Store* s, const std::string& capability, const std::string& reason) {
598 "find", [](Store* s, const std::string& id) -> Rule* { return s ? const_cast<Rule*>(s->find(id)) : nullptr; });
604 [](Store* s, int index) -> Rule* { return s ? const_cast<Rule*>(s->queryAt(index)) : nullptr; });
616 [](Store* s, int index) -> Event* { return s ? const_cast<Event*>(s->eventAt(index)) : nullptr; });
665 return eve::script::projectResult(vm, view->grant(actor, scope, capability, source, priority, duration),
686 return eve::script::projectResult(vm, view->deny(actor, scope, capability, source, priority, duration),
689 ownedStore.addFunc("revoke", [vm](ScriptAuthorityStore* value, const std::string& id, const std::string& reason) {
727 ownedStore.addFunc("can", [](ScriptAuthorityStore* value, const std::string& actor, const std::string& scope,
732 ownedStore.addFunc("explain", [](ScriptAuthorityStore* value, const std::string& actor, const std::string& scope,
749 ownedStore.addFunc("queryCapability", [](ScriptAuthorityStore* value, const std::string& capability) {
753 ownedStore.addFunc("query", [](ScriptAuthorityStore* value, const std::string& actor, const std::string& scope,
The single Squirrel projection for common Result, Status and Value.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Definition Diagnostic.cpp:21
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Result< void > add(LogicalId schema, SchemaVersion from, SchemaVersion to, Migration migration)
Register one schema-local migration edge.
Definition Snapshot.cpp:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
Script module factory for generic authority stores.
Definition Authority.h:286
static eve::Result< void > release(AuthorityStoreHandleRef reference)
Releases a module-owned store.
Definition Authority.cpp:503
static eve::Result< AuthorityStoreHandleRef > newStore()
Allocates an authority store and returns its ownership reference.
Definition Authority.cpp:492
static bool isStale(AuthorityStoreHandleRef reference) noexcept
Reports whether a store reference is stale for the current module.
Definition Authority.cpp:512
static eve::script::Borrowed< Store > resolve(AuthorityStoreHandleRef reference) noexcept
Resolves a live store as a non-owning observation.
Definition Authority.cpp:497
const Rule * queryAt(int index) const
Returns a rule from the latest query, or nullptr. @ownership Borrowed from this store; callers must n...
Definition Authority.cpp:338
Store(eve::PersistentId instanceId={})
Creates an authority store with an optional persistent identity.
Definition Authority.cpp:111
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.
Definition Authority.cpp:231
void update(double dtSeconds)
Advances finite rule durations and expires rules reaching zero.
Definition Authority.cpp:280
eve::Result< void > restoreSnapshot(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Restores a verified or migratable snapshot transactionally.
Definition Authority.cpp:450
int revokeBySource(const std::string &source, const std::string &reason="source_revoked")
Revokes every rule from a source and returns the number removed.
Definition Authority.cpp:264
int queryScope(const std::string &scope)
Queries rules for a scope in deterministic creation order.
Definition Authority.cpp:336
eve::Result< void > setEventCapacity(int capacity)
Sets the maximum number of retained lifecycle events.
Definition Authority.cpp:342
int revokeByCapability(const std::string &capability, const std::string &reason="capability_revoked")
Revokes every rule whose capability field equals capability.
Definition Authority.cpp:276
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.
Definition Authority.cpp:227
eve::Result< void > revoke(const std::string &id, const std::string &reason="revoked")
Revokes a rule by stable ID.
Definition Authority.cpp:236
eve::Result< std::string > snapshotEnvelopeJson(const eve::SnapshotHashProvider &hashProvider) const
Serializes the common snapshot envelope as canonical JSON.
Definition Authority.cpp:479
eve::Result< void > restoreSnapshotJson(std::string_view json, const eve::SnapshotHashProvider &hashProvider)
Parses and transactionally restores a common snapshot envelope.
Definition Authority.cpp:486
int query(const std::string &actor, const std::string &scope, const std::string &capability)
Queries rules matching actor, scope, and capability.
Definition Authority.cpp:325
void clearEvents()
Clears retained events without resetting sequence allocation.
Definition Authority.cpp:357
const Event * eventAt(int index) const
Returns a retained event, or nullptr. @ownership Borrowed from this store's retained event deque....
Definition Authority.cpp:354
int queryActor(const std::string &actor)
Queries rules for an actor in deterministic creation order.
Definition Authority.cpp:335
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...
Definition Authority.cpp:320
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...
Definition Authority.cpp:317
int revokeByScope(const std::string &scope, const std::string &reason="scope_revoked")
Revokes every rule whose scope field equals scope.
Definition Authority.cpp:272
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...
Definition Authority.cpp:302
eve::Result< eve::SnapshotEnvelope > snapshot(const eve::SnapshotHashProvider &hashProvider) const
Captures this store in the common versioned snapshot envelope.
Definition Authority.cpp:443
eve::Result< void > restoreJson(const std::string &json)
Transactionally restores a snapshot produced by snapshotJson().
Definition Authority.cpp:382
int revokeByActor(const std::string &actor, const std::string &reason="actor_revoked")
Revokes every rule whose actor field equals actor.
Definition Authority.cpp:268
int queryCapability(const std::string &capability)
Queries rules for a capability in deterministic creation order.
Definition Authority.cpp:337
std::string snapshotJson() const
Exports persistent state as deterministic compact JSON.
Definition Authority.cpp:364
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
Non-owning observation of a registry-owned object.
Definition RuntimeBorrow.h:27
Definition Authority.cpp:15
std::string effectName(RuleEffect effect)
Returns the stable lowercase name of a rule effect.
Definition Authority.cpp:113
eve::script::RuntimeHandleRef< AuthorityStoreHandleTag > AuthorityStoreHandleRef
Generation- and module-epoch-qualified authority store reference.
Definition Authority.h:24
@ Expired
@ Granted
@ Revoked
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.
Definition Authority.cpp:114
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)
Definition ProcgenScriptSupport.h:200
@ Borrowed
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
Definition SquirrelBinding.cpp:524
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Definition SquirrelBinding.cpp:540
@ Decision
@ InvalidArgument
@ NotFound
@ InvariantViolation
@ ParseError
@ StaleHandle
@ Conflict
Result< void > validateSnapshotPayloadMetadata(const Value &payload, Revision revision, SimulationTick tick)
Validate optional payload copies of envelope revision and tick.
Definition Snapshot.cpp:80
@ Applied
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
Definition Container.h:602
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
Deterministically sequenced authority lifecycle event.
Definition Authority.h:64
One stable authority rule over an opaque actor and scope.
Definition Authority.h:38
Handle plus owner-lifetime epoch for a non-ECS registry object.
Definition RuntimeBorrow.h:72
constexpr bool isValid() const noexcept
Returns whether both the handle and its registry epoch are set.
Definition RuntimeBorrow.h:77