载入中...
搜索中...
未找到
EditorDiskAssetCatalog.cpp
浏览该文件的文档.
2
4
5#include <fstream>
6#include <iomanip>
7#include <iterator>
8#include <set>
9#include <sstream>
10#include <utility>
11
12namespace eve::editor {
13namespace {
14
15Result<DiskAssetScanResult> scanError(EditorStatus status, const char* rule, std::string message) {
16 return eve::editing::failed<DiskAssetScanResult>(status, RuleId(rule), std::move(message));
17}
18
19std::string textMember(const EditorValue::Object& object, const char* key) {
20 const auto found = object.find(key);
21 const auto* value = found == object.end() ? nullptr : found->second.getIf<std::string>();
22 return value ? *value : std::string{};
23}
24
25} // namespace
26
27DiskAssetCatalog::DiskAssetCatalog(std::filesystem::path projectRoot, MemoryAssetDatabase* database)
28 : database_(database) {
29 std::error_code ec;
30 contentRoot_ = std::filesystem::weakly_canonical(std::move(projectRoot), ec) / "Content";
31 if (ec) contentRoot_.clear();
32}
33
34std::filesystem::path DiskAssetCatalog::resolveContent(const std::filesystem::path& relative) const {
35 if (contentRoot_.empty() || relative.empty() || relative.is_absolute()) return {};
36 auto candidate = (contentRoot_ / relative).lexically_normal();
37 const auto scoped = candidate.lexically_relative(contentRoot_);
38 if (scoped.empty()) return {};
39 for (const auto& part : scoped)
40 if (part == "..") return {};
41 return candidate;
42}
43
44Result<void> DiskAssetCatalog::writeSidecar(const std::filesystem::path& contentRelativePath, AssetGuid guid,
45 std::string typeId, std::uint32_t schemaVersion) {
46 const auto source = resolveContent(contentRelativePath);
47 if (source.empty() || guid.empty() || typeId.empty())
48 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.asset.sidecar-invalid"),
49 "Content path, GUID and type are required");
50 EditorValue::Object metadata;
51 metadata["guid"] = EditorValue(guid.value());
52 metadata["type"] = EditorValue(std::move(typeId));
53 metadata["schemaVersion"] = EditorValue(static_cast<std::int64_t>(schemaVersion));
54 const std::filesystem::path sidecar = source.string() + ".evmeta";
55 std::error_code ec;
56 std::filesystem::create_directories(sidecar.parent_path(), ec);
57 if (ec)
58 return eve::editing::failed<void>(EditorStatus::Failed, RuleId("editor.asset.sidecar-directory"), ec.message());
59 const std::filesystem::path temporary = sidecar.string() + ".tmp";
60 {
61 std::ofstream output(temporary, std::ios::binary | std::ios::trunc);
62 if (!output)
63 return eve::editing::failed<void>(EditorStatus::Failed, RuleId("editor.asset.sidecar-write"),
64 "Cannot open asset sidecar temp file");
65 output << editorValueToJson(EditorValue(std::move(metadata)));
66 }
67 std::filesystem::rename(temporary, sidecar, ec);
68 if (ec) {
69 std::filesystem::remove(sidecar, ec);
70 ec.clear();
71 std::filesystem::rename(temporary, sidecar, ec);
72 }
73 if (ec)
74 return eve::editing::failed<void>(EditorStatus::Failed, RuleId("editor.asset.sidecar-replace"), ec.message());
75 return eve::editing::applied<void>();
76}
77
79 if (!database_ || contentRoot_.empty())
80 return scanError(EditorStatus::Rejected, "editor.asset.catalog-invalid",
81 "Asset database and Content root are required");
83 std::error_code ec;
84 if (!std::filesystem::exists(contentRoot_)) return eve::editing::applied<DiskAssetScanResult>(std::move(result));
85 std::set<AssetGuid> discovered;
86 for (std::filesystem::recursive_directory_iterator iterator(contentRoot_, ec), end; iterator != end && !ec;
87 iterator.increment(ec)) {
88 if (!iterator->is_regular_file() || iterator->path().extension() != ".evmeta") continue;
89 std::ifstream input(iterator->path(), std::ios::binary);
90 const std::string json{std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
91 auto parsed = editorValueFromJson(json);
92 const auto* metadata = parsed.ok() ? parsed.value().getIf<EditorValue::Object>() : nullptr;
93 AssetGuid guid(metadata ? textMember(*metadata, "guid") : std::string{});
94 const std::string type = metadata ? textMember(*metadata, "type") : std::string{};
95 if (!parsed.ok() || !metadata || guid.empty() || type.empty()) {
96 result.diagnostics.push_back(editing::ruleDiagnostic(
97 eve::DiagnosticCode::InvalidArgument, RuleId("editor.asset.sidecar-invalid"),
98 DiagnosticSeverity::Error,
99 "Invalid asset sidecar: " + iterator->path().generic_string()));
100 continue;
101 }
102 if (!discovered.emplace(guid).second) {
103 result.diagnostics.push_back(editing::ruleDiagnostic(
104 eve::DiagnosticCode::Conflict, RuleId("editor.asset.duplicate-guid"),
105 DiagnosticSeverity::Error, "Duplicate asset GUID: " + guid.value()));
106 continue;
107 }
108 std::filesystem::path source = iterator->path();
109 source.replace_extension();
110 if (!std::filesystem::is_regular_file(source)) {
111 result.diagnostics.push_back(editing::ruleDiagnostic(
112 eve::DiagnosticCode::NotFound, RuleId("editor.asset.source-missing"),
113 DiagnosticSeverity::Error,
114 "Asset sidecar source is missing: " + source.generic_string()));
115 continue;
116 }
117 const auto relative = source.lexically_relative(contentRoot_);
118 const std::string hash = fileHash(source);
119 std::string fingerprint = relative.generic_string();
120 fingerprint.push_back(':');
121 fingerprint.append(hash);
122 fingerprint.push_back(':');
123 const auto previous = fingerprints_.find(guid);
124 const bool changed = previous == fingerprints_.end() || !previous->second.starts_with(fingerprint) ||
125 previous->second.compare(fingerprint.size(), std::string::npos, json) != 0;
126 if (changed) fingerprint.append(json);
128 record.guid = guid;
129 record.logicalUri = "content://" + relative.generic_string();
130 record.typeId = type;
131 record.sourceUri = source.generic_string();
132 record.sourceHash = hash;
133 record.schemaVersion = 1;
134 auto published = database_->publish(std::move(record));
135 if (!published.ok()) {
136 const auto& diagnostics = published.diagnostics();
137 result.diagnostics.insert(result.diagnostics.end(), diagnostics.begin(), diagnostics.end());
138 continue;
139 }
140 ++result.indexed;
141 if (changed) {
142 ++result.changed;
143 fingerprints_.insert_or_assign(std::move(guid), std::move(fingerprint));
144 }
145 }
146 if (ec) return scanError(EditorStatus::Failed, "editor.asset.scan-failed", ec.message());
147 auto diagnostics = result.diagnostics;
148 return eve::editing::applied<DiskAssetScanResult>(std::move(result), std::move(diagnostics));
149}
150
152
153std::string DiskAssetCatalog::fileHash(const std::filesystem::path& path) {
154 std::ifstream input(path, std::ios::binary);
155 std::uint64_t hash = 1469598103934665603ULL;
156 char buffer[8192];
157 while (input) {
158 input.read(buffer, sizeof(buffer));
159 for (std::streamsize index = 0; index < input.gcount(); ++index) {
160 hash ^= static_cast<unsigned char>(buffer[index]);
161 hash *= 1099511628211ULL;
162 }
163 }
164 std::ostringstream text;
165 text << std::hex << std::setfill('0') << std::setw(16) << hash;
166 return text.str();
167}
168
169} // namespace eve::editor
170
172
174
175#include <algorithm>
176#include <cctype>
177#include <fstream>
178#include <iterator>
179
180#if defined(_WIN32)
181#include <windows.h>
182#endif
183
184namespace eve::editor {
185namespace {
186
187const EditorValue* member(const EditorValue& value, const char* key) {
188 const auto* object = value.getIf<EditorValue::Object>();
189 if (!object) return nullptr;
190 const auto found = object->find(key);
191 return found == object->end() ? nullptr : &found->second;
192}
193
194std::string stringMember(const EditorValue& value, const char* key) {
195 const EditorValue* field = member(value, key);
196 const auto* text = field ? field->getIf<std::string>() : nullptr;
197 return text ? *text : std::string{};
198}
199
200Revision revisionMember(const EditorValue& value, const char* key) {
201 const EditorValue* field = member(value, key);
202 const auto* integer = field ? field->getIf<std::int64_t>() : nullptr;
203 return integer && *integer >= 0 ? static_cast<Revision>(*integer) : 0;
204}
205
206Result<AutosaveDraft> draftFailure(const char* rule, std::string message) {
207 return eve::editing::failed<AutosaveDraft>(EditorStatus::Rejected, RuleId(rule), std::move(message));
208}
209
210} // namespace
211
212DiskAtomicDocumentStore::DiskAtomicDocumentStore(std::filesystem::path projectRoot) {
213 std::error_code ec;
214 root_ = std::filesystem::weakly_canonical(std::move(projectRoot), ec);
215 if (ec) root_.clear();
216}
217
218std::filesystem::path DiskAtomicDocumentStore::resolve(const std::string& resourceUri) const {
219 if (root_.empty()) return {};
220 std::string relative;
221 if (resourceUri.rfind("content://", 0) == 0)
222 relative = "Content/" + resourceUri.substr(10);
223 else if (resourceUri.rfind("autosave://", 0) == 0)
224 relative = "Saved/Autosave/" + resourceUri.substr(11);
225 else
226 return {};
227 if (relative.empty()) return {};
228
229 std::filesystem::path candidate(relative);
230 if (candidate.is_absolute()) return {};
231 for (const auto& part : candidate)
232 if (part == "..") return {};
233
234 candidate = (root_ / candidate).lexically_normal();
235 const std::filesystem::path scoped = candidate.lexically_relative(root_);
236 if (scoped.empty()) return {};
237 for (const auto& part : scoped)
238 if (part == "..") return {};
239 return candidate;
240}
241
242Result<StoredDocument> DiskAtomicDocumentStore::read(const std::string& resourceUri) const {
243 const std::filesystem::path path = resolve(resourceUri);
244 if (path.empty()) return failure(EditorStatus::Rejected, "editor.document.invalid-uri", "Rejected resource URI");
245 std::ifstream input(path, std::ios::binary);
246 if (!input)
247 return failure(EditorStatus::NotFound, "editor.document.store-not-found",
248 "Document resource is not persisted: " + resourceUri);
249 const std::string json{std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
250 Result<EditorValue> parsed = editorValueFromJson(json);
251 if (!parsed.ok() || !parsed.ok())
252 return failure(EditorStatus::Failed, "editor.document.invalid-envelope", "Document JSON envelope is invalid");
253
254 const EditorValue* content = member(parsed.value(), "content");
255 const Revision revision = revisionMember(parsed.value(), "revision");
256 const auto* schema = member(parsed.value(), "schemaVersion");
257 const auto* schemaInteger = schema ? schema->getIf<std::int64_t>() : nullptr;
258 if (!content || !schemaInteger || *schemaInteger != 1)
259 return failure(EditorStatus::Failed, "editor.document.unsupported-schema",
260 "Document envelope schemaVersion must be 1");
261
263 stored.content = *content;
264 stored.revision = revision;
265 stored.contentHash = editorValueContentHash(stored.content);
266 return eve::editing::applied<StoredDocument>(std::move(stored));
267}
268
270 Revision expectedRevision,
271 const std::string& expectedContentHash,
272 const EditorValue& content) {
273 const std::filesystem::path path = resolve(resourceUri);
274 if (path.empty()) return failure(EditorStatus::Rejected, "editor.document.invalid-uri", "Rejected resource URI");
275
277 Result<StoredDocument> existing = read(resourceUri);
278 if (existing.ok())
279 current = existing.value();
280 else if (existing.code() != EditorStatus::NotFound)
281 return existing;
282 else
283 current.contentHash.clear();
284 if (current.revision != expectedRevision || current.contentHash != expectedContentHash)
285 return failure(EditorStatus::Conflict, "editor.document.disk-conflict",
286 "Document content or revision changed before save");
287
288 StoredDocument next;
289 next.content = content;
290 next.revision = current.revision + 1;
291 next.contentHash = editorValueContentHash(content);
292 EditorValue::Object envelope;
293 envelope["schemaVersion"] = EditorValue(1);
294 envelope["revision"] = EditorValue(static_cast<std::int64_t>(next.revision));
295 envelope["contentHash"] = EditorValue(next.contentHash);
296 envelope["content"] = content;
297
298 std::error_code ec;
299 std::filesystem::create_directories(path.parent_path(), ec);
300 if (ec) return failure(EditorStatus::Failed, "editor.document.create-directory", ec.message());
301 const std::filesystem::path temporary = path.string() + ".tmp." + std::to_string(++sequence_);
302 {
303 std::ofstream output(temporary, std::ios::binary | std::ios::trunc);
304 if (!output) return failure(EditorStatus::Failed, "editor.document.temp-open", "Cannot open temp file");
305 output << editorValueToJson(EditorValue(std::move(envelope)));
306 output.flush();
307 if (!output.good()) {
308 output.close();
309 std::filesystem::remove(temporary, ec);
310 return failure(EditorStatus::Failed, "editor.document.temp-write", "Cannot flush temp file");
311 }
312 }
313 if ((beforeReplace_ && !beforeReplace_(path)) || !replace(temporary, path)) {
314 std::filesystem::remove(temporary, ec);
315 return failure(EditorStatus::Failed, "editor.document.atomic-replace", "Atomic replacement failed");
316 }
317 return eve::editing::applied<StoredDocument>(std::move(next));
318}
319
320Result<StoredDocument> DiskAtomicDocumentStore::failure(EditorStatus status, const char* rule, std::string message) {
321 return eve::editing::failed<StoredDocument>(status, RuleId(rule), std::move(message));
322}
323
324bool DiskAtomicDocumentStore::replace(const std::filesystem::path& temporary,
325 const std::filesystem::path& destination) const {
326#if defined(_WIN32)
327 return MoveFileExW(temporary.c_str(), destination.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
328#else
329 std::error_code ec;
330 std::filesystem::rename(temporary, destination, ec);
331 return !ec;
332#endif
333}
334
335std::string AutosaveService::draftUri(const DocumentId& document) const {
336 std::string safeDocument = document.value();
337 std::replace_if(
338 safeDocument.begin(), safeDocument.end(),
339 [](unsigned char character) { return !std::isalnum(character) && character != '-' && character != '_'; }, '_');
340 return "autosave://" + projectId_ + "/" + safeDocument + ".draft";
341}
342
344 if (!store_ || snapshot.id.empty())
345 return eve::editing::failed<StoredDocument>(EditorStatus::Rejected, RuleId("editor.autosave.invalid"),
346 "Autosave store and document are required");
347 const std::string uri = draftUri(snapshot.id);
348 Revision revision = 0;
349 std::string hash;
350 Result<StoredDocument> existing = store_->read(uri);
351 if (existing.ok()) {
352 revision = existing.value().revision;
353 hash = existing.value().contentHash;
354 } else if (existing.code() != EditorStatus::NotFound) {
355 return existing;
356 }
358 draft["document"] = EditorValue(snapshot.id.value());
359 draft["baseDiskHash"] = EditorValue(snapshot.diskContentHash);
360 draft["schemaVersion"] = EditorValue(1);
361 draft["editRevision"] = EditorValue(static_cast<std::int64_t>(snapshot.revision.edit));
362 draft["content"] = content;
363 return store_->compareAndSwap(uri, revision, hash, EditorValue(std::move(draft)));
364}
365
367 if (!store_ || document.empty()) return draftFailure("editor.autosave.invalid", "Autosave store is required");
368 const Result<StoredDocument> stored = store_->read(draftUri(document));
369 if (!stored.ok()) return Result<AutosaveDraft>::failure(stored.status());
370 const EditorValue& root = stored.value().content;
371 const EditorValue* content = member(root, "content");
372 if (!content || revisionMember(root, "schemaVersion") != 1)
373 return draftFailure("editor.autosave.unsupported-schema", "Autosave draft schemaVersion must be 1");
375 draft.document = DocumentId(stringMember(root, "document"));
376 draft.baseDiskHash = stringMember(root, "baseDiskHash");
377 draft.schemaVersion = 1;
378 draft.editRevision = revisionMember(root, "editRevision");
379 draft.content = *content;
380 if (draft.document != document)
381 return draftFailure("editor.autosave.document-mismatch", "Autosave draft belongs to another document");
382 return eve::editing::applied<AutosaveDraft>(std::move(draft));
383}
384
386 return draft.document == formal.id && draft.editRevision > formal.revision.saved &&
387 draft.baseDiskHash == formal.diskContentHash;
388}
389
390} // namespace eve::editor
int root
Definition AnimSmr.cpp:119
Vec3 relative
Definition AnimSmr.cpp:164
std::string output
std::uint64_t revision
bool changed
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
std::vector< std::uint8_t > stored
Definition Evpack.cpp:171
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
wgpu::PopErrorScopeStatus status
std::function< Numbers(b3JointId)> read
std::string fingerprint
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::shared_ptr< const OceanSprayFrame > previous
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string path
Definition PlayHost.cpp:111
std::string uri
Object::Ptr value
std::string hash
RoadPresetDraft draft
bool found
std::string text
std::string_view source
size_t end
double current
float(ui::Theme::* member)[4]
uint32_t index
Move-only operation result carrying either a value or Status.
Definition Result.h:176
const T & value() const &
Borrow the value from a const lvalue after checking success.
Definition Result.h:339
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:286
StatusCode code() const noexcept
Inspect the stable operation code.
Definition Result.h:307
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
const std::string & value() const noexcept
Returns the exact legacy or canonical compatibility spelling.
Definition Identity.h:365
bool empty() const noexcept
True when no compatibility spelling has been assigned.
Definition Identity.h:377
Deterministic owning value tree shared by authoring hosts.
std::map< std::string, Value > Object
const T * getIf() const
Return an immediately borrowed typed value.
Result< AutosaveDraft > readDraft(const DocumentId &document) const
Read a draft and validate its schema.
bool shouldOfferRecovery(const AutosaveDraft &draft, const DocumentSnapshot &formal) const
True when a newer draft differs from the current formal disk base.
std::string draftUri(const DocumentId &document) const
Return the stable draft URI for one document.
Result< StoredDocument > writeDraft(const DocumentSnapshot &snapshot, const EditorValue &content)
Write one revisioned draft under autosave://project/document.draft.
Result< DiskAssetScanResult > scan()
Scan every sidecar and atomically publish valid records.
Result< void > writeSidecar(const std::filesystem::path &contentRelativePath, AssetGuid guid, std::string typeId, std::uint32_t schemaVersion=1)
Create/replace a sidecar for a Content-relative source file.
DiskAssetCatalog(std::filesystem::path projectRoot, MemoryAssetDatabase *database)
Create a host-driven disk asset catalog.
Result< DiskAssetScanResult > poll()
Rescan and report only content/sidecar fingerprints that changed.
Result< StoredDocument > compareAndSwap(const std::string &resourceUri, Revision expectedRevision, const std::string &expectedContentHash, const EditorValue &content) override
CAS and atomically replace one document envelope on disk.
DiskAtomicDocumentStore(std::filesystem::path projectRoot)
Create a store rooted at a project directory.
std::filesystem::path resolve(const std::string &resourceUri) const
Resolve a logical URI to a canonical project path, or an empty path when rejected.
Result< StoredDocument > read(const std::string &resourceUri) const override
Read and validate the latest atomic document envelope.
virtual Result< StoredDocument > read(const std::string &resourceUri) const =0
Read the latest value for a resource URI.
virtual Result< StoredDocument > compareAndSwap(const std::string &resourceUri, Revision expectedRevision, const std::string &expectedContentHash, const EditorValue &content)=0
Replace a value only when the expected disk revision still matches.
Thread-neutral in-memory asset index used by editor hosts and tests.
Result< AssetRecord > publish(AssetRecord record, std::vector< AssetDependency > dependencies={})
Atomically publish one validated record and its dependencies.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
Diagnostic ruleDiagnostic(eve::DiagnosticCode code, RuleId rule, DiagnosticSeverity severity, std::string message)
Build an owning common diagnostic carrying an open editing rule identity.
eve::editing::Value EditorValue
Compatibility alias for the UI-independent authoring value tree.
Definition EditorValue.h:8
eve::editing::RuleId RuleId
Definition EditorIds.h:32
eve::editing::DocumentId DocumentId
Definition EditorIds.h:40
eve::StatusCode EditorStatus
Definition EditorResult.h:8
eve::editing::Revision Revision
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
Value snapshot stored by the editor asset index.
Persisted draft metadata used to decide whether recovery should be offered.
Result of one disk asset sidecar scan/poll.
Immutable document metadata snapshot.
Value snapshot returned by an atomic document store.