载入中...
搜索中...
未找到
FactStore.cpp
浏览该文件的文档.
2
4#include "common/Diagnostic.h"
5
6#include <set>
7#include <utility>
8
9namespace eve::emergence {
10namespace {
11
12const char* domainPrefix(FactDomain domain) {
13 switch (domain) {
14 case FactDomain::Value: return "value:";
15 case FactDomain::Tag: return "tag:";
16 case FactDomain::Attribute: return "attr:";
17 case FactDomain::Resource: return "resource:";
18 case FactDomain::State: return "state:";
19 case FactDomain::Authority: return "authority:";
20 case FactDomain::Policy: return "policy:";
21 }
22 return "value:";
23}
24
25const eve::Value* field(const eve::Value::Object& object, std::string_view name) {
26 const auto it = object.find(std::string(name));
27 return it == object.end() ? nullptr : &it->second;
28}
29
30bool exactFields(const eve::Value::Object& object, std::initializer_list<std::string_view> allowed) {
31 const std::set<std::string_view> fields(allowed.begin(), allowed.end());
32 for (const auto& [name, unused] : object) {
33 (void)unused;
34 if (!fields.contains(name)) return false;
35 }
36 return true;
37}
38
39eve::Result<condition::ConditionReasonCode> parseReasonCode(std::string_view text) {
41 static const std::pair<std::string_view, R> names[] = {
42 {"passed", R::Passed},
43 {"child_failed", R::ChildFailed},
44 {"no_child_passed", R::NoChildPassed},
45 {"negated", R::Negated},
46 {"missing_value", R::MissingValue},
47 {"value_mismatch", R::ValueMismatch},
48 {"tag_missing", R::TagMissing},
49 {"tag_unavailable", R::TagUnavailable},
50 {"attribute_missing", R::AttributeMissing},
51 {"resource_missing", R::ResourceMissing},
52 {"state_missing", R::StateMissing},
53 {"state_mismatch", R::StateMismatch},
54 {"authority_denied", R::AuthorityDenied},
55 {"authority_unavailable", R::AuthorityUnavailable},
56 {"policy_rejected", R::PolicyRejected},
57 {"policy_unavailable", R::PolicyUnavailable},
58 {"invalid_condition", R::InvalidCondition},
59 };
60 for (const auto& [name, code] : names) {
62 }
64 eve::DiagnosticCode::InvalidArgument, "unknown condition reason code", "reason", {}, "emergence.fact"));
65}
66
68 const auto* object = value.getIf<eve::Value::Object>();
69 if (object == nullptr)
71 eve::DiagnosticCode::InvalidArgument, "policy result must be an object", {}, {}, "emergence.fact"));
72 if (!exactFields(*object, {"passed", "reason", "evidence", "details"}))
74 eve::DiagnosticCode::InvalidArgument, "policy result contains an unknown field", {}, {}, "emergence.fact"));
75 const auto* passed = field(*object, "passed");
76 const auto* reason = field(*object, "reason");
77 if (passed == nullptr || !passed->isBool())
79 eve::DiagnosticCode::InvalidArgument, "policy passed must be a boolean", "passed", {}, "emergence.fact"));
80 if (reason == nullptr || !reason->isString())
82 eve::DiagnosticCode::InvalidArgument, "policy reason must be a string", "reason", {}, "emergence.fact"));
83 auto code = parseReasonCode(reason->asString());
87 if (const auto* evidenceValue = field(*object, "evidence")) evidence = *evidenceValue;
88 if (const auto* detailsValue = field(*object, "details")) details = *detailsValue;
89 if (passed->asBool())
91 condition::ConditionResult::success(std::move(evidence), std::move(details)));
93 condition::ConditionResult::failed(code.value(), std::move(evidence), std::move(details)));
94}
95
96eve::Value encodePolicyResult(const condition::ConditionResult& result) {
98 object.emplace("passed", eve::Value(result.passed()));
99 object.emplace("reason", eve::Value(condition::conditionReasonCodeName(result.reasonCode())));
100 object.emplace("evidence", result.evidence());
101 object.emplace("details", result.details());
102 return eve::Value(std::move(object));
103}
104
105} // namespace
106
107std::string makeFactKey(FactDomain domain, std::string_view name) {
108 if (name.empty()) return {};
109 std::string key(domainPrefix(domain));
110 key.append(name);
111 return key;
112}
113
115 const auto fail = [](const char* message) {
118 };
119 if (key.empty()) return fail("fact key must be non-empty");
120 const auto slash = key.find(':');
121 if (slash == std::string_view::npos || slash == 0 || slash + 1 >= key.size())
122 return fail("fact key must use domain:name form");
123 const auto domainText = key.substr(0, slash);
124 const auto name = key.substr(slash + 1);
126 if (domainText == "value")
128 else if (domainText == "tag")
130 else if (domainText == "attr")
132 else if (domainText == "resource")
134 else if (domainText == "state")
136 else if (domainText == "authority")
138 else if (domainText == "policy")
140 else
141 return fail("unknown fact domain prefix");
142 return eve::Result<std::pair<FactDomain, std::string>>::success(std::make_pair(domain, std::string(name)));
143}
144
145template <class Map, class T>
146FactChange FactStore::assign(Map& map, std::string key, T value) {
147 auto it = map.find(key);
148 if (it != map.end()) {
149 if (it->second == value) return FactChange::Unchanged;
150 it->second = std::move(value);
151 return FactChange::Changed;
152 }
153 map.emplace(std::move(key), std::move(value));
154 return FactChange::Changed;
155}
156
158 values_.clear();
159 tags_.clear();
160 attributes_.clear();
161 resources_.clear();
162 states_.clear();
163 authorities_.clear();
164 policies_.clear();
165}
166
168 if (key.empty()) return FactChange::Unchanged;
169 return assign(values_, std::move(key), std::move(value));
170}
171
173 if (tag.empty()) return FactChange::Unchanged;
174 return assign(tags_, std::move(tag), present);
175}
176
178 if (key.empty()) return FactChange::Unchanged;
179 return assign(attributes_, std::move(key), std::move(value));
180}
181
183 if (key.empty()) return FactChange::Unchanged;
184 return assign(resources_, std::move(key), std::move(value));
185}
186
188 if (key.empty()) return FactChange::Unchanged;
189 return assign(states_, std::move(key), std::move(value));
190}
191
192FactChange FactStore::setAuthority(std::string scope, bool granted) {
193 if (scope.empty()) return FactChange::Unchanged;
194 return assign(authorities_, std::move(scope), granted);
195}
196
198 if (name.empty()) return FactChange::Unchanged;
199 auto it = policies_.find(name);
200 if (it != policies_.end()) {
201 if (it->second.passed() == result.passed() && it->second.reasonCode() == result.reasonCode() &&
202 it->second.evidence() == result.evidence())
204 it->second = std::move(result);
205 return FactChange::Changed;
206 }
207 policies_.emplace(std::move(name), std::move(result));
208 return FactChange::Changed;
209}
210
212 return values_.erase(std::string(key)) > 0 ? FactChange::Changed : FactChange::Unchanged;
213}
214
216 return tags_.erase(std::string(tag)) > 0 ? FactChange::Changed : FactChange::Unchanged;
217}
218
219std::optional<eve::Value> FactStore::value(std::string_view key) const {
221 auto it = tags_.find(std::string(*tag));
222 return it == tags_.end() ? std::nullopt : std::optional<eve::Value>(eve::Value(it->second));
223 }
225 auto it = attributes_.find(std::string(*attr));
226 return it == attributes_.end() ? std::nullopt : std::optional<eve::Value>(it->second);
227 }
229 auto it = resources_.find(std::string(*resource));
230 return it == resources_.end() ? std::nullopt : std::optional<eve::Value>(it->second);
231 }
233 auto it = states_.find(std::string(*state));
234 return it == states_.end() ? std::nullopt : std::optional<eve::Value>(it->second);
235 }
236 auto it = values_.find(std::string(key));
237 return it == values_.end() ? std::nullopt : std::optional<eve::Value>(it->second);
238}
239
240std::optional<condition::ConditionResult> FactStore::policy(std::string_view name, const eve::Value& arguments) const {
241 if (auto authority = condition::resolveAuthorityAllow(name, arguments, [this](std::string_view scope) {
242 auto it = authorities_.find(std::string(scope));
243 return it == authorities_.end() ? std::nullopt : std::optional<bool>(it->second);
244 })) {
245 return authority;
246 }
247 auto it = policies_.find(std::string(name));
248 return it == policies_.end() ? std::nullopt : std::optional<condition::ConditionResult>(it->second);
249}
250
251std::string FactStore::snapshotJson() const {
254 for (const auto& [key, value] : values_) values.emplace(key, value);
256 for (const auto& [key, value] : tags_) tags.emplace(key, eve::Value(value));
258 for (const auto& [key, value] : attributes_) attributes.emplace(key, value);
260 for (const auto& [key, value] : resources_) resources.emplace(key, value);
261 eve::Value::Object states;
262 for (const auto& [key, value] : states_) states.emplace(key, value);
263 eve::Value::Object authorities;
264 for (const auto& [key, value] : authorities_) authorities.emplace(key, eve::Value(value));
265 eve::Value::Object policies;
266 for (const auto& [key, value] : policies_) policies.emplace(key, encodePolicyResult(value));
267 root.emplace("schema", eve::Value("eve.emergence.facts"));
268 root.emplace("version", eve::Value(std::int64_t{1}));
269 root.emplace("values", eve::Value(std::move(values)));
270 root.emplace("tags", eve::Value(std::move(tags)));
271 root.emplace("attributes", eve::Value(std::move(attributes)));
272 root.emplace("resources", eve::Value(std::move(resources)));
273 root.emplace("states", eve::Value(std::move(states)));
274 root.emplace("authorities", eve::Value(std::move(authorities)));
275 root.emplace("policies", eve::Value(std::move(policies)));
276 auto encoded = eve::Value(std::move(root)).toJson();
277 return encoded ? std::move(encoded).takeValue() : std::string("{}");
278}
279
281 auto parsed = eve::Value::fromJson(json);
282 if (!parsed) return eve::Result<void>::failure(parsed.status());
283 const auto* object = parsed.value().getIf<eve::Value::Object>();
284 if (object == nullptr)
286 eve::DiagnosticCode::InvalidArgument, "fact snapshot must be an object", {}, {}, "emergence.fact"));
287 if (!exactFields(*object, {"schema", "version", "values", "tags", "attributes", "resources", "states",
288 "authorities", "policies"}))
290 eve::DiagnosticCode::InvalidArgument, "fact snapshot contains an unknown field", {}, {}, "emergence.fact"));
291 const auto* schema = field(*object, "schema");
292 const auto* version = field(*object, "version");
293 if (schema == nullptr || !schema->isString() || schema->asString() != "eve.emergence.facts")
295 eve::DiagnosticCode::InvalidArgument, "unexpected fact snapshot schema", "schema", {}, "emergence.fact"));
296 if (version == nullptr || !version->isInt64() || version->asInt() != 1)
298 eve::DiagnosticCode::UnknownVersion, "unsupported fact snapshot version", "version", {}, "emergence.fact"));
299
300 FactStore next;
301 auto loadObject = [&](const char* fieldName, auto&& setter) -> eve::Result<void> {
302 const auto it = object->find(fieldName);
303 if (it == object->end()) return eve::Result<void>::success();
304 const auto* map = it->second.getIf<eve::Value::Object>();
305 if (map == nullptr)
307 eve::DiagnosticCode::InvalidArgument, "fact field must be an object", fieldName, {}, "emergence.fact"));
308 for (const auto& [key, value] : *map) {
309 if (!setter(next, key, value))
311 eve::DiagnosticCode::InvalidArgument, "invalid fact entry", fieldName, {}, "emergence.fact"));
312 }
314 };
315
316 if (auto r = loadObject("values",
317 [](FactStore& store, const std::string& key, const eve::Value& value) {
318 (void)store.setValue(key, value);
319 return true;
320 });
321 !r)
322 return r;
323 if (auto r = loadObject("tags",
324 [](FactStore& store, const std::string& key, const eve::Value& value) {
325 if (!value.isBool()) return false;
326 (void)store.setTag(key, value.asBool());
327 return true;
328 });
329 !r)
330 return r;
331 if (auto r = loadObject("attributes",
332 [](FactStore& store, const std::string& key, const eve::Value& value) {
333 (void)store.setAttribute(key, value);
334 return true;
335 });
336 !r)
337 return r;
338 if (auto r = loadObject("resources",
339 [](FactStore& store, const std::string& key, const eve::Value& value) {
340 (void)store.setResource(key, value);
341 return true;
342 });
343 !r)
344 return r;
345 if (auto r = loadObject("states",
346 [](FactStore& store, const std::string& key, const eve::Value& value) {
347 (void)store.setState(key, value);
348 return true;
349 });
350 !r)
351 return r;
352 if (auto r = loadObject("authorities",
353 [](FactStore& store, const std::string& key, const eve::Value& value) {
354 if (!value.isBool()) return false;
355 (void)store.setAuthority(key, value.asBool());
356 return true;
357 });
358 !r)
359 return r;
360 if (auto r = loadObject("policies",
361 [](FactStore& store, const std::string& key, const eve::Value& value) {
362 auto decoded = decodePolicyResult(value);
363 if (!decoded) return false;
364 (void)store.setPolicy(key, std::move(decoded).takeValue());
365 return true;
366 });
367 !r)
368 return r;
369
370 *this = std::move(next);
372}
373
374} // namespace eve::emergence
int root
Definition AnimSmr.cpp:119
Canonical Compare key prefixes and PolicyCall names for thin conditions.
Stable, structured diagnostics shared by engine modules.
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
bool passed
Authoritative, rule-visible world facts implementing EvaluationContext.
std::string message
DiagnosticCode code
double r
JobScope scope
bool present
std::string evidence
Poco::JSON::Object::Ptr result
std::unordered_set< std::string > tags
const std::string * tag
std::vector< std::weak_ptr< DeviceBytes > > resources
Definition OnnxGpgpu.cpp:55
std::set< std::string > values
Object::Ptr value
std::string domain
std::map< std::string, double > attributes
std::string text
std::string resource
Json object
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
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
Result< std::string > toJson() const
Serialize this value as deterministic compact JSON.
Definition Value.cpp:187
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
Explain one condition evaluation in a UI- and log-friendly form.
Definition Condition.h:137
static ConditionResult success(Value evidence={}, Value details=Value::Object{})
Construct a passed result with optional evidence and details.
static ConditionResult failed(ConditionReasonCode reason, Value evidence={}, Value details=Value::Object{})
Construct a rejected result with a stable reason and explanation.
Mutable fact bag that doubles as a read-only Condition evaluation context.
Definition FactStore.h:60
std::string snapshotJson() const
Export deterministic compact JSON for runtime snapshots.
eve::Result< void > restoreJson(std::string_view json)
Transactionally restore facts from a snapshot produced by snapshotJson().
std::optional< condition::ConditionResult > policy(std::string_view name, const eve::Value &arguments) const override
Evaluate a named read-only policy with owned arguments.
FactChange setValue(std::string key, eve::Value value)
Set a compare/value fact.
FactChange setTag(std::string tag, bool present)
Set tag membership; present=true means the tag exists.
FactChange setState(std::string key, eve::Value value)
Set a state value.
FactChange setAttribute(std::string key, eve::Value value)
Set an attribute value.
void clear()
Clear every fact without invoking callbacks.
FactChange setPolicy(std::string name, condition::ConditionResult result)
Register or replace a read-only policy result.
FactChange clearTag(std::string_view tag)
Erase a tag fact.
FactChange setAuthority(std::string scope, bool granted)
Set authority for a scope.
FactChange setResource(std::string key, eve::Value value)
Set a resource value.
std::optional< eve::Value > value(std::string_view key) const override
Query a named scalar or structured value for Compare nodes.
FactChange clearValue(std::string_view key)
Erase a value fact.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
ConditionReasonCode
Stable machine-readable explanation code for a condition outcome.
Definition Condition.h:82
constexpr std::string_view kResourcePrefix
Prefix for resource values (resource:<name>).
constexpr std::string_view kStatePrefix
Prefix for state values (state:<name>).
const char * conditionReasonCodeName(ConditionReasonCode code) noexcept
Return the stable lowercase spelling of a condition reason code. @ownership Borrowed process-static t...
Definition Condition.cpp:84
constexpr std::string_view kTagPrefix
Prefix for tag membership booleans (tag:<name>).
std::optional< ConditionResult > resolveAuthorityAllow(std::string_view name, const Value &arguments, AuthorityQuery &&authorityQuery)
Resolve the built-in authority.allow policy when name matches.
std::optional< std::string_view > stripPrefix(std::string_view key, std::string_view prefix)
Strip a known domain prefix from a key.
constexpr std::string_view kAttrPrefix
Prefix for attribute values (attr:<name>).
FactChange
Whether a FactStore mutation changed stored state.
Definition FactStore.h:34
FactDomain
Domain partition of a fact key used by the watch index.
Definition FactStore.h:23
eve::Result< std::pair< FactDomain, std::string > > parseFactKey(std::string_view key)
Parse a canonical watch key into domain and leaf name.
std::string makeFactKey(FactDomain domain, std::string_view name)
Build the canonical watch key for one fact domain.