using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using Aetheria.State.Documents; using GameCult.Caching; using GameCult.Caching.MessagePack; using GameCult.Eve.Surface; 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 DaemonAssetManifest { get; } = new CultRecordKey("daemon:aetheria.asset_manifest.v1"); public static CultRecordKey VerseAuthorityPolicy { get; } = new CultRecordKey(AetheriaRuntimeVerseAuthorityPolicyDocument.DocumentKey); 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 StarbridgeScenarioLatest { get; } = new CultRecordKey("starbridge:aetheria.scenario.latest.v1"); public static CultRecordKey StarbridgeSessionLatest { get; } = new CultRecordKey("starbridge:aetheria.session.latest.v1"); public static CultRecordKey StarbridgeSessionSummary { get; } = new CultRecordKey("daemon:aetheria.starbridge.session.latest.v1"); public static CultRecordKey StarbridgePlayerSeat(string seatId) { return new CultRecordKey(AetheriaRuntimeStarbridgePlayerSeatDocument.RecordKey(seatId)); } 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(AetheriaRuntimeVerseAuthorityPolicyDocument), typeof(AetheriaRuntimeDaemonFrameDocument), typeof(AetheriaRuntimeDaemonSoaViewDocument), typeof(AetheriaRuntimeCatalogSnapshot), typeof(AetheriaRuntimeLoadoutTemplatesDocument), typeof(AetheriaRuntimeAssetManifestDocument), typeof(AetheriaRuntimeObjectsViewportDocument), typeof(AetheriaRuntimeGravityViewportDocument), typeof(AetheriaRuntimeCurrentZoneDocument), typeof(AetheriaRuntimeCurrentEntityDocument), typeof(AetheriaRuntimeCurrentDockingDocument), typeof(AetheriaRuntimeZoneContactsDocument), typeof(AetheriaRuntimeStationRefitDocument), typeof(AetheriaRuntimeSectorMapDocument), typeof(AetheriaRuntimeZoneDetailsDocument), typeof(AetheriaRuntimeZoneRenderDocument), typeof(AetheriaRuntimeSelectedObjectDocument), typeof(AetheriaRuntimeInventoryDocument), typeof(AetheriaRuntimeStarbridgeScenarioDocument), typeof(AetheriaRuntimeStarbridgeSessionDocument), typeof(AetheriaRuntimeStarbridgeSessionSummaryDocument), typeof(AetheriaRuntimeStarbridgePlayerSeatDocument), typeof(AetheriaRuntimePlayerSettingsDocument), typeof(AetheriaRuntimeVerseHostSettingsDocument), typeof(AetheriaRuntimeDaemonCommandDocument), typeof(AetheriaRuntimeEveCommandDocument), typeof(EveSurfaceState) }; public static CultDocumentRegistry CreateCultCacheRegistry() { return CultMesh.CreateCultCacheDocumentRegistry(RuntimeDocumentTypes); } public static CultNetDocumentRegistry CreateCultNetRegistry(CultDocumentRegistry? cacheRegistry = null) { var registry = cacheRegistry ?? CreateCultCacheRegistry(); return CultMesh.CreateCultNetDocumentRegistry(RuntimeDocumentTypes, registry); } } public sealed class AetheriaRuntimeVerseClient : IDisposable { public const string DefaultRuntimeId = "aetheria-verse-client"; private readonly CultMeshNode _node; private AetheriaClientState? _aetheriaState; 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 AetheriaClientState Aetheria() { ThrowIfDisposed(); return _aetheriaState ??= CreateAetheriaState(); } public CultMeshMutableStatePointer ProviderAdvertisement() { ThrowIfDisposed(); return MutableDocumentPointer( AetheriaRuntimeVerseRecordKeys.DaemonProviderAdvertisement); } public CultMeshMutableStatePointer Health() { ThrowIfDisposed(); return MutableDocumentPointer( AetheriaRuntimeVerseRecordKeys.DaemonHealth); } public CultMeshMutableStatePointer CommandBoundary() { ThrowIfDisposed(); return MutableDocumentPointer( AetheriaRuntimeVerseRecordKeys.DaemonCommandBoundary); } public CultMeshMutableStatePointer VerseAuthorityPolicy() { ThrowIfDisposed(); return MutableDocumentPointer( AetheriaRuntimeVerseRecordKeys.VerseAuthorityPolicy); } public CultMeshMutableStatePointer LatestFrame() { ThrowIfDisposed(); return MutableDocumentPointer( AetheriaRuntimeVerseRecordKeys.DaemonFrameLatest); } public CultMeshMutableStatePointer LatestSoaView() { ThrowIfDisposed(); return MutableDocumentPointer( AetheriaRuntimeVerseRecordKeys.DaemonSoaViewLatest); } public CultMeshMutableStatePointer StarbridgeScenario() { ThrowIfDisposed(); return MutableDocumentPointer( AetheriaRuntimeVerseRecordKeys.StarbridgeScenarioLatest); } public CultMeshMutableStatePointer StarbridgeSession() { ThrowIfDisposed(); return MutableDocumentPointer( AetheriaRuntimeVerseRecordKeys.StarbridgeSessionLatest); } public CultMeshMutableStatePointer StarbridgePlayerSeat( string seatId) { ThrowIfDisposed(); return MutableDocumentPointer( AetheriaRuntimeVerseRecordKeys.StarbridgePlayerSeat(seatId)); } public CultMeshMutableStatePointer DaemonGameSurface() { ThrowIfDisposed(); return MutableDocumentPointer(AetheriaRuntimeVerseRecordKeys.DaemonGameSurface); } public CultMeshMutableStatePointer DaemonGameTuiSurface() { ThrowIfDisposed(); return MutableDocumentPointer(AetheriaRuntimeVerseRecordKeys.DaemonGameTuiSurface); } public CultMeshMutableStatePointer DaemonEditorSurface() { ThrowIfDisposed(); return MutableDocumentPointer(AetheriaRuntimeVerseRecordKeys.DaemonEditorSurface); } public CultMeshMutableStatePointer DaemonEditorTuiSurface() { ThrowIfDisposed(); return MutableDocumentPointer(AetheriaRuntimeVerseRecordKeys.DaemonEditorTuiSurface); } public CultMeshDocumentHandle Document( CultRecordKey key, string? documentId = null) where TDocument : class { ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(key.Value)) throw new ArgumentException("Value must be non-empty.", nameof(key)); var descriptor = CultDocumentRegistry.Shared.GetRequired(); return CultMesh.Document( Database, key, CultMesh.Verse("aetheria.local", RuntimeId), documentId, new[] { CultMesh.ProjectionSource(key.ToString(), descriptor.SchemaId, "Aetheria Verse database document") }, new CultMeshRouteHint(CultMeshLocalityKind.SharedMemory, "Aetheria Verse database")); } public Task> ReactiveDocumentAsync( CultRecordKey key, CultMeshReactiveDocumentOptions? options = null, string? documentId = null) where TDocument : class { return Document(key, documentId).ReactiveAsync(options); } 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> WatchVerseAuthorityPolicies() { ThrowIfDisposed(); return Database.WatchRecord( AetheriaRuntimeVerseRecordKeys.VerseAuthorityPolicy); } public Observable> WatchLatestFrames() { ThrowIfDisposed(); return Database.WatchRecord( AetheriaRuntimeVerseRecordKeys.DaemonFrameLatest); } public Observable> WatchLatestSoaViews() { ThrowIfDisposed(); return Database.WatchRecord( AetheriaRuntimeVerseRecordKeys.DaemonSoaViewLatest); } public Observable> WatchStarbridgeScenarios() { ThrowIfDisposed(); return Database.WatchRecord( AetheriaRuntimeVerseRecordKeys.StarbridgeScenarioLatest); } public Observable> WatchStarbridgeSessions() { ThrowIfDisposed(); return Database.WatchRecord( AetheriaRuntimeVerseRecordKeys.StarbridgeSessionLatest); } public Observable> WatchStarbridgePlayerSeat(string seatId) { ThrowIfDisposed(); return Database.WatchRecord( AetheriaRuntimeVerseRecordKeys.StarbridgePlayerSeat(seatId)); } public Observable> WatchDaemonGameSurfaces() { ThrowIfDisposed(); return Database.WatchRecord(AetheriaRuntimeVerseRecordKeys.DaemonGameSurface); } public Observable> WatchDaemonGameTuiSurfaces() { ThrowIfDisposed(); return Database.WatchRecord(AetheriaRuntimeVerseRecordKeys.DaemonGameTuiSurface); } public Observable> WatchDaemonEditorSurfaces() { ThrowIfDisposed(); return Database.WatchRecord(AetheriaRuntimeVerseRecordKeys.DaemonEditorSurface); } public Observable> WatchDaemonEditorTuiSurfaces() { ThrowIfDisposed(); return Database.WatchRecord(AetheriaRuntimeVerseRecordKeys.DaemonEditorTuiSurface); } internal 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); } internal 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); } internal Task SubmitInputSettingsCommandAsync( AetheriaRuntimeEveCommandKind command, AetheriaRuntimeInputSettingsCommandBody body, string clientId, bool flush = true) { ThrowIfDisposed(); return SubmitEveCommandAsync( AetheriaRuntimeEveCommandClient.ToDocument( AetheriaRuntimeEveCommandClient.CreateInputSettingsCommand(command, body, clientId)), flush); } internal Task SubmitLoadoutTemplateCommandAsync( AetheriaRuntimeLoadoutTemplateCommit loadoutTemplate, string clientId, bool flush = true) { ThrowIfDisposed(); return SubmitEveCommandAsync( AetheriaRuntimeEveCommandClient.ToDocument( AetheriaRuntimeEveCommandClient.CreateLoadoutTemplateCommand(loadoutTemplate, clientId)), flush); } internal Task SubmitKnownSurfaceCommandAsync( EveSurfaceCommandRequest request, string clientId, bool flush = true) { ThrowIfDisposed(); if (!AetheriaRuntimeEveCommandClient.TryCreateKnownSurfaceCommand(request, out var envelope)) { throw new InvalidOperationException( $"Unknown Aetheria Eve surface command: {request?.ProviderId}/{request?.SurfaceId}/{request?.Command}"); } var document = AetheriaRuntimeEveCommandClient.ToDocument(envelope!); if (!string.IsNullOrWhiteSpace(clientId)) document.ClientId = clientId; return SubmitEveCommandAsync(document, flush); } 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 AetheriaClientState CreateAetheriaState() { var frameChanges = WatchLatestFrames() .Where(change => change.Document != null) .Select(change => change.Document!); var catalogDocument = BootstrapCatalogDocument( "aetheria.catalog.runtime", () => Task.FromResult(BootstrapRuntimeCatalogSnapshot()), AetheriaRuntimeCatalogSnapshot.SchemaId, CatalogBootstrapSource("catalog:aetheria.runtime")); var loadoutTemplatesDocument = BootstrapCatalogDocument( "aetheria.catalog.loadout_templates", () => Task.FromResult(BootstrapLoadoutTemplatesDocument()), AetheriaRuntimeLoadoutTemplatesDocument.SchemaId, CatalogBootstrapSource("catalog:aetheria.loadout_templates")); var starbridgeScenarioDocument = Document( AetheriaRuntimeVerseRecordKeys.StarbridgeScenarioLatest); var starbridgeSessionDocument = Document( AetheriaRuntimeVerseRecordKeys.StarbridgeSessionLatest); return new AetheriaClientState( Document( AetheriaRuntimeVerseRecordKeys.DaemonProviderAdvertisement), Document( AetheriaRuntimeVerseRecordKeys.DaemonHealth), Document( AetheriaRuntimeVerseRecordKeys.DaemonCommandBoundary), Document( AetheriaRuntimeVerseRecordKeys.VerseAuthorityPolicy), Document( AetheriaRuntimeVerseRecordKeys.DaemonFrameLatest), Document( AetheriaRuntimeVerseRecordKeys.DaemonSoaViewLatest), Document( AetheriaRuntimeVerseRecordKeys.DaemonGameSurface), Document( AetheriaRuntimeVerseRecordKeys.DaemonGameTuiSurface), Document( AetheriaRuntimeVerseRecordKeys.DaemonEditorSurface), Document( AetheriaRuntimeVerseRecordKeys.DaemonEditorTuiSurface), catalogDocument, loadoutTemplatesDocument, BootstrapCatalogDocument( "aetheria.settings.player", () => Task.FromResult(BootstrapPlayerSettingsDocument()), AetheriaRuntimePlayerSettingsDocument.SchemaId, CatalogBootstrapSource("catalog:aetheria.player_settings")), BootstrapCatalogDocument( "aetheria.settings.verse_host", () => Task.FromResult(BootstrapVerseHostSettingsDocument()), AetheriaRuntimeVerseHostSettingsDocument.SchemaId, CatalogBootstrapSource("catalog:aetheria.verse_host_settings")), ProjectedDocument( "aetheria.current.zone", frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectCurrentZone(frame)), AetheriaRuntimeDaemonSchemas.CurrentZone), ProjectedDocument( "aetheria.current.entity", frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectCurrentEntity(frame)), AetheriaRuntimeDaemonSchemas.CurrentEntity), ProjectedDocument( "aetheria.current.docking", frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectCurrentDocking(frame)), AetheriaRuntimeDaemonSchemas.CurrentDocking), ProjectedDocument( "aetheria.zone.contacts", frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectZoneContacts(frame)), AetheriaRuntimeDaemonSchemas.ZoneContacts), ProjectedDocument( "aetheria.station.refit", ProjectStationRefitAsync, AetheriaRuntimeDaemonSchemas.StationRefit, CultMesh.ProjectionSource("catalog:aetheria.runtime"), CultMesh.ProjectionSource("loadout-templates:aetheria.runtime")), ProjectedDocument( "aetheria.sector.map", frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectSectorMap(frame)), AetheriaRuntimeDaemonSchemas.SectorMap), ProjectedDocument( "aetheria.zone.render", frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectZoneRender(frame)), AetheriaRuntimeDaemonSchemas.ZoneRender), viewport => ProjectedDocument( ViewportDocumentId("aetheria.viewport.map", viewport), frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectViewport(frame, viewport)), AetheriaRuntimeDaemonSchemas.RtsViewport), viewport => ProjectedDocument( ViewportDocumentId("aetheria.viewport.objects", viewport), frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectObjectsViewport(frame, viewport)), AetheriaRuntimeDaemonSchemas.ObjectsViewport), viewport => ProjectedDocument( ViewportDocumentId("aetheria.viewport.gravity", viewport), frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectGravityViewport(frame, viewport)), AetheriaRuntimeDaemonSchemas.GravityViewport), viewport => ProjectedDocument( ViewportDocumentId("aetheria.viewport.render_splats", viewport), frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectRenderSplatsViewport(frame, viewport)), AetheriaRuntimeDaemonSchemas.RenderSplatsViewport), zoneIndex => ProjectedDocument( IndexedDocumentId("aetheria.zone.details", zoneIndex), frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectZoneDetails(frame, zoneIndex)), AetheriaRuntimeDaemonSchemas.ZoneDetails), entityIndex => ProjectedDocument( IndexedDocumentId("aetheria.object.selected", entityIndex), frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectSelectedObject(frame, entityIndex)), AetheriaRuntimeDaemonSchemas.SelectedObject), entityIndex => ProjectedDocument( IndexedDocumentId("aetheria.inventory", entityIndex), frame => Task.FromResult(AetheriaRuntimeRtsProjection.ProjectInventory(frame, entityIndex)), AetheriaRuntimeDaemonSchemas.Inventory), starbridgeScenarioDocument, starbridgeSessionDocument, ProjectedDocument( "aetheria.starbridge.summary", ProjectStarbridgeSummaryAsync, AetheriaRuntimeDaemonSchemas.StarbridgeSessionSummary, CultMesh.ProjectionSource(AetheriaRuntimeVerseRecordKeys.StarbridgeScenarioLatest.ToString()), CultMesh.ProjectionSource(AetheriaRuntimeVerseRecordKeys.StarbridgeSessionLatest.ToString()), CultMesh.ProjectionSource("catalog:aetheria.runtime")), seatId => Document( AetheriaRuntimeVerseRecordKeys.StarbridgePlayerSeat(seatId))); CultMeshDocumentHandle ProjectedDocument( string documentId, Func> project, string schemaId, params CultMeshProjectionSource[] additionalSources) where TDocument : class { var sources = new[] { CultMesh.ProjectionSource( AetheriaRuntimeVerseRecordKeys.DaemonFrameLatest.ToString(), AetheriaRuntimeDaemonSchemas.Frame, "latest authoritative daemon frame") } .Concat(additionalSources ?? Array.Empty()) .Append(CultMesh.ProjectionSource(documentId, schemaId, "projected Aetheria client document")) .ToArray(); var verse = CultMesh.Verse("aetheria.local", RuntimeId); return CultMesh.Document( documentId, verse, async _ => await project(await RequireFrameAsync().ConfigureAwait(false)).ConfigureAwait(false), _ => frameChanges .SelectAwait(async (frame, cancellationToken) => await project(frame).ConfigureAwait(false)), sources: sources, routeHint: new CultMeshRouteHint(CultMeshLocalityKind.SharedMemory, "Aetheria typed projected state")); } CultMeshDocumentHandle BootstrapCatalogDocument( string documentId, Func> bootstrap, string schemaId, params CultMeshProjectionSource[] additionalSources) where TDocument : class { var sources = (additionalSources ?? Array.Empty()) .Append(CultMesh.ProjectionSource(documentId, schemaId, "managed Aetheria catalog document")) .ToArray(); var verse = CultMesh.Verse("aetheria.local", RuntimeId); return CultMesh.Document( documentId, verse, async _ => await bootstrap().ConfigureAwait(false), _ => frameChanges .SelectAwait(async (_, cancellationToken) => await bootstrap().ConfigureAwait(false)), sources: sources, routeHint: new CultMeshRouteHint(CultMeshLocalityKind.SharedMemory, "Aetheria managed catalog state")); } async Task ProjectStationRefitAsync( AetheriaRuntimeDaemonFrameDocument frame) { var loadoutTemplates = await loadoutTemplatesDocument.LatestAsync().ConfigureAwait(false); var catalog = await catalogDocument.LatestAsync().ConfigureAwait(false); return AetheriaRuntimeRtsProjection.ProjectStationRefit(frame, loadoutTemplates.Templates, catalog); } async Task ProjectStarbridgeSummaryAsync( AetheriaRuntimeDaemonFrameDocument frame) { var scenario = await starbridgeScenarioDocument.LatestAsync().ConfigureAwait(false); var session = await starbridgeSessionDocument.LatestAsync().ConfigureAwait(false); var catalog = await catalogDocument.LatestAsync().ConfigureAwait(false); return AetheriaRuntimeStarbridgeProjection.ProjectSessionSummary( frame, scenario, session, catalog); } static string IndexedDocumentId(string prefix, int index) { return $"{prefix}.{index.ToString(CultureInfo.InvariantCulture)}"; } static string ViewportDocumentId(string prefix, AetheriaRuntimeRtsViewportBounds viewport) { var normalized = AetheriaRuntimeRtsProjection.Normalize(viewport); return string.Join( ".", prefix, ViewportToken(normalized.MinX), ViewportToken(normalized.MinY), ViewportToken(normalized.MaxX), ViewportToken(normalized.MaxY)); } static string ViewportToken(double value) { return value .ToString("0.###", CultureInfo.InvariantCulture) .Replace('-', 'n') .Replace('.', 'p'); } } private async Task RequireFrameAsync() { var frame = await Aetheria().Daemon.LatestFrame.LatestAsync().ConfigureAwait(false); if (frame == null) throw new InvalidOperationException("Aetheria Verse client has no daemon frame yet."); return frame; } private CultMeshMutableStatePointer MutableDocumentPointer(CultRecordKey key) where T : class { return CultMesh.MutableStatePointer( key.ToString(), _ => Database.GetAsync(key), _ => Database.WatchRecord(key) .Where(change => change.Document != null) .Select(change => change.Document!), async (_, value) => { await Database.PutAsync(key, value).ConfigureAwait(false); }, sources: new[] { CultMesh.ProjectionSource(key.ToString()) }); } private static CultMeshProjectionSource CatalogBootstrapSource(string sourceId) { return CultMesh.ProjectionSource( sourceId, description: "legacy catalog store bootstrap seed for managed Aetheria state"); } private AetheriaRuntimeCatalogSnapshot BootstrapRuntimeCatalogSnapshot() { return AetheriaRuntimeCatalogStore.OpenReadOnly(StatePath); } private AetheriaRuntimeLoadoutTemplatesDocument BootstrapLoadoutTemplatesDocument() { return new AetheriaRuntimeLoadoutTemplatesDocument( AetheriaRuntimeCatalogStore.ReadLoadoutTemplates(StatePath)); } private AetheriaRuntimePlayerSettingsDocument BootstrapPlayerSettingsDocument() { return AetheriaRuntimePlayerSettingsDocument.FromSnapshot( AetheriaRuntimeCatalogStore.ReadPlayerSettings(StatePath)); } private AetheriaRuntimeVerseHostSettingsDocument BootstrapVerseHostSettingsDocument() { return AetheriaRuntimeVerseHostSettingsDocument.FromSnapshot( AetheriaRuntimeCatalogStore.ReadVerseHostSettings(StatePath)); } } }