diff --git a/Aetheria.State.Verify/Program.cs b/Aetheria.State.Verify/Program.cs index 0090b253c..27c4ba930 100644 --- a/Aetheria.State.Verify/Program.cs +++ b/Aetheria.State.Verify/Program.cs @@ -62,6 +62,7 @@ RequireTypedStatRecipeOperations(root); RequireTypedDaemonCommandPayloads(root); RequireUnityPublicRequestVocabulary(root); RequireDaemonVersePublication(root); +RequireAetheriaRuntimeVerseClientContract(root); RequireTypedEveCommandBodies(root); RequireMainMenuVerseHostProjection(root); RequireMainMenuContinueRunState(root); @@ -799,6 +800,7 @@ static void RequirePackageSerializerBoundary(string root) "AetheriaRuntimeClientTargetStore.cs", "AetheriaRuntimeCultCacheDocumentStore.cs", "AetheriaRuntimeCommandPort.cs", + "AetheriaRuntimeVerseClient.cs", "AetheriaRuntimeSnapshotDocuments.cs", "AetheriaRuntimeEveCommandDocument.cs", "AetheriaRuntimeDaemonDocuments.cs", @@ -8043,6 +8045,102 @@ static void RequireDaemonVersePublication(string root) } } +static void RequireAetheriaRuntimeVerseClientContract(string root) +{ + var clientPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeVerseClient.cs"); + var commandPortPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeCommandPort.cs"); + var docPath = Path.Combine(root, "docs", "aetheria-verse-client-contract.md"); + + var requiredFiles = new[] { clientPath, commandPortPath, docPath }; + var missingFiles = requiredFiles + .Where(path => !File.Exists(path)) + .Select(path => Path.GetRelativePath(root, path)) + .ToArray(); + if (missingFiles.Length > 0) + { + throw new InvalidOperationException( + "Aetheria runtime Verse client contract cannot be verified because required files are missing: " + + string.Join(", ", missingFiles)); + } + + var client = File.ReadAllText(clientPath); + var commandPort = File.ReadAllText(commandPortPath); + var doc = File.ReadAllText(docPath); + + var requiredClientSymbols = new[] + { + "public sealed class AetheriaRuntimeVerseClient", + "public static class AetheriaRuntimeVerseRecordKeys", + "public static class AetheriaRuntimeVerseContractRegistry", + "AetheriaRuntimeVerseContractRegistry.CreateCultCacheRegistry()", + "AetheriaRuntimeVerseContractRegistry.CreateCultNetRegistry(registry)", + "WatchLatestFrames()", + "WatchLatestSoaViews()", + "WatchRecord", + "WatchRecord", + "AetheriaRuntimeVerseDocument", + "SubmitDaemonCommandAsync(", + "AetheriaRuntimeVerseRecordKeys.DaemonCommand(command.CommandId)", + "DaemonGameTuiSurface { get; }", + "DaemonEditorTuiSurface { get; }" + }; + var missingClientSymbols = requiredClientSymbols + .Where(symbol => !client.Contains(symbol, StringComparison.Ordinal)) + .ToArray(); + if (missingClientSymbols.Length > 0) + { + throw new InvalidOperationException( + "Aetheria runtime Verse client is missing typed CultMesh client contract symbols: " + + string.Join(", ", missingClientSymbols)); + } + + if (!commandPort.Contains("AetheriaRuntimeVerseContractRegistry.CreateCultCacheRegistry()", StringComparison.Ordinal) || + !commandPort.Contains("AetheriaRuntimeVerseContractRegistry.CreateCultNetRegistry(registry)", StringComparison.Ordinal) || + !commandPort.Contains("AetheriaRuntimeVerseRecordKeys.DaemonCommand(commandId)", StringComparison.Ordinal) || + !commandPort.Contains("AetheriaRuntimeVerseRecordKeys.EveCommand(commandId)", StringComparison.Ordinal)) + { + throw new InvalidOperationException( + "Runtime command port must share AetheriaRuntimeVerseClient contract registry and record keys."); + } + + var forbiddenCommandPortRegistrySymbols = new[] + { + "private static CultDocumentRegistry CreateCultCacheRegistry", + "private static CultNetDocumentRegistry CreateCultNetRegistry", + "daemon:commands:{StableToken(commandId)}", + "eve:commands:{StableToken(commandId)}" + }; + var forbiddenCommandPortHits = forbiddenCommandPortRegistrySymbols + .Where(symbol => commandPort.Contains(symbol, StringComparison.Ordinal)) + .ToArray(); + if (forbiddenCommandPortHits.Length > 0) + { + throw new InvalidOperationException( + "Runtime command port still owns a duplicate Verse contract boundary: " + + string.Join(", ", forbiddenCommandPortHits)); + } + + var requiredDocSymbols = new[] + { + "AetheriaRuntimeVerseClient", + "WatchRecord()", + "AetheriaRuntimeVerseDocument", + "Unity", + "Verse records", + "EveSurfaceState", + "same typed records" + }; + var missingDocSymbols = requiredDocSymbols + .Where(symbol => !doc.Contains(symbol, StringComparison.Ordinal)) + .ToArray(); + if (missingDocSymbols.Length > 0) + { + throw new InvalidOperationException( + "Aetheria Verse client contract note is missing required architecture terms: " + + string.Join(", ", missingDocSymbols)); + } +} + static void RequireTypedEveCommandBodies(string root) { var eveCommandDocumentPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeEveCommandDocument.cs"); diff --git a/GameCult.Aetheria.State.Unity.csproj b/GameCult.Aetheria.State.Unity.csproj index 14b7275ba..8c5cebfa0 100644 --- a/GameCult.Aetheria.State.Unity.csproj +++ b/GameCult.Aetheria.State.Unity.csproj @@ -86,6 +86,7 @@ + diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCommandPort.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCommandPort.cs index d8762f4a6..249653293 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCommandPort.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeCommandPort.cs @@ -33,7 +33,7 @@ namespace Aetheria.State throw new ArgumentException("State file path must be non-empty.", nameof(stateFilePath)); var fullPath = Path.GetFullPath(stateFilePath); - var registry = CreateCultCacheRegistry(); + var registry = AetheriaRuntimeVerseContractRegistry.CreateCultCacheRegistry(); var node = await CultMesh.CreateNodeAsync( fullPath, new CultMeshNodeOptions @@ -50,7 +50,7 @@ namespace Aetheria.State DatabaseOptions = new CultNetDatabaseOptions { RuntimeId = string.IsNullOrWhiteSpace(runtimeId) ? "aetheria-command-client" : runtimeId, - DocumentRegistry = CreateCultNetRegistry(registry) + DocumentRegistry = AetheriaRuntimeVerseContractRegistry.CreateCultNetRegistry(registry) } }) .ConfigureAwait(false); @@ -91,47 +91,14 @@ namespace Aetheria.State return AetheriaRuntimeEveCommandClient.ToEnvelope(command); } - private static CultDocumentRegistry CreateCultCacheRegistry() - { - var registry = new CultDocumentRegistry(); - registry.GetRequired(typeof(AetheriaRuntimeDaemonCommandDocument)); - registry.GetRequired(typeof(AetheriaRuntimeEveCommandDocument)); - return registry; - } - - private static CultNetDocumentRegistry CreateCultNetRegistry(CultDocumentRegistry registry) - { - return new CultNetDocumentRegistry( - registry, - new[] - { - CultNetDocumentBinding.ForDocument(registry), - CultNetDocumentBinding.ForDocument(registry) - }); - } - private static CultRecordKey DaemonCommandKey(string commandId) { - return new CultRecordKey($"daemon:commands:{StableToken(commandId)}:gamecult.aetheria.daemon_command.v1"); + return AetheriaRuntimeVerseRecordKeys.DaemonCommand(commandId); } private static CultRecordKey EveCommandKey(string commandId) { - return new CultRecordKey($"eve:commands:{StableToken(commandId)}:gamecult.eve.command.v1"); - } - - private static string StableToken(string value) - { - if (string.IsNullOrWhiteSpace(value)) - return "empty"; - - var chars = value - .Select(character => char.IsLetterOrDigit(character) ? character : '-') - .ToArray(); - var token = new string(chars).Trim('-').ToLowerInvariant(); - while (token.Contains("--", StringComparison.Ordinal)) - token = token.Replace("--", "-", StringComparison.Ordinal); - return string.IsNullOrWhiteSpace(token) ? "empty" : token; + return AetheriaRuntimeVerseRecordKeys.EveCommand(commandId); } public void Dispose() diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeVerseClient.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeVerseClient.cs new file mode 100644 index 000000000..a541eec63 --- /dev/null +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeVerseClient.cs @@ -0,0 +1,392 @@ +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using GameCult.Mesh; +using GameCult.Networking; +using R3; + +#nullable enable + +namespace GameCult.Aetheria.State.Verse +{ + public static class AetheriaRuntimeVerseRecordKeys + { + public static CultRecordKey DaemonProviderAdvertisement { get; } = + new CultRecordKey("daemon:aetheria.provider_advertisement.v1"); + + public static CultRecordKey DaemonHealth { get; } = + new CultRecordKey("daemon:aetheria.health.v1"); + + public static CultRecordKey DaemonCommandBoundary { get; } = + new CultRecordKey("daemon:aetheria.command_boundary.v1"); + + public static CultRecordKey DaemonFrameLatest { get; } = + new CultRecordKey("daemon:aetheria.frame.latest.v1"); + + public static CultRecordKey DaemonSoaViewLatest { get; } = + new CultRecordKey("daemon:aetheria.soa_view.latest.v1"); + + public static CultRecordKey DaemonGameSurface { get; } = + new CultRecordKey("eve:surface:aetheria.daemon.game"); + + public static CultRecordKey DaemonGameTuiSurface { get; } = + new CultRecordKey("eve:surface:aetheria.daemon.game.tui"); + + public static CultRecordKey DaemonEditorSurface { get; } = + new CultRecordKey("eve:surface:aetheria.daemon.editor"); + + public static CultRecordKey DaemonEditorTuiSurface { get; } = + new CultRecordKey("eve:surface:aetheria.daemon.editor.tui"); + + public static CultRecordKey DaemonCommand(string commandId) + { + return new CultRecordKey($"daemon:commands:{StableToken(commandId)}:gamecult.aetheria.daemon_command.v1"); + } + + public static CultRecordKey EveCommand(string commandId) + { + return new CultRecordKey($"eve:commands:{StableToken(commandId)}:gamecult.eve.command.v1"); + } + + public static string StableToken(string value) + { + if (string.IsNullOrWhiteSpace(value)) + return "empty"; + + var chars = value + .Select(character => char.IsLetterOrDigit(character) ? character : '-') + .ToArray(); + var token = new string(chars).Trim('-').ToLowerInvariant(); + while (token.Contains("--", StringComparison.Ordinal)) + token = token.Replace("--", "-", StringComparison.Ordinal); + return string.IsNullOrWhiteSpace(token) ? "empty" : token; + } + } + + public static class AetheriaRuntimeVerseContractRegistry + { + private static readonly Type[] RuntimeDocumentTypes = + { + typeof(AetheriaRuntimeDaemonProviderAdvertisementDocument), + typeof(AetheriaRuntimeDaemonHealthDocument), + typeof(AetheriaRuntimeDaemonCommandBoundaryDocument), + typeof(AetheriaRuntimeDaemonFrameDocument), + typeof(AetheriaRuntimeDaemonSoaViewDocument), + typeof(AetheriaRuntimeDaemonCommandDocument), + typeof(AetheriaRuntimeEveCommandDocument) + }; + + public static CultDocumentRegistry CreateCultCacheRegistry() + { + var registry = new CultDocumentRegistry(); + foreach (var documentType in RuntimeDocumentTypes) + { + registry.GetRequired(documentType); + } + + return registry; + } + + public static CultNetDocumentRegistry CreateCultNetRegistry(CultDocumentRegistry? cacheRegistry = null) + { + var registry = cacheRegistry ?? CreateCultCacheRegistry(); + return new CultNetDocumentRegistry( + registry, + new[] + { + CultNetDocumentBinding.ForDocument(registry), + CultNetDocumentBinding.ForDocument(registry), + CultNetDocumentBinding.ForDocument(registry), + CultNetDocumentBinding.ForDocument(registry), + CultNetDocumentBinding.ForDocument(registry), + CultNetDocumentBinding.ForDocument(registry), + CultNetDocumentBinding.ForDocument(registry) + }); + } + } + + public sealed class AetheriaRuntimeVerseDocument where T : class + { + private readonly Func> _read; + private readonly Func _replace; + private readonly Observable _watch; + + public AetheriaRuntimeVerseDocument( + CultRecordKey key, + Func> read, + Func replace, + Observable watch) + { + Key = key; + _read = read ?? throw new ArgumentNullException(nameof(read)); + _replace = replace ?? throw new ArgumentNullException(nameof(replace)); + _watch = watch ?? throw new ArgumentNullException(nameof(watch)); + } + + public CultRecordKey Key { get; } + + public Task ReadAsync() + { + return _read(); + } + + public Task ReplaceAsync(T value) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + return _replace(value); + } + + public Observable Watch() + { + return _watch; + } + } + + public sealed class AetheriaRuntimeVerseClient : IDisposable + { + public const string DefaultRuntimeId = "aetheria-verse-client"; + + private readonly CultMeshNode _node; + private bool _disposed; + + private AetheriaRuntimeVerseClient(string statePath, string runtimeId, CultMeshNode node) + { + StatePath = statePath; + RuntimeId = runtimeId; + _node = node ?? throw new ArgumentNullException(nameof(node)); + } + + public string StatePath { get; } + + public string RuntimeId { get; } + + public CultMeshNode Node => _node; + + public CultCache Cache => _node.Cache; + + public CultNetDatabase Database => _node.Database; + + public static async Task OpenAsync( + string statePath, + string runtimeId = DefaultRuntimeId, + bool startServer = false, + bool pullOnOpen = true) + { + if (string.IsNullOrWhiteSpace(statePath)) + throw new ArgumentException("State path must be non-empty.", nameof(statePath)); + + var fullPath = Path.GetFullPath(statePath); + var effectiveRuntimeId = string.IsNullOrWhiteSpace(runtimeId) ? DefaultRuntimeId : runtimeId; + var registry = AetheriaRuntimeVerseContractRegistry.CreateCultCacheRegistry(); + var node = await CultMesh.CreateNodeAsync( + fullPath, + new CultMeshNodeOptions + { + StartServer = startServer, + EnableDurableShardLogs = true, + CacheOptions = new CultCacheOpenOptions + { + Registry = registry, + PullOnOpen = pullOnOpen, + StoreFlushOnDispose = true, + UseDirectoryStore = true + }, + DatabaseOptions = new CultNetDatabaseOptions + { + RuntimeId = effectiveRuntimeId, + DocumentRegistry = AetheriaRuntimeVerseContractRegistry.CreateCultNetRegistry(registry) + } + }) + .ConfigureAwait(false); + + return new AetheriaRuntimeVerseClient(fullPath, effectiveRuntimeId, node); + } + + public Task GetProviderAdvertisementAsync() + { + ThrowIfDisposed(); + return Database.GetAsync( + AetheriaRuntimeVerseRecordKeys.DaemonProviderAdvertisement); + } + + public Task GetHealthAsync() + { + ThrowIfDisposed(); + return Database.GetAsync( + AetheriaRuntimeVerseRecordKeys.DaemonHealth); + } + + public Task GetCommandBoundaryAsync() + { + ThrowIfDisposed(); + return Database.GetAsync( + AetheriaRuntimeVerseRecordKeys.DaemonCommandBoundary); + } + + public Task GetLatestFrameAsync() + { + ThrowIfDisposed(); + return Database.GetAsync( + AetheriaRuntimeVerseRecordKeys.DaemonFrameLatest); + } + + public Task GetLatestSoaViewAsync() + { + ThrowIfDisposed(); + return Database.GetAsync( + AetheriaRuntimeVerseRecordKeys.DaemonSoaViewLatest); + } + + public AetheriaRuntimeVerseDocument ProviderAdvertisement() + { + ThrowIfDisposed(); + return Document( + AetheriaRuntimeVerseRecordKeys.DaemonProviderAdvertisement); + } + + public AetheriaRuntimeVerseDocument Health() + { + ThrowIfDisposed(); + return Document( + AetheriaRuntimeVerseRecordKeys.DaemonHealth); + } + + public AetheriaRuntimeVerseDocument CommandBoundary() + { + ThrowIfDisposed(); + return Document( + AetheriaRuntimeVerseRecordKeys.DaemonCommandBoundary); + } + + public AetheriaRuntimeVerseDocument LatestFrame() + { + ThrowIfDisposed(); + return Document( + AetheriaRuntimeVerseRecordKeys.DaemonFrameLatest); + } + + public AetheriaRuntimeVerseDocument LatestSoaView() + { + ThrowIfDisposed(); + return Document( + AetheriaRuntimeVerseRecordKeys.DaemonSoaViewLatest); + } + + public Observable> + WatchProviderAdvertisements() + { + ThrowIfDisposed(); + return Database.WatchRecord( + AetheriaRuntimeVerseRecordKeys.DaemonProviderAdvertisement); + } + + public Observable> WatchHealth() + { + ThrowIfDisposed(); + return Database.WatchRecord( + AetheriaRuntimeVerseRecordKeys.DaemonHealth); + } + + public Observable> + WatchCommandBoundary() + { + ThrowIfDisposed(); + return Database.WatchRecord( + AetheriaRuntimeVerseRecordKeys.DaemonCommandBoundary); + } + + public Observable> WatchLatestFrames() + { + ThrowIfDisposed(); + return Database.WatchRecord( + AetheriaRuntimeVerseRecordKeys.DaemonFrameLatest); + } + + public Observable> WatchLatestSoaViews() + { + ThrowIfDisposed(); + return Database.WatchRecord( + AetheriaRuntimeVerseRecordKeys.DaemonSoaViewLatest); + } + + public async Task SubmitDaemonCommandAsync( + AetheriaRuntimeDaemonCommandDocument command, + bool flush = true) + { + ThrowIfDisposed(); + if (command == null) throw new ArgumentNullException(nameof(command)); + + command.Schema = AetheriaRuntimeDaemonSchemas.Command; + if (string.IsNullOrWhiteSpace(command.CommandId)) + command.CommandId = Guid.NewGuid().ToString("N"); + if (string.IsNullOrWhiteSpace(command.ClientId)) + command.ClientId = RuntimeId; + if (string.IsNullOrWhiteSpace(command.IssuedAtUtc)) + command.IssuedAtUtc = DateTime.UtcNow.ToString("O"); + + await Database.PutAsync(AetheriaRuntimeVerseRecordKeys.DaemonCommand(command.CommandId), command) + .ConfigureAwait(false); + if (flush) + await FlushAsync().ConfigureAwait(false); + + return AetheriaRuntimeDaemonOperationClient.ToEnvelope(command); + } + + public async Task SubmitEveCommandAsync( + AetheriaRuntimeEveCommandDocument command, + bool flush = true) + { + ThrowIfDisposed(); + if (command == null) throw new ArgumentNullException(nameof(command)); + + AetheriaRuntimeEveCommandClient.NormalizeDocument(command); + command.Schema = AetheriaRuntimeEveCommandDocument.SchemaId; + if (string.IsNullOrWhiteSpace(command.CommandId)) + command.CommandId = Guid.NewGuid().ToString("N"); + if (string.IsNullOrWhiteSpace(command.IssuedAtUtc)) + command.IssuedAtUtc = DateTime.UtcNow.ToString("O"); + + await Database.PutAsync(AetheriaRuntimeVerseRecordKeys.EveCommand(command.CommandId), command) + .ConfigureAwait(false); + if (flush) + await FlushAsync().ConfigureAwait(false); + + return AetheriaRuntimeEveCommandClient.ToEnvelope(command); + } + + public Task FlushAsync(bool soft = false) + { + ThrowIfDisposed(); + return _node.FlushAsync(soft); + } + + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _node.Dispose(); + } + + private void ThrowIfDisposed() + { + if (_disposed) + throw new ObjectDisposedException(nameof(AetheriaRuntimeVerseClient)); + } + + private AetheriaRuntimeVerseDocument Document(CultRecordKey key) where T : class + { + return new AetheriaRuntimeVerseDocument( + key, + () => Database.GetAsync(key), + async value => { await Database.PutAsync(key, value).ConfigureAwait(false); }, + Database.WatchRecord(key) + .Where(change => change.Document != null) + .Select(change => change.Document!)); + } + } +} diff --git a/docs/aetheria-verse-client-contract.md b/docs/aetheria-verse-client-contract.md new file mode 100644 index 000000000..eda19e8eb --- /dev/null +++ b/docs/aetheria-verse-client-contract.md @@ -0,0 +1,75 @@ +# Aetheria Verse Client Contract + +Aetheria clients should enter the runtime through CultMesh typed state, not through +daemon internals. The daemon owns simulation authority and publishes daemon state +as Verse records. Unity, tools, test harnesses, and later non-Unity clients open +the same state store with the same runtime document registry and read/write typed +documents through CultNet. + +The shared entrypoint is `AetheriaRuntimeVerseClient` in the runtime state +package. It opens a local `CultMeshNode` with the runtime-only Aetheria contract +registry and exposes: + +- current typed reads for provider advertisement, health, command boundary, + latest daemon frame, and latest SoA view; +- reactive watches via `WatchRecord()`, including `WatchLatestFrames()` and + `WatchLatestSoaViews()`; +- `AetheriaRuntimeVerseDocument` handles for transparent reactive POCO + presentation; +- typed daemon and Eve command submission through the same command record keys + used by the daemon. + +This is the intended shape for the Unity client: + +```csharp +using var client = await AetheriaRuntimeVerseClient.OpenAsync( + statePath, + runtimeId: "unity-render-client"); + +using var frames = client.WatchLatestFrames().Subscribe(change => +{ + var frame = change.Document; + if (frame == null) + return; + + // Feed presentation jobs from the authoritative daemon frame. +}); + +var soa = await client.GetLatestSoaViewAsync(); +``` + +Unity should treat the client as its Aetheria-facing runtime surface. It can +still use Burst, DOTS rendering, and native views for presentation, but the state +authority boundary is the typed CultMesh contract. No Unity-facing code should +reach for string command names, mutable payload dictionaries, local simulation +ticks, or daemon implementation classes. + +## Embedded Host Option + +Running an embeddable daemon core in Unity remains a deployment option, but it +does not change the client contract. Even in-process hosting should publish and +consume the same typed records so that the Unity renderer, a standalone daemon, +and another client all agree on schema and semantics. + +The alternative idea of "Unity runs CultMesh using the same state assembly, but +not the daemon assembly" is exactly what this contract supports. The Unity side +references the runtime state package, opens `AetheriaRuntimeVerseClient`, and +uses CultMesh reactive wrappers to observe daemon state as if it were native +state. The current Unity CultMesh DLL exposes `WatchRecord()`; once the +packaged DLL catches up with local CultLib, the client handle can delegate +directly to CultMesh `Document` without changing callers. + +## Eve Surface Boundary + +The daemon already publishes game and editor Eve surface records at these keys: + +- `eve:surface:aetheria.daemon.game` +- `eve:surface:aetheria.daemon.game.tui` +- `eve:surface:aetheria.daemon.editor` +- `eve:surface:aetheria.daemon.editor.tui` + +`AetheriaRuntimeVerseRecordKeys` exposes those keys now. The remaining cleanup is +to move the `EveSurfaceState` document contract into the shared runtime package +so `AetheriaRuntimeVerseClient` can expose typed surface watches too. Until then, +surface resolution stays in the existing Eve Unity runtime host, which already +resolves Aetheria state refs automatically.