载入中...
搜索中...
未找到
PolicyRegistry.cpp
浏览该文件的文档.
39 if (!number || *number < std::numeric_limits<int>::min() || *number > std::numeric_limits<int>::max()) return false;
83eve::Result<PolicyDescriptor> makeDescriptor(const std::string& domain, const std::string& name, int version,
88 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "policy domain and name must not be empty"));
91 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "policy schema version must be positive"));
103 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "policy metadata must be a JSON object"));
114 {"schemaId", schemaId}, {"schemaVersion", std::to_string(version)}, {"validationCode", error.code}},
177 : storage_([](PolicyDescriptor& value, eve::Generation generation) { value.generation = generation; }),
209eve::Result<PolicyHandle> PolicyRegistry::insert(const std::string& domain, const std::string& name, int version,
212 auto descriptor = makeDescriptor(domain, name, version, priority, enabled, kind, schemaId, metadataJson);
229eve::Result<PolicyHandle> PolicyRegistry::replace(const std::string& domain, const std::string& name, int version,
232 auto descriptor = makeDescriptor(domain, name, version, priority, enabled, kind, schemaId, metadataJson);
249eve::Result<PolicyHandle> PolicyRegistry::remove(const std::string& domain, const std::string& name) {
268eve::Result<PolicyHandle> PolicyRegistry::enable(const std::string& domain, const std::string& name, bool enabled) {
309eve::Result<PolicyHandle> PolicyRegistry::handle(const std::string& domain, const std::string& name) const {
315eve::Result<eve::Generation> PolicyRegistry::generationOf(const std::string& domain, const std::string& name) const {
319bool PolicyRegistry::isTombstone(const std::string& domain, const std::string& name) const noexcept {
462 const auto* descriptorArray = descriptorValue ? descriptorValue->getIf<eve::Value::Array>() : nullptr;
463 const auto* generationArray = generationValue ? generationValue->getIf<eve::Value::Array>() : nullptr;
466 if (!versionNumber || *versionNumber != 1 || !descriptorArray || !generationArray || !eventArray ||
467 !nextSequenceValue || !readUint64String(*nextSequenceValue, nextSequence) || nextSequence == 0) {
479 if (!item || !readString(*item, "domain", domain) || !readString(*item, "name", name) || domain.empty() ||
480 name.empty() || !generationField || !readUint64String(*generationField, generation) || generation == 0 ||
481 !candidate.entries.emplace(Key{domain, name}, Storage::Entry{eve::Generation(generation), std::nullopt})
484 eve::DiagnosticCode::ParseError, "invalid policy generation at index " + std::to_string(index)));
504 if (!item || !readString(*item, "domain", domain) || !readString(*item, "name", name) || domain.empty() ||
505 name.empty() || !versionField || !readPositiveSchemaVersion(*versionField, version) || !priorityField ||
506 !readInt(*priorityField, priority) || !enabledField || !enabledField->isBool() || !generationField ||
508 !readString(*item, "kind", kindName) || !parseImplementationKind(kindName, kind) || !metadata ||
511 eve::DiagnosticCode::ParseError, "invalid policy descriptor at index " + std::to_string(index)));
515 if (entry == candidate.entries.end() || entry->second.generation != eve::Generation(generation) ||
556 (!previousSequence.isZero() && eve::EventSequence(sequence) <= previousSequence) || !generationField ||
564 eve::DiagnosticCode::ParseError, "invalid policy event version at index " + std::to_string(index)));
596eve::Result<eve::SnapshotEnvelope> PolicyRegistry::snapshot(const eve::SnapshotHashProvider& hashProvider) const {
599 return eve::makeSnapshotEnvelope("policyregistry.registry", policySchema(), eve::SchemaVersion(1), instanceId_,
607 eve::DiagnosticCode::InvalidArgument, "snapshot does not belong to policyregistry::PolicyRegistry"));
610 eve::DiagnosticCode::Conflict, "snapshot instanceId does not match policyregistry::PolicyRegistry"));
624eve::Result<std::string> PolicyRegistry::snapshotEnvelopeJson(const eve::SnapshotHashProvider& hashProvider) const {
656 "PolicyDescriptor", std::function<PolicyDescriptor*()>([]() -> PolicyDescriptor* { return nullptr; }), false);
657 descriptor.addFunc("getDomain", [](PolicyDescriptor* v) { return v ? v->domain : std::string{}; });
666 descriptor.addFunc("getSchemaId", [](PolicyDescriptor* v) { return v ? v->schemaId : std::string{}; });
667 descriptor.addFunc("getMetadataJson", [](PolicyDescriptor* v) { return v ? v->metadataJson : std::string{}; });
675 [](PolicyEvent* v) { return v ? static_cast<std::int64_t>(v->sequence.value()) : std::int64_t{0}; });
678 event.addFunc("getPolicyName", [](PolicyEvent* v) { return v ? v->policyName : std::string{}; });
680 [](PolicyEvent* v) { return v ? static_cast<std::int64_t>(v->version.value()) : std::int64_t{0}; });
687 "PolicyRegistry", std::function<PolicyRegistry*()>([]() -> PolicyRegistry* { return nullptr; }), false);
688 registry.addFunc("insert", [vm](PolicyRegistry* value, const std::string& domain, const std::string& policyName,
699 vm, value->insert(domain, policyName, version, priority, enabled, kind, schemaId, metadataJson),
702 registry.addFunc("replace", [vm](PolicyRegistry* value, const std::string& domain, const std::string& policyName,
713 vm, value->replace(domain, policyName, version, priority, enabled, kind, schemaId, metadataJson),
716 registry.addFunc("remove", [vm](PolicyRegistry* value, const std::string& domain, const std::string& policyName) {
728 "enable", [vm](PolicyRegistry* value, const std::string& domain, const std::string& policyName, bool enabled) {
739 registry.addFunc("resolve", [vm](PolicyRegistry* value, const std::string& domain, const std::string& policyName) {
744 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "policy registry must not be null",
760 eve::Result<DescriptorRef>::failure(eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument,
767 eve::Result<DescriptorRef>::failure(eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument,
777 registry.addFunc("handle", [vm](PolicyRegistry* value, const std::string& domain, const std::string& policyName) {
796 registry.addFunc("atDomain", [](PolicyRegistry* v, const std::string& d, int i) -> PolicyDescriptor* {
818 eve::Result<eve::Generation>::failure(eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument,
821 [](eve::Generation generation) { return eve::Value(static_cast<std::int64_t>(generation.value())); });
822 return eve::script::projectResult(vm, value->generationOf(domain, policyName), [](eve::Generation generation) {
std::unordered_map< std::string, std::unordered_map< std::string, std::uint64_t > > generations
Definition CapabilityOwned.cpp:9
The single Squirrel projection for common Result, Status and Value.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={}, DiagnosticDetails details={}, std::string source={})
Construct an error diagnostic with the standard error severity.
Definition Diagnostic.h:125
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:411
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:36
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:175
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.h:81
Move-only RAII token that owns one observer registration.
Definition Subscription.h:27
Result< std::string > toJson() const
Serialize this value as deterministic compact JSON.
Definition Value.cpp:67
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:57
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:180
const Key * keyAt(std::size_t index) const noexcept
Returns the key for a live enumeration index, or nullptr.
Definition VersionedRegistry.h:385
ResultRef< const Value > resolve(const Key &key) const
Resolves a live key to a borrowed value.
Definition VersionedRegistry.h:277
std::size_t size() const noexcept
Number of live values, excluding tombstones.
Definition VersionedRegistry.h:341
Result< Handle > replace(Key key, Value value, EventData data={}, std::string label={})
Replaces an existing live value and invalidates its old handle.
Definition VersionedRegistry.h:240
void clearEvents() noexcept
Clears retained events without changing entries or sequence monotonicity.
Definition VersionedRegistry.h:410
Result< Handle > handle(const Key &key) const
Returns the current live handle for a key.
Definition VersionedRegistry.h:302
Result< void > restoreState(State candidate)
Transactionally replaces all registry state from an owning image.
Definition VersionedRegistry.h:423
const Value * at(std::size_t index) const noexcept
Returns a live value by deterministic key order.
Definition VersionedRegistry.h:368
Subscription subscribe(ChangeCallback callback)
Subscribes to successful insert, replace and remove events.
Definition VersionedRegistry.h:461
Result< Generation > generationOf(const Key &key) const
Returns the latest generation for a live key or tombstone.
Definition VersionedRegistry.h:313
Result< Handle > insert(Key key, Value value, EventData data={}, std::string label={})
Inserts a new live value, or revives a tombstoned key.
Definition VersionedRegistry.h:219
Result< Handle > remove(Key key, EventData data={}, std::string label={})
Removes a live value while retaining its generation tombstone.
Definition VersionedRegistry.h:260
const Event * eventAt(std::size_t index) const noexcept
Returns a retained event by insertion sequence order, or nullptr.
Definition VersionedRegistry.h:402
State snapshotState() const
Takes an owning copy of live entries, tombstones and event history.
Definition VersionedRegistry.h:413
std::size_t eventCount() const noexcept
Number of retained mutation events.
Definition VersionedRegistry.h:407
constexpr bool isNil() const noexcept
Returns whether this value is the all-zero nil ID.
Definition Identity.h:176
constexpr std::optional< StrongUint64 > incremented() const noexcept
Returns the next value, or empty instead of unsigned wraparound.
Definition StrongUint64.h:30
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
Definition StrongUint64.h:26
constexpr bool isZero() const noexcept
Returns whether this value is zero.
Definition StrongUint64.h:28
Script module factory for independent policy registries.
Definition PolicyRegistry.h:154
PolicyRegistry * newRegistry()
Allocates a module-owned policy registry.
Definition PolicyRegistry.cpp:646
Deterministic registry for discoverable, non-executable policy descriptions.
Definition PolicyRegistry.h:55
eve::Subscription subscribe(std::function< void(const PolicyEvent &)> callback)
Subscribes to successful registry mutations.
Definition PolicyRegistry.cpp:638
eve::ResultRef< const PolicyDescriptor > resolve(const std::string &domain, const std::string &name) const
Resolves a descriptor through the common checked-registry API.
Definition PolicyRegistry.cpp:296
const PolicyDescriptor * atDomain(const std::string &domain, int index) const
Returns a live descriptor in lexical name order within a domain.
Definition PolicyRegistry.cpp:359
eve::Result< PolicyHandle > replace(const std::string &domain, const std::string &name, int version, int priority, bool enabled, const std::string &kind, const std::string &schemaId, const std::string &metadataJson)
Replaces a descriptor and invalidates the prior generation handle.
Definition PolicyRegistry.cpp:229
eve::Result< void > restoreSnapshotJson(std::string_view json, const eve::SnapshotHashProvider &hashProvider)
Parses and transactionally restores a common snapshot envelope.
Definition PolicyRegistry.cpp:631
int countDomain(const std::string &domain) const
Returns live descriptor count in a domain.
Definition PolicyRegistry.cpp:344
const PolicyDescriptor * select(const std::string &domain) const
Selects the enabled highest-priority policy, breaking ties by lexical name.
Definition PolicyRegistry.cpp:327
eve::Result< std::string > snapshotEnvelopeJson(const eve::SnapshotHashProvider &hashProvider) const
Serializes the common snapshot envelope as canonical JSON.
Definition PolicyRegistry.cpp:624
eve::Result< PolicyHandle > handle(const std::string &domain, const std::string &name) const
Returns the current generation-qualified handle through Result.
Definition PolicyRegistry.cpp:309
eve::Result< PolicyHandle > enable(const std::string &domain, const std::string &name, bool enabled)
Changes enabled state through the same replacement generation path.
Definition PolicyRegistry.cpp:268
eve::Result< void > restoreJson(const std::string &json)
Transactionally restores state from the registry snapshot.
Definition PolicyRegistry.cpp:445
bool isTombstone(const std::string &domain, const std::string &name) const noexcept
Returns whether a key is retained as a removal tombstone.
Definition PolicyRegistry.cpp:319
eve::Result< eve::SnapshotEnvelope > snapshot(const eve::SnapshotHashProvider &hashProvider) const
Captures this registry in the common snapshot envelope.
Definition PolicyRegistry.cpp:596
eve::Result< PolicyHandle > insert(const std::string &domain, const std::string &name, int version, int priority, bool enabled, const std::string &kind, const std::string &schemaId, const std::string &metadataJson)
Inserts a descriptor through the common checked registry.
Definition PolicyRegistry.cpp:209
eve::ResultRef< const PolicyDescriptor > resolveHandle(const PolicyHandle &handle) const
Resolves a generation-qualified policy handle through Result.
Definition PolicyRegistry.cpp:303
void clearEvents()
Clears events without resetting the sequence allocator.
Definition PolicyRegistry.cpp:384
const PolicyDescriptor * at(int index) const
Returns a live descriptor in globally sorted domain/name order.
Definition PolicyRegistry.cpp:354
eve::Result< eve::Generation > generationOf(const std::string &domain, const std::string &name) const
Returns the latest generation, including a retained tombstone.
Definition PolicyRegistry.cpp:315
bool isStale(const PolicyHandle &handle) const noexcept
Returns whether a generation-qualified policy handle is stale.
Definition PolicyRegistry.cpp:323
eve::Result< void > restoreSnapshot(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Restores a verified snapshot transactionally without per-item events.
Definition PolicyRegistry.cpp:603
eve::Result< PolicyHandle > remove(const std::string &domain, const std::string &name)
Removes a descriptor and returns its retained tombstone handle.
Definition PolicyRegistry.cpp:249
const PolicyEvent * eventAt(int index) const
Returns a retained event by sequence order.
Definition PolicyRegistry.cpp:373
std::string snapshotJson() const
Exports registry state as deterministic JSON.
Definition PolicyRegistry.cpp:390
static std::vector< ValidationError > validate(const std::string &schemaId, const std::string &json)
Validates JSON text against the highest registered schema version.
Definition SchemaRegistry.cpp:955
static const SchemaDefinition * resolve(const std::string &schemaId, int schemaVersion)
Resolves one exact (schemaId, schemaVersion) pair, or nullptr.
Definition SchemaRegistry.cpp:879
Definition PolicyRegistry.cpp:14
ImplementationKind
Implementation category advertised by a policy descriptor.
Definition PolicyRegistry.h:20
std::string implementationKindName(ImplementationKind kind)
Returns the stable lowercase implementation kind name.
Definition PolicyRegistry.cpp:155
bool parseImplementationKind(const std::string &name, ImplementationKind &kind)
Parses a stable lowercase implementation kind name.
Definition PolicyRegistry.cpp:164
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Definition SquirrelBinding.cpp:470
std::vector< DiagnosticDetail > DiagnosticDetails
Owning collection of diagnostic details with stable insertion order.
Definition Diagnostic.h:88
@ InvalidArgument
@ InvariantViolation
@ ParseError
@ Conflict
detail::StrongUint64< detail::GenerationTag > Generation
Registry/object replacement generation used to reject stale handles.
Definition Generation.h:13
@ NoOp
@ 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
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
Definition SchemaVersion.h:13
Result< std::string > serializeSnapshotEnvelope(const SnapshotEnvelope &snapshot)
Serialize an envelope as deterministic compact JSON.
Definition Snapshot.cpp:184
@ Replace
@ Remove
@ Insert
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
detail::StrongUint64< detail::EventSequenceTag > EventSequence
Stream-local event ordering value; it is not a global event identity.
Definition EventSequence.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
Discoverable policy description without an executable callback.
Definition PolicyRegistry.h:30
Deterministically sequenced policy registry mutation event.
Definition PolicyRegistry.h:44
Generation-qualified policy handle used to detect replacement or removal.
Definition PolicyRegistry.h:23