Add typed CultMesh body publications

This commit is contained in:
Meta Vens 2026-07-13 17:48:42 +01:00
commit 5e867bd92c
3 changed files with 357 additions and 1 deletions

View file

@ -148,6 +148,7 @@ namespace GameCult.Mesh
{
private readonly IReadOnlyDictionary<CultMeshBodyTransportKind, ICultMeshBodyTransportAdapter> _adapters;
private readonly Func<CultMeshBodyDescriptor, bool> _authorizeProducer;
private readonly Func<string, CultMeshBodyDescriptor, bool>? _authorizeNamedProducer;
public CultMeshBodyTransportService(
IEnumerable<ICultMeshBodyTransportAdapter> adapters,
@ -158,6 +159,16 @@ namespace GameCult.Mesh
_authorizeProducer = authorizeProducer ?? throw new ArgumentNullException(nameof(authorizeProducer));
}
public CultMeshBodyTransportService(
IEnumerable<ICultMeshBodyTransportAdapter> adapters,
Func<string, CultMeshBodyDescriptor, bool> authorizeProducer)
{
_adapters = (adapters ?? throw new ArgumentNullException(nameof(adapters)))
.ToDictionary(adapter => adapter.TransportKind);
_authorizeProducer = _ => true;
_authorizeNamedProducer = authorizeProducer ?? throw new ArgumentNullException(nameof(authorizeProducer));
}
public ICultMeshBodyReadLease OpenReadOnly(
CultMeshBodyDescriptor preferred,
CultMeshBodyDescriptor networkFallback,
@ -173,6 +184,15 @@ namespace GameCult.Mesh
CultMeshBodyDescriptor preferred,
CultMeshBodyDescriptor networkFallback,
CultMeshBodyValidationRequest request)
{
return NegotiateReadOnly(null, preferred, networkFallback, request);
}
internal CultMeshBodyNegotiationResult NegotiateReadOnly(
string? producerId,
CultMeshBodyDescriptor preferred,
CultMeshBodyDescriptor networkFallback,
CultMeshBodyValidationRequest request)
{
if (preferred == null) throw new ArgumentNullException(nameof(preferred));
if (networkFallback == null) throw new ArgumentNullException(nameof(networkFallback));
@ -180,7 +200,10 @@ namespace GameCult.Mesh
throw new InvalidOperationException("CultMesh local and network representations describe different logical body generations.");
CultMeshBodyDescriptorValidator.Validate(preferred, request);
CultMeshBodyDescriptorValidator.Validate(networkFallback, request);
if (!_authorizeProducer(preferred))
var authorized = _authorizeNamedProducer == null
? _authorizeProducer(preferred)
: !string.IsNullOrWhiteSpace(producerId) && _authorizeNamedProducer(producerId!, preferred);
if (!authorized)
throw new UnauthorizedAccessException("CultMesh body producer is not authorized for this logical body.");
Exception? preferredFailure = null;

View file

@ -0,0 +1,140 @@
using System;
using GameCult.Caching;
using GameCult.Networking;
using MessagePack;
namespace GameCult.Mesh
{
public static class CultMeshBodyPublicationSchemaVersions
{
public const string Publication = "gamecult.mesh.body_publication.v1";
}
[MessagePackObject]
[CultDocument("gamecult.mesh.body_publication", CultMeshBodyPublicationSchemaVersions.Publication)]
public sealed class CultMeshBodyPublicationDocument
{
[Key(0), CultName] public string BodyId { get; set; } = string.Empty;
[Key(1), CultIndex] public string ProducerId { get; set; } = string.Empty;
[Key(2)] public string SchemaId { get; set; } = string.Empty;
[Key(3)] public int LayoutVersion { get; set; }
[Key(4)] public long ByteSize { get; set; }
[Key(5)] public int Capacity { get; set; }
[Key(6)] public long ProducerEpoch { get; set; }
[Key(7)] public long Sequence { get; set; }
[Key(8)] public CultMeshBodySynchronization Synchronization { get; set; }
[Key(9)] public long LivenessExpiresAtUnixMs { get; set; }
[Key(10)] public CultMeshBodyDescriptor PreferredLocal { get; set; } = new();
[Key(11)] public CultMeshBodyDescriptor NetworkFallback { get; set; } = new();
public static CultRecordKey CreateRecordKey(string bodyId)
{
if (string.IsNullOrWhiteSpace(bodyId))
throw new ArgumentException("Logical body identity is required.", nameof(bodyId));
return new CultRecordKey("mesh:body:" + bodyId);
}
[IgnoreMember]
public CultRecordKey RecordKey => CreateRecordKey(BodyId);
}
public sealed class CultMeshBodyPublicationHandle
{
public CultMeshBodyPublicationHandle(string bodyId)
{
BodyId = string.IsNullOrWhiteSpace(bodyId)
? throw new ArgumentException("Logical body identity is required.", nameof(bodyId))
: bodyId;
RecordKey = CultMeshBodyPublicationDocument.CreateRecordKey(bodyId);
}
public string BodyId { get; }
public CultRecordKey RecordKey { get; }
public void Validate(CultMeshBodyPublicationDocument publication) =>
CultMeshBodyPublicationValidator.Validate(publication, BodyId);
}
public static class CultMeshBodyPublicationValidator
{
public static void Validate(CultMeshBodyPublicationDocument publication, string? expectedBodyId = null)
{
if (publication == null) throw new ArgumentNullException(nameof(publication));
if (string.IsNullOrWhiteSpace(publication.BodyId))
throw new InvalidOperationException("CultMesh body publication has no logical body identity.");
if (expectedBodyId != null && !string.Equals(publication.BodyId, expectedBodyId, StringComparison.Ordinal))
throw new InvalidOperationException("CultMesh body publication handle identity mismatch.");
if (string.IsNullOrWhiteSpace(publication.ProducerId))
throw new InvalidOperationException("CultMesh body publication has no producer identity.");
if (string.IsNullOrWhiteSpace(publication.SchemaId))
throw new InvalidOperationException("CultMesh body publication has no schema identity.");
if (publication.LayoutVersion < 0 || publication.ByteSize < 0 || publication.Capacity < 0 ||
publication.ProducerEpoch < 0 || publication.Sequence < 0)
throw new InvalidOperationException("CultMesh body publication generation values must be non-negative.");
ValidateDescriptor(publication, publication.PreferredLocal, "preferred local");
ValidateDescriptor(publication, publication.NetworkFallback, "network fallback");
if (publication.PreferredLocal.TransportKind == CultMeshBodyTransportKind.Network)
throw new InvalidOperationException("CultMesh preferred local body descriptor must use a local transport.");
if (publication.NetworkFallback.TransportKind != CultMeshBodyTransportKind.Network)
throw new InvalidOperationException("CultMesh network fallback body descriptor must use network transport.");
}
private static void ValidateDescriptor(
CultMeshBodyPublicationDocument publication,
CultMeshBodyDescriptor descriptor,
string label)
{
if (descriptor == null)
throw new InvalidOperationException($"CultMesh body publication has no {label} descriptor.");
if (!string.Equals(descriptor.BodyId, publication.BodyId, StringComparison.Ordinal) ||
!string.Equals(descriptor.SchemaId, publication.SchemaId, StringComparison.Ordinal) ||
descriptor.LayoutVersion != publication.LayoutVersion ||
descriptor.ByteSize != publication.ByteSize ||
descriptor.Capacity != publication.Capacity ||
descriptor.ProducerEpoch != publication.ProducerEpoch ||
descriptor.Sequence != publication.Sequence ||
descriptor.Synchronization != publication.Synchronization ||
descriptor.LeaseExpiresAtUnixMs != publication.LivenessExpiresAtUnixMs)
throw new InvalidOperationException($"CultMesh {label} descriptor disagrees with its publication envelope.");
}
}
public sealed class CultMeshBodyPublicationResolver
{
private readonly CultMeshBodyTransportService _transport;
public CultMeshBodyPublicationResolver(CultMeshBodyTransportService transport) =>
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
public ICultMeshBodyReadLease ResolveReadOnly(
CultMeshBodyPublicationDocument publication,
CultMeshBodyValidationRequest request) =>
NegotiateReadOnly(publication, request).Lease;
public CultMeshBodyNegotiationResult NegotiateReadOnly(
CultMeshBodyPublicationDocument publication,
CultMeshBodyValidationRequest request)
{
CultMeshBodyPublicationValidator.Validate(publication);
if (request == null) throw new ArgumentNullException(nameof(request));
if (publication.LivenessExpiresAtUnixMs <= request.NowUtc.ToUnixTimeMilliseconds())
throw new InvalidOperationException("CultMesh body publication is no longer live.");
return _transport.NegotiateReadOnly(
publication.ProducerId,
publication.PreferredLocal,
publication.NetworkFallback,
request);
}
}
public static partial class CultMesh
{
public static CultNetDocumentRegistry CreateBodyPublicationDocumentRegistry(
CultDocumentRegistry? documents = null)
{
documents ??= CultDocumentRegistry.Shared;
return new CultNetDocumentRegistry(documents)
.Register(CultNetDocumentBinding.ForDocument<CultMeshBodyPublicationDocument>(documents));
}
}
}

View file

@ -0,0 +1,193 @@
using System;
using System.IO;
using FluentAssertions;
using GameCult.Caching;
using NUnit.Framework;
#nullable enable
namespace GameCult.Mesh.Tests;
public sealed class CultMeshBodyPublicationTests
{
private string _root = null!;
[SetUp]
public void SetUp() =>
_root = Path.Combine(Path.GetTempPath(), "cultmesh-body-publications", Guid.NewGuid().ToString("N"));
[TearDown]
public void TearDown()
{
if (Directory.Exists(_root)) Directory.Delete(_root, true);
}
[Test]
public void TypedDocument_RoundTripsAndRegistersWithLogicalBodyKey()
{
var now = DateTimeOffset.UtcNow;
var publication = Publication(new byte[] { 1, 2, 3, 4 }, now);
var path = Path.Combine(_root, "publication.cc");
var handle = new CultMeshBodyPublicationHandle(publication.BodyId);
CultMesh.WriteSingleFileDocument(path, handle.RecordKey, publication);
var restored = CultMesh.ReadSingleFileDocument<CultMeshBodyPublicationDocument>(path, handle.RecordKey);
var registry = CultMesh.CreateBodyPublicationDocumentRegistry();
handle.Validate(restored);
restored.Should().BeEquivalentTo(publication);
registry.GetByDocumentType(typeof(CultMeshBodyPublicationDocument)).Should().NotBeNull();
handle.RecordKey.Should().Be(CultMeshBodyPublicationDocument.CreateRecordKey(publication.BodyId));
}
[Test]
public void Resolver_UsesPreferredLocalRepresentation()
{
var now = DateTimeOffset.UtcNow;
var bytes = BitConverter.GetBytes(12.5f);
var publication = Publication(bytes, now);
var resolver = Resolver(bytes, (producer, _) => producer == "aetheria");
using var lease = resolver.ResolveReadOnly(publication, Request(publication, now));
lease.TransportKind.Should().Be(CultMeshBodyTransportKind.SharedFileMapping);
lease.ReadSingle(0).Should().Be(12.5f);
}
[Test]
public void Resolver_FallsBackToEquivalentNetworkRepresentation()
{
var now = DateTimeOffset.UtcNow;
var bytes = new byte[] { 4, 8, 15, 16 };
var publication = Publication(bytes, now);
new CultMeshMappedBodyPublisher(_root).Revoke(publication.PreferredLocal);
var result = Resolver(bytes, (_, _) => true).NegotiateReadOnly(publication, Request(publication, now));
using var lease = result.Lease;
result.UsedFallback.Should().BeTrue();
lease.TransportKind.Should().Be(CultMeshBodyTransportKind.Network);
}
[TestCase("body")]
[TestCase("schema")]
[TestCase("capacity")]
[TestCase("epoch")]
[TestCase("sequence")]
[TestCase("liveness")]
public void Resolver_RejectsDescriptorThatDisagreesWithEnvelope(string field)
{
var now = DateTimeOffset.UtcNow;
var publication = Publication(new byte[4], now);
var descriptor = publication.NetworkFallback;
if (field == "body") descriptor.BodyId += ":wrong";
if (field == "schema") descriptor.SchemaId += ".wrong";
if (field == "capacity") descriptor.Capacity++;
if (field == "epoch") descriptor.ProducerEpoch++;
if (field == "sequence") descriptor.Sequence++;
if (field == "liveness") descriptor.LeaseExpiresAtUnixMs++;
Action resolve = () => Resolver(new byte[4], (_, _) => true)
.ResolveReadOnly(publication, Request(publication, now));
resolve.Should().Throw<InvalidOperationException>().WithMessage("*envelope*");
}
[Test]
public void Resolver_RejectsUnauthorizedProducerBeforeOpeningTransport()
{
var now = DateTimeOffset.UtcNow;
var publication = Publication(new byte[4], now);
var fetched = false;
var resolver = Resolver(new byte[4], (producer, _) =>
{
producer.Should().Be("aetheria");
return false;
}, () => fetched = true);
Action resolve = () => resolver.ResolveReadOnly(publication, Request(publication, now));
resolve.Should().Throw<UnauthorizedAccessException>();
fetched.Should().BeFalse();
}
[Test]
public void Resolver_RejectsExpiredPublicationAndStaleRequestedGeneration()
{
var now = DateTimeOffset.UtcNow;
var publication = Publication(new byte[4], now);
var resolver = Resolver(new byte[4], (_, _) => true);
Action expired = () => resolver.ResolveReadOnly(publication, Request(publication, now.AddMinutes(2)));
expired.Should().Throw<InvalidOperationException>().WithMessage("*live*");
var stale = Request(publication, now);
stale.ProducerEpoch--;
Action wrongGeneration = () => resolver.ResolveReadOnly(publication, stale);
wrongGeneration.Should().Throw<InvalidOperationException>().WithMessage("*epoch*");
}
private CultMeshBodyPublicationDocument Publication(byte[] bytes, DateTimeOffset now)
{
var local = new CultMeshMappedBodyPublisher(_root, TimeSpan.FromMinutes(1))
.Publish("aetheria:entities", "eve.entity_soa.v1", 2, 128, 7, 42, bytes, now);
return new CultMeshBodyPublicationDocument
{
BodyId = local.BodyId,
ProducerId = "aetheria",
SchemaId = local.SchemaId,
LayoutVersion = local.LayoutVersion,
ByteSize = local.ByteSize,
Capacity = local.Capacity,
ProducerEpoch = local.ProducerEpoch,
Sequence = local.Sequence,
Synchronization = local.Synchronization,
LivenessExpiresAtUnixMs = local.LeaseExpiresAtUnixMs,
PreferredLocal = local,
NetworkFallback = Network(local)
};
}
private CultMeshBodyPublicationResolver Resolver(
byte[] bytes,
Func<string, CultMeshBodyDescriptor, bool> authorize,
Action? fetched = null) =>
new(new CultMeshBodyTransportService(
new ICultMeshBodyTransportAdapter[]
{
new CultMeshMappedBodyAdapter(_root),
new CultMeshNetworkBodyAdapter(_ => { fetched?.Invoke(); return bytes; })
},
authorize));
private static CultMeshBodyValidationRequest Request(
CultMeshBodyPublicationDocument publication,
DateTimeOffset now) => new()
{
BodyId = publication.BodyId,
SchemaId = publication.SchemaId,
LayoutVersion = publication.LayoutVersion,
ProducerEpoch = publication.ProducerEpoch,
Sequence = publication.Sequence,
Capacity = publication.Capacity,
AccessMode = CultMeshBodyAccessMode.ReadOnly,
NowUtc = now
};
private static CultMeshBodyDescriptor Network(CultMeshBodyDescriptor local) => new()
{
BodyId = local.BodyId,
SchemaId = local.SchemaId,
LayoutVersion = local.LayoutVersion,
ByteSize = local.ByteSize,
Capacity = local.Capacity,
ProducerEpoch = local.ProducerEpoch,
Sequence = local.Sequence,
AccessMode = local.AccessMode,
Synchronization = local.Synchronization,
LeaseExpiresAtUnixMs = local.LeaseExpiresAtUnixMs,
TransportKind = CultMeshBodyTransportKind.Network,
CapabilityToken = "cultnet:body:aetheria:entities:7:42",
SemanticHash = local.SemanticHash
};
}