Add CultMesh game session facade

This commit is contained in:
Meta Vens 2026-05-20 07:45:10 +01:00
commit 1a87ac35b4
6 changed files with 355 additions and 2 deletions

View file

@ -220,6 +220,16 @@ namespace GameCult.Mesh
return new CultMeshSimulationFactCommitter(database);
}
/// <summary>
/// Creates a gameplay-facing session facade over a CultMesh node.
/// </summary>
public static CultMeshGameSession CreateGameSession(
CultMeshNode node,
CultMeshGameSessionOptions? options = null)
{
return new CultMeshGameSession(node, options);
}
/// <summary>
/// Attaches Verse discovery responses to a CultMesh node.
/// </summary>

View file

@ -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
{
/// <summary>
/// Options for creating a gameplay-facing CultMesh session facade.
/// </summary>
public sealed class CultMeshGameSessionOptions
{
/// <summary>
/// Gets or sets the Verse catalog used by the session.
/// </summary>
public CultMeshVerseCatalog? VerseCatalog { get; set; }
/// <summary>
/// Gets or sets the peer catalog used by the session.
/// </summary>
public CultMeshPeerCatalog? PeerCatalog { get; set; }
/// <summary>
/// Gets or sets the authority lease catalog used by the session.
/// </summary>
public CultMeshAuthorityLeaseCatalog? AuthorityLeases { get; set; }
/// <summary>
/// Gets or sets simulation consensus options.
/// </summary>
public CultNetSimulationConsensusOptions? ConsensusOptions { get; set; }
/// <summary>
/// Gets or sets whether incoming observation messages should update the session hub.
/// </summary>
public bool ServeSimulationObservations { get; set; } = true;
/// <summary>
/// Gets or sets whether the node should answer Verse catalog requests from the session catalog.
/// </summary>
public bool ServeVerseDiscovery { get; set; } = true;
/// <summary>
/// Gets or sets whether the node should answer peer exchange requests from the session peer catalog.
/// </summary>
public bool ServePeerExchange { get; set; } = true;
}
/// <summary>
/// Gameplay-facing facade over common CultMesh runtime pieces.
/// </summary>
public sealed class CultMeshGameSession : IDisposable
{
private readonly List<IDisposable> _owned = new();
private readonly HashSet<string> _committedFactIds = new(StringComparer.Ordinal);
private bool _disposed;
/// <summary>
/// Creates a game session facade.
/// </summary>
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));
}
}
/// <summary>
/// Gets the underlying node.
/// </summary>
public CultMeshNode Node { get; }
/// <summary>
/// Gets the session Verse catalog.
/// </summary>
public CultMeshVerseCatalog VerseCatalog { get; }
/// <summary>
/// Gets the session peer catalog.
/// </summary>
public CultMeshPeerCatalog PeerCatalog { get; }
/// <summary>
/// Gets the session authority lease catalog.
/// </summary>
public CultMeshAuthorityLeaseCatalog AuthorityLeases { get; }
/// <summary>
/// Gets the session simulation observation hub.
/// </summary>
public CultNetSimulationObservationHub ObservationHub { get; }
/// <summary>
/// Gets the session simulation fact committer.
/// </summary>
public CultMeshSimulationFactCommitter FactCommitter { get; }
/// <summary>
/// Watches consensus candidate updates.
/// </summary>
public Observable<CultNetSimulationConsensusCandidate> WatchCandidates()
{
ThrowIfDisposed();
return ObservationHub.WatchCandidates();
}
/// <summary>
/// Watches committed simulation facts.
/// </summary>
public Observable<CultNetDatabaseChange<CultMeshSimulationFact>> WatchSimulationFacts()
{
ThrowIfDisposed();
return Node.Database.Watch<CultMeshSimulationFact>();
}
/// <summary>
/// Applies a local client prediction through the underlying database.
/// </summary>
public Task<CultRecordHandle<T>> PredictAsync<T>(CultRecordKey key, T document) where T : class
{
ThrowIfDisposed();
return Node.Database.PutPredictedAsync(key, document);
}
/// <summary>
/// Submits one witness observation and returns the current candidates for that subject.
/// </summary>
public IReadOnlyList<CultNetSimulationConsensusCandidate> SubmitObservation(
CultNetSimulationObservation observation)
{
ThrowIfDisposed();
return ObservationHub.Submit(observation);
}
/// <summary>
/// Submits one witness observation and commits any new quorum facts it creates.
/// </summary>
public async Task<IReadOnlyList<CultRecordHandle<CultMeshSimulationFact>>> SubmitAndCommitAsync(
CultNetSimulationObservation observation)
{
ThrowIfDisposed();
var candidates = ObservationHub.Submit(observation);
return await CommitQuorumCandidatesAsync(candidates).ConfigureAwait(false);
}
/// <summary>
/// Commits quorum candidates that have not already been committed by this session.
/// </summary>
public async Task<IReadOnlyList<CultRecordHandle<CultMeshSimulationFact>>> CommitQuorumCandidatesAsync(
IEnumerable<CultNetSimulationConsensusCandidate> candidates)
{
ThrowIfDisposed();
if (candidates == null) throw new ArgumentNullException(nameof(candidates));
var handles = new List<CultRecordHandle<CultMeshSimulationFact>>();
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<CultMeshSimulationFact>(key).ConfigureAwait(false) != null)
{
continue;
}
handles.Add(await FactCommitter.CommitAsync(candidate).ConfigureAwait(false));
}
return handles;
}
/// <inheritdoc />
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));
}
}
}
}

View file

@ -136,6 +136,36 @@ using var sub = db.WatchRecord<PlayerInput>(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,

View file

@ -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.

View file

@ -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

View file

@ -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<CultMeshSimulationFact>().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<CultNetDatabaseChange<CultMeshSimulationFact>>();
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<CultMeshSimulationFact>(secondCommit[0].Key)!.ClaimHash, Is.EqualTo(claimHash));
Assert.That(committed.Exists(change => change.Document?.ClaimHash == claimHash), Is.True);
}
[Test]
public void CultMeshSimulationFactCommitter_Rejects_CandidateWithoutQuorum()
{