Recover authority-bound CultMesh and atomic generations

This commit is contained in:
Meta Vens 2026-08-26 19:01:24 +02:00
commit 334e60f192
92 changed files with 6071 additions and 688 deletions

View file

@ -17,9 +17,18 @@ namespace GameCult.Caching.MessagePack;
/// </summary>
public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
{
private const string IndexedFormatVersion = "cultcache.store.v2.directory-indexed";
/// <summary>Fault-probe stage emitted before each immutable record page write.</summary>
public const string BeforeRecordPageWriteStage = "before-record-page-write";
/// <summary>Fault-probe stage emitted after all pages exist and before manifest finality.</summary>
public const string BeforeManifestCommitStage = "before-manifest-commit";
/// <summary>Read-probe stage emitted while the selected manifest generation is leased.</summary>
public const string AfterManifestReadStage = "after-manifest-read";
private const string LegacyIndexedFormatVersion = "cultcache.store.v2.directory-indexed";
private const string LegacyMetadataPageFormatVersion = "cultcache.store.v3.directory-immutable-pages";
private const string IndexedFormatVersion = "cultcache.store.v4.directory-content-addressed-pages";
private readonly FileInfo _manifestFile;
private readonly DirectoryInfo _recordDirectory;
private readonly object _mutationGate = new();
private readonly ConcurrentDictionary<string, bool> _dirtyKeys = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, bool> _deletedKeys = new(StringComparer.Ordinal);
private readonly HashSet<string> _hydratedKeys = new(StringComparer.Ordinal);
@ -27,6 +36,8 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
private Dictionary<string, CultPersistedRecord> _legacyInlineRecords = new(StringComparer.Ordinal);
private CultSchemaCatalogEntry[] _durableCatalog = Array.Empty<CultSchemaCatalogEntry>();
private bool _needsIndexUpgrade;
private bool _manifestUsesImmutablePages;
private bool _manifestUsesMetadataPages;
/// <summary>
/// Gets or sets the predicate that selects indexed record payloads for hydration.
@ -34,6 +45,12 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
/// </summary>
public Func<CultPersistedRecordMetadata, bool>? HydrationFilter { get; set; }
/// <summary>Optional deterministic fault/progress hook for durability tests and host diagnostics.</summary>
public Action<string, int>? FlushStageProbe { get; set; }
/// <summary>Optional deterministic read hook for generation-consistency tests and host diagnostics.</summary>
public Action<string>? ReadStageProbe { get; set; }
/// <summary>
/// Creates a paged MessagePack backing store.
/// </summary>
@ -53,8 +70,65 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
/// </summary>
public static string DefaultRecordDirectoryPath(string manifestPath) => manifestPath + ".records";
/// <summary>
/// Reads one complete persisted generation without deserializing documents through a
/// runtime registry. Indexed manifests are resolved only through the pages they name;
/// orphaned pages from older generations are never included.
/// </summary>
public CultPersistedStoreSnapshot ReadPersistedGeneration()
{
lock (_mutationGate)
using (AcquireCommitLease())
{
var manifest = ReadManifest();
var indexed = string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal) ||
string.Equals(manifest.FormatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal) ||
string.Equals(manifest.FormatVersion, LegacyIndexedFormatVersion, StringComparison.Ordinal);
var records = indexed
? manifest.Records
.OrderBy(record => record.Key, StringComparer.Ordinal)
.Select(record => ReadPersistedRecordPage(record, manifest.FormatVersion, out _))
.ToArray()
: ReadLegacyPersistedGenerationRecords(manifest);
return new CultPersistedStoreSnapshot
{
FormatVersion = manifest.FormatVersion,
SchemaCatalog = manifest.SchemaCatalog.ToArray(),
Records = records
};
}
}
private CultPersistedRecord[] ReadLegacyPersistedGenerationRecords(CultPersistedStoreSnapshot manifest)
{
var records = manifest.Records
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
.ToList();
_recordDirectory.Refresh();
if (_recordDirectory.Exists)
{
records.AddRange(_recordDirectory.EnumerateFiles("*.msgpack")
.OrderBy(file => file.Name, StringComparer.Ordinal)
.Select(file => CultDocumentMessagePackSerialization.DeserializePersistedRecord(
ReadAllBytesShared(file.FullName))));
}
return records
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
.GroupBy(record => record.Key, StringComparer.Ordinal)
.Select(group => group.Last())
.OrderBy(record => record.Key, StringComparer.Ordinal)
.ToArray();
}
/// <inheritdoc />
public override void PullAll()
{
lock (_mutationGate)
PullAllCore();
}
private void PullAllCore()
{
var traceStartup = string.Equals(
Environment.GetEnvironmentVariable("CULTCACHE_TRACE_STARTUP_PHASES"),
@ -68,42 +142,50 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
startupPhase.Restart();
}
_recordDirectory.Refresh();
if (!File.Exists(_manifestFile.FullName) && !_recordDirectory.Exists)
{
SetLastSchemaMigrationReports(Array.Empty<CultSchemaMigrationReport>());
IsDirty = false;
return;
}
var manifest = ReadManifest();
Trace($"manifest records={manifest.Records.Length}");
_durableCatalog = manifest.SchemaCatalog;
var reports = new List<CultSchemaMigrationReport>();
var loaded = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
var indexed = string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal);
if (indexed)
using (AcquireCommitLease())
{
_needsIndexUpgrade = false;
_durableIndex = manifest.Records
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
.GroupBy(record => record.Key, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.Last(), StringComparer.Ordinal);
_recordDirectory.Refresh();
if (!File.Exists(_manifestFile.FullName) && !_recordDirectory.Exists)
{
SetLastSchemaMigrationReports(Array.Empty<CultSchemaMigrationReport>());
IsDirty = false;
return;
}
LoadIndexedRecords(manifest, loaded, reports);
Trace($"indexed-pages loaded={loaded.Count}");
}
else
{
// V1 manifests have no page index. Hydrate once to discover the durable keys;
// the next flush replaces this compatibility path with the indexed manifest.
_needsIndexUpgrade = true;
var legacyRecords = LoadLegacyRecords(manifest, loaded, reports);
_durableIndex = legacyRecords
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
.GroupBy(record => record.Key, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => ToIndexRecord(group.Last()), StringComparer.Ordinal);
Trace($"legacy-pages loaded={loaded.Count}");
var manifest = ReadManifest();
ReadStageProbe?.Invoke(AfterManifestReadStage);
Trace($"manifest records={manifest.Records.Length}");
_durableCatalog = manifest.SchemaCatalog;
var indexed = string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal) ||
string.Equals(manifest.FormatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal) ||
string.Equals(manifest.FormatVersion, LegacyIndexedFormatVersion, StringComparison.Ordinal);
if (indexed)
{
_manifestUsesImmutablePages = string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal);
_manifestUsesMetadataPages = string.Equals(manifest.FormatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal);
_needsIndexUpgrade = !_manifestUsesImmutablePages;
_durableIndex = manifest.Records
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
.GroupBy(record => record.Key, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.Last(), StringComparer.Ordinal);
LoadIndexedRecords(manifest, loaded, reports);
Trace($"indexed-pages loaded={loaded.Count}");
}
else
{
// V1 manifests have no page index. Hydrate once to discover the durable keys;
// the next flush replaces this compatibility path with the indexed manifest.
_needsIndexUpgrade = true;
var legacyRecords = LoadLegacyRecords(manifest, loaded, reports);
_durableIndex = legacyRecords
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
.GroupBy(record => record.Key, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => ToIndexRecord(group.Last()), StringComparer.Ordinal);
Trace($"legacy-pages loaded={loaded.Count}");
}
}
foreach (var pair in loaded)
@ -146,26 +228,46 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
/// <inheritdoc />
public override void PullSelected(Func<CultPersistedRecordMetadata, bool> selector)
{
if (selector == null) throw new ArgumentNullException(nameof(selector));
var manifest = ReadManifest();
if (!string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal))
{
PullAll();
return;
}
lock (_mutationGate)
PullSelectedCore(selector);
}
_durableCatalog = manifest.SchemaCatalog;
_durableIndex = manifest.Records
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
.GroupBy(record => record.Key, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.Last(), StringComparer.Ordinal);
var selected = manifest.Records
.Where(record => selector(ToMetadata(record)))
.OrderBy(record => record.Key, StringComparer.Ordinal)
.ToArray();
private void PullSelectedCore(Func<CultPersistedRecordMetadata, bool> selector)
{
if (selector == null) throw new ArgumentNullException(nameof(selector));
var fallbackToFullPull = false;
CultPersistedRecord[] selected = Array.Empty<CultPersistedRecord>();
var loaded = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
var reports = new List<CultSchemaMigrationReport>();
LoadRecordPages(selected, manifest.SchemaCatalog, loaded, reports);
using (AcquireCommitLease())
{
var manifest = ReadManifest();
ReadStageProbe?.Invoke(AfterManifestReadStage);
fallbackToFullPull = !string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal) &&
!string.Equals(manifest.FormatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal) &&
!string.Equals(manifest.FormatVersion, LegacyIndexedFormatVersion, StringComparison.Ordinal);
if (!fallbackToFullPull)
{
_manifestUsesImmutablePages = string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal);
_manifestUsesMetadataPages = string.Equals(manifest.FormatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal);
_needsIndexUpgrade = !_manifestUsesImmutablePages;
_durableCatalog = manifest.SchemaCatalog;
_durableIndex = manifest.Records
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
.GroupBy(record => record.Key, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.Last(), StringComparer.Ordinal);
selected = manifest.Records
.Where(record => selector(ToMetadata(record)))
.OrderBy(record => record.Key, StringComparer.Ordinal)
.ToArray();
LoadRecordPages(selected, manifest.SchemaCatalog, loaded, reports);
}
}
if (fallbackToFullPull)
{
PullAllCore();
return;
}
PublishSelected(loaded, selected.Select(record => record.Key).ToHashSet(StringComparer.Ordinal));
SetLastSchemaMigrationReports(reports);
IsDirty = !_dirtyKeys.IsEmpty || !_deletedKeys.IsEmpty;
@ -174,29 +276,88 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
/// <inheritdoc />
public override bool ContainsDurableRecord(CultRecordKey key)
{
return _durableIndex.ContainsKey(key.Value) || base.ContainsDurableRecord(key);
lock (_mutationGate)
return _durableIndex.ContainsKey(key.Value) || base.ContainsDurableRecord(key);
}
/// <inheritdoc />
public override void Push(CultStoredDocument entry)
{
Entries[entry.Key.Value] = entry;
_dirtyKeys[entry.Key.Value] = true;
_deletedKeys.TryRemove(entry.Key.Value, out _);
IsDirty = true;
lock (_mutationGate)
{
Entries[entry.Key.Value] = entry;
_dirtyKeys[entry.Key.Value] = true;
_deletedKeys.TryRemove(entry.Key.Value, out _);
IsDirty = true;
}
}
/// <inheritdoc />
public override void Delete(CultStoredDocument entry)
{
Entries.TryRemove(entry.Key.Value, out _);
_dirtyKeys.TryRemove(entry.Key.Value, out _);
_deletedKeys[entry.Key.Value] = true;
IsDirty = true;
lock (_mutationGate)
{
Entries.TryRemove(entry.Key.Value, out _);
_dirtyKeys.TryRemove(entry.Key.Value, out _);
_deletedKeys[entry.Key.Value] = true;
IsDirty = true;
}
}
/// <inheritdoc />
public override void CommitBatch(
IReadOnlyCollection<CultStoredDocument> upserts,
IReadOnlyCollection<CultStoredDocument> deletes,
bool soft)
{
lock (_mutationGate)
{
var previousEntries = Entries.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);
var previousDirtyKeys = _dirtyKeys.Keys.ToArray();
var previousDeletedKeys = _deletedKeys.Keys.ToArray();
var wasDirty = IsDirty;
try
{
foreach (var entry in deletes)
{
Entries.TryRemove(entry.Key.Value, out _);
_dirtyKeys.TryRemove(entry.Key.Value, out _);
_deletedKeys[entry.Key.Value] = true;
}
foreach (var entry in upserts)
{
Entries[entry.Key.Value] = entry;
_dirtyKeys[entry.Key.Value] = true;
_deletedKeys.TryRemove(entry.Key.Value, out _);
}
IsDirty = true;
PushAllCore(soft);
}
catch
{
Entries.Clear();
foreach (var pair in previousEntries)
Entries[pair.Key] = pair.Value;
_dirtyKeys.Clear();
foreach (var key in previousDirtyKeys)
_dirtyKeys[key] = true;
_deletedKeys.Clear();
foreach (var key in previousDeletedKeys)
_deletedKeys[key] = true;
IsDirty = wasDirty;
throw;
}
}
}
/// <inheritdoc />
public override void PushAll(bool soft = false)
{
lock (_mutationGate)
PushAllCore(soft);
}
private void PushAllCore(bool soft)
{
if (!IsDirty && !_needsIndexUpgrade)
{
@ -205,15 +366,17 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
Directory.CreateDirectory(_manifestFile.DirectoryName!);
Directory.CreateDirectory(_recordDirectory.FullName);
using var commitLease = AcquireCommitLease();
var currentManifest = ReadManifest();
var currentIndex = string.Equals(currentManifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal)
var currentManifestIsIndexed = string.Equals(currentManifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal) ||
string.Equals(currentManifest.FormatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal) ||
string.Equals(currentManifest.FormatVersion, LegacyIndexedFormatVersion, StringComparison.Ordinal);
var currentManifestUsesImmutablePages = string.Equals(currentManifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal);
var currentManifestUsesMetadataPages = string.Equals(currentManifest.FormatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal);
var currentIndex = currentManifestIsIndexed
? currentManifest.Records.ToDictionary(record => record.Key, record => record, StringComparer.Ordinal)
: new Dictionary<string, CultPersistedRecord>(_durableIndex, StringComparer.Ordinal);
var precommitIndex = currentIndex.Values
.Select(ToIndexRecord)
.OrderBy(record => record.Key, StringComparer.Ordinal)
.ToArray();
foreach (var key in _deletedKeys.Keys)
currentIndex.Remove(key);
foreach (var key in _dirtyKeys.Keys)
@ -233,18 +396,10 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
.Where(entry => usedSchemaIds.Contains(entry.SchemaId))
.OrderBy(entry => entry.SchemaName, StringComparer.Ordinal)
.ToArray();
var precommitCatalog = currentManifest.SchemaCatalog
.Concat(targetCatalog)
.GroupBy(entry => entry.SchemaId, StringComparer.Ordinal)
.Select(group => group.Last())
.OrderBy(entry => entry.SchemaName, StringComparer.Ordinal)
.ToArray();
WriteManifest(precommitCatalog, precommitIndex);
var keysToWrite = (_needsIndexUpgrade ? Entries.Keys : _dirtyKeys.Keys)
.OrderBy(value => value, StringComparer.Ordinal)
.ToArray();
var pageWriteIndex = 0;
foreach (var key in keysToWrite)
{
if (!Entries.TryGetValue(key, out var stored))
@ -257,31 +412,56 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
document,
stored.Descriptor.DocumentType,
Registry));
WriteFileAtomically(RecordPath(key), CultDocumentMessagePackSerialization.SerializePersistedRecord(record));
var pagePayload = CultDocumentMessagePackSerialization.SerializePersistedRecord(record);
var indexRecord = ToContentAddressedIndexRecord(record, pagePayload);
currentIndex[key] = indexRecord;
FlushStageProbe?.Invoke(BeforeRecordPageWriteStage, pageWriteIndex++);
WriteFileAtomically(
ContentAddressedRecordPath(indexRecord),
pagePayload);
}
if (!currentManifestUsesImmutablePages)
{
foreach (var metadata in currentManifest.Records
.Where(record => !_deletedKeys.ContainsKey(record.Key) && !_dirtyKeys.ContainsKey(record.Key))
.OrderBy(record => record.Key, StringComparer.Ordinal))
{
var sourcePath = currentManifestUsesMetadataPages
? MetadataRecordPath(metadata)
: LegacyRecordPath(metadata.Key);
if (!File.Exists(sourcePath))
continue;
var pagePayload = ReadAllBytesShared(sourcePath);
var indexRecord = ToContentAddressedIndexRecord(metadata, pagePayload);
currentIndex[metadata.Key] = indexRecord;
var targetPath = ContentAddressedRecordPath(indexRecord);
if (!File.Exists(targetPath))
WriteFileAtomically(targetPath, pagePayload);
}
}
foreach (var pair in _legacyInlineRecords.OrderBy(pair => pair.Key, StringComparer.Ordinal))
{
if (_deletedKeys.ContainsKey(pair.Key) || _dirtyKeys.ContainsKey(pair.Key))
continue;
var pagePayload = CultDocumentMessagePackSerialization.SerializePersistedRecord(pair.Value);
var indexRecord = ToContentAddressedIndexRecord(pair.Value, pagePayload);
currentIndex[pair.Key] = indexRecord;
WriteFileAtomically(
RecordPath(pair.Key),
CultDocumentMessagePackSerialization.SerializePersistedRecord(pair.Value));
}
foreach (var key in _deletedKeys.Keys.OrderBy(value => value, StringComparer.Ordinal))
{
var path = RecordPath(key);
if (File.Exists(path))
{
File.Delete(path);
}
ContentAddressedRecordPath(indexRecord),
pagePayload);
}
FlushStageProbe?.Invoke(BeforeManifestCommitStage, pageWriteIndex);
WriteManifest(targetCatalog, currentIndex.Values
.OrderBy(record => record.Key, StringComparer.Ordinal)
.ToArray());
_manifestUsesImmutablePages = true;
_manifestUsesMetadataPages = false;
DeleteUnreferencedRecordPages(currentIndex.Values);
_durableCatalog = targetCatalog;
_durableIndex = currentIndex;
_legacyInlineRecords.Clear();
@ -367,13 +547,11 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
{
var started = tracePages ? Stopwatch.GetTimestamp() : 0L;
var metadata = records[index];
var path = RecordPath(metadata.Key);
if (!File.Exists(path))
return;
var pagePayload = ReadAllBytesShared(path);
var record = CultDocumentMessagePackSerialization.DeserializePersistedRecord(pagePayload);
if (!string.Equals(record.Key, metadata.Key, StringComparison.Ordinal))
throw new InvalidDataException($"Record page '{path}' contains key '{record.Key}', expected '{metadata.Key}'.");
var record = ReadPersistedRecordPage(
metadata,
_manifestUsesImmutablePages,
_manifestUsesMetadataPages,
out var pagePayload);
var catalog = ResolveLegacyUncataloguedRecordCatalog(record, catalogEntries);
recordReports[index] = Registry.ResolvePersistedSchemaReport(record.SchemaId, catalog);
storedRecords[index] = ToStoredDocument(
@ -509,6 +687,16 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
Payload = Array.Empty<byte>()
};
private static CultPersistedRecord ToContentAddressedIndexRecord(
CultPersistedRecord record,
byte[] pagePayload) => new()
{
Key = record.Key,
SchemaId = record.SchemaId,
StoredAt = record.StoredAt,
Payload = HashPayload(pagePayload)
};
private CultPersistedStoreSnapshot ReadManifest()
{
if (File.Exists(_manifestFile.FullName))
@ -607,7 +795,82 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
: "";
}
private string RecordPath(string key) => Path.Combine(_recordDirectory.FullName, $"{HashKey(key)}.msgpack");
private string LegacyRecordPath(string key) => Path.Combine(_recordDirectory.FullName, $"{HashKey(key)}.msgpack");
private string MetadataRecordPath(CultPersistedRecord metadata) => Path.Combine(
_recordDirectory.FullName,
$"{HashKey(metadata.Key + "\0" + metadata.SchemaId + "\0" + metadata.StoredAt)}.msgpack");
private string ContentAddressedRecordPath(CultPersistedRecord metadata)
{
if (metadata.Payload == null || metadata.Payload.Length != 32)
throw new InvalidDataException($"Record '{metadata.Key}' has no committed SHA-256 page identity.");
var hash = BitConverter.ToString(metadata.Payload).Replace("-", string.Empty).ToLowerInvariant();
return Path.Combine(_recordDirectory.FullName, $"{hash}.msgpack");
}
private static byte[] HashPayload(byte[] payload)
{
using var sha256 = SHA256.Create();
return sha256.ComputeHash(payload);
}
private void DeleteUnreferencedRecordPages(IEnumerable<CultPersistedRecord> durableRecords)
{
var referenced = durableRecords
.Select(ContentAddressedRecordPath)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var file in _recordDirectory.EnumerateFiles("*.msgpack"))
{
if (referenced.Contains(file.FullName))
continue;
try
{
File.Delete(file.FullName);
}
catch (IOException)
{
// An orphan is harmless: no committed manifest references it.
}
catch (UnauthorizedAccessException)
{
// Cleanup is best effort and never changes the committed generation.
}
}
}
private CultPersistedRecord ReadPersistedRecordPage(
CultPersistedRecord metadata,
string formatVersion,
out byte[] pagePayload) =>
ReadPersistedRecordPage(
metadata,
string.Equals(formatVersion, IndexedFormatVersion, StringComparison.Ordinal),
string.Equals(formatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal),
out pagePayload);
private CultPersistedRecord ReadPersistedRecordPage(
CultPersistedRecord metadata,
bool usesContentAddressedPages,
bool usesMetadataPages,
out byte[] pagePayload)
{
var path = usesContentAddressedPages
? ContentAddressedRecordPath(metadata)
: usesMetadataPages
? MetadataRecordPath(metadata)
: LegacyRecordPath(metadata.Key);
if (!File.Exists(path))
throw new InvalidDataException($"Committed record page '{path}' is missing from the selected manifest generation.");
pagePayload = ReadAllBytesShared(path);
if (usesContentAddressedPages &&
!HashPayload(pagePayload).SequenceEqual(metadata.Payload))
throw new InvalidDataException($"Record page '{path}' does not match its committed content hash.");
var record = CultDocumentMessagePackSerialization.DeserializePersistedRecord(pagePayload);
if (!string.Equals(record.Key, metadata.Key, StringComparison.Ordinal))
throw new InvalidDataException($"Record page '{path}' contains key '{record.Key}', expected '{metadata.Key}'.");
return record;
}
private static string HashKey(string key)
{
@ -662,6 +925,30 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
return buffer.ToArray();
}
private FileStream AcquireCommitLease()
{
Directory.CreateDirectory(_recordDirectory.FullName);
var lockPath = Path.Combine(_recordDirectory.FullName, ".commit.lock");
var started = Stopwatch.StartNew();
while (true)
{
try
{
return new FileStream(
lockPath,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None,
bufferSize: 1,
FileOptions.WriteThrough);
}
catch (IOException) when (started.Elapsed < TimeSpan.FromSeconds(30))
{
Thread.Sleep(10);
}
}
}
private static void ReplaceExistingFile(string sourcePath, string destinationPath)
{
for (var attempt = 0; attempt < 3; attempt++)
@ -681,6 +968,6 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
}
}
File.Copy(sourcePath, destinationPath, overwrite: true);
File.Replace(sourcePath, destinationPath, null);
}
}

View file

@ -39,6 +39,21 @@ These are **not** domain fields and should not be exposed on app-facing types:
Those belong to the CultCache persistence layer.
## Transaction Visibility
An authoritative multi-record change uses `CultCache.ExecuteTransactionAsync`.
The executing async flow sees its buffered overlay while staging; other readers
and all observers continue to see the prior committed generation. The backing
store commits the complete batch before the live cache swaps to it. Observer
notifications run only after the transaction context and commit lock have been
released, so an observer-triggered write begins a separate transaction.
An exception before durable finality discards the overlay. It cannot become
visible through a later flush. A transaction currently permits at most one
durable backing store because independent stores cannot provide one atomic
commit boundary. Applications that require authoritative writes may configure
`CultNetDatabase` to reject record-at-a-time writes outside this primitive.
## Canonical Store Shape
A persisted CultCache file should contain:

View file

@ -7,6 +7,7 @@ using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Logging;
using R3;
@ -1278,6 +1279,9 @@ namespace GameCult.Caching
private readonly ConditionalWeakTable<object, DocumentHandleBox> _documentHandles = new();
private readonly Subject<object> _changes = new();
private readonly CultCacheSoaStore _soa = new();
private readonly SemaphoreSlim _transactionGate = new(1, 1);
private readonly AsyncLocal<CultCacheTransaction?> _ambientTransaction = new();
private readonly object _stateGate = new();
private ILogger _logger = new NullLogger();
private bool _hasUnflushedMutations;
@ -1348,14 +1352,29 @@ namespace GameCult.Caching
/// <summary>
/// Gets all document instances currently held by the cache.
/// </summary>
public IEnumerable<object> AllEntries => _entries.Values.Select(entry => entry.Document);
public IEnumerable<object> AllEntries
{
get
{
lock (_stateGate)
return VisibleStoredDocuments().Select(entry => entry.Document).ToArray();
}
}
/// <summary>
/// Gets all stored document records currently held by the cache.
/// </summary>
public IEnumerable<CultStoredDocument> AllStoredDocuments =>
_entries.Values.OrderBy(entry => entry.Descriptor.SchemaName, StringComparer.Ordinal)
.ThenBy(entry => entry.Key.Value, StringComparer.Ordinal);
public IEnumerable<CultStoredDocument> AllStoredDocuments
{
get
{
lock (_stateGate)
return VisibleStoredDocuments()
.OrderBy(entry => entry.Descriptor.SchemaName, StringComparer.Ordinal)
.ThenBy(entry => entry.Key.Value, StringComparer.Ordinal)
.ToArray();
}
}
/// <summary>
/// Gets the document registry used by this cache.
@ -1427,13 +1446,22 @@ namespace GameCult.Caching
/// </summary>
public async Task PullAllBackingStoresAsync()
{
foreach (var store in _backingStores)
{
store.PullAll();
}
if (_ambientTransaction.Value != null)
throw new InvalidOperationException(
"CultCache hydration cannot run inside a mutation transaction; hydrate before opening the commit scope.");
_hasUnflushedMutations = _backingStores.Any(store => store.IsDirty);
await Task.CompletedTask;
await _transactionGate.WaitAsync().ConfigureAwait(false);
try
{
foreach (var store in _backingStores)
store.PullAll();
_hasUnflushedMutations = _backingStores.Any(store => store.IsDirty);
}
finally
{
_transactionGate.Release();
}
}
/// <summary>
@ -1443,13 +1471,22 @@ namespace GameCult.Caching
public async Task PullBackingStoreRecordsAsync(Func<CultPersistedRecordMetadata, bool> selector)
{
if (selector == null) throw new ArgumentNullException(nameof(selector));
foreach (var store in _backingStores)
{
store.PullSelected(selector);
}
if (_ambientTransaction.Value != null)
throw new InvalidOperationException(
"CultCache hydration cannot run inside a mutation transaction; hydrate before opening the commit scope.");
_hasUnflushedMutations = _backingStores.Any(store => store.IsDirty);
await Task.CompletedTask;
await _transactionGate.WaitAsync().ConfigureAwait(false);
try
{
foreach (var store in _backingStores)
store.PullSelected(selector);
_hasUnflushedMutations = _backingStores.Any(store => store.IsDirty);
}
finally
{
_transactionGate.Release();
}
}
/// <summary>
@ -1457,15 +1494,22 @@ namespace GameCult.Caching
/// </summary>
public void FlushAllBackingStores(bool soft = false)
{
foreach (var store in _backingStores)
{
FlushBackingStore(store, soft);
}
if (_ambientTransaction.Value != null)
throw new InvalidOperationException("A CultCache transaction owns durable commit; do not flush inside its stage callback.");
RecomputeDirtyState();
if (!IsDirty)
_transactionGate.Wait();
try
{
LastSuccessfulFlushAtUtc = DateTimeOffset.UtcNow;
foreach (var store in _backingStores)
FlushBackingStoreCore(store, soft);
RecomputeDirtyState();
if (!IsDirty)
LastSuccessfulFlushAtUtc = DateTimeOffset.UtcNow;
}
finally
{
_transactionGate.Release();
}
}
@ -1489,6 +1533,22 @@ namespace GameCult.Caching
throw new InvalidOperationException("Backing store is not attached to this cache.");
}
if (_ambientTransaction.Value != null)
throw new InvalidOperationException("A CultCache transaction owns durable commit; do not flush inside its stage callback.");
_transactionGate.Wait();
try
{
FlushBackingStoreCore(store, soft);
}
finally
{
_transactionGate.Release();
}
}
private void FlushBackingStoreCore(CacheBackingStore store, bool soft)
{
store.PushAll(soft);
RecomputeDirtyState();
if (!store.IsDirty)
@ -1514,17 +1574,79 @@ namespace GameCult.Caching
return Task.CompletedTask;
}
/// <summary>
/// Runs a buffered cache mutation. Staged records are visible only to the executing
/// async flow. The durable backing store is committed before the live cache and its
/// observers advance; an exception discards the entire staged batch.
/// </summary>
public async Task ExecuteTransactionAsync(Func<Task> stageAsync, bool soft = false)
{
if (stageAsync == null) throw new ArgumentNullException(nameof(stageAsync));
if (_ambientTransaction.Value != null)
{
await stageAsync().ConfigureAwait(false);
return;
}
await _transactionGate.WaitAsync().ConfigureAwait(false);
var transaction = new CultCacheTransaction();
IReadOnlyList<(CultStoredDocument Stored, object? Previous, bool Removed)> changes;
_ambientTransaction.Value = transaction;
try
{
await stageAsync().ConfigureAwait(false);
transaction.Seal();
changes = CommitTransaction(transaction, soft);
}
finally
{
transaction.Seal();
_ambientTransaction.Value = null;
_transactionGate.Release();
}
foreach (var change in changes)
PublishChange(change.Stored, change.Previous, change.Removed);
}
/// <summary>Runs a value-producing buffered cache mutation.</summary>
public async Task<T> ExecuteTransactionAsync<T>(Func<Task<T>> stageAsync, bool soft = false)
{
if (stageAsync == null) throw new ArgumentNullException(nameof(stageAsync));
T result = default!;
await ExecuteTransactionAsync(async () =>
{
result = await stageAsync().ConfigureAwait(false);
}, soft).ConfigureAwait(false);
return result;
}
/// <summary>
/// Adds or replaces a typed document and returns its record handle.
/// </summary>
public async Task<CultRecordHandle<T>> AddAsync<T>(T document, CultRecordHandle<T>? handle = null)
{
if (document == null) throw new ArgumentNullException(nameof(document));
var stored = await AddStoredDocumentInternal(
CreateStoredDocument(typeof(T), document, handle?.Key),
source: null,
raiseUpdate: false);
return new CultRecordHandle<T>(stored.Key);
if (_ambientTransaction.Value is { } transaction)
{
var staged = CreateStoredDocument(typeof(T), document, handle?.Key);
transaction.Stage(staged);
return new CultRecordHandle<T>(staged.Key);
}
await _transactionGate.WaitAsync().ConfigureAwait(false);
try
{
var stored = await AddStoredDocumentInternal(
CreateStoredDocument(typeof(T), document, handle?.Key),
source: null,
raiseUpdate: false).ConfigureAwait(false);
return new CultRecordHandle<T>(stored.Key);
}
finally
{
_transactionGate.Release();
}
}
/// <summary>
@ -1549,11 +1671,26 @@ namespace GameCult.Caching
nameof(document));
}
var stored = await AddStoredDocumentInternal(
CreateStoredDocument(documentType, document, key),
source: null,
raiseUpdate: false).ConfigureAwait(false);
return stored.Key;
if (_ambientTransaction.Value is { } transaction)
{
var staged = CreateStoredDocument(documentType, document, key);
transaction.Stage(staged);
return staged.Key;
}
await _transactionGate.WaitAsync().ConfigureAwait(false);
try
{
var stored = await AddStoredDocumentInternal(
CreateStoredDocument(documentType, document, key),
source: null,
raiseUpdate: false).ConfigureAwait(false);
return stored.Key;
}
finally
{
_transactionGate.Release();
}
}
/// <summary>
@ -1572,9 +1709,15 @@ namespace GameCult.Caching
/// </summary>
public object? Get(CultRecordKey key)
{
return _entries.TryGetValue(key.Value, out var stored)
? stored.Document
: null;
lock (_stateGate)
{
if (_ambientTransaction.Value is { } transaction &&
transaction.TryGet(key, out var staged))
return staged?.Document;
return _entries.TryGetValue(key.Value, out var stored)
? stored.Document
: null;
}
}
/// <summary>
@ -1607,17 +1750,13 @@ namespace GameCult.Caching
/// </summary>
public IEnumerable<CultStoredDocument> GetStoredDocuments<T>() where T : class
{
var type = typeof(T);
if (type.IsSealed)
lock (_stateGate)
{
return _typeMaps.TryGetValue(type, out var exact)
? exact.Values
: Enumerable.Empty<CultStoredDocument>();
var type = typeof(T);
return VisibleStoredDocuments()
.Where(entry => type.IsAssignableFrom(entry.Descriptor.DocumentType))
.ToArray();
}
return _typeMaps
.Where(pair => type.IsAssignableFrom(pair.Key))
.SelectMany(pair => pair.Value.Values);
}
/// <summary>
@ -1690,9 +1829,21 @@ namespace GameCult.Caching
/// </summary>
public void Remove<T>(CultRecordHandle<T> handle)
{
if (_entries.TryGetValue(handle.Key.Value, out var stored))
if (_ambientTransaction.Value is { } transaction)
{
RemoveStoredDocumentInternal(stored, source: null, raiseUpdate: false);
transaction.Delete(handle.Key);
return;
}
_transactionGate.Wait();
try
{
if (_entries.TryGetValue(handle.Key.Value, out var stored))
RemoveStoredDocumentInternal(stored, source: null, raiseUpdate: false);
}
finally
{
_transactionGate.Release();
}
}
@ -1701,12 +1852,27 @@ namespace GameCult.Caching
/// </summary>
public bool Remove(CultRecordKey key)
{
if (!_entries.TryGetValue(key.Value, out var stored))
if (Get(key) == null)
{
return false;
}
RemoveStoredDocumentInternal(stored, source: null, raiseUpdate: false);
if (_ambientTransaction.Value is { } transaction)
{
transaction.Delete(key);
return true;
}
_transactionGate.Wait();
try
{
if (_entries.TryGetValue(key.Value, out var stored))
RemoveStoredDocumentInternal(stored, source: null, raiseUpdate: false);
}
finally
{
_transactionGate.Release();
}
return true;
}
@ -1734,9 +1900,171 @@ namespace GameCult.Caching
store.Dispose();
}
_transactionGate.Dispose();
_changes.Dispose();
}
private IEnumerable<CultStoredDocument> VisibleStoredDocuments()
{
if (_ambientTransaction.Value == null)
return _entries.Values.ToArray();
var visible = _entries.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);
foreach (var pair in _ambientTransaction.Value.Mutations)
{
if (pair.Value == null)
visible.Remove(pair.Key);
else
visible[pair.Key] = pair.Value;
}
return visible.Values.ToArray();
}
private IReadOnlyList<(CultStoredDocument Stored, object? Previous, bool Removed)> CommitTransaction(
CultCacheTransaction transaction,
bool soft)
{
var mutations = transaction.SnapshotForCommit()
.OrderBy(pair => pair.Key, StringComparer.Ordinal)
.ToArray();
if (mutations.Length == 0)
return Array.Empty<(CultStoredDocument, object?, bool)>();
if (_backingStores.Count > 1)
{
throw new InvalidOperationException(
"A CultCache transaction requires zero or one durable backing store; multiple stores cannot share one atomic commit boundary.");
}
CultStoredDocument[] previous;
lock (_stateGate)
{
previous = mutations
.Select(pair => _entries.TryGetValue(pair.Key, out var stored) ? stored : null)
.Where(stored => stored != null)
.Cast<CultStoredDocument>()
.ToArray();
}
var upserts = mutations.Where(pair => pair.Value != null).Select(pair => pair.Value!).ToArray();
var deleted = mutations
.Where(pair => pair.Value == null)
.Select(pair => previous.FirstOrDefault(stored => string.Equals(stored.Key.Value, pair.Key, StringComparison.Ordinal)))
.Where(stored => stored != null)
.Cast<CultStoredDocument>()
.ToArray();
foreach (var store in _backingStores)
store.CommitBatch(upserts, deleted, soft);
var changes = new List<(CultStoredDocument Stored, object? Previous, bool Removed)>();
lock (_stateGate)
{
foreach (var pair in mutations)
{
_entries.TryGetValue(pair.Key, out var existing);
if (existing != null)
{
RemoveIndexes(existing);
_documentHandles.Remove(existing.Document);
_soa.Remove(existing);
}
if (pair.Value == null)
{
if (existing != null)
{
_entries.TryRemove(pair.Key, out _);
changes.Add((existing, existing.Document, true));
}
continue;
}
var stored = pair.Value;
_entries[pair.Key] = stored;
_documentHandles.Remove(stored.Document);
_documentHandles.Add(stored.Document, new DocumentHandleBox(stored.Key));
_soa.Upsert(stored);
AddIndexes(stored);
changes.Add((stored, existing?.Document, false));
}
_hasUnflushedMutations = _backingStores.Any(store => store.IsDirty);
if (!IsDirty)
LastSuccessfulFlushAtUtc = DateTimeOffset.UtcNow;
}
return changes;
}
private sealed class CultCacheTransaction
{
private readonly object _gate = new();
private readonly Dictionary<string, CultStoredDocument?> _mutations = new(StringComparer.Ordinal);
private bool _sealed;
public IReadOnlyDictionary<string, CultStoredDocument?> Mutations
{
get
{
lock (_gate)
{
ThrowIfSealedForAmbientAccess();
return new Dictionary<string, CultStoredDocument?>(_mutations, StringComparer.Ordinal);
}
}
}
public void Stage(CultStoredDocument stored)
{
lock (_gate)
{
ThrowIfSealedForAmbientAccess();
_mutations[stored.Key.Value] = stored;
}
}
public void Delete(CultRecordKey key)
{
lock (_gate)
{
ThrowIfSealedForAmbientAccess();
_mutations[key.Value] = null;
}
}
public bool TryGet(CultRecordKey key, out CultStoredDocument? stored)
{
lock (_gate)
{
ThrowIfSealedForAmbientAccess();
return _mutations.TryGetValue(key.Value, out stored);
}
}
public void Seal()
{
lock (_gate)
_sealed = true;
}
public IReadOnlyDictionary<string, CultStoredDocument?> SnapshotForCommit()
{
lock (_gate)
{
if (!_sealed)
throw new InvalidOperationException("A CultCache transaction must be sealed before commit.");
return new Dictionary<string, CultStoredDocument?>(_mutations, StringComparer.Ordinal);
}
}
private void ThrowIfSealedForAmbientAccess()
{
if (_sealed)
throw new InvalidOperationException(
"This CultCache transaction has already completed; escaped async work cannot read or mutate it.");
}
}
internal CultStoredDocument CreateStoredDocument(Type documentType, object document, CultRecordKey? key = null, string? storedAt = null)
{
var descriptor = _registry.GetRequired(documentType);
@ -1754,33 +2082,28 @@ namespace GameCult.Caching
bool raiseUpdate)
{
CultStoredDocument? existing = null;
_entries.TryGetValue(stored.Key.Value, out existing);
if (existing != null)
lock (_stateGate)
{
RemoveIndexes(existing);
}
_entries.TryGetValue(stored.Key.Value, out existing);
if (existing != null)
RemoveIndexes(existing);
_entries[stored.Key.Value] = stored;
_documentHandles.Remove(stored.Document);
_documentHandles.Add(stored.Document, new DocumentHandleBox(stored.Key));
_soa.Upsert(stored);
AddIndexes(stored);
_entries[stored.Key.Value] = stored;
_documentHandles.Remove(stored.Document);
_documentHandles.Add(stored.Document, new DocumentHandleBox(stored.Key));
_soa.Upsert(stored);
AddIndexes(stored);
foreach (var store in _backingStores)
{
if (store != source)
foreach (var store in _backingStores)
{
store.Push(stored);
if (store != source)
store.Push(stored);
}
}
if (source == null)
{
_hasUnflushedMutations = true;
}
else
{
RecomputeDirtyState();
if (source == null)
_hasUnflushedMutations = true;
else
RecomputeDirtyState();
}
PublishChange(stored, existing?.Document);
@ -1799,30 +2122,26 @@ namespace GameCult.Caching
CacheBackingStore? source,
bool raiseUpdate)
{
if (!_entries.TryRemove(stored.Key.Value, out var existing))
CultStoredDocument? existing;
lock (_stateGate)
{
return;
}
if (!_entries.TryRemove(stored.Key.Value, out existing))
return;
RemoveIndexes(existing);
_documentHandles.Remove(existing.Document);
_soa.Remove(existing);
RemoveIndexes(existing);
_documentHandles.Remove(existing.Document);
_soa.Remove(existing);
foreach (var store in _backingStores)
{
if (store != source)
foreach (var store in _backingStores)
{
store.Delete(existing);
if (store != source)
store.Delete(existing);
}
}
if (source == null)
{
_hasUnflushedMutations = true;
}
else
{
RecomputeDirtyState();
if (source == null)
_hasUnflushedMutations = true;
else
RecomputeDirtyState();
}
PublishChange(existing, existing.Document, removed: true);
@ -2104,6 +2423,34 @@ namespace GameCult.Caching
/// </summary>
public abstract void Delete(CultStoredDocument entry);
/// <summary>
/// Atomically stages and durably commits a buffered record batch for this store.
/// Implementations must restore their prior staged view when finality fails.
/// </summary>
public virtual void CommitBatch(
IReadOnlyCollection<CultStoredDocument> upserts,
IReadOnlyCollection<CultStoredDocument> deletes,
bool soft)
{
var previousEntries = Entries.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);
var wasDirty = IsDirty;
try
{
foreach (var entry in deletes)
Delete(entry);
foreach (var entry in upserts)
Push(entry);
PushAll(soft);
}
catch
{
Entries.Clear();
foreach (var pair in previousEntries)
Entries[pair.Key] = pair.Value;
IsDirty = wasDirty;
throw;
}
}
/// <summary>
/// Persists all current backing store entries.
/// </summary>
public abstract void PushAll(bool soft = false);

View file

@ -42,11 +42,11 @@ namespace GameCult.Mesh.Quic.Native
public async Task<ICultMeshRealtimeTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default)
{
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
if (target == null) throw new ArgumentNullException(nameof(target));
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port, out var pin))
throw new NotSupportedException($"Native QUIC connector does not support '{candidate.Endpoint}'.");
@ -72,7 +72,9 @@ namespace GameCult.Mesh.Quic.Native
var transport = new CultMeshNativeQuicRealtimeTransport(
candidate.Endpoint,
handle,
_options.PollInterval);
_options.PollInterval,
target,
candidate.Generation);
try
{
await transport.WaitUntilConnectedAsync(_options.HandshakeTimeout, cancellationToken).ConfigureAwait(false);
@ -122,23 +124,42 @@ namespace GameCult.Mesh.Quic.Native
}
}
internal sealed class CultMeshNativeQuicRealtimeTransport : ICultMeshRealtimeTransport
internal sealed class CultMeshNativeQuicRealtimeTransport : ICultMeshRealtimeTransport, ICultMeshVerifiedTransport
{
private readonly object _gate = new object();
private readonly TimeSpan _pollInterval;
private IntPtr _handle;
private readonly CultMeshSessionTarget _target;
private readonly string _routeGeneration;
private bool _disposed;
public CultMeshNativeQuicRealtimeTransport(string endpoint, IntPtr handle, TimeSpan pollInterval)
public CultMeshNativeQuicRealtimeTransport(
string endpoint,
IntPtr handle,
TimeSpan pollInterval,
CultMeshSessionTarget target,
string routeGeneration)
{
Endpoint = endpoint;
_handle = handle;
_pollInterval = pollInterval;
_target = target;
_routeGeneration = routeGeneration ?? string.Empty;
}
public string TransportId => "msquic-native-realtime";
public string Endpoint { get; }
public bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration) =>
string.Equals(_target.VerseId, verseId, StringComparison.Ordinal) &&
string.Equals(_target.AuthorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(CultMeshProtocols.RealtimeState.Value, protocolId, StringComparison.Ordinal) &&
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
public Task SendAsync(CultMeshRealtimeFrame frame, CancellationToken cancellationToken = default) =>
Task.FromException(new NotSupportedException(
"The Unity-compatible native QUIC connector currently owns provider-to-client state only."));

View file

@ -22,7 +22,7 @@ public sealed class CultMeshQuicRealtimeConnectorOptions
/// <summary>
/// Optional provider-aware certificate validator. Standard TLS validation is used when omitted.
/// </summary>
public Func<CultMeshEndpointId, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>?
public Func<CultMeshRuntimeId, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>?
ValidateProviderCertificate { get; set; }
}
@ -55,11 +55,11 @@ public sealed class CultMeshQuicRealtimeTransportConnector : ICultMeshRealtimeTr
/// <inheritdoc />
public async Task<ICultMeshRealtimeTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default)
{
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
if (target == null) throw new ArgumentNullException(nameof(target));
if (!QuicConnection.IsSupported)
throw new PlatformNotSupportedException("QUIC is unavailable. Install a supported MsQuic runtime.");
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port))
@ -84,14 +84,15 @@ public sealed class CultMeshQuicRealtimeTransportConnector : ICultMeshRealtimeTr
{
var providerCertificate = certificate as X509Certificate2 ??
(certificate == null ? null : new X509Certificate2(certificate));
return validator?.Invoke(endpointId, providerCertificate, chain, errors) ??
return validator?.Invoke(CultMeshRuntimeId.Parse(target.AuthorityRuntimeId), providerCertificate, chain, errors) ??
errors == SslPolicyErrors.None ||
MatchesAdvertisedCertificatePin(candidate.Endpoint, providerCertificate);
}
}
}, cancellationToken).ConfigureAwait(false);
return new CultMeshQuicRealtimeTransport(candidate.Endpoint, connection);
return new CultMeshQuicRealtimeTransport(
candidate.Endpoint, connection, target: target, routeGeneration: candidate.Generation);
}
private static bool TryParseEndpoint(string? endpoint, out string host, out int port)
@ -308,7 +309,7 @@ public sealed class CultMeshQuicRealtimeServer : IAsyncDisposable
}
}
internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport, ICultMeshVerifiedTransport
{
private readonly QuicConnection _connection;
private readonly CancellationTokenSource _shutdown = new();
@ -318,6 +319,8 @@ internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
private readonly SemaphoreSlim _reliableSendGate = new(1, 1);
private readonly CultMeshRealtimeInbox _outbound = new();
private readonly Action<CultMeshRealtimeFrame>? _observer;
private readonly CultMeshSessionTarget? _target;
private readonly string _routeGeneration;
private readonly Task _acceptLoop;
private readonly Task _outboundLoop;
private readonly Task _completion;
@ -328,11 +331,15 @@ internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
public CultMeshQuicRealtimeTransport(
string endpoint,
QuicConnection connection,
Action<CultMeshRealtimeFrame>? observer = null)
Action<CultMeshRealtimeFrame>? observer = null,
CultMeshSessionTarget? target = null,
string routeGeneration = "")
{
Endpoint = endpoint;
_connection = connection;
_observer = observer;
_target = target;
_routeGeneration = routeGeneration ?? string.Empty;
_acceptLoop = AcceptStreamsAsync(_shutdown.Token);
_outboundLoop = SendPublishedFramesAsync(_shutdown.Token);
_completion = Task.WhenAll(_acceptLoop, _outboundLoop);
@ -342,6 +349,17 @@ internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
public string Endpoint { get; }
public Task Completion => _completion;
public bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration) =>
_target != null &&
string.Equals(_target.VerseId, verseId, StringComparison.Ordinal) &&
string.Equals(_target.AuthorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(CultMeshProtocols.RealtimeState.Value, protocolId, StringComparison.Ordinal) &&
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
internal bool TryPublishLatest(CultMeshRealtimeFrame frame)
{
if (_disposed || frame.Delivery != CultMeshRealtimeDelivery.LatestOnly) return false;

View file

@ -0,0 +1,349 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using GameCult.Networking;
namespace GameCult.Mesh
{
public enum CultMeshAuthorityTrustMode
{
AuthenticatedRemote,
LocalDevelopment
}
public sealed class CultMeshEcdsaP256PublicKey
{
public CultMeshEcdsaP256PublicKey(string keyId, string x, string y)
{
KeyId = Require(keyId, nameof(keyId));
X = RequireCoordinate(x, nameof(x));
Y = RequireCoordinate(y, nameof(y));
}
public string KeyId { get; }
public string X { get; }
public string Y { get; }
internal ECDsa CreateVerifier()
{
var verifier = ECDsa.Create();
verifier.ImportParameters(new ECParameters
{
Curve = ECCurve.NamedCurves.nistP256,
Q = new ECPoint { X = Convert.FromBase64String(X), Y = Convert.FromBase64String(Y) }
});
return verifier;
}
public static CultMeshEcdsaP256PublicKey From(string keyId, ECDsa key)
{
if (key == null) throw new ArgumentNullException(nameof(key));
var parameters = key.ExportParameters(false);
return new CultMeshEcdsaP256PublicKey(
keyId,
Convert.ToBase64String(parameters.Q.X ?? throw new InvalidOperationException("P-256 key has no X coordinate.")),
Convert.ToBase64String(parameters.Q.Y ?? throw new InvalidOperationException("P-256 key has no Y coordinate.")));
}
private static string RequireCoordinate(string value, string name)
{
var required = Require(value, name);
byte[] bytes;
try { bytes = Convert.FromBase64String(required); }
catch (FormatException error) { throw new ArgumentException("P-256 coordinates must be base64.", name, error); }
if (bytes.Length != 32) throw new ArgumentException("P-256 coordinates must contain 32 bytes.", name);
return required;
}
private static string Require(string value, string name) =>
string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value must be non-empty.", name) : value.Trim();
}
public sealed class CultMeshRouteCertificate
{
public CultMeshRouteCertificate(
CultMeshEcdsaP256PublicKey providerKey,
string odinKeyId,
long issuedAtUnixMilliseconds,
long expiresAtUnixMilliseconds,
string signature)
{
ProviderKey = providerKey ?? throw new ArgumentNullException(nameof(providerKey));
OdinKeyId = string.IsNullOrWhiteSpace(odinKeyId)
? throw new ArgumentException("Odin key identity is required.", nameof(odinKeyId))
: odinKeyId.Trim();
if (issuedAtUnixMilliseconds < 0) throw new ArgumentOutOfRangeException(nameof(issuedAtUnixMilliseconds));
if (expiresAtUnixMilliseconds <= issuedAtUnixMilliseconds) throw new ArgumentOutOfRangeException(nameof(expiresAtUnixMilliseconds));
IssuedAtUnixMilliseconds = issuedAtUnixMilliseconds;
ExpiresAtUnixMilliseconds = expiresAtUnixMilliseconds;
Signature = signature?.Trim() ?? string.Empty;
}
public CultMeshEcdsaP256PublicKey ProviderKey { get; }
public string OdinKeyId { get; }
public long IssuedAtUnixMilliseconds { get; }
public long ExpiresAtUnixMilliseconds { get; }
public string Signature { get; }
}
public sealed class CultMeshAuthorityTrustPolicy
{
private readonly Dictionary<string, CultMeshEcdsaP256PublicKey> _odinRoots;
public CultMeshAuthorityTrustPolicy(
CultMeshAuthorityTrustMode mode,
IEnumerable<CultMeshEcdsaP256PublicKey>? odinRoots = null)
{
Mode = mode;
_odinRoots = (odinRoots ?? Array.Empty<CultMeshEcdsaP256PublicKey>())
.ToDictionary(key => key.KeyId, StringComparer.Ordinal);
}
public CultMeshAuthorityTrustMode Mode { get; }
public IReadOnlyCollection<CultMeshEcdsaP256PublicKey> OdinRoots => _odinRoots.Values;
/// <summary>Fails closed unless the route is valid under this consumer-owned policy.</summary>
public void Validate(string verseId, CultMeshAuthorityRoute route, DateTimeOffset now) =>
Verify(verseId, route, now);
internal CultMeshVerifiedAuthorityRoute Verify(
string verseId,
CultMeshAuthorityRoute route,
DateTimeOffset now)
{
if (route == null) throw new ArgumentNullException(nameof(route));
var certificate = route.Certificate;
if (certificate == null || string.IsNullOrWhiteSpace(certificate.Signature))
{
if (Mode == CultMeshAuthorityTrustMode.LocalDevelopment && IsLoopback(route.Endpoint))
return CultMeshVerifiedAuthorityRoute.Local(route);
throw Failure(route, "Remote CultMesh routes require an Odin-signed authority certificate.");
}
if (!IsProtected(route.Endpoint) &&
!(Mode == CultMeshAuthorityTrustMode.LocalDevelopment && IsLoopback(route.Endpoint)))
throw Failure(route, "Authenticated remote CultMesh routes require TLS or QUIC channel protection.");
if (!_odinRoots.TryGetValue(certificate.OdinKeyId, out var root))
throw Failure(route, $"Odin key '{certificate.OdinKeyId}' is not trusted by this consumer.");
var nowMs = now.ToUnixTimeMilliseconds();
if (nowMs < certificate.IssuedAtUnixMilliseconds || nowMs >= certificate.ExpiresAtUnixMilliseconds)
throw Failure(route, "The Odin route certificate is not currently valid.");
byte[] signature;
try { signature = Convert.FromBase64String(certificate.Signature); }
catch (FormatException error) { throw Failure(route, "The Odin route signature is not base64.", error); }
if (signature.Length != 64) throw Failure(route, "The Odin route signature is not IEEE P1363 P-256.");
using var verifier = root.CreateVerifier();
if (!verifier.VerifyData(
CultMeshAuthorityProof.CanonicalRoute(verseId, route),
signature,
HashAlgorithmName.SHA256))
throw Failure(route, "The Odin route certificate signature is invalid.");
return CultMeshVerifiedAuthorityRoute.Authenticated(route, certificate.ProviderKey);
}
private static bool IsLoopback(string endpoint)
{
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri)) return false;
return uri.IsLoopback ||
string.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase) ||
string.Equals(uri.Host, "127.0.0.1", StringComparison.Ordinal) ||
string.Equals(uri.Host, "::1", StringComparison.Ordinal);
}
private static bool IsProtected(string endpoint)
{
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri)) return false;
return string.Equals(uri.Scheme, "wss", StringComparison.OrdinalIgnoreCase) ||
string.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase) ||
uri.Scheme.IndexOf("quic", StringComparison.OrdinalIgnoreCase) >= 0;
}
private static CultMeshSessionException Failure(CultMeshAuthorityRoute route, string message, Exception? inner = null) =>
new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authentication,
message,
route.Endpoint), inner);
}
internal sealed class CultMeshVerifiedAuthorityRoute
{
private CultMeshVerifiedAuthorityRoute(
CultMeshAuthorityRoute route,
CultMeshEcdsaP256PublicKey? providerKey,
bool localDevelopment)
{
Route = route;
ProviderKey = providerKey;
IsLocalDevelopment = localDevelopment;
}
public CultMeshAuthorityRoute Route { get; }
public CultMeshEcdsaP256PublicKey? ProviderKey { get; }
public bool IsLocalDevelopment { get; }
public static CultMeshVerifiedAuthorityRoute Authenticated(CultMeshAuthorityRoute route, CultMeshEcdsaP256PublicKey key) => new(route, key, false);
public static CultMeshVerifiedAuthorityRoute Local(CultMeshAuthorityRoute route) => new(route, null, true);
}
public sealed class CultMeshSessionProofSigner
{
private readonly ECDsa _key;
public CultMeshSessionProofSigner(CultMeshAuthorityRoute route, ECDsa providerPrivateKey)
{
Route = route ?? throw new ArgumentNullException(nameof(route));
_key = providerPrivateKey ?? throw new ArgumentNullException(nameof(providerPrivateKey));
var certificate = route.Certificate ?? throw new ArgumentException("A session proof signer requires a certified route.", nameof(route));
ProviderKeyId = certificate.ProviderKey.KeyId;
var exported = CultMeshEcdsaP256PublicKey.From(ProviderKeyId, _key);
if (!string.Equals(exported.X, certificate.ProviderKey.X, StringComparison.Ordinal) ||
!string.Equals(exported.Y, certificate.ProviderKey.Y, StringComparison.Ordinal))
throw new ArgumentException("Provider private key does not match the certified route key.", nameof(providerPrivateKey));
}
public CultMeshAuthorityRoute Route { get; }
public string ProviderKeyId { get; }
public string Sign(CultMeshSessionOpenMessage request)
{
var bytes = CultMeshAuthorityProof.CanonicalSession(request, Route.Endpoint);
return Convert.ToBase64String(CultMeshAuthorityProof.SignP256(_key, bytes));
}
}
public static class CultMeshAuthorityProof
{
private const string RouteDomain = "gamecult.cultmesh.route-certificate.v1";
private const string SessionDomain = "gamecult.cultmesh.session-proof.v1";
public static CultMeshAuthorityRoute CreateSignedRoute(
string verseId,
string authorityRuntimeId,
string endpoint,
IEnumerable<string> protocolIds,
int priority,
string generation,
CultMeshEcdsaP256PublicKey providerKey,
string odinKeyId,
DateTimeOffset issuedAt,
DateTimeOffset expiresAt,
ECDsa odinPrivateKey)
{
if (odinPrivateKey == null) throw new ArgumentNullException(nameof(odinPrivateKey));
var unsignedCertificate = new CultMeshRouteCertificate(
providerKey,
odinKeyId,
issuedAt.ToUnixTimeMilliseconds(),
expiresAt.ToUnixTimeMilliseconds(),
string.Empty);
var unsignedRoute = new CultMeshAuthorityRoute(
authorityRuntimeId, endpoint, protocolIds, priority, generation, unsignedCertificate);
var signature = Convert.ToBase64String(SignP256(
odinPrivateKey,
CanonicalRoute(verseId, unsignedRoute)));
return new CultMeshAuthorityRoute(
authorityRuntimeId,
endpoint,
protocolIds,
priority,
generation,
new CultMeshRouteCertificate(
providerKey,
odinKeyId,
issuedAt.ToUnixTimeMilliseconds(),
expiresAt.ToUnixTimeMilliseconds(),
signature));
}
/// <summary>Verifies both the Odin route certificate and provider nonce proof.</summary>
public static bool VerifySessionProof(
CultMeshSessionOpenMessage request,
CultMeshSessionAcceptedMessage response,
string verseId,
CultMeshAuthorityRoute route,
CultMeshAuthorityTrustPolicy trust,
DateTimeOffset now)
{
if (request == null) throw new ArgumentNullException(nameof(request));
if (response == null) throw new ArgumentNullException(nameof(response));
if (trust == null) throw new ArgumentNullException(nameof(trust));
return VerifySession(request, response, trust.Verify(verseId, route, now));
}
internal static byte[] CanonicalRoute(string verseId, CultMeshAuthorityRoute route)
{
var certificate = route.Certificate ?? throw new InvalidOperationException("Route certificate is required.");
return Canonical(
RouteDomain,
verseId,
route.AuthorityRuntimeId,
route.Endpoint,
string.Join("\u001f", route.ProtocolIds.OrderBy(value => value, StringComparer.Ordinal)),
route.Priority.ToString(System.Globalization.CultureInfo.InvariantCulture),
route.Generation,
certificate.ProviderKey.KeyId,
certificate.ProviderKey.X,
certificate.ProviderKey.Y,
certificate.OdinKeyId,
certificate.IssuedAtUnixMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture),
certificate.ExpiresAtUnixMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
internal static byte[] CanonicalSession(CultMeshSessionOpenMessage request, string endpoint) => Canonical(
SessionDomain,
request.ClientNonce ?? string.Empty,
request.MessageId ?? string.Empty,
request.SourceRuntimeId ?? string.Empty,
request.VerseId ?? string.Empty,
request.AuthorityRuntimeId ?? string.Empty,
request.ProtocolId ?? string.Empty,
endpoint ?? string.Empty,
request.RouteGeneration ?? string.Empty);
internal static bool VerifySession(
CultMeshSessionOpenMessage request,
CultMeshSessionAcceptedMessage response,
CultMeshVerifiedAuthorityRoute route)
{
if (route.IsLocalDevelopment) return true;
if (route.ProviderKey == null ||
!string.Equals(response.ProviderKeyId, route.ProviderKey.KeyId, StringComparison.Ordinal) ||
!string.Equals(response.ClientNonce, request.ClientNonce, StringComparison.Ordinal) ||
string.IsNullOrWhiteSpace(response.ProviderSignature))
return false;
byte[] signature;
try { signature = Convert.FromBase64String(response.ProviderSignature); }
catch (FormatException) { return false; }
if (signature.Length != 64) return false;
using var verifier = route.ProviderKey.CreateVerifier();
return verifier.VerifyData(
CanonicalSession(request, route.Route.Endpoint),
signature,
HashAlgorithmName.SHA256);
}
internal static byte[] SignP256(ECDsa key, byte[] payload)
{
var signature = key.SignData(payload, HashAlgorithmName.SHA256);
if (signature.Length != 64)
throw new CryptographicException("ECDSA provider did not emit IEEE P1363 P-256 signature bytes.");
return signature;
}
private static byte[] Canonical(params string[] values)
{
using var stream = new MemoryStream();
var length = new byte[4];
foreach (var value in values)
{
var bytes = Encoding.UTF8.GetBytes(value ?? string.Empty);
BinaryPrimitives.WriteInt32BigEndian(length, bytes.Length);
stream.Write(length, 0, length.Length);
stream.Write(bytes, 0, bytes.Length);
}
return stream.ToArray();
}
}
}

View file

@ -225,9 +225,11 @@ namespace GameCult.Mesh
{
internal CultMeshBodyDemandPlan(
string bodyId,
long generation,
IReadOnlyList<CultMeshBodyConsumerRoute> consumers)
{
BodyId = bodyId;
Generation = generation;
Consumers = consumers;
RequiresSharedMemory = consumers.Any(value => value.Transport == CultMeshBodyTransportKind.SharedMemory);
RequiresSharedFileMapping = consumers.Any(value => value.Transport == CultMeshBodyTransportKind.SharedFileMapping);
@ -235,6 +237,11 @@ namespace GameCult.Mesh
}
public string BodyId { get; }
/// <summary>
/// Monotone generation of the exact routed consumer set. Publishers must rotate any
/// retained capability before writing after this value changes.
/// </summary>
public long Generation { get; }
public bool HasConsumers => Consumers.Count > 0;
public bool RequiresSharedMemory { get; }
public bool RequiresSharedFileMapping { get; }
@ -271,6 +278,8 @@ namespace GameCult.Mesh
private readonly object _gate = new();
private readonly Dictionary<string, CultNetDatabaseSubscriptionDemand> _demands =
new(StringComparer.Ordinal);
private readonly Dictionary<string, long> _bodyGenerations =
new(StringComparer.Ordinal);
private bool _disposed;
public CultMeshBodyDemandTracker(CultNetDatabaseSubscriptionServer subscriptions)
@ -298,7 +307,10 @@ namespace GameCult.Mesh
.OrderBy(value => value.ConsumerRuntimeId, StringComparer.Ordinal)
.ThenBy(value => value.SubscriptionId, StringComparer.Ordinal)
.ToArray();
return new CultMeshBodyDemandPlan(bodyId, routes);
return new CultMeshBodyDemandPlan(
bodyId,
_bodyGenerations.TryGetValue(bodyId, out var generation) ? generation : 0,
routes);
}
}
@ -310,6 +322,7 @@ namespace GameCult.Mesh
_disposed = true;
if (_subscriptions != null) _subscriptions.DemandChanged -= OnDemandChanged;
_demands.Clear();
_bodyGenerations.Clear();
}
}
@ -322,11 +335,63 @@ namespace GameCult.Mesh
lock (_gate)
{
if (_disposed) return;
_demands.TryGetValue(key, out var previous);
var affectedBodyIds = (previous?.BodyIds ?? Array.Empty<string>())
.Concat(demand.BodyIds)
.Where(value => !string.IsNullOrWhiteSpace(value))
.Distinct(StringComparer.Ordinal)
.ToArray();
var before = affectedBodyIds.ToDictionary(
bodyId => bodyId,
RoutedConsumerSignature,
StringComparer.Ordinal);
if (demand.Active) _demands[key] = demand;
else _demands.Remove(key);
foreach (var bodyId in affectedBodyIds)
{
var after = RoutedConsumerSignature(bodyId);
if (string.Equals(before[bodyId], after, StringComparison.Ordinal)) continue;
_bodyGenerations[bodyId] = checked(
(_bodyGenerations.TryGetValue(bodyId, out var generation) ? generation : 0) + 1);
}
}
}
/// <summary>
/// Executes one synchronous capability commit only while the exact routed consumer
/// generation remains current. Demand transitions serialize against the callback, so
/// either this work linearizes before the transition or it is rejected without running.
/// </summary>
public bool TryExecuteAtGeneration(string bodyId, long generation, Action action)
{
if (string.IsNullOrWhiteSpace(bodyId)) throw new ArgumentException("Body identity is required.", nameof(bodyId));
if (generation < 0) throw new ArgumentOutOfRangeException(nameof(generation));
if (action == null) throw new ArgumentNullException(nameof(action));
lock (_gate)
{
ThrowIfDisposed();
var current = _bodyGenerations.TryGetValue(bodyId, out var value) ? value : 0;
if (current != generation) return false;
action();
return true;
}
}
private string RoutedConsumerSignature(string bodyId) => string.Join(
"\u001e",
_demands.Values
.Where(value => value.BodyIds.Contains(bodyId, StringComparer.Ordinal))
.Select(Route)
.Where(value => value != null)
.Cast<CultMeshBodyConsumerRoute>()
.OrderBy(value => value.ConsumerRuntimeId, StringComparer.Ordinal)
.ThenBy(value => value.SubscriptionId, StringComparer.Ordinal)
.Select(value => string.Join(
"\u001f",
value.ConsumerRuntimeId,
value.SubscriptionId,
value.Transport.ToString())));
private void OnDemandChanged(CultNetDatabaseSubscriptionDemand demand) => Observe(demand);
private static CultMeshBodyConsumerRoute? Route(CultNetDatabaseSubscriptionDemand demand)

View file

@ -27,8 +27,8 @@ namespace GameCult.Mesh
public IReadOnlyList<ICultMeshTransportConnector>? Connectors { get; set; }
/// <summary>
/// Gets or sets streaming content connectors. TCP content delivery is used by default;
/// applications may replace it or explicitly add legacy RUDP.
/// Gets or sets streaming content connectors. HTTPS and loopback TCP content
/// delivery are used by default; applications may replace them or explicitly add legacy RUDP.
/// </summary>
public IReadOnlyList<ICultMeshContentTransportConnector>? ContentConnectors { get; set; }
@ -184,6 +184,7 @@ namespace GameCult.Mesh
},
options.ContentConnectors ?? new ICultMeshContentTransportConnector[]
{
new CultMeshHttpsContentTransportConnector(),
new CultMeshTcpContentTransportConnector()
},
options.RealtimeConnectors,
@ -391,7 +392,8 @@ namespace GameCult.Mesh
PayloadSchema = requestSchema.Trim(),
PayloadEncoding = "messagepack-base64",
Payload = Convert.ToBase64String(MessagePackSerializer.Serialize(request, CultNetSchemaMessageSerialization.Options)),
SourceRuntimeId = sourceRuntimeId.Trim()
SourceRuntimeId = sourceRuntimeId.Trim(),
TargetRuntimeId = target.AuthorityRuntimeId
};
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(_operationResponseTimeout);
@ -441,6 +443,11 @@ namespace GameCult.Mesh
if (!string.Equals(envelope.ServiceId, expectedService, StringComparison.Ordinal) ||
!string.Equals(envelope.Operation, expectedOperation, StringComparison.Ordinal))
throw new InvalidOperationException("CultMesh operation response did not match the requested service and operation.");
if (!string.Equals(envelope.SourceRuntimeId, target.AuthorityRuntimeId, StringComparison.Ordinal))
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
$"CultMesh operation response came from runtime '{envelope.SourceRuntimeId ?? "(missing)"}', " +
$"not selected authority '{target.AuthorityRuntimeId}'."));
if (string.Equals(envelope.PayloadSchema, CultNetOperationServer.FailureSchemaId, StringComparison.Ordinal))
{
if (!string.Equals(envelope.PayloadEncoding, "messagepack-base64", StringComparison.Ordinal))
@ -580,7 +587,7 @@ namespace GameCult.Mesh
using var snapshot = await CultMeshSnapshotSession.ConnectAsync(
_sessions,
target,
CultMeshProtocols.Content,
CultMeshProtocols.Documents,
new CultMeshSnapshotRequestOptions
{
ConnectTimeout = TimeSpan.FromSeconds(5),
@ -795,7 +802,7 @@ namespace GameCult.Mesh
_cache,
new CultRecordKey(recordKey),
CultMesh.Verse(target.VerseId, "cultmesh-client").Context,
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, target.ProviderRuntimeId));
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, target.AuthorityRuntimeId));
}
public CultMeshDocumentHandle<TDocument> Handle { get; }
@ -897,7 +904,7 @@ namespace GameCult.Mesh
_subscription = new CultNetDatabaseSubscriptionClient(session.OpenSchemaClient(), _cache, networkRegistry);
Handle = CultMesh.Collection<TDocument>(
_cache,
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, target.ProviderRuntimeId));
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, target.AuthorityRuntimeId));
}
public CultMeshCollectionHandle<TDocument> Handle { get; }

View file

@ -122,31 +122,58 @@ namespace GameCult.Mesh
public async Task<ICultMeshContentTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default)
{
if (!CanConnect(candidate))
throw new NotSupportedException($"Legacy RUDP content connector does not support '{candidate.Endpoint}'.");
var client = await _schemaConnector.ConnectAsync(candidate, CultMeshProtocols.Content, cancellationToken)
.ConfigureAwait(false);
return new LegacyRudpContentTransport(candidate.Endpoint, client, _options);
try
{
await CultMeshSessionIdentityClient.VerifyAsync(
client,
"cultmesh-content-client",
target,
CultMeshProtocols.Content,
candidate,
null,
_options.Clock.UtcNow,
_options.ResponseTimeout,
cancellationToken).ConfigureAwait(false);
return new LegacyRudpContentTransport(
candidate.Endpoint, client, _options, target, candidate.Generation);
}
catch
{
client.Dispose();
throw;
}
}
private sealed class LegacyRudpContentTransport : ICultMeshContentTransport
private sealed class LegacyRudpContentTransport : ICultMeshContentTransport, ICultMeshVerifiedTransport
{
private readonly ICultNetSchemaClient _client;
private readonly CultMeshLegacyRudpContentTransportOptions _options;
private readonly string _verseId;
private readonly string _authorityRuntimeId;
private readonly string _routeGeneration;
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, TaskCompletionSource<CultMeshContentChunkResponseMessage>> _pending = new(StringComparer.Ordinal);
private bool _disposed;
public LegacyRudpContentTransport(
string endpoint,
ICultNetSchemaClient client,
CultMeshLegacyRudpContentTransportOptions options)
CultMeshLegacyRudpContentTransportOptions options,
CultMeshSessionTarget target,
string routeGeneration)
{
Endpoint = endpoint;
_client = client;
_options = options;
_verseId = target.VerseId;
_authorityRuntimeId = target.AuthorityRuntimeId;
_routeGeneration = routeGeneration ?? string.Empty;
_client.OnCultNet<CultMeshContentChunkResponseMessage>(OnResponse);
_client.OnCultNet<CultNetErrorMessage>(OnError);
}
@ -154,6 +181,16 @@ namespace GameCult.Mesh
public string TransportId => "legacy-rudp-content";
public string Endpoint { get; }
public bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration) =>
string.Equals(_verseId, verseId, StringComparison.Ordinal) &&
string.Equals(_authorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(CultMeshProtocols.Content.Value, protocolId, StringComparison.Ordinal) &&
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
public async Task CopyChunkToAsync(
CultMeshCdnChunkRef chunk,
Stream destination,

View file

@ -36,7 +36,7 @@ namespace GameCult.Mesh
bool CanConnect(CultMeshTransportCandidate candidate);
Task<ICultMeshContentTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default);
}

View file

@ -267,7 +267,8 @@ namespace GameCult.Mesh
var observations = results.SelectMany(result => result.Observations)
.Where(observation => query.VerseIds.Count == 0 || query.VerseIds.Contains(observation.Candidate.VerseId, StringComparer.Ordinal))
.Where(observation => query.AuthorityRuntimeId == null ||
observation.Candidate.AuthorityRuntimeIds.Contains(query.AuthorityRuntimeId, StringComparer.Ordinal))
observation.Candidate.AuthorityRoutes.Any(route =>
string.Equals(route.AuthorityRuntimeId, query.AuthorityRuntimeId, StringComparison.Ordinal)))
.ToArray();
foreach (var rejected in observations.Where(observation => observation.Trust == CultMeshDiscoveryTrust.Rejected))

View file

@ -0,0 +1,124 @@
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace GameCult.Mesh
{
/// <summary>
/// Opens immutable content over an Odin-certified HTTPS route. Provider
/// identity comes from the verified route and TLS endpoint; the transfer
/// service remains responsible for checking the advertised chunk hash.
/// </summary>
public sealed class CultMeshHttpsContentTransportConnector : ICultMeshContentTransportConnector
{
private readonly Func<HttpMessageHandler> _createHandler;
public CultMeshHttpsContentTransportConnector(Func<HttpMessageHandler>? createHandler = null)
{
_createHandler = createHandler ?? (() => new HttpClientHandler());
}
public string ConnectorId => "https-content";
public int Priority => 0;
public bool CanConnect(CultMeshTransportCandidate candidate) =>
candidate != null &&
Uri.TryCreate(candidate.Endpoint, UriKind.Absolute, out var endpoint) &&
string.Equals(endpoint.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
public Task<ICultMeshContentTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default)
{
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
if (target == null) throw new ArgumentNullException(nameof(target));
if (!CanConnect(candidate))
throw new NotSupportedException($"HTTPS content connector does not support '{candidate.Endpoint}'.");
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult<ICultMeshContentTransport>(new CultMeshHttpsContentTransport(
candidate.Endpoint,
new HttpClient(_createHandler(), disposeHandler: true),
target,
candidate.Generation));
}
}
internal sealed class CultMeshHttpsContentTransport : ICultMeshContentTransport, ICultMeshVerifiedTransport
{
private readonly HttpClient _client;
private readonly CultMeshSessionTarget _target;
private readonly string _routeGeneration;
private bool _disposed;
public CultMeshHttpsContentTransport(
string endpoint,
HttpClient client,
CultMeshSessionTarget target,
string routeGeneration)
{
Endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_client = client ?? throw new ArgumentNullException(nameof(client));
_target = target ?? throw new ArgumentNullException(nameof(target));
_routeGeneration = routeGeneration ?? string.Empty;
}
public string TransportId => "https-content";
public string Endpoint { get; }
public bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration) =>
string.Equals(_target.VerseId, verseId, StringComparison.Ordinal) &&
string.Equals(_target.AuthorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(CultMeshProtocols.Content.Value, protocolId, StringComparison.Ordinal) &&
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
public async Task CopyChunkToAsync(
CultMeshCdnChunkRef chunk,
Stream destination,
CancellationToken cancellationToken = default)
{
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshHttpsContentTransport));
if (chunk == null) throw new ArgumentNullException(nameof(chunk));
if (destination == null) throw new ArgumentNullException(nameof(destination));
if (!destination.CanWrite) throw new ArgumentException("Content destination must be writable.", nameof(destination));
var requestUri = BuildChunkUri(Endpoint, chunk);
using var response = await _client.GetAsync(
requestUri,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
if (response.Content.Headers.ContentLength is long contentLength &&
contentLength != chunk.SizeBytes)
{
throw new InvalidDataException(
$"HTTPS content length {contentLength} did not match advertised chunk size {chunk.SizeBytes}.");
}
using var source = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
await source.CopyToAsync(destination, 81920, cancellationToken).ConfigureAwait(false);
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_client.Dispose();
}
private static Uri BuildChunkUri(string endpoint, CultMeshCdnChunkRef chunk)
{
var builder = new UriBuilder(endpoint);
var separator = string.IsNullOrWhiteSpace(builder.Query) ? string.Empty : builder.Query.TrimStart('?') + "&";
builder.Query = separator +
"chunkHash=" + Uri.EscapeDataString(CultMeshCdn.NormalizeHash(chunk.ChunkHash, nameof(chunk.ChunkHash))) +
"&recordKey=" + Uri.EscapeDataString(chunk.RecordKey ?? string.Empty);
return builder.Uri;
}
}
}

View file

@ -59,7 +59,7 @@ namespace GameCult.Mesh
bool CanConnect(CultMeshTransportCandidate candidate);
Task<ICultMeshRealtimeTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default);
}

View file

@ -0,0 +1,283 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Networking;
namespace GameCult.Mesh
{
/// <summary>
/// Optional transport proof surfaced by connectors that already authenticate
/// the peer during their native handshake. Other schema clients must complete
/// the portable CultMesh handshake before use.
/// </summary>
public interface ICultMeshVerifiedSchemaClient
{
bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration);
}
/// <summary>
/// Proof exposed by content and realtime transports after their native or
/// portable handshake has bound the physical channel to an Odin route.
/// </summary>
public interface ICultMeshVerifiedTransport
{
bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration);
}
internal static class CultMeshTransportIdentity
{
public static void RequireVerified(
object transport,
CultMeshSessionTarget target,
CultMeshProtocolId protocol,
CultMeshTransportCandidate candidate)
{
if (transport is ICultMeshVerifiedTransport verified &&
verified.IsVerifiedFor(
target.VerseId,
target.AuthorityRuntimeId,
protocol.Value,
candidate.Generation))
return;
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
$"Transport did not prove CultMesh authority '{target}' for protocol '{protocol}'.",
candidate.Endpoint));
}
}
/// <summary>
/// Owns the server side of the transport-neutral CultMesh session identity
/// handshake. Application messages are not authority proof; providers attach
/// this gate to every schema transport they advertise.
/// </summary>
public sealed class CultMeshSessionIdentityServer : IDisposable
{
private readonly ICultNetSchemaServer _server;
private readonly string _authorityRuntimeId;
private readonly HashSet<string> _verseIds;
private readonly HashSet<string> _protocolIds;
private readonly HashSet<string> _routeGenerations;
private readonly Dictionary<string, CultMeshSessionProofSigner> _proofSigners;
private readonly ConcurrentDictionary<ICultNetSchemaServerPeer, string> _acceptedPeers = new();
private readonly Func<CultMeshSessionOpenMessage, ICultNetSchemaServerPeer, Task> _handler;
private readonly ICultNetSchemaServerPeerLifecycle? _peerLifecycle;
private bool _disposed;
public CultMeshSessionIdentityServer(
ICultNetSchemaServer server,
string authorityRuntimeId,
IEnumerable<string> verseIds,
IEnumerable<string> protocolIds,
IEnumerable<string> routeGenerations,
IEnumerable<CultMeshSessionProofSigner>? proofSigners = null)
{
_server = server ?? throw new ArgumentNullException(nameof(server));
_authorityRuntimeId = Require(authorityRuntimeId, nameof(authorityRuntimeId));
_verseIds = Clean(verseIds, nameof(verseIds));
_protocolIds = Clean(protocolIds, nameof(protocolIds));
_routeGenerations = Clean(routeGenerations, nameof(routeGenerations));
_proofSigners = (proofSigners ?? Array.Empty<CultMeshSessionProofSigner>())
.ToDictionary(signer => signer.Route.Generation, StringComparer.Ordinal);
_handler = HandleAsync;
_server.OnCultNet(_handler);
_peerLifecycle = server as ICultNetSchemaServerPeerLifecycle;
if (_peerLifecycle != null)
_peerLifecycle.PeerDisconnected += ForgetPeer;
}
/// <summary>
/// Resolves the runtime identity established by this peer's accepted session-open handshake.
/// Application ingress must use this transport-bound value instead of trusting payload identity fields.
/// </summary>
public bool TryGetSourceRuntimeId(ICultNetSchemaServerPeer peer, out string sourceRuntimeId) =>
_acceptedPeers.TryGetValue(peer, out sourceRuntimeId!);
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_server.RemoveCultNetMessageListener<CultMeshSessionOpenMessage>(_handler);
if (_peerLifecycle != null)
_peerLifecycle.PeerDisconnected -= ForgetPeer;
_acceptedPeers.Clear();
}
private Task HandleAsync(CultMeshSessionOpenMessage request, ICultNetSchemaServerPeer peer)
{
var error = Validate(request);
if (error == null)
error = BindPeer(peer, request.SourceRuntimeId);
_proofSigners.TryGetValue(request.RouteGeneration ?? string.Empty, out var signer);
peer.SendCultNet(new CultMeshSessionAcceptedMessage
{
MessageId = request.MessageId ?? string.Empty,
Accepted = error == null,
VerseId = request.VerseId ?? string.Empty,
AuthorityRuntimeId = _authorityRuntimeId,
ProtocolId = request.ProtocolId ?? string.Empty,
RouteGeneration = request.RouteGeneration ?? string.Empty,
ClientNonce = request.ClientNonce ?? string.Empty,
ProviderKeyId = error == null ? signer?.ProviderKeyId ?? string.Empty : string.Empty,
ProviderSignature = error == null && signer != null ? signer.Sign(request) : string.Empty,
Error = error
});
return Task.CompletedTask;
}
private void ForgetPeer(ICultNetSchemaServerPeer peer) => _acceptedPeers.TryRemove(peer, out _);
private string? BindPeer(ICultNetSchemaServerPeer peer, string sourceRuntimeId)
{
if (_acceptedPeers.TryGetValue(peer, out var established))
return string.Equals(established, sourceRuntimeId, StringComparison.Ordinal)
? null
: "session-source-runtime-rebind-forbidden";
return _acceptedPeers.TryAdd(peer, sourceRuntimeId)
? null
: BindPeer(peer, sourceRuntimeId);
}
private string? Validate(CultMeshSessionOpenMessage request)
{
if (string.IsNullOrWhiteSpace(request.MessageId)) return "session-message-id-required";
if (string.IsNullOrWhiteSpace(request.SourceRuntimeId)) return "source-runtime-id-required";
if (!TryNonce(request.ClientNonce)) return "client-nonce-invalid";
if (!string.Equals(request.AuthorityRuntimeId, _authorityRuntimeId, StringComparison.Ordinal))
return "target-runtime-mismatch";
if (!_verseIds.Contains(request.VerseId ?? string.Empty)) return "verse-not-served";
if (!_protocolIds.Contains(request.ProtocolId ?? string.Empty)) return "protocol-not-served";
if (!_routeGenerations.Contains(request.RouteGeneration ?? string.Empty)) return "route-generation-not-served";
return null;
}
private static bool TryNonce(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return false;
try { return Convert.FromBase64String(value).Length == 32; }
catch (FormatException) { return false; }
}
private static HashSet<string> Clean(IEnumerable<string> values, string name)
{
if (values == null) throw new ArgumentNullException(name);
var result = new HashSet<string>(
values.Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value.Trim()),
StringComparer.Ordinal);
if (result.Count == 0) throw new ArgumentException("At least one identity is required.", name);
return result;
}
private static string Require(string value, string name) =>
string.IsNullOrWhiteSpace(value)
? throw new ArgumentException("Value must be non-empty.", name)
: value.Trim();
}
internal static class CultMeshSessionIdentityClient
{
public static async Task VerifyAsync(
ICultNetSchemaClient client,
string sourceRuntimeId,
CultMeshSessionTarget target,
CultMeshProtocolId protocol,
CultMeshTransportCandidate candidate,
CultMeshAuthorityTrustPolicy? trust,
DateTimeOffset now,
TimeSpan timeout,
CancellationToken cancellationToken = default)
{
if (client == null) throw new ArgumentNullException(nameof(client));
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
var route = candidate.AuthorityRoute ?? new CultMeshAuthorityRoute(
target.AuthorityRuntimeId,
candidate.Endpoint,
new[] { protocol.Value },
candidate.Priority,
candidate.Generation);
var verifiedRoute = candidate.VerifiedAuthority ??
(trust ?? throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authentication,
"No consumer trust policy verified this CultMesh route.",
candidate.Endpoint))).Verify(target.VerseId, route, now);
if (client is ICultMeshVerifiedSchemaClient verified)
{
if (!verified.IsVerifiedFor(
target.VerseId,
target.AuthorityRuntimeId,
protocol.Value,
candidate.Generation))
{
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
$"Native transport identity did not match CultMesh target '{target}' for '{protocol}'."));
}
// Native identity is sufficient only for an explicitly selected
// loopback development route. Remote schema sessions still prove
// possession of the provider key certified by Odin.
if (verifiedRoute.IsLocalDevelopment) return;
}
var messageId = Guid.NewGuid().ToString("N");
var nonce = new byte[32];
using (var random = RandomNumberGenerator.Create()) random.GetBytes(nonce);
var completion = new TaskCompletionSource<CultMeshSessionAcceptedMessage>(
TaskCreationOptions.RunContinuationsAsynchronously);
client.OnCultNet<CultMeshSessionAcceptedMessage>(response =>
{
if (string.Equals(response.MessageId, messageId, StringComparison.Ordinal))
completion.TrySetResult(response);
});
var request = new CultMeshSessionOpenMessage
{
MessageId = messageId,
SourceRuntimeId = sourceRuntimeId,
VerseId = target.VerseId,
AuthorityRuntimeId = target.AuthorityRuntimeId,
ProtocolId = protocol.Value,
RouteGeneration = candidate.Generation,
ClientNonce = Convert.ToBase64String(nonce)
};
client.SendCultNet(request);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(timeout);
var cancelled = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
using (deadline.Token.Register(() => cancelled.TrySetResult(true)))
{
if (await Task.WhenAny(completion.Task, cancelled.Task).ConfigureAwait(false) != completion.Task)
{
cancellationToken.ThrowIfCancellationRequested();
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Timeout,
$"Timed out verifying authority runtime '{target.AuthorityRuntimeId}'."));
}
}
var accepted = await completion.Task.ConfigureAwait(false);
if (!accepted.Accepted ||
!string.Equals(accepted.VerseId, target.VerseId, StringComparison.Ordinal) ||
!string.Equals(accepted.AuthorityRuntimeId, target.AuthorityRuntimeId, StringComparison.Ordinal) ||
!string.Equals(accepted.ProtocolId, protocol.Value, StringComparison.Ordinal) ||
!string.Equals(accepted.RouteGeneration, candidate.Generation, StringComparison.Ordinal) ||
!CultMeshAuthorityProof.VerifySession(request, accepted, verifiedRoute))
{
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
$"Route did not prove CultMesh authority '{target}' for protocol '{protocol}': " +
(accepted.Error ?? "identity-mismatch")));
}
}
}
}

View file

@ -9,14 +9,14 @@ using R3;
namespace GameCult.Mesh
{
public sealed class CultMeshEndpointId : IEquatable<CultMeshEndpointId>
public sealed class CultMeshRuntimeId : IEquatable<CultMeshRuntimeId>
{
private CultMeshEndpointId(string value) { Value = value; }
private CultMeshRuntimeId(string value) { Value = value; }
public string Value { get; }
public static CultMeshEndpointId Parse(string value) => new CultMeshEndpointId(
string.IsNullOrWhiteSpace(value) ? throw new FormatException("CultMesh endpoint identity must be non-empty.") : value.Trim());
public bool Equals(CultMeshEndpointId? other) => other != null && string.Equals(Value, other.Value, StringComparison.Ordinal);
public override bool Equals(object? obj) => Equals(obj as CultMeshEndpointId);
public static CultMeshRuntimeId Parse(string value) => new CultMeshRuntimeId(
string.IsNullOrWhiteSpace(value) ? throw new FormatException("CultMesh runtime identity must be non-empty.") : value.Trim());
public bool Equals(CultMeshRuntimeId? other) => other != null && string.Equals(Value, other.Value, StringComparison.Ordinal);
public override bool Equals(object? obj) => Equals(obj as CultMeshRuntimeId);
public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value);
public override string ToString() => Value;
}
@ -28,31 +28,32 @@ namespace GameCult.Mesh
public sealed class CultMeshSessionTarget : IEquatable<CultMeshSessionTarget>
{
/// <summary>Creates one stable provider target inside one Verse.</summary>
public CultMeshSessionTarget(string verseId, string providerRuntimeId)
public CultMeshSessionTarget(string verseId, string authorityRuntimeId)
{
VerseId = string.IsNullOrWhiteSpace(verseId)
? throw new ArgumentException("Verse identity is required.", nameof(verseId))
: verseId.Trim();
ProviderEndpointId = CultMeshEndpointId.Parse(providerRuntimeId);
ProviderRuntimeId = ProviderEndpointId.Value;
AuthorityRuntimeId = CultMeshRuntimeId.Parse(authorityRuntimeId).Value;
}
/// <summary>Gets the stable Verse identity.</summary>
public string VerseId { get; }
/// <summary>Gets the stable provider runtime identity advertised by that Verse.</summary>
public string ProviderRuntimeId { get; }
internal CultMeshEndpointId ProviderEndpointId { get; }
internal string SessionKey => VerseId + "\u001f" + ProviderRuntimeId;
/// <summary>Gets the stable authority runtime identity advertised by that Verse.</summary>
public string AuthorityRuntimeId { get; }
/// <summary>Compatibility projection. Use <see cref="AuthorityRuntimeId"/>.</summary>
[Obsolete("Use AuthorityRuntimeId. Provider identity is not a physical endpoint.")]
public string ProviderRuntimeId => AuthorityRuntimeId;
internal string SessionKey => VerseId + "\u001f" + AuthorityRuntimeId;
public bool Equals(CultMeshSessionTarget? other) =>
other != null &&
string.Equals(VerseId, other.VerseId, StringComparison.Ordinal) &&
string.Equals(ProviderRuntimeId, other.ProviderRuntimeId, StringComparison.Ordinal);
string.Equals(AuthorityRuntimeId, other.AuthorityRuntimeId, StringComparison.Ordinal);
public override bool Equals(object? obj) => Equals(obj as CultMeshSessionTarget);
public override int GetHashCode() => HashCode.Combine(
StringComparer.Ordinal.GetHashCode(VerseId),
StringComparer.Ordinal.GetHashCode(ProviderRuntimeId));
public override string ToString() => VerseId + "/" + ProviderRuntimeId;
StringComparer.Ordinal.GetHashCode(AuthorityRuntimeId));
public override string ToString() => VerseId + "/" + AuthorityRuntimeId;
}
public sealed class CultMeshProtocolId : IEquatable<CultMeshProtocolId>
@ -80,15 +81,33 @@ namespace GameCult.Mesh
public sealed class CultMeshTransportCandidate
{
public CultMeshTransportCandidate(string endpoint, CultMeshTransportPathKind pathKind = CultMeshTransportPathKind.Direct, int priority = 0)
public CultMeshTransportCandidate(
string endpoint,
CultMeshTransportPathKind pathKind = CultMeshTransportPathKind.Direct,
int priority = 0,
string authorityRuntimeId = "",
string generation = "",
CultMeshAuthorityRoute? authorityRoute = null)
{
Endpoint = string.IsNullOrWhiteSpace(endpoint) ? throw new ArgumentException("Physical endpoint is required.", nameof(endpoint)) : endpoint;
PathKind = pathKind;
Priority = priority;
AuthorityRuntimeId = authorityRuntimeId?.Trim() ?? string.Empty;
Generation = generation?.Trim() ?? string.Empty;
AuthorityRoute = authorityRoute;
}
public string Endpoint { get; }
public CultMeshTransportPathKind PathKind { get; }
public int Priority { get; }
public string AuthorityRuntimeId { get; }
public string Generation { get; }
public CultMeshAuthorityRoute? AuthorityRoute { get; }
internal CultMeshVerifiedAuthorityRoute? VerifiedAuthority { get; private set; }
internal CultMeshTransportCandidate WithVerifiedAuthority(CultMeshVerifiedAuthorityRoute verified)
{
VerifiedAuthority = verified ?? throw new ArgumentNullException(nameof(verified));
return this;
}
}
public enum CultMeshSessionStatus { Connecting, Online, Degraded, Reconnecting, Offline }
@ -522,6 +541,11 @@ namespace GameCult.Mesh
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
public ICultMeshDiagnosticSink Diagnostics { get; set; } = CultMeshNullDiagnosticSink.Instance;
public int MaxRacedCandidates { get; set; } = 2;
public string RuntimeId { get; set; } = "cultmesh-client";
public TimeSpan IdentityHandshakeTimeout { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>Gets or sets the consumer-owned trust roots and explicit local-development policy.</summary>
public CultMeshAuthorityTrustPolicy Trust { get; set; } = new(
CultMeshAuthorityTrustMode.AuthenticatedRemote);
}
public sealed class CultMeshSessionManager : IDisposable
@ -581,6 +605,8 @@ namespace GameCult.Mesh
throw new ArgumentException("Realtime transport connectors cannot contain null entries.", nameof(realtimeConnectors));
_options = options ?? new CultMeshSessionManagerOptions();
if (_options.MaxRacedCandidates <= 0) throw new ArgumentOutOfRangeException(nameof(options));
if (string.IsNullOrWhiteSpace(_options.RuntimeId)) throw new ArgumentException("Client runtime identity is required.", nameof(options));
if (_options.IdentityHandshakeTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(options));
}
public async Task<CultMeshSession> ConnectAsync(
@ -661,14 +687,10 @@ namespace GameCult.Mesh
"No streaming content connectors are configured. Register the TCP content connector or the explicit legacy RUDP connector.");
var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(
target.ProviderRuntimeId,
target.AuthorityRuntimeId,
new[] { target.VerseId },
target.ProviderRuntimeId)).ConfigureAwait(false);
var candidates = discovery.Candidates
.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints)
.Distinct(StringComparer.Ordinal)
.Select(endpoint => new CultMeshTransportCandidate(endpoint))
.ToArray();
target.AuthorityRuntimeId)).ConfigureAwait(false);
var candidates = BoundCandidates(discovery, target, CultMeshProtocols.Content);
var routes = candidates
.SelectMany(candidate => _contentConnectors
.Where(connector => connector.CanConnect(candidate))
@ -685,7 +707,7 @@ namespace GameCult.Mesh
foreach (var tier in routes.GroupBy(route => route.Connector.Priority).OrderBy(group => group.Key))
{
var attempts = tier.Take(_options.MaxRacedCandidates)
.Select(route => ConnectContentCandidateAsync(target.ProviderEndpointId, route))
.Select(route => ConnectContentCandidateAsync(target, route))
.ToList();
while (attempts.Count > 0)
{
@ -709,18 +731,33 @@ namespace GameCult.Mesh
}
var last = failures.LastOrDefault();
var reason = last is CultMeshSessionException typed
? typed.Failure.Reason
: last is TimeoutException
? CultMeshSessionFailureReason.Timeout
: CultMeshSessionFailureReason.Transport;
throw Failure(
last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport,
reason,
$"No streaming content path connected for '{target}'.",
last);
}
private static async Task<ConnectedContentPath> ConnectContentCandidateAsync(
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
ContentRoute route)
{
var transport = await route.Connector.ConnectAsync(route.Candidate, endpointId).ConfigureAwait(false);
return new ConnectedContentPath(route.Candidate, transport);
var transport = await route.Connector.ConnectAsync(route.Candidate, target).ConfigureAwait(false);
try
{
CultMeshTransportIdentity.RequireVerified(
transport, target, CultMeshProtocols.Content, route.Candidate);
return new ConnectedContentPath(route.Candidate, transport);
}
catch
{
transport.Dispose();
throw;
}
}
private void InvalidateContentSession(string key, CultMeshContentSession session)
@ -790,13 +827,10 @@ namespace GameCult.Mesh
"No realtime state connectors are configured. Register a QUIC connector explicitly.");
var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(
target.ProviderRuntimeId,
target.AuthorityRuntimeId,
new[] { target.VerseId },
target.ProviderRuntimeId)).ConfigureAwait(false);
var routes = discovery.Candidates
.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints)
.Distinct(StringComparer.Ordinal)
.Select(endpoint => new CultMeshTransportCandidate(endpoint))
target.AuthorityRuntimeId)).ConfigureAwait(false);
var routes = BoundCandidates(discovery, target, CultMeshProtocols.RealtimeState)
.SelectMany(candidate => _realtimeConnectors
.Where(connector => connector.CanConnect(candidate))
.Select(connector => new RealtimeRoute(candidate, connector)))
@ -812,7 +846,7 @@ namespace GameCult.Mesh
foreach (var tier in routes.GroupBy(route => route.Connector.Priority).OrderBy(group => group.Key))
{
var attempts = tier.Take(_options.MaxRacedCandidates)
.Select(route => ConnectRealtimeCandidateAsync(target.ProviderEndpointId, route))
.Select(route => ConnectRealtimeCandidateAsync(target, route))
.ToList();
while (attempts.Count > 0)
{
@ -836,18 +870,33 @@ namespace GameCult.Mesh
}
var last = failures.LastOrDefault();
var reason = last is CultMeshSessionException typed
? typed.Failure.Reason
: last is TimeoutException
? CultMeshSessionFailureReason.Timeout
: CultMeshSessionFailureReason.Transport;
throw Failure(
last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport,
reason,
$"No realtime state path connected for '{target}'.",
last);
}
private static async Task<ConnectedRealtimePath> ConnectRealtimeCandidateAsync(
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
RealtimeRoute route)
{
var transport = await route.Connector.ConnectAsync(route.Candidate, endpointId).ConfigureAwait(false);
return new ConnectedRealtimePath(route.Candidate, transport);
var transport = await route.Connector.ConnectAsync(route.Candidate, target).ConfigureAwait(false);
try
{
CultMeshTransportIdentity.RequireVerified(
transport, target, CultMeshProtocols.RealtimeState, route.Candidate);
return new ConnectedRealtimePath(route.Candidate, transport);
}
catch
{
transport.Dispose();
throw;
}
}
private void InvalidateRealtimeSession(string key, CultMeshRealtimeSession session)
@ -880,13 +929,10 @@ namespace GameCult.Mesh
private async Task<ConnectedPath> ResolveConnectedPathAsync(CultMeshSessionTarget target, CultMeshProtocolId protocol)
{
var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(
target.ProviderRuntimeId,
target.AuthorityRuntimeId,
new[] { target.VerseId },
target.ProviderRuntimeId)).ConfigureAwait(false);
var candidates = discovery.Candidates.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints)
.Distinct(StringComparer.Ordinal)
.Select(endpoint => new CultMeshTransportCandidate(endpoint))
.ToArray();
target.AuthorityRuntimeId)).ConfigureAwait(false);
var candidates = BoundCandidates(discovery, target, protocol);
var routes = candidates
.SelectMany(candidate => _connectors
.Where(connector => connector.CanConnect(candidate))
@ -908,7 +954,7 @@ namespace GameCult.Mesh
foreach (var tier in routes.GroupBy(route => route.Connector.Priority).OrderBy(group => group.Key))
{
var attempts = tier.Take(_options.MaxRacedCandidates)
.Select(route => ConnectCandidateAsync(route, protocol))
.Select(route => ConnectCandidateAsync(target, route, protocol))
.ToList();
while (attempts.Count > 0)
{
@ -925,7 +971,12 @@ namespace GameCult.Mesh
}
}
var last = failures.LastOrDefault();
throw Failure(last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport,
var reason = last is CultMeshSessionException typed
? typed.Failure.Reason
: last is TimeoutException
? CultMeshSessionFailureReason.Timeout
: CultMeshSessionFailureReason.Transport;
throw Failure(reason,
$"No transport path connected for '{target}' and protocol '{protocol}'.", last);
}
@ -960,9 +1011,9 @@ namespace GameCult.Mesh
try
{
_discovery.Invalidate(new CultMeshDiscoveryQuery(
session.Target.ProviderRuntimeId,
session.Target.AuthorityRuntimeId,
new[] { session.Target.VerseId },
session.Target.ProviderRuntimeId));
session.Target.AuthorityRuntimeId));
var replacement = await ResolveConnectedPathAsync(session.Target, session.Protocol).ConfigureAwait(false);
session.ReplacePhysicalChannel(replacement.Client);
session.Transition(new CultMeshSessionState(
@ -987,10 +1038,30 @@ namespace GameCult.Mesh
}
}
private static async Task<ConnectedPath> ConnectCandidateAsync(SchemaRoute route, CultMeshProtocolId protocol)
private async Task<ConnectedPath> ConnectCandidateAsync(
CultMeshSessionTarget target,
SchemaRoute route,
CultMeshProtocolId protocol)
{
var client = await route.Connector.ConnectAsync(route.Candidate, protocol).ConfigureAwait(false);
return new ConnectedPath(route.Candidate, client);
try
{
await CultMeshSessionIdentityClient.VerifyAsync(
client,
_options.RuntimeId,
target,
protocol,
route.Candidate,
_options.Trust,
_options.Clock.UtcNow,
_options.IdentityHandshakeTimeout).ConfigureAwait(false);
return new ConnectedPath(route.Candidate, client);
}
catch
{
client.Dispose();
throw;
}
}
private static async Task<T> AwaitForCallerAsync<T>(Task<T> shared, CancellationToken cancellationToken)
@ -1008,12 +1079,62 @@ namespace GameCult.Mesh
private CultMeshSessionException Failure(CultMeshSessionFailureReason reason, string message, Exception? inner = null) =>
new CultMeshSessionException(new CultMeshSessionFailure(reason, message), inner);
private CultMeshTransportCandidate[] BoundCandidates(
CultMeshDiscoveryState discovery,
CultMeshSessionTarget target,
CultMeshProtocolId protocol)
{
var routes = discovery.Candidates
.SelectMany(candidate => candidate.Descriptor.AuthorityRoutes)
.Where(route => string.Equals(
route.AuthorityRuntimeId,
target.AuthorityRuntimeId,
StringComparison.Ordinal))
.Where(route => route.Supports(protocol))
.ToArray();
var verified = new List<CultMeshTransportCandidate>();
var rejected = new List<Exception>();
foreach (var route in routes)
{
try
{
verified.Add(new CultMeshTransportCandidate(
route.Endpoint,
priority: route.Priority,
authorityRuntimeId: route.AuthorityRuntimeId,
generation: route.Generation,
authorityRoute: route)
.WithVerifiedAuthority(_options.Trust.Verify(
target.VerseId,
route,
_options.Clock.UtcNow)));
}
catch (CultMeshSessionException error)
{
rejected.Add(error);
}
}
if (verified.Count == 0 && rejected.Count > 0)
{
throw Failure(
CultMeshSessionFailureReason.Authentication,
$"No trusted route remained for CultMesh target '{target}' and protocol '{protocol}'.",
new AggregateException(rejected));
}
return verified
.GroupBy(candidate => candidate.Endpoint, StringComparer.Ordinal)
.Select(group => group.OrderBy(candidate => candidate.Priority).First())
.OrderBy(candidate => candidate.Priority)
.ThenBy(candidate => candidate.Endpoint, StringComparer.Ordinal)
.ToArray();
}
private void Emit(CultMeshSessionTarget target, CultMeshProtocolId protocol, string state, string path)
{
_options.Diagnostics.Emit(new CultMeshDiagnosticEvent(
Interlocked.Increment(ref _diagnosticSequence), _options.Clock.UtcNow,
CultMeshReliabilityOrgan.Session, CultMeshDiagnosticKind.PathChanged,
target.SessionKey + ":" + protocol.Value, target.ProviderRuntimeId, state,
target.SessionKey + ":" + protocol.Value, target.AuthorityRuntimeId, state,
sourceId: "session-manager", endpoint: path));
}

View file

@ -102,7 +102,7 @@ namespace GameCult.Mesh
CultNetDocumentRegistry? registry)
{
_sharedSession = session ?? throw new ArgumentNullException(nameof(session));
_endpoint = session.State.Path?.Endpoint ?? session.Target.ProviderRuntimeId;
_endpoint = session.State.Path?.Endpoint ?? session.Target.AuthorityRuntimeId;
_defaults = CultMesh.CloneSnapshotRequestOptions(options);
_registry = registry ?? new CultNetDocumentRegistry();
_client = session.Channel;

View file

@ -11,6 +11,22 @@ using GameCult.Networking;
namespace GameCult.Mesh
{
/// <summary>Identity served by one dedicated content listener.</summary>
public sealed class CultMeshTcpContentServerOptions
{
public string VerseId { get; set; } = string.Empty;
public string AuthorityRuntimeId { get; set; } = string.Empty;
public string RouteGeneration { get; set; } = string.Empty;
public CultMeshSessionProofSigner? ProofSigner { get; set; }
internal void Validate()
{
if (string.IsNullOrWhiteSpace(VerseId)) throw new InvalidOperationException("Content Verse identity is required.");
if (string.IsNullOrWhiteSpace(AuthorityRuntimeId)) throw new InvalidOperationException("Content authority runtime identity is required.");
if (string.IsNullOrWhiteSpace(RouteGeneration)) throw new InvalidOperationException("Content route generation is required.");
}
}
/// <summary>Creates dedicated TCP streams for immutable CultMesh content.</summary>
public sealed class CultMeshTcpContentTransportConnector : ICultMeshContentTransportConnector
{
@ -33,11 +49,11 @@ namespace GameCult.Mesh
public async Task<ICultMeshContentTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default)
{
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
if (target == null) throw new ArgumentNullException(nameof(target));
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port))
throw new NotSupportedException($"TCP content connector does not support '{candidate.Endpoint}'.");
@ -48,8 +64,10 @@ namespace GameCult.Mesh
{
await CultMeshTcpContentWire.AwaitAsync(client.ConnectAsync(host, port), timeout.Token)
.ConfigureAwait(false);
await CultMeshTcpContentWire.VerifyAuthorityAsync(
client.GetStream(), target, candidate, timeout.Token).ConfigureAwait(false);
Interlocked.Increment(ref _connectCount);
return new CultMeshTcpContentTransport(candidate.Endpoint, client);
return new CultMeshTcpContentTransport(candidate.Endpoint, client, target, candidate.Generation);
}
catch
{
@ -72,7 +90,7 @@ namespace GameCult.Mesh
}
}
internal sealed class CultMeshTcpContentTransport : ICultMeshContentTransport
internal sealed class CultMeshTcpContentTransport : ICultMeshContentTransport, ICultMeshVerifiedTransport
{
private readonly TcpClient _client;
private readonly NetworkStream _stream;
@ -80,12 +98,22 @@ namespace GameCult.Mesh
private readonly ConcurrentDictionary<string, PendingCopy> _pending = new(StringComparer.Ordinal);
private readonly CancellationTokenSource _shutdown = new();
private readonly Task _receiveLoop;
private readonly string _verseId;
private readonly string _authorityRuntimeId;
private readonly string _routeGeneration;
private bool _disposed;
public CultMeshTcpContentTransport(string endpoint, TcpClient client)
public CultMeshTcpContentTransport(
string endpoint,
TcpClient client,
CultMeshSessionTarget target,
string routeGeneration)
{
Endpoint = endpoint;
_client = client ?? throw new ArgumentNullException(nameof(client));
_verseId = target?.VerseId ?? throw new ArgumentNullException(nameof(target));
_authorityRuntimeId = target.AuthorityRuntimeId;
_routeGeneration = routeGeneration ?? string.Empty;
_stream = client.GetStream();
_receiveLoop = ReceiveLoopAsync(_shutdown.Token);
}
@ -93,6 +121,16 @@ namespace GameCult.Mesh
public string TransportId => "tcp-content";
public string Endpoint { get; }
public bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration) =>
string.Equals(_verseId, verseId, StringComparison.Ordinal) &&
string.Equals(_authorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(CultMeshProtocols.Content.Value, protocolId, StringComparison.Ordinal) &&
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
public async Task CopyChunkToAsync(
CultMeshCdnChunkRef chunk,
Stream destination,
@ -212,6 +250,7 @@ namespace GameCult.Mesh
private readonly TcpListener _listener;
private readonly Func<string, CultMeshCdnArtifactChunk?> _resolveChunk;
private readonly Func<string, bool> _canServeHash;
private readonly CultMeshTcpContentServerOptions _options;
private readonly CancellationTokenSource _shutdown = new();
private readonly ConcurrentDictionary<TcpClient, byte> _clients = new();
private readonly Task _acceptLoop;
@ -221,8 +260,9 @@ namespace GameCult.Mesh
public CultMeshTcpContentServer(
TcpListener listener,
CultCache content,
CultMeshTcpContentServerOptions options,
Func<string, bool>? canServeHash = null)
: this(listener, CreateCacheResolver(content), canServeHash)
: this(listener, CreateCacheResolver(content), options, canServeHash)
{
}
@ -234,10 +274,13 @@ namespace GameCult.Mesh
public CultMeshTcpContentServer(
TcpListener listener,
Func<string, CultMeshCdnArtifactChunk?> resolveChunk,
CultMeshTcpContentServerOptions options,
Func<string, bool>? canServeHash = null)
{
_listener = listener ?? throw new ArgumentNullException(nameof(listener));
_resolveChunk = resolveChunk ?? throw new ArgumentNullException(nameof(resolveChunk));
_options = options ?? throw new ArgumentNullException(nameof(options));
_options.Validate();
_canServeHash = canServeHash ?? (_ => true);
_listener.Start();
_acceptLoop = AcceptLoopAsync(_shutdown.Token);
@ -278,6 +321,7 @@ namespace GameCult.Mesh
try
{
using var stream = client.GetStream();
if (!await AcceptAuthorityAsync(stream, cancellationToken).ConfigureAwait(false)) return;
while (!cancellationToken.IsCancellationRequested)
{
var requestBytes = await CultMeshTcpContentWire.ReadFrameAsync(stream, cancellationToken).ConfigureAwait(false);
@ -296,6 +340,47 @@ namespace GameCult.Mesh
}
}
private async Task<bool> AcceptAuthorityAsync(Stream stream, CancellationToken cancellationToken)
{
var requestBytes = await CultMeshTcpContentWire.ReadFrameAsync(stream, cancellationToken).ConfigureAwait(false);
var request = CultNetSchemaMessageSerialization.Deserialize(requestBytes) as CultMeshSessionOpenMessage
?? throw new InvalidDataException("TCP content session did not begin with an authority handshake.");
var accepted = !string.IsNullOrWhiteSpace(request.MessageId) &&
!string.IsNullOrWhiteSpace(request.SourceRuntimeId) &&
IsNonce(request.ClientNonce) &&
string.Equals(request.VerseId, _options.VerseId, StringComparison.Ordinal) &&
string.Equals(request.AuthorityRuntimeId, _options.AuthorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(request.ProtocolId, CultMeshProtocols.Content.Value, StringComparison.Ordinal) &&
string.Equals(request.RouteGeneration, _options.RouteGeneration, StringComparison.Ordinal);
var response = new CultMeshSessionAcceptedMessage
{
MessageId = request.MessageId,
Accepted = accepted,
VerseId = _options.VerseId,
AuthorityRuntimeId = _options.AuthorityRuntimeId,
ProtocolId = CultMeshProtocols.Content.Value,
RouteGeneration = _options.RouteGeneration,
ClientNonce = request.ClientNonce ?? string.Empty,
ProviderKeyId = accepted ? _options.ProofSigner?.ProviderKeyId ?? string.Empty : string.Empty,
ProviderSignature = accepted && _options.ProofSigner != null
? _options.ProofSigner.Sign(request)
: string.Empty,
Error = accepted ? null : "Content session target does not match this authority route."
};
await CultMeshTcpContentWire.WriteFrameAsync(
stream,
CultNetSchemaMessageSerialization.Serialize(response),
cancellationToken).ConfigureAwait(false);
return accepted;
}
private static bool IsNonce(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return false;
try { return Convert.FromBase64String(value).Length == 32; }
catch (FormatException) { return false; }
}
private async Task SendChunkAsync(
Stream stream,
CultMeshContentChunkRequestMessage request,
@ -391,6 +476,48 @@ namespace GameCult.Mesh
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
public static async Task VerifyAuthorityAsync(
Stream stream,
CultMeshSessionTarget target,
CultMeshTransportCandidate candidate,
CancellationToken cancellationToken)
{
var request = new CultMeshSessionOpenMessage
{
MessageId = Guid.NewGuid().ToString("N"),
SourceRuntimeId = "cultmesh-content-client",
VerseId = target.VerseId,
AuthorityRuntimeId = target.AuthorityRuntimeId,
ProtocolId = CultMeshProtocols.Content.Value,
RouteGeneration = candidate.Generation,
ClientNonce = CreateNonce()
};
await WriteFrameAsync(stream, CultNetSchemaMessageSerialization.Serialize(request), cancellationToken)
.ConfigureAwait(false);
var responseBytes = await ReadFrameAsync(stream, cancellationToken).ConfigureAwait(false);
var response = CultNetSchemaMessageSerialization.Deserialize(responseBytes) as CultMeshSessionAcceptedMessage
?? throw new InvalidDataException("TCP content authority handshake returned an unexpected schema.");
if (!string.Equals(response.MessageId, request.MessageId, StringComparison.Ordinal) ||
!response.Accepted ||
!string.Equals(response.VerseId, target.VerseId, StringComparison.Ordinal) ||
!string.Equals(response.AuthorityRuntimeId, target.AuthorityRuntimeId, StringComparison.Ordinal) ||
!string.Equals(response.ProtocolId, CultMeshProtocols.Content.Value, StringComparison.Ordinal) ||
!string.Equals(response.RouteGeneration, candidate.Generation, StringComparison.Ordinal) ||
candidate.VerifiedAuthority == null ||
!CultMeshAuthorityProof.VerifySession(request, response, candidate.VerifiedAuthority))
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
response.Error ?? "TCP content endpoint did not prove the selected authority route.",
candidate.Endpoint));
}
private static string CreateNonce()
{
var nonce = new byte[32];
using (var random = System.Security.Cryptography.RandomNumberGenerator.Create()) random.GetBytes(nonce);
return Convert.ToBase64String(nonce);
}
public static async Task<byte[]> ReadFrameAsync(Stream stream, CancellationToken cancellationToken)
{
var header = new byte[HeaderBytes];

View file

@ -91,6 +91,57 @@ namespace GameCult.Mesh
}
}
/// <summary>
/// Binds one authoritative runtime to one physical route. This relationship is
/// the routing authority; the legacy endpoint/runtime lists are projections only.
/// </summary>
public sealed class CultMeshAuthorityRoute
{
public CultMeshAuthorityRoute(
string authorityRuntimeId,
string endpoint,
IEnumerable<string>? protocolIds = null,
int priority = 0,
string? generation = null,
CultMeshRouteCertificate? certificate = null)
{
AuthorityRuntimeId = RequireNonEmpty(authorityRuntimeId, nameof(authorityRuntimeId));
Endpoint = RequireNonEmpty(endpoint, nameof(endpoint));
ProtocolIds = Clean(protocolIds);
if (priority < 0) throw new ArgumentOutOfRangeException(nameof(priority));
Priority = priority;
Generation = string.IsNullOrWhiteSpace(generation)
? AuthorityRuntimeId + "@" + Endpoint
: generation!.Trim();
Certificate = certificate;
}
public string AuthorityRuntimeId { get; }
public string Endpoint { get; }
public IReadOnlyList<string> ProtocolIds { get; }
public int Priority { get; }
public string Generation { get; }
/// <summary>Gets the optional Odin-signed binding from this route to its provider key.</summary>
public CultMeshRouteCertificate? Certificate { get; }
public bool Supports(CultMeshProtocolId protocol) =>
protocol != null &&
(ProtocolIds.Count == 0 || ProtocolIds.Contains(protocol.Value, StringComparer.Ordinal));
private static string[] Clean(IEnumerable<string>? values) =>
values?.Where(value => !string.IsNullOrWhiteSpace(value))
.Select(value => value.Trim())
.Distinct(StringComparer.Ordinal)
.OrderBy(value => value, StringComparer.Ordinal)
.ToArray()
?? Array.Empty<string>();
private static string RequireNonEmpty(string value, string paramName) =>
string.IsNullOrWhiteSpace(value)
? throw new ArgumentException("Value must be non-empty.", paramName)
: value.Trim();
}
/// <summary>
/// Describes one CultMesh Verse: a rule-bearing consensus graph.
/// </summary>
@ -107,14 +158,36 @@ namespace GameCult.Mesh
IEnumerable<string>? discoveryEndpoints = null,
IEnumerable<string>? authorityRuntimeIds = null,
string? parentVerseId = null,
string? description = null)
string? description = null,
IEnumerable<CultMeshAuthorityRoute>? authorityRoutes = 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);
var legacyEndpoints = Clean(discoveryEndpoints);
var legacyRuntimeIds = Clean(authorityRuntimeIds);
var suppliedRoutes = authorityRoutes?.ToArray();
if (suppliedRoutes?.Any(route => route == null) == true)
throw new ArgumentException("Authority routes cannot contain null.", nameof(authorityRoutes));
if (suppliedRoutes != null && (legacyEndpoints.Length > 0 || legacyRuntimeIds.Length > 0))
throw new ArgumentException(
"Supply bound authority routes or legacy endpoint/runtime lists, never both.",
nameof(authorityRoutes));
if (suppliedRoutes == null && legacyEndpoints.Length > 0 && legacyRuntimeIds.Length > 1)
throw new InvalidOperationException(
"Legacy Verse routing with multiple authority runtimes is ambiguous. " +
"Publish explicit CultMeshAuthorityRoute bindings.");
AuthorityRoutes = NormalizeRoutes(suppliedRoutes ??
(legacyRuntimeIds.Length == 1
? legacyEndpoints.Select(endpoint => new CultMeshAuthorityRoute(legacyRuntimeIds[0], endpoint))
: Array.Empty<CultMeshAuthorityRoute>()));
DiscoveryEndpoints = AuthorityRoutes.Count > 0
? AuthorityRoutes.Select(route => route.Endpoint).Distinct(StringComparer.Ordinal).ToArray()
: legacyEndpoints;
AuthorityRuntimeIds = AuthorityRoutes.Select(route => route.AuthorityRuntimeId)
.Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray();
ParentVerseId = parentVerseId;
Description = description;
}
@ -143,6 +216,8 @@ namespace GameCult.Mesh
/// Gets known authoritative runtime ids, when authority is cluster-shaped.
/// </summary>
public IReadOnlyList<string> AuthorityRuntimeIds { get; }
/// <summary>Gets exact authority-to-route bindings used for identity-sensitive resolution.</summary>
public IReadOnlyList<CultMeshAuthorityRoute> AuthorityRoutes { get; }
/// <summary>
/// Gets the parent Verse id for subscribed overlays or branches.
/// </summary>
@ -177,10 +252,29 @@ namespace GameCult.Mesh
private static string[] Clean(IEnumerable<string>? values)
{
return values?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray()
return values?.Where(value => !string.IsNullOrWhiteSpace(value))
.Select(value => value.Trim())
.Distinct(StringComparer.Ordinal)
.ToArray()
?? Array.Empty<string>();
}
private static CultMeshAuthorityRoute[] NormalizeRoutes(IEnumerable<CultMeshAuthorityRoute> routes)
{
return routes
.GroupBy(route => new
{
route.AuthorityRuntimeId,
route.Endpoint,
Protocols = string.Join("\u001f", route.ProtocolIds)
})
.Select(group => group.OrderBy(route => route.Priority).First())
.OrderBy(route => route.Priority)
.ThenBy(route => route.AuthorityRuntimeId, StringComparer.Ordinal)
.ThenBy(route => route.Endpoint, StringComparer.Ordinal)
.ToArray();
}
private static string RequireNonEmpty(string value, string paramName)
{
if (string.IsNullOrWhiteSpace(value))

View file

@ -33,6 +33,24 @@ namespace GameCult.Mesh
},
DiscoveryEndpoints = verse.DiscoveryEndpoints.ToArray(),
AuthorityRuntimeIds = verse.AuthorityRuntimeIds.ToArray(),
AuthorityRoutes = verse.AuthorityRoutes.Select(route => new CultMeshAuthorityRouteMessage
{
AuthorityRuntimeId = route.AuthorityRuntimeId,
Endpoint = route.Endpoint,
ProtocolIds = route.ProtocolIds.ToArray(),
Priority = route.Priority,
Generation = route.Generation,
Certificate = route.Certificate == null ? null : new CultMeshRouteCertificateMessage
{
ProviderKeyId = route.Certificate.ProviderKey.KeyId,
ProviderPublicKeyX = route.Certificate.ProviderKey.X,
ProviderPublicKeyY = route.Certificate.ProviderKey.Y,
OdinKeyId = route.Certificate.OdinKeyId,
IssuedAtUnixMilliseconds = route.Certificate.IssuedAtUnixMilliseconds,
ExpiresAtUnixMilliseconds = route.Certificate.ExpiresAtUnixMilliseconds,
Signature = route.Certificate.Signature
}
}).ToArray(),
ParentVerseId = verse.ParentVerseId,
Description = verse.Description
};
@ -50,6 +68,21 @@ namespace GameCult.Mesh
out var parsed)
? parsed
: CultMeshVerseAuthorityModel.SubscribedOverlay;
var routes = message.AuthorityRoutes?.Select(route => new CultMeshAuthorityRoute(
route.AuthorityRuntimeId,
route.Endpoint,
route.ProtocolIds,
route.Priority,
route.Generation,
route.Certificate == null ? null : new CultMeshRouteCertificate(
new CultMeshEcdsaP256PublicKey(
route.Certificate.ProviderKeyId,
route.Certificate.ProviderPublicKeyX,
route.Certificate.ProviderPublicKeyY),
route.Certificate.OdinKeyId,
route.Certificate.IssuedAtUnixMilliseconds,
route.Certificate.ExpiresAtUnixMilliseconds,
route.Certificate.Signature))).ToArray();
return new CultMeshVerseDescriptor(
message.VerseId,
message.DisplayName,
@ -60,10 +93,11 @@ namespace GameCult.Mesh
message.Compatibility.CompatibleVerseIds,
message.Compatibility.RequiredPluginIds,
message.Compatibility.OptionalPluginIds),
message.DiscoveryEndpoints,
message.AuthorityRuntimeIds,
routes is { Length: > 0 } ? null : message.DiscoveryEndpoints,
routes is { Length: > 0 } ? null : message.AuthorityRuntimeIds,
message.ParentVerseId,
message.Description);
message.Description,
routes is { Length: > 0 } ? routes : null);
}
/// <summary>Creates the canonical filtered Verse catalog response for any CultNet transport adapter.</summary>
@ -173,6 +207,12 @@ namespace GameCult.Mesh
/// </summary>
public Func<ICultNetSchemaClient>? CreateClient { get; set; }
/// <summary>
/// Gets or sets an endpoint-aware client factory for external transport packages.
/// When present, this owns discovery transport selection for each exact Odin route.
/// </summary>
public Func<string, ICultNetSchemaClient>? CreateClientForEndpoint { get; set; }
/// <summary>Gets or sets the clock that owns discovery deadlines.</summary>
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
@ -307,7 +347,8 @@ namespace GameCult.Mesh
private ICultNetSchemaClient CreateClient(string endpoint)
{
return _options.CreateClient?.Invoke()
return _options.CreateClientForEndpoint?.Invoke(endpoint)
?? _options.CreateClient?.Invoke()
?? CultNetSchemaClients.CreateForEndpoint(endpoint, _options.Security, _options.ConfigureClient);
}

View file

@ -8,7 +8,8 @@ This is the implementation map for the browser Verse boundary.
`samples/eve-two-runtime` remains the clean package-consumer/jsdom checkpoint.
`samples/eve-browser-network` runs a durable C# provider, a real Chromium Eve
lowerer, an independent C# headless observer, and a separate local Odin fixture
over authenticated binary CultNet WebSocket routes. It proves one canonical
over binary loopback CultNet WebSocket routes under an explicit
`local-development` trust policy. It proves one canonical
command effect, idempotent retry, shared observation, provider restart on a new
physical route, browser rediscovery, retained lease resubscription, and a second
canonical command after reconnection.
@ -29,6 +30,10 @@ not a complete public Verse proof:
`cultmesh.verse_catalog_request.v0` and
`cultmesh.verse_catalog_response.v0`; application callbacks no longer need to
smuggle provider URLs into the browser client;
- `CultMeshBrowserClient` owns the final authority gate: remote use requires a
consumer-pinned Odin P-256 root, an Odin-signed route certificate, `wss://`,
and provider possession proof over a fresh nonce. A catalog source cannot
bypass that gate by returning a route-shaped object;
- Kotlin has a channel-aware WebSocket transport adapter, TypeScript has the
browser client, and `GameCult.Networking.WebSockets` provides the bounded C#
schema server host adapter;
@ -58,9 +63,9 @@ Owner:
Inputs:
- an Odin-discovered WebSocket transport candidate;
- an Odin-discovered route certificate and consumer-configured Odin root;
- stable Verse and provider identities;
- authenticated session evidence;
- provider key possession over a fresh client nonce;
- requested schema ids and record keys;
- typed operation invocations and idempotency keys;
- canonical CultNet schema-v0 MessagePack messages.

View file

@ -34,7 +34,7 @@ using var node = await CultMesh.CreateNodeAsync("counter.cc", new CultMeshNodeOp
CacheOptions = new CultCacheOpenOptions { Registry = registry },
DatabaseOptions = new CultNetDatabaseOptions
{
RuntimeId = "sample.counter-provider",
RuntimeId = "sample.counter-daemon",
DocumentRegistry = documents
}
});

View file

@ -1,24 +1,56 @@
# 2. Connect A Client By Stable Identity
Clients address a live session by stable Verse/provider identity. In this tutorial,
`sample.counter` is the Verse id and `sample.counter-provider` is the authority
`sample.counter` is the Verse id and `sample.counter-daemon` is the authority
runtime Odin currently advertises for it. Application clients pass that typed
pair, never a socket address and never one ambiguous string that might mean
either identity. A product may expose only a Verse choice to its user; its
selection owner then resolves the provider runtime from Odin's descriptor before
opening the session. Discovery owns the current physical routes, and the session
manager owns connection reuse, path rotation, and transport failure state.
Each Odin route binds that authority runtime to one endpoint, protocol set, and
generation. For a remote Verse, Odin signs that exact tuple and the provider's
P-256 public key. The client pins an Odin root from its own configuration, then
requires the connected provider to sign a fresh client nonce. A route cannot
become usable by merely repeating the expected Verse and runtime strings.
```csharp
using GameCult.Mesh;
using GameCult.Networking.WebSockets;
var odinEndpoint = Environment.GetEnvironmentVariable("ODIN_ENDPOINT")
?? throw new InvalidOperationException("Set ODIN_ENDPOINT to the configured rendezvous route.");
const string verseId = "sample.counter";
var target = new CultMeshSessionTarget(verseId, "sample.counter-provider");
var target = new CultMeshSessionTarget(verseId, "sample.counter-daemon");
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var cancellationToken = timeout.Token;
var odinRoot = new CultMeshEcdsaP256PublicKey(
Environment.GetEnvironmentVariable("ODIN_ROOT_KEY_ID")
?? throw new InvalidOperationException("Set ODIN_ROOT_KEY_ID."),
Environment.GetEnvironmentVariable("ODIN_ROOT_P256_X")
?? throw new InvalidOperationException("Set ODIN_ROOT_P256_X."),
Environment.GetEnvironmentVariable("ODIN_ROOT_P256_Y")
?? throw new InvalidOperationException("Set ODIN_ROOT_P256_Y."));
using var mesh = new CultMeshClient(new CultMeshClientOptions
{
RendezvousEndpoints = new[] { odinEndpoint }
RendezvousEndpoints = new[] { odinEndpoint },
Discovery = new CultMeshVerseDiscoveryClientOptions
{
CreateClientForEndpoint = _ => new CultNetWebSocketSchemaClient()
},
Sessions = new CultMeshSessionManagerOptions
{
Trust = new CultMeshAuthorityTrustPolicy(
CultMeshAuthorityTrustMode.AuthenticatedRemote,
new[] { odinRoot })
},
Connectors = new ICultMeshTransportConnector[]
{
new CultMeshUriSchemaTransportConnector(
"cultnet-websocket",
new[] { "wss" },
_ => new CultNetWebSocketSchemaClient())
}
});
using var counterLease = await mesh.LeaseDocumentAsync<CounterState>(
@ -58,6 +90,45 @@ using var stateWatch = session.WatchState().Subscribe(state =>
Application code does not reconnect, sleep, rank endpoints, or replace the
session. Those decisions belong to CultMesh.
For a deliberately local, moddable Verse, select the exception explicitly and
use only in-process or loopback routes:
```csharp
Sessions = new CultMeshSessionManagerOptions
{
Trust = new CultMeshAuthorityTrustPolicy(CultMeshAuthorityTrustMode.LocalDevelopment)
}
```
`LocalDevelopment` never accepts an unsigned non-loopback route. Verse names,
provider names, and Odin wire fields cannot turn this exception on. Remote
routes require a trusted Odin signature, provider nonce proof, certificate
validity, and a protected channel.
The remote example requires both `GameCult.Mesh` and
`GameCult.Networking.WebSockets` at the same CultLib package version. Core
CultMesh does not silently install a network stack: the consumer chooses the
secure connector and its TLS policy. The default TCP connector exists for the
explicit loopback-development case and cannot satisfy authenticated-remote
trust.
An authenticated provider receives an Odin-certified route and its matching
provider private key from deployment configuration. It attaches the proof gate
to the same WSS schema server before publishing the route:
```csharp
using var identity = new CultMeshSessionIdentityServer(
schemaServer,
authorityRuntimeId: "sample.counter-daemon",
verseIds: new[] { "sample.counter" },
protocolIds: new[] { CultMeshProtocols.Documents.Value },
routeGenerations: new[] { certifiedRoute.Generation },
proofSigners: new[] { new CultMeshSessionProofSigner(certifiedRoute, providerPrivateKey) });
```
`certifiedRoute` is the exact signed route Odin publishes. The provider never
holds Odin's signing key, and an unsigned WSS route is still untrusted.
Fast session-management check (this uses controlled transports; it is not the
network proof):
@ -65,6 +136,11 @@ network proof):
dotnet test tests/GameCult.Mesh.Tests/GameCult.Mesh.Tests.csproj --filter FullyQualifiedName~CultMeshSessionManagerTests
```
The local checkpoint in chapter 4 additionally advertises a better-priority
endpoint for the wrong authority runtime. Both the C# and browser clients must
ignore it, verify the intended peer, survive route replacement, and reject
wrong-source operation responses.
Advanced hosts may inject lookup sources, connectors, clocks, persistence, and
diagnostics through the lower-level discovery and session APIs. Application
features should not need them.

View file

@ -97,6 +97,10 @@ GameCult dependency is `PackageReference Include="GameCult.Eve.Surface"`.
This proves the renderer-neutral provider contract does not require a sibling
Eve or CultLib source tree after packaging.
The real-process C# sample is then rebuilt from that same temporary NuGet feed.
The source project references in its `.csproj` are contributor convenience only
and are disabled by the checkpoint; they are not the consumer contract.
The first layer builds and packs `cultcache-ts`, `cultnet-ts`, `cultmesh-ts`,
`@gamecult/eve-contracts`, and `@gamecult/eve-browser-lowering`, installs the
tarballs into an empty temporary consumer, and runs
@ -108,11 +112,11 @@ both consumers converge on the same state and canonical receipt identity, a
duplicate idempotency key is not applied twice, and the state plus receipt
survive reopening the `.cc` store.
The second layer runs a durable C# provider, a separate local Odin fixture, a
real Chromium Eve lowerer, and an independent C# headless observer over binary
The second layer runs a durable C# provider, a wrong-authority decoy, a separate
local Odin fixture, a real Chromium Eve lowerer, and an independent C# headless observer over binary
CultNet WebSocket lanes. The open browser resolves the `sample.counter` Verse
through the canonical catalog, survives its provider restarting on a different route,
and resubscribes. The retained C# client then invokes a second typed operation
through the canonical catalog, rejects the decoy route, survives its provider
restarting on a different route, and resubscribes. The retained C# client then invokes a second typed operation
through `CultMeshClient.InvokeAsync`; Chromium and C# observe the same
provider-authored state and receipt chronology. The same retained C# session
then completes 10,000 typed no-op operations under explicit p99 and post-GC

View file

@ -10,6 +10,8 @@ The counter is now one small multiplayer game:
typed operation boundary;
- both clients remain attached when Odin moves the Verse to a replacement
physical provider route.
- a better-priority route bound to another runtime remains unreachable to both
clients throughout the chronology.
Run the whole chronology from the CultLib checkout:
@ -34,8 +36,10 @@ packages, installs those artifacts into an empty temporary consumer, and proves
DOM/headless convergence plus `.cc` reopen. This rejects a sample that only
works through repository-relative source imports.
The third checkpoint boots separate Odin, provider, Chromium, and C# headless
processes. Chromium performs the first increment. The provider then restarts on
The third checkpoint boots separate Odin, intended provider, wrong-authority
decoy provider, Chromium, and C# headless processes. Its C# application is built
from the temporary NuGet feed produced by the first checkpoint, not sibling
project references. Chromium performs the first increment. The provider then restarts on
a different route, Odin advertises the replacement, and the retained clients
resubscribe without application reconnect code. C# performs the second
increment. Both clients must observe count 2 and both canonical receipt ids.

View file

@ -4,14 +4,22 @@ This series builds one typed application state and presents it through multiple
Eve runtimes. It is maintained as an API acceptance test: examples use public
APIs, name the owner of each decision, and include a verification checkpoint.
Run the complete getting-started checkpoint:
Application consumers install released packages and do not need the source
repositories. This checkout also contains a maintainer checkpoint that creates
the same clean consumers from local package artifacts:
```powershell
pwsh -File ./scripts/verify-eve-getting-started.ps1
```
With clean sibling CultLib and Eve checkouts, the command installs missing build
dependencies and runs three explicit evidence layers. First it packs the
The maintainer command takes an explicit `-EveRoot` when Eve is not a sibling:
```powershell
pwsh -File ./scripts/verify-eve-getting-started.ps1 -EveRoot D:\src\Eve
```
It installs missing build dependencies and runs three explicit evidence layers.
First it packs the
CultLib managed dependency closure plus `GameCult.Eve.Surface`, then restores
and runs an empty .NET consumer using only `PackageReference`. Next it packs the five
TypeScript packages into another empty temporary consumer, validates the Eve surface
@ -20,7 +28,8 @@ headless observer converge, and reopens the durable `.cc` store. Then it boots a
durable C# provider, local Odin fixture, real Chromium lowerer, and independent
C# client. Chromium invokes before provider replacement; C# invokes afterward.
Both retained clients prove discovery by identity, canonical receipts, provider
restart on another route, resubscription, and durable convergence. The retained
restart on another route, rejection of a better-priority wrong-authority route,
resubscription, and durable convergence. The retained
C# session also completes 10,000 non-persistent typed operations under p99 and
post-GC managed-memory gates.
Set `CHROME_PATH` only when no installed Chrome, Chromium, Edge, or Playwright
@ -58,3 +67,6 @@ native projection. CultMesh owns discovery and connection continuity.
pull request.
- A setup step that depends on repository internals is an API defect, not
acceptable tutorial folklore.
- The maintainer command may read owner checkouts to create packages. Every
sample process it launches must consume those package artifacts rather than
compiling through sibling project references.

View file

@ -50,8 +50,12 @@ not the brand surface.
### 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.
transport compatibility, rules hash, authority model, exact authority-route
bindings, optional parent Verse id, and plugin requirements. Each route binds
an authority runtime to one endpoint, protocol set, priority, and generation.
The old endpoint/runtime arrays are derived projections; a legacy descriptor
with several authority runtimes is rejected because it cannot identify which
runtime owns which route.
`CultMeshVerseCatalog` is the local reactive catalog for discovered Verses.
It can publish discovery updates and find compatible transfer targets.

View file

@ -9,7 +9,8 @@ be equally good at files, realtime state, and same-machine memory access.
registered connector for each traffic class. A connector owns only its physical
connection and byte movement.
**Inputs:** stable Verse/provider identity, advertised physical candidates,
**Inputs:** stable Verse/authority-runtime identity, exact Odin-bound physical
routes with protocol and generation,
connector support and priority, caller cancellation, and locality evidence for
body negotiation.
@ -63,13 +64,29 @@ operation.
transport diagnostics. None of these grant provider authority or become content
identity.
Before a schema, content, or realtime session becomes online, consumer-owned
trust verifies an Odin-signed route certificate binding Verse, authority
runtime, protocol set, endpoint, generation, validity interval, and provider
P-256 key. Schema and content lanes then require a fresh client nonce signed by
that provider key. QUIC uses the signed endpoint plus its TLS
endpoint/certificate proof. A connector that returns bytes without this chain
is rejected; racing every endpoint in a Verse descriptor is not route
selection. Unsigned traffic exists only under an explicitly selected
`LocalDevelopment` policy and only for in-process or loopback routes.
Route and session signatures use ECDSA P-256 with SHA-256 and fixed-width IEEE
P1363 `r || s` encoding, matching browser WebCrypto. Their canonical
transcripts are ordered UTF-8 fields prefixed by four-byte big-endian lengths;
serializer bytes are never signature authority.
**Forbidden writers:** applications and renderers do not choose unadvertised
endpoints, implement reconnect loops, or bypass verification. Schema messages
must not carry bulk bodies. RUDP/LiteNetLib cannot become an implicit default
for any traffic class. QUIC does not own schemas or immutable files merely
because it can transport bytes.
**Shared paths:** discovery and identity resolution remain common. Each traffic
**Shared paths:** exact route resolution and peer verification remain common.
Each traffic
class has its own connector set, connection cache, priority tiers, and failure
state. All content connectors feed the same transfer and promotion owner.
@ -84,7 +101,8 @@ new seam does not pretend that migration has already occurred.
## Security and release gate
The current TCP control and content connectors are plaintext and therefore
restricted to local or otherwise trusted deployment. Adding TLS must not move
restricted to explicit loopback development. They cannot carry an authenticated
remote session. Adding TLS must not move
discovery, authorization, content verification, or application semantics into
the TCP adapter.

View file

@ -21,8 +21,10 @@ The same transport can carry many Verses:
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
- `AuthorityRoutes`: exact authority-runtime, endpoint, protocol, priority, and
generation bindings. This is the routing authority.
- `DiscoveryEndpoints`: read-only endpoint projection for legacy inspection
- `AuthorityRuntimeIds`: read-only authority projection for legacy inspection
- `ParentVerseId`: source Verse for overlays or branches
## Compatibility
@ -57,6 +59,13 @@ 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.
An endpoint and an authority id are not two independent facts. A descriptor
with explicit routes binds them. The legacy parallel arrays are accepted only
when exactly one authority runtime exists; a multi-authority legacy descriptor
is ambiguous and fails closed. Session establishment then requires the selected
physical route to prove the exact Verse, authority runtime, protocol, and route
generation before the session becomes online.
Peer exchange is the torrent-shaped layer under Verse discovery. A Verse
catalog says which graph exists; a peer catalog says which nodes can currently
serve or observe parts of that graph. Peer cards can advertise discovery,

View file

@ -0,0 +1,46 @@
using System;
using System.IO;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace GameCult.Networking.WebSockets;
internal static class CultNetWebSocketMessageIO
{
public static Task SendAsync(WebSocket socket, byte[] payload, CancellationToken cancellationToken) =>
socket.SendAsync(new ArraySegment<byte>(payload), WebSocketMessageType.Binary, true, cancellationToken);
public static async Task<byte[]?> ReceiveAsync(
WebSocket socket,
int maxMessageBytes,
CancellationToken cancellationToken)
{
var segment = new byte[Math.Min(16 * 1024, maxMessageBytes)];
using var message = new MemoryStream();
while (true)
{
var result = await socket.ReceiveAsync(new ArraySegment<byte>(segment), cancellationToken)
.ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close) return null;
if (result.MessageType != WebSocketMessageType.Binary)
{
await socket.CloseAsync(
WebSocketCloseStatus.InvalidMessageType,
"CultNet requires binary MessagePack WebSocket messages.",
cancellationToken).ConfigureAwait(false);
return null;
}
if (message.Length + result.Count > maxMessageBytes)
{
await socket.CloseAsync(
WebSocketCloseStatus.MessageTooBig,
"CultNet message exceeds the configured maximum.",
cancellationToken).ConfigureAwait(false);
return null;
}
message.Write(segment, 0, result.Count);
if (result.EndOfMessage) return message.ToArray();
}
}
}

View file

@ -37,7 +37,7 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
/// <inheritdoc />
public void Connect(string host, int port)
{
ArgumentException.ThrowIfNullOrWhiteSpace(host);
if (string.IsNullOrWhiteSpace(host)) throw new ArgumentException("Host is required.", nameof(host));
if (port <= 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port));
ConnectAsync(new Uri($"ws://{host}:{port}/cultmesh"), CancellationToken.None)
.GetAwaiter().GetResult();
@ -46,7 +46,7 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
/// <summary>Connects to an exact WebSocket route.</summary>
public async Task ConnectAsync(Uri endpoint, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(endpoint);
if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
if (endpoint.Scheme is not ("ws" or "wss"))
throw new ArgumentException("CultNet WebSocket endpoint must use ws:// or wss://.", nameof(endpoint));
ThrowIfDisposed();
@ -69,7 +69,7 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
/// <inheritdoc />
public void SendCultNet<T>(T message) where T : ICultNetSchemaMessage
{
ArgumentNullException.ThrowIfNull(message);
if (message == null) throw new ArgumentNullException(nameof(message));
ThrowIfDisposed();
var socket = _socket;
if (socket?.State != WebSocketState.Open)
@ -92,7 +92,7 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
/// <inheritdoc />
public void OnCultNet<T>(Action<T> callback) where T : ICultNetSchemaMessage
{
ArgumentNullException.ThrowIfNull(callback);
if (callback == null) throw new ArgumentNullException(nameof(callback));
ThrowIfDisposed();
lock (_handlerGate)
{
@ -161,6 +161,6 @@ public sealed class CultNetWebSocketSchemaClient : ICultNetUriSchemaClient, ICul
private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_disposed) throw new ObjectDisposedException(nameof(CultNetWebSocketSchemaClient));
}
}

View file

@ -178,44 +178,6 @@ public sealed class CultNetWebSocketSchemaServer :
}
}
internal static class CultNetWebSocketMessageIO
{
public static Task SendAsync(WebSocket socket, byte[] payload, CancellationToken cancellationToken) =>
socket.SendAsync(payload, WebSocketMessageType.Binary, true, cancellationToken);
public static async Task<byte[]?> ReceiveAsync(
WebSocket socket,
int maxMessageBytes,
CancellationToken cancellationToken)
{
var segment = new byte[Math.Min(16 * 1024, maxMessageBytes)];
using var message = new MemoryStream();
while (true)
{
var result = await socket.ReceiveAsync(segment, cancellationToken).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close) return null;
if (result.MessageType != WebSocketMessageType.Binary)
{
await socket.CloseAsync(
WebSocketCloseStatus.InvalidMessageType,
"CultNet requires binary MessagePack WebSocket messages.",
cancellationToken).ConfigureAwait(false);
return null;
}
if (message.Length + result.Count > maxMessageBytes)
{
await socket.CloseAsync(
WebSocketCloseStatus.MessageTooBig,
"CultNet message exceeds the configured maximum.",
cancellationToken).ConfigureAwait(false);
return null;
}
message.Write(segment, 0, result.Count);
if (result.EndOfMessage) return message.ToArray();
}
}
}
/// <summary>ASP.NET Core endpoint mapping for the CultNet WebSocket schema server.</summary>
public static class CultNetWebSocketEndpointRouteBuilderExtensions
{

View file

@ -1,12 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework></TargetFramework>
<TargetFrameworks>net10.0;netstandard2.1</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Description>CultNet schema-v0 WebSocket host adapter for browser and web runtimes</Description>
<PackageId>GameCult.Networking.WebSockets</PackageId>
<PackageTags>game;networking;websocket;cultnet;cultmesh</PackageTags>
</PropertyGroup>
<ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net10.0'">
<ProjectReference Include="..\GameCult.Networking\GameCult.Networking.csproj" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.1'">
<ProjectReference Include="..\GameCult.Networking\GameCult.Networking.csproj" />
<Compile Remove="CultNetWebSocketSchemaServer.cs" />
</ItemGroup>
</Project>

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Caching;
using R3;
@ -297,6 +298,11 @@ namespace GameCult.Networking
/// Gets or sets the durable store for accepted shard mutation logs.
/// </summary>
public ICultNetShardMutationLogStore? MutationLogStore { get; set; }
/// <summary>
/// Gets or sets whether authoritative writes must occur inside ExecuteTransactionAsync.
/// Use this for state owners that forbid record-at-a-time mutation bypasses.
/// </summary>
public bool RequireTransactionsForAuthoritativeWrites { get; set; }
}
/// <summary>
@ -464,6 +470,8 @@ namespace GameCult.Networking
private readonly Dictionary<string, long> _nextLogSequences = new(StringComparer.Ordinal);
private readonly Dictionary<string, long> _appliedShardSequences = new(StringComparer.Ordinal);
private readonly Subject<object> _changes = new();
private readonly AsyncLocal<CultNetDatabaseTransaction?> _ambientTransaction = new();
private readonly bool _requireTransactionsForAuthoritativeWrites;
private bool _disposed;
/// <summary>
@ -476,6 +484,7 @@ namespace GameCult.Networking
_runtimeId = options.RuntimeId;
_documents = options.DocumentRegistry ?? new CultNetDocumentRegistry(cache.Registry);
_mutationLogStore = options.MutationLogStore;
_requireTransactionsForAuthoritativeWrites = options.RequireTransactionsForAuthoritativeWrites;
_shards = (options.Shards == null || options.Shards.Count == 0
? new[] { CultNetShardDescriptor.PrimaryAll(options.RuntimeId) }
: options.Shards)
@ -503,6 +512,49 @@ namespace GameCult.Networking
/// </summary>
public IReadOnlyList<CultNetClientAuthorityScope> ClientAuthorityScopes => _clientAuthorityScopes;
/// <summary>
/// Runs one buffered authoritative database mutation. Cache state, durable state,
/// mutation logs, and database observers advance only after the complete stage succeeds.
/// </summary>
public async Task ExecuteTransactionAsync(Func<Task> stageAsync, bool soft = false)
{
ThrowIfDisposed();
if (stageAsync == null) throw new ArgumentNullException(nameof(stageAsync));
if (_ambientTransaction.Value != null)
{
await stageAsync().ConfigureAwait(false);
return;
}
var transaction = new CultNetDatabaseTransaction();
IReadOnlyList<Action> afterCommit;
_ambientTransaction.Value = transaction;
try
{
await _cache.ExecuteTransactionAsync(stageAsync, soft).ConfigureAwait(false);
afterCommit = transaction.AfterCommit.ToArray();
}
finally
{
_ambientTransaction.Value = null;
}
foreach (var publish in afterCommit)
publish();
}
/// <summary>Runs one value-producing buffered authoritative database mutation.</summary>
public async Task<T> ExecuteTransactionAsync<T>(Func<Task<T>> stageAsync, bool soft = false)
{
if (stageAsync == null) throw new ArgumentNullException(nameof(stageAsync));
T result = default!;
await ExecuteTransactionAsync(async () =>
{
result = await stageAsync().ConfigureAwait(false);
}, soft).ConfigureAwait(false);
return result;
}
/// <summary>Gets whether this database instance can authoritatively replace the document at a key.</summary>
public bool CanWriteAuthoritatively<T>(CultRecordKey key) where T : class
{
@ -817,6 +869,7 @@ namespace GameCult.Networking
public async Task<CultRecordHandle<T>> PutAsync<T>(CultRecordKey key, T document) where T : class
{
ThrowIfDisposed();
EnsureAuthoritativeTransaction();
if (document == null) throw new ArgumentNullException(nameof(document));
var descriptor = _cache.Registry.GetRequired<T>();
@ -825,20 +878,27 @@ namespace GameCult.Networking
var previous = _cache.Get<T>(key);
var handle = await _cache.UpsertAsync(document, new CultRecordHandle<T>(key)).ConfigureAwait(false);
AppendMutationLogEntry(
shard,
previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated,
key,
descriptor.SchemaId,
document,
previous);
Publish(new CultNetDatabaseChange<T>(
previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated,
key,
descriptor.SchemaId,
shard,
document,
previous));
void PublishCommittedPut()
{
AppendMutationLogEntry(
shard,
previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated,
key,
descriptor.SchemaId,
document,
previous);
Publish(new CultNetDatabaseChange<T>(
previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated,
key,
descriptor.SchemaId,
shard,
document,
previous));
}
if (_ambientTransaction.Value is { } transaction)
transaction.AfterCommit.Add(PublishCommittedPut);
else
PublishCommittedPut();
return handle;
}
@ -873,6 +933,7 @@ namespace GameCult.Networking
public Task DeleteAsync<T>(CultRecordKey key) where T : class
{
ThrowIfDisposed();
EnsureAuthoritativeTransaction();
var descriptor = _cache.Registry.GetRequired<T>();
var shard = ResolveShardInternal(descriptor, key);
EnsurePrimary(shard, descriptor.SchemaId, key);
@ -881,20 +942,27 @@ namespace GameCult.Networking
if (previous != null)
{
_cache.Remove(new CultRecordHandle<T>(key));
AppendMutationLogEntry(
shard,
CultNetDatabaseChangeKind.Removed,
key,
descriptor.SchemaId,
document: null,
previousDocument: previous);
Publish(new CultNetDatabaseChange<T>(
CultNetDatabaseChangeKind.Removed,
key,
descriptor.SchemaId,
shard,
document: null,
previousDocument: previous));
void PublishCommittedDelete()
{
AppendMutationLogEntry(
shard,
CultNetDatabaseChangeKind.Removed,
key,
descriptor.SchemaId,
document: null,
previousDocument: previous);
Publish(new CultNetDatabaseChange<T>(
CultNetDatabaseChangeKind.Removed,
key,
descriptor.SchemaId,
shard,
document: null,
previousDocument: previous));
}
if (_ambientTransaction.Value is { } transaction)
transaction.AfterCommit.Add(PublishCommittedDelete);
else
PublishCommittedDelete();
}
return Task.CompletedTask;
@ -906,6 +974,7 @@ namespace GameCult.Networking
public async Task<object> ApplyPutAsync(CultNetDocumentPutRawMessage message)
{
ThrowIfDisposed();
EnsureAuthoritativeTransaction();
if (message == null) throw new ArgumentNullException(nameof(message));
if (message.Document == null)
{
@ -920,31 +989,41 @@ namespace GameCult.Networking
var document = await _documents.ApplyRawDocumentPutMessageAsync(_cache, message).ConfigureAwait(false);
var kind = previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated;
var predictionKey = PredictionKey(descriptor.SchemaId, key);
if (_predictedDocuments.Remove(predictionKey))
var reconcilesPrediction = _predictedDocuments.ContainsKey(predictionKey);
if (reconcilesPrediction)
{
kind = CultNetDatabaseChangeKind.Reconciled;
}
AppendMutationLogEntry(
shard,
kind == CultNetDatabaseChangeKind.Reconciled ? CultNetDatabaseChangeKind.Updated : kind,
key,
descriptor.SchemaId,
document,
previous,
new CultNetShardLogEntryMessage
{
ChangeKind = previous == null ? "added" : "updated",
Put = message
});
PublishUntyped(
descriptor.DocumentType,
kind,
key,
descriptor.SchemaId,
shard,
document,
previous);
void PublishCommittedPut()
{
if (reconcilesPrediction)
_predictedDocuments.Remove(predictionKey);
AppendMutationLogEntry(
shard,
kind == CultNetDatabaseChangeKind.Reconciled ? CultNetDatabaseChangeKind.Updated : kind,
key,
descriptor.SchemaId,
document,
previous,
new CultNetShardLogEntryMessage
{
ChangeKind = previous == null ? "added" : "updated",
Put = message
});
PublishUntyped(
descriptor.DocumentType,
kind,
key,
descriptor.SchemaId,
shard,
document,
previous);
}
if (_ambientTransaction.Value is { } transaction)
transaction.AfterCommit.Add(PublishCommittedPut);
else
PublishCommittedPut();
return document;
}
@ -954,6 +1033,7 @@ namespace GameCult.Networking
public Task ApplyDeleteAsync(CultNetDocumentDeleteMessage message)
{
ThrowIfDisposed();
EnsureAuthoritativeTransaction();
if (message == null) throw new ArgumentNullException(nameof(message));
var key = new CultRecordKey(message.RecordKey);
@ -967,26 +1047,33 @@ namespace GameCult.Networking
}
_cache.Remove(key);
AppendMutationLogEntry(
shard,
CultNetDatabaseChangeKind.Removed,
key,
descriptor.SchemaId,
document: null,
previousDocument: previous,
wireEntry: new CultNetShardLogEntryMessage
{
ChangeKind = "removed",
Delete = message
});
PublishUntyped(
descriptor.DocumentType,
CultNetDatabaseChangeKind.Removed,
key,
descriptor.SchemaId,
shard,
document: null,
previousDocument: previous);
void PublishCommittedDelete()
{
AppendMutationLogEntry(
shard,
CultNetDatabaseChangeKind.Removed,
key,
descriptor.SchemaId,
document: null,
previousDocument: previous,
wireEntry: new CultNetShardLogEntryMessage
{
ChangeKind = "removed",
Delete = message
});
PublishUntyped(
descriptor.DocumentType,
CultNetDatabaseChangeKind.Removed,
key,
descriptor.SchemaId,
shard,
document: null,
previousDocument: previous);
}
if (_ambientTransaction.Value is { } transaction)
transaction.AfterCommit.Add(PublishCommittedDelete);
else
PublishCommittedDelete();
return Task.CompletedTask;
}
@ -1699,6 +1786,20 @@ namespace GameCult.Networking
};
}
private sealed class CultNetDatabaseTransaction
{
public List<Action> AfterCommit { get; } = new();
}
private void EnsureAuthoritativeTransaction()
{
if (_requireTransactionsForAuthoritativeWrites && _ambientTransaction.Value == null)
{
throw new InvalidOperationException(
"This CultNet database requires authoritative writes to use ExecuteTransactionAsync.");
}
}
private void ThrowIfDisposed()
{
if (_disposed)

View file

@ -13,6 +13,8 @@ namespace GameCult.Networking
{
/// <summary>
/// Publishes live database changes through any schema-v0 server transport.
/// Optional record projection runs after authorization and owns both initial
/// snapshot and live-update delivery for a peer.
/// </summary>
public sealed class CultNetDatabaseSubscriptionServer : IDisposable
{
@ -20,18 +22,32 @@ namespace GameCult.Networking
private readonly CultNetDatabase _database;
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, Task> _subscribe;
private readonly Func<CultNetDatabaseUnsubscribeMessage, ICultNetSchemaServerPeer, Task> _unsubscribe;
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, bool>? _authorizeRequest;
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, string, string, bool>? _authorizeRecord;
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, CultNetRawDocumentRecord, CultNetRawDocumentRecord?>? _projectRecord;
private readonly ICultNetSchemaServerPeerLifecycle? _peerLifecycle;
private readonly ConcurrentDictionary<SubscriptionKey, IDisposable> _subscriptions =
new ConcurrentDictionary<SubscriptionKey, IDisposable>(SubscriptionKeyComparer.Instance);
private readonly ConcurrentDictionary<SubscriptionKey, CultNetDatabaseSubscribeMessage> _requests =
new ConcurrentDictionary<SubscriptionKey, CultNetDatabaseSubscribeMessage>(SubscriptionKeyComparer.Instance);
private readonly ConcurrentDictionary<SubscriptionKey, SubscriptionProjectionState> _projections =
new ConcurrentDictionary<SubscriptionKey, SubscriptionProjectionState>(SubscriptionKeyComparer.Instance);
private readonly object _lifecycleGate = new();
private bool _disposed;
/// <summary>Attaches live database subscription handlers to a schema server.</summary>
public CultNetDatabaseSubscriptionServer(ICultNetSchemaServer server, CultNetDatabase database)
public CultNetDatabaseSubscriptionServer(
ICultNetSchemaServer server,
CultNetDatabase database,
Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, bool>? authorizeRequest = null,
Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, string, string, bool>? authorizeRecord = null,
Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, CultNetRawDocumentRecord, CultNetRawDocumentRecord?>? projectRecord = null)
{
_server = server ?? throw new ArgumentNullException(nameof(server));
_database = database ?? throw new ArgumentNullException(nameof(database));
_authorizeRequest = authorizeRequest;
_authorizeRecord = authorizeRecord;
_projectRecord = projectRecord;
_subscribe = HandleSubscribeAsync;
_unsubscribe = HandleUnsubscribeAsync;
_server.OnCultNet(_subscribe);
@ -48,34 +64,48 @@ namespace GameCult.Networking
/// </summary>
public event Action<CultNetDatabaseSubscriptionDemand>? DemandChanged;
/// <summary>
/// Re-evaluates every live peer projection against current authorization and source state.
/// Records that lost visibility are explicitly removed and body demand is withdrawn while
/// the request is unauthorized. The subscription intent remains available for a later
/// authorized generation on the same established peer.
/// </summary>
public void Reconcile()
{
lock (_lifecycleGate)
{
if (_disposed) return;
foreach (var entry in _requests.ToArray())
Reconcile(entry.Key, entry.Value);
}
}
/// <summary>Detaches handlers and releases all active watches.</summary>
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_server.RemoveCultNetMessageListener<CultNetDatabaseSubscribeMessage>(_subscribe);
_server.RemoveCultNetMessageListener<CultNetDatabaseUnsubscribeMessage>(_unsubscribe);
if (_peerLifecycle != null)
_peerLifecycle.PeerDisconnected -= HandlePeerDisconnected;
foreach (var entry in _subscriptions)
lock (_lifecycleGate)
{
entry.Value.Dispose();
if (_requests.TryRemove(entry.Key, out var request))
PublishDemand(request, entry.Key, active: false);
if (_disposed) return;
_disposed = true;
_server.RemoveCultNetMessageListener<CultNetDatabaseSubscribeMessage>(_subscribe);
_server.RemoveCultNetMessageListener<CultNetDatabaseUnsubscribeMessage>(_unsubscribe);
if (_peerLifecycle != null)
_peerLifecycle.PeerDisconnected -= HandlePeerDisconnected;
foreach (var entry in _subscriptions.ToArray())
Withdraw(entry.Key, sendRemovals: false, forgetRequest: true);
_subscriptions.Clear();
_requests.Clear();
_projections.Clear();
}
_subscriptions.Clear();
_requests.Clear();
}
private void HandlePeerDisconnected(ICultNetSchemaServerPeer peer)
{
foreach (var key in _subscriptions.Keys.Where(candidate =>
SubscriptionKeyComparer.SamePeer(candidate.Peer, peer)).ToArray())
lock (_lifecycleGate)
{
if (_subscriptions.TryRemove(key, out var subscription))
subscription.Dispose();
if (_requests.TryRemove(key, out var request))
PublishDemand(request, key, active: false);
foreach (var key in _subscriptions.Keys.Where(candidate =>
SubscriptionKeyComparer.SamePeer(candidate.Peer, peer)).ToArray())
Withdraw(key, sendRemovals: false, forgetRequest: true);
}
}
@ -89,39 +119,49 @@ namespace GameCult.Networking
peer.SendCultNet(new CultNetErrorMessage { Error = "Database subscription requires a subscriptionId or messageId." });
return Task.CompletedTask;
}
var key = new SubscriptionKey(peer, subscriptionId);
if (_requests.TryGetValue(key, out var previous))
PublishDemand(previous, key, active: false);
_subscriptions.AddOrUpdate(
key,
_ => Watch(request, subscriptionId, peer),
(_, current) =>
{
current.Dispose();
return Watch(request, subscriptionId, peer);
});
_requests[key] = request;
PublishDemand(request, key, active: true);
if (request.IncludeSnapshot)
if (_authorizeRequest?.Invoke(request, peer) == false)
{
peer.SendCultNet(_database.Documents.CreateRawSnapshotResponse(
_database.Cache,
request.MessageId,
new CultNetSnapshotRequestMessage
{
MessageId = request.MessageId,
SchemaIds = request.SchemaIds,
RecordKeys = request.RecordKeys
}));
peer.SendCultNet(new CultNetErrorMessage { Error = "Database subscription is not authorized for this peer." });
return Task.CompletedTask;
}
else
lock (_lifecycleGate)
{
peer.SendCultNet(new CultNetSnapshotResponseRawMessage
var key = new SubscriptionKey(peer, subscriptionId);
Withdraw(key, sendRemovals: true, forgetRequest: true);
var projection = new SubscriptionProjectionState();
_projections[key] = projection;
_requests[key] = request;
try
{
MessageId = request.MessageId,
Documents = Array.Empty<CultNetRawDocumentRecord>()
});
_subscriptions[key] = Watch(request, subscriptionId, peer, key);
if (request.IncludeSnapshot)
{
var snapshot = CreateProjectedSnapshot(request, peer);
foreach (var entry in snapshot.BySourceRecordKey)
projection.DeliveredBySourceRecordKey[entry.Key] = entry.Value;
peer.SendCultNet(new CultNetSnapshotResponseRawMessage
{
MessageId = request.MessageId,
Documents = snapshot.Documents
});
}
else
{
peer.SendCultNet(new CultNetSnapshotResponseRawMessage
{
MessageId = request.MessageId,
Documents = Array.Empty<CultNetRawDocumentRecord>()
});
}
PublishDemand(request, key, active: true);
projection.DemandActive = true;
}
catch
{
Withdraw(key, sendRemovals: false, forgetRequest: true);
throw;
}
}
return Task.CompletedTask;
}
@ -134,9 +174,8 @@ namespace GameCult.Networking
if (!string.IsNullOrWhiteSpace(subscriptionId))
{
var key = new SubscriptionKey(peer, subscriptionId);
if (_subscriptions.TryRemove(key, out var subscription)) subscription.Dispose();
if (_requests.TryRemove(key, out var subscribed))
PublishDemand(subscribed, key, active: false);
lock (_lifecycleGate)
Withdraw(key, sendRemovals: false, forgetRequest: true);
}
return Task.CompletedTask;
}
@ -179,19 +218,232 @@ namespace GameCult.Networking
private IDisposable Watch(
CultNetDatabaseSubscribeMessage request,
string subscriptionId,
ICultNetSchemaServerPeer peer)
ICultNetSchemaServerPeer peer,
SubscriptionKey key)
{
return _database.WatchAllChanges().Subscribe(change =>
{
var message = CreateChange(change, request, subscriptionId);
if (message != null) peer.SendCultNet(message);
lock (_lifecycleGate)
{
if (_disposed || !_requests.ContainsKey(key) || !_projections.TryGetValue(key, out var projection))
return;
if (_authorizeRequest?.Invoke(request, peer) == false)
{
Reconcile(key, request);
return;
}
var sourceRecordKey = ResolveChangeRecordKey(change);
var message = CreateAuthorizedChange(change, request, subscriptionId, peer);
var projected = message?.Document;
if (projected != null && _projectRecord != null)
projected = _projectRecord(request, peer, projected);
ApplyProjectedChange(
projection,
sourceRecordKey,
projected,
peer,
subscriptionId);
}
});
}
private void Reconcile(SubscriptionKey key, CultNetDatabaseSubscribeMessage request)
{
if (!_projections.TryGetValue(key, out var projection)) return;
var authorized = _authorizeRequest?.Invoke(request, key.Peer) != false;
var next = authorized
? CreateProjectedSnapshot(request, key.Peer)
: ProjectedSnapshot.Empty;
foreach (var previous in projection.DeliveredBySourceRecordKey.ToArray())
{
if (!next.BySourceRecordKey.TryGetValue(previous.Key, out var current))
{
SendRemoval(key.Peer, key.Id, previous.Value);
continue;
}
if (!string.Equals(previous.Value.RecordKey, current.RecordKey, StringComparison.Ordinal) ||
!string.Equals(previous.Value.SchemaId, current.SchemaId, StringComparison.Ordinal))
{
SendRemoval(key.Peer, key.Id, previous.Value);
SendUpsert(key.Peer, key.Id, current, added: true);
}
else if (!Equivalent(previous.Value, current))
{
SendUpsert(key.Peer, key.Id, current, added: false);
}
}
foreach (var current in next.BySourceRecordKey)
{
if (!projection.DeliveredBySourceRecordKey.ContainsKey(current.Key))
SendUpsert(key.Peer, key.Id, current.Value, added: true);
}
projection.DeliveredBySourceRecordKey.Clear();
foreach (var current in next.BySourceRecordKey)
projection.DeliveredBySourceRecordKey[current.Key] = current.Value;
if (projection.DemandActive != authorized)
{
projection.DemandActive = authorized;
PublishDemand(request, key, authorized);
}
}
private ProjectedSnapshot CreateProjectedSnapshot(
CultNetDatabaseSubscribeMessage request,
ICultNetSchemaServerPeer peer)
{
var snapshot = _database.Documents.CreateRawSnapshotResponse(
_database.Cache,
request.MessageId,
new CultNetSnapshotRequestMessage
{
MessageId = request.MessageId,
SchemaIds = request.SchemaIds,
RecordKeys = request.RecordKeys
});
var bySourceRecordKey = new Dictionary<string, CultNetRawDocumentRecord>(StringComparer.Ordinal);
var projectedRecordKeys = new HashSet<string>(StringComparer.Ordinal);
foreach (var source in snapshot.Documents)
{
var sourceRecordKey = source.RecordKey;
if (_authorizeRecord?.Invoke(request, peer, sourceRecordKey, source.SchemaId) == false)
continue;
var projected = _projectRecord == null ? source : _projectRecord(request, peer, source);
if (projected == null) continue;
if (!projectedRecordKeys.Add(projected.RecordKey))
throw new InvalidOperationException(
$"Database subscription projection produced duplicate record key '{projected.RecordKey}'.");
bySourceRecordKey[sourceRecordKey] = projected;
}
return new ProjectedSnapshot(bySourceRecordKey);
}
private void ApplyProjectedChange(
SubscriptionProjectionState projection,
string sourceRecordKey,
CultNetRawDocumentRecord? current,
ICultNetSchemaServerPeer peer,
string subscriptionId)
{
projection.DeliveredBySourceRecordKey.TryGetValue(sourceRecordKey, out var previous);
if (current == null)
{
if (previous != null)
{
projection.DeliveredBySourceRecordKey.Remove(sourceRecordKey);
SendRemoval(peer, subscriptionId, previous);
}
return;
}
if (previous == null)
{
projection.DeliveredBySourceRecordKey[sourceRecordKey] = current;
SendUpsert(peer, subscriptionId, current, added: true);
return;
}
if (!string.Equals(previous.RecordKey, current.RecordKey, StringComparison.Ordinal) ||
!string.Equals(previous.SchemaId, current.SchemaId, StringComparison.Ordinal))
{
SendRemoval(peer, subscriptionId, previous);
projection.DeliveredBySourceRecordKey[sourceRecordKey] = current;
SendUpsert(peer, subscriptionId, current, added: true);
return;
}
if (!Equivalent(previous, current))
{
projection.DeliveredBySourceRecordKey[sourceRecordKey] = current;
SendUpsert(peer, subscriptionId, current, added: false);
}
}
private static string ResolveChangeRecordKey(object change)
{
var value = change.GetType().GetProperty("Key")?.GetValue(change);
return value is CultRecordKey key ? key.Value : string.Empty;
}
private static bool Equivalent(CultNetRawDocumentRecord left, CultNetRawDocumentRecord right) =>
string.Equals(left.SchemaId, right.SchemaId, StringComparison.Ordinal) &&
string.Equals(left.SchemaName, right.SchemaName, StringComparison.Ordinal) &&
string.Equals(left.SchemaVersion, right.SchemaVersion, StringComparison.Ordinal) &&
string.Equals(left.SchemaContentHash, right.SchemaContentHash, StringComparison.Ordinal) &&
string.Equals(left.RecordKey, right.RecordKey, StringComparison.Ordinal) &&
string.Equals(left.PayloadEncoding, right.PayloadEncoding, StringComparison.Ordinal) &&
left.Payload.SequenceEqual(right.Payload) &&
string.Equals(left.SourceRuntimeId, right.SourceRuntimeId, StringComparison.Ordinal) &&
string.Equals(left.SourceAgentId, right.SourceAgentId, StringComparison.Ordinal) &&
string.Equals(left.SourceRole, right.SourceRole, StringComparison.Ordinal);
private static void SendUpsert(
ICultNetSchemaServerPeer peer,
string subscriptionId,
CultNetRawDocumentRecord document,
bool added) =>
peer.SendCultNet(new CultNetDatabaseChangeRawMessage
{
MessageId = Guid.NewGuid().ToString("N"),
SubscriptionId = subscriptionId,
ChangeKind = added ? "added" : "updated",
Document = document
});
private static void SendRemoval(
ICultNetSchemaServerPeer peer,
string subscriptionId,
CultNetRawDocumentRecord document) =>
peer.SendCultNet(new CultNetDatabaseChangeRawMessage
{
MessageId = Guid.NewGuid().ToString("N"),
SubscriptionId = subscriptionId,
ChangeKind = "removed",
RecordKey = document.RecordKey,
SchemaId = document.SchemaId
});
private void Withdraw(SubscriptionKey key, bool sendRemovals, bool forgetRequest)
{
if (_subscriptions.TryRemove(key, out var subscription))
subscription.Dispose();
if (_projections.TryRemove(key, out var projection))
{
if (sendRemovals)
{
foreach (var delivered in projection.DeliveredBySourceRecordKey.Values)
SendRemoval(key.Peer, key.Id, delivered);
}
if (projection.DemandActive && _requests.TryGetValue(key, out var activeRequest))
PublishDemand(activeRequest, key, active: false);
}
if (forgetRequest)
_requests.TryRemove(key, out _);
}
private CultNetDatabaseChangeRawMessage? CreateAuthorizedChange(
object change,
CultNetDatabaseSubscribeMessage request,
string subscriptionId,
ICultNetSchemaServerPeer peer)
{
return CreateChangeCore(change, request, subscriptionId, (recordKey, schemaId) =>
_authorizeRecord?.Invoke(request, peer, recordKey, schemaId) != false);
}
private CultNetDatabaseChangeRawMessage? CreateChange(
object change,
CultNetDatabaseSubscribeMessage request,
string subscriptionId)
{
return CreateChangeCore(change, request, subscriptionId, (_, _) => true);
}
private CultNetDatabaseChangeRawMessage? CreateChangeCore(
object change,
CultNetDatabaseSubscribeMessage request,
string subscriptionId,
Func<string, string, bool> authorizeRecord)
{
var changeType = change.GetType();
var key = (CultRecordKey)(changeType.GetProperty("Key")?.GetValue(change) ?? new CultRecordKey(""));
@ -206,6 +458,8 @@ namespace GameCult.Networking
var schemaId = ResolveWireSchemaId(previous, (string?)changeType.GetProperty("SchemaId")?.GetValue(change) ?? "");
if (!MatchesRequestedSchema(request.SchemaIds, previous, schemaId))
return null;
if (!authorizeRecord(key.Value, schemaId))
return null;
return new CultNetDatabaseChangeRawMessage
{
MessageId = Guid.NewGuid().ToString("N"),
@ -219,6 +473,8 @@ namespace GameCult.Networking
var raw = CreateRawRecord(key, document);
if (!MatchesRequestedSchema(request.SchemaIds, document, raw.SchemaId))
return null;
if (!authorizeRecord(key.Value, raw.SchemaId))
return null;
return new CultNetDatabaseChangeRawMessage
{
MessageId = Guid.NewGuid().ToString("N"),
@ -258,6 +514,27 @@ namespace GameCult.Networking
return ((CultNetDocumentPutRawMessage)put!).Document;
}
private sealed class SubscriptionProjectionState
{
public Dictionary<string, CultNetRawDocumentRecord> DeliveredBySourceRecordKey { get; } =
new(StringComparer.Ordinal);
public bool DemandActive { get; set; }
}
private sealed class ProjectedSnapshot
{
public ProjectedSnapshot(Dictionary<string, CultNetRawDocumentRecord> bySourceRecordKey)
{
BySourceRecordKey = bySourceRecordKey;
Documents = bySourceRecordKey.Values.ToArray();
}
public static ProjectedSnapshot Empty { get; } =
new(new Dictionary<string, CultNetRawDocumentRecord>(StringComparer.Ordinal));
public Dictionary<string, CultNetRawDocumentRecord> BySourceRecordKey { get; }
public CultNetRawDocumentRecord[] Documents { get; }
}
private sealed class SubscriptionKey
{
public SubscriptionKey(ICultNetSchemaServerPeer peer, string id)

View file

@ -164,6 +164,16 @@ namespace GameCult.Networking
if (_disposed) return;
if (request == null) throw new ArgumentNullException(nameof(request));
if (peer == null) throw new ArgumentNullException(nameof(peer));
if (_sourceRuntimeId != null &&
!string.Equals(request.TargetRuntimeId, _sourceRuntimeId, StringComparison.Ordinal))
{
peer.SendCultNet(Failure(
request,
"denied",
"target-runtime-mismatch",
$"Operation targeted runtime '{request.TargetRuntimeId ?? "(missing)"}', not '{_sourceRuntimeId}'."));
return;
}
Route route;
try

View file

@ -72,6 +72,8 @@ namespace GameCult.Networking
CultNetSchemaVersions.SimulationConsensusCandidate => Deserialize<CultNetSimulationConsensusCandidateMessage>(payload),
CultNetSchemaVersions.VerseCatalogRequest => Deserialize<CultMeshVerseCatalogRequestMessage>(payload),
CultNetSchemaVersions.VerseCatalogResponse => Deserialize<CultMeshVerseCatalogResponseMessage>(payload),
CultNetSchemaVersions.SessionOpen => Deserialize<CultMeshSessionOpenMessage>(payload),
CultNetSchemaVersions.SessionAccepted => Deserialize<CultMeshSessionAcceptedMessage>(payload),
CultNetSchemaVersions.PeerExchangeRequest => Deserialize<CultMeshPeerExchangeRequestMessage>(payload),
CultNetSchemaVersions.PeerExchangeResponse => Deserialize<CultMeshPeerExchangeResponseMessage>(payload),
CultNetSchemaVersions.ContentChunkRequest => Deserialize<CultMeshContentChunkRequestMessage>(payload),

View file

@ -135,6 +135,10 @@ namespace GameCult.Networking
/// CultMesh Verse catalog response contract identifier.
/// </summary>
public const string VerseCatalogResponse = "cultmesh.verse_catalog_response.v0";
/// <summary>CultMesh session identity request contract identifier.</summary>
public const string SessionOpen = "cultmesh.session_open.v2";
/// <summary>CultMesh verified session identity response contract identifier.</summary>
public const string SessionAccepted = "cultmesh.session_accepted.v2";
/// <summary>
/// CultMesh peer exchange request contract identifier.
/// </summary>
@ -1179,6 +1183,37 @@ namespace GameCult.Networking
}
}
/// <summary>Requests an identity-bound CultMesh session before application traffic begins.</summary>
[MessagePackObject]
public class CultMeshSessionOpenMessage : ICultNetSchemaMessage
{
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SessionOpen;
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
[Key("sourceRuntimeId")] public string SourceRuntimeId { get; set; } = string.Empty;
[Key("verseId")] public string VerseId { get; set; } = string.Empty;
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
[Key("protocolId")] public string ProtocolId { get; set; } = string.Empty;
[Key("routeGeneration")] public string RouteGeneration { get; set; } = string.Empty;
[Key("clientNonce")] public string ClientNonce { get; set; } = string.Empty;
}
/// <summary>Accepts or rejects a CultMesh session with the server's actual identity.</summary>
[MessagePackObject]
public class CultMeshSessionAcceptedMessage : ICultNetSchemaMessage
{
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SessionAccepted;
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
[Key("accepted")] public bool Accepted { get; set; }
[Key("verseId")] public string VerseId { get; set; } = string.Empty;
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
[Key("protocolId")] public string ProtocolId { get; set; } = string.Empty;
[Key("routeGeneration")] public string RouteGeneration { get; set; } = string.Empty;
[Key("clientNonce")] public string ClientNonce { get; set; } = string.Empty;
[Key("providerKeyId")] public string ProviderKeyId { get; set; } = string.Empty;
[Key("providerSignature")] public string ProviderSignature { get; set; } = string.Empty;
[Key("error")] public string? Error { get; set; }
}
/// <summary>
/// Requests known CultMesh Verses from a peer.
/// </summary>
@ -1254,6 +1289,11 @@ namespace GameCult.Networking
/// </summary>
[Key("authorityRuntimeIds")] public string[] AuthorityRuntimeIds { get; set; } = Array.Empty<string>();
/// <summary>
/// Gets or sets exact authoritative-runtime route bindings. This is the
/// routing authority; the parallel legacy arrays are projections only.
/// </summary>
[Key("authorityRoutes")] public CultMeshAuthorityRouteMessage[] AuthorityRoutes { get; set; } = Array.Empty<CultMeshAuthorityRouteMessage>();
/// <summary>
/// Gets or sets the parent Verse id for overlays or branches.
/// </summary>
[Key("parentVerseId")] public string? ParentVerseId { get; set; }
@ -1263,6 +1303,30 @@ namespace GameCult.Networking
[Key("description")] public string? Description { get; set; }
}
/// <summary>Wire representation of one authority-bound CultMesh route.</summary>
[MessagePackObject]
public class CultMeshAuthorityRouteMessage
{
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
[Key("endpoint")] public string Endpoint { get; set; } = string.Empty;
[Key("protocolIds")] public string[] ProtocolIds { get; set; } = Array.Empty<string>();
[Key("priority")] public int Priority { get; set; }
[Key("generation")] public string Generation { get; set; } = string.Empty;
[Key("certificate")] public CultMeshRouteCertificateMessage? Certificate { get; set; }
}
[MessagePackObject]
public class CultMeshRouteCertificateMessage
{
[Key("providerKeyId")] public string ProviderKeyId { get; set; } = string.Empty;
[Key("providerPublicKeyX")] public string ProviderPublicKeyX { get; set; } = string.Empty;
[Key("providerPublicKeyY")] public string ProviderPublicKeyY { get; set; } = string.Empty;
[Key("odinKeyId")] public string OdinKeyId { get; set; } = string.Empty;
[Key("issuedAtUnixMilliseconds")] public long IssuedAtUnixMilliseconds { get; set; }
[Key("expiresAtUnixMilliseconds")] public long ExpiresAtUnixMilliseconds { get; set; }
[Key("signature")] public string Signature { get; set; } = string.Empty;
}
/// <summary>
/// Wire representation of CultMesh Verse compatibility.
/// </summary>