载入中...
搜索中...
未找到
EvpackRegistry.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <exception>
4#include <limits>
5#include <new>
6#include <set>
7#include <tuple>
9
10// EvpackRegistry.cpp
11namespace eve::asset {
12namespace {
13
14template <class Entry>
15bool sameGeneration(const EvpackHandle& handle, const Entry& entry) {
16 return handle.generation == entry.generation && handle.buildId == entry.pack->buildId();
17}
18
19std::vector<Diagnostic> dispatchCallbacks(const std::vector<EvpackRegistry::Callback>& callbacks,
20 const EvpackRegistryEvent& event) {
21 std::vector<Diagnostic> diagnostics;
22 for (const auto& callback : callbacks) {
23 try {
24 auto notified = callback(event);
25 if (!notified && notified.error()) diagnostics.push_back(*notified.error());
26 } catch (const std::exception& error) {
28 "registry callback threw: " + std::string(error.what()),
29 event.handle.packageId.format(), {}, "asset.evpack.registry"));
30 } catch (...) {
32 "registry callback threw a non-standard exception",
33 event.handle.packageId.format(), {}, "asset.evpack.registry"));
34 }
35 }
36 return diagnostics;
37}
38
39} // namespace
40
42 const EvpackTrust& trust) {
43 auto parsed = parseEvpack(bytes, limits, trust);
44 if (!parsed) return Result<PreparedEvpackMount>::failure(parsed.status());
45 auto pack = std::make_shared<const Evpack>(std::move(parsed).takeValue());
47}
48
50 if (!callback)
52 DiagnosticCode::InvalidArgument, "registry callback is empty", {}, {}, "asset.evpack.registry"));
53 std::lock_guard lock(mutex_);
54 if (nextSubscription_ == std::numeric_limits<std::uint64_t>::max())
56 Diagnostic::error(DiagnosticCode::InvariantViolation, "registry subscription identity is exhausted", {}, {},
57 "asset.evpack.registry"));
58 const auto id = ++nextSubscription_;
59 callbacks_.emplace(id, std::move(callback));
61}
62
64 if (subscription.value == 0)
66 "registry subscription identity is invalid", {}, {},
67 "asset.evpack.registry"));
68 std::lock_guard lock(mutex_);
69 if (callbacks_.erase(subscription.value) == 0)
70 return Result<void>::failure(Diagnostic::error(DiagnosticCode::NotFound, "registry subscription is not active",
71 {}, {}, "asset.evpack.registry"));
72 return Result<void>::success();
73}
74
76 if (!candidate.pack_)
78 "mount candidate has already been consumed", {},
79 {}, "asset.evpack.registry"));
80 const PersistentId packageId = candidate.pack_->packageId();
81 bool replaced = false;
83 std::vector<Callback> callbacks;
84 {
85 std::lock_guard lock(mutex_);
86 std::set<PersistentId> available;
87 std::set<PersistentId> candidateAssets;
88 for (const auto& chunk : candidate.pack_->chunks()) {
89 available.emplace(chunk.assetId);
90 candidateAssets.emplace(chunk.assetId);
91 }
92 for (const auto& [mountedId, entry] : packages_) {
93 if (mountedId == packageId) continue;
94 for (const auto& chunk : entry.pack->chunks()) {
95 if (candidateAssets.contains(chunk.assetId))
97 DiagnosticCode::Conflict, "runtime asset identity already has another mounted provider",
98 chunk.assetId.format(), {}, "asset.evpack.registry"));
99 available.emplace(chunk.assetId);
100 }
101 }
102 for (const auto& chunk : candidate.pack_->chunks()) {
103 for (const auto& dependency : chunk.dependencies) {
104 if (!available.contains(dependency))
106 Diagnostic::error(DiagnosticCode::NotFound, "required runtime dependency is not mounted",
107 dependency.format(), {}, "asset.evpack.registry"));
108 }
109 }
110 for (const auto& [mountedId, entry] : packages_) {
111 if (mountedId == packageId) continue;
112 for (const auto& chunk : entry.pack->chunks()) {
113 for (const auto& dependency : chunk.dependencies) {
114 if (!available.contains(dependency))
116 DiagnosticCode::NotFound, "replacement would invalidate a mounted package dependency",
117 dependency.format(), {}, "asset.evpack.registry"));
118 }
119 }
120 }
121 replaced = packages_.contains(packageId);
122 std::uint64_t& next = nextGenerations_[packageId];
123 if (next == std::numeric_limits<std::uint64_t>::max())
125 Diagnostic::error(DiagnosticCode::InvariantViolation, "package generation is exhausted",
126 packageId.format(), {}, "asset.evpack.registry"));
127 ++next;
128 auto pack = std::move(candidate.pack_);
129 handle = {packageId, pack->buildId(), next};
130 packages_.insert_or_assign(packageId, Entry{std::move(pack), next});
131 callbacks.reserve(callbacks_.size());
132 for (const auto& [id, callback] : callbacks_) {
133 (void)id;
134 callbacks.push_back(callback);
135 }
136 }
138 handle};
139 auto callbackDiagnostics = dispatchCallbacks(callbacks, event);
140 return Result<EvpackMountReceipt>::success({handle, replaced, std::move(callbackDiagnostics)});
141}
142
144 std::lock_guard lock(mutex_);
145 const auto found = packages_.find(handle.packageId);
146 if (found == packages_.end())
148 Diagnostic::error(DiagnosticCode::NotFound, "runtime package is not mounted", handle.packageId.format(), {},
149 "asset.evpack.registry"));
150 if (!sameGeneration(handle, found->second))
152 Diagnostic::error(DiagnosticCode::StaleHandle, "runtime package handle is stale", handle.packageId.format(),
153 {}, "asset.evpack.registry"));
154 return Result<std::shared_ptr<const Evpack>>::success(found->second.pack);
155}
156
157Result<EvpackAssetHandle> EvpackRegistry::resolveAsset(const AssetRef& assetRef, std::string_view expectedType,
158 const EvpackCapabilities& capabilities) const {
159 if (expectedType.empty())
161 DiagnosticCode::InvalidArgument, "expected runtime asset type is empty", {}, {}, "asset.evpack.registry"));
162 std::lock_guard lock(mutex_);
163 bool identityFound = false;
164 bool typeFound = false;
165 for (const auto& [packageId, entry] : packages_) {
166 const EvpackChunk* representative = nullptr;
167 for (const auto& chunk : entry.pack->chunks()) {
168 if (chunk.assetId != assetRef.id()) continue;
169 identityFound = true;
170 representative = &chunk;
171 const std::string actual = chunk.type + "/" + std::to_string(chunk.schemaVersion.value());
172 if (actual == expectedType)
173 typeFound = true;
174 else
176 DiagnosticCode::TypeMismatch, "runtime asset provider has a different canonical type",
177 assetRef.format(), {}, "asset.evpack.registry"));
178 }
179 if (!representative) continue;
180 auto selected = selectEvpackVariant(*entry.pack, capabilities);
181 if (!selected) continue;
183 {{packageId, entry.pack->buildId(), entry.generation}, assetRef, std::string(expectedType), capabilities});
184 }
185 if (identityFound && typeFound)
187 "asset provider has no compatible variant",
188 assetRef.format(), {}, "asset.evpack.registry"));
190 "runtime asset has no mounted provider",
191 assetRef.format(), {}, "asset.evpack.registry"));
192}
193
195 std::uint64_t maximumDecodedBytes) const {
196 auto pack = resolve(handle.package);
197 if (!pack) return Result<RuntimeAssetPayload>::failure(pack.status());
198 EvpackResourceReader reader(std::move(pack).takeValue());
199 return reader.read(handle.asset, handle.expectedType, handle.capabilities, maximumDecodedBytes);
200}
201
203 std::string_view type, EvpackChunkKind kind,
204 std::uint32_t chunkId, std::uint32_t variantIndex) const {
205 auto resolved = resolve(handle);
207 const auto pack = std::move(resolved).takeValue();
208 for (std::size_t index = 0; index < pack->chunks().size(); ++index) {
209 const auto& chunk = pack->chunks()[index];
210 if (chunk.assetId == assetId && chunk.type == type && chunk.kind == kind && chunk.chunkId == chunkId &&
211 chunk.variantIndex == variantIndex)
212 return Result<EvpackChunkHandle>::success({handle, static_cast<std::uint32_t>(index)});
213 }
215 DiagnosticCode::NotFound, "runtime chunk is not present", assetId.format(), {}, "asset.evpack.registry"));
216}
217
219 auto resolved = resolve(handle.package);
220 if (!resolved) return Result<std::vector<std::uint8_t>>::failure(resolved.status());
221 const auto pack = std::move(resolved).takeValue();
222 if (handle.chunkIndex >= pack->chunks().size())
224 DiagnosticCode::InvalidArgument, "chunk index is outside the TOC", {}, {}, "asset.evpack.registry"));
225 return pack->decodeChunk(handle.chunkIndex, pack->chunks()[handle.chunkIndex].decodedSize);
226}
227
229 std::vector<Callback> callbacks;
230 {
231 std::lock_guard lock(mutex_);
232 const auto found = packages_.find(handle.packageId);
233 if (found == packages_.end())
235 DiagnosticCode::NotFound, "runtime package is not mounted", {}, {}, "asset.evpack.registry"));
236 if (!sameGeneration(handle, found->second))
238 DiagnosticCode::StaleHandle, "runtime package handle is stale", {}, {}, "asset.evpack.registry"));
239 packages_.erase(found);
240 callbacks.reserve(callbacks_.size());
241 for (const auto& [id, callback] : callbacks_) {
242 (void)id;
243 callbacks.push_back(callback);
244 }
245 }
247 auto callbackDiagnostics = dispatchCallbacks(callbacks, event);
248 return Result<EvpackUnmountReceipt>::success({handle, std::move(callbackDiagnostics)});
249}
250
251} // namespace eve::asset
252
253// EvpackResourceReader.cpp
254namespace eve::asset {
255namespace {} // namespace
256
257Result<RuntimeAssetPayload> EvpackResourceReader::read(const AssetRef& asset, std::string_view expectedType,
258 const EvpackCapabilities& capabilities,
259 std::uint64_t maximumDecodedBytes) const {
260 if (!pack_ || asset.id().isNil() || expectedType.empty())
262 "pack, asset and expected type are required", {},
263 {}, "asset.evpack.reader"));
264 auto selected = selectEvpackVariant(*pack_, capabilities);
266 RuntimeAssetPayload result{asset, {}, {}, selected.value(), {}};
267 bool identityFound = false;
268 bool typeFound = false;
269 std::uint64_t decodedTotal = 0;
270 for (std::size_t index = 0; index < pack_->chunks().size(); ++index) {
271 const auto& chunk = pack_->chunks()[index];
272 if (chunk.assetId != asset.id()) continue;
273 identityFound = true;
274 const std::string actualType = chunk.type + "/" + std::to_string(chunk.schemaVersion.value());
275 if (actualType != expectedType) continue;
276 typeFound = true;
277 if (chunk.variantIndex != selected.value().index) continue;
278 if (decodedTotal > maximumDecodedBytes || chunk.decodedSize > maximumDecodedBytes - decodedTotal)
280 "asset payload exceeds decoded budget",
281 asset.format(), {}, "asset.evpack.reader"));
282 auto bytes = pack_->decodeChunk(index, maximumDecodedBytes - decodedTotal);
283 if (!bytes) return Result<RuntimeAssetPayload>::failure(bytes.status());
284 decodedTotal += bytes.value().size();
285 result.type = chunk.type;
286 result.schemaVersion = chunk.schemaVersion;
287 result.chunks.push_back({chunk.kind, chunk.chunkId, std::move(bytes).takeValue()});
288 }
289 if (result.chunks.empty()) {
290 if (identityFound && !typeFound)
292 Diagnostic::error(DiagnosticCode::TypeMismatch, "asset does not provide the expected type/version",
293 asset.format(), {}, "asset.evpack.reader"));
294 if (typeFound)
296 "asset has no chunk for the selected variant",
297 asset.format(), {}, "asset.evpack.reader"));
299 asset.format(), {}, "asset.evpack.reader"));
300 }
301 std::sort(result.chunks.begin(), result.chunks.end(), [](const auto& left, const auto& right) {
302 return std::tie(left.kind, left.chunkId) < std::tie(right.kind, right.chunkId);
303 });
304 if (result.chunks.front().kind != EvpackChunkKind::Definition)
306 "asset has no definition chunk", asset.format(),
307 {}, "asset.evpack.reader"));
309}
310
312 const EvpackCapabilities& capabilities,
313 std::uint32_t maximumAssets) const {
314 if (!pack_ || expectedType.empty() || maximumAssets == 0)
315 return Result<std::vector<AssetRef>>::failure(
316 Diagnostic::error(DiagnosticCode::InvalidArgument, "pack, expected type and asset budget are required", {},
317 {}, "asset.evpack.reader"));
318 auto selected = selectEvpackVariant(*pack_, capabilities);
319 if (!selected) return Result<std::vector<AssetRef>>::failure(selected.status());
320 try {
321 std::vector<PersistentId> identities;
322 for (const auto& chunk : pack_->chunks()) {
323 const std::string actualType = chunk.type + "/" + std::to_string(chunk.schemaVersion.value());
324 if (chunk.variantIndex != selected.value().index || actualType != expectedType) continue;
325 identities.push_back(chunk.assetId);
326 }
327 std::sort(identities.begin(), identities.end());
328 identities.erase(std::unique(identities.begin(), identities.end()), identities.end());
329 if (identities.size() > maximumAssets)
331 DiagnosticCode::InvalidArgument, "asset listing exceeds result budget", {}, {}, "asset.evpack.reader"));
332 std::vector<AssetRef> result;
333 result.reserve(identities.size());
334 for (const auto& identity : identities) {
336 if (!reference) return Result<std::vector<AssetRef>>::failure(reference.status());
337 result.push_back(std::move(reference).takeValue());
338 }
339 return Result<std::vector<AssetRef>>::success(std::move(result));
340 } catch (const std::bad_alloc&) {
342 DiagnosticCode::Failed, "asset listing allocation failed", {}, {}, "asset.evpack.reader"));
343 }
344}
345} // namespace eve::asset
std::string selected
std::string packageId
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
Prepare/commit runtime package publication with stale-generation detection.
Typed capability-aware runtime access to admitted packs.
HexVec3 left
HexVec3 right
ActionGuidePack pack
Poco::JSON::Object::Ptr result
std::uint64_t bytes
std::string error
Definition Package.cpp:174
PrimitiveHandle handle
std::set< std::string > identities
RoadNetwork resolved
bool found
std::string kind
float size
Definition TreeMesh.cpp:158
const AssetImportLimits & limits
uint32_t index
ViewPreparation callback
uint64_t identity
Stable asset identity backed by PersistentId.
Definition ResourceRef.h:53
const PersistentId & id() const noexcept
Return the stable asset identity.
Definition ResourceRef.h:65
static Result< AssetRef > fromId(PersistentId id)
Build an asset reference from a non-nil persistent identity.
std::string format() const
Return canonical asset://<uuid> text.
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
Result< RuntimeAssetPayload > readAsset(const EvpackAssetHandle &handle, std::uint64_t maximumDecodedBytes) const
Decode an asset through its generation-qualified provider handle.
Result< std::vector< std::uint8_t > > copyChunkBytes(const EvpackChunkHandle &handle) const
Copy verified chunk bytes so the result remains valid across hot replacement.
Result< std::shared_ptr< const Evpack > > resolve(const EvpackHandle &handle) const
Resolve a current package handle to shared immutable ownership.
Result< EvpackChunkHandle > resolveChunk(const EvpackHandle &handle, const PersistentId &assetId, std::string_view type, EvpackChunkKind kind, std::uint32_t chunkId, std::uint32_t variantIndex) const
Resolve an exact asset/type/kind/variant tuple to a generation-scoped chunk handle.
Result< void > unsubscribe(EvpackRegistrySubscription subscription)
Cancel a live subscription; an unknown token returns NotFound.
Result< EvpackRegistrySubscription > subscribe(Callback callback)
Subscribe to committed lifecycle changes.
Result< EvpackAssetHandle > resolveAsset(const AssetRef &asset, std::string_view expectedType, const EvpackCapabilities &capabilities) const
Resolve one stable AssetRef across uniquely owning mounted packages.
std::function< Result< void >(const EvpackRegistryEvent &)> Callback
Result< EvpackUnmountReceipt > unmount(const EvpackHandle &handle)
Unmount exactly the referenced current generation and dispatch a lock-free event.
Result< EvpackMountReceipt > commit(PreparedEvpackMount candidate)
Atomically publish an admitted package and invalidate its previous generation.
Immutable reader retaining an admitted pack by shared ownership.
Result< std::vector< AssetRef > > listAssets(std::string_view expectedType, const EvpackCapabilities &capabilities, std::uint32_t maximumAssets=1 '000 '000) const
List stable assets providing an exact type/version for the selected runtime variant.
Result< RuntimeAssetPayload > read(const AssetRef &asset, std::string_view expectedType, const EvpackCapabilities &capabilities, std::uint64_t maximumDecodedBytes) const
Resolve, type-check, variant-select and decode a canonical runtime asset.
Owning admitted mount candidate that has not changed observable registry state.
Id128 public API.
Definition Identity.h:111
std::string format() const
Formats the ID in lower-case canonical UUID text.
Definition Identity.h:172
constexpr bool isNil() const noexcept
Returns whether this value is the all-zero nil ID.
Definition Identity.h:175
Result< Evpack > parseEvpack(std::span< const std::uint8_t > bytes, const EvpackLimits &limits, const EvpackTrust &trust)
Parse, bound-check and hash-verify a complete untrusted .evpack.
Definition Evpack.cpp:542
Result< EvpackVariantSelection > selectEvpackVariant(const Evpack &pack, const EvpackCapabilities &capabilities)
Select the first explicitly ordered variant satisfied by device capabilities.
Definition Evpack.cpp:585
Result< PreparedEvpackMount > prepareEvpackMount(std::span< const std::uint8_t > bytes, const EvpackLimits &limits, const EvpackTrust &trust)
Fully parse and verify package bytes without publishing them.
EvpackChunkKind
Semantic role of a runtime chunk.
Definition Evpack.h:26
@ TypeMismatch
A stable reference resolved to a different canonical domain type.
Generation-scoped stable-reference resolution across mounted packages.
Actual runtime device capabilities used for variant selection.
Definition Evpack.h:92
Generation-scoped handle to one verified chunk in a mounted package.
Admitted immutable chunk metadata.
Definition Evpack.h:138
Generation-scoped handle to one mounted runtime package.
Resource limits checked before package allocations and hash work.
Definition Evpack.h:126
Immutable lifecycle event delivered to registry subscribers.
Opaque identity used to cancel a registry subscription.
Trust inputs kept separate from size/resource limits.
Definition Evpack.h:75
Owning backend-neutral payload returned to a domain decoder.