From 6b435b8f134171135c3e1487163cc7254e67dc48 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 13 Jun 2026 17:02:52 +0100 Subject: [PATCH] Drain Eve commands through provider state --- .voidbot/state/aetheria.cc | Bin 40589 -> 41413 bytes Aetheria.State.ApplyPending/Program.cs | 61 +++- Aetheria.State.Smoke/Program.cs | 46 +++- Aetheria.State/AetheriaDocumentRegistry.cs | 2 + Aetheria.State/AetheriaEveCommandBridge.cs | 260 ++++++++++++++++++ .../AetheriaOperationsSurfaceProjector.cs | 39 ++- .../AetheriaProviderAdvertisementProjector.cs | 4 +- Aetheria.State/AetheriaStateNode.cs | 12 + .../AetheriaEveCommandDrainStatus.cs | 57 ++++ Aetheria.State/README.md | 27 +- Economy.Server/Program.cs | 99 ++++++- .../README.md | 2 +- .../Runtime/AetheriaRuntimeEveCommandLog.cs | 8 +- docs/aetheria-perfect-machine-map.md | 29 +- 14 files changed, 613 insertions(+), 33 deletions(-) create mode 100644 Aetheria.State/AetheriaEveCommandBridge.cs create mode 100644 Aetheria.State/Documents/AetheriaEveCommandDrainStatus.cs diff --git a/.voidbot/state/aetheria.cc b/.voidbot/state/aetheria.cc index 91ad1ea4775905390c95d98451515d410755c171..955929023356a4aac2248e92814f03f229b3641a 100644 GIT binary patch delta 1942 zcmaJ?-)me&6edZnZCcQXx*Dxasv^i{^P@?c=B31FK~!jd`4B;z+zVlzH=;@FwN8`ln= zI~Kh+(pn@FkrJGxvcV#*?VHz1_Q|WGtqRqtl2ICpw8jFNBs>inrFDvBMw+=lMS)bI zW~P}@$U?T@tA^lQO>thK^_|q ztqrMCpXxjgY8F zQB{$Sj=+`?dD{VCdAbF*)1H-HHVbqu!MjjibksVqIVkJ!y#ypnJc!71PL(g;$w|Ab z4}V-Nu%giB1ckzYOGkSf3l#9qh#c6H1so@!Ar(+~zp4EU&vx@)iXRG8+t2H}k7 zSX08Znisz?gd@Q7`x-!QdO2B=L!N|hQQw7%cnle3UW=HKtWbd%S{qUpI2^8+*cMTC zbfwF&CS|-OjN_G~5gRZADpFyd8UYM4jhht|*sqvxT<9;c3mg>kIdSm={oyFw&EW=I znVPuCc$UQii%=q_s&PdsY3$g|hg)|qS*F$&XO>tHli8 z1ZLQ>-!f&G4lL%*K93je!>URqNJAP0JDsJne_nmeUSDCSzv5{CQC6s`KR$T&gP#Xp zSz1&5Msh#?QU7Q&k?xwc$Yh%mHYkpYun+LXXS&I@W>^RkZIccjLGWJcb z_ONp@*-uu_tzUBaUUP1D^N(00(WQPM>Rw&Js-KX`<4>SeAqg?40gbUMxB*ee>u#8c#evW{EtpN{>G#u>V~cJSBE@WA~A)vwx5 zn^zrW;V%WH}$}ruxlvvDH;=RrO2; zgDr#{7FJQ(HQ?2VA|4`(7a@3%9K=gJt{1QV4SMla^^X}gx9+O<>V4n$zW1L0*7@{V z=joHqYnQHEyl`c3IoiBD-1=heRQbHKbD}-l7?e-HdZWybnB&W{^3T09<*P@}c0L>J zpFf&BC_cW1EojF5w!kd7MTRj% zoCB&EN}W;QL>pi*$z5)cp3yTwc|AQ>6nQx5PZ zzkHCOg1In0sPGjP-gk$U=|V!3ZK87-9~QA@1POIPqOmYzQp6rL9RTATGv}#TtTc;* zm`&EQQFGx6D&Rn(3y?jSw#{Rt40^IA;`?W=e&IApyo&L9mJa4?_)`;=qE3LR=3jXp`h7Y@A*z=%-W{2#W)w#U@v?-8jWPt zh|nFQrwt>|0jr0#H`hkSGd-^@%X0PW=mhu2%=L{NwG{i!NzD)7uo( zT(;Kg21^;t^05?_ELBsdv8zTuxIBUzIuM^|BI6gyQWoVjm`eKEN&Zf_us+CKi9Tr@ z&t3EbQ=ED`!ig>S&prBmt+3Y&PlThH^P41P8JUx7Lk??A(r87yAlS?Aq-I{ zcTuZwtt`b>Mx@HJWI61glelmZve9?cU{5&6=`uPqukOa^Q z*8A(jUVqpdTqp}ZEC1X1vK)PMx;(x6&dGM?4hLIL9Glv`^7d|b|Lffo$Cf*KI4EBn xIkVj3o9khZ|FidO8MAqb_V~_9%tnaWdR)|J8&SVM@Mrt~KK}LC%HhSW{{ek 0 && !args[0].StartsWith("--", StringComparison.Ordinal) ? Path.GetFullPath(args[0]) @@ -10,14 +11,72 @@ var statePath = string.IsNullOrWhiteSpace(explicitStatePath) ? AetheriaStatePaths.ResolveDefaultStatePath(root) : Path.GetFullPath(explicitStatePath); var deleteApplied = !args.Any(arg => string.Equals(arg, "--keep", StringComparison.OrdinalIgnoreCase)); +var runtimeId = "aetheria-state-apply-pending"; +var runtimePendingBefore = CountPendingRuntimeCommits(statePath); +var evePendingBefore = CountPendingEveCommands(statePath); +var now = DateTimeOffset.UtcNow.ToString("O"); -await using var node = await AetheriaStateNode.OpenAsync(statePath, "aetheria-state-apply-pending"); +await using var node = await AetheriaStateNode.OpenAsync(statePath, runtimeId); var report = await AetheriaRuntimeCommitLogApplier.ApplyPendingAsync(node, deleteApplied); +var eveReport = await AetheriaEveCommandBridge.ApplyPendingAsync(node, deleteApplied); +var commitStatus = new AetheriaRuntimeCommitDrainStatus +{ + RuntimeId = runtimeId, + StatePath = statePath, + LastPollAtUtc = now, + LastAppliedAtUtc = report.AppliedPaths.Length > 0 ? now : "", + PendingBeforeApply = runtimePendingBefore, + CommandsApplied = report.AppliedPaths.Length, + AppliedPlayerSettings = report.AppliedPlayerSettings, + AppliedLoadoutTemplates = report.AppliedLoadoutTemplates, + AppliedRunCheckpoints = report.AppliedRunCheckpoints, + Status = "ok" +}; +var eveStatus = new AetheriaEveCommandDrainStatus +{ + RuntimeId = runtimeId, + StatePath = statePath, + LastPollAtUtc = now, + LastAcceptedAtUtc = eveReport.AcceptedPaths.Length > 0 ? now : "", + PendingBeforeApply = evePendingBefore, + CommandsAccepted = eveReport.AcceptedPaths.Length, + CommandsRejected = eveReport.RejectedCommands, + AppliedCatalogRefreshes = eveReport.AppliedCatalogRefreshes, + AppliedOperationsRefreshes = eveReport.AppliedOperationsRefreshes, + LastRejectedCommand = eveReport.LastRejectedCommand, + LastRejectedReason = eveReport.LastRejectedReason, + Status = eveReport.RejectedCommands > 0 ? "rejected" : "ok" +}; +await node.PutRuntimeCommitDrainStatusAsync(commitStatus); +await node.PutEveCommandDrainStatusAsync(eveStatus); +await node.PutOperationsSurfaceAsync(AetheriaOperationsSurfaceProjector.Build(commitStatus, eveStatus)); +await node.PutProviderAdvertisementAsync(AetheriaProviderAdvertisementProjector.Build(statePath, now)); +await node.FlushAsync(); Console.WriteLine($"Applied pending Aetheria runtime commits: {statePath}"); Console.WriteLine($"Player settings: {report.AppliedPlayerSettings}"); Console.WriteLine($"Loadout templates: {report.AppliedLoadoutTemplates}"); Console.WriteLine($"Run checkpoints: {report.AppliedRunCheckpoints}"); Console.WriteLine($"Commands applied: {report.AppliedPaths.Length}"); +Console.WriteLine($"Eve commands accepted: {eveReport.AcceptedPaths.Length}"); +Console.WriteLine($"Eve commands rejected: {eveReport.RejectedCommands}"); +Console.WriteLine($"Eve catalog refreshes: {eveReport.AppliedCatalogRefreshes}"); +Console.WriteLine($"Eve operations refreshes: {eveReport.AppliedOperationsRefreshes}"); if (!deleteApplied) Console.WriteLine("Applied command files were kept because --keep was supplied."); + +static int CountPendingRuntimeCommits(string statePath) +{ + var pendingDirectory = statePath + ".pending"; + return Directory.Exists(pendingDirectory) + ? Directory.EnumerateFiles(pendingDirectory, "*.cc").Count() + : 0; +} + +static int CountPendingEveCommands(string statePath) +{ + var pendingDirectory = AetheriaEveCommandBridge.GetPendingDirectory(statePath); + return Directory.Exists(pendingDirectory) + ? Directory.EnumerateFiles(pendingDirectory, "*.cc").Count() + : 0; +} diff --git a/Aetheria.State.Smoke/Program.cs b/Aetheria.State.Smoke/Program.cs index db52081a8..ca402191b 100644 --- a/Aetheria.State.Smoke/Program.cs +++ b/Aetheria.State.Smoke/Program.cs @@ -105,6 +105,39 @@ await using (var node = await AetheriaStateNode.OpenAsync(statePath, "aetheria-s await node.PutOperationsSurfaceAsync(AetheriaOperationsSurfaceProjector.Build(drainStatus)); await node.PutProviderAdvertisementAsync(AetheriaProviderAdvertisementProjector.Build(statePath, now)); + AetheriaEveCommandBridge.QueueCommand( + statePath, + AetheriaProviderAdvertisementProjector.ProviderId, + AetheriaCatalogSurfaceProjector.SurfaceId, + "aetheria.catalog.refresh", + new Dictionary { ["source"] = "state-smoke" }, + "aetheria-state-smoke"); + AetheriaEveCommandBridge.QueueCommand( + statePath, + AetheriaProviderAdvertisementProjector.ProviderId, + AetheriaCatalogSurfaceProjector.SurfaceId, + "aetheria.catalog.unknown", + new Dictionary { ["source"] = "state-smoke" }, + "aetheria-state-smoke"); + var eveCommandReport = await AetheriaEveCommandBridge.ApplyPendingAsync(node); + var eveCommandStatus = new AetheriaEveCommandDrainStatus + { + RuntimeId = "smoke-runtime", + StatePath = statePath, + LastPollAtUtc = now, + LastAcceptedAtUtc = now, + PendingBeforeApply = 2, + CommandsAccepted = eveCommandReport.AcceptedPaths.Length, + CommandsRejected = eveCommandReport.RejectedCommands, + AppliedCatalogRefreshes = eveCommandReport.AppliedCatalogRefreshes, + AppliedOperationsRefreshes = eveCommandReport.AppliedOperationsRefreshes, + LastRejectedCommand = eveCommandReport.LastRejectedCommand, + LastRejectedReason = eveCommandReport.LastRejectedReason, + Status = eveCommandReport.RejectedCommands > 0 ? "rejected" : "ok" + }; + await node.PutEveCommandDrainStatusAsync(eveCommandStatus); + await node.PutOperationsSurfaceAsync(AetheriaOperationsSurfaceProjector.Build(drainStatus, eveCommandStatus)); + await node.PutLoadoutTemplateAsync(loadoutKey, new AetheriaLoadoutTemplate { Name = "Smoke Aether Runner", @@ -256,6 +289,7 @@ await using (var reopened = await AetheriaStateNode.OpenAsync(statePath, "aether var quarantine = await reopened.GetLegacyCatalogQuarantineAsync(); var catalogSurface = await reopened.GetCatalogSurfaceAsync(); var drainStatus = await reopened.GetRuntimeCommitDrainStatusAsync(); + var eveCommandStatus = await reopened.GetEveCommandDrainStatusAsync(); var operationsSurface = await reopened.GetOperationsSurfaceAsync(); var advertisement = await reopened.GetProviderAdvertisementAsync(); var playerSettings = await reopened.GetPlayerSettingsAsync(); @@ -297,15 +331,21 @@ await using (var reopened = await AetheriaStateNode.OpenAsync(statePath, "aether if (drainStatus?.RuntimeId != "smoke-runtime" || drainStatus.CommandsApplied != 1 || - operationsSurface?.Surface.Id != AetheriaOperationsSurfaceProjector.SurfaceId) + eveCommandStatus?.CommandsAccepted != 1 || + eveCommandStatus.CommandsRejected != 1 || + eveCommandStatus.AppliedCatalogRefreshes != 1 || + !eveCommandStatus.LastRejectedReason.Contains("not advertised", StringComparison.Ordinal) || + operationsSurface?.Surface.Id != AetheriaOperationsSurfaceProjector.SurfaceId || + !operationsSurface.Surface.Root.Children.Any(child => child.Id == "aetheria.operations.eveCommandDrain")) { - throw new InvalidOperationException("Runtime commit drain status or operations surface did not survive flush/reopen."); + throw new InvalidOperationException("Runtime commit/Eve command drain status or operations surface did not survive flush/reopen."); } if (advertisement?.ProviderId != AetheriaProviderAdvertisementProjector.ProviderId || advertisement.Surfaces.Length < 2 || !advertisement.Surfaces.Any(surface => surface.SurfaceId == AetheriaCatalogSurfaceProjector.SurfaceId) || - !advertisement.Surfaces.Any(surface => surface.SurfaceId == AetheriaOperationsSurfaceProjector.SurfaceId)) + !advertisement.Surfaces.Any(surface => surface.SurfaceId == AetheriaOperationsSurfaceProjector.SurfaceId) || + !advertisement.Schemas.Contains(AetheriaEveCommandBridge.CommandSchema)) { throw new InvalidOperationException("Aetheria Eve provider advertisement did not survive flush/reopen."); } diff --git a/Aetheria.State/AetheriaDocumentRegistry.cs b/Aetheria.State/AetheriaDocumentRegistry.cs index cb4095e23..3bac5a6b8 100644 --- a/Aetheria.State/AetheriaDocumentRegistry.cs +++ b/Aetheria.State/AetheriaDocumentRegistry.cs @@ -38,6 +38,7 @@ public static class AetheriaDocumentRegistry CultNetDocumentBinding.ForDocument(registry), CultNetDocumentBinding.ForDocument(registry), CultNetDocumentBinding.ForDocument(registry), + CultNetDocumentBinding.ForDocument(registry), CultNetDocumentBinding.ForDocument(registry), CultNetDocumentBinding.ForDocument(registry) }); @@ -59,6 +60,7 @@ public static class AetheriaDocumentRegistry typeof(AetheriaZoneState), typeof(AetheriaEntitySnapshot), typeof(AetheriaRuntimeCommitDrainStatus), + typeof(AetheriaEveCommandDrainStatus), typeof(EveSurfaceState), typeof(EveProviderAdvertisementState) ]; diff --git a/Aetheria.State/AetheriaEveCommandBridge.cs b/Aetheria.State/AetheriaEveCommandBridge.cs new file mode 100644 index 000000000..8af91ac55 --- /dev/null +++ b/Aetheria.State/AetheriaEveCommandBridge.cs @@ -0,0 +1,260 @@ +using System.Buffers; +using Aetheria.State.Documents; +using MessagePack; + +namespace Aetheria.State; + +public sealed class AetheriaEveCommandApplyReport +{ + public int AppliedCatalogRefreshes { get; set; } + public int AppliedOperationsRefreshes { get; set; } + public int RejectedCommands { get; set; } + public string[] AcceptedPaths { get; set; } = []; + public string[] RejectedPaths { get; set; } = []; + public string LastRejectedCommand { get; set; } = ""; + public string LastRejectedReason { get; set; } = ""; +} + +public static class AetheriaEveCommandBridge +{ + public const string CommandSchema = "gamecult.eve.command.v1"; + + public static string GetPendingDirectory(string stateFilePath) + { + if (string.IsNullOrWhiteSpace(stateFilePath)) + throw new ArgumentException("State file path must be non-empty.", nameof(stateFilePath)); + + return stateFilePath + ".eve.pending"; + } + + public static async Task ApplyPendingAsync( + AetheriaStateNode node, + bool deleteAccounted = true) + { + if (node == null) throw new ArgumentNullException(nameof(node)); + + var pendingDirectory = GetPendingDirectory(node.StatePath); + var report = new AetheriaEveCommandApplyReport(); + var accepted = new List(); + var rejected = new List(); + + if (!Directory.Exists(pendingDirectory)) + return report; + + foreach (var path in Directory.EnumerateFiles(pendingDirectory, "*.cc").OrderBy(path => path, StringComparer.Ordinal)) + { + var command = ReadCommand(path); + var rejection = Validate(command); + if (!string.IsNullOrWhiteSpace(rejection)) + { + RecordRejection(report, command, rejection, path, rejected, deleteAccounted); + continue; + } + + switch (command.Command) + { + case "aetheria.catalog.refresh": + await node.PutCatalogSurfaceAsync( + AetheriaCatalogSurfaceProjector.Build(node.ReadCatalogSnapshot(), command.IssuedAtUtc)).ConfigureAwait(false); + report.AppliedCatalogRefreshes++; + break; + case "aetheria.operations.refresh": + var commitStatus = await node.GetRuntimeCommitDrainStatusAsync().ConfigureAwait(false) ?? + EmptyCommitDrainStatus(node.StatePath, command.IssuedAtUtc); + var eveStatus = await node.GetEveCommandDrainStatusAsync().ConfigureAwait(false) ?? + EmptyEveCommandDrainStatus(node.StatePath, command.IssuedAtUtc); + await node.PutOperationsSurfaceAsync( + AetheriaOperationsSurfaceProjector.Build(commitStatus, eveStatus)).ConfigureAwait(false); + report.AppliedOperationsRefreshes++; + break; + } + + accepted.Add(path); + if (deleteAccounted) + File.Delete(path); + } + + await node.FlushAsync().ConfigureAwait(false); + report.AcceptedPaths = accepted.ToArray(); + report.RejectedPaths = rejected.ToArray(); + return report; + } + + public static void QueueCommand( + string stateFilePath, + string providerId, + string surfaceId, + string command, + IReadOnlyDictionary? payload = null, + string clientId = "aetheria-state") + { + var issuedAtUtc = DateTimeOffset.UtcNow.UtcDateTime.ToString("O"); + var commandId = Guid.NewGuid().ToString("N"); + var pendingDirectory = GetPendingDirectory(stateFilePath); + Directory.CreateDirectory(pendingDirectory); + + var finalPath = Path.Combine( + pendingDirectory, + $"{issuedAtUtc.Replace(':', '-')}.{StableToken(surfaceId)}.{StableToken(command)}.{commandId}.cc"); + var tempPath = finalPath + ".tmp"; + + var buffer = new ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteArrayHeader(8); + writer.Write(CommandSchema); + writer.Write(commandId); + writer.Write(providerId ?? ""); + writer.Write(surfaceId ?? ""); + writer.Write(command ?? ""); + writer.Write(issuedAtUtc); + writer.Write(clientId ?? ""); + WritePayload(ref writer, payload); + writer.Flush(); + + File.WriteAllBytes(tempPath, buffer.WrittenSpan.ToArray()); + if (File.Exists(finalPath)) + File.Delete(finalPath); + File.Move(tempPath, finalPath); + } + + private static AetheriaPendingEveCommand ReadCommand(string path) + { + var reader = new MessagePackReader(File.ReadAllBytes(path)); + var fields = reader.ReadArrayHeader(); + var command = new AetheriaPendingEveCommand + { + Schema = fields > 0 ? ReadString(ref reader) : "", + CommandId = fields > 1 ? ReadString(ref reader) : "", + ProviderId = fields > 2 ? ReadString(ref reader) : "", + SurfaceId = fields > 3 ? ReadString(ref reader) : "", + Command = fields > 4 ? ReadString(ref reader) : "", + IssuedAtUtc = fields > 5 ? ReadString(ref reader) : "", + ClientId = fields > 6 ? ReadString(ref reader) : "", + Payload = fields > 7 ? ReadPayload(ref reader) : new Dictionary(0, StringComparer.Ordinal), + Path = path + }; + for (var field = 8; field < fields; field++) + reader.Skip(); + + return command; + } + + private static string Validate(AetheriaPendingEveCommand command) + { + if (!string.Equals(command.Schema, CommandSchema, StringComparison.Ordinal)) + return $"Unexpected Eve command schema '{command.Schema}'."; + if (!string.Equals(command.ProviderId, AetheriaProviderAdvertisementProjector.ProviderId, StringComparison.Ordinal)) + return $"Unexpected Eve provider '{command.ProviderId}'."; + if (!KnownCommand(command.SurfaceId, command.Command)) + return $"Command '{command.Command}' is not advertised for surface '{command.SurfaceId}'."; + + return ""; + } + + private static bool KnownCommand(string surfaceId, string command) + { + return (string.Equals(surfaceId, AetheriaCatalogSurfaceProjector.SurfaceId, StringComparison.Ordinal) && + string.Equals(command, "aetheria.catalog.refresh", StringComparison.Ordinal)) || + (string.Equals(surfaceId, AetheriaOperationsSurfaceProjector.SurfaceId, StringComparison.Ordinal) && + string.Equals(command, "aetheria.operations.refresh", StringComparison.Ordinal)); + } + + private static void RecordRejection( + AetheriaEveCommandApplyReport report, + AetheriaPendingEveCommand command, + string reason, + string path, + List rejected, + bool deleteAccounted) + { + report.RejectedCommands++; + report.LastRejectedCommand = string.IsNullOrWhiteSpace(command.Command) + ? command.CommandId + : command.Command; + report.LastRejectedReason = reason; + rejected.Add(path); + if (deleteAccounted) + File.Delete(path); + } + + private static AetheriaRuntimeCommitDrainStatus EmptyCommitDrainStatus(string statePath, string now) + { + return new AetheriaRuntimeCommitDrainStatus + { + RuntimeId = "aetheria-state", + StatePath = statePath, + LastPollAtUtc = now, + Status = "idle" + }; + } + + private static AetheriaEveCommandDrainStatus EmptyEveCommandDrainStatus(string statePath, string now) + { + return new AetheriaEveCommandDrainStatus + { + RuntimeId = "aetheria-state", + StatePath = statePath, + LastPollAtUtc = now, + Status = "idle" + }; + } + + private static void WritePayload(ref MessagePackWriter writer, IReadOnlyDictionary? payload) + { + payload ??= new Dictionary(0, StringComparer.Ordinal); + writer.WriteMapHeader(payload.Count); + foreach (var entry in payload.OrderBy(entry => entry.Key, StringComparer.Ordinal)) + { + writer.Write(entry.Key ?? ""); + writer.Write(entry.Value ?? ""); + } + } + + private static IReadOnlyDictionary ReadPayload(ref MessagePackReader reader) + { + var count = reader.ReadMapHeader(); + var payload = new Dictionary(count, StringComparer.Ordinal); + for (var index = 0; index < count; index++) + { + var key = ReadString(ref reader); + var value = ReadString(ref reader); + if (!string.IsNullOrWhiteSpace(key)) + payload[key] = value; + } + + return payload; + } + + 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; + } + + private static string ReadString(ref MessagePackReader reader) + { + return reader.ReadString() ?? ""; + } + + private sealed class AetheriaPendingEveCommand + { + public string Schema { get; set; } = ""; + public string CommandId { get; set; } = ""; + public string ProviderId { get; set; } = ""; + public string SurfaceId { get; set; } = ""; + public string Command { get; set; } = ""; + public string IssuedAtUtc { get; set; } = ""; + public string ClientId { get; set; } = ""; + public IReadOnlyDictionary Payload { get; set; } = + new Dictionary(0, StringComparer.Ordinal); + public string Path { get; set; } = ""; + } +} diff --git a/Aetheria.State/AetheriaOperationsSurfaceProjector.cs b/Aetheria.State/AetheriaOperationsSurfaceProjector.cs index 6b6c44cc9..96498b436 100644 --- a/Aetheria.State/AetheriaOperationsSurfaceProjector.cs +++ b/Aetheria.State/AetheriaOperationsSurfaceProjector.cs @@ -7,15 +7,19 @@ public static class AetheriaOperationsSurfaceProjector public const string SurfaceKey = "eve:surface:aetheria.operations"; public const string SurfaceId = "aetheria.operations"; - public static EveSurfaceState Build(AetheriaRuntimeCommitDrainStatus drainStatus, long version = 1) + public static EveSurfaceState Build( + AetheriaRuntimeCommitDrainStatus drainStatus, + AetheriaEveCommandDrainStatus? eveCommandStatus = null, + long version = 1) { + var updatedAtUtc = LatestTimestamp(drainStatus.LastPollAtUtc, eveCommandStatus?.LastPollAtUtc); return new EveSurfaceState { ProviderId = "aetheria", ProviderKind = "game.runtime", Title = "Aetheria Operations", Version = version, - UpdatedAtUtc = drainStatus.LastPollAtUtc, + UpdatedAtUtc = updatedAtUtc, Surface = new EveSurface { Id = SurfaceId, @@ -39,7 +43,26 @@ public static class AetheriaOperationsSurfaceProjector ("runtime", drainStatus.RuntimeId), ("lastPoll", drainStatus.LastPollAtUtc), ("lastApplied", drainStatus.LastAppliedAtUtc), - ("error", drainStatus.LastError)))) + ("error", drainStatus.LastError))), + Node( + "aetheria.operations.eveCommandDrain", + "card", + [("title", "Eve Command Drain")], + Metric("eveCommandDrain.status", "Status", eveCommandStatus?.Status ?? "missing"), + Metric("eveCommandDrain.pending", "Pending Before Apply", (eveCommandStatus?.PendingBeforeApply ?? 0).ToString()), + Metric("eveCommandDrain.accepted", "Commands Accepted", (eveCommandStatus?.CommandsAccepted ?? 0).ToString()), + Metric("eveCommandDrain.rejected", "Commands Rejected", (eveCommandStatus?.CommandsRejected ?? 0).ToString()), + Metric("eveCommandDrain.catalogRefreshes", "Catalog Refreshes", (eveCommandStatus?.AppliedCatalogRefreshes ?? 0).ToString()), + Metric("eveCommandDrain.operationsRefreshes", "Operations Refreshes", (eveCommandStatus?.AppliedOperationsRefreshes ?? 0).ToString()), + Metric("eveCommandDrain.failures", "Consecutive Failures", (eveCommandStatus?.ConsecutiveFailures ?? 0).ToString()), + Row( + "eveCommandDrain.last", + ("runtime", eveCommandStatus?.RuntimeId ?? ""), + ("lastPoll", eveCommandStatus?.LastPollAtUtc ?? ""), + ("lastAccepted", eveCommandStatus?.LastAcceptedAtUtc ?? ""), + ("lastRejected", eveCommandStatus?.LastRejectedCommand ?? ""), + ("rejectedReason", eveCommandStatus?.LastRejectedReason ?? ""), + ("error", eveCommandStatus?.LastError ?? "")))) }, Commands = [ @@ -53,6 +76,16 @@ public static class AetheriaOperationsSurfaceProjector }; } + private static string LatestTimestamp(string first, string? second) + { + if (string.IsNullOrWhiteSpace(second)) + return first; + if (string.IsNullOrWhiteSpace(first)) + return second; + + return string.CompareOrdinal(second, first) > 0 ? second : first; + } + private static EveSurfaceComponent Metric(string id, string label, string value) { return Node(id, "metric", [("label", label), ("value", value)]); diff --git a/Aetheria.State/AetheriaProviderAdvertisementProjector.cs b/Aetheria.State/AetheriaProviderAdvertisementProjector.cs index 66f60ce10..9507e0197 100644 --- a/Aetheria.State/AetheriaProviderAdvertisementProjector.cs +++ b/Aetheria.State/AetheriaProviderAdvertisementProjector.cs @@ -39,7 +39,9 @@ public static class AetheriaProviderAdvertisementProjector "aetheria.zone_state.v1", "aetheria.entity_snapshot.v1", "aetheria.runtime_commit_drain_status.v1", - "gamecult.eve.surface.v1" + "aetheria.eve_command_drain_status.v1", + "gamecult.eve.surface.v1", + "gamecult.eve.command.v1" ], Witnesses = [ diff --git a/Aetheria.State/AetheriaStateNode.cs b/Aetheria.State/AetheriaStateNode.cs index a1e3f07a8..860baff18 100644 --- a/Aetheria.State/AetheriaStateNode.cs +++ b/Aetheria.State/AetheriaStateNode.cs @@ -261,6 +261,18 @@ public sealed class AetheriaStateNode : IAsyncDisposable, IDisposable new CultRecordKey("global:aetheria.runtime_commit_drain_status.v1")); } + public Task> PutEveCommandDrainStatusAsync( + AetheriaEveCommandDrainStatus status) + { + return Database.PutAsync(new CultRecordKey("global:aetheria.eve_command_drain_status.v1"), status); + } + + public Task GetEveCommandDrainStatusAsync() + { + return Database.GetAsync( + new CultRecordKey("global:aetheria.eve_command_drain_status.v1")); + } + public Task FlushAsync(bool soft = false) { return _node.FlushAsync(soft); diff --git a/Aetheria.State/Documents/AetheriaEveCommandDrainStatus.cs b/Aetheria.State/Documents/AetheriaEveCommandDrainStatus.cs new file mode 100644 index 000000000..ab2d06399 --- /dev/null +++ b/Aetheria.State/Documents/AetheriaEveCommandDrainStatus.cs @@ -0,0 +1,57 @@ +using GameCult.Caching; +using MessagePack; + +namespace Aetheria.State.Documents; + +[CultDocument("aetheria.eve_command_drain_status", "aetheria.eve_command_drain_status.v1")] +[CultGlobal] +[MessagePackObject] +public sealed class AetheriaEveCommandDrainStatus +{ + [Key(0)] + [CultName] + public string Name { get; set; } = "Aetheria Eve command drain"; + + [Key(1)] + [CultIndex("runtimeId")] + public string RuntimeId { get; set; } = ""; + + [Key(2)] + public string StatePath { get; set; } = ""; + + [Key(3)] + public string LastPollAtUtc { get; set; } = ""; + + [Key(4)] + public string LastAcceptedAtUtc { get; set; } = ""; + + [Key(5)] + public int PendingBeforeApply { get; set; } + + [Key(6)] + public int CommandsAccepted { get; set; } + + [Key(7)] + public int CommandsRejected { get; set; } + + [Key(8)] + public int AppliedCatalogRefreshes { get; set; } + + [Key(9)] + public int AppliedOperationsRefreshes { get; set; } + + [Key(10)] + public int ConsecutiveFailures { get; set; } + + [Key(11)] + public string LastError { get; set; } = ""; + + [Key(12)] + public string LastRejectedCommand { get; set; } = ""; + + [Key(13)] + public string LastRejectedReason { get; set; } = ""; + + [Key(14)] + public string Status { get; set; } = "ok"; +} diff --git a/Aetheria.State/README.md b/Aetheria.State/README.md index 75c542128..8254ce71a 100644 --- a/Aetheria.State/README.md +++ b/Aetheria.State/README.md @@ -29,6 +29,12 @@ runtime commit envelopes beside `GameData/aetheria-world.cc`. `Aetheria.State` owns applying those envelopes into canonical typed state through `AetheriaRuntimeCommitLogApplier`; the Unity-side command log is command-only and cannot become durable truth by itself. +Unity Eve surfaces also emit `gamecult.eve.command.v1` envelopes under +`GameData/aetheria-world.cc.eve.pending`. `AetheriaEveCommandBridge` is the +provider-owned acceptance organ for those commands: it validates the provider, +surface, and command template before running the narrow refresh handlers for +the catalog and operations surfaces. Renderer callbacks do not accept commands +or mutate game state locally. The old `SavedGame`/`SavedZone` DTOs and `Galaxy` loader constructor have also been deleted; the new document family is live Verse run/zone state, not a bespoke save-file format. @@ -130,22 +136,25 @@ zone/entity snapshots can be queued, applied through `Aetheria.State`, and cleared. `Economy.Server` opens the CultMesh state host, applies pending runtime commits -on startup, and polls for new pending commits while running. For a bounded -one-shot drain without leaving the host running: +and pending Eve surface commands on startup, and polls for new pending work +while running. For a bounded one-shot drain without leaving the host running: ```powershell dotnet run --project .\Economy.Server\Economy.Server.csproj -- --apply-pending-once ``` -The server publishes `AetheriaRuntimeCommitDrainStatus` and the -`aetheria.operations` Eve surface after each drain attempt, so pending depth, -applied counts, failures, and timestamps are typed state rather than console-only -status. It also publishes `gamecult.eve.provider_advertisement.v1` for the -`aetheria` provider, advertising the catalog and operations surfaces plus the -typed schemas witnessed by the local `.cc` state file. +The server publishes `AetheriaRuntimeCommitDrainStatus`, +`AetheriaEveCommandDrainStatus`, and the `aetheria.operations` Eve surface after +drain attempts, so pending depth, accepted/applied/rejected counts, failures, +and timestamps are typed state rather than console-only status. It also +publishes `gamecult.eve.provider_advertisement.v1` for the `aetheria` provider, +advertising the catalog and operations surfaces plus the typed schemas witnessed +by the local `.cc` state file. `Aetheria.State.ApplyPending` is the smaller local operator applicator for -queued Unity runtime commits when the server host is not being used: +queued Unity runtime commits and Eve commands when the server host is not being +used. It also republishes the typed drain status, operations surface, and +provider advertisement after applying pending files: ```powershell dotnet run --project .\Aetheria.State.ApplyPending\Aetheria.State.ApplyPending.csproj -- . diff --git a/Economy.Server/Program.cs b/Economy.Server/Program.cs index 5802e05f7..7d0974e06 100644 --- a/Economy.Server/Program.cs +++ b/Economy.Server/Program.cs @@ -19,11 +19,12 @@ internal static class Program await EnsureWorldDocumentAsync(node).ConfigureAwait(false); await ApplyPendingRuntimeCommitsAsync(node).ConfigureAwait(false); + await ApplyPendingEveCommandsAsync(node).ConfigureAwait(false); await node.FlushAsync().ConfigureAwait(false); if (HasFlag(args, "--apply-pending-once")) { - Console.WriteLine("Aetheria pending runtime commit drain completed."); + Console.WriteLine("Aetheria pending runtime and Eve command drains completed."); return; } @@ -129,9 +130,92 @@ internal static class Program AetheriaRuntimeCommitDrainStatus status) { await node.PutRuntimeCommitDrainStatusAsync(status).ConfigureAwait(false); - await node.PutOperationsSurfaceAsync(AetheriaOperationsSurfaceProjector.Build(status)).ConfigureAwait(false); + await PublishOperationsStateAsync(node, status.LastPollAtUtc).ConfigureAwait(false); + } + + private static async Task ApplyPendingEveCommandsAsync(AetheriaStateNode node) + { + var pendingBefore = CountPendingEveCommands(node.StatePath); + var now = DateTimeOffset.UtcNow.ToString("O"); + + try + { + var report = await AetheriaEveCommandBridge.ApplyPendingAsync(node).ConfigureAwait(false); + var status = new AetheriaEveCommandDrainStatus + { + RuntimeId = RuntimeId, + StatePath = node.StatePath, + LastPollAtUtc = now, + LastAcceptedAtUtc = report.AcceptedPaths.Length > 0 ? now : "", + PendingBeforeApply = pendingBefore, + CommandsAccepted = report.AcceptedPaths.Length, + CommandsRejected = report.RejectedCommands, + AppliedCatalogRefreshes = report.AppliedCatalogRefreshes, + AppliedOperationsRefreshes = report.AppliedOperationsRefreshes, + LastRejectedCommand = report.LastRejectedCommand, + LastRejectedReason = report.LastRejectedReason, + ConsecutiveFailures = 0, + Status = report.RejectedCommands > 0 ? "rejected" : "ok" + }; + await PublishEveCommandStatusAsync(node, status).ConfigureAwait(false); + + if (report.AcceptedPaths.Length == 0 && report.RejectedCommands == 0) + { + Console.WriteLine("No pending Aetheria Eve commands."); + return; + } + + Console.WriteLine( + "Drained pending Aetheria Eve commands: " + + $"accepted={report.AcceptedPaths.Length}, " + + $"rejected={report.RejectedCommands}, " + + $"catalogRefreshes={report.AppliedCatalogRefreshes}, " + + $"operationsRefreshes={report.AppliedOperationsRefreshes}"); + } + catch (Exception ex) + { + var existing = await node.GetEveCommandDrainStatusAsync().ConfigureAwait(false); + var status = new AetheriaEveCommandDrainStatus + { + RuntimeId = RuntimeId, + StatePath = node.StatePath, + LastPollAtUtc = now, + LastAcceptedAtUtc = existing?.LastAcceptedAtUtc ?? "", + PendingBeforeApply = pendingBefore, + ConsecutiveFailures = (existing?.ConsecutiveFailures ?? 0) + 1, + LastError = ex.ToString(), + Status = "error" + }; + await PublishEveCommandStatusAsync(node, status).ConfigureAwait(false); + throw; + } + } + + private static async Task PublishEveCommandStatusAsync( + AetheriaStateNode node, + AetheriaEveCommandDrainStatus status) + { + await node.PutEveCommandDrainStatusAsync(status).ConfigureAwait(false); + await PublishOperationsStateAsync(node, status.LastPollAtUtc).ConfigureAwait(false); + } + + private static async Task PublishOperationsStateAsync( + AetheriaStateNode node, + string updatedAtUtc) + { + var commitStatus = await node.GetRuntimeCommitDrainStatusAsync().ConfigureAwait(false) ?? + new AetheriaRuntimeCommitDrainStatus + { + RuntimeId = RuntimeId, + StatePath = node.StatePath, + LastPollAtUtc = updatedAtUtc, + Status = "idle" + }; + var eveStatus = await node.GetEveCommandDrainStatusAsync().ConfigureAwait(false); + await node.PutOperationsSurfaceAsync(AetheriaOperationsSurfaceProjector.Build(commitStatus, eveStatus)) + .ConfigureAwait(false); await node.PutProviderAdvertisementAsync( - AetheriaProviderAdvertisementProjector.Build(node.StatePath, status.LastPollAtUtc)).ConfigureAwait(false); + AetheriaProviderAdvertisementProjector.Build(node.StatePath, updatedAtUtc)).ConfigureAwait(false); await node.FlushAsync().ConfigureAwait(false); } @@ -143,6 +227,14 @@ internal static class Program : 0; } + private static int CountPendingEveCommands(string statePath) + { + var pendingDirectory = AetheriaEveCommandBridge.GetPendingDirectory(statePath); + return Directory.Exists(pendingDirectory) + ? Directory.EnumerateFiles(pendingDirectory, "*.cc").Count() + : 0; + } + private static async Task RunUntilShutdownAsync(AetheriaStateNode node, TimeSpan pendingInterval) { var stopped = new TaskCompletionSource(); @@ -160,6 +252,7 @@ internal static class Program break; await ApplyPendingRuntimeCommitsAsync(node).ConfigureAwait(false); + await ApplyPendingEveCommandsAsync(node).ConfigureAwait(false); } } diff --git a/Packages/org.gamecult.aetheria.eve-runtime/README.md b/Packages/org.gamecult.aetheria.eve-runtime/README.md index fd5d70f51..0078d0a58 100644 --- a/Packages/org.gamecult.aetheria.eve-runtime/README.md +++ b/Packages/org.gamecult.aetheria.eve-runtime/README.md @@ -8,7 +8,7 @@ CultCache state into Unity UI Toolkit. - it reads `gamecult.eve.surface.v1` from `GameData/aetheria-world.cc`; - it lowers the retained tree through `org.gamecult.eve.unity-uitoolkit`; - it queues renderer-emitted commands as typed `.cc.eve.pending` command - envelopes for the future CultMesh command bridge. + envelopes for Aetheria's provider-owned command bridge. Commands are surfaced as `gamecult.eve.command.v1` requests. The presenter does not accept or apply them locally; provider acceptance still belongs to the diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEveCommandLog.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEveCommandLog.cs index 27d116405..372578ddc 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEveCommandLog.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEveCommandLog.cs @@ -94,11 +94,11 @@ namespace GameCult.Aetheria.State.Unity return new AetheriaRuntimeEveCommandEnvelope( CommandSchema, commandId, - request.ProviderId, - request.SurfaceId, - request.Command, + request.ProviderId ?? "", + request.SurfaceId ?? "", + request.Command ?? "", issuedAtUtc, - request.ClientId, + request.ClientId ?? "", new Dictionary(request.Payload, StringComparer.Ordinal), finalPath); } diff --git a/docs/aetheria-perfect-machine-map.md b/docs/aetheria-perfect-machine-map.md index d2538cc88..3ea94a115 100644 --- a/docs/aetheria-perfect-machine-map.md +++ b/docs/aetheria-perfect-machine-map.md @@ -42,9 +42,10 @@ legacy catalog cache, and legacy UI paths should be migration-only or deleted. legacy `PlayerSettings` runtime object is no longer decorated as a MessagePack persistence shape. `Economy.Server` now drains `aetheria-world.cc.pending` - into canonical typed state on startup and on a daemon polling loop while - hosting the CultMesh state node. `Aetheria.State.ApplyPending` remains a - bounded local operator applicator. + into canonical typed state and drains `aetheria-world.cc.eve.pending` through + the provider-owned Eve command bridge on startup and on a daemon polling loop + while hosting the CultMesh state node. `Aetheria.State.ApplyPending` remains a + bounded local operator applicator for both pending lanes. - Shared domain state is still partly built around `DatabaseEntry`, GUID identity, MessagePack attributes, and static cache references. Newtonsoft, JsonKnownTypes, RethinkDB, LiteNetLib client transport, and the broken @@ -290,8 +291,11 @@ legacy catalog cache, and legacy UI paths should be migration-only or deleted. `UIDocument` presenter that reads provider-owned Eve surfaces from `GameData/aetheria-world.cc` and mounts them through the lowerer. Its command path queues `gamecult.eve.command.v1` envelopes under - `aetheria-world.cc.eve.pending` for the future CultMesh command bridge - instead of accepting renderer-local command effects. + `aetheria-world.cc.eve.pending` for the provider-owned command bridge instead + of accepting renderer-local command effects. `AetheriaEveCommandBridge` + currently accepts the advertised catalog/operations refresh commands, + republishes provider-owned surfaces, rejects unknown/unadvertised commands, + and records `AetheriaEveCommandDrainStatus` as typed state. ## Invariants @@ -558,9 +562,12 @@ First Aetheria surfaces to publish: `gamecult.eve.command.v1` envelopes under `.eve.pending`, separate from runtime state commits so the existing state applicator cannot accidentally accept commands it does not own. - - Add the CultMesh command bridge that drains `.eve.pending`, validates - command templates, invokes provider-owned command handlers, and republishes - accepted state. + - Done: add the provider-owned Eve command bridge that drains `.eve.pending`, + validates provider/surface/command templates, invokes the current refresh + handlers, republishes accepted surfaces, rejects unknown commands, and + records typed command-drain status. + - Extend the command bridge beyond refresh commands as gameplay/editor Eve + surfaces acquire provider-owned handlers. - Wire the presenter into a Unity scene/prefab for the first runtime surface and replace a concrete uGUI screen. - Move the staged packages into the Eve repo once its worktree is clean, then @@ -592,6 +599,8 @@ First Aetheria surfaces to publish: and daemon polling, with `--apply-pending-once` for bounded operation. - Done: publish pending-drain health as typed CultCache state and an Eve operations surface. + - Done: publish Eve command-drain health as typed CultCache state and include + it in the operations surface. - Done: publish an Eve provider advertisement so Odin/Eve can discover Aetheria surfaces and command boundaries through typed state. - Done: stop legacy catalog pull/read paths from writing entries back to @@ -638,6 +647,10 @@ First Aetheria surfaces to publish: can apply them into canonical typed settings/run/zone/entity state, and commands are cleared after application. It also proves renderer-emitted Eve commands are queued as typed command envelopes separately from state commits. +- `Aetheria.State.Smoke` proves the provider-owned Eve command bridge drains + `gamecult.eve.command.v1` envelopes, accepts advertised refresh commands, + rejects unknown commands, persists `AetheriaEveCommandDrainStatus`, and exposes + the Eve command drain through the operations surface. - Unity play smoke proves runtime UI reads from Eve surfaces and sends commands through the shared state service. - UI Toolkit lowering parity compares Aetheria surfaces against the Eve browser