From 1a87ac35b43e58360c165f3b71bc6c1664210d73 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 20 May 2026 07:45:10 +0100 Subject: [PATCH] Add CultMesh game session facade --- src/GameCult.Mesh/CultMesh.cs | 10 + src/GameCult.Mesh/CultMeshGameSession.cs | 234 ++++++++++++++++++ src/GameCult.Mesh/README.md | 30 +++ src/GameCult.Mesh/docs/public-api.md | 6 + .../Contracts/cultnet-distributed-database.md | 9 +- .../NetworkingTests.cs | 68 +++++ 6 files changed, 355 insertions(+), 2 deletions(-) create mode 100644 src/GameCult.Mesh/CultMeshGameSession.cs diff --git a/src/GameCult.Mesh/CultMesh.cs b/src/GameCult.Mesh/CultMesh.cs index 70899b28..a5b7ae3a 100644 --- a/src/GameCult.Mesh/CultMesh.cs +++ b/src/GameCult.Mesh/CultMesh.cs @@ -220,6 +220,16 @@ namespace GameCult.Mesh return new CultMeshSimulationFactCommitter(database); } + /// + /// Creates a gameplay-facing session facade over a CultMesh node. + /// + public static CultMeshGameSession CreateGameSession( + CultMeshNode node, + CultMeshGameSessionOptions? options = null) + { + return new CultMeshGameSession(node, options); + } + /// /// Attaches Verse discovery responses to a CultMesh node. /// diff --git a/src/GameCult.Mesh/CultMeshGameSession.cs b/src/GameCult.Mesh/CultMeshGameSession.cs new file mode 100644 index 00000000..d34c1860 --- /dev/null +++ b/src/GameCult.Mesh/CultMeshGameSession.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Networking; +using R3; + +namespace GameCult.Mesh +{ + /// + /// Options for creating a gameplay-facing CultMesh session facade. + /// + public sealed class CultMeshGameSessionOptions + { + /// + /// Gets or sets the Verse catalog used by the session. + /// + public CultMeshVerseCatalog? VerseCatalog { get; set; } + + /// + /// Gets or sets the peer catalog used by the session. + /// + public CultMeshPeerCatalog? PeerCatalog { get; set; } + + /// + /// Gets or sets the authority lease catalog used by the session. + /// + public CultMeshAuthorityLeaseCatalog? AuthorityLeases { get; set; } + + /// + /// Gets or sets simulation consensus options. + /// + public CultNetSimulationConsensusOptions? ConsensusOptions { get; set; } + + /// + /// Gets or sets whether incoming observation messages should update the session hub. + /// + public bool ServeSimulationObservations { get; set; } = true; + + /// + /// Gets or sets whether the node should answer Verse catalog requests from the session catalog. + /// + public bool ServeVerseDiscovery { get; set; } = true; + + /// + /// Gets or sets whether the node should answer peer exchange requests from the session peer catalog. + /// + public bool ServePeerExchange { get; set; } = true; + } + + /// + /// Gameplay-facing facade over common CultMesh runtime pieces. + /// + public sealed class CultMeshGameSession : IDisposable + { + private readonly List _owned = new(); + private readonly HashSet _committedFactIds = new(StringComparer.Ordinal); + private bool _disposed; + + /// + /// Creates a game session facade. + /// + public CultMeshGameSession(CultMeshNode node, CultMeshGameSessionOptions? options = null) + { + Node = node ?? throw new ArgumentNullException(nameof(node)); + options ??= new CultMeshGameSessionOptions(); + VerseCatalog = options.VerseCatalog ?? new CultMeshVerseCatalog(); + PeerCatalog = options.PeerCatalog ?? new CultMeshPeerCatalog(); + AuthorityLeases = options.AuthorityLeases ?? new CultMeshAuthorityLeaseCatalog(); + ObservationHub = new CultNetSimulationObservationHub(options.ConsensusOptions); + FactCommitter = new CultMeshSimulationFactCommitter(Node.Database); + + if (options.VerseCatalog == null) + { + _owned.Add(VerseCatalog); + } + + if (options.PeerCatalog == null) + { + _owned.Add(PeerCatalog); + } + + if (options.ServeSimulationObservations) + { + _owned.Add(new CultNetSimulationObservationServer(Node.Server, ObservationHub)); + } + + if (options.ServeVerseDiscovery) + { + _owned.Add(new CultMeshVerseDiscoveryServer(Node.Server, VerseCatalog)); + } + + if (options.ServePeerExchange) + { + _owned.Add(new CultMeshPeerExchangeServer(Node.Server, PeerCatalog)); + } + } + + /// + /// Gets the underlying node. + /// + public CultMeshNode Node { get; } + + /// + /// Gets the session Verse catalog. + /// + public CultMeshVerseCatalog VerseCatalog { get; } + + /// + /// Gets the session peer catalog. + /// + public CultMeshPeerCatalog PeerCatalog { get; } + + /// + /// Gets the session authority lease catalog. + /// + public CultMeshAuthorityLeaseCatalog AuthorityLeases { get; } + + /// + /// Gets the session simulation observation hub. + /// + public CultNetSimulationObservationHub ObservationHub { get; } + + /// + /// Gets the session simulation fact committer. + /// + public CultMeshSimulationFactCommitter FactCommitter { get; } + + /// + /// Watches consensus candidate updates. + /// + public Observable WatchCandidates() + { + ThrowIfDisposed(); + return ObservationHub.WatchCandidates(); + } + + /// + /// Watches committed simulation facts. + /// + public Observable> WatchSimulationFacts() + { + ThrowIfDisposed(); + return Node.Database.Watch(); + } + + /// + /// Applies a local client prediction through the underlying database. + /// + public Task> PredictAsync(CultRecordKey key, T document) where T : class + { + ThrowIfDisposed(); + return Node.Database.PutPredictedAsync(key, document); + } + + /// + /// Submits one witness observation and returns the current candidates for that subject. + /// + public IReadOnlyList SubmitObservation( + CultNetSimulationObservation observation) + { + ThrowIfDisposed(); + return ObservationHub.Submit(observation); + } + + /// + /// Submits one witness observation and commits any new quorum facts it creates. + /// + public async Task>> SubmitAndCommitAsync( + CultNetSimulationObservation observation) + { + ThrowIfDisposed(); + var candidates = ObservationHub.Submit(observation); + return await CommitQuorumCandidatesAsync(candidates).ConfigureAwait(false); + } + + /// + /// Commits quorum candidates that have not already been committed by this session. + /// + public async Task>> CommitQuorumCandidatesAsync( + IEnumerable candidates) + { + ThrowIfDisposed(); + if (candidates == null) throw new ArgumentNullException(nameof(candidates)); + + var handles = new List>(); + foreach (var candidate in candidates.Where(candidate => candidate.HasQuorum)) + { + var factId = CultMeshSimulationFact.ComputeFactId(candidate); + if (!_committedFactIds.Add(factId)) + { + continue; + } + + var key = CultMeshSimulationFact.CreateRecordKey(candidate); + if (await Node.Database.GetAsync(key).ConfigureAwait(false) != null) + { + continue; + } + + handles.Add(await FactCommitter.CommitAsync(candidate).ConfigureAwait(false)); + } + + return handles; + } + + /// + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + foreach (var owned in _owned) + { + owned.Dispose(); + } + + ObservationHub.Dispose(); + _owned.Clear(); + } + + private void ThrowIfDisposed() + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(CultMeshGameSession)); + } + } + } +} diff --git a/src/GameCult.Mesh/README.md b/src/GameCult.Mesh/README.md index b3baf9fa..412eb620 100644 --- a/src/GameCult.Mesh/README.md +++ b/src/GameCult.Mesh/README.md @@ -136,6 +136,36 @@ using var sub = db.WatchRecord(inputKey) }); ``` +## Game Session + +`CultMeshGameSession` wires the common gameplay loop: local catalogs, +observation hub, observation server, peer exchange, Verse discovery, prediction, +and quorum fact commits. + +```csharp +using var session = CultMesh.CreateGameSession(node, new CultMeshGameSessionOptions +{ + ConsensusOptions = new CultNetSimulationConsensusOptions + { + MinimumWitnesses = 2, + QuorumRatio = 0.66d + } +}); + +await session.PredictAsync(inputKey, inputState); + +var committed = await session.SubmitAndCommitAsync(new CultNetSimulationObservation +{ + WitnessRuntimeId = "watcher-1", + ShardId = "arena", + ShardEpoch = 4, + Frame = 100, + SubjectId = "bob", + ClaimKind = "hit", + ClaimHash = CultNetSimulationObservation.ComputeClaimHash("hit", "alice", "bob", "frame:100") +}); +``` + ## Witness Consensus CultMesh nodes can publish observations about simulation facts: shard epoch, diff --git a/src/GameCult.Mesh/docs/public-api.md b/src/GameCult.Mesh/docs/public-api.md index 5ad699c0..51351f51 100644 --- a/src/GameCult.Mesh/docs/public-api.md +++ b/src/GameCult.Mesh/docs/public-api.md @@ -16,6 +16,7 @@ Namespace: `GameCult.Mesh` - `CultMesh.CreatePeerExchangeClient(...)` - `CultMesh.CreateAuthorityLeaseCatalog()` - `CultMesh.CreateSimulationFactCommitter(...)` +- `CultMesh.CreateGameSession(...)` - `CultMesh.CreateClient(...)` - `CultMesh.ConnectClient(...)` @@ -112,3 +113,8 @@ replica cursor to the snapshot's represented log sequence. Candidates are opinions. `CultMeshSimulationFactCommitter` commits quorum candidates as `CultMeshSimulationFact` documents through `CultNetDatabase`, so final world state still belongs in the authoritative shard log. + +`CultMeshGameSession` is the gameplay-facing composition layer. It owns the +common loop for prediction, observations, candidate watches, simulation fact +watches, and committing new quorum facts without forcing game code to manually +wire every bridge. diff --git a/src/GameCult.Networking/Contracts/cultnet-distributed-database.md b/src/GameCult.Networking/Contracts/cultnet-distributed-database.md index 68b1ef92..42faa603 100644 --- a/src/GameCult.Networking/Contracts/cultnet-distributed-database.md +++ b/src/GameCult.Networking/Contracts/cultnet-distributed-database.md @@ -82,6 +82,8 @@ Implemented: - deterministic consensus candidates derived from witness observations - committed CultMesh simulation fact documents written from quorum candidates through shard authority +- gameplay-facing CultMesh session facade for prediction, observations, + catalogs, peer exchange, and quorum fact commits - schema-v0 simulation observation and consensus candidate messages - reactive simulation observation hub that receives witness gossip and emits consensus candidates @@ -128,6 +130,9 @@ Not implemented yet: - `CultMeshSimulationFact` is the committed form of a quorum candidate. It is written through `CultNetDatabase`, so normal shard authority and replication rules still apply. +- `CultMeshGameSession` composes common gameplay surfaces. It does not create a + second authority path; all committed state still flows through shard-owned + database writes. - Peer cards are contact candidates. They can advertise roles and authority lease ids, but they do not grant authority without Verse-specific validation. - Authority leases bind peer id, Verse id, roles, optional shard scope, issuer, @@ -141,8 +146,8 @@ Add discovery fanout and operational polish: - add periodic gossip fanout over known peer cards - add real signature verification for authority leases - add snapshot throttling and size limits for public mesh edges -- after that, add simulation-frame rollback/resimulation helpers around - predicted input streams +- add simulation-frame rollback/resimulation helpers around predicted input + streams - add peer-to-peer fanout for observation gossip and candidate propagation The log is wire-readable, replicas can apply it explicitly, a pull loop can diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index a58b694d..381ffaf0 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -2097,6 +2097,74 @@ namespace GameCult.Networking.Tests Assert.That(log[0].Kind, Is.EqualTo(CultNetDatabaseChangeKind.Added)); } + [Test] + public async Task CultMeshGameSession_SubmitsWitnesses_AndCommitsQuorumFact() + { + var rootPath = Path.Combine(TestContext.CurrentContext.WorkDirectory, "cultmesh-session", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(rootPath); + var cachePath = Path.Combine(rootPath, "world.ccmp"); + var schemaId = new CultCache().Registry.GetRequired().SchemaId; + using var node = await CultMesh.CreateNodeAsync(cachePath, new CultMeshNodeOptions + { + StartServer = false, + DatabaseOptions = new CultNetDatabaseOptions + { + Shards = + [ + new CultNetShardDescriptor( + "arena", + "runtime-a", + epoch: 4, + isPrimary: true, + schemaIds: [schemaId], + keyPrefix: "simulation:") + ] + } + }); + using var session = CultMesh.CreateGameSession(node, new CultMeshGameSessionOptions + { + ConsensusOptions = new CultNetSimulationConsensusOptions + { + MinimumWitnesses = 2, + QuorumRatio = 1d + }, + ServeSimulationObservations = false, + ServeVerseDiscovery = false, + ServePeerExchange = false + }); + var committed = new List>(); + using var facts = session.WatchSimulationFacts().Subscribe(committed.Add); + var claimHash = CultNetSimulationObservation.ComputeClaimHash("hit", "alice", "bob", "frame:100"); + + var firstCommit = await session.SubmitAndCommitAsync(new CultNetSimulationObservation + { + WitnessRuntimeId = "watcher-1", + ShardId = "arena", + ShardEpoch = 4, + Frame = 100, + SubjectId = "bob", + ClaimKind = "hit", + ClaimHash = claimHash, + ClaimSummary = "alice shot bob first" + }); + var secondCommit = await session.SubmitAndCommitAsync(new CultNetSimulationObservation + { + WitnessRuntimeId = "watcher-2", + ShardId = "arena", + ShardEpoch = 4, + Frame = 100, + SubjectId = "bob", + ClaimKind = "hit", + ClaimHash = claimHash, + ClaimSummary = "alice shot bob first" + }); + + Assert.That(firstCommit, Is.Empty); + Assert.That(secondCommit, Has.Count.EqualTo(1)); + Assert.That(node.Cache.Get(secondCommit[0].Key)!.ClaimHash, Is.EqualTo(claimHash)); + Assert.That(committed.Exists(change => change.Document?.ClaimHash == claimHash), Is.True); + } + [Test] public void CultMeshSimulationFactCommitter_Rejects_CandidateWithoutQuorum() {