Add negotiated CultMesh body transport

This commit is contained in:
Meta Vens 2026-07-13 01:58:54 +01:00
commit fde4d5f01c
2 changed files with 532 additions and 0 deletions

View file

@ -0,0 +1,373 @@
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Linq;
using MessagePack;
#nullable enable
namespace GameCult.Mesh
{
public enum CultMeshBodyAccessMode
{
ReadOnly = 0,
ReadWrite = 1
}
public enum CultMeshBodySynchronization
{
ImmutableSequence = 0,
EpochSequence = 1,
TripleBuffer = 2
}
public enum CultMeshBodyTransportKind
{
Network = 0,
SharedFileMapping = 1,
SharedMemory = 2
}
[MessagePackObject]
public sealed class CultMeshBodyDescriptor
{
[Key(0)] public string BodyId { get; set; } = string.Empty;
[Key(1)] public string SchemaId { get; set; } = string.Empty;
[Key(2)] public int LayoutVersion { get; set; }
[Key(3)] public long ByteSize { get; set; }
[Key(4)] public int Capacity { get; set; }
[Key(5)] public long ProducerEpoch { get; set; }
[Key(6)] public long Sequence { get; set; }
[Key(7)] public CultMeshBodyAccessMode AccessMode { get; set; } = CultMeshBodyAccessMode.ReadOnly;
[Key(8)] public CultMeshBodySynchronization Synchronization { get; set; } = CultMeshBodySynchronization.ImmutableSequence;
[Key(9)] public long LeaseExpiresAtUnixMs { get; set; }
[Key(10)] public CultMeshBodyTransportKind TransportKind { get; set; } = CultMeshBodyTransportKind.Network;
[Key(11)] public string CapabilityToken { get; set; } = string.Empty;
}
public sealed class CultMeshBodyValidationRequest
{
public string BodyId { get; set; } = string.Empty;
public string SchemaId { get; set; } = string.Empty;
public int LayoutVersion { get; set; }
public long ProducerEpoch { get; set; }
public CultMeshBodyAccessMode AccessMode { get; set; } = CultMeshBodyAccessMode.ReadOnly;
public DateTimeOffset NowUtc { get; set; } = DateTimeOffset.UtcNow;
}
public static class CultMeshBodyDescriptorValidator
{
public static void Validate(CultMeshBodyDescriptor descriptor, CultMeshBodyValidationRequest request)
{
if (descriptor == null) throw new ArgumentNullException(nameof(descriptor));
if (request == null) throw new ArgumentNullException(nameof(request));
if (string.IsNullOrWhiteSpace(descriptor.BodyId) ||
!string.Equals(descriptor.BodyId, request.BodyId, StringComparison.Ordinal))
throw new InvalidOperationException("CultMesh body identity mismatch.");
if (string.IsNullOrWhiteSpace(descriptor.SchemaId) ||
!string.Equals(descriptor.SchemaId, request.SchemaId, StringComparison.Ordinal))
throw new InvalidOperationException("CultMesh body schema mismatch.");
if (descriptor.LayoutVersion != request.LayoutVersion)
throw new InvalidOperationException("CultMesh body layout version mismatch.");
if (descriptor.ProducerEpoch != request.ProducerEpoch)
throw new InvalidOperationException("CultMesh body producer epoch mismatch.");
if (descriptor.ByteSize < 0 || descriptor.Capacity < 0 || descriptor.ByteSize > descriptor.Capacity)
throw new InvalidOperationException("CultMesh body size exceeds its declared capacity.");
if (descriptor.Sequence < 0)
throw new InvalidOperationException("CultMesh body sequence must be non-negative.");
if (descriptor.LeaseExpiresAtUnixMs <= request.NowUtc.ToUnixTimeMilliseconds())
throw new InvalidOperationException("CultMesh body lease has expired.");
if (request.AccessMode != CultMeshBodyAccessMode.ReadOnly ||
descriptor.AccessMode != CultMeshBodyAccessMode.ReadOnly)
throw new UnauthorizedAccessException("CultMesh body consumers are read-only by default.");
if (descriptor.TransportKind != CultMeshBodyTransportKind.Network &&
string.IsNullOrWhiteSpace(descriptor.CapabilityToken))
throw new InvalidOperationException("Local CultMesh body descriptor has no capability token.");
}
}
public interface ICultMeshBodyReadLease : IDisposable
{
CultMeshBodyDescriptor Descriptor { get; }
CultMeshBodyTransportKind TransportKind { get; }
byte ReadByte(long offset);
int ReadInt32(long offset);
long ReadInt64(long offset);
float ReadSingle(long offset);
double ReadDouble(long offset);
int CopyTo(long offset, byte[] destination, int destinationOffset, int count);
}
public interface ICultMeshBodyTransportAdapter
{
CultMeshBodyTransportKind TransportKind { get; }
bool CanOpen(CultMeshBodyDescriptor descriptor);
ICultMeshBodyReadLease OpenReadOnly(
CultMeshBodyDescriptor descriptor,
CultMeshBodyValidationRequest request);
}
public sealed class CultMeshBodyTransportService
{
private readonly IReadOnlyDictionary<CultMeshBodyTransportKind, ICultMeshBodyTransportAdapter> _adapters;
private readonly Func<CultMeshBodyDescriptor, bool> _authorizeProducer;
public CultMeshBodyTransportService(
IEnumerable<ICultMeshBodyTransportAdapter> adapters,
Func<CultMeshBodyDescriptor, bool> authorizeProducer)
{
_adapters = (adapters ?? throw new ArgumentNullException(nameof(adapters)))
.ToDictionary(adapter => adapter.TransportKind);
_authorizeProducer = authorizeProducer ?? throw new ArgumentNullException(nameof(authorizeProducer));
}
public ICultMeshBodyReadLease OpenReadOnly(
CultMeshBodyDescriptor preferred,
CultMeshBodyDescriptor networkFallback,
CultMeshBodyValidationRequest request,
out Exception? localFailure)
{
if (preferred == null) throw new ArgumentNullException(nameof(preferred));
if (networkFallback == null) throw new ArgumentNullException(nameof(networkFallback));
if (!SameLogicalGeneration(preferred, networkFallback))
throw new InvalidOperationException("CultMesh local and network representations describe different logical body generations.");
if (!_authorizeProducer(preferred))
throw new UnauthorizedAccessException("CultMesh body producer is not authorized for this logical body.");
localFailure = null;
try
{
if (_adapters.TryGetValue(preferred.TransportKind, out var local) && local.CanOpen(preferred))
return local.OpenReadOnly(preferred, request);
}
catch (Exception error) when (!(error is UnauthorizedAccessException))
{
localFailure = error;
}
if (!_adapters.TryGetValue(CultMeshBodyTransportKind.Network, out var network) || !network.CanOpen(networkFallback))
throw new NotSupportedException("No CultMesh network body fallback is available.");
return network.OpenReadOnly(networkFallback, request);
}
private static bool SameLogicalGeneration(CultMeshBodyDescriptor left, CultMeshBodyDescriptor right) =>
string.Equals(left.BodyId, right.BodyId, StringComparison.Ordinal) &&
string.Equals(left.SchemaId, right.SchemaId, StringComparison.Ordinal) &&
left.LayoutVersion == right.LayoutVersion &&
left.ProducerEpoch == right.ProducerEpoch &&
left.Sequence == right.Sequence &&
left.ByteSize == right.ByteSize &&
left.Capacity == right.Capacity;
}
public sealed class CultMeshMappedBodyPublisher
{
private readonly string _rootPath;
private readonly TimeSpan _leaseDuration;
public CultMeshMappedBodyPublisher(string rootPath, TimeSpan? leaseDuration = null)
{
_rootPath = string.IsNullOrWhiteSpace(rootPath)
? throw new ArgumentException("Mapped body root is required.", nameof(rootPath))
: Path.GetFullPath(rootPath);
_leaseDuration = leaseDuration ?? TimeSpan.FromSeconds(5);
if (_leaseDuration <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(leaseDuration));
Directory.CreateDirectory(_rootPath);
}
public CultMeshBodyDescriptor Publish(
string bodyId,
string schemaId,
int layoutVersion,
int logicalCapacity,
long producerEpoch,
long sequence,
ReadOnlySpan<byte> body,
DateTimeOffset nowUtc)
{
if (string.IsNullOrWhiteSpace(bodyId)) throw new ArgumentException("Body identity is required.", nameof(bodyId));
if (string.IsNullOrWhiteSpace(schemaId)) throw new ArgumentException("Schema identity is required.", nameof(schemaId));
if (layoutVersion < 0) throw new ArgumentOutOfRangeException(nameof(layoutVersion));
if (logicalCapacity < 0) throw new ArgumentOutOfRangeException(nameof(logicalCapacity));
if (producerEpoch < 0) throw new ArgumentOutOfRangeException(nameof(producerEpoch));
if (sequence < 0) throw new ArgumentOutOfRangeException(nameof(sequence));
var token = CreateCapabilityToken();
var finalPath = ResolveTokenPath(token);
var temporaryPath = finalPath + ".tmp";
using (var stream = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
stream.Write(body);
File.Move(temporaryPath, finalPath);
return new CultMeshBodyDescriptor
{
BodyId = bodyId,
SchemaId = schemaId,
LayoutVersion = layoutVersion,
ByteSize = body.Length,
Capacity = logicalCapacity,
ProducerEpoch = producerEpoch,
Sequence = sequence,
AccessMode = CultMeshBodyAccessMode.ReadOnly,
Synchronization = CultMeshBodySynchronization.ImmutableSequence,
LeaseExpiresAtUnixMs = nowUtc.Add(_leaseDuration).ToUnixTimeMilliseconds(),
TransportKind = CultMeshBodyTransportKind.SharedFileMapping,
CapabilityToken = token
};
}
public void Revoke(CultMeshBodyDescriptor descriptor)
{
if (descriptor == null || string.IsNullOrWhiteSpace(descriptor.CapabilityToken)) return;
var path = ResolveTokenPath(descriptor.CapabilityToken);
if (File.Exists(path)) File.Delete(path);
}
private string ResolveTokenPath(string token)
{
if (token.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || token.Contains(".."))
throw new InvalidOperationException("Invalid CultMesh body capability token.");
var path = Path.GetFullPath(Path.Combine(_rootPath, token + ".body"));
if (!path.StartsWith(_rootPath + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("CultMesh body token escaped the broker root.");
return path;
}
private static string CreateCapabilityToken()
{
var bytes = new byte[32];
using (var random = RandomNumberGenerator.Create()) random.GetBytes(bytes);
return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
}
}
public sealed class CultMeshMappedBodyAdapter : ICultMeshBodyTransportAdapter
{
private readonly string _rootPath;
public CultMeshMappedBodyAdapter(string rootPath) =>
_rootPath = Path.GetFullPath(string.IsNullOrWhiteSpace(rootPath)
? throw new ArgumentException("Mapped body root is required.", nameof(rootPath))
: rootPath);
public CultMeshBodyTransportKind TransportKind => CultMeshBodyTransportKind.SharedFileMapping;
public bool CanOpen(CultMeshBodyDescriptor descriptor) =>
descriptor != null && descriptor.TransportKind == TransportKind;
public ICultMeshBodyReadLease OpenReadOnly(
CultMeshBodyDescriptor descriptor,
CultMeshBodyValidationRequest request)
{
CultMeshBodyDescriptorValidator.Validate(descriptor, request);
if (descriptor.TransportKind != CultMeshBodyTransportKind.SharedFileMapping)
throw new NotSupportedException($"CultMesh body transport '{descriptor.TransportKind}' is not a file mapping.");
var token = descriptor.CapabilityToken;
if (token.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || token.Contains(".."))
throw new UnauthorizedAccessException("Invalid CultMesh body capability token.");
var path = Path.GetFullPath(Path.Combine(_rootPath, token + ".body"));
if (!path.StartsWith(_rootPath + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
throw new UnauthorizedAccessException("CultMesh body token escaped the broker root.");
var info = new FileInfo(path);
if (!info.Exists || info.Length != descriptor.ByteSize)
throw new InvalidDataException("Mapped CultMesh body size does not match its descriptor.");
return new CultMeshMappedBodyLease(descriptor, path);
}
}
public sealed class CultMeshMappedBodyLease : ICultMeshBodyReadLease
{
private readonly MemoryMappedFile _mapping;
private readonly MemoryMappedViewAccessor _view;
private bool _disposed;
internal CultMeshMappedBodyLease(CultMeshBodyDescriptor descriptor, string path)
{
Descriptor = descriptor;
_mapping = MemoryMappedFile.CreateFromFile(path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read);
_view = _mapping.CreateViewAccessor(0, descriptor.ByteSize, MemoryMappedFileAccess.Read);
}
public CultMeshBodyDescriptor Descriptor { get; }
public CultMeshBodyTransportKind TransportKind => CultMeshBodyTransportKind.SharedFileMapping;
public byte ReadByte(long offset) { ValidateRange(offset, 1); return _view.ReadByte(offset); }
public int ReadInt32(long offset) { ValidateRange(offset, sizeof(int)); return _view.ReadInt32(offset); }
public long ReadInt64(long offset) { ValidateRange(offset, sizeof(long)); return _view.ReadInt64(offset); }
public float ReadSingle(long offset) { ValidateRange(offset, sizeof(float)); return _view.ReadSingle(offset); }
public double ReadDouble(long offset) { ValidateRange(offset, sizeof(double)); return _view.ReadDouble(offset); }
public int CopyTo(long offset, byte[] destination, int destinationOffset, int count)
{
if (destination == null) throw new ArgumentNullException(nameof(destination));
ValidateRange(offset, count);
return _view.ReadArray(offset, destination, destinationOffset, count);
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_view.Dispose();
_mapping.Dispose();
}
private void ValidateRange(long offset, long length)
{
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshMappedBodyLease));
if (offset < 0 || length < 0 || offset > Descriptor.ByteSize - length)
throw new ArgumentOutOfRangeException(nameof(offset));
}
}
public sealed class CultMeshNetworkBodyAdapter : ICultMeshBodyTransportAdapter
{
private readonly Func<CultMeshBodyDescriptor, byte[]> _fetch;
public CultMeshNetworkBodyAdapter(Func<CultMeshBodyDescriptor, byte[]> fetch) =>
_fetch = fetch ?? throw new ArgumentNullException(nameof(fetch));
public CultMeshBodyTransportKind TransportKind => CultMeshBodyTransportKind.Network;
public bool CanOpen(CultMeshBodyDescriptor descriptor) =>
descriptor != null && descriptor.TransportKind == TransportKind;
public ICultMeshBodyReadLease OpenReadOnly(
CultMeshBodyDescriptor descriptor,
CultMeshBodyValidationRequest request)
{
CultMeshBodyDescriptorValidator.Validate(descriptor, request);
var bytes = _fetch(descriptor) ?? throw new InvalidDataException("CultMesh network body returned no bytes.");
if (bytes.LongLength != descriptor.ByteSize)
throw new InvalidDataException("CultMesh network body size does not match its descriptor.");
return new CultMeshBufferedBodyLease(descriptor, bytes);
}
}
internal sealed class CultMeshBufferedBodyLease : ICultMeshBodyReadLease
{
private byte[] _body;
public CultMeshBufferedBodyLease(CultMeshBodyDescriptor descriptor, byte[] body)
{
Descriptor = descriptor;
_body = body;
}
public CultMeshBodyDescriptor Descriptor { get; }
public CultMeshBodyTransportKind TransportKind => CultMeshBodyTransportKind.Network;
public byte ReadByte(long offset) { Validate(offset, 1); return _body[(int)offset]; }
public int ReadInt32(long offset) { Validate(offset, 4); return BitConverter.ToInt32(_body, (int)offset); }
public long ReadInt64(long offset) { Validate(offset, 8); return BitConverter.ToInt64(_body, (int)offset); }
public float ReadSingle(long offset) { Validate(offset, 4); return BitConverter.ToSingle(_body, (int)offset); }
public double ReadDouble(long offset) { Validate(offset, 8); return BitConverter.ToDouble(_body, (int)offset); }
public int CopyTo(long offset, byte[] destination, int destinationOffset, int count)
{
Validate(offset, count);
Buffer.BlockCopy(_body, (int)offset, destination, destinationOffset, count);
return count;
}
public void Dispose() { _body = Array.Empty<byte>(); }
private void Validate(long offset, int count)
{
if (offset < 0 || count < 0 || offset > _body.LongLength - count)
throw new ArgumentOutOfRangeException(nameof(offset));
}
}
}

View file

@ -0,0 +1,159 @@
using System;
using System.IO;
using FluentAssertions;
using NUnit.Framework;
namespace GameCult.Mesh.Tests;
public sealed class CultMeshBodyTransportTests
{
private string _root = null!;
[SetUp]
public void SetUp()
{
_root = Path.Combine(Path.GetTempPath(), "cultmesh-body-tests", Guid.NewGuid().ToString("N"));
}
[TearDown]
public void TearDown()
{
if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true);
}
[Test]
public void MappedBody_IsReadOnlyAndPreservesLogicalIdentityAcrossTransportMaterial()
{
var publisher = new CultMeshMappedBodyPublisher(_root, TimeSpan.FromMinutes(1));
var now = DateTimeOffset.UtcNow;
var firstBytes = BitConverter.GetBytes(12.5f);
var secondBytes = BitConverter.GetBytes(13.5f);
var first = publisher.Publish("aetheria:pilot-entities", "eve.entity_soa.v1", 1, 128, 7, 40, firstBytes, now);
var second = publisher.Publish("aetheria:pilot-entities", "eve.entity_soa.v1", 1, 128, 7, 41, secondBytes, now);
first.BodyId.Should().Be(second.BodyId);
first.CapabilityToken.Should().NotBe(second.CapabilityToken);
first.AccessMode.Should().Be(CultMeshBodyAccessMode.ReadOnly);
using var lease = new CultMeshMappedBodyAdapter(_root).OpenReadOnly(first, Request(first, now));
lease.ReadSingle(0).Should().Be(12.5f);
lease.Descriptor.Sequence.Should().Be(40);
}
[Test]
public void Validation_RejectsExpiredEpochLayoutAndWritableConsumption()
{
var publisher = new CultMeshMappedBodyPublisher(_root, TimeSpan.FromSeconds(1));
var now = DateTimeOffset.UtcNow;
var descriptor = publisher.Publish("body", "schema", 2, 4, 9, 1, new byte[4], now);
var adapter = new CultMeshMappedBodyAdapter(_root);
Action expired = () => adapter.OpenReadOnly(descriptor, Request(descriptor, now.AddSeconds(2)));
expired.Should().Throw<InvalidOperationException>().WithMessage("*expired*");
var wrongEpoch = Request(descriptor, now);
wrongEpoch.ProducerEpoch++;
Action epoch = () => adapter.OpenReadOnly(descriptor, wrongEpoch);
epoch.Should().Throw<InvalidOperationException>().WithMessage("*epoch*");
var writable = Request(descriptor, now);
writable.AccessMode = CultMeshBodyAccessMode.ReadWrite;
Action write = () => adapter.OpenReadOnly(descriptor, writable);
write.Should().Throw<UnauthorizedAccessException>();
}
[Test]
public void CapabilityToken_CannotEscapeBrokerRoot()
{
var descriptor = new CultMeshBodyDescriptor
{
BodyId = "body",
SchemaId = "schema",
LayoutVersion = 1,
ByteSize = 4,
Capacity = 4,
ProducerEpoch = 1,
Sequence = 1,
LeaseExpiresAtUnixMs = DateTimeOffset.UtcNow.AddMinutes(1).ToUnixTimeMilliseconds(),
TransportKind = CultMeshBodyTransportKind.SharedFileMapping,
CapabilityToken = ".." + Path.DirectorySeparatorChar + "outside"
};
Action open = () => new CultMeshMappedBodyAdapter(_root).OpenReadOnly(
descriptor,
Request(descriptor, DateTimeOffset.UtcNow));
open.Should().Throw<UnauthorizedAccessException>();
}
[Test]
public void Negotiation_FallsBackToEquivalentNetworkBody_WhenLocalMappingFails()
{
var now = DateTimeOffset.UtcNow;
var bytes = BitConverter.GetBytes(42.25f);
var publisher = new CultMeshMappedBodyPublisher(_root, TimeSpan.FromMinutes(1));
var local = publisher.Publish("body", "schema", 1, bytes.Length, 3, 8, bytes, now);
publisher.Revoke(local);
var network = new CultMeshBodyDescriptor
{
BodyId = local.BodyId,
SchemaId = local.SchemaId,
LayoutVersion = local.LayoutVersion,
ByteSize = local.ByteSize,
Capacity = local.Capacity,
ProducerEpoch = local.ProducerEpoch,
Sequence = local.Sequence,
AccessMode = CultMeshBodyAccessMode.ReadOnly,
Synchronization = local.Synchronization,
LeaseExpiresAtUnixMs = local.LeaseExpiresAtUnixMs,
TransportKind = CultMeshBodyTransportKind.Network
};
var service = new CultMeshBodyTransportService(
new ICultMeshBodyTransportAdapter[]
{
new CultMeshMappedBodyAdapter(_root),
new CultMeshNetworkBodyAdapter(_ => bytes)
},
_ => true);
using var lease = service.OpenReadOnly(local, network, Request(local, now), out var localFailure);
localFailure.Should().BeOfType<InvalidDataException>();
lease.TransportKind.Should().Be(CultMeshBodyTransportKind.Network);
lease.Descriptor.BodyId.Should().Be(local.BodyId);
lease.ReadSingle(0).Should().Be(42.25f);
}
[Test]
public void Negotiation_RejectsUnauthorizedProducerBeforeOpeningAnyRepresentation()
{
var now = DateTimeOffset.UtcNow;
var bytes = new byte[4];
var local = new CultMeshMappedBodyPublisher(_root, TimeSpan.FromMinutes(1))
.Publish("body", "schema", 1, 4, 3, 8, bytes, now);
var network = new CultMeshBodyDescriptor
{
BodyId = local.BodyId, SchemaId = local.SchemaId, LayoutVersion = 1,
ByteSize = 4, Capacity = 4, ProducerEpoch = 3, Sequence = 8,
LeaseExpiresAtUnixMs = local.LeaseExpiresAtUnixMs,
TransportKind = CultMeshBodyTransportKind.Network
};
var service = new CultMeshBodyTransportService(
new ICultMeshBodyTransportAdapter[]
{
new CultMeshMappedBodyAdapter(_root),
new CultMeshNetworkBodyAdapter(_ => bytes)
},
_ => false);
Action open = () => service.OpenReadOnly(local, network, Request(local, now), out _);
open.Should().Throw<UnauthorizedAccessException>();
}
private static CultMeshBodyValidationRequest Request(CultMeshBodyDescriptor descriptor, DateTimeOffset now) => new()
{
BodyId = descriptor.BodyId,
SchemaId = descriptor.SchemaId,
LayoutVersion = descriptor.LayoutVersion,
ProducerEpoch = descriptor.ProducerEpoch,
AccessMode = CultMeshBodyAccessMode.ReadOnly,
NowUtc = now
};
}