Conform CultMesh body network fallback
This commit is contained in:
parent
0a092d8c7a
commit
7e09668b7b
5 changed files with 248 additions and 14 deletions
|
|
@ -46,6 +46,7 @@ namespace GameCult.Mesh
|
|||
[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;
|
||||
[Key(12)] public string SemanticHash { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public sealed class CultMeshBodyValidationRequest
|
||||
|
|
@ -62,6 +63,17 @@ namespace GameCult.Mesh
|
|||
|
||||
public static class CultMeshBodyDescriptorValidator
|
||||
{
|
||||
public static string ComputeSemanticHash(ReadOnlySpan<byte> body)
|
||||
{
|
||||
using var sha256 = SHA256.Create();
|
||||
Span<byte> digest = stackalloc byte[32];
|
||||
if (!sha256.TryComputeHash(body, digest, out var written) || written != digest.Length)
|
||||
throw new CryptographicException("Unable to compute the CultMesh body semantic digest.");
|
||||
return BitConverter.ToString(digest.ToArray())
|
||||
.Replace("-", string.Empty)
|
||||
.ToLowerInvariant();
|
||||
}
|
||||
|
||||
public static void Validate(CultMeshBodyDescriptor descriptor, CultMeshBodyValidationRequest request)
|
||||
{
|
||||
if (descriptor == null) throw new ArgumentNullException(nameof(descriptor));
|
||||
|
|
@ -92,6 +104,25 @@ namespace GameCult.Mesh
|
|||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshBodyNegotiationResult
|
||||
{
|
||||
internal CultMeshBodyNegotiationResult(
|
||||
ICultMeshBodyReadLease lease,
|
||||
CultMeshBodyTransportKind preferredTransport,
|
||||
Exception? preferredFailure)
|
||||
{
|
||||
Lease = lease;
|
||||
PreferredTransport = preferredTransport;
|
||||
PreferredFailure = preferredFailure;
|
||||
}
|
||||
|
||||
public ICultMeshBodyReadLease Lease { get; }
|
||||
public CultMeshBodyTransportKind PreferredTransport { get; }
|
||||
public CultMeshBodyTransportKind SelectedTransport => Lease.TransportKind;
|
||||
public Exception? PreferredFailure { get; }
|
||||
public bool UsedFallback => SelectedTransport != PreferredTransport;
|
||||
}
|
||||
|
||||
public interface ICultMeshBodyReadLease : IDisposable
|
||||
{
|
||||
CultMeshBodyDescriptor Descriptor { get; }
|
||||
|
|
@ -132,28 +163,45 @@ namespace GameCult.Mesh
|
|||
CultMeshBodyDescriptor networkFallback,
|
||||
CultMeshBodyValidationRequest request,
|
||||
out Exception? localFailure)
|
||||
{
|
||||
var result = NegotiateReadOnly(preferred, networkFallback, request);
|
||||
localFailure = result.PreferredFailure;
|
||||
return result.Lease;
|
||||
}
|
||||
|
||||
public CultMeshBodyNegotiationResult NegotiateReadOnly(
|
||||
CultMeshBodyDescriptor preferred,
|
||||
CultMeshBodyDescriptor networkFallback,
|
||||
CultMeshBodyValidationRequest request)
|
||||
{
|
||||
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.");
|
||||
CultMeshBodyDescriptorValidator.Validate(preferred, request);
|
||||
CultMeshBodyDescriptorValidator.Validate(networkFallback, request);
|
||||
if (!_authorizeProducer(preferred))
|
||||
throw new UnauthorizedAccessException("CultMesh body producer is not authorized for this logical body.");
|
||||
|
||||
localFailure = null;
|
||||
Exception? preferredFailure = null;
|
||||
try
|
||||
{
|
||||
if (_adapters.TryGetValue(preferred.TransportKind, out var local) && local.CanOpen(preferred))
|
||||
return local.OpenReadOnly(preferred, request);
|
||||
if (!_adapters.TryGetValue(preferred.TransportKind, out var local))
|
||||
throw new NotSupportedException($"No CultMesh {preferred.TransportKind} body adapter is available.");
|
||||
if (!local.CanOpen(preferred))
|
||||
throw new NotSupportedException($"The CultMesh {preferred.TransportKind} body adapter declined the preferred descriptor.");
|
||||
var lease = local.OpenReadOnly(preferred, request);
|
||||
return new CultMeshBodyNegotiationResult(lease, preferred.TransportKind, null);
|
||||
}
|
||||
catch (Exception error) when (!(error is UnauthorizedAccessException))
|
||||
{
|
||||
localFailure = error;
|
||||
preferredFailure = 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);
|
||||
var fallback = network.OpenReadOnly(networkFallback, request);
|
||||
return new CultMeshBodyNegotiationResult(fallback, preferred.TransportKind, preferredFailure);
|
||||
}
|
||||
|
||||
private static bool SameLogicalGeneration(CultMeshBodyDescriptor left, CultMeshBodyDescriptor right) =>
|
||||
|
|
@ -163,7 +211,10 @@ namespace GameCult.Mesh
|
|||
left.ProducerEpoch == right.ProducerEpoch &&
|
||||
left.Sequence == right.Sequence &&
|
||||
left.ByteSize == right.ByteSize &&
|
||||
left.Capacity == right.Capacity;
|
||||
left.Capacity == right.Capacity &&
|
||||
left.AccessMode == right.AccessMode &&
|
||||
left.Synchronization == right.Synchronization &&
|
||||
string.Equals(left.SemanticHash, right.SemanticHash, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
public sealed class CultMeshMappedBodyPublisher
|
||||
|
|
@ -217,7 +268,8 @@ namespace GameCult.Mesh
|
|||
Synchronization = CultMeshBodySynchronization.ImmutableSequence,
|
||||
LeaseExpiresAtUnixMs = nowUtc.Add(_leaseDuration).ToUnixTimeMilliseconds(),
|
||||
TransportKind = CultMeshBodyTransportKind.SharedFileMapping,
|
||||
CapabilityToken = token
|
||||
CapabilityToken = token,
|
||||
SemanticHash = CultMeshBodyDescriptorValidator.ComputeSemanticHash(body)
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -339,7 +391,8 @@ namespace GameCult.Mesh
|
|||
Synchronization = networkDescriptor.Synchronization,
|
||||
LeaseExpiresAtUnixMs = expiresAtUnixMs,
|
||||
TransportKind = CultMeshBodyTransportKind.SharedFileMapping,
|
||||
CapabilityToken = token
|
||||
CapabilityToken = token,
|
||||
SemanticHash = networkDescriptor.SemanticHash
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -464,6 +517,11 @@ namespace GameCult.Mesh
|
|||
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.");
|
||||
if (string.IsNullOrWhiteSpace(descriptor.SemanticHash))
|
||||
throw new InvalidDataException("CultMesh network body descriptor has no semantic digest.");
|
||||
var actualHash = CultMeshBodyDescriptorValidator.ComputeSemanticHash(bytes);
|
||||
if (!string.Equals(actualHash, descriptor.SemanticHash, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("CultMesh network body semantic digest does not match its descriptor.");
|
||||
return new CultMeshBufferedBodyLease(descriptor, bytes);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -240,7 +240,9 @@ namespace GameCult.Mesh
|
|||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
Synchronization = CultMeshBodySynchronization.TripleBuffer,
|
||||
LeaseExpiresAtUnixMs = long.MaxValue,
|
||||
TransportKind = CultMeshBodyTransportKind.SharedMemory
|
||||
TransportKind = CultMeshBodyTransportKind.SharedMemory,
|
||||
SemanticHash = CultMeshBodyDescriptorValidator.ComputeSemanticHash(
|
||||
lease.Span[..byteLength])
|
||||
};
|
||||
var generation = new CultMeshFrameGeneration(
|
||||
lease.SlotIndex, descriptor, timestampNs, durationNs, unavoidableCopyCount, metadata);
|
||||
|
|
|
|||
|
|
@ -728,6 +728,60 @@ rejected rather than creating a second buffering model.
|
|||
- Negotiation failure is observable and falls back to the network body without
|
||||
changing logical body identity.
|
||||
|
||||
### Phase 5 local/remote conformance slice
|
||||
|
||||
**Owner:** `CultMeshBodyTransportService` owns representation selection for one
|
||||
validated logical generation. Each transport adapter owns only acquisition and
|
||||
pre-interpretation validation of its representation. Producer authorization is
|
||||
an independent input to negotiation; a valid digest never grants authority.
|
||||
|
||||
**Inputs:** equivalent local and network descriptors, the consumer's expected
|
||||
body identity/schema/layout/capacity/epoch/sequence, an authorized-producer
|
||||
decision, registered transport adapters, and network bytes carrying the
|
||||
descriptor-bound semantic digest.
|
||||
|
||||
**Outputs:** one read-only lease for the selected representation plus a typed
|
||||
negotiation result that records the selected transport and any rejected local
|
||||
attempt. Local and network leases expose the same logical descriptor fields and
|
||||
semantic bytes.
|
||||
|
||||
**Derived state:** local preference, adapter availability, and fallback reason
|
||||
are negotiation state only. Capability tokens and network fetch details remain
|
||||
transport material and cannot alter logical body identity.
|
||||
|
||||
**Invariants:** both descriptors must agree on body identity, schema, layout,
|
||||
byte size, capacity, producer epoch, sequence, synchronization, access mode,
|
||||
and semantic digest before either representation is opened. Lease expiry is
|
||||
representation lifetime, validated independently for each descriptor; it is
|
||||
not logical generation identity because a local broker may issue a shorter
|
||||
capability lease than the network representation.
|
||||
Expected schema, layout, capacity, epoch, and sequence are validated before a
|
||||
network fetch. Fetched network bytes are digest-verified before a lease is
|
||||
created or any typed read is possible. Digest integrity does not authorize the
|
||||
publisher.
|
||||
|
||||
**Forbidden writers:** adapters, fallback handling, capability material,
|
||||
network payloads, and integrity checks cannot rewrite logical identity or grant
|
||||
producer authority. A failed local adapter cannot repair, mutate, or reinterpret
|
||||
the network descriptor.
|
||||
|
||||
**Shared paths:** successful local open and network fallback use the same
|
||||
logical-generation equivalence check and consumer validation request. Direct
|
||||
network consumption uses the same pre-interpretation descriptor and digest
|
||||
validation as fallback consumption.
|
||||
|
||||
**Cut line:** replace exception-only fallback reporting with a typed negotiation
|
||||
result while retaining the existing overload as a delegating compatibility
|
||||
surface. Add only descriptor-bound semantic integrity; do not add a shared-memory
|
||||
control bus, content-authority inference, reconnect policy, or profiling hooks.
|
||||
|
||||
**Verification layer:** conformance tests compare descriptor semantics and full
|
||||
bytes across file mapping, shared memory where supported, direct network, and
|
||||
network fallback. Negative tests prove stale schema/epoch/sequence are rejected
|
||||
before fetch, corrupt network bytes never produce a lease, local failure is
|
||||
reported, fallback preserves identity, and authorization is evaluated separately
|
||||
from content integrity.
|
||||
|
||||
### Gate
|
||||
|
||||
- Two local consumers map one verified CDN artifact without duplicate process
|
||||
|
|
|
|||
|
|
@ -105,7 +105,8 @@ public sealed class CultMeshBodyTransportTests
|
|||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
Synchronization = local.Synchronization,
|
||||
LeaseExpiresAtUnixMs = local.LeaseExpiresAtUnixMs,
|
||||
TransportKind = CultMeshBodyTransportKind.Network
|
||||
TransportKind = CultMeshBodyTransportKind.Network,
|
||||
SemanticHash = local.SemanticHash
|
||||
};
|
||||
var service = new CultMeshBodyTransportService(
|
||||
new ICultMeshBodyTransportAdapter[]
|
||||
|
|
@ -115,14 +116,104 @@ public sealed class CultMeshBodyTransportTests
|
|||
},
|
||||
_ => true);
|
||||
|
||||
using var lease = service.OpenReadOnly(local, network, Request(local, now), out var localFailure);
|
||||
var result = service.NegotiateReadOnly(local, network, Request(local, now));
|
||||
using var lease = result.Lease;
|
||||
|
||||
localFailure.Should().BeOfType<InvalidDataException>();
|
||||
result.PreferredFailure.Should().BeOfType<InvalidDataException>();
|
||||
result.UsedFallback.Should().BeTrue();
|
||||
result.PreferredTransport.Should().Be(CultMeshBodyTransportKind.SharedFileMapping);
|
||||
result.SelectedTransport.Should().Be(CultMeshBodyTransportKind.Network);
|
||||
lease.TransportKind.Should().Be(CultMeshBodyTransportKind.Network);
|
||||
lease.Descriptor.BodyId.Should().Be(local.BodyId);
|
||||
lease.ReadSingle(0).Should().Be(42.25f);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LocalAndNetworkRepresentationsExposeTheSameLogicalContractAndSemanticBytes()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var bytes = new byte[] { 1, 3, 5, 7, 9, 11 };
|
||||
var local = new CultMeshMappedBodyPublisher(_root, TimeSpan.FromMinutes(1))
|
||||
.Publish("body", "schema.v2", 2, 64, 5, 12, bytes, now);
|
||||
var network = NetworkRepresentation(local);
|
||||
var request = Request(local, now);
|
||||
|
||||
using var localLease = new CultMeshMappedBodyAdapter(_root).OpenReadOnly(local, request);
|
||||
using var networkLease = new CultMeshNetworkBodyAdapter(_ => bytes).OpenReadOnly(network, request);
|
||||
|
||||
networkLease.Descriptor.Should().BeEquivalentTo(localLease.Descriptor, options => options
|
||||
.Excluding(value => value.TransportKind)
|
||||
.Excluding(value => value.CapabilityToken));
|
||||
ReadAll(localLease).Should().Equal(bytes);
|
||||
ReadAll(networkLease).Should().Equal(bytes);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MissingPreferredAdapterProducesObservableFallbackReason()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var bytes = new byte[] { 4, 8, 15, 16, 23, 42 };
|
||||
var local = new CultMeshMappedBodyPublisher(_root, TimeSpan.FromMinutes(1))
|
||||
.Publish("body", "schema", 1, bytes.Length, 3, 8, bytes, now);
|
||||
var network = NetworkRepresentation(local);
|
||||
var service = new CultMeshBodyTransportService(
|
||||
new ICultMeshBodyTransportAdapter[] { new CultMeshNetworkBodyAdapter(_ => bytes) },
|
||||
_ => true);
|
||||
|
||||
var result = service.NegotiateReadOnly(local, network, Request(local, now));
|
||||
using var lease = result.Lease;
|
||||
|
||||
result.UsedFallback.Should().BeTrue();
|
||||
result.PreferredFailure.Should().BeOfType<NotSupportedException>();
|
||||
result.PreferredFailure!.Message.Should().Contain("adapter is available");
|
||||
lease.TransportKind.Should().Be(CultMeshBodyTransportKind.Network);
|
||||
}
|
||||
|
||||
[TestCase("schema")]
|
||||
[TestCase("epoch")]
|
||||
[TestCase("sequence")]
|
||||
public void NegotiationRejectsStaleLogicalGenerationBeforeFetchingNetworkBytes(string staleField)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var bytes = new byte[] { 2, 4, 6, 8 };
|
||||
var local = new CultMeshMappedBodyPublisher(_root, TimeSpan.FromMinutes(1))
|
||||
.Publish("body", "schema", 1, 4, 3, 8, bytes, now);
|
||||
var network = NetworkRepresentation(local);
|
||||
var request = Request(local, now);
|
||||
if (staleField == "schema") request.SchemaId = "stale";
|
||||
if (staleField == "epoch") request.ProducerEpoch--;
|
||||
if (staleField == "sequence") request.Sequence--;
|
||||
var fetched = false;
|
||||
var service = new CultMeshBodyTransportService(
|
||||
new ICultMeshBodyTransportAdapter[]
|
||||
{
|
||||
new CultMeshMappedBodyAdapter(_root),
|
||||
new CultMeshNetworkBodyAdapter(_ => { fetched = true; return bytes; })
|
||||
},
|
||||
_ => true);
|
||||
|
||||
Action open = () => service.NegotiateReadOnly(local, network, request);
|
||||
|
||||
open.Should().Throw<InvalidOperationException>();
|
||||
fetched.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NetworkRepresentationRejectsCorruptBytesBeforeCreatingAReadableLease()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var bytes = new byte[] { 10, 20, 30, 40 };
|
||||
var local = new CultMeshMappedBodyPublisher(_root, TimeSpan.FromMinutes(1))
|
||||
.Publish("body", "schema", 1, 4, 3, 8, bytes, now);
|
||||
var network = NetworkRepresentation(local);
|
||||
var corrupt = new byte[] { 10, 20, 30, 41 };
|
||||
|
||||
Action open = () => new CultMeshNetworkBodyAdapter(_ => corrupt)
|
||||
.OpenReadOnly(network, Request(network, now));
|
||||
|
||||
open.Should().Throw<InvalidDataException>().WithMessage("*semantic digest*");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Negotiation_RejectsUnauthorizedProducerBeforeOpeningAnyRepresentation()
|
||||
{
|
||||
|
|
@ -135,7 +226,8 @@ public sealed class CultMeshBodyTransportTests
|
|||
BodyId = local.BodyId, SchemaId = local.SchemaId, LayoutVersion = 1,
|
||||
ByteSize = 4, Capacity = 4, ProducerEpoch = 3, Sequence = 8,
|
||||
LeaseExpiresAtUnixMs = local.LeaseExpiresAtUnixMs,
|
||||
TransportKind = CultMeshBodyTransportKind.Network
|
||||
TransportKind = CultMeshBodyTransportKind.Network,
|
||||
SemanticHash = local.SemanticHash
|
||||
};
|
||||
var service = new CultMeshBodyTransportService(
|
||||
new ICultMeshBodyTransportAdapter[]
|
||||
|
|
@ -177,7 +269,32 @@ public sealed class CultMeshBodyTransportTests
|
|||
SchemaId = descriptor.SchemaId,
|
||||
LayoutVersion = descriptor.LayoutVersion,
|
||||
ProducerEpoch = descriptor.ProducerEpoch,
|
||||
Sequence = descriptor.Sequence,
|
||||
Capacity = descriptor.Capacity,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
NowUtc = now
|
||||
};
|
||||
|
||||
private static CultMeshBodyDescriptor NetworkRepresentation(CultMeshBodyDescriptor descriptor) => new()
|
||||
{
|
||||
BodyId = descriptor.BodyId,
|
||||
SchemaId = descriptor.SchemaId,
|
||||
LayoutVersion = descriptor.LayoutVersion,
|
||||
ByteSize = descriptor.ByteSize,
|
||||
Capacity = descriptor.Capacity,
|
||||
ProducerEpoch = descriptor.ProducerEpoch,
|
||||
Sequence = descriptor.Sequence,
|
||||
AccessMode = descriptor.AccessMode,
|
||||
Synchronization = descriptor.Synchronization,
|
||||
LeaseExpiresAtUnixMs = descriptor.LeaseExpiresAtUnixMs,
|
||||
TransportKind = CultMeshBodyTransportKind.Network,
|
||||
SemanticHash = descriptor.SemanticHash
|
||||
};
|
||||
|
||||
private static byte[] ReadAll(ICultMeshBodyReadLease lease)
|
||||
{
|
||||
var bytes = new byte[lease.Descriptor.ByteSize];
|
||||
lease.CopyTo(0, bytes, 0, bytes.Length);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -230,7 +230,8 @@ public sealed class CultMeshContentTransferTests
|
|||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
Synchronization = CultMeshBodySynchronization.ImmutableSequence,
|
||||
LeaseExpiresAtUnixMs = now.AddMinutes(2).ToUnixTimeMilliseconds(),
|
||||
TransportKind = CultMeshBodyTransportKind.Network
|
||||
TransportKind = CultMeshBodyTransportKind.Network,
|
||||
SemanticHash = artifact.Manifest.ContentHash
|
||||
};
|
||||
|
||||
private static CultMeshBodyValidationRequest Request(CultMeshBodyDescriptor descriptor, DateTimeOffset now) => new()
|
||||
|
|
@ -239,6 +240,8 @@ public sealed class CultMeshContentTransferTests
|
|||
SchemaId = descriptor.SchemaId,
|
||||
LayoutVersion = descriptor.LayoutVersion,
|
||||
ProducerEpoch = descriptor.ProducerEpoch,
|
||||
Sequence = descriptor.Sequence,
|
||||
Capacity = descriptor.Capacity,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
NowUtc = now
|
||||
};
|
||||
|
|
|
|||
Loading…
Reference in a new issue