From d73c3d26e815bd898cafb7eb775a10c64036e395 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 19 May 2026 19:08:48 +0100 Subject: [PATCH] Add GameCult Mesh package home --- CultLib.sln | 7 + README.md | 3 + src/GameCult.Mesh/CultMesh.cs | 172 +++++++++++ src/GameCult.Mesh/CultMeshVerse.cs | 273 ++++++++++++++++++ src/GameCult.Mesh/GameCult.Mesh.csproj | 19 ++ src/GameCult.Mesh/README.md | 87 ++++++ src/GameCult.Mesh/docs/public-api.md | 68 +++++ src/GameCult.Mesh/docs/research.md | 41 +++ src/GameCult.Mesh/docs/verses.md | 58 ++++ src/GameCult.Networking/README.md | 10 + .../GameCult.Networking.Tests.csproj | 1 + .../NetworkingTests.cs | 53 ++++ 12 files changed, 792 insertions(+) create mode 100644 src/GameCult.Mesh/CultMesh.cs create mode 100644 src/GameCult.Mesh/CultMeshVerse.cs create mode 100644 src/GameCult.Mesh/GameCult.Mesh.csproj create mode 100644 src/GameCult.Mesh/README.md create mode 100644 src/GameCult.Mesh/docs/public-api.md create mode 100644 src/GameCult.Mesh/docs/research.md create mode 100644 src/GameCult.Mesh/docs/verses.md diff --git a/CultLib.sln b/CultLib.sln index e4cf225d..4d90a321 100644 --- a/CultLib.sln +++ b/CultLib.sln @@ -17,6 +17,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Caching.MessagePac EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Networking", "src\GameCult.Networking\GameCult.Networking.csproj", "{67383F6C-C9C3-4C5B-95D4-5C50C20EDD4F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Mesh", "src\GameCult.Mesh\GameCult.Mesh.csproj", "{8D1B01A7-BF9E-44E6-88E1-B17255728B42}" +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{39D316AB-ABB5-49A2-8E83-CAF4C75B48F4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Networking.Tests", "tests\GameCult.Networking.Tests\GameCult.Networking.Tests.csproj", "{E2DC8FF6-D39E-4FCA-9549-1F7681F0AA81}" @@ -48,6 +50,10 @@ Global {67383F6C-C9C3-4C5B-95D4-5C50C20EDD4F}.Debug|Any CPU.Build.0 = Debug|Any CPU {67383F6C-C9C3-4C5B-95D4-5C50C20EDD4F}.Release|Any CPU.ActiveCfg = Release|Any CPU {67383F6C-C9C3-4C5B-95D4-5C50C20EDD4F}.Release|Any CPU.Build.0 = Release|Any CPU + {8D1B01A7-BF9E-44E6-88E1-B17255728B42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8D1B01A7-BF9E-44E6-88E1-B17255728B42}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8D1B01A7-BF9E-44E6-88E1-B17255728B42}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8D1B01A7-BF9E-44E6-88E1-B17255728B42}.Release|Any CPU.Build.0 = Release|Any CPU {E2DC8FF6-D39E-4FCA-9549-1F7681F0AA81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E2DC8FF6-D39E-4FCA-9549-1F7681F0AA81}.Debug|Any CPU.Build.0 = Debug|Any CPU {E2DC8FF6-D39E-4FCA-9549-1F7681F0AA81}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -70,6 +76,7 @@ Global {9DDA917D-B4DB-4AC1-9B9A-4ECF06A5ABA1} = {E733CBFF-42AE-4B6A-B5B9-0071ECFB45F1} {26EE4C38-F06E-4E7A-A89C-908318BCB0DB} = {E733CBFF-42AE-4B6A-B5B9-0071ECFB45F1} {67383F6C-C9C3-4C5B-95D4-5C50C20EDD4F} = {E733CBFF-42AE-4B6A-B5B9-0071ECFB45F1} + {8D1B01A7-BF9E-44E6-88E1-B17255728B42} = {E733CBFF-42AE-4B6A-B5B9-0071ECFB45F1} {E2DC8FF6-D39E-4FCA-9549-1F7681F0AA81} = {39D316AB-ABB5-49A2-8E83-CAF4C75B48F4} {EB15435B-7147-4BD9-BB9C-B0A14318D3D5} = {39D316AB-ABB5-49A2-8E83-CAF4C75B48F4} {0E990C96-3808-450E-9349-A0C3262195ED} = {E733CBFF-42AE-4B6A-B5B9-0071ECFB45F1} diff --git a/README.md b/README.md index 74479e8e..e7f892a6 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ The libraries cover three main areas: - logging primitives and implementations - a typed in-memory cache with pluggable persistence - LiteNetLib-based networking with encrypted credential exchange and signed session tokens +- CultMesh distributed realtime database and simulation-consensus primitives - declarative Unity UI composition and reflective runtime inspector tooling ## Repository Scope @@ -20,6 +21,7 @@ The solution includes: - `GameCult.Caching.MessagePack.Generator`: source generator for MessagePack formatters for cache models - `GameCult.Caching.MessagePack.Analyzers`: packaging project that delivers the generator to consuming projects - `GameCult.Networking`: encrypted login/register/verify flows and message dispatch over LiteNetLib +- `GameCult.Mesh`: CultMesh package home for distributed realtime database, shard replication, client prediction, Verse discovery, and mesh witness consensus - `GameCult.Caching.Tests`: NUnit tests for cache and backing-store behavior - `GameCult.Networking.Tests`: NUnit tests for networking behavior - `GameCult.Unity`: CultUI, a Unity runtime UI composition framework with reflective inspector generation, prefab-backed field resolvers, reusable controls, and a demo project packaged for UPM-style consumption @@ -35,6 +37,7 @@ src/ GameCult.Caching.MessagePack.Generator/ GameCult.Caching.MessagePack.Analyzers/ GameCult.Networking/ + GameCult.Mesh/ GameCult.Unity/ tests/ GameCult.Caching.Tests/ diff --git a/src/GameCult.Mesh/CultMesh.cs b/src/GameCult.Mesh/CultMesh.cs new file mode 100644 index 00000000..458c7f58 --- /dev/null +++ b/src/GameCult.Mesh/CultMesh.cs @@ -0,0 +1,172 @@ +using System; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using GameCult.Networking; + +namespace GameCult.Mesh +{ + /// + /// Options for creating a local CultMesh node. + /// + public sealed class CultMeshNodeOptions + { + /// + /// Gets or sets the cache-open options used for the underlying CultCache. + /// + public CultCacheOpenOptions? CacheOptions { get; set; } + + /// + /// Gets or sets the server security configuration. When omitted, development defaults are used. + /// + public ServerSecurityOptions? Security { get; set; } + + /// + /// Gets or sets whether the server should start immediately after creation. + /// + public bool StartServer { get; set; } = true; + + /// + /// Gets or sets the mesh database sharding options used for the hosted CultCache. + /// + public CultNetDatabaseOptions? DatabaseOptions { get; set; } + + /// + /// Gets or sets the database server bridge options used for shard routing and forwarding. + /// + public CultNetDatabaseServerOptions? DatabaseServerOptions { get; set; } + + /// + /// Gets or sets an optional callback used to customize the server before start. + /// + public Action? ConfigureServer { get; set; } + + internal CultNetHostOptions ToCultNetOptions() + { + return new CultNetHostOptions + { + CacheOptions = CacheOptions, + Security = Security, + StartServer = StartServer, + DatabaseOptions = DatabaseOptions, + DatabaseServerOptions = DatabaseServerOptions, + ConfigureServer = ConfigureServer + }; + } + } + + /// + /// A locally hosted CultMesh node over CultCache, CultNet transport, and the mesh database facade. + /// + public sealed class CultMeshNode : IDisposable + { + private readonly CultNetHost _host; + + internal CultMeshNode(CultNetHost host) + { + _host = host ?? throw new ArgumentNullException(nameof(host)); + } + + /// + /// Gets the durable cache used by the node. + /// + public CultCache Cache => _host.Cache; + + /// + /// Gets the canonical single-file MessagePack store, when one is attached. + /// + public SingleFileMessagePackBackingStore? Store => _host.Store; + + /// + /// Gets the underlying CultNet server. + /// + public Server Server => _host.Server; + + /// + /// Gets the distributed realtime database facade. + /// + public CultNetDatabase Database => _host.Database; + + /// + /// Gets the schema-v0 server bridge for distributed database messages. + /// + public CultNetDatabaseServer DatabaseServer => _host.DatabaseServer; + + /// + /// Starts the underlying server. + /// + public void Start() + { + _host.Start(); + } + + /// + /// Flushes the durable cache. + /// + public Task FlushAsync(bool soft = false) + { + return _host.FlushAsync(soft); + } + + /// + public void Dispose() + { + _host.Dispose(); + } + } + + /// + /// Public CultMesh entrypoints. + /// + public static class CultMesh + { + /// + /// Creates a local CultMesh node with a durable CultCache and the canonical MessagePack backing store. + /// + public static async Task CreateNodeAsync(string cachePath, CultMeshNodeOptions? options = null) + { + var host = await CultNetLocal.CreateHostAsync( + cachePath, + (options ?? new CultMeshNodeOptions()).ToCultNetOptions()).ConfigureAwait(false); + return new CultMeshNode(host); + } + + /// + /// Creates and starts a local CultMesh node with development-friendly defaults. + /// + public static Task StartNodeAsync(string cachePath, CultMeshNodeOptions? options = null) + { + options ??= new CultMeshNodeOptions(); + options.StartServer = true; + return CreateNodeAsync(cachePath, options); + } + + /// + /// Creates a local reactive catalog for discovered Verses. + /// + public static CultMeshVerseCatalog CreateVerseCatalog() + { + return new CultMeshVerseCatalog(); + } + + /// + /// Creates a CultNet client configured for CultMesh use. + /// + public static Client CreateClient(ClientSecurityOptions? security = null, Action? configureClient = null) + { + return CultNetLocal.CreateClient(security, configureClient); + } + + /// + /// Creates and connects a CultNet client to a CultMesh node. + /// + public static Client ConnectClient( + string host = "localhost", + int port = 3075, + ClientSecurityOptions? security = null, + Action? configureClient = null) + { + return CultNetLocal.ConnectClient(host, port, security, configureClient); + } + } +} diff --git a/src/GameCult.Mesh/CultMeshVerse.cs b/src/GameCult.Mesh/CultMeshVerse.cs new file mode 100644 index 00000000..94a1b1fb --- /dev/null +++ b/src/GameCult.Mesh/CultMeshVerse.cs @@ -0,0 +1,273 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using R3; + +namespace GameCult.Mesh +{ + /// + /// Describes how a CultMesh Verse makes authority decisions. + /// + public enum CultMeshVerseAuthorityModel + { + /// + /// A known operator cluster is authoritative for committed world state. + /// + OperatorCluster, + /// + /// Regional operators share authority for lower latency and availability. + /// + FederatedCluster, + /// + /// Peers participate directly in authority decisions. + /// + PeerToPeer, + /// + /// The Verse follows another Verse and applies declared overlays. + /// + SubscribedOverlay + } + + /// + /// Declares transport and rules compatibility for a Verse. + /// + public sealed class CultMeshVerseCompatibility + { + /// + /// Creates compatibility metadata. + /// + public CultMeshVerseCompatibility( + string transportVersion, + string rulesHash, + IEnumerable? compatibleVerseIds = null, + IEnumerable? requiredPluginIds = null, + IEnumerable? optionalPluginIds = null) + { + TransportVersion = RequireNonEmpty(transportVersion, nameof(transportVersion)); + RulesHash = RequireNonEmpty(rulesHash, nameof(rulesHash)); + CompatibleVerseIds = Clean(compatibleVerseIds); + RequiredPluginIds = Clean(requiredPluginIds); + OptionalPluginIds = Clean(optionalPluginIds); + } + + /// + /// Gets the CultMesh/CultNet transport compatibility version. + /// + public string TransportVersion { get; } + /// + /// Gets the stable rules hash. + /// + public string RulesHash { get; } + /// + /// Gets Verse ids this Verse can transfer from or subscribe to. + /// + public IReadOnlyList CompatibleVerseIds { get; } + /// + /// Gets plugin ids required to enter this Verse. + /// + public IReadOnlyList RequiredPluginIds { get; } + /// + /// Gets plugin ids supported but not required by this Verse. + /// + public IReadOnlyList OptionalPluginIds { get; } + + private static string[] Clean(IEnumerable? values) + { + return values?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray() + ?? Array.Empty(); + } + + private static string RequireNonEmpty(string value, string paramName) + { + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value must be non-empty.", paramName); + } + + return value; + } + } + + /// + /// Describes one CultMesh Verse: a rule-bearing consensus graph. + /// + public sealed class CultMeshVerseDescriptor + { + /// + /// Creates a Verse descriptor. + /// + public CultMeshVerseDescriptor( + string verseId, + string displayName, + CultMeshVerseAuthorityModel authorityModel, + CultMeshVerseCompatibility compatibility, + IEnumerable? discoveryEndpoints = null, + IEnumerable? authorityRuntimeIds = null, + string? parentVerseId = null, + string? description = null) + { + VerseId = RequireNonEmpty(verseId, nameof(verseId)); + DisplayName = RequireNonEmpty(displayName, nameof(displayName)); + AuthorityModel = authorityModel; + Compatibility = compatibility ?? throw new ArgumentNullException(nameof(compatibility)); + DiscoveryEndpoints = Clean(discoveryEndpoints); + AuthorityRuntimeIds = Clean(authorityRuntimeIds); + ParentVerseId = parentVerseId; + Description = description; + } + + /// + /// Gets the stable Verse id. + /// + public string VerseId { get; } + /// + /// Gets the human-facing Verse name. + /// + public string DisplayName { get; } + /// + /// Gets the authority model used by this Verse. + /// + public CultMeshVerseAuthorityModel AuthorityModel { get; } + /// + /// Gets compatibility metadata for transport, rules, and plugins. + /// + public CultMeshVerseCompatibility Compatibility { get; } + /// + /// Gets discovery endpoints for nodes serving this Verse. + /// + public IReadOnlyList DiscoveryEndpoints { get; } + /// + /// Gets known authoritative runtime ids, when authority is cluster-shaped. + /// + public IReadOnlyList AuthorityRuntimeIds { get; } + /// + /// Gets the parent Verse id for subscribed overlays or branches. + /// + public string? ParentVerseId { get; } + /// + /// Gets optional public description. + /// + public string? Description { get; } + + /// + /// Returns whether this Verse can accept transfer from another Verse. + /// + public bool CanTransferFrom(CultMeshVerseDescriptor source) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + return string.Equals(Compatibility.TransportVersion, source.Compatibility.TransportVersion, StringComparison.Ordinal) && + (string.Equals(Compatibility.RulesHash, source.Compatibility.RulesHash, StringComparison.Ordinal) || + Compatibility.CompatibleVerseIds.Contains(source.VerseId, StringComparer.Ordinal)); + } + + /// + /// Computes a stable rules hash from ordered rules/plugin parts. + /// + public static string ComputeRulesHash(params string[] parts) + { + if (parts == null) throw new ArgumentNullException(nameof(parts)); + var canonical = string.Join("\u001F", parts.Select(part => part ?? string.Empty)); + using var sha = SHA256.Create(); + var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(canonical)); + return string.Concat(bytes.Select(value => value.ToString("x2"))); + } + + private static string[] Clean(IEnumerable? values) + { + return values?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray() + ?? Array.Empty(); + } + + private static string RequireNonEmpty(string value, string paramName) + { + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value must be non-empty.", paramName); + } + + return value; + } + } + + /// + /// Reactive local catalog for discovered CultMesh Verses. + /// + public sealed class CultMeshVerseCatalog : IDisposable + { + private readonly Dictionary _verses = new(StringComparer.Ordinal); + private readonly Subject _updates = new(); + private bool _disposed; + + /// + /// Gets all known Verses. + /// + public IReadOnlyList Verses => _verses.Values.OrderBy(verse => verse.VerseId, StringComparer.Ordinal).ToArray(); + + /// + /// Watches Verse discovery updates. + /// + public Observable Watch() + { + ThrowIfDisposed(); + return _updates; + } + + /// + /// Adds or replaces a discovered Verse. + /// + public void Upsert(CultMeshVerseDescriptor verse) + { + ThrowIfDisposed(); + if (verse == null) throw new ArgumentNullException(nameof(verse)); + _verses[verse.VerseId] = verse; + _updates.OnNext(verse); + } + + /// + /// Gets a Verse by id, if known. + /// + public CultMeshVerseDescriptor? Get(string verseId) + { + ThrowIfDisposed(); + if (string.IsNullOrWhiteSpace(verseId)) throw new ArgumentException("Value must be non-empty.", nameof(verseId)); + return _verses.TryGetValue(verseId, out var verse) ? verse : null; + } + + /// + /// Gets known Verses that can accept transfer from the supplied source Verse. + /// + public IReadOnlyList FindTransferTargets(CultMeshVerseDescriptor source) + { + ThrowIfDisposed(); + if (source == null) throw new ArgumentNullException(nameof(source)); + return _verses.Values + .Where(verse => !string.Equals(verse.VerseId, source.VerseId, StringComparison.Ordinal) && + verse.CanTransferFrom(source)) + .OrderBy(verse => verse.VerseId, StringComparer.Ordinal) + .ToArray(); + } + + /// + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + _updates.Dispose(); + _verses.Clear(); + } + + private void ThrowIfDisposed() + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(CultMeshVerseCatalog)); + } + } + } +} diff --git a/src/GameCult.Mesh/GameCult.Mesh.csproj b/src/GameCult.Mesh/GameCult.Mesh.csproj new file mode 100644 index 00000000..c9904d28 --- /dev/null +++ b/src/GameCult.Mesh/GameCult.Mesh.csproj @@ -0,0 +1,19 @@ + + + CultMesh: distributed realtime mesh database and simulation consensus for GameCult projects + GameCult.Mesh + game;distributed;realtime;mesh;database;simulation;consensus + README.md + + + + + + + + + + + + + diff --git a/src/GameCult.Mesh/README.md b/src/GameCult.Mesh/README.md new file mode 100644 index 00000000..06a273c7 --- /dev/null +++ b/src/GameCult.Mesh/README.md @@ -0,0 +1,87 @@ +# CultMesh + +CultMesh is the distributed realtime database and simulation-consensus layer for +GameCult projects. The NuGet package and assembly are named `GameCult.Mesh`; +the public surface is branded as CultMesh. + +CultMesh sits over: + +- `GameCult.Caching` for typed domain documents, local indexes, persistence, and + file-compatible cache storage. +- `GameCult.Networking` for LiteNetLib transport, schema-v0 wire messages, and + secure client/server sessions. + +The intent is direct: a game can treat a mesh of clients and servers as one +reactive database for persistent state, prediction-friendly input state, and +simulation observations. + +## First Node + +```csharp +using GameCult.Mesh; + +using var node = await CultMesh.StartNodeAsync("world.ccmp"); + +var player = await node.Database.GetAsync(playerKey); +await node.Database.PutAsync(playerKey, player); +``` + +## Verses + +A Verse is a rule-bearing consensus graph. Aetheria Main can be a +cloud-authoritative Verse backed by GameCult regional simulators. A modded +community branch can be transport-compatible with Aetheria Main while declaring +different rules, required plugins, and authority policy. A peer-hosted game can +choose a peer-to-peer authority model. + +```csharp +var rulesHash = CultMeshVerseDescriptor.ComputeRulesHash( + "aetheria", + "rules:v1", + "plugins:vanilla"); + +var aetheria = new CultMeshVerseDescriptor( + "aetheria-main", + "Aetheria", + CultMeshVerseAuthorityModel.OperatorCluster, + new CultMeshVerseCompatibility("cultmesh.v0", rulesHash), + discoveryEndpoints: ["cultmesh://us-east.aetheria.gamecult.net:3075"]); + +using var catalog = CultMesh.CreateVerseCatalog(); +catalog.Upsert(aetheria); +``` + +## Client-Side Prediction + +CultMesh lets a runtime declare which input documents it may author +optimistically. The local cache updates immediately, game simulation can proceed +against that predicted state, and the authoritative shard log later reconciles +the record. + +```csharp +var db = node.Database; + +await db.PutPredictedAsync(inputKey, inputState); + +using var sub = db.WatchRecord(inputKey) + .Subscribe(change => + { + ReconcilePrediction(change); + }); +``` + +## Witness Consensus + +CultMesh nodes can publish observations about simulation facts: shard epoch, +frame, subject, claim kind, and claim hash. `CultNetSimulationConsensus` +aggregates those observations deterministically into candidate facts with +support weight, total observed weight, confidence, and quorum status. + +Those candidates are not committed world state by themselves. They are the fast +mesh opinion layer that can feed an authoritative shard commit path. + +## Documentation + +- [Public API](docs/public-api.md) +- [Research Notes](docs/research.md) +- [Verse Model](docs/verses.md) diff --git a/src/GameCult.Mesh/docs/public-api.md b/src/GameCult.Mesh/docs/public-api.md new file mode 100644 index 00000000..fe60e985 --- /dev/null +++ b/src/GameCult.Mesh/docs/public-api.md @@ -0,0 +1,68 @@ +# CultMesh Public API + +Package: `GameCult.Mesh` + +Brand: CultMesh + +Namespace: `GameCult.Mesh` + +## Entry Points + +- `CultMesh.CreateNodeAsync(...)` +- `CultMesh.StartNodeAsync(...)` +- `CultMesh.CreateVerseCatalog()` +- `CultMesh.CreateClient(...)` +- `CultMesh.ConnectClient(...)` + +`CultMeshNode` wraps the current local runtime pieces: + +- `Cache`: the underlying `CultCache` +- `Server`: the underlying CultNet server +- `Database`: the distributed realtime database facade +- `DatabaseServer`: the schema-v0 database bridge + +The package home and primary entrypoint are `GameCult.Mesh` / `CultMesh`. +Some lower-level database and wire-contract types still retain `CultNet` names +because they are shared with the transport package. Treat those as plumbing, +not the brand surface. + +## Core Behaviors + +### Verses + +`CultMeshVerseDescriptor` describes a rule-bearing consensus graph. It includes +transport compatibility, rules hash, authority model, discovery endpoints, +known authority runtimes, optional parent Verse id, and plugin requirements. + +`CultMeshVerseCatalog` is the local reactive catalog for discovered Verses. +It can publish discovery updates and find compatible transfer targets. + +### Shard Authority + +Each shard has one primary writer for now. Non-primary writes are rejected or +explicitly forwarded. Stale epochs fail loudly. + +### Reactive Documents + +Consumers subscribe to typed document changes through `CultNetDatabase` watch +methods. Subscriptions receive domain changes rather than storage envelopes. + +### Client Prediction + +`CultNetClientAuthorityScope` declares input documents a runtime may predict. +`PutPredictedAsync` writes local state and emits `Predicted`. When the +authoritative log arrives, the database emits `Reconciled`. + +### Replica Catch-Up + +Shard logs can be requested over schema-v0 and applied by replicas. Replica +cursors can be stored with `ICultNetShardReplicaCursorStore`. + +### Simulation Witness Consensus + +`CultNetSimulationObservation` records what a node saw for a simulation fact. +`CultNetSimulationObservationHub` collects those observations and emits +`CultNetSimulationConsensusCandidate` updates. + +Candidates are opinions. Final world state still belongs in the authoritative +shard log. diff --git a/src/GameCult.Mesh/docs/research.md b/src/GameCult.Mesh/docs/research.md new file mode 100644 index 00000000..46d4d579 --- /dev/null +++ b/src/GameCult.Mesh/docs/research.md @@ -0,0 +1,41 @@ +# CultMesh Research Notes + +CultMesh follows the research trail captured in +`research/cultnet-distributed-database/summary.md`. + +The current design keeps these borrowed pieces: + +- RethinkDB-style changefeeds for reactive document subscriptions. +- Firebase-like realtime ergonomics, without pretending offline multi-writer + conflicts are free. +- Dynamo-inspired shard metadata, hinted recovery, and anti-entropy direction. +- Raft-shaped primary authority per shard before automatic failover. +- SWIM-shaped membership later, once there is enough state worth gossiping. +- CRDTs only for document types with declared deterministic merge laws. +- Hashgraph's gossip-about-gossip as an event-provenance idea, not as a crypto + ledger import. + +## Live Model + +CultMesh is currently primary-shard authority plus replica catch-up: + +1. A primary shard accepts ordered writes. +2. Followers pull shard logs and apply committed entries. +3. Clients can predict their own input documents inside explicit authority + scopes. +4. Witnesses publish immutable observations about simulation facts. +5. Nodes aggregate observations into deterministic consensus candidates. +6. Authoritative world state is still committed through shard logs. +7. Verses describe rule-bearing consensus graphs so compatible branches can + share transport without pretending their rules or authority are identical. + +## Next Research Cut + +The next hard problem is not more vocabulary. It is durable authority: + +- persist authoritative shard logs +- define compaction and snapshot fallback +- add observation fanout across peers +- add Verse discovery gossip and subscription policy +- add simulation rollback/resimulation helpers +- then revisit membership, failover, and consensus protocol depth diff --git a/src/GameCult.Mesh/docs/verses.md b/src/GameCult.Mesh/docs/verses.md new file mode 100644 index 00000000..e5d94ed7 --- /dev/null +++ b/src/GameCult.Mesh/docs/verses.md @@ -0,0 +1,58 @@ +# CultMesh Verses + +A Verse is a rule-bearing consensus graph. + +That phrasing is intentionally dry. It keeps the system honest. + +The same transport can carry many Verses: + +- `aetheria-main`: public Aetheria, operated by GameCult regional simulators. +- `aetheria-community-hardcore`: compatible transport, different rules. +- `aetheria-modded-skylands`: compatible branch with required runtime plugins. +- `p2p-arena-nightly`: peer-to-peer authority for a small experimental game. + +## Descriptor + +`CultMeshVerseDescriptor` owns: + +- `VerseId`: stable id +- `DisplayName`: public-facing name +- `AuthorityModel`: operator cluster, federated cluster, peer-to-peer, or + subscribed overlay +- `Compatibility`: transport version, rules hash, compatible Verse ids, and + plugin requirements +- `DiscoveryEndpoints`: endpoints where nodes for the Verse can be found +- `AuthorityRuntimeIds`: known authoritative runtimes when cluster-shaped +- `ParentVerseId`: source Verse for overlays or branches + +## Compatibility + +Two Verses can share a transport without sharing rules. + +Transfer is allowed when: + +- transport versions match, and +- rules hashes match, or the destination explicitly lists the source Verse as + compatible + +That lets a modded branch choose its boundary. It can accept transfers from +Aetheria Main, require a plugin pack, and still reject another branch with +incompatible rules. + +## Authority + +Authority is a Verse-level policy, not a transport accident. + +- `OperatorCluster`: one known operator cluster is final authority. +- `FederatedCluster`: several regional or organizational clusters share + authority. +- `PeerToPeer`: participating peers directly contribute authority. +- `SubscribedOverlay`: the Verse follows another Verse and adds local rules, + mods, or presentation layers. + +## Discovery + +`CultMeshVerseCatalog` is a local reactive catalog. It can be filled from +static config, cloud discovery, peer gossip, or mod portals. It does not care +where the descriptor came from. That keeps discovery pluggable while the Verse +model stays stable. diff --git a/src/GameCult.Networking/README.md b/src/GameCult.Networking/README.md index f518cae1..6c25ad32 100644 --- a/src/GameCult.Networking/README.md +++ b/src/GameCult.Networking/README.md @@ -94,6 +94,16 @@ same payload schema and MessagePack semantics. It carries exact payload bytes plus `schemaId`/record-key metadata; it does not guess what a blob "probably" means. +## CultMesh Lives In GameCult.Mesh + +The distributed realtime database and simulation-consensus surface now has its +own package home: `GameCult.Mesh`, branded publicly as CultMesh. This networking +package still owns CultNet transport, authentication, and schema-v0 wire +contracts. CultMesh owns the developer-facing mesh entrypoints and higher-level +runtime documentation. + +See `src/GameCult.Mesh/README.md` for the public-facing CultMesh API. + ## Distributed CultCache CultNet should be able to start as a sharding layer over CultCache. In that diff --git a/tests/GameCult.Networking.Tests/GameCult.Networking.Tests.csproj b/tests/GameCult.Networking.Tests/GameCult.Networking.Tests.csproj index d57542ea..f50aa15d 100644 --- a/tests/GameCult.Networking.Tests/GameCult.Networking.Tests.csproj +++ b/tests/GameCult.Networking.Tests/GameCult.Networking.Tests.csproj @@ -7,6 +7,7 @@ + diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index b63d9971..e41c6984 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -7,6 +7,7 @@ using System.Text; using System.Threading.Tasks; using GameCult.Caching; using GameCult.Caching.MessagePack; +using GameCult.Mesh; using NUnit.Framework; using R3; @@ -731,6 +732,58 @@ namespace GameCult.Networking.Tests Throws.TypeOf()); } + [Test] + public void CultMesh_CreateClient_Returns_CultNetClient() + { + using var client = CultMesh.CreateClient(DevelopmentClientSecurity); + + Assert.That(client, Is.Not.Null); + Assert.That(client.Connected, Is.False); + } + + [Test] + public void CultMeshVerseCatalog_Finds_CompatibleTransferTargets() + { + var vanillaRules = CultMeshVerseDescriptor.ComputeRulesHash("aetheria", "rules:v1", "vanilla"); + var moddedRules = CultMeshVerseDescriptor.ComputeRulesHash("aetheria", "rules:v1", "skylands"); + var aetheria = new CultMeshVerseDescriptor( + "aetheria-main", + "Aetheria", + CultMeshVerseAuthorityModel.OperatorCluster, + new CultMeshVerseCompatibility("cultmesh.v0", vanillaRules), + discoveryEndpoints: ["cultmesh://aetheria.example.test:3075"], + authorityRuntimeIds: ["gc-us-east", "gc-eu-west"]); + var modded = new CultMeshVerseDescriptor( + "aetheria-skylands", + "Aetheria: Skylands", + CultMeshVerseAuthorityModel.SubscribedOverlay, + new CultMeshVerseCompatibility( + "cultmesh.v0", + moddedRules, + compatibleVerseIds: ["aetheria-main"], + requiredPluginIds: ["skylands"]), + parentVerseId: "aetheria-main"); + var incompatible = new CultMeshVerseDescriptor( + "other-game", + "Other Game", + CultMeshVerseAuthorityModel.PeerToPeer, + new CultMeshVerseCompatibility("cultmesh.v0", CultMeshVerseDescriptor.ComputeRulesHash("other"))); + using var catalog = CultMesh.CreateVerseCatalog(); + var updates = new List(); + using var subscription = catalog.Watch().Subscribe(update => updates.Add(update)); + + catalog.Upsert(aetheria); + catalog.Upsert(modded); + catalog.Upsert(incompatible); + var targets = catalog.FindTransferTargets(aetheria); + + Assert.That(updates, Has.Count.EqualTo(3)); + Assert.That(targets, Has.Count.EqualTo(1)); + Assert.That(targets[0].VerseId, Is.EqualTo("aetheria-skylands")); + Assert.That(modded.CanTransferFrom(aetheria), Is.True); + Assert.That(incompatible.CanTransferFrom(aetheria), Is.False); + } + [Test] public async Task CultNetDatabase_Appends_PerShardMutationLog() {